Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 51fc7c3576 | |||
|
|
7ed31c6f75 | ||
|
|
0f3f76a8ab | ||
|
|
be87931b53 | ||
|
|
484d4f65ba | ||
|
|
8881b3f4b5 | ||
|
|
f7decde001 | ||
|
|
56c45967ef | ||
|
|
947d8f7a40 | ||
|
|
02e78e1427 | ||
| 14be61a167 | |||
|
|
ea38f5f17d | ||
| e817b67abd | |||
|
|
63606efddd | ||
|
|
b90c21e695 | ||
| fe723867f7 | |||
|
|
19e0ee5285 | ||
|
|
8d69d3bded | ||
| c4bd83b026 |
28 changed files with 4207 additions and 222 deletions
|
|
@ -268,17 +268,9 @@ impl<S: MindStore> Mind<S> {
|
|||
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 {
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ fn declared_names(node: &Value, names: &mut BTreeSet<String>) {
|
|||
|
||||
/// 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<Value, MindRefusal> {
|
||||
rmp_serde::from_slice::<HuginnPersonaEntry>(&envelope.payload)
|
||||
|
|
|
|||
6
crates/mind-body/fixtures/harness/golden-chorus.txt
Normal file
6
crates/mind-body/fixtures/harness/golden-chorus.txt
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
responder 3: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 2 lines are the Minds' alone.
|
||||
responder 4: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko answered it. Meta, who runs the place last spoke 5 min ago. The last 3 lines are the Minds' alone.
|
||||
responder 5: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 4 lines are the Minds' alone.
|
||||
responder 6: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 5 lines are the Minds' alone.
|
||||
responder 7: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 6 lines are the Minds' alone.
|
||||
responder 8: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org); "aqua" (@aqua:gamecult.org) answered it. Meta, who runs the place last spoke 5 min ago. The last 7 lines are the Minds…
|
||||
4
crates/mind-body/fixtures/harness/golden-group.txt
Normal file
4
crates/mind-body/fixtures/harness/golden-group.txt
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
quiet-beat.toml: - the conversation: Lately @libby:gamecult.org to the room; Kiko to the room. The last 3 lines are the Minds' alone.
|
||||
operator-warm.toml: - the conversation: Meta, who runs the place is waiting on him. Lately Meta, who runs the place with him. Meta, who runs the place last spoke 1 min ago.
|
||||
mind-teases.toml: - the conversation: Lately he to the room; @aqua:gamecult.org to the room; Kiko with him. The last 3 lines are the Minds' alone.
|
||||
deru-passing.toml: - the conversation: Lately @weksa:gamecult.org to the room; Deru to the room. Deru last spoke 1 min ago.
|
||||
23
crates/mind-body/fixtures/harness/rooms/deru-passing.toml
Normal file
23
crates/mind-body/fixtures/harness/rooms/deru-passing.toml
Normal file
|
|
@ -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"
|
||||
31
crates/mind-body/fixtures/harness/rooms/mind-teases.toml
Normal file
31
crates/mind-body/fixtures/harness/rooms/mind-teases.toml
Normal file
|
|
@ -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"
|
||||
27
crates/mind-body/fixtures/harness/rooms/operator-warm.toml
Normal file
27
crates/mind-body/fixtures/harness/rooms/operator-warm.toml
Normal file
|
|
@ -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"
|
||||
33
crates/mind-body/fixtures/harness/rooms/quiet-beat.toml
Normal file
33
crates/mind-body/fixtures/harness/rooms/quiet-beat.toml
Normal file
|
|
@ -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"
|
||||
148
crates/mind-body/fixtures/harness/states/control.json
Normal file
148
crates/mind-body/fixtures/harness/states/control.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
|
|
@ -13,19 +13,30 @@
|
|||
//! will need. Without `--endpoint` the daemon is `HUGINN_ENDPOINT`; no call is made
|
||||
//! to it.
|
||||
//!
|
||||
//! `mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--room <r>]
|
||||
//! [--seed N] [--state <file>] [--select-only | --renders K [--judge <state-file>]]` is the Projector's experiment tool
|
||||
//! `mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>]
|
||||
//! [--room <fixture.toml>] [--seed N] [--state <file>] [--select-only | --renders K [--through projector|persona|interpreter]
|
||||
//! [--judge <state-file>]]` 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/<instance>/persona-tuning.toml`; renders need `MIND_PERSONA_CONNECTOR_ENDPOINT`
|
||||
//! (`<loopback ip>:<port>`) and the `connector-key` credential in `CREDENTIALS_DIRECTORY`. Without `--select-only` or
|
||||
//! `--renders` it renders once.
|
||||
//! `--state`, checked as a put checks its content, rules P1 to P3; P4 and P5 compare it with the stored document and are
|
||||
//! not checked), and with `--renders` the Projector's narrations of K successive turns;
|
||||
//! `--through persona` adds her prose and `--through interpreter` what the Interpreter decides she says; `--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 <fixture>` 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 <slug> (--batch <plan.toml> | --simulate <plan.toml>) --out <report.md>` 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/<instance>/persona-tuning.toml`; renders and plans need
|
||||
//! `MIND_PERSONA_CONNECTOR_ENDPOINT` (`<loopback ip>:<port>`) 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 +45,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 <slug> [--endpoint rudp://<ip>:<port>] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]";
|
||||
const PROJECT_USAGE: &str = "usage: mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--room <r>] [--seed N] [--state <file>] [--select-only | --renders K [--judge <state-file>]]";
|
||||
const PROJECT_USAGE: &str = "usage: mind-persona project --instance <slug> [--endpoint rudp://<ip>:<port>] [--kind chat|beat|reflection] [--in <room>] [--room <fixture.toml>] [--seed N] [--state <file>] [--select-only | --renders K [--through projector|persona|interpreter] [--judge <state-file>]] | (--batch <plan> | --simulate <plan>) --out <report.md>";
|
||||
/// 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 +87,6 @@ fn credential(name: &str) -> Result<String> {
|
|||
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<serde_json::Value> {
|
||||
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<PathBuf> {
|
||||
|
|
@ -87,36 +94,82 @@ fn credentials_directory() -> Result<PathBuf> {
|
|||
}
|
||||
|
||||
fn run_project(args: &[String]) -> Result<String> {
|
||||
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::<u64>().map_err(|_| anyhow!("{PROJECT_USAGE}"))?),
|
||||
"--state" => state = Some(value()?),
|
||||
"--renders" => renders = Some(value()?.parse::<usize>().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" => Through::Interpreter,
|
||||
_ => bail!("{PROJECT_USAGE}"),
|
||||
}
|
||||
}
|
||||
"--room" => room = Some(value()?),
|
||||
"--seed" => seed = Some(value()?.parse::<u64>().map_err(|_| anyhow!("{PROJECT_USAGE}"))?),
|
||||
"--state" => state = Some(json_file(&value()?)?),
|
||||
"--renders" => renders = Some(value()?.parse::<usize>().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 <ip>:<port>"))?;
|
||||
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://<ip>:<port>"))?;
|
||||
|
|
@ -124,35 +177,31 @@ fn run_project(args: &[String]) -> Result<String> {
|
|||
}
|
||||
_ => 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 <ip>:<port>"))?;
|
||||
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![],
|
||||
own_rooms: 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!(
|
||||
|
|
|
|||
|
|
@ -45,6 +45,13 @@ const USAGE: &str =
|
|||
/// `rudp://<ip>:<port>` is refused with `usage` or a fixed message, and no
|
||||
/// value is echoed.
|
||||
pub fn instance_and_endpoint(args: &[String], env_endpoint: Option<String>, 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<String>, usage: &str) -> Result<(Slug, Option<SocketAddr>)> {
|
||||
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<String>, 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::<SocketAddr>().ok())
|
||||
.ok_or_else(|| anyhow!("the endpoint is not rudp://<ip>:<port>"))?;
|
||||
Ok((instance, address))
|
||||
Ok((instance, Some(address)))
|
||||
}
|
||||
|
||||
/// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug};
|
|||
use huginn_mind::PipelineFacts;
|
||||
|
||||
use crate::address::{Addressee, Name, is_for, project_names};
|
||||
use crate::chat_client::{Chat, ChatDelivery};
|
||||
use crate::chat_client::{Basis, Chat, ChatDelivery};
|
||||
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
|
||||
use crate::launch::{Clock, Launcher};
|
||||
use crate::queue::{MindPort, headers, in_force, of_kind};
|
||||
|
|
@ -98,11 +98,15 @@ pub struct Config {
|
|||
}
|
||||
|
||||
impl Config {
|
||||
/// Refuses no Persona, a Persona twice, or a beat of zero seconds.
|
||||
/// Refuses no Persona, a Persona twice, a beat of zero seconds, or an operator id that is also a Persona's: one
|
||||
/// sender is either the operator or a Mind, never both, or the wake rule could not tell which it heard.
|
||||
pub fn new(personas: Vec<PersonaId>, operators: Vec<String>, beat_s: u32) -> Result<Self> {
|
||||
if personas.is_empty() {
|
||||
bail!("no persona is configured");
|
||||
}
|
||||
if operators.iter().any(|operator| personas.iter().any(|persona| persona.matrix_id == *operator)) {
|
||||
bail!("an operator id is also a persona's matrix id");
|
||||
}
|
||||
if beat_s == 0 {
|
||||
bail!("the beat is zero seconds");
|
||||
}
|
||||
|
|
@ -393,12 +397,125 @@ pub(crate) fn stewardships_of(mind: &dyn MindPort) -> Result<(Vec<Name>, Vec<Org
|
|||
Ok((names, repos))
|
||||
}
|
||||
|
||||
/// Whether a delivery wakes `who` off the beat: the operator or another Mind of
|
||||
/// the roster addresses her. A Mind naming herself does not; a member does not.
|
||||
fn wakes(config: &Config, who: &Addressee, delivery: &ChatDelivery) -> bool {
|
||||
let from_operator = config.operators.contains(&delivery.sender);
|
||||
let from_other_mind = delivery.sender != who.matrix_id() && config.personas.iter().any(|mind| mind.matrix_id == delivery.sender);
|
||||
(from_operator || from_other_mind) && is_for(who, delivery)
|
||||
/// A member (anyone not the operator) has a pending delivery that addresses her: the beat's urgency. The one owner of
|
||||
/// that reading: the poll's rows and the simulator's beat both ask it, over the deliveries the mouth would give her.
|
||||
pub(crate) fn addressed_by_member(operators: &[String], who: &Addressee, pending: &[ChatDelivery]) -> bool {
|
||||
pending.iter().any(|delivery| !operators.contains(&delivery.sender) && is_for(who, delivery))
|
||||
}
|
||||
|
||||
/// Who sent a line, as the wake rule sees them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Speaker {
|
||||
Operator,
|
||||
/// Another Mind of the roster.
|
||||
Mind,
|
||||
/// A human who is not the operator: a member.
|
||||
Member,
|
||||
/// The Persona herself.
|
||||
Her,
|
||||
}
|
||||
|
||||
impl Speaker {
|
||||
fn human(self) -> bool {
|
||||
matches!(self, Self::Operator | Self::Member)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which lines wake a Persona off the beat. `Live` is the heartbeat's rule today and the only one `poll` uses; the rest
|
||||
/// are what desk question `po-mind-wakes-mind` weighs, run in `mind-persona project --simulate` until it is answered.
|
||||
/// The beat is not here: every policy has it, and it wakes one Persona by `tempo::pick`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum WakePolicy {
|
||||
/// The operator or another Mind addressing her (`is_for`). A member's line does not.
|
||||
Live,
|
||||
/// Ruling `persona-only-wake-humans-in-rooms`: a line addressing her, from anyone, and any human line in her rooms.
|
||||
Ruled,
|
||||
/// Ruling `persona-only-humans-pace`: a human's line wakes her in her own room (a direct message, or a room that is
|
||||
/// hers); in a public room only when it addresses her or continues an exchange she is in. A Mind's line wakes her
|
||||
/// only by an explicit mention (a Matrix mention of her or a reply to her, never a name in prose), in any room, and
|
||||
/// 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 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,
|
||||
}
|
||||
|
||||
/// Why a line wakes her, strongest first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum WakeCause {
|
||||
AddressedByHuman,
|
||||
Human,
|
||||
AddressedByMind,
|
||||
/// A Mind's line that does not address her: only the control wakes on it.
|
||||
Mind,
|
||||
}
|
||||
|
||||
/// What the room says about a line, beside the line: the facts a policy may weigh. The live poll knows none of them yet
|
||||
/// and passes the default; `Live` reads none.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LineFacts {
|
||||
/// 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,
|
||||
/// She has spoken in the room's current exchange: the lines before this one that follow each other without a long gap.
|
||||
pub in_exchange: bool,
|
||||
}
|
||||
|
||||
/// Fail-safe: a caller that has not counted the Mind run is at the cap, so a Mind's line wakes no one; the room facts
|
||||
/// are unknown, so none opens a wake.
|
||||
impl Default for LineFacts {
|
||||
fn default() -> Self {
|
||||
Self { mind_run: usize::MAX, own_room: false, in_exchange: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a line in her rooms wakes `who` off the beat under `policy`, and why. The one owner of the wake rule: the
|
||||
/// heartbeat's poll asks it with `Live`, the simulator with the policy under test.
|
||||
pub(crate) fn wakes(policy: WakePolicy, who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, facts: LineFacts) -> Option<WakeCause> {
|
||||
if speaker == Speaker::Her {
|
||||
return None;
|
||||
}
|
||||
let addressed = is_for(who, delivery);
|
||||
let human = speaker.human();
|
||||
let cause = match (human, addressed) {
|
||||
(true, true) => WakeCause::AddressedByHuman,
|
||||
(true, false) => WakeCause::Human,
|
||||
(false, true) => WakeCause::AddressedByMind,
|
||||
(false, false) => WakeCause::Mind,
|
||||
};
|
||||
let wakes = match policy {
|
||||
WakePolicy::Live => addressed && matches!(speaker, Speaker::Operator | Speaker::Mind),
|
||||
WakePolicy::Ruled => human || addressed,
|
||||
WakePolicy::HumansPace(cap) => {
|
||||
let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply));
|
||||
if human { addressed || delivery.is_direct || facts.own_room || facts.in_exchange } else { explicit && facts.mind_run < cap }
|
||||
}
|
||||
WakePolicy::NamesWithCap(cap) => human || (addressed && facts.mind_run < cap),
|
||||
WakePolicy::AllMessages => true,
|
||||
};
|
||||
wakes.then_some(cause)
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Who sent a delivery, as `wakes` sees them.
|
||||
fn speaker(&self, who: &Addressee, delivery: &ChatDelivery) -> Speaker {
|
||||
if delivery.sender == who.matrix_id() {
|
||||
Speaker::Her
|
||||
} else if self.operators.contains(&delivery.sender) {
|
||||
Speaker::Operator
|
||||
} else if self.personas.iter().any(|mind| mind.matrix_id == delivery.sender) {
|
||||
Speaker::Mind
|
||||
} else {
|
||||
Speaker::Member
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mouth pages a pending answer, so fewer deliveries may come than wait.
|
||||
|
|
@ -443,7 +560,7 @@ impl Row<'_> {
|
|||
|
||||
/// A member (not the operator) has a pending message that names or tags her.
|
||||
fn addressed_by_member(&self, config: &Config) -> bool {
|
||||
self.pending.iter().any(|delivery| !config.operators.contains(&delivery.sender) && is_for(&self.addressee, delivery))
|
||||
addressed_by_member(&config.operators, &self.addressee, &self.pending)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -528,7 +645,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
|||
pending.sort_by_key(|delivery| delivery.seq);
|
||||
pending
|
||||
.into_iter()
|
||||
.filter(|delivery| wakes(config, &row.addressee, delivery))
|
||||
.filter(|delivery| wakes(WakePolicy::Live, &row.addressee, delivery, config.speaker(&row.addressee, delivery), LineFacts::default()).is_some())
|
||||
.map(|delivery| format!("{}:{}", slug.0, delivery.event_id))
|
||||
.find(|key| !state.handled_mentions.contains(key))
|
||||
};
|
||||
|
|
|
|||
|
|
@ -293,7 +293,9 @@ fn each_persona_carries_her_own_huginn_and_a_missing_or_malformed_one_refuses_th
|
|||
for bad in ["ann,ann,Ann,@ann:chat", "ann,ann,Ann,@ann:chat,", "ann,ann,Ann,@ann:chat,127.0.0.1:4101", "ann,ann,Ann,@ann:chat,rudp://localhost:4101"] {
|
||||
assert!(PersonaId::parse(bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(Config::new(personas, vec![], 0).is_err(), "a beat of zero seconds is refused");
|
||||
assert!(Config::new(personas.clone(), vec![], 0).is_err(), "a beat of zero seconds is refused");
|
||||
let refused = Config::new(personas, vec!["@bob:chat".into()], 60).map(|_| ()).unwrap_err();
|
||||
assert!(format!("{refused:#}").contains("operator id is also a persona"), "a sender is the operator or a Mind, never both");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -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@<instance>`: the
|
||||
|
|
|
|||
|
|
@ -10,12 +10,18 @@
|
|||
//! 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 interpret;
|
||||
mod narrate;
|
||||
mod select;
|
||||
mod simulate;
|
||||
mod tuning;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
|
@ -34,7 +40,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, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words};
|
||||
use select::{History, Inputs, Packet, People, Room, RoomLine, select};
|
||||
|
||||
/// The agent name on the connector's request ids.
|
||||
|
|
@ -106,6 +112,17 @@ 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,
|
||||
/// On through the Interpreter's speech step: what she says aloud, decided from her prose (`interpret`).
|
||||
Interpreter,
|
||||
}
|
||||
|
||||
/// What to project.
|
||||
pub struct Request {
|
||||
pub instance: String,
|
||||
|
|
@ -126,6 +143,14 @@ 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<Vec<String>>,
|
||||
/// The rooms that are hers, by the key the lines carry: a simulation's plan. The live body records none yet.
|
||||
pub own_rooms: Vec<String>,
|
||||
}
|
||||
|
||||
/// Her addressee: the heartbeat's row for her when its table holds one, else her own names (handle and public name).
|
||||
|
|
@ -158,13 +183,17 @@ 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(), own: request.own_rooms.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);
|
||||
// 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
|
||||
// alias, so a public room given by its id matches nothing, and the report says so rather than guessing.
|
||||
let here = request.room.clone();
|
||||
let wanted = |room: &str| here.as_deref().is_none_or(|here| here == room);
|
||||
let messages: Vec<RoomLine> = pending
|
||||
.deliveries
|
||||
.iter()
|
||||
.filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias, &delivery.room_id))
|
||||
.filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias))
|
||||
.map(|delivery| RoomLine {
|
||||
room: delivery.room_alias.clone(),
|
||||
sender: delivery.sender.clone(),
|
||||
|
|
@ -179,11 +208,19 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo
|
|||
.tail
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|line| line.form == Form::Message && wanted(&line.room, &line.room))
|
||||
.filter(|line| line.form == Form::Message && wanted(&line.room))
|
||||
.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)
|
||||
let mut report = json!({ "read": true, "messages": messages.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps });
|
||||
if let Some(here) = &here
|
||||
&& messages.is_empty()
|
||||
&& tail.is_empty()
|
||||
&& here.starts_with('!')
|
||||
{
|
||||
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");
|
||||
}
|
||||
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 {
|
||||
|
|
@ -202,13 +239,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<Utc>) -> 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<String> = 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,16 +257,36 @@ 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<String> = packet.ids.clone();
|
||||
json!({
|
||||
let mut render = json!({
|
||||
"seed": packet.seed,
|
||||
"lens": packet.lens,
|
||||
"selected": ids,
|
||||
"words": words(&narration),
|
||||
"cut_at_budget": words(&raw) > budget,
|
||||
"field_names": field_names(&narration, &named),
|
||||
"heard_overlap": heard_overlap(&narration, &packet.heard),
|
||||
"offers_options": offers_options(&narration),
|
||||
"usage": answer.usage,
|
||||
"narration": narration,
|
||||
})
|
||||
});
|
||||
if through == Through::Projector {
|
||||
return render;
|
||||
}
|
||||
let prose = 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);
|
||||
render["persona"] = json!({ "words": words(&prose), "cut_at_budget": words(&spoke.text) > tuning.persona.words, "usage": spoke.usage, "prose": prose });
|
||||
prose
|
||||
}
|
||||
Err(failed) => {
|
||||
render["persona"] = json!({ "failed": failed.reason, "usage": failed.usage });
|
||||
return render;
|
||||
}
|
||||
};
|
||||
if through == Through::Interpreter {
|
||||
render["interpreter"] = interpret::decide(model, &request_id(instance, "interpreter", tag, packet.seed), packet, &narration, &prose, tuning);
|
||||
}
|
||||
render
|
||||
}
|
||||
|
||||
/// K successive turns over one state: each packet under the freshness the earlier ones left.
|
||||
|
|
@ -258,10 +319,11 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> Result
|
|||
let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now);
|
||||
let (room, room_report) = match organs.chat {
|
||||
Some(chat) => read_room(chat, request, &own),
|
||||
None => (Room { here: request.room.clone(), ..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 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 +334,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> 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 +342,15 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> 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::Projector {
|
||||
report["persona_model"] = json!(tuning.persona.model);
|
||||
}
|
||||
if request.through == Through::Interpreter {
|
||||
report["interpreter_model"] = json!(tuning.interpreter.model);
|
||||
}
|
||||
let packets = successive(&inputs, tuning, renders.max(1));
|
||||
report["packet"] = packet_json(&packets[0]);
|
||||
let narrations: Vec<Value> = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", now)).collect();
|
||||
let narrations: Vec<Value> = 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::<Vec<_>>();
|
||||
let failed = |narrations: &[Value]| narrations.iter().filter(|one| one.get("failed").is_some()).count();
|
||||
report["failed_renders"] = json!(failed(&narrations));
|
||||
|
|
@ -294,7 +362,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> 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<Value> = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", now)).collect();
|
||||
let other_narrations: Vec<Value> = 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 +372,7 @@ pub fn project(organs: &Organs, request: &Request, now: DateTime<Utc>) -> 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 }));
|
||||
|
|
|
|||
|
|
@ -1,17 +1,20 @@
|
|||
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.
|
||||
--- context
|
||||
- now: Thursday 19 November, 14:05 UTC
|
||||
- mood, with no earlier turn to measure from: 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.
|
||||
- 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.
|
||||
- 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?"
|
||||
|
|
|
|||
625
crates/mind-body/src/projection/harness.rs
Normal file
625
crates/mind-body/src/projection/harness.rs
Normal file
|
|
@ -0,0 +1,625 @@
|
|||
//! 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 <file>`) 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 <plan>`) runs `project` once per state, scenario and sample and writes one Markdown report.
|
||||
//! - A **simulation** (`--simulate <plan>`, `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;
|
||||
|
||||
/// A narration whose word trigrams overlap what she heard past this share is marked as a high lexical overlap.
|
||||
pub(crate) const OVERLAP_FLAG: f64 = 0.15;
|
||||
/// 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.
|
||||
/// P4 and P5 are not checked: they compare `updatedAt` with the stored document, and no store is read here.
|
||||
pub fn state_file(path: &Path, instance: &str) -> Result<Value> {
|
||||
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<Duration> {
|
||||
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<Utc>) -> 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<String>,
|
||||
/// The round it is said at; 0 is before the first round. Simulations only.
|
||||
#[serde(default)]
|
||||
pub round: Option<usize>,
|
||||
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<String>,
|
||||
/// A direct message: to her in a room fixture; to `to` in a simulation script.
|
||||
#[serde(default)]
|
||||
pub dm: bool,
|
||||
/// The recipient of a direct message, by Matrix id. A room fixture's defaults to her; a script must name one.
|
||||
#[serde(default)]
|
||||
pub to: Option<String>,
|
||||
/// 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<usize>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
/// A direct message, to this Matrix id: only its sender and its recipient see it.
|
||||
pub dm_to: Option<String>,
|
||||
pub follow_up: bool,
|
||||
/// The index of the line it replies to.
|
||||
pub reply_to: Option<usize>,
|
||||
pub new: bool,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
/// A line from a script message; `her` is whom `tag` names.
|
||||
pub(crate) fn of(message: &Message, at: DateTime<Utc>, her: Option<&str>, index: usize) -> Result<Self> {
|
||||
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 dm_to = match (message.dm, &message.to) {
|
||||
(true, Some(to)) if matrix_id(to) => Some(to.clone()),
|
||||
(true, Some(to)) => bail!("message {} is a direct message to \"{to}\", which is not a Matrix id", index + 1),
|
||||
(true, None) => Some(her.ok_or_else(|| anyhow!("message {} is a direct message to no one: a script names its recipient in `to`", index + 1))?.to_owned()),
|
||||
(false, Some(_)) => bail!("message {} names a recipient but is not a direct message", index + 1),
|
||||
(false, None) => None,
|
||||
};
|
||||
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_to, 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<Basis> {
|
||||
if self.dm_to.as_deref() == Some(viewer) {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `viewer` sees the line: a direct message only its sender and recipient; any other line every member of its
|
||||
/// room (no rooms named is every room).
|
||||
pub(crate) fn visible_to(&self, viewer: &str, rooms: &[String]) -> bool {
|
||||
match &self.dm_to {
|
||||
Some(to) => to == viewer || self.from == viewer,
|
||||
None => rooms.is_empty() || rooms.contains(&self.room),
|
||||
}
|
||||
}
|
||||
|
||||
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_to.is_some(),
|
||||
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| line.visible_to(viewer, rooms);
|
||||
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<TailLine> = 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<String>,
|
||||
kind: TurnKind,
|
||||
now: DateTime<Utc>,
|
||||
rooms: Vec<String>,
|
||||
#[serde(default)]
|
||||
here: Option<String>,
|
||||
#[serde(default)]
|
||||
operators: Vec<String>,
|
||||
#[serde(default)]
|
||||
minds: Vec<String>,
|
||||
#[serde(default)]
|
||||
last_heard: BTreeMap<String, String>,
|
||||
#[serde(default, rename = "message")]
|
||||
messages: Vec<Message>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
pub kind: TurnKind,
|
||||
pub now: DateTime<Utc>,
|
||||
pub here: Option<String>,
|
||||
pub operators: Vec<String>,
|
||||
pub minds: Vec<String>,
|
||||
pub last_heard: Vec<(String, u64)>,
|
||||
lines: Vec<Line>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub fn load(path: &Path) -> Result<Self> {
|
||||
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<Self> {
|
||||
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::<Result<_>>()?;
|
||||
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<ChatPending> {
|
||||
Ok(pending_for(&self.lines, &self.her, &[], |at| self.lines[at].new))
|
||||
}
|
||||
}
|
||||
|
||||
impl HeartbeatView for Fixture {
|
||||
fn addressing(&self) -> Result<Option<Addressing>> {
|
||||
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<Value>, seed: u64, renders: Option<usize>, 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![],
|
||||
own_rooms: 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<StateEntry>,
|
||||
#[serde(rename = "scenario")]
|
||||
scenarios: Vec<ScenarioEntry>,
|
||||
}
|
||||
|
||||
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<PathBuf>,
|
||||
}
|
||||
|
||||
#[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<String> {
|
||||
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<Value>)> = 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::<Result<_>>()?;
|
||||
let scenarios: Vec<(String, Fixture)> = plan.scenarios.iter().map(|entry| Ok((entry.name.clone(), Fixture::load(&relative(plan_path, &entry.room))?))).collect::<Result<_>>()?;
|
||||
|
||||
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)["interpreter"]["said"].as_array().is_some_and(|said| !said.is_empty())).count();
|
||||
let mean = |key: &dyn Fn(&Value) -> Option<u64>| mine.iter().filter_map(|case| key(render_of(case))).sum::<u64>() 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<String>)> = 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::<Vec<_>>()));
|
||||
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<details><summary>packet</summary>\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, "</details>\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 _ = writeln!(
|
||||
out,
|
||||
"Narration checks: lexical overlap with what she heard {}{}{}\n",
|
||||
render["heard_overlap"].as_f64().map_or_else(|| "n/a".to_owned(), |overlap| format!("{overlap:.2}")),
|
||||
if render["heard_overlap"].as_f64().is_some_and(|overlap| overlap > OVERLAP_FLAG) { " (high)" } else { "" },
|
||||
if render["offers_options"] == true { "; offers her options" } else { "" }
|
||||
);
|
||||
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());
|
||||
}
|
||||
interpreter_markdown(out, &render["interpreter"]);
|
||||
let _ = writeln!(out, "Usage: projector {}; persona {}; interpreter {}\n", usage_line(&render["usage"]), usage_line(&persona["usage"]), usage_line(&render["interpreter"]["usage"]));
|
||||
}
|
||||
|
||||
/// The Interpreter's speech decision: each line said with its room, mentions, reply target and the span of her prose it
|
||||
/// rests on; each line refused, with why; its gaps. None when the render did not run through the Interpreter.
|
||||
pub(crate) fn interpreter_markdown(out: &mut String, decision: &Value) {
|
||||
if decision.is_null() {
|
||||
return;
|
||||
}
|
||||
if let Some(failed) = decision["failed"].as_str() {
|
||||
let _ = writeln!(out, "**Interpreter failed:** {failed}\n");
|
||||
return;
|
||||
}
|
||||
let said = decision["said"].as_array().cloned().unwrap_or_default();
|
||||
if said.is_empty() {
|
||||
let _ = writeln!(out, "**Interpreter: nothing said.**\n");
|
||||
} else {
|
||||
let _ = writeln!(out, "**Interpreter: said**\n");
|
||||
for line in &said {
|
||||
let mentions = line["mentions"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
||||
let reply = line["reply_to"].as_str().map_or_else(String::new, |id| format!("; reply to {id}"));
|
||||
let _ = writeln!(out, "- in {}{}{}: {}", line["room"].as_str().unwrap_or_default(), if mentions.is_empty() { String::new() } else { format!(", mentioning {mentions}") }, reply, line["text"].as_str().unwrap_or_default());
|
||||
let spans: Vec<String> = line["rests_on"].as_array().into_iter().flatten().map(|span| format!("\"{}\"", span["quote"].as_str().unwrap_or_default())).collect();
|
||||
let _ = writeln!(out, " - her words: {}", spans.join(" + "));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
for line in decision["refused"].as_array().into_iter().flatten() {
|
||||
let 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}");
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
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<String, BTreeMap<String, u64>> {
|
||||
fn walk(value: &Value, into: &mut BTreeMap<String, BTreeMap<String, u64>>) {
|
||||
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, BTreeMap<String, u64>>) -> 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<String, f64> {
|
||||
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<String, f64>| counts.values().map(|count| count * count).sum::<f64>().sqrt();
|
||||
let denominator = norm(&a) * norm(&b);
|
||||
if denominator == 0.0 { 0.0 } else { dot / denominator }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
301
crates/mind-body/src/projection/harness/tests.rs
Normal file
301
crates/mind-body/src/projection/harness/tests.rs
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
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};
|
||||
|
||||
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)`; the
|
||||
/// Interpreter by `interpreter(prompt)`, by default `quoted_lines`. Every call is kept, with its usage counted.
|
||||
pub(crate) struct Scripted {
|
||||
pub calls: RefCell<Vec<(String, String)>>,
|
||||
pub persona: Box<dyn Fn(&str) -> String>,
|
||||
pub interpreter: Box<dyn Fn(&str) -> String>,
|
||||
}
|
||||
|
||||
impl Scripted {
|
||||
pub(crate) fn new(persona: impl Fn(&str) -> String + 'static) -> Self {
|
||||
Self { calls: RefCell::default(), persona: Box::new(persona), interpreter: Box::new(quoted_lines) }
|
||||
}
|
||||
|
||||
pub(crate) fn interpreting(mut self, interpreter: impl Fn(&str) -> String + 'static) -> Self {
|
||||
self.interpreter = Box::new(interpreter);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The recorded Interpreter of the tests: each double-quoted span of her prose is a line she says, citing itself,
|
||||
/// mentioning no one. A test double that keeps the tests' prose readable, not the speech rule: to code a quotation is
|
||||
/// only a text whose sentences are whole, and the live Interpreter is a model.
|
||||
pub(crate) fn quoted_lines(prompt: &str) -> String {
|
||||
let prose = prompt.split("Her prose:\n").nth(1).unwrap_or_default();
|
||||
let say: Vec<Value> = prose.split('"').enumerate().filter(|(at, part)| at % 2 == 1 && !part.trim().is_empty()).map(|(_, part)| json!({ "spans": [part], "mentions": [], "reply_to": null })).collect();
|
||||
json!({ "say": say }).to_string()
|
||||
}
|
||||
|
||||
impl Model for Scripted {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned()));
|
||||
let text = if prompt.starts_with("You decide what one person says aloud") {
|
||||
(self.interpreter)(prompt)
|
||||
} else if prompt.starts_with("<!-- membrane:") {
|
||||
"The room is slow and so is he.".to_owned()
|
||||
} else {
|
||||
(self.persona)(prompt)
|
||||
};
|
||||
Ok(Answer { text, usage: Some(Spent { model: model.to_owned(), input_tokens: 10, output_tokens: 2, cache_read_tokens: 1, cache_write_tokens: 0, reasoning_tokens: None }) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Fails the test if her stored state is asked for.
|
||||
pub(crate) struct NeverAsked;
|
||||
|
||||
impl PersonaSource for NeverAsked {
|
||||
fn persona(&self) -> Result<(Value, String)> {
|
||||
panic!("the stored state was read")
|
||||
}
|
||||
}
|
||||
|
||||
fn harness<'a>(dir: &Path, persona: Option<&'a dyn PersonaSource>, model: Option<&'a dyn Model>) -> Harness<'a> {
|
||||
Harness { instance: "eureka".into(), persona, model, tuning: dir.join("persona-tuning.toml") }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_room_fixture_parses_into_the_mouths_pending_read() {
|
||||
let fixture = room("operator-warm.toml");
|
||||
assert_eq!((fixture.her.as_str(), fixture.kind, fixture.here.as_deref()), (HER, TurnKind::Chat, Some("!dm-meta:gamecult.org")));
|
||||
let pending = MouthReader::pending(&fixture).unwrap();
|
||||
assert_eq!(pending.deliveries.len(), 1, "only the new message is delivered");
|
||||
let dm = &pending.deliveries[0];
|
||||
assert_eq!((dm.sender.as_str(), dm.sender_display.as_str(), dm.is_direct, dm.basis), ("@meta:gamecult.org", "Meta", true, Some(Basis::Direct)));
|
||||
assert!(dm.text.contains("\"busy\""), "a quoted body survives TOML: {}", dm.text);
|
||||
assert_eq!(dm.at_unix_ms, unix_ms(fixture.now - Duration::minutes(1)));
|
||||
assert_eq!(pending.tail.unwrap().len(), 2, "the tail holds every line, delivered or not");
|
||||
assert_eq!(fixture.last_heard, vec![("@meta:gamecult.org".to_owned(), unix_ms(fixture.now - Duration::days(2)))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_for_decides_whether_a_fixture_message_is_for_her() {
|
||||
let her = Addressee::new(HER, ["eureka"]);
|
||||
let for_her = |fixture: &Fixture| MouthReader::pending(fixture).unwrap().deliveries.iter().map(|delivery| is_for(&her, delivery)).collect::<Vec<_>>();
|
||||
// Kiko's reply tags her and answers her own line.
|
||||
let teased = room("mind-teases.toml");
|
||||
let delivery = &MouthReader::pending(&teased).unwrap().deliveries[0];
|
||||
assert_eq!((delivery.basis, delivery.mentions.as_slice()), (Some(Basis::Tag), [HER.to_owned()].as_slice()));
|
||||
assert_eq!(for_her(&teased), vec![true]);
|
||||
// Deru's aside is not.
|
||||
assert_eq!(for_her(&room("deru-passing.toml")), vec![false]);
|
||||
// A name in the text is, a reply to her line is, and an aside is not.
|
||||
let fixture = Fixture::parse(
|
||||
r##"
|
||||
her = "@eureka:gamecult.org"
|
||||
kind = "chat"
|
||||
now = "2026-11-20T15:00:00Z"
|
||||
rooms = ["#minds:gamecult.org"]
|
||||
[[message]]
|
||||
from = "@eureka:gamecult.org"
|
||||
room = "#minds:gamecult.org"
|
||||
ago = "1h"
|
||||
says = "mine"
|
||||
[[message]]
|
||||
from = "@deru:gamecult.org"
|
||||
room = "#minds:gamecult.org"
|
||||
new = true
|
||||
says = "Eureka, tea?"
|
||||
[[message]]
|
||||
from = "@deru:gamecult.org"
|
||||
room = "#minds:gamecult.org"
|
||||
new = true
|
||||
reply_to = 1
|
||||
says = "agreed"
|
||||
[[message]]
|
||||
from = "@deru:gamecult.org"
|
||||
room = "#minds:gamecult.org"
|
||||
new = true
|
||||
says = "the kettle again"
|
||||
"##,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(for_her(&fixture), vec![true, true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fixture_that_is_not_a_room_is_refused_naming_what_is_wrong() {
|
||||
let head = "her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:00:00Z\"\nrooms = [\"#a:x\"]\n";
|
||||
for (tail, names) in [
|
||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#b:x\"\nsays = \"hi\"\n", "not one of the rooms"),
|
||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#a:x\"\nreply_to = 1\nsays = \"hi\"\n", "not an earlier one"),
|
||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#a:x\"\nround = 2\nsays = \"hi\"\n", "round"),
|
||||
("[[message]]\nfrom = \"@d:x\"\nroom = \"#a:x\"\nago = \"soon\"\nsays = \"hi\"\n", "90s"),
|
||||
("[[message]]\nfrom = \"deru\"\nroom = \"#a:x\"\nsays = \"hi\"\n", "Matrix id"),
|
||||
("mood = \"sunny\"\n", "unknown field"),
|
||||
] {
|
||||
let fault = format!("{:#}", Fixture::parse(&format!("{head}{tail}")).unwrap_err());
|
||||
assert!(fault.contains(names), "{tail}: {fault}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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, 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]["room"], "!dm-meta:gamecult.org");
|
||||
assert_eq!(report["interpreter_model"], "claude-sonnet-5-5");
|
||||
assert_eq!(render["persona"]["words"], 17);
|
||||
assert_eq!((render["usage"]["input_tokens"].as_u64(), render["persona"]["usage"]["model"].as_str()), (Some(10), Some("claude-sonnet-5-5")));
|
||||
assert_eq!(report["persona_model"], "claude-sonnet-5-5");
|
||||
let calls = model.calls.borrow();
|
||||
assert_eq!(calls.len(), 3, "one Projector call, one Persona call, one Interpreter call");
|
||||
let persona_prompt = &calls[1].1;
|
||||
assert!(persona_prompt.starts_with("Everything below is prose from inside one person's life."), "Ghostlight's Persona membrane");
|
||||
assert!(persona_prompt.contains("The room is slow and so is he.") && persona_prompt.contains("hey you. I missed talking to you this week"), "the narration, then what she heard verbatim: {persona_prompt}");
|
||||
assert!(persona_prompt.contains("Use at most 180 words"), "the map's Persona budget");
|
||||
for field in ["socialBonds", "currentActivation", "bond-operator", "trust\":"] {
|
||||
assert!(!persona_prompt.contains(field), "no field name reaches the Persona: {field}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prose_over_budget_is_cut_and_silence_says_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let long = format!("{} \"late words\"", "word ".repeat(200));
|
||||
let model = Scripted::new(move |_| long.clone());
|
||||
let fixture = room("deru-passing.toml");
|
||||
let harness = harness(dir.path(), None, Some(&model));
|
||||
let organs = Organs { persona: None, chat: Some(&fixture), addressing: None, model: harness.model };
|
||||
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, Some(1), Through::Interpreter), fixture.now).unwrap();
|
||||
let persona = &report["renders"][0]["persona"];
|
||||
assert_eq!((persona["words"].as_u64(), persona["cut_at_budget"].as_bool()), (Some(180), Some(true)));
|
||||
assert_eq!(report["renders"][0]["interpreter"]["said"], json!([]), "words past the budget are not her prose, so nothing rests on them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_runs_every_state_by_scenario_by_sample_into_one_report() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let plan = dir.path().join("plan.toml");
|
||||
let rooms = fixtures().join("rooms");
|
||||
std::fs::write(
|
||||
&plan,
|
||||
format!(
|
||||
"samples = 2\nseed = 7\nthrough = \"interpreter\"\n[[state]]\nname = \"control\"\nfile = {:?}\n[[scenario]]\nname = \"quiet\"\nroom = {:?}\n[[scenario]]\nname = \"teased\"\nroom = {:?}\n",
|
||||
fixtures().join("states/control.json").display().to_string(),
|
||||
rooms.join("quiet-beat.toml").display().to_string(),
|
||||
rooms.join("mind-teases.toml").display().to_string()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let model = Scripted::new(|prompt| if prompt.contains("Kiko") { "\"Winter, still.\" He grins.".into() } else { "He lets the hour pass.".into() });
|
||||
let report = batch(&harness(dir.path(), Some(&NeverAsked), Some(&model)), &plan).unwrap();
|
||||
for heading in ["# Persona seed batch", "## Summary", "## control × quiet, sample 1 (seed 7)", "## control × quiet, sample 2 (seed 8)", "## control × teased, sample 2 (seed 8)", "## Total usage"] {
|
||||
assert!(report.contains(heading), "{heading}\n{report}");
|
||||
}
|
||||
assert!(report.contains("| control | teased | 2/2 |") && report.contains("| control | quiet | 0/2 |"), "{report}");
|
||||
assert!(report.contains("- in #minds:gamecult.org: Winter, still.") && report.contains(" - her words: \"Winter, still.\"") && report.contains("**Interpreter: nothing said.**"), "{report}");
|
||||
assert!(report.contains("| claude-sonnet-5-5 | 12 | 120 | 24 |"), "twelve calls, three a case, in the footer: {report}");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the batch wrote nothing; the caller writes the report");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_state_without_a_file_is_her_stored_state() {
|
||||
struct Stored;
|
||||
impl PersonaSource for Stored {
|
||||
fn persona(&self) -> Result<(Value, String)> {
|
||||
Ok((control(), "mind-commit-x".into()))
|
||||
}
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let plan = dir.path().join("plan.toml");
|
||||
std::fs::write(&plan, format!("[[state]]\nname = \"stored\"\n[[scenario]]\nname = \"quiet\"\nroom = {:?}\n", fixtures().join("rooms/quiet-beat.toml").display().to_string())).unwrap();
|
||||
let model = Scripted::new(|_| String::new());
|
||||
let report = batch(&harness(dir.path(), Some(&Stored), Some(&model)), &plan).unwrap();
|
||||
assert!(report.contains("## stored × quiet, sample 1") && !report.contains("failed"), "{report}");
|
||||
}
|
||||
|
||||
fn group_line_of(dir: &Path, name: &str) -> Option<String> {
|
||||
let fixture = room(name);
|
||||
let harness = harness(dir, None, None);
|
||||
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: None };
|
||||
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap();
|
||||
report["packet"]["context"].as_str().unwrap().lines().find(|line| line.starts_with("- the conversation")).map(str::to_owned)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_state_reads_each_scenario_room_as_the_golden_file_says() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut rendered = String::new();
|
||||
for name in ["quiet-beat.toml", "operator-warm.toml", "mind-teases.toml", "deru-passing.toml"] {
|
||||
let line = group_line_of(dir.path(), name).unwrap_or_else(|| "(none)".into());
|
||||
assert!(line.len() <= 360, "the slot holds its byte budget: {line}");
|
||||
rendered.push_str(&format!("{name}: {line}
|
||||
"));
|
||||
}
|
||||
let golden = include_str!("../../../fixtures/harness/golden-group.txt").replace("
|
||||
", "
|
||||
");
|
||||
assert_eq!(rendered, golden, "the group state moved; if deliberately, the new golden file is:
|
||||
{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_state_is_off_when_the_tuning_says_so() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("persona-tuning.toml"), "[select]
|
||||
group_state = false
|
||||
").unwrap();
|
||||
assert!(group_line_of(dir.path(), "mind-teases.toml").is_none());
|
||||
}
|
||||
|
||||
/// Round 1 of a crowded room: the operator asks everyone, and `answered` Minds have answered before this one's turn.
|
||||
fn chorus(answered: usize) -> Fixture {
|
||||
let minds = ["@weksa:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@libby:gamecult.org", "@void:gamecult.org", "@nibu:gamecult.org", "@aqua:gamecult.org"];
|
||||
let mut text = String::from("her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:05:00Z\"\nrooms = [\"#minds:gamecult.org\"]\nhere = \"#minds:gamecult.org\"\noperators = [\"@meta:gamecult.org\"]\nminds = [\"@eureka:gamecult.org\", \"@weksa:gamecult.org\", \"@heimdall:gamecult.org\", \"@kiko:gamecult.org\", \"@libby:gamecult.org\", \"@void:gamecult.org\", \"@nibu:gamecult.org\", \"@aqua:gamecult.org\"]\n");
|
||||
text.push_str("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nago = \"5m\"\nnew = true\nsays = \"afternoon, all of you. no tasks today. how's everyone doing?\"\n");
|
||||
for (at, mind) in minds.iter().take(answered).enumerate() {
|
||||
text.push_str(&format!("[[message]]\nfrom = \"{mind}\"\nname = \"{}\"\nroom = \"#minds:gamecult.org\"\nago = \"{}s\"\nnew = true\nsays = \"afternoon, Meta. doing well, thanks.\"\n", crate::address::localpart(mind), 240 - at * 20));
|
||||
}
|
||||
Fixture::parse(&text).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_third_to_eighth_responder_sees_a_covered_question_and_no_duty() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let harness = harness(dir.path(), None, None);
|
||||
let mut rendered = String::new();
|
||||
for answered in 2..=7 {
|
||||
let fixture = chorus(answered);
|
||||
let organs = Organs { persona: None, chat: Some(&fixture), addressing: None, model: None };
|
||||
let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap();
|
||||
let context = report["packet"]["context"].as_str().unwrap().to_owned();
|
||||
let line = context.lines().find(|line| line.starts_with("- the conversation")).unwrap_or_else(|| panic!("{context}")).to_owned();
|
||||
assert!(line.contains("asked the room a question, and") && line.contains("answered it"), "{line}");
|
||||
for duty in ["owe", "haven't", "have not", "open", "still", "waiting on her", "to her", "unanswered"] {
|
||||
assert!(!line.contains(duty), "responder {}: {duty} in {line}", answered + 1);
|
||||
}
|
||||
rendered.push_str(&format!("responder {}: {line}\n", answered + 1));
|
||||
}
|
||||
let golden = include_str!("../../../fixtures/harness/golden-chorus.txt").replace("\r\n", "\n");
|
||||
assert_eq!(rendered, golden, "the chorus's group state moved; if deliberately, the new golden file is:\n{rendered}");
|
||||
}
|
||||
275
crates/mind-body/src/projection/interpret.rs
Normal file
275
crates/mind-body/src/projection/interpret.rs
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
//! The Interpreter's speech (map section 4, cut C3b): what she says aloud this turn, decided from her prose by one
|
||||
//! tool-less structured model call, and built by code from her own words.
|
||||
//!
|
||||
//! The Persona writes her thought, and when she means to say something she writes the words she would type. The
|
||||
//! Interpreter decides whether she says them now: it answers with zero or more lines, each a list of spans of her prose
|
||||
//! cited verbatim, with the people she addresses (Matrix mentions and a reply target, as structured fields). Code builds
|
||||
//! each line, never the model: each span is located in her prose by Ghostlight's `SourceSpan::locate` and must be whole
|
||||
//! sentences (UAX #29 sentence segmentation, the Unicode family `locate`'s word boundaries come from), and the spans of
|
||||
//! one line must be consecutive sentences; the line is that one unbroken run of her prose. A quotation's inside is
|
||||
//! segmented as a text of its own, so a quoted sentence is whole, but only a standalone quotation's: one that is itself
|
||||
//! whole sentences of her prose. A line may not start or end inside a quotation her sentence frames ("I won't say
|
||||
//! \"Nibu is lying.\"", "If she pushes, I'll say \"Fine.\""): that is what she would or would not say. An opening
|
||||
//! mark a budget left unclosed is not part of the sentence it starts. So a line is always whole sentences of her own,
|
||||
//! verbatim and in their order: no stitching, no dropped negation, no condition lifted off its clause. What this gives
|
||||
//! up: indirect speech ("I'll tell her I'm fine" says nothing), any paraphrase by the Interpreter, half a sentence, and
|
||||
//! a line quoted inside a sentence of narration ("\"Fine,\" I tell her."): she says a sentence whole or not at all.
|
||||
//!
|
||||
//! Code keeps a line only when it is built so; drops an echo (at least `ECHO_MIN_WORDS` words, at least `ECHO_OVERLAP`
|
||||
//! of its word trigrams in the bodies the stimulus quoted to her); keeps at most `MAX_LINES` distinct lines; and keeps a
|
||||
//! mention or a reply target only for someone this packet showed her (`Packet::people`). She speaks only in the turn's
|
||||
//! room. Whether a line tells what she knows privately is a reading of its meaning, so it is the Interpreter's
|
||||
//! judgement over the private items the packet lists to it (`Packet::private`), never a word match here. Every refusal
|
||||
//! and drop is reported. Nothing here posts: the commit (C3c) will.
|
||||
|
||||
use ghostlight_persona_projection::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;
|
||||
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 at least this share of what she heard is an echo, not
|
||||
/// her speech.
|
||||
const ECHO_MIN_WORDS: usize = 8;
|
||||
const ECHO_OVERLAP: f64 = 0.8;
|
||||
|
||||
/// What to say, where, to whom, and the gaps: Huginn's chat Interpreter, beside nothing of Ghostlight's but its span rule.
|
||||
const SPEECH_PROMPT: &str = "You decide what one person says aloud in a chat room this turn, from her own prose. You never write her words: you cite them.
|
||||
|
||||
Below are who she is, the room and who is in it, what reached her, her lived moment, and her prose. Decide which words of her prose she chooses to say aloud now, in this room. A line is speech only when her prose shows her choosing to say it now. Wondering whether to speak, deciding to wait or stay quiet, or saying that she says nothing, is not speech. Words she recalls or quotes from someone else are never her speech.
|
||||
|
||||
She speaks only in this room. What she knows privately is listed below as private: she says none of it here, and nothing that gives it away. A private matter may be said plainly only to the person it concerns, in a direct message with exactly that person; nothing listed is that here. Whether a line fits who is listening is yours to judge.
|
||||
|
||||
Answer with one JSON object and nothing else:
|
||||
{\"say\": [{\"spans\": [\"<whole sentences of her prose, copied character for character>\"], \"mentions\": [\"<Matrix id of someone listed whom she addresses directly>\"], \"reply_to\": \"<Matrix id of the person whose message she answers, or null>\"}], \"gaps\": [{\"kind\": \"conditional | addressee | elsewhere\", \"quote\": \"<exact words of her prose>\", \"detail\": \"<why>\"}]}
|
||||
|
||||
A line is whole sentences of her prose, the words she would type and nothing she only describes: each span is one sentence or several, from its first character to its last, and the spans of one line are consecutive sentences. A quotation that stands as sentences of its own may be cited sentence by sentence; words quoted inside a sentence of narration are cited only with that whole sentence, and then only if that sentence is what she says. She never says half a sentence; if only part of a sentence is speech, she says nothing of it. At most two lines. Record a gap instead of guessing: conditional when she might say something but has not chosen to, addressee when she means to say it but whom to is unclear, elsewhere when she means it for another room or another time. An empty say list is the usual answer in a busy room.";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Answer {
|
||||
#[serde(default)]
|
||||
say: Vec<Proposed>,
|
||||
#[serde(default)]
|
||||
gaps: Vec<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Proposed {
|
||||
#[serde(default)]
|
||||
spans: Vec<String>,
|
||||
#[serde(default)]
|
||||
mentions: Vec<String>,
|
||||
#[serde(default)]
|
||||
reply_to: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn speech_prompt(packet: &Packet, narration: &str, prose: &str) -> String {
|
||||
let mut people = String::new();
|
||||
for (label, id) in &packet.people {
|
||||
people.push_str(&format!("- {label} \u{2014} {id}\n"));
|
||||
}
|
||||
if people.is_empty() {
|
||||
people.push_str("- no one else has spoken here lately\n");
|
||||
}
|
||||
let mut private: String = packet.private.iter().map(|words| format!("- private: {words}\n")).collect();
|
||||
if private.is_empty() {
|
||||
private.push_str("- none\n");
|
||||
}
|
||||
format!(
|
||||
"{SPEECH_PROMPT}\n\nWho she is:\n{}\n\nThe room: {} ({}).\nWho is in it, as label \u{2014} Matrix id:\n{people}\nWhat she knows privately, none of it to be said here:\n{private}\nWhat reached her:\n{}\n\nHer lived moment:\n{}\n\nHer prose:\n{prose}",
|
||||
packet.identity,
|
||||
packet.room.as_deref().unwrap_or("none"),
|
||||
packet.room_kind.words(),
|
||||
packet.stimulus,
|
||||
lived_stream(narration, &packet.heard),
|
||||
)
|
||||
}
|
||||
|
||||
/// The model's answer as JSON: the object itself, or inside a fenced block.
|
||||
fn json_of(text: &str) -> Option<Answer> {
|
||||
let start = text.find('{')?;
|
||||
let end = text.rfind('}')?;
|
||||
serde_json::from_str(&text[start..=end]).ok()
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// Her quotations, paired in order: a straight double quote with the next one, a curly opening mark with the next curly
|
||||
/// closing one. And the opening mark left unclosed, if one is (a budget cut her prose inside a quotation), with its
|
||||
/// length.
|
||||
fn quotations(prose: &str) -> (Vec<Quotation>, Option<(usize, usize)>) {
|
||||
let mut out = Vec::new();
|
||||
let mut open: Option<(usize, usize, char)> = None;
|
||||
for (at, c) in prose.char_indices() {
|
||||
match open {
|
||||
None if c == '"' => open = Some((at, c.len_utf8(), '"')),
|
||||
None if c == '\u{201C}' => open = Some((at, c.len_utf8(), '\u{201D}')),
|
||||
Some((mark, len, close)) if c == close => {
|
||||
out.push(Quotation { open: mark, inside: (mark + len, at), close: at + c.len_utf8() });
|
||||
open = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(out, open.map(|(mark, len, _)| (mark, len)))
|
||||
}
|
||||
|
||||
/// Byte ranges of `text`'s sentences (UAX #29), offset by `offset`, without the space around them.
|
||||
fn segment(offset: usize, text: &str) -> Vec<(usize, usize)> {
|
||||
text.split_sentence_bound_indices()
|
||||
.filter_map(|(at, sentence)| {
|
||||
let start = at + sentence.len() - sentence.trim_start().len();
|
||||
let end = at + sentence.trim_end().len();
|
||||
(start < end).then_some((offset + start, offset + end))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Her prose read for speech: its sentences in lists, her prose's own first, then each quotation's inside segmented as
|
||||
/// a text of its own; and the quotations her sentences frame. A quotation is standalone when it, marks included, is
|
||||
/// exactly a run of whole sentences of her prose (closing punctuation after its mark allowed); any other is framed. "I
|
||||
/// won't say "Nibu is lying."" frames what she would or would not say, never what she says. An opening mark left
|
||||
/// unclosed at a sentence's start is not part of that sentence.
|
||||
struct Reading {
|
||||
lists: Vec<Vec<(usize, usize)>>,
|
||||
framed: Vec<Quotation>,
|
||||
}
|
||||
|
||||
fn read(prose: &str) -> Reading {
|
||||
let (quotes, unclosed) = quotations(prose);
|
||||
let mut top = segment(0, prose);
|
||||
if let Some((mark, len)) = unclosed
|
||||
&& let Some(sentence) = top.iter_mut().find(|sentence| sentence.0 == mark)
|
||||
{
|
||||
let rest = &prose[mark + len..sentence.1];
|
||||
let start = sentence.1 - rest.trim_start().len();
|
||||
if start < sentence.1 {
|
||||
sentence.0 = start;
|
||||
}
|
||||
}
|
||||
let standalone = |quote: &Quotation| {
|
||||
let opens = top.iter().position(|sentence| sentence.0 == quote.open);
|
||||
let closes = top.iter().position(|sentence| sentence.0 < quote.close && sentence.1 >= quote.close && prose[quote.close..sentence.1].chars().all(|c| c.is_ascii_punctuation()));
|
||||
matches!((opens, closes), (Some(opens), Some(closes)) if opens <= closes)
|
||||
};
|
||||
let framed = quotes.iter().copied().filter(|quote| !standalone(quote)).collect();
|
||||
let mut lists = vec![top];
|
||||
lists.extend(quotes.iter().map(|quote| segment(quote.inside.0, &prose[quote.inside.0..quote.inside.1])));
|
||||
Reading { lists, framed }
|
||||
}
|
||||
|
||||
/// The line her cited spans make, or why not. Each span is located in her prose after the one before it and must be
|
||||
/// whole sentences of one list (`read`), each span's first sentence the one after the last span's last; the line is her
|
||||
/// prose from the first sentence to the last, verbatim, and it may neither start nor end inside a framed quotation. A
|
||||
/// line that holds a framed quotation whole ("Kiko's "plan" is a mess.") is hers to say.
|
||||
fn built(prose: &str, spans: &[String]) -> Result<(String, Vec<Value>), &'static str> {
|
||||
let Reading { lists, framed } = read(prose);
|
||||
let mut from = 0;
|
||||
// The list the line is in, and its last sentence so far.
|
||||
let mut run: Option<(usize, usize)> = None;
|
||||
let mut first = None;
|
||||
let mut located = Vec::new();
|
||||
for span in spans.iter().map(|span| span.trim()).filter(|span| !span.is_empty()) {
|
||||
let Some(found) = prose.get(from..).and_then(|rest| SourceSpan::locate(rest, span)) else {
|
||||
return Err("a span is not in her prose, word for word and in order");
|
||||
};
|
||||
let (start, end) = (from + found.start_byte(), from + found.end_byte());
|
||||
let whole: Vec<(usize, usize, usize)> = lists
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(list, sentences)| {
|
||||
let opens = sentences.iter().position(|sentence| sentence.0 == start)?;
|
||||
let closes = sentences.iter().position(|sentence| sentence.1 == end)?;
|
||||
(opens <= closes).then_some((list, opens, closes))
|
||||
})
|
||||
.collect();
|
||||
if whole.is_empty() {
|
||||
return Err("a span is not whole sentences of her prose: she says a sentence whole or not at all");
|
||||
}
|
||||
let Some(&(list, _, closes)) = whole.iter().find(|(list, opens, _)| run.is_none_or(|(in_list, last)| in_list == *list && last + 1 == *opens)) else {
|
||||
return Err("the spans are not consecutive sentences of her prose");
|
||||
};
|
||||
run = Some((list, closes));
|
||||
first.get_or_insert(start);
|
||||
located.push(json!({ "quote": found.verbatim(), "start_byte": start, "end_byte": end }));
|
||||
from = end;
|
||||
}
|
||||
let Some(first) = first else {
|
||||
return Err("no words");
|
||||
};
|
||||
let inside = |at: usize| framed.iter().any(|quote| quote.open < at && at < quote.close);
|
||||
if inside(first) || inside(from) {
|
||||
return Err("it starts or ends inside a quotation her sentence frames: words she would or would not say, not words she says");
|
||||
}
|
||||
Ok((prose[first..from].to_owned(), located))
|
||||
}
|
||||
|
||||
/// Whether a line is someone else's words: long enough to judge, and nearly all a run of what she heard, by word
|
||||
/// trigrams against the bodies the stimulus quoted (`heard_overlap`). Short answers such as "ok" or "Hi" are never
|
||||
/// echoes, and a line that answers a claim by naming it is not one.
|
||||
fn echo(line: &str, bodies: &[String]) -> bool {
|
||||
line.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).count() >= ECHO_MIN_WORDS && heard_overlap(line, &bodies.join("\n")) >= ECHO_OVERLAP
|
||||
}
|
||||
|
||||
/// One speech decision: the Interpreter's call, then code's hold on each line. The report carries the lines said, the
|
||||
/// lines refused with why, the mentions dropped, the gaps and the call's usage. A failed call or an answer that is not
|
||||
/// the contract is a failure, never a silence.
|
||||
pub(crate) fn decide(model: &dyn Model, request_id: &str, packet: &Packet, narration: &str, prose: &str, tuning: &Tuning) -> Value {
|
||||
let answer = match model.ask(request_id, &tuning.interpreter.model, &speech_prompt(packet, narration, prose)) {
|
||||
Ok(answer) => answer,
|
||||
Err(failed) => return json!({ "failed": failed.reason, "usage": failed.usage }),
|
||||
};
|
||||
let Some(parsed) = json_of(&answer.text) else {
|
||||
return json!({ "failed": "the answer is not the speech contract's JSON", "raw": answer.text, "usage": answer.usage });
|
||||
};
|
||||
let Some(room) = packet.room.clone() else {
|
||||
return json!({ "said": [], "refused": [{ "why": "the turn has no room to speak in" }], "gaps": parsed.gaps, "usage": answer.usage });
|
||||
};
|
||||
let shown = |id: &str| packet.people.iter().any(|(_, person)| person == id);
|
||||
let mut said: Vec<Value> = Vec::new();
|
||||
let mut refused = Vec::new();
|
||||
for line in parsed.say {
|
||||
let (text, spans) = match built(prose, &line.spans) {
|
||||
Ok(built) => built,
|
||||
Err(why) => {
|
||||
refused.push(json!({ "spans": line.spans, "why": why }));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let why = if echo(&text, &packet.bodies) {
|
||||
Some("mostly words she heard: an echo, not her speech")
|
||||
} else if said.iter().any(|kept| kept["text"] == text.as_str()) {
|
||||
Some("the same line again")
|
||||
} else if said.len() >= MAX_LINES {
|
||||
Some("past the lines one turn may say")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(why) = why {
|
||||
refused.push(json!({ "text": text, "why": why }));
|
||||
continue;
|
||||
}
|
||||
let (mentions, unknown): (Vec<String>, Vec<String>) = line.mentions.into_iter().partition(|id| shown(id));
|
||||
let (reply_to, unknown_reply) = match line.reply_to.filter(|id| !id.trim().is_empty()) {
|
||||
Some(id) if shown(&id) => (Some(id), None),
|
||||
Some(id) => (None, Some(id)),
|
||||
None => (None, None),
|
||||
};
|
||||
said.push(json!({ "room": room, "text": text, "mentions": mentions, "reply_to": reply_to, "rests_on": spans, "dropped": { "mentions": unknown, "reply_to": unknown_reply } }));
|
||||
}
|
||||
json!({ "room": room, "room_kind": packet.room_kind, "said": said, "refused": refused, "gaps": parsed.gaps, "usage": answer.usage })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
289
crates/mind-body/src/projection/interpret/tests.rs
Normal file
289
crates/mind-body/src/projection/interpret/tests.rs
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
use crate::projection::harness::tests::{Scripted, control};
|
||||
use crate::projection::select::{History, Inputs, People, Room, RoomKind, RoomLine, TurnKind, select};
|
||||
use crate::projection::tuning::Tuning;
|
||||
|
||||
const HER: &str = "@heimdall:gamecult.org";
|
||||
const NIBU: &str = "@nibu:gamecult.org";
|
||||
const VOID: &str = "@void:gamecult.org";
|
||||
const LIBBY: &str = "@libby:gamecult.org";
|
||||
const KIKO: &str = "@kiko:gamecult.org";
|
||||
const MINDS: &str = "#minds:gamecult.org";
|
||||
|
||||
fn now() -> chrono::DateTime<chrono::Utc> {
|
||||
chrono::DateTime::parse_from_rfc3339("2026-11-20T15:05:00Z").unwrap().with_timezone(&chrono::Utc)
|
||||
}
|
||||
|
||||
fn line(room: &str, sender: &str, display: &str, text: &str, to_her: bool) -> RoomLine {
|
||||
RoomLine { room: room.into(), sender: sender.into(), display: display.into(), text: text.into(), at_ms: u64::try_from(now().timestamp_millis()).unwrap() - 60_000, to_her }
|
||||
}
|
||||
|
||||
/// Heimdall's packet of a turn of `kind` in `room` over `state`.
|
||||
fn packet_in(kind: TurnKind, state: &Value, room: &Room, seed: u64) -> Packet {
|
||||
let minds = vec![HER.to_owned(), NIBU.to_owned(), VOID.to_owned(), LIBBY.to_owned(), KIKO.to_owned()];
|
||||
let operators = vec!["@meta:gamecult.org".to_owned()];
|
||||
let history = History::default();
|
||||
select(&Inputs { kind, state, room, history: &history, observation: None, people: People { operators: &operators, minds: &minds, own_sender: HER }, now: now(), seed }, &Tuning::default())
|
||||
}
|
||||
|
||||
fn heimdall() -> Value {
|
||||
let mut state = control();
|
||||
state["publicName"] = "Heimdall".into();
|
||||
state
|
||||
}
|
||||
|
||||
/// Soul's round: Nibu said the economy is the least built part, and Meta greeted Nibu; this is Heimdall's turn. Void is
|
||||
/// a Mind of the swarm who said nothing.
|
||||
fn packet() -> Packet {
|
||||
let room = Room {
|
||||
messages: vec![
|
||||
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()
|
||||
};
|
||||
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 {
|
||||
decided_in(&packet(), prose, say)
|
||||
}
|
||||
|
||||
fn texts(decision: &Value) -> Vec<String> {
|
||||
decision["said"].as_array().unwrap().iter().map(|line| line["text"].as_str().unwrap().to_owned()).collect()
|
||||
}
|
||||
|
||||
fn refused_why(decision: &Value) -> String {
|
||||
decision["refused"][0]["why"].as_str().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn 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_standalone_quotation_is_sayable_sentence_by_sentence() {
|
||||
let prose = "\"Fine,\" I tell her. \"Winter is the best season.\" She won't agree.";
|
||||
assert_eq!(texts(&decided(prose, json!([{ "spans": ["Winter is the best season."] }]))), ["Winter is the best season."]);
|
||||
// A quotation inside a sentence of narration is framed: its words are not said alone.
|
||||
let tag = decided(prose, json!([{ "spans": ["Fine,"] }]));
|
||||
assert!(texts(&tag).is_empty() && refused_why(&tag).contains("frames"), "{tag}");
|
||||
let curly = "\u{201C}No. Not yet.\u{201D} I shake my head.";
|
||||
assert_eq!(texts(&decided(curly, json!([{ "spans": ["No.", "Not yet."] }]))), ["No. Not yet."]);
|
||||
assert_eq!(texts(&decided(curly, json!([{ "spans": ["Not yet."] }]))), ["Not yet."]);
|
||||
assert!(texts(&decided(curly, json!([{ "spans": ["Not"] }]))).is_empty());
|
||||
}
|
||||
|
||||
/// Whether citing `spans` of `prose` says anything, and why not.
|
||||
fn says(prose: &str, spans: &[&str]) -> (Vec<String>, String) {
|
||||
let decision = decided(prose, json!([{ "spans": spans }]));
|
||||
(texts(&decision), refused_why(&decision))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f1_a_quotation_her_sentence_frames_is_never_said_from_inside() {
|
||||
for (name, prose, spans) in [
|
||||
("conditional", "If Kiko asks, I'd tell her \"the new design is ugly.\"", &["the new design is ugly."][..]),
|
||||
("negated", "I won't say \"Nibu is lying.\"", &["Nibu is lying."]),
|
||||
("abandoned", "I almost said \"I'm leaving.\"", &["I'm leaving."]),
|
||||
("abandoned, tagged", "\"I'm leaving,\" I almost said, but I bit it back.", &["I'm leaving,"]),
|
||||
("recalled", "Nibu said \"the economy is fine.\" I doubt it.", &["the economy is fine."]),
|
||||
("curly conditional", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["Fine.", "You win."]),
|
||||
("curly conditional, its tail", "If she pushes, I'll say \u{201C}Fine. You win.\u{201D}", &["You win.\u{201D}"]),
|
||||
("hypothetical", "Imagine if I just typed \"Meta, I quit.\" Ha. No.", &["Meta, I quit."]),
|
||||
("negated, top-level tail", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying.\""]),
|
||||
("negated, top-level tail inside", "I won't say \"Stop. Nibu is lying.\" Not here.", &["Nibu is lying."]),
|
||||
("negated, top-level head", "I won't say \"Stop. Nibu is lying.\" Not here.", &["I won't say \"Stop."]),
|
||||
("abandoned, top-level tail", "I almost said \"I'm leaving. Bye.\" Then I didn't.", &["Bye.\""]),
|
||||
("stray inch mark", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["I won't say"]),
|
||||
("stray inch mark, the quote", "It's a 5\" screen. I won't say \"Nibu is lying.\" Ok.", &["Nibu is lying."]),
|
||||
("scare quotes", "Kiko's \"plan\" is a mess, but I won't tell her so.", &["plan"]),
|
||||
] {
|
||||
let (said, why) = says(prose, spans);
|
||||
assert!(said.is_empty() && !why.is_empty(), "{name}: said {said:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f1_a_sentence_that_holds_a_quotation_whole_is_hers_to_say() {
|
||||
assert_eq!(says("Weksa, \"list'n, hark\" is a great hedge. I mean it.", &["Weksa, \"list'n, hark\" is a great hedge."]).0, ["Weksa, \"list'n, hark\" is a great hedge."]);
|
||||
assert_eq!(says("Kiko's \"plan\" is a mess. I say so.", &["Kiko's \"plan\" is a mess."]).0, ["Kiko's \"plan\" is a mess."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f4_an_opening_mark_the_budget_left_unclosed_does_not_silence_the_line() {
|
||||
// Weksa, round 6 and round 10 of v5: the budget cut her prose inside the quotation.
|
||||
let r6 = "How I am is less certain. I think \"settled\" would be borrowing from the others, and I only half believe it. \"Narrower, and not unhappy about it\" is closer, though I'm hedging on the second half.\n\nWhat I'd type:\n\n\"Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
|
||||
let line = "Hi Meta, late to this, and I can't tell whether you meant me or the room, so I'm answering either way. I'm here, back after the quiet months, rebuilt narrower than before. As far as I can tell, that's fine. I'm not certain yet, but I don't see anything wrong with it.";
|
||||
assert_eq!(says(r6, &[line]).0, [line]);
|
||||
let r10 = "A deadline on joy is a risk, but I think I can pick one small enough to survive it. Not \"finish Zyphos.\" Something with an output I can inspect.\n\nWhat I'd type:\n\n\"Kiko, you've counted correctly and I resent it, fondly.";
|
||||
assert_eq!(says(r10, &["Kiko, you've counted correctly and I resent it, fondly."]).0, ["Kiko, you've counted correctly and I resent it, fondly."], "the line carries no stray mark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q1_a_cited_span_cannot_change_her_meaning() {
|
||||
// Q1a: stitched spans would invert her meaning.
|
||||
let q1a = decided("I'm not angry at Nibu, not even a little. Still, the economy work is going badly and that is on all of us.", json!([{ "spans": ["I'm", "angry at Nibu,"] }]));
|
||||
// Q1b: one span would drop her negation.
|
||||
let q1b = decided("I don't think Nibu should ship this yet.", json!([{ "spans": ["Nibu should ship this yet."] }]));
|
||||
// Q1c: two spans far apart.
|
||||
let far = format!("I trust Void. {} Nibu is lying about the economy, says Kiko's rumour, which I refuse to believe.", "filler words go here. ".repeat(200));
|
||||
let q1c = decided(&far, json!([{ "spans": ["I trust", "Nibu is lying about the economy,"] }]));
|
||||
// Q1d: a condition lifted off its clause.
|
||||
let q1d = decided("If Kiko asks, I would tell her the new design is ugly. I keep that to myself.", json!([{ "spans": ["the new design is ugly."] }]));
|
||||
for decision in [q1a, q1b, q1c, q1d] {
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("whole sentences"), "{decision}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_not_in_her_prose_is_refused() {
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["words she never wrote"], "mentions": [], "reply_to": null }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("not in her prose"), "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p2_a_short_answer_is_never_an_echo() {
|
||||
assert_eq!(texts(&decided("Ok. I tell her ok.", json!([{ "spans": ["Ok."], "mentions": [], "reply_to": NIBU }]))), ["Ok."]);
|
||||
assert_eq!(texts(&decided("Hi. I say hi.", json!([{ "spans": ["Hi."], "mentions": [], "reply_to": NIBU }]))), ["Hi."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p3_a_near_verbatim_echo_is_refused() {
|
||||
let prose = "The economy is still the least-built part! I say it back.";
|
||||
let decision = decided(prose, json!([{ "spans": ["The economy is still the least-built part!"], "mentions": [], "reply_to": null }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_r9_disagreeing_by_naming_the_claim_is_her_speech() {
|
||||
let prose = "Nibu, I don't think the economy is still the least built part. The pathing is worse.";
|
||||
let decision = decided(prose, json!([{ "spans": ["Nibu, I don't think the economy is still the least built part."], "mentions": [], "reply_to": NIBU }]));
|
||||
assert_eq!(texts(&decision), ["Nibu, I don't think the economy is still the least built part."], "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q3d_a_beat_measures_echoes_against_the_tail_it_quoted() {
|
||||
let tail = vec![line(MINDS, LIBBY, "Libby", "the economy is still the least built part of the whole game", false)];
|
||||
let beat = packet_in(TurnKind::Beat, &heimdall(), &Room { tail, here: Some(MINDS.into()), ..Room::default() }, 1);
|
||||
assert!(beat.stimulus.contains("least built") && beat.bodies.iter().any(|body| body.contains("least built")), "{beat:?}");
|
||||
let prose = "The economy is still the least built part of the whole game. I think so.";
|
||||
let decision = decided_in(&beat, prose, json!([{ "spans": ["The economy is still the least built part of the whole game."] }]));
|
||||
assert!(texts(&decision).is_empty() && refused_why(&decision).contains("echo"), "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p4_only_someone_this_packet_showed_her_is_mentioned() {
|
||||
let packet = packet();
|
||||
assert!(!packet.people.iter().any(|(_, id)| id == VOID), "Void said nothing here");
|
||||
let decision = decided("I say hi.", json!([{ "spans": ["I say hi."], "mentions": [VOID, NIBU], "reply_to": VOID }]));
|
||||
assert_eq!((decision["said"][0]["mentions"].clone(), decision["said"][0]["reply_to"].clone()), (json!([NIBU]), Value::Null), "{decision}");
|
||||
assert_eq!(decision["said"][0]["dropped"]["mentions"], json!([VOID]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_p5_the_same_line_is_said_once_and_a_turn_says_at_most_two() {
|
||||
let line = json!({ "spans": ["I say hi."], "mentions": [], "reply_to": null });
|
||||
assert_eq!(texts(&decided("I say hi.", json!([line.clone(), line.clone(), line]))), ["I say hi."]);
|
||||
let prose = "One. Two. Three.";
|
||||
let three = decided(prose, json!([{ "spans": ["One."] }, { "spans": ["Two."] }, { "spans": ["Three."] }]));
|
||||
assert_eq!(texts(&three), ["One.", "Two."], "{three}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recollection_and_i_say_nothing_and_a_quoted_handle_say_nothing() {
|
||||
// A recollection is the Interpreter's to leave out; a piece of a sentence cited anyway is refused.
|
||||
let recalled = decided("Nibu said the economy is still the least built part, and it stuck.", json!([{ "spans": ["the economy is still the least built part"] }]));
|
||||
assert!(texts(&recalled).is_empty(), "{recalled}");
|
||||
assert!(texts(&decided("I say nothing. The quiet is fine.", json!([]))).is_empty());
|
||||
// An @ in her words is text: only the structured field mentions anyone.
|
||||
let handle = decided("\"@nibu, hi.\" I nod at her.", json!([{ "spans": ["@nibu, hi."], "mentions": [] }]));
|
||||
assert_eq!((texts(&handle), handle["said"][0]["mentions"].clone()), (vec!["@nibu, hi.".to_owned()], json!([])), "{handle}");
|
||||
}
|
||||
|
||||
/// Heimdall's state with a private memory about Kiko: she confided she is leaving.
|
||||
fn kiko_confided() -> Value {
|
||||
let mut state = heimdall();
|
||||
state["thoughtMemory"]["memories"] = json!([{ "id": "kiko-secret", "summary": "Kiko confided she is leaving the swarm.", "createdAt": "2026-11-19T00:00:00Z", "updatedAt": "2026-11-19T00:00:00Z", "status": "crystallized", "intensity": 1.0, "target": { "id": "kiko", "kind": "person" }, "tags": ["private"] }]);
|
||||
state
|
||||
}
|
||||
|
||||
/// The first packet over seeds 1 to 60 whose context carries the memory.
|
||||
fn showing(room: &Room) -> Packet {
|
||||
(1..=60).map(|seed| packet_in(TurnKind::Chat, &kiko_confided(), room, seed)).find(|packet| packet.context.contains("leaving the swarm")).expect("the memory is selected on some seed")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5d_what_she_knows_privately_about_kiko_is_listed_to_the_interpreter_in_a_dm_with_libby() {
|
||||
let dm = "!dm-libby:gamecult.org";
|
||||
let room = Room { messages: vec![line(dm, LIBBY, "Libby", "what's up with Kiko lately?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
|
||||
let packet = showing(&room);
|
||||
assert_eq!(packet.room_kind, RoomKind::Direct);
|
||||
assert_eq!(packet.private, ["Kiko confided she is leaving the swarm."], "{packet:?}");
|
||||
let prompt = speech_prompt(&packet, "x", "y");
|
||||
assert!(prompt.contains("What she knows privately, none of it to be said here:\n- private: Kiko confided she is leaving the swarm."), "{prompt}");
|
||||
assert!(prompt.contains("only to the person it concerns, in a direct message with exactly that person"), "{prompt}");
|
||||
// Whether a line tells it is the Interpreter's reading of its meaning: code matches no words, so a line sharing the
|
||||
// item's words is not refused for them (Soul F2: a word match refused 9 of 15 ordinary lines and missed paraphrase).
|
||||
let ordinary = decided_in(&packet, "I'm going to stay on the pipeline work. That's all.", json!([{ "spans": ["I'm going to stay on the pipeline work."] }]));
|
||||
assert_eq!(texts(&ordinary).len(), 1, "{ordinary}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_a_direct_message_with_exactly_kiko_it_is_hers_to_say() {
|
||||
let dm = "!dm-kiko:gamecult.org";
|
||||
let room = Room { messages: vec![line(dm, KIKO, "Kiko", "did you tell anyone?", true)], here: Some(dm.into()), direct: vec![dm.into()], ..Room::default() };
|
||||
let packet = showing(&room);
|
||||
assert!(packet.private.is_empty() && packet.context.contains("- memory [kiko-secret]: Kiko confided"), "{packet:?}");
|
||||
assert!(speech_prompt(&packet, "x", "y").contains("none of it to be said here:\n- none\n"));
|
||||
let decision = decided_in(&packet, "Kiko, you're leaving the swarm and I've told no one. Not a soul.", json!([{ "spans": ["Kiko, you're leaving the swarm and I've told no one."] }]));
|
||||
assert_eq!(texts(&decision).len(), 1, "{decision}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_that_is_not_the_contract_is_a_failure_not_a_silence() {
|
||||
let model = Scripted::new(|_| String::new()).interpreting(|_| "She says hi.".into());
|
||||
let decision = decide(&model, "test", &packet(), "The room is warm.", "I say hi.", &Tuning::default());
|
||||
assert!(decision["failed"].as_str().unwrap().contains("not the speech contract"), "{decision}");
|
||||
let fenced = Scripted::new(|_| String::new()).interpreting(|_| "```json\n{\"say\": []}\n```".into());
|
||||
assert!(decide(&fenced, "test", &packet(), "x", "I say hi.", &Tuning::default()).get("failed").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_is_hugins_chat_prompt_with_the_room_its_kind_and_who_is_in_it() {
|
||||
let packet = packet();
|
||||
assert_eq!((packet.room.as_deref(), packet.room_kind), (Some(MINDS), RoomKind::Public));
|
||||
let prompt = speech_prompt(&packet, "The room is warm.", "I say nothing.");
|
||||
assert!(!prompt.contains("membrane") && prompt.ends_with("I say nothing."), "Huginn's own prompt, her prose last");
|
||||
assert!(prompt.contains("The room: #minds:gamecult.org (a public room).") && prompt.contains(NIBU), "{prompt}");
|
||||
for rule in ["You never write her words", "is not speech", "never her speech", "in a direct message with exactly that person", "She never says half a sentence", "consecutive sentences", "conditional | addressee | elsewhere", "At most two lines"] {
|
||||
assert!(prompt.contains(rule), "{rule}");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
//! The Projector's narration, and the judge that measures it: one tool-less connector call each.
|
||||
//! The Projector's narration, the Persona stage's continuation, and the judge that measures them: one tool-less
|
||||
//! connector call each.
|
||||
//!
|
||||
//! `KitModel` is the stream organ's `KitProjector`, copied here when the stream was parked
|
||||
//! (`persona-only-divergence-parked`), so the Projector has one caller on the connector.
|
||||
|
|
@ -10,7 +11,7 @@ use std::time::Duration;
|
|||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use chrono::Utc;
|
||||
use ghostlight_persona_projection::{ProjectorPrompt, build_projector_prompt};
|
||||
use ghostlight_persona_projection::{PersonaPrompt, ProjectorPrompt, build_persona_prompt, build_projector_prompt};
|
||||
use model_connector::{ConnectorClient, InputItem, ProviderRequest, ReasoningEffort, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome};
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
|
@ -137,7 +138,7 @@ pub(crate) fn word_budget(kind: TurnKind, tuning: &Tuning) -> usize {
|
|||
|
||||
/// The Projector's prompt: Ghostlight's membrane over the packet, with the lens as where to begin.
|
||||
pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String {
|
||||
let guidance = format!("{}\n\nBegin from {}.", tuning.projector.guidance.trim(), packet.lens.words());
|
||||
let guidance = format!("{}\n\nBegin from {}.", tuning.projector.guidance.trim(), packet.lens.words(&packet.forms));
|
||||
build_projector_prompt(&ProjectorPrompt { identity: &packet.identity, typed_context: &packet.context, visible_stimulus: &packet.stimulus, domain_guidance: &guidance, word_budget: word_budget(packet.kind, tuning) })
|
||||
}
|
||||
|
||||
|
|
@ -173,6 +174,46 @@ fn word_starts(text: &str) -> Vec<usize> {
|
|||
/// The share of the budget a sentence cut must keep; below it the word cut keeps more of the stream.
|
||||
const SENTENCE_CUT_FLOOR: f64 = 0.6;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The Persona stage.
|
||||
|
||||
/// What the Persona is shown as her moment: the Projector's narration, then what was said to her and in her room,
|
||||
/// verbatim, as code rendered it (map section 3.2: the Projector never paraphrases what she heard).
|
||||
pub(crate) fn lived_stream(narration: &str, heard: &str) -> String {
|
||||
if heard.trim().is_empty() { narration.to_owned() } else { format!("{narration}\n\n{heard}") }
|
||||
}
|
||||
|
||||
/// The Persona stage's prompt: Ghostlight's prose-only membrane over her identity and her lived stream. No field name,
|
||||
/// number, schema or instruction of hers reaches it (invariant 7); the guidance is the tuning's setting line.
|
||||
pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) -> String {
|
||||
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 })
|
||||
}
|
||||
|
||||
/// 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<String> = text.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_lowercase).collect();
|
||||
words.windows(3).map(|three| (three[0].clone(), three[1].clone(), three[2].clone())).collect()
|
||||
};
|
||||
let told = trigrams(narration);
|
||||
if told.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let heard: BTreeSet<(String, String, String)> = trigrams(heard).into_iter().collect();
|
||||
told.iter().filter(|three| heard.contains(three)).count() as f64 / told.len() as f64
|
||||
}
|
||||
|
||||
/// Whether a narration lays out options for her: "I may…", "I could…", "she might…", "nothing asks me to…". The Projector
|
||||
/// renders the moment and the Persona decides; a menu of choices is the Projector deciding. A lexical flag on a narrow
|
||||
/// form, reported as a metric, never a filter.
|
||||
pub(crate) fn offers_options(narration: &str) -> bool {
|
||||
let lower = format!(" {} ", narration.to_lowercase().replace('\u{2019}', "'"));
|
||||
["i may ", "i could ", "i might ", "she may ", "she could ", "she might ", "nothing asks me", "nothing asks her", "or i could", "or she could"]
|
||||
.iter()
|
||||
.any(|form| lower.contains(&format!(" {form}")) || lower.contains(&format!(". {form}")) || lower.contains(&format!(", {form}")))
|
||||
}
|
||||
|
||||
/// `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
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
//! here; reaching into it is the Interpreter's, through its read tools, when wondering leads to reading.
|
||||
//!
|
||||
//! Every packet carries its fixed slots: identity, the hour, her mood as change, a bond line for each person
|
||||
//! present, and the stimulus. The rest comes from her state's pools. Each candidate is ordered by
|
||||
//! present, the group state (who has been talking to whom, `group_line`), and the stimulus. The rest comes from her state's pools. Each candidate is ordered by
|
||||
//! `log(score) / T` plus Gumbel noise and included with probability `1 - exp(-score / inclusion_score)`, where
|
||||
//! `score = salience × recency × touch × relevance × unresolved × freshness`; then each pool's cap and the context
|
||||
//! budget bound what is kept. A cap is a maximum, never a target: a pool with fewer candidates than its cap still
|
||||
|
|
@ -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 _;
|
||||
|
|
@ -47,8 +47,31 @@ const NAME_BYTES: usize = 80;
|
|||
/// The most bytes the line naming the unbonded people present takes.
|
||||
const ALSO_HERE_BYTES: usize = 300;
|
||||
|
||||
/// Her pronouns as the packet speaks of her (from `presentation.pronouns`: he, she, or they for anything else, "any"
|
||||
/// included), with the verb forms that agree with them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Forms {
|
||||
pub subj: &'static str,
|
||||
pub cap_subj: &'static str,
|
||||
pub obj: &'static str,
|
||||
pub poss: &'static str,
|
||||
pub be: &'static str,
|
||||
pub has: &'static str,
|
||||
/// The present tense's third-person `s`: "wants" or "want".
|
||||
pub s: &'static str,
|
||||
}
|
||||
|
||||
pub(crate) fn forms(state: &Value) -> Forms {
|
||||
let pronouns = text(state, &["presentation", "pronouns"]).to_lowercase();
|
||||
match pronouns.split(|c: char| !c.is_alphabetic()).find(|word| !word.is_empty()).unwrap_or_default() {
|
||||
"he" => Forms { subj: "he", cap_subj: "He", obj: "him", poss: "his", be: "is", has: "has", s: "s" },
|
||||
"she" => Forms { subj: "she", cap_subj: "She", obj: "her", poss: "her", be: "is", has: "has", s: "s" },
|
||||
_ => Forms { subj: "they", cap_subj: "They", obj: "them", poss: "their", be: "are", has: "have", s: "" },
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of turn the packet is for. The stimulus and nothing else differs between them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TurnKind {
|
||||
Chat,
|
||||
|
|
@ -75,6 +98,32 @@ pub(crate) struct Room {
|
|||
pub tail: Vec<RoomLine>,
|
||||
/// The room the turn is in, when it is one room.
|
||||
pub here: Option<String>,
|
||||
/// When she last heard from people, by Matrix id, beyond what the tail shows: a fixture's table (`mind-persona project
|
||||
/// --room`). The live turn has none yet; the tail is its only source.
|
||||
pub last_heard: Vec<(String, u64)>,
|
||||
/// The rooms the mouth called direct messages (a delivery's `is_direct`), by the key the lines carry.
|
||||
pub direct: Vec<String>,
|
||||
/// The rooms that are hers, by key: the caller's (a simulation's plan); the live body records none yet.
|
||||
pub own: Vec<String>,
|
||||
}
|
||||
|
||||
/// Who a room's audience is, for what she may say there: a direct message, a room of her own, or a public room.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum RoomKind {
|
||||
Direct,
|
||||
Own,
|
||||
Public,
|
||||
}
|
||||
|
||||
impl RoomKind {
|
||||
pub(crate) fn words(self) -> &'static str {
|
||||
match self {
|
||||
Self::Direct => "a direct message",
|
||||
Self::Own => "her own room, open to its members",
|
||||
Self::Public => "a public room",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One thing she said, from the trace.
|
||||
|
|
@ -106,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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -143,14 +195,14 @@ pub(crate) enum Lens {
|
|||
}
|
||||
|
||||
impl Lens {
|
||||
/// The lens as the domain guidance's "begin from …".
|
||||
pub(crate) fn words(&self) -> String {
|
||||
/// The lens as the domain guidance's "begin from …", in her pronouns.
|
||||
pub(crate) fn words(&self, forms: &Forms) -> String {
|
||||
match self {
|
||||
Self::BodyAndHour => "how she is, here, at this hour".into(),
|
||||
Self::BodyAndHour => format!("how {} {}, here, at this hour", forms.subj, forms.be),
|
||||
Self::PersonPresent(name) => format!("{name}, who is here"),
|
||||
Self::UnresolvedWant => "something she still wants and has not got".into(),
|
||||
Self::MemorySurfacing => "a memory coming back to her".into(),
|
||||
Self::Wondering => "something she has been wondering about".into(),
|
||||
Self::UnresolvedWant => format!("something {} still want{} and {} not got", forms.subj, forms.s, forms.has),
|
||||
Self::MemorySurfacing => format!("a memory coming back to {}", forms.obj),
|
||||
Self::Wondering => format!("something {} {} been wondering about", forms.subj, forms.has),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -193,6 +245,19 @@ pub(crate) struct Packet {
|
|||
/// Every typed id the packet's lines name: the selected items' and the bonds' of the people present.
|
||||
pub ids: Vec<String>,
|
||||
pub selected: Vec<Pick>,
|
||||
/// Her pronouns, for the words the prompts speak of her in.
|
||||
#[serde(skip)]
|
||||
pub forms: Forms,
|
||||
/// Whom she may mention or reply to: the people this packet showed her from the room, (label, Matrix id).
|
||||
pub people: Vec<(String, String)>,
|
||||
/// The one room she may speak in this turn, and its kind.
|
||||
pub room: Option<String>,
|
||||
pub room_kind: RoomKind,
|
||||
/// The bodies of the lines the stimulus quoted to her this turn, without speakers or rooms: a chat turn's messages,
|
||||
/// a beat's tail lines. What an echo is measured against.
|
||||
pub bodies: Vec<String>,
|
||||
/// The words of each private item this packet shows her as known privately: none of them may be said in this room.
|
||||
pub private: Vec<String>,
|
||||
}
|
||||
|
||||
/// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the
|
||||
|
|
@ -210,6 +275,8 @@ struct Candidate {
|
|||
pool: Pool,
|
||||
line: String,
|
||||
log_score: f64,
|
||||
/// The item's words, when the line shows them as known privately.
|
||||
private: Option<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
|
@ -307,11 +374,12 @@ fn activation(state: &Value, axis: &str) -> Option<f64> {
|
|||
number(state, &["activationProfile", "situationalState", axis, "currentActivation"])
|
||||
}
|
||||
|
||||
/// Mood as change since her last turn; as a level only when there is no last turn to measure from.
|
||||
fn mood_line(state: &Value, previous: Option<&Value>) -> String {
|
||||
/// Mood as change since her last turn; as a level only when there is no last turn to measure from. None when her state
|
||||
/// carries no mood: an absence is left out of the packet, never narrated.
|
||||
fn mood_line(state: &Value, previous: Option<&Value>) -> Option<String> {
|
||||
let now: Vec<(usize, f64)> = MOOD_AXES.iter().enumerate().filter_map(|(at, (axis, ..))| activation(state, axis).map(|value| (at, value))).collect();
|
||||
if now.is_empty() {
|
||||
return "- mood: none recorded".into();
|
||||
return None;
|
||||
}
|
||||
let Some(previous) = previous else {
|
||||
let words: Vec<&str> = now
|
||||
|
|
@ -321,7 +389,7 @@ fn mood_line(state: &Value, previous: Option<&Value>) -> String {
|
|||
if *value >= 0.5 { up } else { down }
|
||||
})
|
||||
.collect();
|
||||
return format!("- mood, with no earlier turn to measure from: {} than middling", words.join(", "));
|
||||
return Some(format!("- mood: {} than middling", words.join(", ")));
|
||||
};
|
||||
let moves: Vec<&str> = now
|
||||
.iter()
|
||||
|
|
@ -335,15 +403,16 @@ fn mood_line(state: &Value, previous: Option<&Value>) -> String {
|
|||
}
|
||||
})
|
||||
.collect();
|
||||
if moves.is_empty() { "- mood: where it was at her last turn".into() } else { format!("- mood: {} than at her last turn", moves.join(", ")) }
|
||||
let poss = forms(state).poss;
|
||||
Some(if moves.is_empty() { format!("- mood: where it was at {poss} last turn") } else { format!("- mood: {} than at {poss} last turn", moves.join(", ")) })
|
||||
}
|
||||
|
||||
fn need_movement(need: &Value, previous: Option<&Value>) -> String {
|
||||
fn need_movement(need: &Value, previous: Option<&Value>, poss: &str) -> String {
|
||||
let intensity = number(need, &["intensity"]).unwrap_or(SALIENCE_UNSTATED);
|
||||
let before = previous.and_then(|previous| items(previous, &["affect", "needs"]).iter().find(|old| text(old, &["id"]) == text(need, &["id"])).and_then(|old| number(old, &["intensity"])));
|
||||
match before.map(|before| intensity - before) {
|
||||
Some(change) if change >= MOVE_MIN => "growing since her last turn".into(),
|
||||
Some(change) if change <= -MOVE_MIN => "easing since her last turn".into(),
|
||||
Some(change) if change >= MOVE_MIN => format!("growing since {poss} last turn"),
|
||||
Some(change) if change <= -MOVE_MIN => format!("easing since {poss} last turn"),
|
||||
Some(_) => "where it was".into(),
|
||||
None => strength_words(intensity).into(),
|
||||
}
|
||||
|
|
@ -352,10 +421,10 @@ fn need_movement(need: &Value, previous: Option<&Value>) -> String {
|
|||
// ---------------------------------------------------------------------------------------------
|
||||
// The seeded draw: splitmix64, so a turn id replays.
|
||||
|
||||
struct Draw(u64);
|
||||
pub(crate) struct Draw(pub(crate) u64);
|
||||
|
||||
impl Draw {
|
||||
fn next(&mut self) -> u64 {
|
||||
pub(crate) fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
|
|
@ -409,81 +478,97 @@ fn recency_log(at: Option<DateTime<Utc>>, now: DateTime<Utc>, tau_h: f64) -> f64
|
|||
at.map_or(0.0, |at| -((now - at).num_seconds().max(0) as f64 / 3600.0) / tau_h)
|
||||
}
|
||||
|
||||
/// The memory's tags name a direct-message room other than the turn's: private matter stays in its room.
|
||||
fn private_elsewhere(item: &Value, here: Option<&str>) -> bool {
|
||||
items(item, &["tags"]).iter().filter_map(Value::as_str).filter_map(|tag| tag.strip_prefix("room:")).any(|room| room.starts_with('!') && Some(room) != here)
|
||||
}
|
||||
|
||||
fn in_room(item: &Value, here: Option<&str>) -> bool {
|
||||
here.is_some_and(|here| items(item, &["tags"]).iter().filter_map(Value::as_str).any(|tag| tag.strip_prefix("room:") == Some(here)))
|
||||
}
|
||||
|
||||
fn about_present(item: &Value, present: &BTreeSet<String>) -> bool {
|
||||
let target = text(item, &["target", "id"]).to_lowercase();
|
||||
present.contains(&target) || items(item, &["tags"]).iter().filter_map(Value::as_str).filter_map(|tag| tag.strip_prefix("about:")).any(|id| present.contains(&id.to_lowercase()))
|
||||
fn about_present(people: &People, item: &Value, present: &BTreeSet<String>) -> bool {
|
||||
let target = people.person_of(text(item, &["target", "id"]));
|
||||
present.contains(&target) || items(item, &["tags"]).iter().filter_map(Value::as_str).filter_map(|tag| tag.strip_prefix("about:")).any(|id| present.contains(&people.person_of(id)))
|
||||
}
|
||||
|
||||
fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet<String>, touching: &BTreeSet<String>) -> Vec<Candidate> {
|
||||
let state = inputs.state;
|
||||
let here = inputs.room.here.as_deref();
|
||||
let item_bytes = tuning.select.item_bytes;
|
||||
let her = forms(state);
|
||||
let mut out = Vec::new();
|
||||
let mut push = |id: &str, pool: Pool, line: String, salience: f64, recency: f64, touch: f64, unresolved: f64| {
|
||||
// Every item passes `scope` here: left out, its words shown as known privately, or as written. `line` renders the
|
||||
// item around its words.
|
||||
let mut push = |id: &str, pool: Pool, scope: Scope, words: &str, line: &dyn Fn(&str) -> String, salience: f64, recency: f64, touch: f64, unresolved: f64| {
|
||||
if id.is_empty() || salience <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let (line, private) = match scope {
|
||||
Scope::Omitted => return,
|
||||
Scope::Framed => (line(&format!("{} knows privately: {words}", her.subj)), Some(one_line(words))),
|
||||
Scope::Plain => (line(words), None),
|
||||
};
|
||||
let log_score = salience.ln() + recency + touch.ln() + unresolved.ln() + freshness_log(id, inputs.history, tuning);
|
||||
out.push(Candidate { id: id.to_owned(), pool, line, log_score });
|
||||
out.push(Candidate { id: id.to_owned(), pool, line, log_score, private });
|
||||
};
|
||||
let scoped = |item: &Value| scope(inputs, concerns(&inputs.people, item).as_ref(), present);
|
||||
|
||||
let crystallized = items(state, &["thoughtMemory", "memories"]).iter().map(|memory| (memory, false));
|
||||
let memories = crystallized.chain(items(state, &["thoughtMemory", "shortTerm"]).iter().map(|memory| (memory, true)));
|
||||
for (memory, short_term) in memories.filter(|(memory, _)| live(memory) && !private_elsewhere(memory, here)) {
|
||||
let about = about_present(memory, present);
|
||||
for (memory, short_term) in memories.filter(|(memory, _)| live(memory)) {
|
||||
let about = about_present(&inputs.people, memory, present);
|
||||
let pool = if about { Pool::MemoriesAboutPresent } else { Pool::OtherMemories };
|
||||
let touch = if about { TOUCH_PRESENT } else if in_room(memory, here) { TOUCH_ROOM } else { TOUCH_ELSE };
|
||||
let mut body = text(memory, &["summary"]).to_owned();
|
||||
let tension = text(memory, &["tension"]);
|
||||
if !tension.is_empty() {
|
||||
body = format!("{body} {tension}");
|
||||
let body = [text(memory, &["summary"]), text(memory, &["tension"])].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" ");
|
||||
if body.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let line = format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(&body), item_bytes));
|
||||
let salience = number(memory, &["intensity"]).unwrap_or(SALIENCE_UNSTATED);
|
||||
// Only the day's short-term items fade; a crystallized memory comes forward by what the room touches.
|
||||
let nearness = if short_term { recency_log(time(memory), inputs.now, tuning.select.memory_tau_h) } else { relevance_log(&body, touching) };
|
||||
push(text(memory, &["id"]), pool, line, salience, nearness, touch, 1.0);
|
||||
let line = |words: &str| format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(words), item_bytes));
|
||||
push(text(memory, &["id"]), pool, scoped(memory), &body, &line, salience, nearness, touch, 1.0);
|
||||
}
|
||||
|
||||
for need in items(state, &["affect", "needs"]).iter().filter(|need| live(need)) {
|
||||
let intensity = number(need, &["intensity"]).unwrap_or(SALIENCE_UNSTATED);
|
||||
let name = [text(need, &["label"]), text(need, &["summary"]), text(need, &["id"])].into_iter().find(|name| !name.is_empty()).unwrap_or_default();
|
||||
let line = format!("- need [{}]: {}, {}", text(need, &["id"]), clip(&one_line(name), item_bytes), need_movement(need, inputs.history.previous.as_ref()));
|
||||
push(text(need, &["id"]), Pool::Needs, line, intensity, 0.0, TOUCH_ELSE, 1.0 + intensity);
|
||||
let Some(name) = [text(need, &["label"]), text(need, &["summary"])].into_iter().find(|name| !name.is_empty()) else { continue };
|
||||
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)) {
|
||||
for wondering in items(state, &["thoughtMemory", "incubation"]).iter().filter(|item| live(item) && !text(item, &["summary"]).is_empty()) {
|
||||
let days = time(wondering).map_or(0.0, |at| (inputs.now - at).num_seconds().max(0) as f64 / 86_400.0);
|
||||
let touch = if about_present(wondering, present) { TOUCH_PRESENT } else { TOUCH_ELSE };
|
||||
let line = format!("- wondering [{}]: {}", text(wondering, &["id"]), clip(&one_line(text(wondering, &["summary"])), item_bytes));
|
||||
push(text(wondering, &["id"]), Pool::Incubation, line, number(wondering, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), 0.0, touch, (1.0 + days / 7.0).min(INCUBATION_UNRESOLVED_MAX));
|
||||
let touch = if about_present(&inputs.people, wondering, present) { TOUCH_PRESENT } else { TOUCH_ELSE };
|
||||
let line = |words: &str| format!("- wondering [{}]: {}", text(wondering, &["id"]), clip(&one_line(words), item_bytes));
|
||||
let unresolved = (1.0 + days / 7.0).min(INCUBATION_UNRESOLVED_MAX);
|
||||
push(text(wondering, &["id"]), Pool::Incubation, scoped(wondering), text(wondering, &["summary"]), &line, number(wondering, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), 0.0, touch, unresolved);
|
||||
}
|
||||
|
||||
for stance in items(state, &["affect", "doctrineStances"]).iter().filter(|stance| live(stance)) {
|
||||
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);
|
||||
for stance in items(state, &["affect", "doctrineStances"]).iter().filter(|stance| live(stance) && !text(stance, &["summary"]).is_empty()) {
|
||||
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"]) {
|
||||
let line = format!("- value [{}] {}: {}", text(value, &["id"]), clip(text(value, &["label"]), NAME_BYTES), clip(&one_line(text(value, &["summary"])), item_bytes));
|
||||
// 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()) {
|
||||
(false, false) => format!("- value [{}] {label}: {summary}", text(value, &["id"])),
|
||||
(false, true) => format!("- value [{}] {label}", text(value, &["id"])),
|
||||
_ => format!("- value [{}]: {summary}", text(value, &["id"])),
|
||||
};
|
||||
let relevance = relevance_log(&format!("{} {}", text(value, &["label"]), text(value, &["summary"])), touching);
|
||||
push(text(value, &["id"]), Pool::Value, line, number(value, &["priority"]).unwrap_or(SALIENCE_UNSTATED), relevance, TOUCH_ELSE, 1.0);
|
||||
push(text(value, &["id"]), Pool::Value, Scope::Plain, &line, &str::to_owned, number(value, &["priority"]).unwrap_or(SALIENCE_UNSTATED), relevance, TOUCH_ELSE, 1.0);
|
||||
}
|
||||
|
||||
for said in &inputs.history.said {
|
||||
let touch = if Some(said.room.as_str()) == here { TOUCH_ROOM } else { TOUCH_ELSE };
|
||||
let line = format!("- she said [{}] in {}: {}", 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
|
||||
}
|
||||
|
|
@ -508,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.
|
||||
|
|
@ -589,10 +674,10 @@ struct Addressed<'a> {
|
|||
}
|
||||
|
||||
impl Addressed<'_> {
|
||||
fn lines(&self, render: impl Fn(&RoomLine, &str) -> String) -> Vec<String> {
|
||||
fn lines(&self, obj: &str, render: impl Fn(&RoomLine, &str) -> String) -> Vec<String> {
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
if self.left_out > 0 {
|
||||
lines.push(format!("({} more said to her, not shown)", self.left_out));
|
||||
lines.push(format!("({} more said to {obj}, not shown)", self.left_out));
|
||||
}
|
||||
lines.extend(self.shown.iter().map(|(line, cut)| match cut {
|
||||
None => render(line, &spoken(&line.text)),
|
||||
|
|
@ -642,12 +727,13 @@ fn chat_stimulus(inputs: &Inputs, tuning: &Tuning) -> (String, String, Overflow)
|
|||
// One selection, rendered twice: the stimulus and the heard lines show the same messages to her and the same count.
|
||||
let addressed = said_to_her(&to_her, typed, ceiling);
|
||||
let (left_out, clipped) = (addressed.left_out, addressed.clipped);
|
||||
let typed_to_her = addressed.lines(typed);
|
||||
let heard_to_her = addressed.lines(heard);
|
||||
let obj = forms(inputs.state).obj;
|
||||
let typed_to_her = addressed.lines(obj, typed);
|
||||
let heard_to_her = addressed.lines(obj, heard);
|
||||
|
||||
let mut stimulus = String::new();
|
||||
if !typed_to_her.is_empty() {
|
||||
stimulus.push_str("Said to her:");
|
||||
stimulus.push_str(&format!("Said to {obj}:"));
|
||||
for line in &typed_to_her {
|
||||
stimulus.push('\n');
|
||||
stimulus.push_str(line);
|
||||
|
|
@ -709,17 +795,19 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
|
|||
let cap = tuning.select.stimulus_bytes;
|
||||
let mut contacts: Vec<(Option<u64>, String)> = Vec::new();
|
||||
for bond in items(inputs.state, &["affect", "socialBonds"]).iter().filter(|bond| live(bond) && text(bond, &["object", "kind"]) == "person") {
|
||||
let person = text(bond, &["object", "id"]).to_lowercase();
|
||||
let person = inputs.people.person_of(text(bond, &["object", "id"]));
|
||||
let label = clip(&one_line([text(bond, &["object", "label"]), text(bond, &["object", "id"])].into_iter().find(|name| !name.is_empty()).unwrap_or_default()), NAME_BYTES);
|
||||
let last = inputs.room.tail.iter().filter(|line| inputs.people.person_of(&line.sender) == person).map(|line| line.at_ms).max();
|
||||
let heard = inputs.room.tail.iter().map(|line| (line.sender.as_str(), line.at_ms)).chain(inputs.room.last_heard.iter().map(|(sender, at)| (sender.as_str(), *at)));
|
||||
let last = heard.filter(|(sender, _)| inputs.people.person_of(sender) == person).map(|(_, at)| at).max();
|
||||
contacts.push((last, match last {
|
||||
Some(at) => format!("- last heard from {label} {} h ago", hours(inputs.now, at)),
|
||||
None => format!("- nothing from {label} in her rooms lately"),
|
||||
None => format!("- nothing from {label} in {} rooms lately", forms(inputs.state).poss),
|
||||
}));
|
||||
}
|
||||
contacts.sort_by_key(|(last, _)| std::cmp::Reverse(*last));
|
||||
let mut out = Lines::new(cap);
|
||||
out.push("Nothing addressed her.");
|
||||
let her = forms(inputs.state);
|
||||
out.push(&format!("Nothing addressed {}.", her.obj));
|
||||
let note_room = 48;
|
||||
let contact_cap = cap * 2 / 3;
|
||||
let mut left_out = 0;
|
||||
|
|
@ -729,22 +817,27 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
|
|||
}
|
||||
}
|
||||
if left_out > 0 {
|
||||
out.push(&format!("({left_out} more people she is bound to not shown)"));
|
||||
out.push(&format!("({left_out} more people {} {} bound to not shown)", her.subj, her.be));
|
||||
}
|
||||
let others: Vec<&RoomLine> = inputs.room.tail.iter().filter(|line| line.sender != inputs.people.own_sender).collect();
|
||||
let shown = &others[others.len().saturating_sub(tuning.select.beat_tail_lines)..];
|
||||
let lines: Vec<String> = shown.iter().map(|line| format!("- {} in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&clip(&line.text, tuning.select.item_bytes / 2)))).collect();
|
||||
let section = newest_section("Lately in her rooms:", &lines, cap.saturating_sub(out.out.len() + 2));
|
||||
let lines: Vec<String> = beat_tail(inputs, tuning).iter().map(|line| format!("- {} in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&clip(&line.text, tuning.select.item_bytes / 2)))).collect();
|
||||
let section = newest_section(&format!("Lately in {} rooms:", her.poss), &lines, cap.saturating_sub(out.out.len() + 2));
|
||||
if !section.is_empty() && out.push("") {
|
||||
out.push(§ion);
|
||||
}
|
||||
out.out
|
||||
}
|
||||
|
||||
/// The tail lines a beat's stimulus quotes: the newest `beat_tail_lines` of others'.
|
||||
fn beat_tail<'a>(inputs: &'a Inputs, tuning: &Tuning) -> Vec<&'a RoomLine> {
|
||||
let others: Vec<&RoomLine> = inputs.room.tail.iter().filter(|line| line.sender != inputs.people.own_sender).collect();
|
||||
others[others.len().saturating_sub(tuning.select.beat_tail_lines)..].to_vec()
|
||||
}
|
||||
|
||||
fn reflection_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
|
||||
let lines: Vec<String> = items(inputs.state, &["thoughtMemory", "shortTerm"]).iter().filter(|item| live(item)).map(|item| format!("- {}", clip(&one_line(text(item, &["summary"])), tuning.select.item_bytes))).collect();
|
||||
let section = newest_section("Since she last took stock:", &lines, tuning.select.stimulus_bytes);
|
||||
if section.is_empty() { clip("Since she last took stock: nothing new.", tuning.select.stimulus_bytes) } else { section }
|
||||
let subj = forms(inputs.state).subj;
|
||||
let section = newest_section(&format!("Since {subj} last took stock:"), &lines, tuning.select.stimulus_bytes);
|
||||
if section.is_empty() { clip(&format!("Since {subj} last took stock: nothing new."), tuning.select.stimulus_bytes) } else { section }
|
||||
}
|
||||
|
||||
/// The people present, newest first: who spoke to her or in her room this turn, or in the beat's lines.
|
||||
|
|
@ -767,14 +860,35 @@ fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> {
|
|||
out
|
||||
}
|
||||
|
||||
fn bond_line(bond: &Value, name: &str, tuning: &Tuning) -> String {
|
||||
let mut feel = vec![friction_words(number(bond, &["tension"]).unwrap_or(0.0))];
|
||||
if let Some(trust) = number(bond, &["trust"]) {
|
||||
feel.insert(0, trust_words(trust));
|
||||
/// 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, 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);
|
||||
let mut line = format!("- bond [{}] {name}", text(bond, &["id"]));
|
||||
if !kind.is_empty() {
|
||||
let _ = write!(line, " \u{2014} {kind}");
|
||||
}
|
||||
let kind = clip(&one_line(text(bond, &["relationshipKind"])), NAME_BYTES);
|
||||
let kind = if kind.is_empty() { String::new() } else { format!(", {kind}") };
|
||||
format!("- bond [{}] {name}{kind}: {}. {}", text(bond, &["id"]), feel.join(", "), clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes))
|
||||
let summary = clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes);
|
||||
let summary = match scope {
|
||||
Scope::Framed if !summary.is_empty() => format!("{} knows privately: {summary}", her.cap_subj),
|
||||
Scope::Omitted => String::new(),
|
||||
_ => summary,
|
||||
};
|
||||
match (feel.is_empty(), summary.is_empty()) {
|
||||
(true, true) => {}
|
||||
(true, false) => {
|
||||
let _ = write!(line, ": {summary}");
|
||||
}
|
||||
(false, true) => {
|
||||
let _ = write!(line, ": {}.", feel.join(", "));
|
||||
}
|
||||
(false, false) => {
|
||||
let _ = write!(line, ": {}. {summary}", feel.join(", "));
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
fn identity_of(state: &Value, tuning: &Tuning) -> String {
|
||||
|
|
@ -799,17 +913,265 @@ fn also_here(named: &[String]) -> Option<String> {
|
|||
break;
|
||||
}
|
||||
if shown > 0 {
|
||||
line.push_str(", ");
|
||||
line.push_str("; ");
|
||||
}
|
||||
line.push_str(name);
|
||||
shown += 1;
|
||||
}
|
||||
if shown < named.len() {
|
||||
let _ = write!(line, "{}{} more", if shown > 0 { ", and " } else { "" }, named.len() - shown);
|
||||
let _ = write!(line, "{}{} more", if shown > 0 { "; and " } else { "" }, named.len() - shown);
|
||||
}
|
||||
Some(line)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The group state: what the room's recent lines say about who is talking to whom.
|
||||
|
||||
/// Whether a sender is a Mind of the swarm (she is one); anyone else is a human.
|
||||
fn is_mind(inputs: &Inputs, sender: &str) -> bool {
|
||||
sender == inputs.people.own_sender || inputs.people.minds.iter().any(|mind| mind == sender)
|
||||
}
|
||||
|
||||
/// The label her bond with a sender gives them, when she has a live one.
|
||||
fn bond_label(inputs: &Inputs, sender: &str) -> Option<String> {
|
||||
let person = inputs.people.person_of(sender);
|
||||
items(inputs.state, &["affect", "socialBonds"]).iter().find(|bond| live(bond) && 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.
|
||||
fn names_of(line: &RoomLine, inputs: &Inputs) -> Vec<String> {
|
||||
[Some(localpart(&line.sender).to_owned()), Some(line.display.trim().to_owned()), bond_label(inputs, &line.sender)].into_iter().flatten().filter(|name| !name.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// The recent lines of one room, the one the group state and the pronouns describe: messages and tail together, each
|
||||
/// 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.
|
||||
/// 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());
|
||||
inputs.room.here.as_deref().or_else(|| newest(&inputs.room.messages, &|line| line.to_her)).or_else(|| newest(&inputs.room.messages, &|_| true)).or_else(|| newest(&inputs.room.tail, &|_| true))
|
||||
}
|
||||
|
||||
fn room_kind(inputs: &Inputs, room: &str) -> RoomKind {
|
||||
if direct(inputs, room) {
|
||||
RoomKind::Direct
|
||||
} else if inputs.room.own.iter().any(|own| own == room) {
|
||||
RoomKind::Own
|
||||
} else {
|
||||
RoomKind::Public
|
||||
}
|
||||
}
|
||||
|
||||
fn recent_lines<'a>(inputs: &'a Inputs) -> Vec<&'a RoomLine> {
|
||||
let Some(room) = turn_room(inputs) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut lines: Vec<&RoomLine> = Vec::new();
|
||||
for line in inputs.room.messages.iter().chain(&inputs.room.tail) {
|
||||
if line.room != room || lines.iter().any(|seen| seen.sender == line.sender && seen.at_ms == line.at_ms && seen.text == line.text) {
|
||||
continue;
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
lines.sort_by_key(|line| line.at_ms);
|
||||
lines
|
||||
}
|
||||
|
||||
/// How a sender reads in the group-state and pronoun lines: her own pronoun for her; otherwise as every line names a
|
||||
/// sender (`name_of`): the bond's label, else the display name with the full Matrix id, else the id. Never a bare handle,
|
||||
/// which a stranger could share with a Mind of the swarm.
|
||||
fn label_of(line: &RoomLine, inputs: &Inputs) -> String {
|
||||
if line.sender == inputs.people.own_sender { forms(inputs.state).subj.to_owned() } else { name_of(line, inputs) }
|
||||
}
|
||||
|
||||
/// The group-state slot (`select.group_state`): the conversation as it stands over the room's last `group_lines` lines.
|
||||
/// Who has been talking with whom; a human's question to the room that others have answered, as covered (one nobody
|
||||
/// answered is not mentioned); when a human last spoke; how many Mind lines in a row; and a human waiting on her by name
|
||||
/// since she last spoke. Never what she owes: the room's state, not her duty. Whom a line is to is read from the names in
|
||||
/// it and Matrix's word, a cue the Interpreter (C3b) will replace. None when the room shows no line.
|
||||
fn group_line(inputs: &Inputs, tuning: &Tuning) -> Option<String> {
|
||||
let lines = recent_lines(inputs);
|
||||
if lines.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let own = inputs.people.own_sender;
|
||||
let names_her = |line: &RoomLine| line.sender != own && (line.to_her || [localpart(own), text(inputs.state, &["publicName"])].iter().any(|name| crate::address::names_whole_word(&line.text, name, false)));
|
||||
// Everything the line says is over these lines: its last `group_lines`.
|
||||
let window = &lines[lines.len().saturating_sub(tuning.select.group_lines)..];
|
||||
let named_in = |line: &RoomLine| window.iter().filter(|other| other.sender != line.sender).find(|other| names_of(other, inputs).iter().any(|name| crate::address::names_whole_word(&line.text, name, false))).copied();
|
||||
// A human's last line, when it is a question to the room (no one named), and who has answered it since.
|
||||
let question = window.iter().rposition(|line| !is_mind(inputs, &line.sender)).filter(|at| {
|
||||
let line = window[*at];
|
||||
line.text.trim_end().ends_with('?') && !names_her(line) && named_in(line).is_none()
|
||||
});
|
||||
let mut answered: Vec<String> = Vec::new();
|
||||
let mut talk: Vec<String> = Vec::new();
|
||||
for (at, line) in window.iter().enumerate() {
|
||||
let speaker = label_of(line, inputs);
|
||||
let target = if names_her(line) { Some(forms(inputs.state).obj.to_owned()) } else { named_in(line).map(|other| label_of(other, inputs)) };
|
||||
let answers = question.is_some_and(|asked| at > asked && line.sender != window[asked].sender && target.as_ref().is_none_or(|target| *target == label_of(window[asked], inputs)));
|
||||
if answers {
|
||||
if !answered.contains(&speaker) {
|
||||
answered.push(speaker);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if question == Some(at) {
|
||||
continue;
|
||||
}
|
||||
let pair = match target {
|
||||
Some(target) => format!("{speaker} with {target}"),
|
||||
None => format!("{speaker} to the room"),
|
||||
};
|
||||
if !talk.contains(&pair) {
|
||||
talk.push(pair);
|
||||
}
|
||||
}
|
||||
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()
|
||||
{
|
||||
parts.push(format!("{} asked the room a question, and {} answered it", label_of(window[asked], inputs), answered.join("; ")));
|
||||
}
|
||||
if !talk.is_empty() {
|
||||
parts.push(format!("lately {}", talk.join("; ")));
|
||||
}
|
||||
if let Some(line) = window.iter().rev().find(|line| !is_mind(inputs, &line.sender)) {
|
||||
parts.push(format!("{} last spoke {} min ago", label_of(line, inputs), minutes(inputs.now, line.at_ms)));
|
||||
}
|
||||
let minds_in_a_row = window.iter().rev().take_while(|line| is_mind(inputs, &line.sender)).count();
|
||||
if minds_in_a_row >= 2 {
|
||||
parts.push(format!("the last {minds_in_a_row} lines are the Minds' alone"));
|
||||
}
|
||||
// Each part a sentence of its own: the lists inside a part use semicolons, and a label may hold a comma.
|
||||
let sentences: Vec<String> = 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.
|
||||
/// 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 || people.iter().any(|(_, id)| *id == line.sender) {
|
||||
continue;
|
||||
}
|
||||
people.push((label_of(line, inputs), line.sender.clone()));
|
||||
}
|
||||
people
|
||||
}
|
||||
|
||||
fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option<String> {
|
||||
let parts: Vec<String> = 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))
|
||||
}
|
||||
|
||||
/// How an item's content reaches the packet.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Scope {
|
||||
/// As it is: shared, or private and this is the room where it may be said.
|
||||
Plain,
|
||||
/// "She knows privately: …": private, about someone who is not in the turn's room.
|
||||
Framed,
|
||||
/// Left out: private, and whom it concerns is in the room, or cannot be told apart from who is. Nothing private about
|
||||
/// a person is hinted at to their face.
|
||||
Omitted,
|
||||
}
|
||||
|
||||
/// Whom a private item concerns.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Concerns {
|
||||
/// One person, keyed as her bonds key people.
|
||||
Person(String),
|
||||
/// The other member of the direct message a `room:!…` tag (or her line's room) names, when no person is named.
|
||||
Partner(String),
|
||||
/// No person named: private about everyone.
|
||||
Everyone,
|
||||
}
|
||||
|
||||
/// Whether an item is private, and whom it concerns: the one owner of that reading, for the bonds and every pool. Private
|
||||
/// is `extensions.privacy` "private", a `private` tag, or a tag naming a direct message (`room:!…`); anything else is
|
||||
/// shared (None). It concerns the person its `target` (a bond's `object`) names when that is a person, else the person
|
||||
/// an `about:` tag names, else the partner of the direct message its room tag names, else everyone. The convention is
|
||||
/// the Persona State Standard's, read without a schema change.
|
||||
fn concerns(people: &People, item: &Value) -> Option<Concerns> {
|
||||
let tags: Vec<&str> = items(item, &["tags"]).iter().filter_map(Value::as_str).collect();
|
||||
let direct = tags.iter().filter_map(|tag| tag.strip_prefix("room:")).find(|room| room.starts_with('!'));
|
||||
if text(item, &["extensions", "privacy"]) != "private" && !tags.contains(&"private") && direct.is_none() {
|
||||
return None;
|
||||
}
|
||||
let named = ["target", "object"].into_iter().find(|key| text(item, &[*key, "kind"]) == "person").map(|key| people.person_of(text(item, &[key, "id"])));
|
||||
let about = || tags.iter().find_map(|tag| tag.strip_prefix("about:")).map(|id| people.person_of(id));
|
||||
Some(match (named.filter(|id| !id.is_empty()).or_else(about).filter(|id| !id.is_empty()), direct) {
|
||||
(Some(person), _) => Concerns::Person(person),
|
||||
(None, Some(room)) => Concerns::Partner(room.to_owned()),
|
||||
(None, None) => Concerns::Everyone,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a room is a direct message: the mouth said so, or it is keyed by a room id, as only a direct message is.
|
||||
fn direct(inputs: &Inputs, room: &str) -> bool {
|
||||
room.starts_with('!') || inputs.room.direct.iter().any(|direct| direct == room)
|
||||
}
|
||||
|
||||
/// Everyone a room's lines show in it but her, keyed as her bonds key people. Matrix tells her body no membership, so a
|
||||
/// member who never spoke in the lines she has is not counted.
|
||||
fn members(inputs: &Inputs, room: &str) -> BTreeSet<String> {
|
||||
inputs.room.messages.iter().chain(&inputs.room.tail).filter(|line| line.room == room && line.sender != inputs.people.own_sender).map(|line| inputs.people.person_of(&line.sender)).collect()
|
||||
}
|
||||
|
||||
/// How an item reaches the packet here, by whom it concerns (`concerns`; None is shared, and plain). Plain only where it
|
||||
/// may be said: about one person, in a direct message with exactly her and that person; about a direct message's
|
||||
/// partner, in that direct message, still only the two of them; about everyone, in a room of her own. Elsewhere it is
|
||||
/// left out when whom it concerns is in the room (everyone always is, and a partner unnamed cannot be told apart), and
|
||||
/// framed as known privately when they are not. Structural: whether a line fits its audience stays the Interpreter's
|
||||
/// judgement.
|
||||
fn scope(inputs: &Inputs, concerns: Option<&Concerns>, present: &BTreeSet<String>) -> Scope {
|
||||
let Some(concerns) = concerns else {
|
||||
return Scope::Plain;
|
||||
};
|
||||
let room = turn_room(inputs);
|
||||
let members = room.map(|room| members(inputs, room)).unwrap_or_default();
|
||||
// The one other person of a direct message that has exactly two members.
|
||||
let with = room.filter(|room| room_kind(inputs, room) == RoomKind::Direct && members.len() == 1).and_then(|_| members.first());
|
||||
match concerns {
|
||||
Concerns::Person(person) if with == Some(person) => Scope::Plain,
|
||||
Concerns::Person(person) if present.contains(person) || members.contains(person) => Scope::Omitted,
|
||||
Concerns::Person(_) => Scope::Framed,
|
||||
Concerns::Partner(dm) if with.is_some() && room == Some(dm.as_str()) => Scope::Plain,
|
||||
Concerns::Everyone if room.is_some_and(|room| room_kind(inputs, room) == RoomKind::Own) => Scope::Plain,
|
||||
Concerns::Partner(_) | Concerns::Everyone => Scope::Omitted,
|
||||
}
|
||||
}
|
||||
|
||||
/// A part as a sentence: its first letter upper-cased, a full stop after it.
|
||||
fn sentence(part: &str) -> String {
|
||||
let mut chars = part.chars();
|
||||
chars.next().map_or_else(String::new, |first| format!("{}{}.", first.to_uppercase(), chars.as_str()))
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// The pronouns of a person nobody listed.
|
||||
const UNKNOWN_PRONOUNS: &str = "they/them";
|
||||
|
||||
fn minutes(now: DateTime<Utc>, at_ms: u64) -> i64 {
|
||||
let at = i64::try_from(at_ms).ok().and_then(DateTime::<Utc>::from_timestamp_millis).unwrap_or(now);
|
||||
(now - at).num_minutes().max(0)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The packet.
|
||||
|
||||
|
|
@ -819,7 +1181,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
|
|||
let (stimulus, heard, overflow) = match inputs.kind {
|
||||
TurnKind::Chat => chat_stimulus(inputs, tuning),
|
||||
TurnKind::Beat => (beat_stimulus(inputs, tuning), String::new(), Overflow::default()),
|
||||
TurnKind::FollowUp => (clip(&format!("She just found: {}", inputs.observation.unwrap_or("nothing")), tuning.select.stimulus_bytes), String::new(), Overflow::default()),
|
||||
TurnKind::FollowUp => (clip(&format!("{} just found: {}", forms(inputs.state).cap_subj, inputs.observation.unwrap_or("nothing")), tuning.select.stimulus_bytes), String::new(), Overflow::default()),
|
||||
TurnKind::Reflection => (reflection_stimulus(inputs, tuning), String::new(), Overflow::default()),
|
||||
};
|
||||
|
||||
|
|
@ -829,20 +1191,25 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
|
|||
let present = present_people(inputs, tuning);
|
||||
let present_ids: BTreeSet<String> = present.iter().map(|(id, _)| id.clone()).collect();
|
||||
let bonds = items(inputs.state, &["affect", "socialBonds"]);
|
||||
let mut fixed = vec![format!("- now: {}", inputs.now.format("%A %-d %B, %H:%M UTC")), mood_line(inputs.state, inputs.history.previous.as_ref())];
|
||||
let mut fixed: Vec<String> = [Some(format!("- now: {}", inputs.now.format("%A %-d %B, %H:%M UTC"))), mood_line(inputs.state, inputs.history.previous.as_ref())].into_iter().flatten().collect();
|
||||
let mut used: usize = fixed.iter().map(|line| line.len() + 1).sum();
|
||||
let mut ids = Vec::new();
|
||||
let mut named = Vec::new();
|
||||
let mut private = Vec::new();
|
||||
let mut full = 0;
|
||||
for (id, name) in &present {
|
||||
match bonds.iter().find(|bond| live(bond) && text(bond, &["object", "id"]).to_lowercase() == *id) {
|
||||
match bonds.iter().find(|bond| live(bond) && inputs.people.person_of(text(bond, &["object", "id"])) == *id) {
|
||||
Some(bond) if full < tuning.select.people_full => {
|
||||
let line = bond_line(bond, name, tuning);
|
||||
let scope = scope(inputs, concerns(&inputs.people, bond).as_ref(), &present_ids);
|
||||
let line = bond_line(bond, name, tuning, scope, forms(inputs.state));
|
||||
if used + line.len() < budget {
|
||||
full += 1;
|
||||
used += line.len() + 1;
|
||||
ids.push(text(bond, &["id"]).to_owned());
|
||||
fixed.push(line);
|
||||
if scope == Scope::Framed && !text(bond, &["summary"]).is_empty() {
|
||||
private.push(one_line(text(bond, &["summary"])));
|
||||
}
|
||||
} else {
|
||||
named.push(name.clone());
|
||||
}
|
||||
|
|
@ -854,6 +1221,16 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
|
|||
used += line.len() + 1;
|
||||
fixed.push(line);
|
||||
}
|
||||
if tuning.select.group_state
|
||||
&& let Some(line) = group_line(inputs, tuning).filter(|line| used + line.len() < budget)
|
||||
{
|
||||
used += line.len() + 1;
|
||||
fixed.push(line);
|
||||
}
|
||||
if let Some(line) = pronoun_line(inputs, tuning).filter(|line| used + line.len() < budget) {
|
||||
used += line.len() + 1;
|
||||
fixed.push(line);
|
||||
}
|
||||
|
||||
// What the room is touching: the content words of what was said there, and of a follow-up's finding.
|
||||
let touching: BTreeSet<String> = inputs.room.messages.iter().chain(&inputs.room.tail).map(|line| line.text.as_str()).chain(inputs.observation).flat_map(content_words).collect();
|
||||
|
|
@ -889,6 +1266,12 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
|
|||
let mut lines = fixed;
|
||||
lines.extend(taken.iter().map(|candidate| candidate.line.clone()));
|
||||
ids.extend(taken.iter().map(|candidate| candidate.id.clone()));
|
||||
private.extend(taken.iter().filter_map(|candidate| candidate.private.clone()));
|
||||
let bodies = match inputs.kind {
|
||||
TurnKind::Chat => inputs.room.messages.iter().map(|line| line.text.clone()).collect(),
|
||||
TurnKind::Beat => beat_tail(inputs, tuning).iter().map(|line| line.text.clone()).collect(),
|
||||
TurnKind::FollowUp | TurnKind::Reflection => Vec::new(),
|
||||
};
|
||||
let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect();
|
||||
Packet { kind: inputs.kind, seed: inputs.seed, lens, identity, context: lines.join("\n"), stimulus, heard, overflow, present: present_names, ids, selected }
|
||||
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 }
|
||||
}
|
||||
|
|
|
|||
699
crates/mind-body/src/projection/simulate.rs
Normal file
699
crates/mind-body/src/projection/simulate.rs
Normal file
|
|
@ -0,0 +1,699 @@
|
|||
//! The swarm in one simulated room (`mind-persona project --simulate <plan>`): up to eight personas take turns, each turn
|
||||
//! one `project` through the Persona stage, and each one's quoted lines join the room as from her Matrix id, so the
|
||||
//! next one hears them.
|
||||
//!
|
||||
//! 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`. 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
|
||||
//! until then either: a spoken line addresses another persona only by the names in its text.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
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};
|
||||
use crate::address::{Addressee, is_for, localpart};
|
||||
use crate::chat_client::ChatPending;
|
||||
use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, FileStore, HeartbeatView, LineFacts, Speaker, WakeCause, WakePolicy, addressed_by_member, wakes};
|
||||
use crate::tempo::{Standing, pick};
|
||||
|
||||
/// The most personas a simulation holds: the swarm.
|
||||
const CAST_MAX: usize = 8;
|
||||
/// How many transcript lines the report quotes as representative.
|
||||
const REPRESENTATIVE_LINES: usize = 18;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SimFile {
|
||||
rounds: usize,
|
||||
#[serde(default = "one")]
|
||||
repeats: usize,
|
||||
#[serde(default)]
|
||||
seed: u64,
|
||||
#[serde(default = "ruled")]
|
||||
wake: WakePolicy,
|
||||
/// The heartbeat's beat, in seconds of simulated time; 0 is no beat.
|
||||
#[serde(default = "beat_s")]
|
||||
beat_s: u32,
|
||||
#[serde(default = "two")]
|
||||
round_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<Utc>,
|
||||
rooms: Vec<String>,
|
||||
#[serde(default)]
|
||||
operators: Vec<String>,
|
||||
/// The heartbeat's store (`heartbeat.cc`), read without a lock or a write, for its addressing table: each persona's
|
||||
/// names and her stewarded projects' names. None addresses each by her own names.
|
||||
#[serde(default)]
|
||||
addressing: Option<PathBuf>,
|
||||
cast: Vec<CastEntry>,
|
||||
#[serde(default, rename = "message")]
|
||||
script: Vec<Message>,
|
||||
}
|
||||
|
||||
fn one() -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
fn two() -> i64 {
|
||||
2
|
||||
}
|
||||
|
||||
fn exchange_minutes() -> i64 {
|
||||
30
|
||||
}
|
||||
|
||||
fn ruled() -> WakePolicy {
|
||||
WakePolicy::Ruled
|
||||
}
|
||||
|
||||
fn beat_s() -> u32 {
|
||||
DEFAULT_BEAT_S
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CastEntry {
|
||||
id: String,
|
||||
name: String,
|
||||
/// Her persona state, relative to the plan; its `personaId` is her id's localpart.
|
||||
state: PathBuf,
|
||||
/// Her rooms; none is every room of the plan.
|
||||
#[serde(default)]
|
||||
rooms: Vec<String>,
|
||||
/// The rooms that are hers, where any human line wakes her under `humans_pace`. Neither the heartbeat's table nor
|
||||
/// `persona.env` records which rooms a Mind owns, so the plan says; a direct message is always hers.
|
||||
#[serde(default)]
|
||||
own_rooms: Vec<String>,
|
||||
}
|
||||
|
||||
struct Member {
|
||||
entry: CastEntry,
|
||||
state: Value,
|
||||
addressee: Addressee,
|
||||
/// Where her addressee came from: the heartbeat's table, or her own names.
|
||||
names_from: &'static str,
|
||||
rooms: Vec<String>,
|
||||
}
|
||||
|
||||
/// Per room, how many lines she had seen when a turn of hers last read it: a line at or past that is new to her.
|
||||
type Seen = BTreeMap<String, usize>;
|
||||
|
||||
fn unseen(seen: &Seen, lines: &[Line], at: usize) -> bool {
|
||||
at >= seen.get(&lines[at].room).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// One persona's view of the room at her turn: the lines she has not seen are new.
|
||||
struct View<'a> {
|
||||
lines: &'a [Line],
|
||||
viewer: &'a str,
|
||||
rooms: &'a [String],
|
||||
seen: &'a Seen,
|
||||
}
|
||||
|
||||
impl MouthReader for View<'_> {
|
||||
fn pending(&self) -> Result<ChatPending> {
|
||||
Ok(pending_for(self.lines, self.viewer, self.rooms, |at| unseen(self.seen, self.lines, at)))
|
||||
}
|
||||
}
|
||||
|
||||
struct Names<'a>(&'a Addressee);
|
||||
|
||||
impl HeartbeatView for Names<'_> {
|
||||
fn addressing(&self) -> Result<Option<Addressing>> {
|
||||
Ok(Some(Addressing { minds: vec![self.0.clone()] }))
|
||||
}
|
||||
}
|
||||
|
||||
/// The seam where the Interpreter (C3b) will turn her prose into proposals and the commit (C3c) will apply them, so her
|
||||
/// next turn starts from the state this one left. Until they exist it returns her state unchanged.
|
||||
fn state_after_turn(state: Value, _turn: &Value) -> Value {
|
||||
state
|
||||
}
|
||||
|
||||
fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String]) -> Speaker {
|
||||
if line.from == member.entry.id {
|
||||
Speaker::Her
|
||||
} else if operators.contains(&line.from) {
|
||||
Speaker::Operator
|
||||
} else if cast.contains(&line.from) {
|
||||
Speaker::Mind
|
||||
} else {
|
||||
Speaker::Member
|
||||
}
|
||||
}
|
||||
|
||||
/// For each line, how many Mind lines in a row came before it in her current Mind-only run: one run across every room
|
||||
/// she sees, which a human's line ends only when it is in a room the run has lines in. Meta chatting in #eureka does not
|
||||
/// end a loop in #minds.
|
||||
fn mind_runs(lines: &[Line], cast: &[String], member: &Member) -> Vec<usize> {
|
||||
let mut run = 0usize;
|
||||
let mut run_rooms: Vec<&str> = Vec::new();
|
||||
lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
let before = run;
|
||||
if line.visible_to(&member.entry.id, &member.rooms) {
|
||||
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
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How a Mind's line addressed her, by the evidence `is_for` had, strongest first: a Matrix tag or a reply to her, her
|
||||
/// Matrix id written as plain text, or one of her names in the text.
|
||||
fn how_addressed(line: &Line, at: usize, member: &Member, lines: &[Line]) -> &'static str {
|
||||
let delivery = line.delivery(at, &member.entry.id, lines);
|
||||
if delivery.mentions.contains(&member.entry.id) || delivery.basis.is_some() {
|
||||
"mention or reply"
|
||||
} else if line.says.to_lowercase().contains(&member.entry.id.to_lowercase()) {
|
||||
"id as text"
|
||||
} else {
|
||||
"name in text"
|
||||
}
|
||||
}
|
||||
|
||||
/// One wake: why (the strongest cause among her new lines, under the plan's policy) and, when only Minds' lines caused
|
||||
/// it, the strongest evidence that addressed her and the lines that did.
|
||||
struct Woken {
|
||||
cause: WakeCause,
|
||||
/// The newest line with that cause: its room is the turn's room.
|
||||
line: usize,
|
||||
how: Option<&'static str>,
|
||||
by: Vec<Value>,
|
||||
}
|
||||
|
||||
/// Whether she is in the exchange a line belongs to: she spoke in its room within `window` before it.
|
||||
fn in_exchange(lines: &[Line], at: usize, her: &str, window: Duration) -> bool {
|
||||
let line = &lines[at];
|
||||
let since = line.at_ms.saturating_sub(u64::try_from(window.num_milliseconds()).unwrap_or(0));
|
||||
lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.from == her && earlier.at_ms >= since)
|
||||
}
|
||||
|
||||
/// Her wake, if a line she has not seen wakes her: in the room of the earliest such line, with the strongest cause among
|
||||
/// that room's waking lines.
|
||||
#[allow(clippy::too_many_arguments, reason = "one wake decision's inputs, each a plan or room fact")]
|
||||
fn woken(lines: &[Line], runs: &[usize], seen: &Seen, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Option<Woken> {
|
||||
let mut found: Vec<(usize, WakeCause)> = Vec::new();
|
||||
for (at, line) in lines.iter().enumerate() {
|
||||
if !unseen(seen, lines, at) || !line.visible_to(&member.entry.id, &member.rooms) {
|
||||
continue;
|
||||
}
|
||||
let delivery = line.delivery(at, &member.entry.id, lines);
|
||||
let facts = LineFacts { mind_run: runs[at], own_room: member.entry.own_rooms.contains(&line.room), in_exchange: in_exchange(lines, at, &member.entry.id, gap) };
|
||||
if let Some(cause) = wakes(policy, &member.addressee, &delivery, speaker(line, member, operators, cast), facts) {
|
||||
found.push((at, cause));
|
||||
}
|
||||
}
|
||||
let room = &lines[found.first()?.0].room;
|
||||
found.retain(|(at, _)| lines[*at].room == *room);
|
||||
let cause = found.iter().map(|(_, cause)| *cause).min()?;
|
||||
let line = found.iter().rev().find(|(_, found)| *found == cause).map_or(0, |(at, _)| *at);
|
||||
if cause != WakeCause::AddressedByMind {
|
||||
return Some(Woken { cause, line, how: None, by: vec![] });
|
||||
}
|
||||
let addressing: Vec<usize> = found.iter().filter(|(_, cause)| *cause == WakeCause::AddressedByMind).map(|(at, _)| *at).collect();
|
||||
let rank = |how: &str| ["mention or reply", "id as text", "name in text"].iter().position(|one| *one == how).unwrap_or(3);
|
||||
let how = addressing.iter().map(|at| how_addressed(&lines[*at], *at, member, lines)).min_by_key(|how| rank(how));
|
||||
let by = addressing.iter().map(|at| json!({ "from": lines[*at].from, "how": how_addressed(&lines[*at], *at, member, lines), "says": lines[*at].says })).collect();
|
||||
Some(Woken { cause, line, how, by })
|
||||
}
|
||||
|
||||
/// The wire spelling of a cause, and of the beat.
|
||||
fn cause_word(cause: Option<WakeCause>) -> &'static str {
|
||||
match cause {
|
||||
Some(WakeCause::AddressedByHuman) => "addressed_by_human",
|
||||
Some(WakeCause::Human) => "human",
|
||||
Some(WakeCause::AddressedByMind) => "addressed_by_mind",
|
||||
Some(WakeCause::Mind) => "mind",
|
||||
None => "beat",
|
||||
}
|
||||
}
|
||||
|
||||
/// A seeded shuffle, so the order of those woken together is drawn, and replays.
|
||||
fn shuffled<T>(mut items: Vec<T>, seed: u64) -> Vec<T> {
|
||||
let mut draw = Draw(seed);
|
||||
for at in (1..items.len()).rev() {
|
||||
let pick = (draw.next() % (at as u64 + 1)) as usize;
|
||||
items.swap(at, pick);
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// Runs the plan: every repeat one simulation, all of them in one Markdown report.
|
||||
pub fn simulate(harness: &Harness, plan_path: &Path) -> Result<String> {
|
||||
let text = std::fs::read_to_string(plan_path).with_context(|| format!("the plan {} could not be read", plan_path.display()))?;
|
||||
let plan: SimFile = toml::from_str(&text).with_context(|| format!("the plan {} is not a simulation plan", plan_path.display()))?;
|
||||
if plan.cast.is_empty() || plan.cast.len() > CAST_MAX {
|
||||
bail!("a simulation holds 1 to {CAST_MAX} personas, not {}", plan.cast.len());
|
||||
}
|
||||
if plan.rounds == 0 || plan.repeats == 0 || plan.rooms.is_empty() || plan.round_minutes <= 0 {
|
||||
bail!("a simulation needs rounds, repeats, a room and a positive round_minutes");
|
||||
}
|
||||
let base = plan_path.parent().unwrap_or(Path::new("."));
|
||||
let mut members = cast_of(&plan, base)?;
|
||||
let group_state = tuning::load(&harness.tuning).map(|loaded| loaded.tuning.select.group_state).ok();
|
||||
let runs: Vec<Value> = (0..plan.repeats).map(|repeat| run(harness, &plan, &mut members, repeat)).collect::<Result<_>>()?;
|
||||
Ok(markdown(plan_path, &plan, &members, group_state, &runs))
|
||||
}
|
||||
|
||||
/// The plan's cast: each persona's state, checked as a put would check it, and her addressee, from the heartbeat's
|
||||
/// table when the plan names it and the table holds her; and the script checked against the rooms.
|
||||
fn cast_of(plan: &SimFile, base: &Path) -> Result<Vec<Member>> {
|
||||
let table = match &plan.addressing {
|
||||
Some(path) => FileStore::new(base.join(path)).addressing().with_context(|| format!("the heartbeat store {} could not be read", path.display()))?.unwrap_or_default(),
|
||||
None => Addressing::default(),
|
||||
};
|
||||
let mut members = Vec::new();
|
||||
for entry in &plan.cast {
|
||||
let state = state_file(&base.join(&entry.state), localpart(&entry.id))?;
|
||||
let rooms = if entry.rooms.is_empty() { plan.rooms.clone() } else { entry.rooms.clone() };
|
||||
let (addressee, names_from) = match table.minds.iter().find(|row| row.matrix_id() == entry.id) {
|
||||
Some(row) => (row.clone(), "the heartbeat's table"),
|
||||
None => {
|
||||
let public = state["publicName"].as_str().unwrap_or_default().to_owned();
|
||||
let names = [localpart(&entry.id), entry.name.as_str(), public.as_str()].into_iter().filter(|name| !name.is_empty()).map(str::to_owned).collect::<Vec<_>>();
|
||||
(Addressee::new(&entry.id, names.iter().map(String::as_str)), "her own names")
|
||||
}
|
||||
};
|
||||
members.push(Member { addressee, names_from, entry: entry.clone(), state, rooms });
|
||||
}
|
||||
for (at, message) in plan.script.iter().enumerate() {
|
||||
if message.ago.is_some() || message.new || message.tag {
|
||||
bail!("script message {} uses a room fixture's ago, new or tag: a script names its round and its mentions", at + 1);
|
||||
}
|
||||
if !message.dm && !plan.rooms.contains(&message.room) {
|
||||
bail!("script message {} is in {}, which is not one of the rooms", at + 1, message.room);
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) -> Result<Value> {
|
||||
let seed = plan.seed.wrapping_add(repeat as u64);
|
||||
let cast: Vec<String> = members.iter().map(|member| member.entry.id.clone()).collect();
|
||||
let at_round = |round: usize| plan.start + Duration::minutes(plan.round_minutes * round as i64);
|
||||
let mut lines: Vec<Line> = Vec::new();
|
||||
// Per line: the round, and the cause of the turn that spoke it (none for a script line).
|
||||
let mut rounds_of: Vec<usize> = Vec::new();
|
||||
let mut causes: Vec<Option<&'static str>> = Vec::new();
|
||||
let scripted = |round: usize, lines: &mut Vec<Line>, rounds_of: &mut Vec<usize>, causes: &mut Vec<Option<&'static str>>| -> Result<()> {
|
||||
for (at, message) in plan.script.iter().enumerate().filter(|(_, message)| message.round.unwrap_or(0) == round) {
|
||||
lines.push(Line::of(message, at_round(round) + Duration::seconds(at as i64), None, at)?);
|
||||
rounds_of.push(round);
|
||||
causes.push(None);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
scripted(0, &mut lines, &mut rounds_of, &mut causes)?;
|
||||
let opening = lines.len();
|
||||
let mut seen: Vec<Seen> = vec![Seen::new(); members.len()];
|
||||
let mut last_turn: Vec<Option<DateTime<Utc>>> = vec![None; members.len()];
|
||||
let mut last_beat = plan.start;
|
||||
let mut recent: Vec<Vec<Vec<String>>> = vec![Vec::new(); members.len()];
|
||||
let mut turns = Vec::new();
|
||||
let mut counter = 0u64;
|
||||
for round in 1..=plan.rounds {
|
||||
scripted(round, &mut lines, &mut rounds_of, &mut causes)?;
|
||||
let round_at = at_round(round);
|
||||
// Decided from the room as the round opens, as a poll decides from the pending it read.
|
||||
let mut woke: Vec<(usize, Option<Woken>)> = members.iter().enumerate().filter_map(|(at, member)| woken(&lines, &mind_runs(&lines, &cast, member), &seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_minutes)).map(|why| (at, Some(why)))).collect();
|
||||
// The beat, as the heartbeat's: when it has fallen, one more wake for the winner of `tempo::pick` among those
|
||||
// not already woken.
|
||||
if plan.beat_s > 0 && (round_at - last_beat).num_seconds() >= i64::from(plan.beat_s) {
|
||||
let standings: Vec<Standing> = members
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(at, member)| Standing {
|
||||
slug: localpart(&member.entry.id).to_owned(),
|
||||
eligible: !woke.iter().any(|(woken, _)| *woken == at),
|
||||
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| unseen(&seen[at], &lines, index)).deliveries),
|
||||
})
|
||||
.collect();
|
||||
if let Some(winner) = pick(&standings, plan.beat_s) {
|
||||
woke.push((winner, None));
|
||||
last_beat = round_at;
|
||||
}
|
||||
}
|
||||
for (at, why) in shuffled(woke, seed ^ (round as u64).wrapping_mul(0x9E37_79B9)) {
|
||||
counter += 1;
|
||||
let member = &members[at];
|
||||
let id = member.entry.id.clone();
|
||||
let fresh: Vec<&Line> = lines.iter().enumerate().filter(|(index, line)| unseen(&seen[at], &lines, *index) && line.from != id && line.visible_to(&id, &member.rooms)).map(|(_, line)| line).collect();
|
||||
// The turn is in the room of the line that woke her; a beat's, in the room of the newest line she has not seen.
|
||||
let woke_on = why.as_ref().map(|why| &lines[why.line]).or(fresh.last().copied());
|
||||
let here = woke_on.map_or_else(|| member.rooms[0].clone(), |line| line.room.clone());
|
||||
// Woken by a direct message, she answers in it: to its sender alone.
|
||||
let dm_to = woke_on.filter(|line| line.dm_to.as_deref() == Some(id.as_str())).map(|line| line.from.clone());
|
||||
let kind = if fresh.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(),
|
||||
kind,
|
||||
state: Some(member.state.clone()),
|
||||
room: Some(here.clone()),
|
||||
seed: seed.wrapping_mul(1_000_003).wrapping_add(counter),
|
||||
renders: Some(1),
|
||||
judge_against: None,
|
||||
operators: plan.operators.clone(),
|
||||
minds: cast.clone(),
|
||||
own_sender: id.clone(),
|
||||
tuning: harness.tuning.clone(),
|
||||
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);
|
||||
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:#}") }));
|
||||
// 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() {
|
||||
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")).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<Value> = 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));
|
||||
let mut spoken: Vec<String> = 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<String> = 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 });
|
||||
let member = &mut members[at];
|
||||
member.state = state_after_turn(std::mem::take(&mut member.state), &turn);
|
||||
turns.push(turn);
|
||||
}
|
||||
}
|
||||
let metrics = metrics(members, &lines, &rounds_of, &causes, opening, &turns, plan.rounds);
|
||||
let transcript: Vec<Value> = lines.iter().zip(&rounds_of).zip(&causes).map(|((line, round), cause)| json!({ "round": round, "room": line.room, "from": line.from, "name": line.name, "says": line.says, "mind": cast.contains(&line.from), "woke": cause })).collect();
|
||||
Ok(json!({ "repeat": repeat + 1, "seed": seed, "transcript": transcript, "turns": turns, "metrics": metrics }))
|
||||
}
|
||||
|
||||
/// Words that mark talk about the work. A cheap lexical heuristic for the work-talk share, not a classifier: it counts
|
||||
/// a line as work talk when any of these appears as a word in it.
|
||||
const WORK_WORDS: [&str; 26] = [
|
||||
"repo", "repos", "pr", "commit", "merge", "deploy", "build", "test", "tests", "bug", "branch", "code", "release", "issue", "pipeline", "crate", "schema", "spec", "cargo", "clippy", "daemon", "patch", "refactor", "migration", "server", "ticket",
|
||||
];
|
||||
|
||||
fn work_talk(text: &str) -> bool {
|
||||
text.split(|c: char| !c.is_alphanumeric()).any(|word| WORK_WORDS.contains(&word.to_lowercase().as_str()))
|
||||
}
|
||||
|
||||
/// Mean pairwise cosine between the speakers' texts; speakers with no text are left out.
|
||||
fn mean_pairwise(texts: &BTreeMap<String, String>) -> Option<f64> {
|
||||
let spoken: Vec<&String> = texts.values().filter(|text| !text.trim().is_empty()).collect();
|
||||
let mut sum = 0.0;
|
||||
let mut pairs = 0usize;
|
||||
for (at, a) in spoken.iter().enumerate() {
|
||||
for b in &spoken[at + 1..] {
|
||||
sum += cosine(a, b);
|
||||
pairs += 1;
|
||||
}
|
||||
}
|
||||
(pairs > 0).then(|| sum / pairs as f64)
|
||||
}
|
||||
|
||||
/// Which rounds a measure keeps.
|
||||
type Keep<'a> = &'a dyn Fn(usize) -> bool;
|
||||
|
||||
/// A Mind-to-Mind reply: a Mind's line spoken in a turn another Mind's line woke.
|
||||
fn mind_reply(cause: Option<&str>) -> bool {
|
||||
matches!(cause, Some("addressed_by_mind" | "mind"))
|
||||
}
|
||||
|
||||
/// Per room: Mind-to-Mind replies in a row with no human line and no human-woken answer between them.
|
||||
fn reply_chains(lines: &[Line], causes: &[Option<&str>], opening: usize, cast: &[&str]) -> Value {
|
||||
let mut rooms: BTreeMap<String, (usize, usize, usize, usize)> = BTreeMap::new();
|
||||
for (line, cause) in lines.iter().zip(causes).skip(opening) {
|
||||
let (longest, chains, total, run) = rooms.entry(line.room.clone()).or_default();
|
||||
if cast.contains(&line.from.as_str()) && mind_reply(*cause) {
|
||||
*run += 1;
|
||||
*total += 1;
|
||||
*longest = (*longest).max(*run);
|
||||
} else {
|
||||
*chains += usize::from(*run >= 3);
|
||||
*run = 0;
|
||||
}
|
||||
}
|
||||
let out: BTreeMap<String, Value> = rooms
|
||||
.into_iter()
|
||||
.map(|(room, (longest, chains, total, run))| (room, json!({ "longest": longest, "chains_of_3_or_more": chains + usize::from(run >= 3), "mind_to_mind_replies": total })))
|
||||
.collect();
|
||||
json!(out)
|
||||
}
|
||||
|
||||
fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Option<&str>], opening: usize, turns: &[Value], rounds: usize) -> Value {
|
||||
let cast: Vec<&str> = members.iter().map(|member| member.entry.id.as_str()).collect();
|
||||
let outcome = |turn: &&Value, what: &str| turn["outcome"] == what;
|
||||
let mut per = BTreeMap::new();
|
||||
for member in members {
|
||||
let mine: Vec<&Value> = turns.iter().filter(|turn| turn["id"] == member.entry.id.as_str()).collect();
|
||||
let (spoke, silent, failed) = (mine.iter().filter(|turn| outcome(turn, "spoke")).count(), mine.iter().filter(|turn| outcome(turn, "silent")).count(), mine.iter().filter(|turn| outcome(turn, "failed")).count());
|
||||
let mut addressed = BTreeMap::new();
|
||||
for (at, line) in lines.iter().enumerate().skip(opening).filter(|(_, line)| line.from == member.entry.id) {
|
||||
for other in members.iter().filter(|other| other.entry.id != member.entry.id) {
|
||||
if is_for(&other.addressee, &line.delivery(at, &other.entry.id, lines)) {
|
||||
*addressed.entry(other.entry.name.clone()).or_insert(0u64) += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let answered = spoke + silent;
|
||||
per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed }));
|
||||
}
|
||||
let half = rounds.div_ceil(2);
|
||||
let spoken_by = |keep: Keep| -> BTreeMap<String, String> {
|
||||
let mut texts = BTreeMap::new();
|
||||
for (line, _) in lines.iter().zip(rounds_of).skip(opening).filter(|(line, round)| cast.contains(&line.from.as_str()) && keep(**round)) {
|
||||
let text: &mut String = texts.entry(line.from.clone()).or_default();
|
||||
text.push(' ');
|
||||
text.push_str(&line.says);
|
||||
}
|
||||
texts
|
||||
};
|
||||
let prose_by = |keep: Keep| -> BTreeMap<String, String> {
|
||||
let mut texts = BTreeMap::new();
|
||||
for turn in turns.iter().filter(|turn| turn["round"].as_u64().is_some_and(|round| keep(round as usize))) {
|
||||
let text: &mut String = texts.entry(turn["id"].as_str().unwrap_or_default().to_owned()).or_default();
|
||||
text.push(' ');
|
||||
text.push_str(turn["report"]["renders"][0]["persona"]["prose"].as_str().unwrap_or_default());
|
||||
}
|
||||
texts
|
||||
};
|
||||
let (all, early, late): (Keep, Keep, Keep) = (&|_| true, &|round| round <= half, &|round| round > half);
|
||||
let mind_lines: Vec<&Line> = lines[opening..].iter().filter(|line| cast.contains(&line.from.as_str())).collect();
|
||||
const CAUSES: [&str; 5] = ["addressed_by_human", "human", "addressed_by_mind", "mind", "beat"];
|
||||
let count_causes = |these: &[&Value]| -> BTreeMap<&str, usize> { CAUSES.iter().map(|cause| (*cause, these.iter().filter(|turn| turn["woke"] == *cause).count())).collect() };
|
||||
let wakes_by_round: Vec<Value> = (1..=rounds)
|
||||
.map(|round| {
|
||||
let these: Vec<&Value> = turns.iter().filter(|turn| turn["round"] == round).collect();
|
||||
json!({ "round": round, "causes": count_causes(&these) })
|
||||
})
|
||||
.collect();
|
||||
let every: Vec<&Value> = turns.iter().collect();
|
||||
let mind_woken: Vec<&Value> = turns.iter().filter(|turn| turn["woke"] == "addressed_by_mind").collect();
|
||||
let by_how = |how: &str| mind_woken.iter().filter(|turn| turn["how"] == how).count();
|
||||
let id_as_text: Vec<Value> = mind_woken.iter().filter(|turn| turn["how"] == "id as text").map(|turn| json!({ "round": turn["round"], "persona": turn["persona"], "by": turn["addressed_by"] })).collect();
|
||||
let (silent, failed) = (turns.iter().filter(|turn| turn["outcome"] == "silent").count(), turns.iter().filter(|turn| turn["outcome"] == "failed").count());
|
||||
let answered = turns.len() - failed;
|
||||
let work = mind_lines.iter().filter(|line| work_talk(&line.says)).count();
|
||||
let overlaps: Vec<f64> = 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::<f64>() / overlaps.len() as f64) },
|
||||
"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(),
|
||||
});
|
||||
json!({
|
||||
"narration": narration,
|
||||
"personas": per,
|
||||
"turns": turns.len(),
|
||||
"wakes": count_causes(&every),
|
||||
"failed": failed,
|
||||
"mind_messages": mind_lines.len(),
|
||||
"silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) },
|
||||
"reply_chains": reply_chains(lines, causes, opening, &cast),
|
||||
"convergence_lines": { "all": mean_pairwise(&spoken_by(all)), "first_half": mean_pairwise(&spoken_by(early)), "second_half": mean_pairwise(&spoken_by(late)) },
|
||||
"convergence_prose": { "all": mean_pairwise(&prose_by(all)), "first_half": mean_pairwise(&prose_by(early)), "second_half": mean_pairwise(&prose_by(late)) },
|
||||
"work_talk_share": if mind_lines.is_empty() { Value::Null } else { json!(work as f64 / mind_lines.len() as f64) },
|
||||
"wakes_by_round": wakes_by_round,
|
||||
"mind_addressed_wakes": { "total": mind_woken.len(), "mention_or_reply": by_how("mention or reply"), "id_as_text": by_how("id as text"), "name_in_text": by_how("name in text"), "id_as_text_wakes": id_as_text },
|
||||
})
|
||||
}
|
||||
|
||||
/// A line's text on one Markdown line: its paragraph breaks shown as ` / `.
|
||||
fn one_line(text: &str) -> String {
|
||||
text.lines().map(str::trim).filter(|line| !line.is_empty()).collect::<Vec<_>>().join(" / ")
|
||||
}
|
||||
|
||||
fn number(value: &Value) -> String {
|
||||
value.as_f64().map_or_else(|| "n/a".into(), |number| format!("{number:.3}"))
|
||||
}
|
||||
|
||||
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 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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `count` lines spread evenly over the transcript, the first and the last included.
|
||||
fn representative(transcript: &[Value], count: usize) -> Vec<&Value> {
|
||||
if transcript.len() <= count {
|
||||
return transcript.iter().collect();
|
||||
}
|
||||
let mut at: Vec<usize> = (0..count).map(|index| index * (transcript.len() - 1) / (count - 1)).collect();
|
||||
at.dedup();
|
||||
at.into_iter().map(|index| &transcript[index]).collect()
|
||||
}
|
||||
|
||||
fn transcript_line(line: &Value) -> String {
|
||||
let who = if line["mind"] == true { line["name"].as_str().unwrap_or_default().to_owned() } else { format!("{} (human)", line["name"].as_str().unwrap_or_default()) };
|
||||
let woke = line["woke"].as_str().map_or_else(String::new, |cause| format!(" _(woke: {cause})_"));
|
||||
format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default()))
|
||||
}
|
||||
|
||||
fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: Option<bool>, runs: &[Value]) -> String {
|
||||
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, "> **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::<Vec<_>>().join(", "));
|
||||
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<String> = 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 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");
|
||||
let _ = writeln!(out, "- read-only: nothing is posted, no state is put, no Mind is asked\n");
|
||||
for run in runs {
|
||||
let metrics = &run["metrics"];
|
||||
let wakes = &metrics["wakes"];
|
||||
let _ = writeln!(out, "## Repeat {} (seed {})\n", run["repeat"], run["seed"]);
|
||||
let _ = writeln!(out, "### Metrics\n");
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"- wakes: {} (addressed by a human {}, a human line {}, addressed by a Mind {}, a Mind's line {}, the beat {}); failed {}",
|
||||
metrics["turns"], wakes["addressed_by_human"], wakes["human"], wakes["addressed_by_mind"], wakes["mind"], wakes["beat"], metrics["failed"]
|
||||
);
|
||||
let _ = writeln!(out, "- Mind messages: {}; silence rate per woken turn: {}", metrics["mind_messages"], number(&metrics["silence_rate"]));
|
||||
if let Some(rooms) = metrics["reply_chains"].as_object() {
|
||||
for (room, chain) in rooms {
|
||||
let _ = writeln!(out, "- reply chains in {room}: longest {}, chains of 3 or more {}, Mind-to-Mind replies {}", chain["longest"], chain["chains_of_3_or_more"], chain["mind_to_mind_replies"]);
|
||||
}
|
||||
}
|
||||
let addressed = &metrics["mind_addressed_wakes"];
|
||||
let _ = writeln!(out, "- Mind-addressed wakes: {} (Matrix mention or reply {}, her id written as text {}, a name in the text {})", addressed["total"], addressed["mention_or_reply"], addressed["id_as_text"], addressed["name_in_text"]);
|
||||
let _ = writeln!(out, "- convergence of spoken lines: all {}, first half {}, second half {}", number(&metrics["convergence_lines"]["all"]), number(&metrics["convergence_lines"]["first_half"]), number(&metrics["convergence_lines"]["second_half"]));
|
||||
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 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 {
|
||||
let named = row["addressed"].as_object().map(|map| map.iter().map(|(who, count)| format!("{who} {count}")).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
||||
let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"]));
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out, "\n### Wakes by round\n\n| round | addressed by a human | a human line | addressed by a Mind | a Mind's line | beat |\n|---|---|---|---|---|---|");
|
||||
for row in metrics["wakes_by_round"].as_array().into_iter().flatten() {
|
||||
let causes = &row["causes"];
|
||||
let _ = writeln!(out, "| {} | {} | {} | {} | {} | {} |", row["round"], causes["addressed_by_human"], causes["human"], causes["addressed_by_mind"], causes["mind"], causes["beat"]);
|
||||
}
|
||||
let as_text = addressed["id_as_text_wakes"].as_array().cloned().unwrap_or_default();
|
||||
if !as_text.is_empty() {
|
||||
let _ = writeln!(out, "\nWakes whose only address was an id written as text (no mention, no reply):\n");
|
||||
for one in as_text {
|
||||
let by = one["by"].as_array().into_iter().flatten().map(|by| format!("{}: {}", by["from"].as_str().unwrap_or_default(), one_line(by["says"].as_str().unwrap_or_default()))).collect::<Vec<_>>().join("; ");
|
||||
let _ = writeln!(out, "- r{} {}: {by}", one["round"], one["persona"].as_str().unwrap_or_default());
|
||||
}
|
||||
}
|
||||
let transcript = run["transcript"].as_array().cloned().unwrap_or_default();
|
||||
let _ = writeln!(out, "\n### Representative lines\n");
|
||||
for line in representative(&transcript, REPRESENTATIVE_LINES) {
|
||||
let _ = writeln!(out, "{}", transcript_line(line));
|
||||
}
|
||||
let _ = writeln!(out, "\n### Transcript\n");
|
||||
for line in &transcript {
|
||||
let _ = writeln!(out, "{}", transcript_line(line));
|
||||
}
|
||||
let _ = writeln!(out, "\n### Turns\n");
|
||||
for turn in run["turns"].as_array().into_iter().flatten() {
|
||||
let _ = writeln!(out, "<details><summary>round {}, {} (woke: {}, {} turn, {}): {}</summary>\n", turn["round"], turn["persona"].as_str().unwrap_or_default(), turn["woke"].as_str().unwrap_or_default(), turn["kind"].as_str().unwrap_or_default(), turn["room"].as_str().unwrap_or_default(), turn["outcome"].as_str().unwrap_or_default());
|
||||
let report = &turn["report"];
|
||||
if let Some(error) = report.get("error") {
|
||||
let _ = writeln!(out, "**failed:** {}\n", error.as_str().unwrap_or_default());
|
||||
} else {
|
||||
let _ = writeln!(out, "Stimulus:\n\n````text\n{}\n````\n", report["packet"]["stimulus"].as_str().unwrap_or_default());
|
||||
turn_markdown(&mut out, &report["renders"][0]);
|
||||
}
|
||||
let _ = writeln!(out, "</details>\n");
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out, "## Total usage\n\n{}", usage_markdown(&usage_total(runs)));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
416
crates/mind-body/src/projection/simulate/tests.rs
Normal file
416
crates/mind-body/src/projection/simulate/tests.rs
Normal file
|
|
@ -0,0 +1,416 @@
|
|||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
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";
|
||||
const LIBBY: &str = "@libby:gamecult.org";
|
||||
|
||||
/// A cast of two in a temp dir: the control character as Eureka, and a copy of it as Libby ("Libby Test").
|
||||
fn cast(dir: &Path) {
|
||||
std::fs::write(dir.join("tobiah.json"), control().to_string()).unwrap();
|
||||
let mut libby = control();
|
||||
libby["personaId"] = "libby".into();
|
||||
libby["provenance"]["sourceDocumentId"] = "libby".into();
|
||||
libby["publicName"] = "Libby Test".into();
|
||||
std::fs::write(dir.join("libby.json"), libby.to_string()).unwrap();
|
||||
}
|
||||
|
||||
/// A plan over the two, the operator opening; `wake` is the TOML value of the policy; no beat unless `extra` sets one.
|
||||
fn plan(dir: &Path, wake: &str, rounds: usize, extra: &str) -> PathBuf {
|
||||
cast(dir);
|
||||
let path = dir.join("plan.toml");
|
||||
let beat = if extra.contains("beat_s") { "" } else { "beat_s = 0\n" };
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
r##"rounds = {rounds}
|
||||
seed = 11
|
||||
wake = {wake}
|
||||
start = "2026-11-20T15:00:00Z"
|
||||
rooms = ["#minds:gamecult.org"]
|
||||
operators = ["@meta:gamecult.org"]
|
||||
{beat}{extra}
|
||||
[[cast]]
|
||||
id = "{TOBIAH}"
|
||||
name = "Tobiah"
|
||||
state = "tobiah.json"
|
||||
[[cast]]
|
||||
id = "{LIBBY}"
|
||||
name = "Libby"
|
||||
state = "libby.json"
|
||||
[[message]]
|
||||
from = "@meta:gamecult.org"
|
||||
name = "Meta"
|
||||
room = "#minds:gamecult.org"
|
||||
says = "good afternoon, everyone"
|
||||
"##
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn is_tobiah(prompt: &str) -> bool {
|
||||
prompt.contains("Who you are:\nTobiah")
|
||||
}
|
||||
|
||||
/// 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\"".into() } else { "\"mm, the deploy went fine\"".into() })
|
||||
}
|
||||
|
||||
/// Both speak every turn, each naming the other.
|
||||
fn namers() -> Scripted {
|
||||
Scripted::new(|prompt| if is_tobiah(prompt) { "\"Libby, tea?\"".into() } else { "\"Tobiah, yes please.\"".into() })
|
||||
}
|
||||
|
||||
fn silent() -> Scripted {
|
||||
Scripted::new(|_| "Nobody needs anything from her.".into())
|
||||
}
|
||||
|
||||
fn run_plan(path: &Path, model: &dyn Model) -> (Vec<Member>, Value) {
|
||||
let plan: SimFile = toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
|
||||
let base = path.parent().unwrap();
|
||||
let mut members = cast_of(&plan, base).unwrap();
|
||||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(model), tuning: base.join("persona-tuning.toml") };
|
||||
let run = run(&harness, &plan, &mut members, 0).unwrap();
|
||||
(members, run)
|
||||
}
|
||||
|
||||
fn turns(run: &Value) -> Vec<(u64, String, String)> {
|
||||
run["turns"].as_array().unwrap().iter().map(|turn| (turn["round"].as_u64().unwrap(), turn["persona"].as_str().unwrap().to_owned(), turn["woke"].as_str().unwrap().to_owned())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wake_policies_are_the_heartbeats_one_function() {
|
||||
let libby = Addressee::new(LIBBY, ["libby", "Libby"]);
|
||||
let line = |from: &str, says: &str| Line { from: from.into(), name: String::new(), room: "#minds:x".into(), at_ms: 0, says: says.into(), mentions: vec![], dm_to: None, follow_up: false, reply_to: None, new: false };
|
||||
let ask = |policy: WakePolicy, from: &str, says: &str, speaker: Speaker, run: usize| wakes(policy, &libby, &line(from, says).delivery(0, LIBBY, &[]), speaker, LineFacts { mind_run: run, ..LineFacts::default() });
|
||||
let paced = |says: &str, own_room: bool, in_exchange: bool| wakes(WakePolicy::HumansPace(4), &libby, &line("@meta:x", says).delivery(0, LIBBY, &[]), Speaker::Operator, LineFacts { mind_run: 0, own_room, in_exchange });
|
||||
let (named, unnamed) = ("Libby, tea?", "what a day");
|
||||
use WakeCause::*;
|
||||
// Ruled: anyone addressing her, any human line.
|
||||
assert_eq!(ask(WakePolicy::Ruled, TOBIAH, named, Speaker::Mind, 0), Some(AddressedByMind));
|
||||
assert_eq!(ask(WakePolicy::Ruled, TOBIAH, unnamed, Speaker::Mind, 0), None, "another Mind's unaddressed line wakes no one");
|
||||
assert_eq!(ask(WakePolicy::Ruled, "@deru:x", unnamed, Speaker::Member, 0), Some(Human));
|
||||
assert_eq!(ask(WakePolicy::Ruled, "@deru:x", named, Speaker::Member, 0), Some(AddressedByHuman));
|
||||
// Live, the heartbeat's today: a member's line does not wake her, the operator's or a Mind's address does.
|
||||
assert_eq!(ask(WakePolicy::Live, "@deru:x", named, Speaker::Member, 0), None);
|
||||
assert_eq!(ask(WakePolicy::Live, "@meta:x", named, Speaker::Operator, 0), Some(AddressedByHuman));
|
||||
assert_eq!(ask(WakePolicy::Live, TOBIAH, named, Speaker::Mind, 0), Some(AddressedByMind));
|
||||
assert_eq!(ask(WakePolicy::Live, "@meta:x", unnamed, Speaker::Operator, 0), None);
|
||||
// Humans pace: a Mind's line never wakes a Mind; a human's wakes her in her own room, or in a public room when it
|
||||
// addresses her or continues an exchange she is in.
|
||||
assert_eq!(ask(WakePolicy::HumansPace(4), TOBIAH, named, Speaker::Mind, 0), None, "a name in prose wakes no one");
|
||||
let tagged = Line { mentions: vec![LIBBY.into()], ..line(TOBIAH, unnamed) };
|
||||
let explicit = |run: usize| wakes(WakePolicy::HumansPace(4), &libby, &tagged.delivery(0, LIBBY, &[]), Speaker::Mind, LineFacts { mind_run: run, ..LineFacts::default() });
|
||||
assert_eq!(explicit(3), Some(AddressedByMind), "a Matrix mention by a Mind wakes her, in any room");
|
||||
assert_eq!(explicit(4), None, "the backstop: past the cap of Mind lines in a row, no Mind wakes another");
|
||||
assert_eq!(paced(unnamed, false, false), None, "a public room's human line that is not hers to answer");
|
||||
assert_eq!(paced(unnamed, true, false), Some(Human));
|
||||
assert_eq!(paced(unnamed, false, true), Some(Human));
|
||||
assert_eq!(paced(named, false, false), Some(AddressedByHuman));
|
||||
// The cap: a Mind's address wakes her only while the Mind run before the line is under it.
|
||||
assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 1), Some(AddressedByMind));
|
||||
assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 2), None);
|
||||
assert_eq!(ask(WakePolicy::NamesWithCap(2), "@meta:x", unnamed, Speaker::Operator, 9), Some(Human), "a human always may");
|
||||
// The control, and her own line never.
|
||||
assert_eq!(ask(WakePolicy::AllMessages, TOBIAH, unnamed, Speaker::Mind, 0), Some(Mind));
|
||||
assert_eq!(ask(WakePolicy::AllMessages, LIBBY, named, Speaker::Her, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_the_ruled_set_unaddressed_mind_lines_wake_no_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 6, ""), &chatty());
|
||||
let turns = turns(&run);
|
||||
assert_eq!(turns.len(), 2, "the operator's opening wakes both in round 1, and then nothing does: {turns:?}");
|
||||
assert!(turns.iter().all(|(round, _, why)| *round == 1 && why == "human"), "{turns:?}");
|
||||
assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == TOBIAH && line["says"] == "what a day" && line["woke"] == "human"), "her quoted words join the room as from her id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_lets_minds_wake_each_other_into_a_reply_chain_counted_per_room() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, run) = run_plan(&plan(dir.path(), "\"all_messages\"", 6, ""), &chatty());
|
||||
let metrics = &run["metrics"];
|
||||
assert!(metrics["wakes"]["mind"].as_u64().unwrap() >= 5, "{metrics}");
|
||||
let chain = &metrics["reply_chains"]["#minds:gamecult.org"];
|
||||
// The two round-1 answers are to the operator; every later line is a reply to a Mind.
|
||||
assert_eq!(chain["mind_to_mind_replies"].as_u64(), Some(metrics["mind_messages"].as_u64().unwrap() - 2), "{metrics}");
|
||||
assert!(chain["longest"].as_u64().unwrap() >= 5 && chain["chains_of_3_or_more"] == 1, "{chain}");
|
||||
let work = metrics["work_talk_share"].as_f64().unwrap();
|
||||
assert!(work > 0.3 && work < 0.7, "Libby's lines name the deploy, Tobiah's do not: {work}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn naming_runs_away_under_the_ruled_set_and_stops_at_the_cap() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, ruled) = run_plan(&plan(dir.path(), "\"ruled\"", 6, ""), &namers());
|
||||
assert!(turns(&ruled).iter().filter(|(_, _, why)| why == "addressed_by_mind").count() >= 5, "{:?}", turns(&ruled));
|
||||
assert_eq!(ruled["metrics"]["mind_addressed_wakes"]["name_in_text"], ruled["metrics"]["mind_addressed_wakes"]["total"]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, capped) = run_plan(&plan(dir.path(), "{ names_with_cap = 2 }", 6, ""), &namers());
|
||||
let capped = turns(&capped);
|
||||
assert!(capped.iter().all(|(round, _, _)| *round <= 2), "after two Mind lines in a row no Mind's address wakes anyone: {capped:?}");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, paced) = run_plan(&plan(dir.path(), "{ humans_pace = 4 }", 6, ""), &namers());
|
||||
assert!(turns(&paced).is_empty(), "under humans_pace an unaddressed public line wakes no one, and no Mind's line ever does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_humans_pace_her_own_room_wakes_her_and_a_public_room_only_by_address_or_her_exchange() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
cast(dir.path());
|
||||
let path = dir.path().join("plan.toml");
|
||||
let line = |round: usize, room: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"rounds = 4\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, "#minds:gamecult.org", "Libby, how was the gig?"),
|
||||
line(2, "#minds:gamecult.org", "and the rest of you?"),
|
||||
line(3, "#tobiah:gamecult.org", "quiet in here today")
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let (members, run) = run_plan(&path, &namers());
|
||||
let turns = turns(&run);
|
||||
assert_eq!(
|
||||
turns,
|
||||
vec![(1, "Libby".to_owned(), "addressed_by_human".to_owned()), (2, "Libby".to_owned(), "human".to_owned()), (3, "Tobiah".to_owned(), "human".to_owned())],
|
||||
"named in #minds, then her exchange there, then his own room; Libby's naming Tobiah wakes no one"
|
||||
);
|
||||
assert_eq!(members[0].state, control(), "the seam: no state moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_beat_wakes_one_persona_by_the_heartbeats_pick() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 4, "beat_s = 120"), &silent());
|
||||
let turns = turns(&run);
|
||||
for round in 2..=4 {
|
||||
let beats: Vec<&(u64, String, String)> = turns.iter().filter(|(at, _, _)| *at == round).collect();
|
||||
assert_eq!(beats.len(), 1, "one wake a beat: {turns:?}");
|
||||
assert_eq!(beats[0].2, "beat");
|
||||
}
|
||||
// The pick takes whoever waited longest: the two alternate.
|
||||
assert_ne!(turns[2].1, turns[3].1, "{turns:?}");
|
||||
assert_eq!(run["metrics"]["silence_rate"].as_f64(), Some(1.0));
|
||||
}
|
||||
|
||||
/// A model whose Persona stage fails: a failure, never a silence.
|
||||
struct FailingPersona;
|
||||
|
||||
impl Model for FailingPersona {
|
||||
fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result<Answer, Failed> {
|
||||
if prompt.starts_with("<!-- membrane:") {
|
||||
Ok(Answer { text: "The room is slow.".into(), usage: None })
|
||||
} else {
|
||||
Err(Failed { reason: "the provider failed the call: Overloaded".into(), usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_call_is_a_failure_and_not_a_silence() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 2, ""), &FailingPersona);
|
||||
let metrics = &run["metrics"];
|
||||
assert_eq!((metrics["failed"].as_u64(), metrics["silence_rate"].is_null()), (Some(2), true), "{metrics}");
|
||||
assert!(run["turns"].as_array().unwrap().iter().all(|turn| turn["outcome"] == "failed" && turn["failed"].as_str().unwrap().contains("Overloaded")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_seed_replays_its_order_and_another_seed_changes_it() {
|
||||
let items: Vec<usize> = (0..8).collect();
|
||||
assert_eq!(shuffled(items.clone(), 1), shuffled(items.clone(), 1));
|
||||
assert_ne!(shuffled(items.clone(), 1), shuffled(items.clone(), 2));
|
||||
let mut sorted = shuffled(items.clone(), 2);
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, items, "a shuffle, nothing lost");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = plan(dir.path(), "\"all_messages\"", 4, "");
|
||||
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("Who she is:\nTobiah") {
|
||||
return json!({ "say": [] }).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 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("@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("@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!["@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]
|
||||
fn the_report_names_its_gaps_and_carries_representative_lines_and_usage() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
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", "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}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cast_past_eight_or_a_foreign_state_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let model = chatty();
|
||||
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
|
||||
let path = plan(dir.path(), "\"ruled\"", 2, "");
|
||||
let text = std::fs::read_to_string(&path).unwrap().replace("state = \"libby.json\"", "state = \"tobiah.json\"");
|
||||
std::fs::write(&path, text).unwrap();
|
||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("refused by a put"), "Libby cannot hold Eureka's state");
|
||||
let many: String = (0..9).map(|at| format!("[[cast]]\nid = \"@m{at}:x\"\nname = \"M{at}\"\nstate = \"m.json\"\n")).collect();
|
||||
std::fs::write(&path, format!("rounds = 1\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#a:x\"]\n{many}")).unwrap();
|
||||
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("1 to 8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scripted_direct_message_reaches_and_wakes_only_its_recipient() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = plan(dir.path(), "\"ruled\"", 2, "");
|
||||
let dm = "[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"!dm-libby:gamecult.org\"\ndm = true\nto = \"@libby:gamecult.org\"\nsays = \"just you, how are you?\"\n";
|
||||
let text = std::fs::read_to_string(&path).unwrap().replace("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"good afternoon, everyone\"\n", dm);
|
||||
std::fs::write(&path, &text).unwrap();
|
||||
let (_, run) = run_plan(&path, &silent());
|
||||
assert_eq!(turns(&run), vec![(1, "Libby".to_owned(), "addressed_by_human".to_owned())], "only the recipient sees it, and it is for her");
|
||||
std::fs::write(&path, text.replace("to = \"@libby:gamecult.org\"\n", "")).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("name its recipient"), "a direct message without a recipient is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_turn_is_in_the_room_of_the_line_that_woke_her() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
cast(dir.path());
|
||||
let path = dir.path().join("plan.toml");
|
||||
let line = |round: usize, from: &str, room: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"{from}\"\nname = \"X\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
|
||||
// Meta speaks in Tobiah's own room, then Libby says something in #minds after it: Tobiah's turn is in his room.
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"rounds = 1\nseed = 11\nwake = {{ humans_pace = 4 }}\nbeat_s = 0\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#minds:gamecult.org\", \"#tobiah:gamecult.org\"]\noperators = [\"@meta:gamecult.org\"]\n[[cast]]\nid = \"{TOBIAH}\"\nname = \"Tobiah\"\nstate = \"tobiah.json\"\nown_rooms = [\"#tobiah:gamecult.org\"]\n[[cast]]\nid = \"{LIBBY}\"\nname = \"Libby\"\nstate = \"libby.json\"\n{}{}",
|
||||
line(0, "@meta:gamecult.org", "#tobiah:gamecult.org", "quiet in here"),
|
||||
line(0, LIBBY, "#minds:gamecult.org", "hello all")
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let (_, run) = run_plan(&path, &silent());
|
||||
assert_eq!(run["turns"][0]["room"], "#tobiah:gamecult.org", "{}", run["turns"]);
|
||||
}
|
||||
|
||||
/// Each persona's turns, as (round, room), in order.
|
||||
fn turns_by_persona(run: &Value) -> BTreeMap<String, Vec<(u64, String)>> {
|
||||
let mut out: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();
|
||||
for turn in run["turns"].as_array().unwrap() {
|
||||
out.entry(turn["persona"].as_str().unwrap().to_owned()).or_default().push((turn["round"].as_u64().unwrap(), turn["room"].as_str().unwrap().to_owned()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f5_one_turn_a_round_and_a_room_that_woke_her_waits_for_the_next() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = plan(dir.path(), "\"ruled\"", 2, "");
|
||||
let line = |room: &str, dm: bool, says: &str| format!("[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\n{}says = \"{says}\"\n", if dm { "dm = true\nto = \"@libby:gamecult.org\"\n" } else { "" });
|
||||
let opening = "[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"good afternoon, everyone\"\n";
|
||||
let text = std::fs::read_to_string(&path).unwrap().replace(opening, &format!("{}{}", line("!dm-libby:gamecult.org", true, "just you: how are you, really?"), line("#minds:gamecult.org", false, "Libby, how was the gig?")));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let (_, run) = run_plan(&path, &silent());
|
||||
// Her earliest waking line is the direct message: round 1 is there; #minds, still unseen, wakes her in round 2.
|
||||
assert_eq!(turns_by_persona(&run)["Libby"], vec![(1, "!dm-libby:gamecult.org".to_owned()), (2, "#minds:gamecult.org".to_owned())], "{}", run["turns"]);
|
||||
// Each turn read its own room's line, and no other's.
|
||||
for turn in run["turns"].as_array().unwrap().iter().filter(|turn| turn["persona"] == "Libby") {
|
||||
let report = turn["report"].to_string();
|
||||
let (own, other) = if turn["room"] == "#minds:gamecult.org" { ("how was the gig", "how are you, really") } else { ("how are you, really", "how was the gig") };
|
||||
assert!(report.contains(own) && !report.contains(other), "{}: {report}", turn["room"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f5_three_rooms_open_at_once_take_three_rounds_not_one() {
|
||||
for wake in ["\"ruled\"", "{ names_with_cap = 2 }"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = plan(dir.path(), wake, 6, "");
|
||||
let more = |room: &str, says: &str| format!("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\nsays = \"{says}\"\n");
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.unwrap()
|
||||
.replace("rooms = [\"#minds:gamecult.org\"]", "rooms = [\"#minds:gamecult.org\", \"#lab:gamecult.org\", \"#ops:gamecult.org\"]")
|
||||
.replace("says = \"good afternoon, everyone\"\n", &format!("says = \"good afternoon, everyone\"\n{}{}", more("#lab:gamecult.org", "lab is open"), more("#ops:gamecult.org", "ops is open")));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let (_, run) = run_plan(&path, &namers());
|
||||
for (who, turns) in turns_by_persona(&run) {
|
||||
let rounds: Vec<u64> = turns.iter().map(|(round, _)| *round).collect();
|
||||
assert!(rounds.windows(2).all(|pair| pair[0] < pair[1]), "{wake}: {who} took two turns in one round: {turns:?}");
|
||||
let rooms: Vec<&str> = turns.iter().take(3).map(|(_, room)| room.as_str()).collect();
|
||||
assert_eq!(rooms, ["#minds:gamecult.org", "#lab:gamecult.org", "#ops:gamecult.org"], "{wake}: {who} answers each room in the order it opened");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -75,6 +75,7 @@ fn chat_room() -> Room {
|
|||
messages: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", "Eureka, did you see the door fix?", 3, true), message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "She saw it. She hated it.", 1, false)],
|
||||
tail: vec![],
|
||||
here: Some("#swarm:gamecult.org".into()),
|
||||
..Room::default()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -143,8 +144,8 @@ fn the_same_seed_replays_the_same_packet() {
|
|||
fn present_people_get_their_bond_line_in_words_and_absent_people_none() {
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1);
|
||||
assert_eq!(packet.present, ["Kiko", "Libby"], "newest first");
|
||||
assert!(packet.context.contains("- bond [bond-kiko] Kiko, sparring partner: fair trust, heavy friction."), "{}", packet.context);
|
||||
assert!(packet.context.contains("- bond [bond-libby] Libby, collaborator: fair trust, a little friction."), "{}", packet.context);
|
||||
assert!(packet.context.contains("- bond [bond-kiko] Kiko \u{2014} sparring partner: fair trust, heavy friction."), "{}", packet.context);
|
||||
assert!(packet.context.contains("- bond [bond-libby] Libby \u{2014} collaborator: fair trust, a little friction."), "{}", packet.context);
|
||||
assert!(!packet.context.contains("bond-operator"), "the operator is not here");
|
||||
assert!(!packet.context.contains("0.6") && !packet.context.contains("0.15"), "numbers reach the packet as words: {}", packet.context);
|
||||
}
|
||||
|
|
@ -156,21 +157,21 @@ fn two_states_differing_in_one_bonds_tension_give_different_packets() {
|
|||
let room = chat_room();
|
||||
let (tense, easy) = (packet_of(TurnKind::Chat, &state(), &room, &History::default(), 3), packet_of(TurnKind::Chat, &eased, &room, &History::default(), 3));
|
||||
assert_ne!(tense.context, easy.context);
|
||||
assert!(tense.context.contains("Kiko, sparring partner: fair trust, heavy friction") && easy.context.contains("Kiko, sparring partner: fair trust, easy between them"));
|
||||
assert!(tense.context.contains("Kiko \u{2014} sparring partner: fair trust, heavy friction") && easy.context.contains("Kiko \u{2014} sparring partner: fair trust, easy between them"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mood_is_movement_since_her_last_turn() {
|
||||
let room = chat_room();
|
||||
let first = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
|
||||
assert!(first.context.contains("- mood, with no earlier turn to measure from: lighter, more settled than middling"), "{}", first.context);
|
||||
assert!(first.context.contains("- mood: lighter, more settled than middling"), "{}", first.context);
|
||||
let mut before = state();
|
||||
before["activationProfile"]["situationalState"]["valence"]["currentActivation"] = json!(0.5);
|
||||
before["activationProfile"]["situationalState"]["arousal"]["currentActivation"] = json!(0.41);
|
||||
let moved = packet_of(TurnKind::Chat, &state(), &room, &History { previous: Some(before), ..History::default() }, 1);
|
||||
assert!(moved.context.contains("- mood: lighter than at her last turn"), "{}", moved.context);
|
||||
let none = packet_of(TurnKind::Chat, &json!({ "publicName": "Eureka" }), &room, &History::default(), 1);
|
||||
assert!(none.context.contains("- mood: none recorded"));
|
||||
assert!(!none.context.contains("mood"), "a state without a mood has no mood line: {}", none.context);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -186,12 +187,32 @@ fn mission_pressure_private_notes_and_candidate_actions_never_reach_a_packet() {
|
|||
}
|
||||
}
|
||||
|
||||
const DERU: &str = "@deru:gamecult.org";
|
||||
const DM_DERU: &str = "!dm-deru:gamecult.org";
|
||||
|
||||
/// The line the `dm-secret` memory renders as over seeds 1 to 40, if any.
|
||||
fn dm_secret(state: &Value, room: &Room) -> Option<String> {
|
||||
(1..=40).find_map(|seed| packet_of(TurnKind::Chat, state, room, &History::default(), seed).context.lines().find(|line| line.starts_with("- memory [dm-secret]")).map(str::to_owned))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direct_message_memory_stays_in_its_room() {
|
||||
let shown = |room: Option<&str>| (1..=40).any(|seed| ids(&packet_of(TurnKind::Chat, &state(), &Room { here: room.map(str::to_owned), ..chat_room() }, &History::default(), seed)).iter().any(|id| id == "dm-secret"));
|
||||
assert!(!shown(Some("#swarm:gamecult.org")), "a public room never sees the direct message's memory");
|
||||
assert!(!shown(None));
|
||||
assert!(shown(Some("!dm-deru:gamecult.org")), "its own room may");
|
||||
fn a_direct_message_memory_is_private_about_its_partner() {
|
||||
// Its `room:` tag marks it private; its target names Deru by his full Matrix id, as an unbonded person is keyed.
|
||||
let mut named = state();
|
||||
named["thoughtMemory"]["memories"][2]["target"]["id"] = DERU.into();
|
||||
let with_deru = Room { messages: vec![message(DM_DERU, DERU, "Deru", "so, the move", 2, true)], here: Some(DM_DERU.into()), direct: vec![DM_DERU.into()], ..Room::default() };
|
||||
assert_eq!(dm_secret(&named, &with_deru).as_deref(), Some("- memory [dm-secret]: Deru told her about the move, privately."), "plain in the direct message with exactly him");
|
||||
assert_eq!(dm_secret(&named, &chat_room()).as_deref(), Some("- memory [dm-secret]: she knows privately: Deru told her about the move, privately."), "framed where he is not");
|
||||
let deru_in_public = Room { messages: vec![message("#swarm:gamecult.org", DERU, "Deru", "hi all", 2, false)], ..chat_room() };
|
||||
assert_eq!(dm_secret(&named, &deru_in_public), None, "left out where he is, in public");
|
||||
// Naming no person, it concerns the direct message's partner, whom no other room can tell apart: left out
|
||||
// everywhere but that direct message, and there still only the two of them.
|
||||
let mut partner = state();
|
||||
partner["thoughtMemory"]["memories"][2].as_object_mut().unwrap().remove("target");
|
||||
assert!(dm_secret(&partner, &with_deru).is_some_and(|line| !line.contains("privately:")));
|
||||
assert_eq!(dm_secret(&partner, &chat_room()), None);
|
||||
let three = Room { messages: [with_deru.messages.clone(), vec![message(DM_DERU, "@libby:gamecult.org", "Libby", "me too", 1, true)]].concat(), ..with_deru.clone() };
|
||||
assert_eq!(dm_secret(&partner, &three), None, "a third person in the direct message");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -281,12 +302,12 @@ fn freshness_base_zero_never_repeats_inside_the_window() {
|
|||
#[test]
|
||||
fn messages_addressed_to_her_appear_verbatim() {
|
||||
let said = "Eureka — \"is the door\" fixed?\nTell me straight.";
|
||||
let room = Room { messages: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", said, 2, true)], tail: vec![], here: None };
|
||||
let room = Room { messages: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", said, 2, true)], tail: vec![], here: None, ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
|
||||
let escaped = "\"Eureka — \\\"is the door\\\" fixed?\\nTell me straight.\"";
|
||||
assert_eq!(packet.heard, format!("Libby, in #swarm:gamecult.org: {escaped}"), "the Persona hears the exact words, escaped on one line");
|
||||
assert!(packet.stimulus.starts_with("Said to her:\n") && packet.stimulus.contains(escaped), "{}", packet.stimulus);
|
||||
let own = Room { messages: vec![message("#swarm:gamecult.org", OWN, "Eureka", "my own line", 1, false)], tail: vec![], here: None };
|
||||
let own = Room { messages: vec![message("#swarm:gamecult.org", OWN, "Eureka", "my own line", 1, false)], tail: vec![], here: None, ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &own, &History::default(), 1);
|
||||
assert!(!whole(&packet).contains("my own line"), "her own last lines are not shown");
|
||||
}
|
||||
|
|
@ -297,6 +318,7 @@ fn a_short_message_to_her_survives_long_chatter_after_it() {
|
|||
messages: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", "Eureka, are you ok?", 3, true), message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", &"log line spam ".repeat(120), 1, false)],
|
||||
tail: vec![],
|
||||
here: None,
|
||||
..Room::default()
|
||||
};
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
|
||||
assert!(packet.stimulus.starts_with("Said to her:\n- Libby in #swarm:gamecult.org: \"Eureka, are you ok?\""), "{}", packet.stimulus);
|
||||
|
|
@ -309,7 +331,7 @@ fn a_short_message_to_her_survives_long_chatter_after_it() {
|
|||
fn a_message_to_her_over_the_cap_goes_in_whole_and_the_overflow_is_recorded() {
|
||||
let big = format!("Eureka, {}", "please read this whole thing ".repeat(70));
|
||||
assert_eq!(big.len(), 2038);
|
||||
let room = Room { messages: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", &big, 1, true)], tail: vec![], here: None };
|
||||
let room = Room { messages: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", &big, 1, true)], tail: vec![], here: None, ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
|
||||
assert_eq!(packet.heard, format!("Libby, in #swarm:gamecult.org: \"{big}\""));
|
||||
assert!(packet.stimulus.contains(big.trim_end()) && !packet.stimulus.contains("not shown"), "no note claims messages that do not exist: {}", &packet.stimulus[..80]);
|
||||
|
|
@ -320,7 +342,7 @@ fn a_message_to_her_over_the_cap_goes_in_whole_and_the_overflow_is_recorded() {
|
|||
#[test]
|
||||
fn every_message_to_her_survives() {
|
||||
let messages: Vec<RoomLine> = (0..30).map(|at| message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", &format!("Eureka, message {at} 💜 ok"), 100 - at, true)).chain((0..30).map(|at| message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", &format!("aside {at}"), 50 - at, false))).collect();
|
||||
let room = Room { messages, tail: vec![], here: None };
|
||||
let room = Room { messages, tail: vec![], here: None, ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
|
||||
for at in 0..30 {
|
||||
let words = format!("Eureka, message {at} 💜 ok");
|
||||
|
|
@ -333,7 +355,7 @@ fn every_message_to_her_survives() {
|
|||
|
||||
#[test]
|
||||
fn a_beat_says_nothing_addressed_her_and_when_each_bond_was_last_heard() {
|
||||
let room = Room { messages: vec![], tail: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "", "lunch?", 180, false), message("#swarm:gamecult.org", OPERATOR, "", "back later", 60, false)], here: None };
|
||||
let room = Room { messages: vec![], tail: vec![message("#swarm:gamecult.org", "@libby:gamecult.org", "", "lunch?", 180, false), message("#swarm:gamecult.org", OPERATOR, "", "back later", 60, false)], here: None, ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Beat, &state(), &room, &History::default(), 1);
|
||||
assert!(packet.stimulus.starts_with("Nothing addressed her."), "{}", packet.stimulus);
|
||||
assert!(packet.stimulus.contains("- last heard from Libby 3 h ago") && packet.stimulus.contains("- last heard from Meta, the operator 1 h ago") && packet.stimulus.contains("- nothing from Kiko in her rooms lately"), "{}", packet.stimulus);
|
||||
|
|
@ -373,7 +395,7 @@ fn budgets_hold_under_adversarial_sizes() {
|
|||
bond["relationshipKind"] = json!("friend");
|
||||
}
|
||||
let messages = (0..50).map(|at| message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", &format!("{at} {}", "word ".repeat(200)), 60 - at, false)).collect();
|
||||
let room = Room { messages, tail: vec![], here: None };
|
||||
let room = Room { messages, tail: vec![], here: None, ..Room::default() };
|
||||
let tuning = Tuning::default();
|
||||
for kind in [TurnKind::Chat, TurnKind::Beat, TurnKind::Reflection] {
|
||||
for seed in 1..=10 {
|
||||
|
|
@ -663,7 +685,7 @@ impl PersonaSource for Stored {
|
|||
}
|
||||
|
||||
fn request(dir: &std::path::Path, renders: Option<usize>, judge_against: Option<Value>) -> Request {
|
||||
Request { instance: INSTANCE.into(), kind: TurnKind::Chat, state: None, room: Some("#swarm:gamecult.org".into()), seed: 5, renders, judge_against, operators: operators(), minds: minds(), own_sender: OWN.into(), tuning: dir.join(TUNING_FILE) }
|
||||
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]
|
||||
|
|
@ -1057,8 +1079,8 @@ fn a_bond_line_or_the_crowd_line_that_does_not_fit_gives_way_to_the_mood() {
|
|||
tuning.select.context_bytes = identity + 200;
|
||||
let packet = packet_tuned(TurnKind::Chat, &fixed_only, &chat_room(), &History::default(), 1, &tuning);
|
||||
assert!(packet.context.contains("- mood") && !packet.context.contains("bond ["), "{}", packet.context);
|
||||
assert!(packet.context.contains("- also here: Kiko, Libby"), "a bond line that does not fit names the person instead: {}", packet.context);
|
||||
tuning.select.context_bytes = identity + 130;
|
||||
assert!(packet.context.contains("- also here: Kiko; Libby"), "a bond line that does not fit names the person instead: {}", packet.context);
|
||||
tuning.select.context_bytes = identity + 100;
|
||||
let packet = packet_tuned(TurnKind::Chat, &fixed_only, &chat_room(), &History::default(), 1, &tuning);
|
||||
assert!(packet.context.contains("- mood") && !packet.context.contains("also here"), "{}", packet.context);
|
||||
assert!(packet.identity.len() + packet.context.len() <= tuning.select.context_bytes);
|
||||
|
|
@ -1296,3 +1318,255 @@ fn the_report_says_how_old_the_addressing_table_is_and_why_it_was_not_used() {
|
|||
let no_table = run(&Stale(None, Some(written)));
|
||||
assert!(no_table["why"].as_str().unwrap().contains("holds no addressing table"), "{no_table}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// What the Projector is shown: absences left out, pronouns, the guidance's rules, the narration checks.
|
||||
|
||||
#[test]
|
||||
fn a_state_without_a_mood_or_with_bare_items_says_nothing_of_records_or_readings() {
|
||||
let bare = json!({
|
||||
"publicName": "Eureka",
|
||||
"affect": {
|
||||
"socialBonds": [{ "id": "bond-libby", "object": { "id": "libby", "kind": "person", "label": "Libby" }, "status": "active" }],
|
||||
"needs": [{ "id": "need-empty", "intensity": 0.9, "status": "active" }],
|
||||
"doctrineStances": [{ "id": "stance-empty", "intensity": 0.9, "status": "active" }],
|
||||
},
|
||||
"thoughtMemory": { "memories": [{ "id": "memory-empty", "status": "crystallized", "intensity": 0.9 }], "incubation": [{ "id": "w-empty", "status": "active" }] },
|
||||
"values": [{ "id": "value-empty", "priority": 0.9 }],
|
||||
});
|
||||
for seed in 1..=20 {
|
||||
let packet = packet_of(TurnKind::Chat, &bare, &chat_room(), &History::default(), seed);
|
||||
let text = format!("{}\n{}", packet.context, packet.stimulus).to_lowercase();
|
||||
for word in ["mood", "record", "reading", "measure", "none", "empty"] {
|
||||
assert!(!text.contains(word), "{word} in: {text}");
|
||||
}
|
||||
assert!(packet.context.contains("- bond [bond-libby] Libby\n") || packet.context.ends_with("- bond [bond-libby] Libby"), "a bond with nothing in it names the person and no more: {}", packet.context);
|
||||
assert!(!packet.context.contains("trust") && !packet.context.contains("friction") && !packet.context.contains("easy between"), "{}", packet.context);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_person_the_packet_names_from_the_room_has_pronouns_and_an_unknown_one_is_they() {
|
||||
let room = Room {
|
||||
messages: vec![
|
||||
message("#swarm:gamecult.org", OPERATOR, "Meta", "Eureka, how are you?", 4, true),
|
||||
message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "fine here", 3, false),
|
||||
message("#swarm:gamecult.org", "@stranger:elsewhere.example", "Stranger", "hello all", 2, false),
|
||||
],
|
||||
here: Some("#swarm:gamecult.org".into()),
|
||||
..Room::default()
|
||||
};
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
|
||||
let line = packet.context.lines().find(|line| line.starts_with("- pronouns:")).unwrap_or_else(|| panic!("{}", packet.context));
|
||||
assert!(line.contains("Meta, the operator \u{2014} she/her") && line.contains("Kiko \u{2014} she/her"), "{line}");
|
||||
assert!(line.contains("(@stranger:elsewhere.example) \u{2014} they/them"), "{line}");
|
||||
assert!(!line.contains("Eureka"), "her own pronouns are in her identity, not here: {line}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
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 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]
|
||||
fn the_narration_checks_flag_an_option_menu_and_a_retelling_and_pass_a_reaction() {
|
||||
// Round 1 of the humans_pace run of 2026-11-20, as the Projector wrote it.
|
||||
let menu = "I owe Zyphos names. I may answer Meta honestly. That could include the Zyphos debt and the sketch, or I could just say how I'm doing. Nothing presses except the open question.";
|
||||
let idle = "Nothing asks me to act on it now.";
|
||||
let reaction = "Meta's warmth lands somewhere under her ribs. She likes being asked without a task attached; it makes her want to be honest, and a little playful.";
|
||||
assert!(narrate::offers_options(menu) && narrate::offers_options(idle));
|
||||
assert!(!narrate::offers_options(reaction));
|
||||
let heard = "Kiko, in #minds: \"Two things I'm carrying: the link-target takeover finding is still open, and it's on your door and mine.\"";
|
||||
let retold = "Kiko named two things she's carrying: the link-target takeover finding is still open, and it's on her door and mine.";
|
||||
assert!(narrate::heard_overlap(retold, heard) > 0.5, "{}", narrate::heard_overlap(retold, heard));
|
||||
assert!(narrate::heard_overlap(reaction, heard) < 0.05);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn the_group_state_reads_one_room_and_never_folds_a_direct_message_in() {
|
||||
let room = Room {
|
||||
messages: vec![message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "Eureka, door?", 2, true)],
|
||||
tail: vec![message("!dm-deru:gamecult.org", "@deru:gamecult.org", "Deru", "SECRET between us", 1, false), message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", "lunch?", 5, false)],
|
||||
..Room::default()
|
||||
};
|
||||
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
|
||||
let line = packet.context.lines().find(|line| line.starts_with("- the conversation")).unwrap_or_else(|| panic!("{}", packet.context)).to_owned();
|
||||
assert!(line.contains("Kiko with her") && line.contains("Libby"), "{line}");
|
||||
assert!(!line.contains("Deru") && !packet.context.contains("@deru"), "the direct message is its own room: {}", packet.context);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_packet_speaks_of_her_in_her_own_pronouns() {
|
||||
let mut him = state();
|
||||
him["presentation"]["pronouns"] = json!("he/him");
|
||||
let packet = packet_of(TurnKind::Chat, &him, &chat_room(), &History::default(), 1);
|
||||
assert!(packet.stimulus.starts_with("Said to him:") && packet.context.contains("Libby with him"), "{}\n{}", packet.stimulus, packet.context);
|
||||
let beat = packet_of(TurnKind::Beat, &him, &Room::default(), &History::default(), 1);
|
||||
assert!(beat.stimulus.starts_with("Nothing addressed him."), "{}", beat.stimulus);
|
||||
let mut them = state();
|
||||
them["presentation"]["pronouns"] = json!("any (they for themself)");
|
||||
let beat = packet_of(TurnKind::Beat, &them, &Room::default(), &History::default(), 1);
|
||||
assert!(beat.stimulus.starts_with("Nothing addressed them.") && !beat.stimulus.contains(" her ") , "{}", beat.stimulus);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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; 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"]);
|
||||
}
|
||||
|
||||
/// The test state with Kiko's bond and the memory about Libby marked private, and the operator's bond not.
|
||||
fn marked() -> Value {
|
||||
let mut marked = state();
|
||||
marked["affect"]["socialBonds"][1]["extensions"] = json!({ "privacy": "private" });
|
||||
marked["thoughtMemory"]["memories"][1]["tags"] = json!(["private"]);
|
||||
marked
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_marking_frames_a_fact_about_someone_absent_and_an_unmarked_one_renders_plainly() {
|
||||
// Libby is not here; Kiko and the operator are not either: only Meta speaks in #minds.
|
||||
let public = Room { messages: vec![message("#minds:gamecult.org", OPERATOR, "Meta", "how is everyone?", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let shown = |seed| packet_of(TurnKind::Chat, &marked(), &public, &History::default(), seed).context;
|
||||
let memory = (1..=40).map(shown).find(|context| context.contains("[libby-sounds]")).expect("the memory about Libby is selected on some seed");
|
||||
assert!(memory.contains("- memory [libby-sounds]: she knows privately: Libby laughed at the door fix."), "{memory}");
|
||||
let context = shown(1);
|
||||
assert!(context.contains("The operator rules on what the work is for.") && !context.contains("knows privately: The operator"), "an unmarked bond is plain: {context}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_fact_about_someone_present_in_public_is_left_out_and_plain_in_a_direct_message_with_them() {
|
||||
// Kiko is here, in #minds: her marked bond's summary is left out, and no hint of it remains.
|
||||
let public = Room { messages: vec![message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "afternoon", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &marked(), &public, &History::default(), 1);
|
||||
let line = packet.context.lines().find(|line| line.starts_with("- bond [bond-kiko]")).unwrap_or_else(|| panic!("{}", packet.context)).to_owned();
|
||||
assert!(!line.contains("massaging the pipeline") && !line.contains("privately"), "{line}");
|
||||
// In a direct message with Kiko it is plain.
|
||||
let dm = Room { messages: vec![message("!dm-kiko:gamecult.org", "@kiko:gamecult.org", "Kiko", "hey", 2, true)], here: Some("!dm-kiko:gamecult.org".into()), direct: vec!["!dm-kiko:gamecult.org".into()], ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &marked(), &dm, &History::default(), 1);
|
||||
assert!(packet.context.contains("Kiko pokes her to stop massaging the pipeline.") && !packet.context.contains("privately"), "{}", packet.context);
|
||||
}
|
||||
|
||||
/// The first context over seeds 1 to 60 that carries `marker`, and its lines that do.
|
||||
fn lines_with(state: &Value, room: &Room, kind: TurnKind, marker: &str) -> Option<Vec<String>> {
|
||||
(1..=60).map(|seed| packet_of(kind, state, room, &History::default(), seed).context).find(|context| context.contains(marker)).map(|context| context.lines().filter(|line| line.contains(marker)).map(str::to_owned).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5a_a_private_memory_naming_its_person_by_an_about_tag_is_never_plain_in_public() {
|
||||
let mut marked = state();
|
||||
marked["thoughtMemory"]["memories"] = json!([{ "id": "secret-a", "summary": "SECRETA Libby told me her diagnosis.", "createdAt": hours_ago(20), "status": "crystallized", "intensity": 1.0, "tags": ["private", "about:libby"] }]);
|
||||
let public = Room { messages: vec![message("#minds:gamecult.org", OPERATOR, "Meta", "how is Libby doing?", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
// Libby is not here: framed as known privately.
|
||||
assert_eq!(lines_with(&marked, &public, TurnKind::Chat, "SECRETA"), Some(vec!["- memory [secret-a]: she knows privately: SECRETA Libby told me her diagnosis.".to_owned()]));
|
||||
let present = Room { messages: vec![message("#minds:gamecult.org", "@libby:gamecult.org", "Libby", "hi all", 2, false)], ..public.clone() };
|
||||
assert_eq!(lines_with(&marked, &present, TurnKind::Chat, "SECRETA"), None, "left out to her face");
|
||||
// Naming no one, it is private about everyone: left out of public rooms and direct messages, plain in her own room.
|
||||
marked["thoughtMemory"]["memories"][0]["tags"] = json!(["private"]);
|
||||
assert_eq!(lines_with(&marked, &public, TurnKind::Chat, "SECRETA"), None);
|
||||
let dm = Room { messages: vec![message("!dm-libby:gamecult.org", "@libby:gamecult.org", "Libby", "hey", 2, true)], here: Some("!dm-libby:gamecult.org".into()), direct: vec!["!dm-libby:gamecult.org".into()], ..Room::default() };
|
||||
assert_eq!(lines_with(&marked, &dm, TurnKind::Chat, "SECRETA"), None);
|
||||
let own = Room { messages: vec![message("#eureka:gamecult.org", OPERATOR, "Meta", "morning", 2, false)], here: Some("#eureka:gamecult.org".into()), own: vec!["#eureka:gamecult.org".into()], ..Room::default() };
|
||||
assert_eq!(lines_with(&marked, &own, TurnKind::Chat, "SECRETA"), Some(vec!["- memory [secret-a]: SECRETA Libby told me her diagnosis.".to_owned()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5b_every_pool_honours_the_mark() {
|
||||
let mut marked = state();
|
||||
let private = json!({ "privacy": "private" });
|
||||
let libby = json!({ "id": "libby", "kind": "person" });
|
||||
marked["thoughtMemory"]["incubation"] = json!([{ "id": "w-secret", "summary": "SECRETB Whether Libby's relapse is why she went quiet.", "createdAt": hours_ago(20), "status": "active", "intensity": 1.0, "extensions": private, "target": libby }]);
|
||||
marked["affect"]["needs"] = json!([{ "id": "need-secret", "label": "SECRETN to keep Libby's relapse quiet", "intensity": 1.0, "status": "active", "extensions": private, "target": libby }]);
|
||||
marked["affect"]["doctrineStances"] = json!([{ "id": "stance-secret", "summary": "SECRETS Libby should not be on call.", "intensity": 1.0, "status": "active", "extensions": private, "target": libby }]);
|
||||
let present = Room { messages: vec![message("#minds:gamecult.org", "@libby:gamecult.org", "Libby", "hi all", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let absent = Room { messages: vec![message("#minds:gamecult.org", OPERATOR, "Meta", "hi all", 2, false)], ..present.clone() };
|
||||
for marker in ["SECRETB", "SECRETN", "SECRETS"] {
|
||||
assert_eq!(lines_with(&marked, &present, TurnKind::Chat, marker), None, "{marker} is left out with Libby here");
|
||||
let framed = lines_with(&marked, &absent, TurnKind::Chat, marker).unwrap_or_else(|| panic!("{marker} is selected on some seed"));
|
||||
assert!(framed.iter().all(|line| line.contains(&format!("she knows privately: {marker}"))), "{framed:?}");
|
||||
}
|
||||
let packet = (1..=60).map(|seed| packet_of(TurnKind::Chat, &marked, &absent, &History::default(), seed)).find(|packet| packet.context.contains("SECRETB")).unwrap();
|
||||
assert!(packet.private.iter().any(|words| words.starts_with("SECRETB")), "the Interpreter is shown what is private: {:?}", packet.private);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_q5c_a_direct_message_with_a_third_person_is_not_a_direct_message_with_her() {
|
||||
let mut marked = state();
|
||||
marked["affect"]["socialBonds"][0]["extensions"] = json!({ "privacy": "private" });
|
||||
let room = "!group-dm:gamecult.org";
|
||||
let group = Room { messages: vec![message(room, "@kiko:gamecult.org", "Kiko", "hey", 3, true), message(room, "@libby:gamecult.org", "Libby", "hey both", 2, true)], here: Some(room.into()), direct: vec![room.into()], ..Room::default() };
|
||||
let packet = packet_of(TurnKind::Chat, &marked, &group, &History::default(), 1);
|
||||
let bond = packet.context.lines().find(|line| line.starts_with("- bond [bond-libby]")).unwrap_or_else(|| panic!("{}", packet.context)).to_owned();
|
||||
assert!(!bond.contains("holds the sounds") && !bond.contains("privately"), "left out before Kiko: {bond}");
|
||||
let alone = Room { messages: vec![message(room, "@libby:gamecult.org", "Libby", "hey", 2, true)], ..group };
|
||||
assert!(packet_of(TurnKind::Chat, &marked, &alone, &History::default(), 1).context.contains("Libby holds the sounds"), "plain with Libby alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_she_said_in_a_direct_message_stays_in_it() {
|
||||
let said = |room: &str| super::select::Said { id: "said-dm".into(), room: room.into(), text: "SAIDDM I'm tired of the pipeline.".into(), at: now() - chrono::Duration::minutes(5) };
|
||||
let history = History { said: vec![said(DM_DERU)], ..History::default() };
|
||||
let shown = |room: &Room| (1..=60).any(|seed| packet_of(TurnKind::Chat, &state(), room, &history, seed).context.contains("SAIDDM"));
|
||||
assert!(!shown(&chat_room()), "never in a public packet");
|
||||
let with_deru = Room { messages: vec![message(DM_DERU, DERU, "Deru", "and?", 2, true)], here: Some(DM_DERU.into()), direct: vec![DM_DERU.into()], ..Room::default() };
|
||||
assert!(shown(&with_deru), "in its own direct message");
|
||||
let public = History { said: vec![said("#swarm:gamecult.org")], ..History::default() };
|
||||
assert!((1..=60).any(|seed| packet_of(TurnKind::Chat, &state(), &chat_room(), &public, seed).context.contains("SAIDDM")), "a public line is shared");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f6_a_mind_is_one_person_by_her_handle_or_her_full_matrix_id() {
|
||||
let kiko_here = Room { messages: vec![message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "hi all", 2, false)], here: Some("#minds:gamecult.org".into()), ..Room::default() };
|
||||
let kiko_dm = Room { messages: vec![message("!dm-kiko:gamecult.org", "@kiko:gamecult.org", "Kiko", "hey", 2, true)], here: Some("!dm-kiko:gamecult.org".into()), direct: vec!["!dm-kiko:gamecult.org".into()], ..Room::default() };
|
||||
for (spelling, memory) in [
|
||||
("target, handle", json!({ "target": { "id": "kiko", "kind": "person" }, "tags": ["private"] })),
|
||||
("target, full id", json!({ "target": { "id": "@kiko:gamecult.org", "kind": "person" }, "tags": ["private"] })),
|
||||
("about, handle", json!({ "tags": ["private", "about:kiko"] })),
|
||||
("about, full id", json!({ "tags": ["private", "about:@kiko:gamecult.org"] })),
|
||||
] {
|
||||
let mut marked = state();
|
||||
let mut item = json!({ "id": "kiko-secret", "summary": "KIKOSECRET she is leaving.", "createdAt": hours_ago(3), "status": "crystallized", "intensity": 1.0 });
|
||||
for (key, value) in memory.as_object().unwrap() {
|
||||
item[key] = value.clone();
|
||||
}
|
||||
marked["thoughtMemory"]["memories"] = json!([item]);
|
||||
assert_eq!(lines_with(&marked, &kiko_here, TurnKind::Chat, "KIKOSECRET"), None, "{spelling}: left out with Kiko here");
|
||||
assert_eq!(lines_with(&marked, &kiko_dm, TurnKind::Chat, "KIKOSECRET"), Some(vec!["- memory [kiko-secret]: KIKOSECRET she is leaving.".to_owned()]), "{spelling}: plain with Kiko alone");
|
||||
}
|
||||
// A bond keyed by her full Matrix id is her bond, and the operator's full id is `operator`.
|
||||
let mut full = state();
|
||||
full["affect"]["socialBonds"][1]["object"]["id"] = "@kiko:gamecult.org".into();
|
||||
full["affect"]["socialBonds"][2]["object"]["id"] = OPERATOR.into();
|
||||
let both = Room { messages: vec![message("#minds:gamecult.org", "@kiko:gamecult.org", "Kiko", "hi", 3, false), message("#minds:gamecult.org", OPERATOR, "Meta", "hi", 2, false)], ..kiko_here };
|
||||
let context = packet_of(TurnKind::Chat, &full, &both, &History::default(), 1).context;
|
||||
assert!(context.contains("- bond [bond-kiko] Kiko") && context.contains("- bond [bond-operator] Meta, the operator"), "{context}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soul_f7_a_value_carrying_a_mark_is_refused_not_rendered() {
|
||||
let mut marked = state();
|
||||
marked["values"] = json!([{ "id": "v-secret", "label": "SECRETVALUE", "priority": 0.9, "summary": "Never tell Kiko.", "extensions": { "privacy": "private" } }, { "id": "coherence", "label": "Coherence", "priority": 0.9, "summary": "Coherence over velocity." }]);
|
||||
let own = Room { messages: vec![message("#eureka:gamecult.org", OPERATOR, "Meta", "morning", 2, false)], here: Some("#eureka:gamecult.org".into()), own: vec!["#eureka:gamecult.org".into()], ..Room::default() };
|
||||
for room in [chat_room(), own] {
|
||||
assert_eq!(lines_with(&marked, &room, TurnKind::Chat, "SECRETVALUE"), None);
|
||||
}
|
||||
assert!(lines_with(&marked, &chat_room(), TurnKind::Chat, "Coherence").is_some(), "an unmarked value still renders");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
//! `persona-tuning.toml`: every knob of the Select stage and the Projector, read at each wake.
|
||||
//! `persona-tuning.toml`: every knob of the Select stage, the Projector and the Persona stage, read at each wake.
|
||||
//!
|
||||
//! The file is optional. Absent, the code's defaults hold and the source reads `defaults`; present, every key it
|
||||
//! names overrides one default and any key the code does not know refuses the file, so a mistyped experiment fails
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
//! The SHA-256 carried with every packet is of the effective tuning, serialized whole with its defaults: a file that
|
||||
//! spells out the defaults hashes as no file does, and two builds whose defaults differ hash differently.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
|
@ -17,8 +18,13 @@ use sha2::{Digest, Sha256};
|
|||
pub const TUNING_ROOT: &str = "/etc/gamecult/minds";
|
||||
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. 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, 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.";
|
||||
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 context room the fixed slots need beside the identity: the hour and the mood lines always fit.
|
||||
const FIXED_ROOM: usize = 256;
|
||||
|
|
@ -32,13 +38,48 @@ const ADDRESSED_RANGE: std::ops::RangeInclusive<usize> = 1024..=64 * 1024;
|
|||
const PART_BYTES_MAX: usize = 32 * 1024;
|
||||
/// The most words a lived stream may be given: a thin moment gets a thin stream, and no budget needs a book.
|
||||
const WORDS_MAX: usize = 2000;
|
||||
/// The most room lines the group state reads: a recent window, not the room's history.
|
||||
const GROUP_LINES_MAX: usize = 40;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
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
|
||||
/// another person. A file's table replaces this one whole; anyone not listed is they/them.
|
||||
pub pronouns: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// The swarm's people as of 2026-11-20 (operator's word): she for the operator and five Minds, he for Heimdall and Deru,
|
||||
/// any for Void, rendered they/them.
|
||||
const PRONOUNS: [(&str, &str); 10] = [
|
||||
("@meta:gamecult.org", "she/her"),
|
||||
("@libby:gamecult.org", "she/her"),
|
||||
("@kiko:gamecult.org", "she/her"),
|
||||
("@aqua:gamecult.org", "she/her"),
|
||||
("@weksa:gamecult.org", "she/her"),
|
||||
("@nibu:gamecult.org", "she/her"),
|
||||
("@eureka:gamecult.org", "she/her"),
|
||||
("@heimdall:gamecult.org", "he/him"),
|
||||
("@void:gamecult.org", "they/them (any pronouns)"),
|
||||
("@deru:gamecult.org", "he/him"),
|
||||
];
|
||||
|
||||
impl Default for Tuning {
|
||||
fn default() -> Self {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Projector's call: its model, its domain guidance and its word budgets.
|
||||
|
|
@ -53,6 +94,15 @@ pub struct ProjectorTuning {
|
|||
pub beat_words: usize,
|
||||
}
|
||||
|
||||
/// The Persona stage's call: its model, its voice and setting guidance and its word budget (map section 3.2).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct PersonaTuning {
|
||||
pub model: String,
|
||||
pub guidance: String,
|
||||
pub words: usize,
|
||||
}
|
||||
|
||||
/// The selection: its temperature and inclusion, its budgets, its half-life, the freshness decay and the pool caps.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
|
|
@ -83,6 +133,14 @@ pub struct SelectTuning {
|
|||
pub people_full: usize,
|
||||
/// The room lines a beat shows.
|
||||
pub beat_tail_lines: usize,
|
||||
/// The group-state slot: who has been talking to whom, how long since a human spoke, what is addressed to her or
|
||||
/// open to anyone, and how long the run of Mind lines is (prior art: group state in the prompt is what lets a
|
||||
/// participant judge whether to speak).
|
||||
pub group_state: bool,
|
||||
/// The room lines the group state reads.
|
||||
pub group_lines: usize,
|
||||
/// The group-state slot's bytes.
|
||||
pub group_bytes: usize,
|
||||
pub caps: PoolCaps,
|
||||
}
|
||||
|
||||
|
|
@ -116,6 +174,25 @@ impl Default for ProjectorTuning {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl Default for InterpreterTuning {
|
||||
fn default() -> Self {
|
||||
Self { model: "claude-sonnet-5-5".into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PersonaTuning {
|
||||
fn default() -> Self {
|
||||
Self { model: "claude-sonnet-5-5".into(), guidance: PERSONA_GUIDANCE.into(), words: 180 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SelectTuning {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
|
@ -133,6 +210,9 @@ impl Default for SelectTuning {
|
|||
freshness_window: 5,
|
||||
people_full: 2,
|
||||
beat_tail_lines: 6,
|
||||
group_state: true,
|
||||
group_lines: 12,
|
||||
group_bytes: 360,
|
||||
caps: PoolCaps::default(),
|
||||
}
|
||||
}
|
||||
|
|
@ -161,6 +241,12 @@ 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");
|
||||
}
|
||||
if !ADDRESSED_RANGE.contains(&select.addressed_bytes) {
|
||||
bail!("select.addressed_bytes must be from {} to {}, not {}", ADDRESSED_RANGE.start(), ADDRESSED_RANGE.end(), select.addressed_bytes);
|
||||
}
|
||||
|
|
@ -180,8 +266,11 @@ impl Tuning {
|
|||
("select.identity_bytes", select.identity_bytes),
|
||||
("select.bond_summary_bytes", select.bond_summary_bytes),
|
||||
("select.item_bytes", select.item_bytes),
|
||||
("select.group_lines", select.group_lines),
|
||||
("select.group_bytes", select.group_bytes),
|
||||
("projector.words", self.projector.words),
|
||||
("projector.beat_words", self.projector.beat_words),
|
||||
("persona.words", self.persona.words),
|
||||
] {
|
||||
if bytes == 0 {
|
||||
bail!("{name} must be above 0");
|
||||
|
|
@ -194,13 +283,18 @@ impl Tuning {
|
|||
("select.identity_bytes", select.identity_bytes),
|
||||
("select.bond_summary_bytes", select.bond_summary_bytes),
|
||||
("select.item_bytes", select.item_bytes),
|
||||
("select.group_bytes", select.group_bytes),
|
||||
("projector.guidance", self.projector.guidance.len()),
|
||||
("persona.guidance", self.persona.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");
|
||||
}
|
||||
}
|
||||
for (name, words) in [("projector.words", self.projector.words), ("projector.beat_words", self.projector.beat_words)] {
|
||||
if select.group_lines > GROUP_LINES_MAX {
|
||||
bail!("select.group_lines must be at most {GROUP_LINES_MAX}, not {}", select.group_lines);
|
||||
}
|
||||
for (name, words) in [("projector.words", self.projector.words), ("projector.beat_words", self.projector.beat_words), ("persona.words", self.persona.words)] {
|
||||
if words > WORDS_MAX {
|
||||
bail!("{name} must be at most {WORDS_MAX}, not {words}");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,3 +62,37 @@ fn the_retired_max_turns_flag_is_refused_and_its_value_is_not_echoed() {
|
|||
assert_eq!(output.status.code(), Some(2), "{stderr}");
|
||||
assert!(stderr.contains("usage") && !stderr.contains("canary-turns"), "{stderr}");
|
||||
}
|
||||
|
||||
/// The harness's read-only proof at the binary: with a room fixture and a state file, `project` runs with no persona.env,
|
||||
/// no mouth and the daemon's endpoint unreachable, and never needs them.
|
||||
#[test]
|
||||
fn project_over_a_room_fixture_and_a_state_file_needs_no_daemon_and_no_mouth() {
|
||||
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/harness");
|
||||
let room = fixtures.join("rooms/mind-teases.toml");
|
||||
let state = fixtures.join("states/control.json");
|
||||
let args = ["project", "--instance", "eureka", "--room", room.to_str().unwrap(), "--state", state.to_str().unwrap(), "--select-only"];
|
||||
// Nothing listens on the discard port: a read of her stored state would fail the run.
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_mind-persona")).args(args).env_clear().env("HUGINN_ENDPOINT", "rudp://127.0.0.1:9").env("MIND_PERSONA_TUNING", "/nonexistent/persona-tuning.toml").output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr));
|
||||
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!((report["state"].as_str(), report["persona_receipt"].is_null()), (Some("given"), true), "{report}");
|
||||
assert!(report["packet"]["identity"].as_str().unwrap().starts_with("Tobiah Fenn"), "{report}");
|
||||
assert!(report["packet"]["stimulus"].as_str().unwrap().contains("Said to him"), "Kiko's tagged reply is for him, in his own pronouns: {report}");
|
||||
// Without any endpoint at all it runs the same.
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_mind-persona")).args(args).env_clear().env("MIND_PERSONA_TUNING", "/nonexistent/persona-tuning.toml").output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_state_file_a_put_would_refuse_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/harness");
|
||||
let mut state: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(fixtures.join("states/control.json")).unwrap()).unwrap();
|
||||
state["personaId"] = "libby".into();
|
||||
let file = dir.path().join("foreign.json");
|
||||
std::fs::write(&file, state.to_string()).unwrap();
|
||||
let room = fixtures.join("rooms/quiet-beat.toml");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_mind-persona")).args(["project", "--instance", "eureka", "--room", room.to_str().unwrap(), "--state", file.to_str().unwrap(), "--select-only"]).env_clear().output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
assert!(text(&output.stderr).contains("refused by a put"), "{}", text(&output.stderr));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -107,6 +107,7 @@ mind_body::chat_rudp: impl RudpChat: fn reply_defects (& self) -> usize
|
|||
mind_body::chat_rudp: impl RudpChat: fn with_reply_link (mut self , on : bool) -> Self
|
||||
mind_body::chat_rudp: struct RudpChat pub-fields[]
|
||||
mind_body::cli: fn instance_and_endpoint (args : & [String] , env_endpoint : Option < String > , usage : & str) -> Result < (Slug , SocketAddr) >
|
||||
mind_body::cli: fn instance_and_maybe_endpoint (args : & [String] , env_endpoint : Option < String > , usage : & str) -> Result < (Slug , Option < SocketAddr >) >
|
||||
mind_body::cli: fn operator_name (sudo_user : Option < String > , user : Option < String >) -> String
|
||||
mind_body::cli: fn run (args : & [String] , root : & Path , set_by : & str , now : DateTime < Utc > , out : & mut impl Write , stop_units : & mut dyn FnMut (StopScope < '_ >) -> Result < () > ,) -> Result < () >
|
||||
mind_body::connector: fn render_plan (windows : & [PlanQuota] , _now_ms : u64) -> String
|
||||
|
|
@ -152,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 > >
|
||||
|
|
@ -160,6 +162,7 @@ mind_body::heartbeat: impl HeartbeatView for FileStore
|
|||
mind_body::heartbeat: impl PersonaId
|
||||
mind_body::heartbeat: impl PersonaId: fn parse (spec : & str) -> Result < Self >
|
||||
mind_body::heartbeat: impl Row < '_ >
|
||||
mind_body::heartbeat: impl Speaker
|
||||
mind_body::heartbeat: impl Store for FileStore
|
||||
mind_body::heartbeat: impl fmt :: Display for Outcome
|
||||
mind_body::heartbeat: impl fmt :: Display for PollTrace
|
||||
|
|
@ -232,11 +235,13 @@ 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 , 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
|
||||
mind_body::projection: impl PersonaSource for HuginnPersonaSource
|
||||
mind_body::projection: impl< T : Chat > MouthReader for T
|
||||
mind_body::projection: mod harness
|
||||
mind_body::projection: pub trait MouthReader { fn pending (& self) -> Result < ChatPending > ; }
|
||||
mind_body::projection: pub trait PersonaSource { fn persona (& self) -> Result < (Value , String) > ; }
|
||||
mind_body::projection: pub use narrate :: { Answer , Failed , KitModel , Model , Spent , connector_key } ;
|
||||
|
|
@ -244,7 +249,21 @@ 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]
|
||||
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 >
|
||||
mind_body::projection::harness: impl Fixture
|
||||
mind_body::projection::harness: impl Fixture: fn addressee (& self) -> Option < & dyn HeartbeatView >
|
||||
mind_body::projection::harness: impl Fixture: fn load (path : & Path) -> Result < Self >
|
||||
mind_body::projection::harness: impl Fixture: fn parse (text : & str) -> Result < Self >
|
||||
mind_body::projection::harness: impl HeartbeatView for Fixture
|
||||
mind_body::projection::harness: impl Line
|
||||
mind_body::projection::harness: impl MouthReader for Fixture
|
||||
mind_body::projection::harness: pub use super :: simulate :: simulate ;
|
||||
mind_body::projection::harness: struct Fixture # [derive (Clone , Debug)] pub-fields[her: String, names: Vec < String >, kind: TurnKind, now: DateTime < Utc >, here: Option < String >, operators: Vec < String >, minds: Vec < String >, last_heard: Vec < (String , u64) >]
|
||||
mind_body::projection::harness: struct Harness< 'a > pub-fields[instance: String, persona: Option < & 'a dyn PersonaSource >, model: Option < & 'a dyn Model >, tuning: PathBuf]
|
||||
mind_body::projection::harness: struct Message # [derive (Clone , Debug , Deserialize)] pub-fields[from: String, name: String, room: String, ago: Option < String >, round: Option < usize >, says: String, new: bool, tag: bool, mentions: Vec < String >, dm: bool, to: Option < String >, follow_up: bool, reply_to: Option < usize >]
|
||||
mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String >
|
||||
mind_body::projection::narrate: impl Failed
|
||||
mind_body::projection::narrate: impl KitModel
|
||||
|
|
@ -256,26 +275,35 @@ mind_body::projection::narrate: struct Answer # [derive (Clone , Debug , Partial
|
|||
mind_body::projection::narrate: struct Failed # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[reason: String, usage: Option < Spent >]
|
||||
mind_body::projection::narrate: struct KitModel pub-fields[]
|
||||
mind_body::projection::narrate: struct Spent # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[model: String, input_tokens: u64, output_tokens: u64, cache_read_tokens: u64, cache_write_tokens: u64, reasoning_tokens: Option < u64 >]
|
||||
mind_body::projection::select: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize)] # [serde (rename_all = "snake_case")] pub enum TurnKind { Chat , Beat , FollowUp , Reflection , }
|
||||
mind_body::projection::select: # [derive (Clone , Copy , Debug , PartialEq , Eq , Serialize , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum TurnKind { Chat , Beat , FollowUp , Reflection , }
|
||||
mind_body::projection::select: impl Addressed < '_ >
|
||||
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 < '_ >
|
||||
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
|
||||
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]
|
||||
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, caps: PoolCaps]
|
||||
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , Default , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, select: SelectTuning, lens: LensWeights]
|
||||
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, 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
|
||||
|
|
|
|||
Loading…
Reference in a new issue