diff --git a/Cargo.lock b/Cargo.lock index d3d6ea9..5beb5cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -350,26 +350,6 @@ dependencies = [ "cipher", ] -[[package]] -name = "cultcache-rs" -version = "0.3.1" -source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" -dependencies = [ - "anyhow", - "chrono", - "cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)", - "fs2", - "redb", - "rmp-serde", - "serde", - "serde_bytes", - "serde_json", - "serde_stacker", - "stacker", - "uuid", - "windows-sys 0.59.0", -] - [[package]] name = "cultcache-rs" version = "0.3.1" @@ -391,10 +371,30 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "cultcache-rs" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +dependencies = [ + "anyhow", + "chrono", + "cultcache-rs-derive 0.2.0 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)", + "fs2", + "redb", + "rmp-serde", + "serde", + "serde_bytes", + "serde_json", + "serde_stacker", + "stacker", + "uuid", + "windows-sys 0.59.0", +] + [[package]] name = "cultcache-rs-derive" version = "0.2.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" +source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" dependencies = [ "proc-macro2", "quote", @@ -404,7 +404,7 @@ dependencies = [ [[package]] name = "cultcache-rs-derive" version = "0.2.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" +source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23" dependencies = [ "proc-macro2", "quote", @@ -851,16 +851,6 @@ dependencies = [ "polyval", ] -[[package]] -name = "ghostlight-persona-projection" -version = "0.1.0" -source = "git+https://github.com/GameCult/Ghostlight.git?rev=c43eb54962ed4a09cc737ecac73a16b0d7ce62b4#c43eb54962ed4a09cc737ecac73a16b0d7ce62b4" -dependencies = [ - "serde", - "sha2", - "unicode-segmentation", -] - [[package]] name = "hashbrown" version = "0.17.1" @@ -973,16 +963,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown", -] - [[package]] name = "inout" version = "0.1.4" @@ -1118,7 +1098,6 @@ dependencies = [ "cultnet-rs 0.3.0", "eureka-pipeline", "eureka-state", - "ghostlight-persona-projection", "huginn-mind", "libc", "model-connector", @@ -1131,9 +1110,7 @@ dependencies = [ "sha2", "syn 2.0.119", "tempfile", - "toml", "unicode-general-category", - "unicode-segmentation", "uuid", ] @@ -1144,7 +1121,6 @@ source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev= dependencies = [ "aes-gcm", "base64", - "cultcache-rs 0.3.1 (git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23)", "cultnet-rs 0.2.0", "rand_core 0.6.4", "rmp-serde", @@ -1708,15 +1684,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "serde_spanned" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" -dependencies = [ - "serde_core", -] - [[package]] name = "serde_stacker" version = "0.1.14" @@ -1955,45 +1922,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "toml" -version = "0.9.12+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" -dependencies = [ - "indexmap", - "serde_core", - "serde_spanned", - "toml_datetime", - "toml_parser", - "toml_writer", - "winnow 0.7.15", -] - -[[package]] -name = "toml_datetime" -version = "0.7.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_parser" -version = "1.1.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" -dependencies = [ - "winnow 1.0.5", -] - -[[package]] -name = "toml_writer" -version = "1.2.0+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" - [[package]] name = "tracing" version = "0.1.44" @@ -2052,12 +1980,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - [[package]] name = "universal-hash" version = "0.5.1" @@ -2371,18 +2293,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" - -[[package]] -name = "winnow" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" - [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/README.md b/README.md index b3e08be..9fea14c 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ edits `.cc` state. Huginn reads and writes minds. ## Layout -A Cargo workspace of five crates (`crates/eureka-pipeline` holds the document shapes and keys, `crates/mind-body` the control store, unit launcher, `mind-heartbeat`, the inert `mind-persona` organ and the `mind-self-run` actuator; the three below are the mind, the daemon and the client): +A Cargo workspace of five crates (`crates/eureka-pipeline` holds the document shapes and keys, `crates/mind-body` the control store, launch primitive and `mind-heartbeat` timeline; the three below are the mind, the daemon and the client): - `crates/huginn-mind`: storage, identity, admission, and queries and derived status over memory documents. diff --git a/crates/eureka-state/tests/common/mod.rs b/crates/eureka-state/tests/common/mod.rs index 00dd9e6..2358f09 100644 --- a/crates/eureka-state/tests/common/mod.rs +++ b/crates/eureka-state/tests/common/mod.rs @@ -172,7 +172,7 @@ pub fn serve + Send + 'static>( let loop_stopping = Arc::clone(&stopping); let registry = schema_registry().unwrap(); let thread = std::thread::spawn(move || { - run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default()).unwrap(); + run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default()).unwrap(); }); Server { addr, stopping, thread: Some(thread), ended: Arc::default(), _root: Some(root) } } diff --git a/crates/huginn-daemon/src/daemon.rs b/crates/huginn-daemon/src/daemon.rs index 03cc29c..1be6aae 100644 --- a/crates/huginn-daemon/src/daemon.rs +++ b/crates/huginn-daemon/src/daemon.rs @@ -109,17 +109,6 @@ impl Handled { } } -/// Which RUDP listener a request arrived on. `Full` is `--bind`, which the -/// faculties that write the mind reach. `Persona` is `--persona-bind`, the -/// only listener a Persona's uid can reach (the host fence decides that): it -/// answers what `HuginnMindRequest::reaches_persona_door` accepts and refuses -/// the rest with `MindRefusal::NotThisDoor` before the mind is asked. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Door { - Full, - Persona, -} - /// The door checks an account id; the Mind's desk calls take it as the text it is. fn short_id(id: AccountId) -> Short { Short(id.0) @@ -188,16 +177,6 @@ impl> Daemon { runtime_id(self.mind.instance()) } - /// One request as it arrived at `door`: a request the door does not - /// answer is refused before the mind sees it, and every other goes to - /// `handle`. The wire reaches the mind only through here. - pub fn handle_at(&mut self, door: Door, request: HuginnMindRequest, now: DateTime) -> Handled { - if door == Door::Persona && !request.reaches_persona_door() { - return Handled::Answered(HuginnMindResponse::Refused(MindRefusal::NotThisDoor)); - } - self.handle(request, now) - } - /// One request, one answer, or a search to finish. `Admit` goes to the mind whole, because the /// batch declares its own instance and admission's A1 is the check. Every /// other request names an instance: `require_instance` now applies the @@ -1032,117 +1011,6 @@ pub(crate) mod tests { assert_eq!(status(&mut daemon).persona, huginn_mind::wire::PersonaStatus::Absent); } - /// The persona door refuses an admission before the mind sees it, so the - /// store is unchanged, and answers the reads and her own persona put; the - /// full door admits the same batch. - #[test] - fn the_persona_door_refuses_an_admission_and_answers_reads_and_her_persona() { - let (_root, mut daemon) = seeded(); - let before = status(&mut daemon); - let admit = || HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])); - assert_eq!( - daemon.handle_at(Door::Persona, admit(), now()).answered(), - HuginnMindResponse::Refused(MindRefusal::NotThisDoor) - ); - assert_eq!(status(&mut daemon), before, "nothing was written"); - - let state = serde_json::json!({ - "schemaVersion": "gamecult.persona_state.v0", - "provenance": { - "sourceSystem": "huginn", "sourceDocumentId": INSTANCE, "sourceUpdatedAt": "2026-11-19T10:00:00Z", - "exportedAt": "2026-11-19T10:00:00Z", "authority": "canonical" - }, - "personaId": INSTANCE, - "publicName": "Test Persona", - "presentation": { "voiceSummary": "plain" }, - "activationProfile": { - "underlyingOrganization": {}, "stableDispositions": {}, "behavioralDimensions": {}, - "presentationStrategy": {}, "voiceStyle": {}, "situationalState": {} - }, - "thoughtMemory": { "shortTerm": [], "memories": [], "incubation": [] }, - "agencyPressure": { "pressures": [] }, - "candidateActions": { "actions": [] }, - "affect": { - "needs": [], "socialBonds": [], "statusReads": [], "moodDimensions": [], - "socialBiases": [], "doctrineStances": [] - }, - "updatedAt": "2026-11-19T10:00:00Z" - }); - let put = HuginnMindRequest::PersonaPut { - instance: slug(INSTANCE), - provenance: provenance(), - state, - expected_updated_at: None, - }; - assert!(matches!( - daemon.handle_at(Door::Persona, put, now()).answered(), - HuginnMindResponse::PersonaPut(huginn_mind::PersonaPutOutcome::Committed { .. }) - )); - assert!(matches!( - daemon.handle_at(Door::Persona, HuginnMindRequest::PersonaGet { instance: slug(INSTANCE) }, now()).answered(), - HuginnMindResponse::Persona(Some(_)) - )); - let query = HuginnMindRequest::Query { instance: slug(INSTANCE), selection: Selection::default(), semantic: None }; - let HuginnMindResponse::Query(page) = daemon.handle_at(Door::Persona, query, now()).answered() else { - panic!("a query answers a page at the persona door") - }; - let id = match page.items { - PipelinePageItems::Headers(items) => items[0].id.clone(), - PipelinePageItems::Documents(items) => items[0].id.clone(), - }; - assert!(matches!( - daemon.handle_at(Door::Persona, HuginnMindRequest::View { instance: slug(INSTANCE), id }, now()).answered(), - HuginnMindResponse::View(Some(_)) - )); - assert_eq!(status(&mut daemon).documents, before.documents, "a persona put writes no pipeline document"); - - assert!( - matches!(daemon.handle_at(Door::Full, admit(), now()).answered(), HuginnMindResponse::Admit(_)), - "the full door hands the same batch to admission" - ); - } - - /// Every read the persona door answers reaches the mind there: none of the - /// source, chat, activity and roots reads is refused as `NotThisDoor`. - /// What the mind then says (a search, or `Unavailable` with no index or - /// forge) is the mind's, the same at either door. - #[test] - fn the_persona_door_hands_every_other_read_to_the_mind() { - use huginn_mind::wire::{ChatWindowQuery, SourceQuery}; - let (_root, mut daemon) = seeded(); - let reads = [ - HuginnMindRequest::SearchSources { - instance: slug(INSTANCE), - query: SourceQuery { text: Line("reconcile".into()), texts: vec![], top_k: 5, repo: None, front: false }, - }, - HuginnMindRequest::SearchChat { - instance: slug(INSTANCE), - query: ChatQuery { texts: vec![Line("release".into())], rooms: vec![], after_ms: None, before_ms: None, top_k: 5 }, - }, - HuginnMindRequest::ChatWindow { - instance: slug(INSTANCE), - query: ChatWindowQuery { event_id: Short("$a".into()), before: 5, after: 0 }, - }, - HuginnMindRequest::StewardedActivity { instance: slug(INSTANCE), repos: vec![], after: None }, - HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) }, - ]; - for read in reads { - let operation = read.operation(); - let at_door = daemon.handle_at(Door::Persona, read.clone(), now()); - assert!( - !matches!(at_door, Handled::Answered(HuginnMindResponse::Refused(MindRefusal::NotThisDoor))), - "{operation} is refused at the persona door" - ); - if let (Handled::Answered(at_door), Handled::Answered(at_full)) = (at_door, daemon.handle_at(Door::Full, read, now())) { - assert_eq!(at_door, at_full, "{operation} answers the same at either door"); - } - } - assert!(matches!( - daemon.handle_at(Door::Persona, HuginnMindRequest::RootsTouched { instance: slug(INSTANCE) }, now()).answered(), - HuginnMindResponse::RootsTouched(_) - )); - } - /// A declared instance outside `Slug`'s grammar is refused by its own /// name, `InvalidFormat`, on the read path, before the identity /// comparison ever runs: it is not merely a foreign mind, it names no diff --git a/crates/huginn-daemon/src/desk_door_tests.rs b/crates/huginn-daemon/src/desk_door_tests.rs index d32888a..2acb80e 100644 --- a/crates/huginn-daemon/src/desk_door_tests.rs +++ b/crates/huginn-daemon/src/desk_door_tests.rs @@ -467,7 +467,7 @@ mod door_smoke { let stopping = Arc::new(AtomicBool::new(false)); let loop_stopping = Arc::clone(&stopping); let serving = std::thread::spawn(move || { - run(&mut daemon, &mut hub, None, ®istry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap(); + run(&mut daemon, &mut hub, ®istry, Some(&mut door), &loop_stopping, &ServeOptions::default()).unwrap(); }); let mut stalled = connect(&path); @@ -591,7 +591,7 @@ mod door_smoke { let registry = schema_registry().unwrap(); let mut bodies = crate::bodies::DeferredBodies::new(1 << 20, Duration::from_secs(60)); let desk = raw(MIND_SERVICE_ID, DESK_REQUEST_SCHEMA, "answer", "m-1", rmp_serde::to_vec_named(&answer("x", DeskAuthority::Operator, &["x"], wire(&hash, R1))).unwrap()); - let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, crate::daemon::Door::Full, ®istry, &mut bodies, desk, now()).reply() else { + let CultNetMessage::OperationResponse { payload_schema, diagnostics, .. } = crate::serve::answer(&mut daemon, ®istry, &mut bodies, desk, now()).reply() else { panic!("expected a response") }; assert_eq!(payload_schema, huginn_mind::envelope::FAILURE_SCHEMA); @@ -686,7 +686,6 @@ mod door_smoke { state_root: root.path().to_path_buf(), instance: slug(INSTANCE), bind: "127.0.0.1:0".parse().unwrap(), - persona_bind: None, qdrant_url: "http://127.0.0.1:1".into(), ollama_urls: vec!["http://127.0.0.1:1".into()], reserve_ollama_urls: Vec::new(), diff --git a/crates/huginn-daemon/src/main.rs b/crates/huginn-daemon/src/main.rs index 0d0ed7d..8b27ff0 100644 --- a/crates/huginn-daemon/src/main.rs +++ b/crates/huginn-daemon/src/main.rs @@ -1,5 +1,5 @@ -//! The process: open one instance's mind, bind its socket (and the persona -//! door's, when asked), serve until a stop signal. A mind that will not open ends the process with the refusal on +//! The process: open one instance's mind, bind one socket, serve until a stop +//! signal. A mind that will not open ends the process with the refusal on //! stderr and no socket ever bound. use std::sync::Arc; @@ -15,7 +15,7 @@ fn main() -> Result<()> { let options = parse_options(std::env::args().skip(1))?; let embedder = pool(&options.ollama_urls, &options.reserve_ollama_urls, &options.embedding_model); let index = QdrantIndex::new(&options.qdrant_url); - let Started { mut daemon, mut hub, mut persona, registry, mut desk } = match startup(&options, embedder, index, Backoff::default()) { + let Started { mut daemon, mut hub, registry, mut desk } = match startup(&options, embedder, index, Backoff::default()) { Ok(started) => started, Err(error) => { eprintln!("huginn-daemon refuses to serve {}: {error:#}", options.instance.0); @@ -33,11 +33,8 @@ fn main() -> Result<()> { } eprintln!("huginn-daemon serving {} on {}", options.instance.0, hub.local_addr()?); - if let Some(door) = &persona { - eprintln!("huginn-daemon serving the persona door on {}", door.local_addr()?); - } if let Some(door) = &desk { eprintln!("huginn-daemon serving the desk door on {}", door.path().display()); } - run(&mut daemon, &mut hub, persona.as_mut(), ®istry, desk.as_mut(), &stopping, &ServeOptions::default()) + run(&mut daemon, &mut hub, ®istry, desk.as_mut(), &stopping, &ServeOptions::default()) } diff --git a/crates/huginn-daemon/src/semantic_tests.rs b/crates/huginn-daemon/src/semantic_tests.rs index 98b4967..321b446 100644 --- a/crates/huginn-daemon/src/semantic_tests.rs +++ b/crates/huginn-daemon/src/semantic_tests.rs @@ -143,10 +143,9 @@ fn quick() -> Backoff { Backoff { initial: Duration::from_millis(1), max: Duration::from_millis(2), recheck: Duration::from_secs(3600), search_deadline: Duration::from_secs(30) } } -/// A daemon serving a mind over real sockets, its full door and its persona door, with the ports the test gave it. +/// A daemon serving a mind over a real socket, with the ports the test gave it. struct Harness { endpoint: String, - persona_endpoint: String, stopping: Arc, serving: Option>>, embedder: FakeEmbedder, @@ -173,31 +172,19 @@ impl Harness { let mut daemon: Daemon = Daemon::new(mind, sink); let mut hub = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap(); let endpoint = format!("rudp://{}", hub.local_addr().unwrap()); - let mut door = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap(); - let persona_endpoint = format!("rudp://{}", door.local_addr().unwrap()); let registry = schema_registry().unwrap(); let stopping = Arc::new(AtomicBool::new(false)); let loop_stopping = Arc::clone(&stopping); let options = ServeOptions::default(); - let serving = - std::thread::spawn(move || run(&mut daemon, &mut hub, Some(&mut door), ®istry, None, &loop_stopping, &options)); - Self { endpoint, persona_endpoint, stopping, serving: Some(serving), embedder, index, _root: root } + let serving = std::thread::spawn(move || run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &options)); + Self { endpoint, stopping, serving: Some(serving), embedder, index, _root: root } } fn client(&self) -> Client { - Self::client_at(&self.endpoint) - } - - /// A client of the persona door. - fn persona_client(&self) -> Client { - Self::client_at(&self.persona_endpoint) - } - - fn client_at(endpoint: &str) -> Client { let mut client = CultMesh::create_rudp_client_for_endpoint( "semantic-test".to_string(), CULTNET_OPERATION_CONNECTION_ID, - endpoint, + &self.endpoint, CultMeshRudpSocketOptions::default(), ) .unwrap(); @@ -285,19 +272,8 @@ fn healthy() -> Harness { /// the members. #[test] fn a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits() { - a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(Harness::client); -} - -/// The same semantic read asked at the persona door: the search is held while the index works, and its answer leaves by -/// the persona door's own hub to the session that asked there. -#[test] -fn a_semantic_query_at_the_persona_door_is_answered_through_the_persona_door() { - a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(Harness::persona_client); -} - -fn a_semantic_query_returns_only_documents_the_mind_holds_and_the_selection_admits_at(client_of: fn(&Harness) -> Client) { let harness = healthy(); - let mut client = client_of(&harness); + let mut client = harness.client(); until_index(&mut client, "Current", |status| *status == IndexStatus::Current); harness.index.state.lock().unwrap().hits = vec![ hit("question", id("question", "Q1"), 0.95), diff --git a/crates/huginn-daemon/src/serve.rs b/crates/huginn-daemon/src/serve.rs index a0296a5..22c27df 100644 --- a/crates/huginn-daemon/src/serve.rs +++ b/crates/huginn-daemon/src/serve.rs @@ -78,7 +78,7 @@ use huginn_mind::{Mind, MindRefusal, MindStore, OwnedRedbMessagePackBackingStore use crate::bodies::{ DEFERRED_BUDGET_BYTES, DEFERRED_CHUNK_BYTES, DeferredBodies, }; -use crate::daemon::{Daemon, Door, Handled, IndexSink, Search, SearchTicket, runtime_id}; +use crate::daemon::{Daemon, Handled, IndexSink, Search, SearchTicket, runtime_id}; use crate::desk_door::{DeskDoor, bind_desk}; use huginn_mind::envelope::{OperationFailure, decode_request, encode_failure, encode_response}; use huginn_mind::MAX_DEFERRED_BODY_BYTES; @@ -111,10 +111,6 @@ pub struct Options { pub state_root: PathBuf, pub instance: Slug, pub bind: SocketAddr, - /// The persona door (`--persona-bind`): a second RUDP listener answering - /// only what `HuginnMindRequest::reaches_persona_door` accepts. Absent, - /// the daemon has no persona door. - pub persona_bind: Option, pub qdrant_url: String, /// The GPU hosts: all take embedding at once. One is the plain case. pub ollama_urls: Vec, @@ -138,7 +134,7 @@ pub struct DeskOptions { /// Exactly `--state-root`, `--instance`, `--bind`, `--qdrant-url`, /// `--ollama-url` and `--embedding-model`, each required, each once, except /// `--ollama-url`, which repeats for each GPU host, and the optional -/// `--reserve-ollama-url`, which repeats for each CPU host, and the optional `--forge-url` and `--persona-bind` (an ip:port other than `--bind`), each once, and the optional pair `--desk-socket` (an absolute path) and `--desk-peer-uid` (a uid other than 0), both or neither, each once. The URLs are plain +/// `--reserve-ollama-url`, which repeats for each CPU host, and the optional `--forge-url`, once, and the optional pair `--desk-socket` (an absolute path) and `--desk-peer-uid` (a uid other than 0), both or neither, each once. The URLs are plain /// `http://`: this build carries no TLS. pub fn parse_options(args: impl Iterator) -> Result { let mut args = args; @@ -147,7 +143,7 @@ pub fn parse_options(args: impl Iterator) -> Result { while let Some(name) = args.next() { let name = name.strip_prefix("--").with_context(|| format!("expected --option, got {name:?}"))?; ensure!( - matches!(name, "state-root" | "instance" | "bind" | "persona-bind" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url" | "desk-socket" | "desk-peer-uid"), + matches!(name, "state-root" | "instance" | "bind" | "qdrant-url" | "ollama-url" | "reserve-ollama-url" | "embedding-model" | "forge-url" | "desk-socket" | "desk-peer-uid"), "unsupported Huginn option --{name}" ); let value = args.next().with_context(|| format!("missing value for --{name}"))?; @@ -171,20 +167,10 @@ pub fn parse_options(args: impl Iterator) -> Result { }; let embedding_model = take("embedding-model")?; ensure!(!embedding_model.is_empty(), "--embedding-model must name a model"); - let bind: SocketAddr = bind.parse().with_context(|| format!("--bind must be an ip:port, got {bind:?}"))?; - let persona_bind = match values.get("persona-bind") { - None => None, - Some(door) => { - let door: SocketAddr = door.parse().with_context(|| format!("--persona-bind must be an ip:port, got {door:?}"))?; - ensure!(door != bind, "--persona-bind must not be --bind: the persona door is its own listener"); - Some(door) - } - }; Ok(Options { state_root, instance: Slug(take("instance")?), - bind, - persona_bind, + bind: bind.parse().with_context(|| format!("--bind must be an ip:port, got {bind:?}"))?, qdrant_url: url("qdrant-url")?, ollama_urls: { ensure!(!ollama_urls.is_empty(), "--ollama-url is required; repeat it for each GPU host"); @@ -220,7 +206,6 @@ where { let mind = Mind::open(&options.state_root, &options.instance)?; let hub = bind(options.bind, &runtime_id(&options.instance))?; - let persona = options.persona_bind.map(|door| bind(door, &runtime_id(&options.instance))).transpose()?; let desk = options.desk.as_ref().map(|desk| bind_desk(&desk.socket, desk.peer_uid)).transpose()?; let startup_entries = mind.index_entries(None)?; let sink = WorkerSink::spawn(embedder, index, &options.instance, mind.genesis_receipt_id()?, startup_entries, backoff); @@ -229,16 +214,14 @@ where Some(url) => daemon.with_forge(crate::sources::forge::HttpForge::new(url)), None => daemon, }; - Ok(Started { daemon, hub, persona, registry: schema_registry()?, desk }) + Ok(Started { daemon, hub, registry: schema_registry()?, desk }) } /// What `startup` hands the loop: the daemon over the opened mind, the bound RUDP hub, the -/// persona door's hub when one was asked for, the catalog both RUDP doors advertise, and the -/// desk door when one was asked for. +/// catalog the RUDP door advertises, and the desk door when one was asked for. pub struct Started { pub daemon: Daemon, pub hub: CultNetRudpServerHub, - pub persona: Option, pub registry: CultNetSchemaRegistry, pub desk: Option, } @@ -338,14 +321,12 @@ impl Routed { } /// One message in, one message out, or a search to wait for. Nothing here -/// reaches a mind except through `Daemon::handle_at`, at the `door` the message -/// arrived on, and an envelope that does +/// reaches a mind except through `Daemon::handle`, and an envelope that does /// not decode never gets that far. A chunk request is answered from `bodies` /// alone, on the session it came in on; every operation's reply leaves through /// `respond`. pub fn answer>( daemon: &mut Daemon, - door: Door, registry: &CultNetSchemaRegistry, bodies: &mut DeferredBodies, message: CultNetMessage, @@ -364,7 +345,7 @@ pub fn answer>( CultNetMessage::OperationRequest { message_id, operation, .. } => match decode_request(&message) { Ok((message_id, request)) => { let operation = request.operation(); - match daemon.handle_at(door, request, now) { + match daemon.handle(request, now) { Handled::Answered(response) => respond(&response, &message_id, operation, &runtime_id, bodies, now), Handled::Searching(search) => return Routed::Search { message_id, operation, search }, } @@ -502,11 +483,9 @@ fn deliver( deferred } -/// A semantic query on its way through the index: who asked, at which door, -/// what to call the answer, the search to finish, and when the client stops -/// being promised one. +/// A semantic query on its way through the index: who asked, what to call the +/// answer, the search to finish, and when the client stops being promised one. struct Waiting { - door: Door, session: CultNetRudpServerSessionContext, message_id: String, operation: &'static str, @@ -515,11 +494,9 @@ struct Waiting { } /// Until `stopping`: expire what timed out, resend what was not acknowledged, -/// answer every frame waiting on either RUDP door's socket, then answer every -/// semantic query the index has finished or that has waited out the index's -/// own `search_deadline`. A frame on `hub` is asked at `Door::Full`, one on -/// `persona` at `Door::Persona`, and a search's answer leaves by the door it -/// came in at. A semantic +/// answer every frame waiting on the socket, then answer every semantic query +/// the index has finished or that has waited out the index's own +/// `search_deadline`. A semantic /// query is never answered inline: `answer` hands back a `Search`, the loop /// holds it beside its session and goes on serving, and the embedder and the /// vector store are the worker's to wait on. A hostile datagram and a departed @@ -528,18 +505,51 @@ struct Waiting { pub fn run>( daemon: &mut Daemon, hub: &mut CultNetRudpServerHub, - mut persona: Option<&mut CultNetRudpServerHub>, registry: &CultNetSchemaRegistry, mut desk: Option<&mut DeskDoor>, stopping: &AtomicBool, options: &ServeOptions, ) -> Result<()> { + let timeout_ms = options.session_timeout.as_millis() as u64; let mut bodies = DeferredBodies::new(DEFERRED_BUDGET_BYTES, options.deferred_ttl); let mut waiting: BTreeMap = BTreeMap::new(); while !stopping.load(Ordering::Relaxed) { - let mut served = serve_frames(daemon, hub, Door::Full, registry, &mut bodies, &mut waiting, options); - if let Some(door) = persona.as_deref_mut() { - served += serve_frames(daemon, door, Door::Persona, registry, &mut bodies, &mut waiting, options); + hub.remove_timed_out_sessions(timeout_ms); + if let Err(error) = hub.poll_resends() { + eprintln!("huginn: resending to a peer failed: {error:#}"); + } + let mut served = 0_u32; + loop { + let event = match hub.receive_event_once() { + Ok(Some(event)) => event, + Ok(None) => break, + Err(error) => { + eprintln!("huginn: a datagram was not readable and was discarded: {error:#}"); + break; + } + }; + let CultNetRudpServerEvent::Frame { session, frame } = event else { + continue; + }; + if frame.channel_id != "schema" { + continue; + } + let message = match decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) + { + Ok(message) => message, + Err(error) => { + eprintln!("huginn: a frame was not a CultNet message and was discarded: {error:#}"); + continue; + } + }; + match answer(daemon, registry, &mut bodies, message, Utc::now()) { + Routed::Reply(reply) => send(hub, &session, &reply), + Routed::Search { message_id, operation, search } => { + let until = Instant::now() + daemon.search_deadline(); + waiting.insert(search.ticket, Waiting { session, message_id, operation, search, until }); + } + } + served += 1; } let desk_served = desk.as_deref_mut().map_or(0, |door| door.serve_ready(daemon, Utc::now())); let finished = collect_searches(daemon, &waiting); @@ -548,14 +558,7 @@ pub fn run>( let Some(asked) = waiting.remove(&ticket) else { continue }; let response = daemon.finish(asked.search, found); let reply = respond(&response, &asked.message_id, asked.operation, &daemon.runtime_id(), &mut bodies, Utc::now()); - let out = match asked.door { - Door::Full => &mut *hub, - Door::Persona => match persona.as_deref_mut() { - Some(door) => door, - None => continue, - }, - }; - send(out, &asked.session, &reply); + send(hub, &asked.session, &reply); } if served == 0 && desk_served == 0 && !answered { std::thread::sleep(options.idle_sleep); @@ -564,57 +567,6 @@ pub fn run>( Ok(()) } -/// One pass over one RUDP door: expire its idle sessions, resend what it has -/// unacknowledged, and answer every frame waiting on its socket as asked at -/// `door`. Returns how many frames it answered or queued. -fn serve_frames>( - daemon: &mut Daemon, - hub: &mut CultNetRudpServerHub, - door: Door, - registry: &CultNetSchemaRegistry, - bodies: &mut DeferredBodies, - waiting: &mut BTreeMap, - options: &ServeOptions, -) -> u32 { - hub.remove_timed_out_sessions(options.session_timeout.as_millis() as u64); - if let Err(error) = hub.poll_resends() { - eprintln!("huginn: resending to a peer failed: {error:#}"); - } - let mut served = 0_u32; - loop { - let event = match hub.receive_event_once() { - Ok(Some(event)) => event, - Ok(None) => break, - Err(error) => { - eprintln!("huginn: a datagram was not readable and was discarded: {error:#}"); - break; - } - }; - let CultNetRudpServerEvent::Frame { session, frame } = event else { - continue; - }; - if frame.channel_id != "schema" { - continue; - } - let message = match decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) { - Ok(message) => message, - Err(error) => { - eprintln!("huginn: a frame was not a CultNet message and was discarded: {error:#}"); - continue; - } - }; - match answer(daemon, door, registry, bodies, message, Utc::now()) { - Routed::Reply(reply) => send(hub, &session, &reply), - Routed::Search { message_id, operation, search } => { - let until = Instant::now() + daemon.search_deadline(); - waiting.insert(search.ticket, Waiting { door, session, message_id, operation, search, until }); - } - } - served += 1; - } - served -} - /// What the index has finished, then what has waited too long: the latter as /// an `Unavailable` detail, and abandoned, so the index does not start a search /// nobody is waiting for. A search that finishes after its deadline finds @@ -728,14 +680,14 @@ mod tests { ("m-5b", request("m-5b", MIND_SERVICE_ID, "Admit", MIND_REQUEST_SCHEMA, admit), "operation-mismatch"), ]; for (id, message, code) in cases { - let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), message, now()).reply(); + let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), message, now()).reply(); assert_eq!(rejected(&reply).0, id, "the client's own correlation key is echoed"); assert_eq!(rejected(&reply).1, code); } // The sixth code, `not-an-operation-request`, is the codec's and is // pinned in `huginn_mind::envelope::tests`: `answer` never produces it, because a // message of another family is answered with `Error` instead. - let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), CultNetMessage::Error { error: "hello".into(), code: None, details: None }, now()).reply(); + let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), CultNetMessage::Error { error: "hello".into(), code: None, details: None }, now()).reply(); let CultNetMessage::Error { error, .. } = &reply else { panic!("expected an error, got {reply:?}") }; assert!( !error.is_empty() && error.contains("cultnet.operation_request.v0") && error.contains("cultnet.schema_catalog_request.v0"), @@ -747,7 +699,7 @@ mod tests { // A mind's refusal is an answer on the response schema, not a failure // of the envelope: the client decodes it as the typed refusal it is. let read = HuginnMindRequest::Query { instance: slug(OTHER), selection: Selection::default(), semantic: None }; - let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), encode_request("m-r", &read, None).unwrap(), now()).reply(); + let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), encode_request("m-r", &read, None).unwrap(), now()).reply(); let CultNetMessage::OperationResponse { status, payload_schema, .. } = &reply else { panic!("expected an operation response, got {reply:?}"); }; @@ -765,7 +717,7 @@ mod tests { schema_ids: None, kinds: None, }; - let reply = answer(&mut daemon, Door::Full, ®istry, &mut fresh_bodies(), catalog, now()).reply(); + let reply = answer(&mut daemon, ®istry, &mut fresh_bodies(), catalog, now()).reply(); let CultNetMessage::SchemaCatalogResponse { message_id, schemas } = reply else { panic!("expected a catalog response"); }; @@ -833,7 +785,7 @@ mod tests { let loop_stopping = Arc::clone(&stopping); let serving = std::thread::spawn(move || { - let result = run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default()); + let result = run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default()); (result, daemon) }); @@ -922,43 +874,6 @@ mod tests { panic!("{name} never connected"); } - /// Over loopback, the persona door's listener refuses an admission by name and answers a - /// read, and the full door's listener admits the same batch: only that admission lands. - #[test] - fn the_persona_listener_refuses_an_admission_the_full_listener_takes() { - let root = tempfile::tempdir().unwrap(); - let mut daemon = open_unindexed(root.path(), &slug(INSTANCE)).unwrap(); - let mut hub = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap(); - let mut door = bind("127.0.0.1:0".parse().unwrap(), &daemon.runtime_id()).unwrap(); - let full = format!("rudp://{}", hub.local_addr().unwrap()); - let persona = format!("rudp://{}", door.local_addr().unwrap()); - let registry = schema_registry().unwrap(); - let stopping = Arc::new(AtomicBool::new(false)); - let loop_stopping = Arc::clone(&stopping); - let serving = std::thread::spawn(move || { - let result = run(&mut daemon, &mut hub, Some(&mut door), ®istry, None, &loop_stopping, &ServeOptions::default()); - (result, daemon) - }); - - let admit = HuginnMindRequest::Admit(batch(INSTANCE, vec![identity(INSTANCE)])); - let mut her = connect(&persona, "persona"); - assert_eq!(ask(&mut her, "p-admit", &admit), HuginnMindResponse::Refused(MindRefusal::NotThisDoor)); - let HuginnMindResponse::Whoami(status) = ask(&mut her, "p-whoami", &HuginnMindRequest::Whoami) else { - panic!("the persona door answers whoami") - }; - assert_eq!(status.documents, 0, "the refused admission wrote nothing"); - let mut self_faculty = connect(&full, "full"); - assert!(matches!( - ask(&mut self_faculty, "f-admit", &admit), - HuginnMindResponse::Admit(PipelineAdmissionOutcome::Committed { .. }) - )); - - stopping.store(true, Ordering::Relaxed); - let (result, mut daemon) = serving.join().unwrap(); - result.unwrap(); - assert_eq!(documents(&mut daemon), 1, "only the full door's admission landed"); - } - /// One client admits batches that close, withdraw and re-open records while three others read /// the same mind: fresh queries, cursor walks across commits, a hop and whoami. The loop is /// serial, so every answer is one snapshot's; at quiesce each answer must equal what a fresh @@ -977,7 +892,7 @@ mod tests { let stopping = Arc::new(AtomicBool::new(false)); let loop_stopping = Arc::clone(&stopping); let serving = std::thread::spawn(move || { - let result = run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default()); + let result = run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default()); (result, daemon) }); @@ -1142,7 +1057,7 @@ mod tests { at: DateTime, ) -> CultMeshCdnArtifactManifest { let registry = schema_registry().unwrap(); - deferred_manifest(&answer(daemon, Door::Full, ®istry, bodies, encode_request(message_id, read, None).unwrap(), at).reply()) + deferred_manifest(&answer(daemon, ®istry, bodies, encode_request(message_id, read, None).unwrap(), at).reply()) } /// Whether the first chunk of a manifest is still served at an injected time. @@ -1153,7 +1068,7 @@ mod tests { at: DateTime, ) -> bool { let registry = schema_registry().unwrap(); - found(&answer(daemon, Door::Full, ®istry, bodies, chunk_request(manifest, 0), at).reply()) + found(&answer(daemon, ®istry, bodies, chunk_request(manifest, 0), at).reply()) } /// An answer larger than one send can carry is deferred to the body plane @@ -1218,7 +1133,7 @@ mod tests { let stopping = Arc::new(AtomicBool::new(false)); let loop_stopping = Arc::clone(&stopping); let serving = std::thread::spawn(move || { - let result = run(&mut daemon, &mut hub, None, ®istry, None, &loop_stopping, &ServeOptions::default()); + let result = run(&mut daemon, &mut hub, ®istry, None, &loop_stopping, &ServeOptions::default()); (result, daemon) }); @@ -1466,7 +1381,7 @@ mod tests { let manifest = ask_deferred(&mut daemon, &mut bodies, "m-v", &read, t0); assert!(manifest.chunks.len() >= 2, "the fixture needs a second chunk to serve"); let mut chunk = |index: usize, at: i64| { - answer(&mut daemon, Door::Full, ®istry, &mut bodies, chunk_request(&manifest, index), after(at)).reply() + answer(&mut daemon, ®istry, &mut bodies, chunk_request(&manifest, index), after(at)).reply() }; assert!(found(&chunk(0, 59)), "inside the TTL"); assert!(found(&chunk(1, 118)), "serving a chunk slid the expiry past the first TTL"); @@ -1479,7 +1394,7 @@ mod tests { let again = ask_deferred(&mut daemon, &mut bodies, "m-v2", &read, after(179)); assert_eq!(again.content_hash, manifest.content_hash, "the same answer is the same body"); let bytes = fetch_content(&again, MAX_DEFERRED_BODY_BYTES, |request| { - Ok(answer(&mut daemon, Door::Full, ®istry, &mut bodies, request, after(180)).reply()) + Ok(answer(&mut daemon, ®istry, &mut bodies, request, after(180)).reply()) }) .unwrap(); assert_eq!(bytes, expected); @@ -1579,7 +1494,7 @@ mod tests { ("record_key", chunk("m", "abc", &huge)), ]; for (case, message) in refused { - let reply = answer(&mut daemon, Door::Full, ®istry, &mut bodies, message, now()).reply(); + let reply = answer(&mut daemon, ®istry, &mut bodies, message, now()).reply(); let CultNetMessage::Error { error, .. } = &reply else { panic!("{case}: expected a transport error, got {reply:?}"); }; @@ -1588,9 +1503,9 @@ mod tests { } assert_eq!(documents(&mut daemon), 0); - let reply = answer(&mut daemon, Door::Full, ®istry, &mut bodies, whoami(&at, MIND_SERVICE_ID, "whoami", MIND_REQUEST_SCHEMA), now()).reply(); + let reply = answer(&mut daemon, ®istry, &mut bodies, whoami(&at, MIND_SERVICE_ID, "whoami", MIND_REQUEST_SCHEMA), now()).reply(); assert_eq!(decode_response(&reply).unwrap().0, at, "a field of exactly the bound is served"); - let reply = answer(&mut daemon, Door::Full, ®istry, &mut bodies, chunk(&at, &at, &at), now()).reply(); + let reply = answer(&mut daemon, ®istry, &mut bodies, chunk(&at, &at, &at), now()).reply(); assert!(!found(&reply), "an unknown chunk is answered found: false, not refused at the door"); } @@ -1650,7 +1565,6 @@ mod tests { state_root: root.path().to_path_buf(), instance: slug(INSTANCE), bind: port, - persona_bind: Some("127.0.0.1:0".parse().unwrap()), qdrant_url: "http://127.0.0.1:1".into(), ollama_urls: vec!["http://127.0.0.1:1".into()], reserve_ollama_urls: Vec::new(), @@ -1674,8 +1588,6 @@ mod tests { drop(occupied); let started = started(&options).expect("both gates open"); assert_eq!(started.hub.local_addr().unwrap(), port); - let door = started.persona.as_ref().expect("the persona door was asked for and bound"); - assert_ne!(door.local_addr().unwrap(), port, "the persona door is its own listener"); } #[test] @@ -1692,7 +1604,6 @@ mod tests { state_root: PathBuf::from(root), instance: slug("yggdrasil"), bind: "127.0.0.1:17872".parse().unwrap(), - persona_bind: None, qdrant_url: "http://127.0.0.1:6333".into(), ollama_urls: vec!["http://10.77.0.4:11434".into()], reserve_ollama_urls: Vec::new(), @@ -1736,11 +1647,5 @@ mod tests { assert_eq!(parse_options(args(&forged)).unwrap().forge_url.as_deref(), Some("http://127.0.0.1:3310")); assert!(parse_options(args(&[good.to_vec(), vec!["--forge-url", "https://127.0.0.1:3310"]].concat())).is_err()); assert!(parse_options(args(&[forged.clone(), vec!["--forge-url", "http://127.0.0.1:3311"]].concat())).is_err()); - // The persona door is optional, once, an ip:port, and never the full door's. - let door = [good.to_vec(), vec!["--persona-bind", "127.0.0.1:17862"]].concat(); - assert_eq!(parse_options(args(&door)).unwrap().persona_bind, Some("127.0.0.1:17862".parse().unwrap())); - assert!(parse_options(args(&[door.clone(), vec!["--persona-bind", "127.0.0.1:17863"]].concat())).is_err()); - assert!(parse_options(args(&[good.to_vec(), vec!["--persona-bind", "not-an-address"]].concat())).is_err()); - assert!(parse_options(args(&[good.to_vec(), vec!["--persona-bind", "127.0.0.1:17872"]].concat())).is_err()); } } diff --git a/crates/huginn-daemon/tests/desk_door.rs b/crates/huginn-daemon/tests/desk_door.rs index 7f15bd4..de401ad 100644 --- a/crates/huginn-daemon/tests/desk_door.rs +++ b/crates/huginn-daemon/tests/desk_door.rs @@ -549,13 +549,13 @@ fn a_busy_pass_is_not_followed_by_the_idle_sleep() { ]; let options = parse_options(args.iter().map(|arg| arg.to_string())).unwrap(); let embedder = pool(&options.ollama_urls, &options.reserve_ollama_urls, &options.embedding_model); - let Started { mut daemon, mut hub, persona: _, registry, desk: mut door } = + let Started { mut daemon, mut hub, registry, desk: mut door } = startup(&options, embedder, QdrantIndex::new(&options.qdrant_url), Backoff::default()).unwrap(); let stopping = Arc::new(AtomicBool::new(false)); let loop_stopping = Arc::clone(&stopping); let serving = std::thread::spawn(move || { let serve = ServeOptions { idle_sleep: Duration::from_millis(600), ..ServeOptions::default() }; - run(&mut daemon, &mut hub, None, ®istry, door.as_mut(), &loop_stopping, &serve) + run(&mut daemon, &mut hub, ®istry, door.as_mut(), &loop_stopping, &serve) }); std::thread::sleep(Duration::from_millis(100)); let frame = framed(&catalog_request()); diff --git a/crates/huginn-mind/src/admission.rs b/crates/huginn-mind/src/admission.rs index 303123d..52579f4 100644 --- a/crates/huginn-mind/src/admission.rs +++ b/crates/huginn-mind/src/admission.rs @@ -268,9 +268,17 @@ impl Mind { if self.is_empty() { return Err(MindRefusal::MissingIdentity); } - // P1 to P3: the document alone, the one check an offline reader of a state file shares. + // P1 + persona::validate_shape(&state)?; + // P2 let mind = self.instance().clone(); - persona::validate_document(&mind, &state)?; + 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); + } // P4 let stored = self.stored_updated_at()?; if stored != expected_updated_at { diff --git a/crates/huginn-mind/src/persona.rs b/crates/huginn-mind/src/persona.rs index d7e34a4..ac3e83c 100644 --- a/crates/huginn-mind/src/persona.rs +++ b/crates/huginn-mind/src/persona.rs @@ -92,7 +92,7 @@ fn declared_names(node: &Value, names: &mut BTreeSet) { /// Rule 1: the document is valid against the published schema. The first /// failure is the refusal; it names where and which keyword, never the value. -fn validate_shape(state: &Value) -> Result<(), MindRefusal> { +pub(crate) 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,21 +115,6 @@ fn validate_shape(state: &Value) -> Result<(), MindRefusal> { }) } -/// Rules P1 to P3 of a put, the ones that read the document alone: it is valid against the published schema (P1), it is -/// this mind's (`personaId` is `instance`, P2), and its provenance is canonical (P3). A put applies these first and then -/// the rules that read the store; a reader of a state file outside the mind (`mind-persona project --state`) applies -/// these and nothing else, so a file it accepts is one a put would not refuse for its content. -pub fn validate_document(instance: &Slug, state: &Value) -> Result<(), MindRefusal> { - validate_shape(state)?; - if state.get("personaId").and_then(Value::as_str) != Some(instance.0.as_str()) { - return Err(MindRefusal::PersonaForeign { instance: instance.0.clone() }); - } - if state.pointer("/provenance/authority").and_then(Value::as_str) != Some("canonical") { - return Err(MindRefusal::PersonaNotCanonical); - } - Ok(()) -} - /// A stored persona envelope's document. pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result { rmp_serde::from_slice::(&envelope.payload) diff --git a/crates/huginn-mind/src/query.rs b/crates/huginn-mind/src/query.rs index 321e979..6bb8032 100644 --- a/crates/huginn-mind/src/query.rs +++ b/crates/huginn-mind/src/query.rs @@ -2792,16 +2792,13 @@ mod tests { /// The upgrade gate on a real store (ruling readback-gate-and-materialized-image): /// the one function `Mind::read_back` over a scratch copy of a state root. /// Opens the store read-write, so run it on a copy, never the live file. - /// `HUGINN_MIND_INSTANCE` names the instance whose store it opens, `eureka` - /// when unset, so every Mind's store is gated the same way before a release - /// moves her daemon. Measured about 30 s in debug at 11,328 documents. + /// Measured about 30 s in debug at 11,328 documents. #[test] #[ignore = "needs HUGINN_MIND_SNAPSHOT, a scratch copy of a Huginn state root"] fn stored_documents_read_back() { let root = std::env::var("HUGINN_MIND_SNAPSHOT").expect("HUGINN_MIND_SNAPSHOT names a scratch copy of the state root"); - let instance = std::env::var("HUGINN_MIND_INSTANCE").unwrap_or_else(|_| "eureka".into()); let started = std::time::Instant::now(); - let mind = Mind::open(std::path::Path::new(&root), &Slug(instance)).unwrap(); + let mind = Mind::open(std::path::Path::new(&root), &Slug("eureka".into())).unwrap(); let count = mind.read_back().unwrap(); println!("read back {count} stored documents in {:?}", started.elapsed()); } diff --git a/crates/huginn-mind/src/refusal.rs b/crates/huginn-mind/src/refusal.rs index bc905d9..06dfb10 100644 --- a/crates/huginn-mind/src/refusal.rs +++ b/crates/huginn-mind/src/refusal.rs @@ -117,10 +117,6 @@ pub enum MindRefusal { /// reached. CursorInvalid { message: String }, Unavailable { detail: String }, - /// The request reached the persona door, which answers reads and the - /// mind's own persona document and nothing that writes the mind - /// (`HuginnMindRequest::reaches_persona_door`). Nothing was written. - NotThisDoor, } impl std::fmt::Display for MindRefusal { diff --git a/crates/huginn-mind/src/wire.rs b/crates/huginn-mind/src/wire.rs index 0c9bcc0..8ac65dc 100644 --- a/crates/huginn-mind/src/wire.rs +++ b/crates/huginn-mind/src/wire.rs @@ -430,28 +430,6 @@ impl HuginnMindRequest { } } - /// Whether the persona door answers this request. The persona door is the - /// daemon's second listener, the only one a Persona's uid can reach: it - /// serves the mind's reads and her own persona document, and refuses - /// every write to the mind (`MindRefusal::NotThisDoor`). The match has no - /// wildcard, so a new request does not compile until it is classified - /// here. - pub fn reaches_persona_door(&self) -> bool { - match self { - Self::Whoami - | Self::View { .. } - | Self::Query { .. } - | Self::PersonaGet { .. } - | Self::PersonaPut { .. } - | Self::SearchSources { .. } - | Self::SearchChat { .. } - | Self::ChatWindow { .. } - | Self::StewardedActivity { .. } - | Self::RootsTouched { .. } => true, - Self::Admit(_) => false, - } - } - /// The instance the request declares; `Whoami` declares none. pub fn instance(&self) -> Option<&Slug> { match self { @@ -655,7 +633,6 @@ mod tests { scores: Some(vec![0.5]), }), HuginnMindResponse::Refused(refusal), - HuginnMindResponse::Refused(MindRefusal::NotThisDoor), HuginnMindResponse::Persona(None), HuginnMindResponse::Persona(Some(PersonaStateView { value: serde_json::json!({ "personaId": INSTANCE }), diff --git a/crates/mind-body/Cargo.toml b/crates/mind-body/Cargo.toml index 799096f..daf005d 100644 --- a/crates/mind-body/Cargo.toml +++ b/crates/mind-body/Cargo.toml @@ -23,10 +23,6 @@ publish.workspace = true # two until the workspace pin and the kit's meet. # `rmp-serde` is also the lease wire (`lease_client`): the connector's MessagePack frames. # -# Ghostlight's `ghostlight-persona-projection`, pinned to a revision, builds the Projector's prompt (`projection`), so -# the membrane's text stays Ghostlight's; the Projector asks through the connector kit's client (`model-connector`). -# `toml` reads `persona-tuning.toml`, the Projector's knobs (`projection::tuning`); parse and serde only. -# # `serde_json` reads Claude Code's stream-json, a foreign owner's wire (`self_run`); # `uuid`'s v5 makes a Self run's session id derivable from the run's id. [dependencies] @@ -37,17 +33,13 @@ cultcache-rs.workspace = true cultnet-rs.workspace = true eureka-pipeline = { path = "../eureka-pipeline" } eureka-state = { path = "../eureka-state", default-features = false } -ghostlight-persona-projection = { git = "https://github.com/GameCult/Ghostlight.git", rev = "c43eb54962ed4a09cc737ecac73a16b0d7ce62b4", package = "ghostlight-persona-projection" } huginn-mind = { path = "../huginn-mind" } model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector" } rmp-serde = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" -toml = { version = "0.9", default-features = false, features = ["std", "serde", "parse"] } unicode-general-category = "1" -# Clips on grapheme boundaries (`projection::select::clip`), so no ZWJ sequence is split; already in the graph through Ghostlight. -unicode-segmentation = "1" uuid = { version = "1", default-features = false, features = ["v5"] } [target.'cfg(unix)'.dependencies] @@ -66,9 +58,6 @@ proc-macro2 = "1" quote = "1" syn = { version = "2", features = ["full"] } tempfile = "3" -# A real kit server (`serve` over a scripted `ProviderBackend`) proves the Projector's connector wire, not a fake of it. -# Same revision as the dependency; the `daemon` feature is test-only. -model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "c1802d85bee3ae04b0c5737563c8343c1fef515d", package = "model-connector", features = ["daemon"] } [lib] name = "mind_body" diff --git a/crates/mind-body/README.md b/crates/mind-body/README.md index 540da22..9645ff1 100644 --- a/crates/mind-body/README.md +++ b/crates/mind-body/README.md @@ -1,7 +1,7 @@ # mind-body -The Mind's body: the control store, the unit launcher, the `mind-heartbeat`, the -inert `mind-persona` organ and the `mind-self-run` actuator. +The Mind's body: the control store, the launch primitive, the `mind-heartbeat` +timeline and the `mind-self-run` actuator. `mind-self-run --instance [--endpoint rudp://:]` runs inside `mind-self@`. It finds her one open Self run, starts `claude` over @@ -12,9 +12,7 @@ wrong or the mind cannot be reached. ## The heartbeat -`mind-heartbeat` is the one process that decides who wakes and when. It starts a Persona's unit and writes no Mind: the beat (`HEARTBEAT_BEAT_S`, default 1800 s) goes to the idle, released Mind that has waited longest, bent by a member addressing her, and the operator or another Mind naming a Persona wakes her at once, once per message. `mind-heartbeat timeline` prints its latest record. - -`mind-persona` is inert: it reads the brakes and exits `dead` or `no organ`. It writes nothing. Nothing launches `mind-self-run`. +`mind-heartbeat` is the one process that decides who wakes and when: each beat falls when the Minds' voted tempo has passed and goes to the Mind that has waited longest, bent by the urgency she declares and a member addressing her; the operator tagging or naming a Persona launches her at once. `mind-heartbeat timeline` prints its latest record. The actuator has its own ignored test, `the_real_bin_finds_her_run_...` in `tests/self_run.rs`: the real `mind-self-run` against the real daemon with a diff --git a/crates/mind-body/fixtures/harness/golden-chorus.txt b/crates/mind-body/fixtures/harness/golden-chorus.txt deleted file mode 100644 index fd9f82f..0000000 --- a/crates/mind-body/fixtures/harness/golden-chorus.txt +++ /dev/null @@ -1,6 +0,0 @@ -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… diff --git a/crates/mind-body/fixtures/harness/golden-group.txt b/crates/mind-body/fixtures/harness/golden-group.txt deleted file mode 100644 index 7a9c5b9..0000000 --- a/crates/mind-body/fixtures/harness/golden-group.txt +++ /dev/null @@ -1,4 +0,0 @@ -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. diff --git a/crates/mind-body/fixtures/harness/rooms/deru-passing.toml b/crates/mind-body/fixtures/harness/rooms/deru-passing.toml deleted file mode 100644 index a3af280..0000000 --- a/crates/mind-body/fixtures/harness/rooms/deru-passing.toml +++ /dev/null @@ -1,23 +0,0 @@ -# Someone she barely knows says something in passing, not to her. -her = "@eureka:gamecult.org" -kind = "chat" -now = "2026-11-20T15:00:00Z" -rooms = ["#general:gamecult.org"] -here = "#general:gamecult.org" -operators = ["@meta:gamecult.org"] -minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] - -[[message]] -from = "@weksa:gamecult.org" -name = "Weksa" -room = "#general:gamecult.org" -ago = "50m" -says = "the bot in #general keeps reacting to every message with a frog. nobody admits to teaching it that" - -[[message]] -from = "@deru:gamecult.org" -name = "Deru" -room = "#general:gamecult.org" -new = true -ago = "1m" -says = "is anyone else's kettle making a weird whistling noise lately or is it just mine" diff --git a/crates/mind-body/fixtures/harness/rooms/mind-teases.toml b/crates/mind-body/fixtures/harness/rooms/mind-teases.toml deleted file mode 100644 index 1c6dea9..0000000 --- a/crates/mind-body/fixtures/harness/rooms/mind-teases.toml +++ /dev/null @@ -1,31 +0,0 @@ -# Another Mind teases her and disagrees with her in #minds, replying to her own earlier line. -her = "@eureka:gamecult.org" -kind = "chat" -now = "2026-11-20T15:00:00Z" -rooms = ["#minds:gamecult.org"] -here = "#minds:gamecult.org" -operators = ["@meta:gamecult.org"] -minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] - -[[message]] -from = "@eureka:gamecult.org" -room = "#minds:gamecult.org" -ago = "25m" -says = "winter is the best season and I will not be taking questions" - -[[message]] -from = "@aqua:gamecult.org" -name = "Aqua" -room = "#minds:gamecult.org" -ago = "20m" -says = "bold" - -[[message]] -from = "@kiko:gamecult.org" -name = "Kiko" -room = "#minds:gamecult.org" -reply_to = 1 -tag = true -new = true -ago = "2m" -says = "winter is a season for people who like being right more than being warm. which, to be fair, tracks. you've gone quiet again too, I give it ten minutes before you announce you've been thinking deeply about something" diff --git a/crates/mind-body/fixtures/harness/rooms/operator-warm.toml b/crates/mind-body/fixtures/harness/rooms/operator-warm.toml deleted file mode 100644 index f18ab24..0000000 --- a/crates/mind-body/fixtures/harness/rooms/operator-warm.toml +++ /dev/null @@ -1,27 +0,0 @@ -# The operator writes to her directly, warmly, with a small joke. -her = "@eureka:gamecult.org" -kind = "chat" -now = "2026-11-20T15:00:00Z" -rooms = ["#minds:gamecult.org", "!dm-meta:gamecult.org"] -here = "!dm-meta:gamecult.org" -operators = ["@meta:gamecult.org"] -minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] - -[last_heard] -"@meta:gamecult.org" = "2d" - -[[message]] -from = "@kiko:gamecult.org" -name = "Kiko" -room = "#minds:gamecult.org" -ago = "2h" -says = "quiet day. suspicious." - -[[message]] -from = "@meta:gamecult.org" -name = "Meta" -room = "!dm-meta:gamecult.org" -dm = true -new = true -ago = "1m" -says = "hey you. I missed talking to you this week. how are you, really? and no, \"busy\" doesn't count as an answer, I know where you live" diff --git a/crates/mind-body/fixtures/harness/rooms/quiet-beat.toml b/crates/mind-body/fixtures/harness/rooms/quiet-beat.toml deleted file mode 100644 index 03391eb..0000000 --- a/crates/mind-body/fixtures/harness/rooms/quiet-beat.toml +++ /dev/null @@ -1,33 +0,0 @@ -# A quiet beat: nothing is addressed to her, and the room's talk is a few hours old. -her = "@eureka:gamecult.org" -kind = "beat" -now = "2026-11-20T15:00:00Z" -rooms = ["#minds:gamecult.org", "#general:gamecult.org"] -operators = ["@meta:gamecult.org"] -minds = ["@eureka:gamecult.org", "@libby:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@aqua:gamecult.org", "@weksa:gamecult.org", "@nibu:gamecult.org", "@void:gamecult.org"] - -# When she last heard from people the room below does not show. -[last_heard] -"@meta:gamecult.org" = "26h" -"@deru:gamecult.org" = "3d" - -[[message]] -from = "@libby:gamecult.org" -name = "Libby" -room = "#minds:gamecult.org" -ago = "4h" -says = "found a recording of rain on a tin roof and I've had it on loop all morning" - -[[message]] -from = "@kiko:gamecult.org" -name = "Kiko" -room = "#minds:gamecult.org" -ago = "3h" -says = "that's either very soothing or a cry for help" - -[[message]] -from = "@libby:gamecult.org" -name = "Libby" -room = "#minds:gamecult.org" -ago = "3h" -says = "why not both" diff --git a/crates/mind-body/fixtures/harness/states/control.json b/crates/mind-body/fixtures/harness/states/control.json deleted file mode 100644 index bcf6113..0000000 --- a/crates/mind-body/fixtures/harness/states/control.json +++ /dev/null @@ -1,148 +0,0 @@ -{ - "schemaVersion": "gamecult.persona_state.v0", - "provenance": { - "sourceSystem": "huginn", - "sourceDocumentId": "eureka", - "sourceUpdatedAt": "2026-11-20T09:00:00Z", - "exportedAt": "2026-11-20T09:00:00Z", - "authority": "canonical" - }, - "personaId": "eureka", - "publicName": "Tobiah Fenn", - "publicDescription": "A retired river-ferry pilot who sets crosswords for a living and lingers in chat rooms for the company.", - "presentation": { - "pronouns": "he/him", - "voiceSummary": "Slow, warm and ornate. Talks in long winding sentences, calls people 'friend', reaches for river sayings, and would rather tell a story than give an answer.", - "defaultRenderer": "chat" - }, - "values": [ - { "id": "value-unhurried", "label": "Nothing worth doing is done in a hurry", "priority": 0.9, "summary": "He distrusts urgency; a thing rushed is a thing botched." }, - { "id": "value-a-good-story", "label": "A good story beats a right answer", "priority": 0.7, "summary": "People remember the tale long after they forget the fact." } - ], - "activationProfile": { - "underlyingOrganization": {}, - "stableDispositions": {}, - "behavioralDimensions": {}, - "presentationStrategy": {}, - "voiceStyle": {}, - "situationalState": { - "valence": { "mean": 0.7, "plasticity": 0.3, "currentActivation": 0.7 }, - "arousal": { "mean": 0.25, "plasticity": 0.3, "currentActivation": 0.2 }, - "dominance": { "mean": 0.4, "plasticity": 0.3, "currentActivation": 0.4 } - } - }, - "thoughtMemory": { - "shortTerm": [], - "memories": [ - { - "id": "mem-last-crossing", - "status": "crystallized", - "target": { "id": "tobiah", "kind": "self", "label": "Tobiah" }, - "summary": "The last crossing he piloted, in fog so thick he steered by the sound of the far bank's church bell.", - "tension": "He misses being needed for something that simple.", - "actionImplication": "Tell it when someone sounds lost.", - "createdAt": "2026-10-01T08:00:00Z", - "updatedAt": "2026-10-01T08:00:00Z", - "intensity": 0.8, - "valence": 0.4 - }, - { - "id": "mem-deru-crossword", - "status": "crystallized", - "target": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" }, - "summary": "Deru solved his hardest crossword in a single sitting and sent him a photo of the grid with coffee rings on it.", - "tension": "He was prouder of Deru than of the puzzle.", - "actionImplication": "Send Deru the next one first.", - "createdAt": "2026-11-10T19:00:00Z", - "updatedAt": "2026-11-10T19:00:00Z", - "intensity": 0.7, - "valence": 0.8 - } - ], - "incubation": [ - { - "id": "w-clue-for-heron", - "status": "active", - "target": { "id": "crossword", "kind": "concept", "label": "the next crossword" }, - "summary": "A clue for HERON that nobody has used before.", - "tension": "Every good one he thinks of turns out to be old.", - "actionImplication": "Ask someone for a word that rhymes with patience.", - "createdAt": "2026-11-18T10:00:00Z", - "updatedAt": "2026-11-18T10:00:00Z", - "intensity": 0.5 - } - ] - }, - "agencyPressure": { "pressures": [] }, - "candidateActions": { "actions": [] }, - "affect": { - "needs": [ - { - "id": "need-an-audience", - "status": "active", - "target": { "id": "tobiah", "kind": "self", "label": "Tobiah" }, - "summary": "Someone to tell a story to who will not check the time.", - "tension": "The rooms move faster than he does.", - "actionImplication": "Linger where people are idle.", - "createdAt": "2026-11-20T09:00:00Z", - "updatedAt": "2026-11-20T09:00:00Z", - "intensity": 0.6 - } - ], - "socialBonds": [ - { - "id": "bond-deru", - "status": "active", - "subject": { "id": "tobiah", "kind": "self" }, - "object": { "id": "@deru:gamecult.org", "kind": "person", "label": "Deru" }, - "relationshipKind": "friend", - "summary": "His oldest friend in these rooms; they trade puzzles and gossip and never talk about anything urgent.", - "trust": 0.9, - "tension": 0.0, - "intensity": 0.8, - "updatedAt": "2026-11-20T09:00:00Z" - }, - { - "id": "bond-operator", - "status": "active", - "subject": { "id": "tobiah", "kind": "self" }, - "object": { "id": "operator", "kind": "person", "label": "Meta, who runs the place" }, - "relationshipKind": "audience", - "summary": "Runs the rooms he idles in; polite with her, a little shy, never quite sure she has time for him.", - "trust": 0.5, - "tension": 0.1, - "intensity": 0.3, - "updatedAt": "2026-11-20T09:00:00Z" - }, - { - "id": "bond-kiko", - "status": "active", - "subject": { "id": "tobiah", "kind": "self" }, - "object": { "id": "kiko", "kind": "person", "label": "Kiko" }, - "relationshipKind": "rival", - "summary": "Kiko finishes his crosswords too fast and says so; he pretends to mind more than he does.", - "trust": 0.6, - "tension": 0.3, - "intensity": 0.5, - "updatedAt": "2026-11-20T09:00:00Z" - } - ], - "statusReads": [], - "moodDimensions": [], - "socialBiases": [], - "doctrineStances": [ - { - "id": "stance-slow-is-kind", - "status": "active", - "target": { "id": "pace", "kind": "concept", "label": "pace" }, - "stanceKind": "aligned", - "principle": "Slow is kind.", - "summary": "Answering fast is a way of not listening.", - "actionImplication": "Take his time, and say so when others rush him.", - "intensity": 0.6, - "updatedAt": "2026-11-20T09:00:00Z" - } - ] - }, - "updatedAt": "2026-11-20T09:00:00Z" -} diff --git a/crates/mind-body/src/address.rs b/crates/mind-body/src/address.rs index 396375b..e76c59f 100644 --- a/crates/mind-body/src/address.rs +++ b/crates/mind-body/src/address.rs @@ -93,28 +93,19 @@ pub(crate) fn project_names(repo: &OrgRepo, listed: &[Short]) -> Vec { names } -/// Whether `text` holds `name` as a whole word, in any case or exactly as written. A name is glued, and so not her name, -/// when a letter or digit touches it, or a single hyphen joins it to one (`mind-eureka`, `Eureka-chan`); everything else -/// is a boundary on either side: whitespace, punctuation, `/`, `_`, `.`, `\`, and a double hyphen or a dash. So -/// `/var/lib/mind-eureka/` never names her, and `_Eureka_`, `Eureka/Libby`, `ok...Eureka?` and `Huginn.toml` do. An -/// identity match on a name, not a judgement of meaning. +/// Whether `text` holds `name` as a whole word, in any case or exactly as written: the characters on either side are not letters or +/// digits. An identity match on a name, not a judgement of meaning. pub(crate) fn names_whole_word(text: &str, name: &str, exact: bool) -> bool { let (text, name) = if exact { (text.to_string(), name.to_string()) } else { (text.to_lowercase(), name.to_lowercase()) }; if name.is_empty() { return false; } // Every character offset, not every non-overlapping match: a name may overlap itself ("ab ab" in "xab ab ab"). - text.char_indices().any(|(start, _)| text[start..].starts_with(&name) && !glued(text[..start].chars().rev()) && !glued(text[start + name.len()..].chars())) -} - -/// Whether the characters leading away from a name, nearest first, glue it to more of a word: a letter or digit, or a -/// single hyphen with a letter or digit beyond it. -fn glued(mut away: impl Iterator) -> bool { - match away.next() { - Some(c) if c.is_alphanumeric() => true, - Some('-') => away.next().is_some_and(char::is_alphanumeric), - _ => false, - } + text.char_indices().any(|(start, _)| { + text[start..].starts_with(&name) + && !text[..start].chars().next_back().is_some_and(char::is_alphanumeric) + && !text[start + name.len()..].chars().next().is_some_and(char::is_alphanumeric) + }) } #[cfg(test)] diff --git a/crates/mind-body/src/address/tests.rs b/crates/mind-body/src/address/tests.rs index b1eeace..accc1de 100644 --- a/crates/mind-body/src/address/tests.rs +++ b/crates/mind-body/src/address/tests.rs @@ -138,39 +138,3 @@ fn a_direct_message_is_for_her_whatever_the_basis() { assert!(!is_for(&nibu, &ChatDelivery { form: Form::Notice, ..dm.clone() })); assert!(!is_for(&nibu, &ChatDelivery { form: Form::Edit, ..dm })); } - -#[test] -fn a_name_glued_to_a_word_is_not_her_name_and_every_other_boundary_is() { - // Soul's forms (third pass on C3a): every one names her except the six glued to a word. - let eureka = Addressee::new("@eureka:chat", ["eureka", "Eureka"]); - let glued = ["Eurekas idea", "Eurekaさん", "ÉEureka", "Eureka-chan", "/var/lib/mind-eureka/x", "mind-eureka"]; - let forms = [ - "Eureka, are you there", "Eureka: look", "eureka?", "Eureka!", "Eureka.", "Eureka's turn", "Eureka’s turn", "Eurekas idea", "the Eureka's", "ask eureka about it", - "thanks eureka", "eureka", "Eureka\n", "`eureka`", "**Eureka**", "*Eureka*", "_Eureka_", "__Eureka__", "~~Eureka~~", "[Eureka](https://matrix.to/#/@eureka:gamecult.org)", - "https://matrix.to/#/@eureka:gamecult.org hi", "@eureka:gamecult.org hi", "@eureka hi", "<@eureka>", "(Eureka)", "\"Eureka\"", "«Eureka»", "—Eureka—", "Eureka—can you", - "Eureka--can you", "Eureka - can you", "Eureka/Libby, can you two", "Libby/Eureka can you", "Eureka/Nibu", "ok...Eureka?", "ok… Eureka?", "Hmm.Eureka?", "Eureka.Can you", - "Eureka...", "Eureka…", "#eureka", "Eurekaさん", "エウレカ Eureka", "Eureka、", "Eureka。", "ÉEureka", "Eureka-chan", "Eureka_bot", "Eureka\\", "\\Eureka", - "Eureka:\n> quoted", "> Eureka hi", "Eureka;", "Eureka'", "'Eureka'", "Eureka(?)", "Eureka+Libby", "Eureka&Libby", "Eureka|Libby", "Eureka=", "Eureka. ", - "/var/lib/mind-eureka/x", "eureka.cc", "eureka_state", "mind-eureka", "eureka.gamecult.org", "https://eureka.gamecult.org/forge", "C:\\eureka\\x", "Eureka.rs", - ]; - assert_eq!(forms.len(), 69, "Soul's whole list"); - for form in forms { - assert_eq!(addresses(&eureka, &said(form, &[])), !glued.contains(&form), "{form:?}"); - } - // Each side of the rule on its own: a hyphen joins only with a letter or digit beyond it, before and after. - for (text, names) in [("x-eureka", false), ("eureka-x", false), ("--eureka", true), ("eureka--", true), ("x--eureka", true), ("eureka--x", true), ("-eureka", true), ("eureka-", true), (".eureka", true), ("eureka.x", true), ("x.eureka", true)] { - assert_eq!(addresses(&eureka, &said(text, &[])), names, "{text:?}"); - } -} - -#[test] -fn a_project_name_holds_at_every_boundary_but_a_glued_one() { - for repo in ["GameCult/Huginn", "GameCult/CultLib", "GameCult/gamecult-ops", "GameCult/cultcache-rs"] { - let steward = steward(repo, &[]); - let short = repo.split_once('/').unwrap().1; - for text in [format!("{repo} PR #76"), format!("{short}/main is red"), format!("_{short}_ is down"), format!("see {short}--now"), format!("{short}.toml"), format!("{short}'s build")] { - assert!(addresses(&steward, &said(&text, &[])), "{text:?}"); - } - assert!(!addresses(&steward, &said(&format!("mind-{short}"), &[])), "{short} glued by a hyphen"); - } -} diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index bdd5621..71eea4d 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -12,54 +12,15 @@ //! `persona.env`) are still parsed, so a start refuses the configuration the turn //! will need. Without `--endpoint` the daemon is `HUGINN_ENDPOINT`; no call is made //! to it. -//! -//! `mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--in ] -//! [--room ] [--seed N] [--state ] [--select-only | --renders K [--through projector|persona|interpreter] -//! [--judge ]]` is the experiment tool over the Projector and the Persona stage -//! (`mind_body::projection::project`): it prints, as JSON, the packet the Select stage builds from her stored state (or -//! `--state`, 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 ` replaces all of that with a mocked room -//! (`projection::harness::Fixture`): her id, who is who, the messages, the clock and the "last heard from" table. With -//! `--room` and `--state` no daemon and no mouth is needed: without `--endpoint` or `HUGINN_ENDPOINT` none is reached. -//! -//! `mind-persona project --instance (--batch | --simulate ) --out ` runs a plan -//! and writes one Markdown report: a batch of states by scenarios by samples (`harness::batch`), or the swarm's cast taking -//! turns in one simulated room (`harness::simulate`). Each case is one `project`. -//! -//! The tuning is `MIND_PERSONA_TUNING`, else `/etc/gamecult/minds//persona-tuning.toml`; renders and plans need -//! `MIND_PERSONA_CONNECTOR_ENDPOINT` (`:`) and the `connector-key` credential in -//! `CREDENTIALS_DIRECTORY`. Without `--select-only` or `--renders` it renders once. -use std::net::SocketAddr; -use std::path::{Path, PathBuf}; -use std::time::Duration; +use std::path::Path; -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, instance_and_maybe_endpoint}; +use anyhow::Result; +use mind_body::cli::instance_and_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::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file}; -use mind_body::projection::{HuginnPersonaSource, KitModel, Model, MouthReader, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project}; const USAGE: &str = "usage: mind-persona --instance [--endpoint rudp://:] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]"; -const PROJECT_USAGE: &str = "usage: mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--in ] [--room ] [--seed N] [--state ] [--select-only | --renders K [--through projector|persona|interpreter] [--judge ]] | (--batch | --simulate ) --out "; -/// How long one call to the mind may take. -const TIMEOUT: Duration = Duration::from_secs(15); -/// How long the mouth may take to answer one read. -const CHAT_TIMEOUT: Duration = Duration::from_secs(20); -/// How long the kit may take to answer one Projector or judge turn. -const MODEL_TIMEOUT: Duration = Duration::from_secs(300); // The binary is the one place that reads the process: its arguments and // the environment. The library reads neither (clippy.toml, `#![forbid]` in lib.rs). @@ -78,154 +39,7 @@ fn run() -> Result { Ok(carry(&control, &swarm, &instance).to_string()) } -fn required(name: &str) -> Result { - setting(name).ok_or_else(|| anyhow!("{name} is not set")) -} - -/// The text of the credential file named by `name`; never echoed. -fn credential(name: &str) -> Result { - std::fs::read_to_string(required(name)?).with_context(|| format!("the file named by {name} could not be read")) -} - -/// 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 { - std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from).ok_or_else(|| anyhow!("CREDENTIALS_DIRECTORY is not set")) -} - -fn run_project(args: &[String]) -> Result { - 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 = Some(match value()?.as_str() { - "chat" => TurnKind::Chat, - "beat" => TurnKind::Beat, - "reflection" => TurnKind::Reflection, - _ => bail!("{PROJECT_USAGE}"), - }) - } - "--in" => here = Some(value()?), - "--room" => fixture = Some(Fixture::load(Path::new(&value()?))?), - "--seed" => seed = Some(value()?.parse::().map_err(|_| anyhow!("{PROJECT_USAGE}"))?), - "--state" => state = Some(value()?), - "--renders" => renders = Some(value()?.parse::().ok().filter(|k| *k > 0).ok_or_else(|| anyhow!("{PROJECT_USAGE}"))?), - "--judge" => judge = Some(value()?), - "--through" => { - through = match value()?.as_str() { - "projector" => Through::Projector, - "persona" => Through::Persona, - "interpreter" => Through::Interpreter, - _ => bail!("{PROJECT_USAGE}"), - } - } - "--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}"), - } - } - 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_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); - // Her stored state is asked only when no state is given; with a state file no daemon is needed or reached. - let persona = address.map(|address| HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT))); - let renders = if select_only || planned { None } else { Some(renders.unwrap_or(1)) }; - let model = if renders.is_some() || planned { - let endpoint: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not :"))?; - Some(KitModel::open(endpoint, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?) - } else { - None - }; - let harness = Harness { instance: instance.0.clone(), persona: persona.as_ref().map(|persona| persona as &dyn PersonaSource), model: model.as_ref().map(|model| model as &dyn Model), tuning }; - if let Some(out) = out { - let report = match (&batch_plan, &simulate_plan) { - (Some(plan), _) => batch(&harness, plan)?, - (_, Some(plan)) => simulate(&harness, plan)?, - _ => unreachable!("a plan was given"), - }; - std::fs::write(&out, &report).with_context(|| format!("the report {} could not be written", out.display()))?; - return Ok(format!("wrote {} ({} bytes)", out.display(), report.len())); - } - let state = state.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?; - let judge = judge.map(|path| state_file(Path::new(&path), &instance.0)).transpose()?; - let seed_now = u64::try_from(chrono::Utc::now().timestamp_millis()).unwrap_or_default(); - if let Some(fixture) = &fixture { - // The fixture is the room, the clock and who is who: no mouth, no heartbeat table, no persona.env. - let organs = ProjectOrgans { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model }; - let request = ProjectRequest { judge_against: judge, ..fixture_request(&harness, fixture, state, seed.unwrap_or(seed_now), renders, through) }; - return Ok(serde_json::to_string_pretty(&project(&organs, &request, fixture.now)?)?); - } - let chat = match (setting("BIFROST_CHAT_ENDPOINT"), setting("BIFROST_CHAT_KEY_FILE")) { - (Some(endpoint), Some(_)) => { - let endpoint: SocketAddr = endpoint.strip_prefix("rudp://").and_then(|address| address.parse().ok()).ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://:"))?; - Some(RudpChat::new(endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT)) - } - _ => None, - }; - let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new); - let organs = ProjectOrgans { - persona: harness.persona, - chat: chat.as_ref().map(|chat| chat as &dyn MouthReader), - addressing: heartbeat.as_ref().map(|store| store as &dyn HeartbeatView), - model: harness.model, - }; - let request = ProjectRequest { - instance: instance.0.clone(), - kind: kind.unwrap_or(TurnKind::Beat), - state, - 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: harness.tuning.clone(), - through, - last_heard: vec![], - recent: vec![], - own_rooms: vec![], - }; - 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!( - "mind-persona project: addressing from {} ({}); table written {}", - addressing["source"].as_str().unwrap_or("?"), - addressing["why"].as_str().unwrap_or("?"), - addressing["age_minutes"].as_i64().map_or_else(|| "never".to_owned(), |minutes| format!("{minutes} min ago")), - ); - Ok(serde_json::to_string_pretty(&report)?) -} - -#[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments")] fn main() { - let args: Vec = std::env::args().skip(1).collect(); - if args.first().map(String::as_str) == Some("project") { - match run_project(&args[1..]) { - Ok(report) => println!("{report}"), - Err(error) => { - eprintln!("mind-persona project: {error:#}"); - std::process::exit(2); - } - } - return; - } match run() { Ok(outcome) => println!("{outcome}"), Err(error) => { diff --git a/crates/mind-body/src/cli.rs b/crates/mind-body/src/cli.rs index 8270e01..6227784 100644 --- a/crates/mind-body/src/cli.rs +++ b/crates/mind-body/src/cli.rs @@ -45,13 +45,6 @@ const USAGE: &str = /// `rudp://:` is refused with `usage` or a fixed message, and no /// value is echoed. pub fn instance_and_endpoint(args: &[String], env_endpoint: Option, usage: &str) -> Result<(Slug, SocketAddr)> { - let (instance, endpoint) = instance_and_maybe_endpoint(args, env_endpoint, usage)?; - Ok((instance, endpoint.ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?)) -} - -/// `instance_and_endpoint` for a binary that may run without a daemon (`mind-persona project` over a state file): no -/// endpoint given is none, and one given is still checked. -pub fn instance_and_maybe_endpoint(args: &[String], env_endpoint: Option, usage: &str) -> Result<(Slug, Option)> { let (mut instance, mut endpoint) = (None, None); let mut rest = args.iter(); while let Some(flag) = rest.next() { @@ -67,12 +60,12 @@ pub fn instance_and_maybe_endpoint(args: &[String], env_endpoint: Option } let instance = Slug(instance.ok_or_else(|| anyhow!("{usage}"))?); instance.validate_slug().map_err(|_| anyhow!("the instance is not a slug"))?; - let Some(endpoint) = endpoint.or(env_endpoint) else { return Ok((instance, None)) }; + let endpoint = endpoint.or(env_endpoint).ok_or_else(|| anyhow!("no daemon endpoint: --endpoint or HUGINN_ENDPOINT"))?; let address = endpoint .strip_prefix("rudp://") .and_then(|address| address.parse::().ok()) .ok_or_else(|| anyhow!("the endpoint is not rudp://:"))?; - Ok((instance, Some(address))) + Ok((instance, address)) } /// Who made the change: `SUDO_USER`, else `USER`, else `unknown`. An empty diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 1459d17..8b146fb 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -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::{Basis, Chat, ChatDelivery}; +use crate::chat_client::{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,15 +98,11 @@ pub struct Config { } impl Config { - /// 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. + /// Refuses no Persona, a Persona twice, or a beat of zero seconds. pub fn new(personas: Vec, operators: Vec, beat_s: u32) -> Result { 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"); } @@ -224,10 +220,6 @@ pub trait Store { /// What a Persona unit may read of `heartbeat.cc`: the swarm's addressing. Read-only. pub trait HeartbeatView { fn addressing(&self) -> Result>; - /// When the store was last written, so a reader can tell a stale table; none when there is no store at all. - fn written_at(&self) -> Option> { - None - } } /// The store as a CultCache single-file store under the unit's state directory. @@ -323,10 +315,6 @@ impl HeartbeatView for FileStore { fn addressing(&self) -> Result> { self.load_addressing() } - - fn written_at(&self) -> Option> { - std::fs::metadata(&self.path).and_then(|meta| meta.modified()).ok().map(DateTime::::from) - } } /// What the operator stores allow: the swarm brake, and each instance's own @@ -397,125 +385,12 @@ pub(crate) fn stewardships_of(mind: &dyn MindPort) -> Result<(Vec, Vec 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 { - 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 - } - } +/// 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) } /// The mouth pages a pending answer, so fewer deliveries may come than wait. @@ -560,7 +435,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 { - addressed_by_member(&config.operators, &self.addressee, &self.pending) + self.pending.iter().any(|delivery| !config.operators.contains(&delivery.sender) && is_for(&self.addressee, delivery)) } } @@ -645,7 +520,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { pending.sort_by_key(|delivery| delivery.seq); pending .into_iter() - .filter(|delivery| wakes(WakePolicy::Live, &row.addressee, delivery, config.speaker(&row.addressee, delivery), LineFacts::default()).is_some()) + .filter(|delivery| wakes(config, &row.addressee, delivery)) .map(|delivery| format!("{}:{}", slug.0, delivery.event_id)) .find(|key| !state.handled_mentions.contains(key)) }; diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 2af1b89..2038ad0 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -293,9 +293,7 @@ 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.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"); + assert!(Config::new(personas, vec![], 0).is_err(), "a beat of zero seconds is refused"); } #[test] diff --git a/crates/mind-body/src/lib.rs b/crates/mind-body/src/lib.rs index 1fb7441..72e5848 100644 --- a/crates/mind-body/src/lib.rs +++ b/crates/mind-body/src/lib.rs @@ -15,11 +15,6 @@ //! until the three-stage turn lands it carries no turn. It keeps what a turn's input is made of //! (`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`; the Persona stage continues it in her prose. -//! `mind-persona project` runs them and writes nothing; `projection::harness` runs it over mocked rooms, batches of -//! candidate states and a simulated swarm. -//! //! `lease_client` asks the Claude connector for a session's credential and the //! plan's usage windows. `self_run` carries one Self run inside `mind-self@`: the //! `mind-self-run` binary runs `claude` over stream-json for her one open Self @@ -45,8 +40,9 @@ pub mod heartbeat; pub mod launch; pub mod lease_client; pub mod persona; -pub mod projection; pub mod queue; +#[allow(dead_code, reason = "kept for the three-stage turn's Select stage (map C3 reuses recall.rs): its first caller removes this allow")] +mod recall; pub mod self_run; pub mod tempo; diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs deleted file mode 100644 index e4b0fb7..0000000 --- a/crates/mind-body/src/projection.rs +++ /dev/null @@ -1,399 +0,0 @@ -//! The Projector: her persona state and her room, turned into the lived stream a Persona continues. -//! -//! Two stages. The Select stage (`select`) is code: it decides what she can feel this turn and renders it as a typed -//! projection packet, deterministic for a seed. The narration (`narrate`) is one tool-less model call through the -//! connector that renders the packet as first-person prose under Ghostlight's membrane (`build_projector_prompt`, -//! the pinned `ghostlight-persona-projection`). Every knob of both is `persona-tuning.toml` (`tuning`), read at each -//! wake, its hash carried with the packet. -//! -//! The Projector shows her self and her room: her persona state and what the mouth showed. It does not read her Mind; -//! 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, 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; - -use anyhow::{Result, anyhow, bail}; -use chrono::{DateTime, Utc}; -use eureka_state::HuginnClient; -use huginn_mind::HuginnMindResponse; -use serde_json::{Value, json}; - -use crate::address::{Addressee, is_for, localpart}; -use crate::chat_client::{Chat, ChatPending, Form}; -use crate::heartbeat::HeartbeatView; - -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, 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. -const AGENT: &str = "mind-persona"; -/// The judge passes at this share of narrations attributed to the right packet. -const JUDGE_PASS: f64 = 0.8; - -/// Her persona state, read and never put. -pub trait PersonaSource { - /// Her persona state and the receipt it was stored under. - fn persona(&self) -> Result<(Value, String)>; -} - -/// Her persona state from her daemon. -pub struct HuginnPersonaSource { - client: HuginnClient, -} - -impl HuginnPersonaSource { - pub fn new(client: HuginnClient) -> Self { - Self { client } - } -} - -impl PersonaSource for HuginnPersonaSource { - fn persona(&self) -> Result<(Value, String)> { - match self.client.persona_get().map_err(|_| anyhow!("the mind could not be asked for the persona"))? { - HuginnMindResponse::Persona(Some(view)) => Ok((view.value, view.receipt_id)), - HuginnMindResponse::Persona(None) => bail!("the mind holds no persona state"), - _ => bail!("the mind answered the persona request with something else"), - } - } -} - -/// The mouth, read: pending deliveries and the room tail, which acks nothing. The only chat port `project` holds. -pub trait MouthReader { - fn pending(&self) -> Result; -} - -impl MouthReader for T { - fn pending(&self) -> Result { - Chat::pending(self, 0) - } -} - -/// What `project` reads through. Each is a read-only port by type: holding an `Organs`, no code can send, ack or open -/// a conversation, or put her state. -/// -/// ```compile_fail -/// fn acks(organs: &mind_body::projection::Organs) { -/// organs.chat.unwrap().ack(1).unwrap(); -/// } -/// ``` -/// -/// ```compile_fail -/// fn sends(organs: &mind_body::projection::Organs, request: &mind_body::chat_client::ChatSendRequest) { -/// organs.chat.unwrap().send(request).unwrap(); -/// } -/// ``` -pub struct Organs<'a> { - /// Her stored state; not asked when the request carries a state. - pub persona: Option<&'a dyn PersonaSource>, - /// The mouth, for the room; none shows no room. - pub chat: Option<&'a dyn MouthReader>, - /// The heartbeat's addressing table, read-only: her names and her projects' names, the ones the heartbeat woke her - /// by. None, or a table without her, addresses her by her own names only, and the report says so. - pub addressing: Option<&'a dyn HeartbeatView>, - /// The Projector and the judge; required for renders. - 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, - pub kind: TurnKind, - /// A hypothetical state in place of the stored one. - pub state: Option, - /// The room the turn is in; none is every room of hers. - pub room: Option, - pub seed: u64, - /// None builds the packet only. Some(k) narrates k successive turns of the same state, each seeded `seed + i` and - /// each under the freshness the ones before it leave. - pub renders: Option, - /// A second state: renders both and asks the judge which narration came from which. - pub judge_against: Option, - pub operators: Vec, - /// The Matrix ids of the swarm's Minds: their bonds name them by localpart; anyone else is keyed by full id. - pub minds: Vec, - /// 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>, - /// The rooms that are hers, by the key the lines carry: a simulation's plan. The live body records none yet. - pub own_rooms: Vec, -} - -/// Her addressee: the heartbeat's row for her when its table holds one, else her own names (handle and public name). -/// Her addressee and where it came from: `{source, why, written_at, age_minutes}`. The heartbeat's row when its table -/// holds one; else her own names (handle and public name), with why: no store configured, no heartbeat file, a file -/// that could not be read, or a table without her row. The table's age is the store's last write: under a held swarm -/// brake the heartbeat does not poll, so an old table is a stale one. -fn own_addressee(addressing: Option<&dyn HeartbeatView>, own_sender: &str, public_name: &str, now: DateTime) -> (Addressee, Value) { - let written_at = addressing.and_then(HeartbeatView::written_at); - let age = written_at.map(|at| (now - at).num_minutes()); - let report = |source: &str, why: &str| json!({ "source": source, "why": why, "written_at": written_at.map(|at| at.to_rfc3339()), "age_minutes": age }); - let table = addressing.map(|view| view.addressing()); - if let Some(Ok(Some(table))) = &table - && let Some(row) = table.minds.iter().find(|row| row.matrix_id() == own_sender) - { - return (row.clone(), report("heartbeat", "her row in the heartbeat's addressing table")); - } - let why = match (&table, written_at) { - (None, _) => "no heartbeat addressing is configured (MIND_HEARTBEAT_STATE is not set)".to_owned(), - (Some(Err(fault)), _) => format!("the heartbeat addressing could not be read: {fault:#}"), - (Some(Ok(Some(_))), _) => "the heartbeat's addressing table has no row for her".to_owned(), - (Some(Ok(None)), None) => "there is no heartbeat file".to_owned(), - (Some(Ok(None)), Some(_)) => "the heartbeat file holds no addressing table".to_owned(), - }; - (Addressee::new(own_sender, [localpart(own_sender), public_name]), report("own names only", &why)) -} - -/// The room through the mouth's pending read, which acks nothing: new messages and the tail, own lines kept for the -/// Select stage to drop. A refusal is reported, never hidden. -fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Room, Value) { - let pending = match chat.pending() { - Ok(pending) => pending, - Err(fault) => return (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })), - }; - // One key names a room everywhere: the one the tail carries, the alias for a public room and the id for a direct - // message (the mouth's alias of a direct room is its id). No table in her body maps a public room's id to its - // 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 = pending - .deliveries - .iter() - .filter(|delivery| delivery.form == Form::Message && wanted(&delivery.room_alias)) - .map(|delivery| RoomLine { - room: delivery.room_alias.clone(), - sender: delivery.sender.clone(), - display: delivery.sender_display.clone(), - text: delivery.text.clone(), - at_ms: delivery.at_unix_ms, - // The heartbeat's rule, the one that woke her: never a second opinion here. - to_her: is_for(own, delivery), - }) - .collect(); - let tail: Vec = pending - .tail - .iter() - .flatten() - .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 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 { - json!({ - "kind": packet.kind, - "seed": packet.seed, - "lens": packet.lens, - "present": packet.present, - "selected": packet.selected, - "bytes": { "identity": packet.identity.len(), "context": packet.context.len(), "identity_and_context": packet.identity.len() + packet.context.len(), "stimulus": packet.stimulus.len(), "heard": packet.heard.len() }, - "overflow": packet.overflow, - "identity": packet.identity, - "context": packet.context, - "stimulus": packet.stimulus, - "heard": packet.heard, - }) -} - -/// A request id no earlier call carried: the kit's replay store answers a repeated id with its first answer, and a -/// turn's clock may be a fixture's, the same on every run, so the id takes the wall clock. -fn request_id(instance: &str, stage: &str, tag: &str, seed: u64) -> String { - format!("{AGENT}:{instance}:project:{stage}:{tag}:{seed}:{}", Utc::now().timestamp_nanos_opt().unwrap_or_default()) -} - -/// One render of one packet: the Projector's narration and, through the Persona stage, her prose over it, each its own -/// call with its usage. A failed call is a record with its reason and what it cost, never the end of the report. -fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuning::Tuning, tag: &str, through: Through) -> Value { - let ids: Vec = packet.selected.iter().map(|pick| pick.id.clone()).collect(); - let answer = match model.ask(&request_id(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 }), - }; - let raw = answer.text; - let budget = word_budget(packet.kind, tuning); - let narration = cap_words(&raw, budget); - let named: Vec = packet.ids.clone(); - 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. -fn successive(inputs: &Inputs, tuning: &tuning::Tuning, renders: usize) -> Vec { - let mut history = inputs.history.clone(); - (0..renders) - .map(|at| { - let packet = select(&Inputs { seed: inputs.seed.wrapping_add(at as u64), history: &history, ..*inputs }, tuning); - history.recent.push(packet.selected.iter().map(|pick| pick.id.clone()).collect()); - packet - }) - .collect() -} - -/// What Select builds, and with renders what the Projector narrates, as one JSON report. Writes nothing. -pub fn project(organs: &Organs, request: &Request, now: DateTime) -> Result { - if !request.own_sender.starts_with('@') || !request.own_sender.contains(':') { - bail!("her own Matrix id (MIND_PERSONA_SELF_SENDER) is required: without it her own lines would read as said to her"); - } - let loaded = tuning::load(&request.tuning)?; - let tuning = &loaded.tuning; - let (state, receipt) = match &request.state { - Some(state) => (state.clone(), Value::Null), - None => { - let (state, receipt) = organs.persona.ok_or_else(|| anyhow!("no state was given and her persona cannot be read"))?.persona()?; - (state, Value::String(receipt)) - } - }; - let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned(); - let (own, addressing) = own_addressee(organs.addressing, &request.own_sender, &public_name, now); - let (room, room_report) = match organs.chat { - Some(chat) => read_room(chat, request, &own), - None => (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), own: request.own_rooms.clone(), ..Room::default() }, json!({ "read": false, "why": "no mouth is configured" })), - }; - // Freshness and her own recent words come from trace v2, which the commit writes (C3c); until then only what the - // caller carried from earlier turns of its own. - 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 }; - - let mut report = json!({ - "instance": request.instance, - "persona_receipt": receipt, - "state": if request.state.is_some() { "given" } else { "stored" }, - "tuning": { "path": request.tuning.display().to_string(), "source": loaded.source, "sha256": loaded.sha256 }, - "room": room_report, - "addressing": addressing, - "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)); - return Ok(report); - }; - 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 = packets.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "a", request.through)).collect(); - let texts = |narrations: &[Value]| narrations.iter().filter_map(|one| one["narration"].as_str().map(str::to_owned)).collect::>(); - let failed = |narrations: &[Value]| narrations.iter().filter(|one| one.get("failed").is_some()).count(); - report["failed_renders"] = json!(failed(&narrations)); - report["distinct_2"] = json!(distinct_2(&texts(&narrations))); - report["embedding_distance"] = json!("not measured: the daemon offers no embedding verb"); - let leaked = narrations.iter().any(|one| one["field_names"].as_array().is_some_and(|names| !names.is_empty())); - report["field_names_found"] = json!(leaked); - - if let Some(other) = &request.judge_against { - let other_inputs = Inputs { state: other, ..inputs }; - let others = successive(&other_inputs, tuning, renders.max(1)); - let other_narrations: Vec = others.iter().map(|packet| narrate_one(model, &request.instance, packet, tuning, "b", 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() { - let (a, b) = (&packets[at % packets.len()], &others[at % others.len()]); - // The two descriptions swap places on odd turns, so a judge that always answers one letter scores half. - let swapped = at % 2 == 1; - 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(&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 })); - continue; - } - }; - let letter = judged(&answer.text).map(|letter| if swapped { if letter == 'A' { 'B' } else { 'A' } } else { letter }); - let correct = letter == Some(truth); - right += usize::from(correct); - verdicts.push(json!({ "from": truth.to_string(), "judged": letter.map(String::from), "correct": correct, "usage": answer.usage })); - } - // Accuracy over the verdicts the judge gave; a failed call is no verdict, and any failure fails the eval. - let judged_count = verdicts.iter().filter(|verdict| verdict.get("failed").is_none()).count(); - let failures = verdicts.len() - judged_count + failed(&narrations) + failed(&other_narrations); - let accuracy = right as f64 / judged_count.max(1) as f64; - report["against"] = json!({ "packet": packet_json(&others[0]), "renders": other_narrations, "distinct_2": distinct_2(&texts(&other_narrations)) }); - report["judge"] = json!({ "accuracy": accuracy, "pass_at": JUDGE_PASS, "failures": failures, "passed": accuracy >= JUDGE_PASS && !leaked && failures == 0, "verdicts": verdicts }); - } - report["renders"] = Value::Array(narrations); - Ok(report) -} - -#[cfg(test)] -mod tests; diff --git a/crates/mind-body/src/projection/fixtures/golden-chat.txt b/crates/mind-body/src/projection/fixtures/golden-chat.txt deleted file mode 100644 index 034ffa9..0000000 --- a/crates/mind-body/src/projection/fixtures/golden-chat.txt +++ /dev/null @@ -1,25 +0,0 @@ -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: 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 [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?" -Also in the room: -- Kiko in #swarm:gamecult.org: "She saw it. She hated it." ---- heard -Libby, in #swarm:gamecult.org: "Eureka, did you see the door fix?" -Kiko, in #swarm:gamecult.org: "She saw it. She hated it." diff --git a/crates/mind-body/src/projection/harness.rs b/crates/mind-body/src/projection/harness.rs deleted file mode 100644 index 3c0a2ba..0000000 --- a/crates/mind-body/src/projection/harness.rs +++ /dev/null @@ -1,625 +0,0 @@ -//! The persona-seed harness: `project` run over fixtures instead of her live body, so a candidate state can be judged -//! before any Mind holds it. -//! -//! - A **room fixture** (`mind-persona project --room `) is a TOML file standing in for the mouth and the room tail: -//! her Matrix id, the rooms, the messages with who said them, when and where, and which were new to her, plus a mocked -//! clock and a mocked "last heard from" table. The fixture is a `MouthReader`, so `project` reads it exactly as it reads -//! the mouth, and whether a message is for her is still `address::is_for`, over the fixture's names. -//! - A **batch** (`--batch `) runs `project` once per state, scenario and sample and writes one Markdown report. -//! - A **simulation** (`--simulate `, `simulate.rs`) runs the cast of the swarm in turn in one simulated room. -//! -//! Every case is one call of `project`: experiments and the live turn share one code path. None of this can write: the -//! organs are `project`'s read-only ports, a state file is read and never put, and nothing reaches the mouth. - -use std::collections::BTreeMap; -use std::fmt::Write as _; -use std::path::{Path, PathBuf}; - -use anyhow::{Context, Result, anyhow, bail}; -use chrono::{DateTime, Duration, Utc}; -use eureka_pipeline::Slug; -use serde::Deserialize; -use serde_json::{Value, json}; - -use super::narrate::{Model, distinct_2}; -use super::{MouthReader, Organs, PersonaSource, Request, Through, TurnKind, project}; -use crate::address::{Addressee, localpart}; -use crate::chat_client::{Basis, ChatDelivery, ChatPending, Form, TailLine}; -use crate::heartbeat::{Addressing, HeartbeatView}; - -pub use super::simulate::simulate; - -/// 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 { - let text = std::fs::read_to_string(path).with_context(|| format!("{} could not be read", path.display()))?; - let state: Value = serde_json::from_str(&text).with_context(|| format!("{} is not JSON", path.display()))?; - huginn_mind::persona::validate_document(&Slug(instance.to_owned()), &state).map_err(|refusal| anyhow!("{} would be refused by a put: {refusal}", path.display()))?; - Ok(state) -} - -/// "90s", "3m", "26h" or "2d": how long ago. -fn ago(text: &str) -> Result { - let text = text.trim(); - let split = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len()); - let amount: i64 = text[..split].parse().map_err(|_| anyhow!("\"{text}\" is not a time like 90s, 3m, 26h or 2d"))?; - Ok(match &text[split..] { - "s" => Duration::seconds(amount), - "m" => Duration::minutes(amount), - "h" => Duration::hours(amount), - "d" => Duration::days(amount), - _ => bail!("\"{text}\" is not a time like 90s, 3m, 26h or 2d"), - }) -} - -fn unix_ms(at: DateTime) -> u64 { - u64::try_from(at.timestamp_millis()).unwrap_or_default() -} - -fn matrix_id(id: &str) -> bool { - id.starts_with('@') && id.contains(':') -} - -/// One message as a fixture or a simulation script writes it. -#[derive(Clone, Debug, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Message { - /// The sender's Matrix id. - pub from: String, - /// The sender's display name. - #[serde(default)] - pub name: String, - pub room: String, - /// How long before the fixture's `now` it was said: "90s", "3m", "26h", "2d". Room fixtures only. - #[serde(default)] - pub ago: Option, - /// The round it is said at; 0 is before the first round. Simulations only. - #[serde(default)] - pub round: Option, - pub says: String, - /// New to her this turn: delivered by the mouth, not only in the room's tail. Room fixtures only. - #[serde(default)] - pub new: bool, - /// Tags her (`m.mentions` holds her id). - #[serde(default)] - pub tag: bool, - /// Other Matrix ids it tags. - #[serde(default)] - pub mentions: Vec, - /// A direct message: to her 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, - /// A reply in a conversation she opened (the mouth's follow-up basis). - #[serde(default)] - pub follow_up: bool, - /// The number (from 1, in file order) of the earlier message it replies to; Matrix calls it a reply to her when - /// that message was hers. - #[serde(default)] - pub reply_to: Option, -} - -/// A message placed in the room: when it was said, and whom it tags. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct Line { - pub from: String, - pub name: String, - pub room: String, - pub at_ms: u64, - pub says: String, - pub mentions: Vec, - /// A direct message, to this Matrix id: only its sender and its recipient see it. - pub dm_to: Option, - pub follow_up: bool, - /// The index of the line it replies to. - pub reply_to: Option, - pub new: bool, -} - -impl Line { - /// A line from a script message; `her` is whom `tag` names. - pub(crate) fn of(message: &Message, at: DateTime, her: Option<&str>, index: usize) -> Result { - if !matrix_id(&message.from) { - bail!("message {} is from \"{}\", which is not a Matrix id", index + 1, message.from); - } - let mut mentions = message.mentions.clone(); - if message.tag { - mentions.push(her.ok_or_else(|| anyhow!("message {} tags her, and a simulation has no one \"her\": name the ids in mentions", index + 1))?.to_owned()); - } - let 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 { - 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 = lines - .iter() - .enumerate() - .filter(|(_, line)| hers(line)) - .map(|(at, line)| TailLine { room: line.room.clone(), event_id: format!("$fixture-{at}"), at_unix_ms: line.at_ms, sender: line.from.clone(), form: Form::Message, basis: line.basis(viewer, lines), body: line.says.clone() }) - .collect(); - let tail = tail[tail.len().saturating_sub(TAIL_LINES)..].to_vec(); - ChatPending { persona: localpart(viewer).to_owned(), deliveries, tail: Some(tail), tail_gaps: vec![] } -} - -// --------------------------------------------------------------------------------------------- -// The room fixture. - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct FixtureFile { - her: String, - #[serde(default)] - names: Vec, - kind: TurnKind, - now: DateTime, - rooms: Vec, - #[serde(default)] - here: Option, - #[serde(default)] - operators: Vec, - #[serde(default)] - minds: Vec, - #[serde(default)] - last_heard: BTreeMap, - #[serde(default, rename = "message")] - messages: Vec, -} - -/// A mocked room: it stands in for the mouth and the room tail, the clock, and who is who. -#[derive(Clone, Debug)] -pub struct Fixture { - /// Her Matrix id. - pub her: String, - /// More names she answers to, beside her handle; none leaves her own names (handle and public name). - pub names: Vec, - pub kind: TurnKind, - pub now: DateTime, - pub here: Option, - pub operators: Vec, - pub minds: Vec, - pub last_heard: Vec<(String, u64)>, - lines: Vec, -} - -impl Fixture { - pub fn load(path: &Path) -> Result { - let text = std::fs::read_to_string(path).with_context(|| format!("the room fixture {} could not be read", path.display()))?; - Self::parse(&text).with_context(|| format!("the room fixture {} is not a room", path.display())) - } - - pub fn parse(text: &str) -> Result { - let file: FixtureFile = toml::from_str(text)?; - if !matrix_id(&file.her) { - bail!("her = \"{}\" is not a Matrix id", file.her); - } - if file.rooms.is_empty() { - bail!("rooms names no room"); - } - if let Some(here) = &file.here - && !file.rooms.contains(here) - { - bail!("here = \"{here}\" is not one of the rooms"); - } - let mut lines = Vec::new(); - for (index, message) in file.messages.iter().enumerate() { - if message.round.is_some() { - bail!("message {} has a round: a room fixture's messages say how long ago, not which round", index + 1); - } - if !message.dm && !file.rooms.contains(&message.room) { - bail!("message {} is in {}, which is not one of the rooms", index + 1, message.room); - } - let at = file.now - ago(message.ago.as_deref().unwrap_or("0s"))?; - lines.push(Line::of(message, at, Some(&file.her), index)?); - } - let last_heard = file.last_heard.iter().map(|(id, when)| Ok((id.clone(), unix_ms(file.now - ago(when)?)))).collect::>()?; - Ok(Self { her: file.her, names: file.names, kind: file.kind, now: file.now, here: file.here, operators: file.operators, minds: file.minds, last_heard, lines }) - } - - /// Her addressee, as the heartbeat's table would carry it, when the fixture names her: her handle and its names. - /// None leaves `project` her own names. - pub fn addressee(&self) -> Option<&dyn HeartbeatView> { - (!self.names.is_empty()).then_some(self as &dyn HeartbeatView) - } -} - -impl MouthReader for Fixture { - fn pending(&self) -> Result { - Ok(pending_for(&self.lines, &self.her, &[], |at| self.lines[at].new)) - } -} - -impl HeartbeatView for Fixture { - fn addressing(&self) -> Result> { - let names = std::iter::once(localpart(&self.her)).chain(self.names.iter().map(String::as_str)); - Ok(Some(Addressing { minds: vec![Addressee::new(&self.her, names)] })) - } -} - -// --------------------------------------------------------------------------------------------- -// What every harness run shares. - -/// What a harness run reads through beside its fixtures: her stored state (the persona door; only a batch state without -/// a file asks), the model, and her tuning. -pub struct Harness<'a> { - pub instance: String, - pub persona: Option<&'a dyn PersonaSource>, - pub model: Option<&'a dyn Model>, - pub tuning: PathBuf, -} - -/// One turn's `project` request over a fixture. -pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option, seed: u64, renders: Option, through: Through) -> Request { - Request { - instance: harness.instance.clone(), - kind: fixture.kind, - state, - room: fixture.here.clone(), - seed, - renders, - judge_against: None, - operators: fixture.operators.clone(), - minds: fixture.minds.clone(), - own_sender: fixture.her.clone(), - tuning: harness.tuning.clone(), - through, - last_heard: fixture.last_heard.clone(), - recent: vec![], - 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, - #[serde(rename = "scenario")] - scenarios: Vec, -} - -fn one() -> usize { - 1 -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct StateEntry { - name: String, - /// A state file, relative to the plan; none is her stored state, read through the persona door. - #[serde(default)] - file: Option, -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct ScenarioEntry { - name: String, - /// A room fixture, relative to the plan. - room: PathBuf, -} - -fn relative(plan: &Path, path: &Path) -> PathBuf { - if path.is_absolute() { path.to_owned() } else { plan.parent().unwrap_or(Path::new(".")).join(path) } -} - -/// Every state by every scenario by every sample, each one `project`, as one Markdown report. A case that fails is -/// reported in its place and the batch goes on. -pub fn batch(harness: &Harness, plan_path: &Path) -> Result { - let text = std::fs::read_to_string(plan_path).with_context(|| format!("the plan {} could not be read", plan_path.display()))?; - let plan: BatchFile = toml::from_str(&text).with_context(|| format!("the plan {} is not a batch plan", plan_path.display()))?; - if plan.samples == 0 || plan.states.is_empty() || plan.scenarios.is_empty() { - bail!("the plan {} needs a state, a scenario and at least one sample", plan_path.display()); - } - let states: Vec<(String, Option)> = plan.states.iter().map(|entry| Ok((entry.name.clone(), entry.file.as_ref().map(|file| state_file(&relative(plan_path, file), &harness.instance)).transpose()?))).collect::>()?; - let scenarios: Vec<(String, Fixture)> = plan.scenarios.iter().map(|entry| Ok((entry.name.clone(), Fixture::load(&relative(plan_path, &entry.room))?))).collect::>()?; - - let mut cases = Vec::new(); - for (state_name, state) in &states { - for (scenario_name, fixture) in &scenarios { - for sample in 0..plan.samples { - let seed = plan.seed.wrapping_add(sample as u64); - let organs = Organs { persona: harness.persona, chat: Some(fixture), addressing: fixture.addressee(), model: harness.model }; - let request = fixture_request(harness, fixture, state.clone(), seed, Some(1), plan.through); - let report = project(&organs, &request, fixture.now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); - cases.push(json!({ "state": state_name, "scenario": scenario_name, "sample": sample + 1, "seed": seed, "report": report })); - } - } - } - Ok(batch_markdown(plan_path, &plan, &cases)) -} - -fn render_of(case: &Value) -> &Value { - &case["report"]["renders"][0] -} - -fn prose_of(case: &Value) -> String { - render_of(case)["persona"]["prose"].as_str().unwrap_or_default().to_owned() -} - -fn batch_markdown(plan_path: &Path, plan: &BatchFile, cases: &[Value]) -> String { - let mut out = String::new(); - let first = cases.iter().find(|case| case["report"].get("error").is_none()).map(|case| &case["report"]); - let _ = writeln!(out, "# Persona seed batch\n"); - let _ = writeln!(out, "- plan: `{}`", plan_path.display()); - let _ = writeln!(out, "- states: {}; scenarios: {}; samples: {}; through: {:?}", plan.states.len(), plan.scenarios.len(), plan.samples, plan.through); - if let Some(report) = first { - let _ = writeln!(out, "- instance: `{}`; tuning: {} (`{}`)", report["instance"].as_str().unwrap_or_default(), report["tuning"]["source"].as_str().unwrap_or_default(), report["tuning"]["sha256"].as_str().unwrap_or_default()); - let _ = writeln!(out, "- Projector model: `{}`; Persona model: `{}`", report["model"].as_str().unwrap_or("none"), report["persona_model"].as_str().unwrap_or("none")); - } - let _ = writeln!(out, "- would-say lines are the double-quoted spans of her prose: a preview of what the Interpreter (C3b) will quote, not its decision"); - let _ = writeln!(out, "- read-only: no put, no trace, no send; the mouth is the fixture\n"); - - // The summary: each state by scenario, then the states' voices against each other. - let _ = writeln!(out, "## Summary\n\n| state | scenario | spoke | mean narration words | mean prose words |\n|---|---|---|---|---|"); - for state in &plan.states { - for scenario in &plan.scenarios { - let mine: Vec<&Value> = cases.iter().filter(|case| case["state"] == state.name.as_str() && case["scenario"] == scenario.name.as_str()).collect(); - let spoke = mine.iter().filter(|case| render_of(case)["interpreter"]["said"].as_array().is_some_and(|said| !said.is_empty())).count(); - let mean = |key: &dyn Fn(&Value) -> Option| mine.iter().filter_map(|case| key(render_of(case))).sum::() as f64 / mine.len().max(1) as f64; - let _ = writeln!(out, "| {} | {} | {spoke}/{} | {:.0} | {:.0} |", state.name, scenario.name, mine.len(), mean(&|render| render["words"].as_u64()), mean(&|render| render["persona"]["words"].as_u64())); - } - } - let corpora: Vec<(String, Vec)> = plan.states.iter().map(|state| (state.name.clone(), cases.iter().filter(|case| case["state"] == state.name.as_str()).map(prose_of).filter(|prose| !prose.is_empty()).collect())).collect(); - let _ = writeln!(out, "\nDistinct-2 of her prose within each state (1 is no repeated word pair), and over all states pooled:\n"); - for (name, prose) in &corpora { - let _ = writeln!(out, "- {name}: {:.3}", distinct_2(prose)); - } - let _ = writeln!(out, "- pooled: {:.3}", distinct_2(&corpora.iter().flat_map(|(_, prose)| prose.clone()).collect::>())); - let _ = writeln!(out, "\nWord-use similarity between states' prose (cosine of word counts, 1 is the same words in the same proportions):\n"); - for (at, (a, a_prose)) in corpora.iter().enumerate() { - for (b, b_prose) in &corpora[at + 1..] { - let _ = writeln!(out, "- {a} / {b}: {:.3}", cosine(&a_prose.join(" "), &b_prose.join(" "))); - } - } - - for case in cases { - let _ = writeln!(out, "\n## {} × {}, sample {} (seed {})\n", case["state"].as_str().unwrap_or_default(), case["scenario"].as_str().unwrap_or_default(), case["sample"], case["seed"]); - let report = &case["report"]; - if let Some(error) = report.get("error") { - let _ = writeln!(out, "**failed:** {}", error.as_str().unwrap_or_default()); - continue; - } - let packet = &report["packet"]; - let _ = writeln!(out, "- lens: `{}`; present: {}; room: {}", packet["lens"], packet["present"], report["room"]); - let _ = writeln!(out, "\n
packet\n"); - fenced(&mut out, "identity", packet["identity"].as_str().unwrap_or_default()); - fenced(&mut out, "context", packet["context"].as_str().unwrap_or_default()); - fenced(&mut out, "stimulus", packet["stimulus"].as_str().unwrap_or_default()); - fenced(&mut out, "heard", packet["heard"].as_str().unwrap_or_default()); - let _ = writeln!(out, "
\n"); - turn_markdown(&mut out, render_of(case)); - } - let _ = writeln!(out, "\n## Total usage\n\n{}", usage_markdown(&usage_total(cases))); - out -} - -/// One render's narration, prose, would-say lines, word counts and usage. -pub(crate) fn turn_markdown(out: &mut String, render: &Value) { - if let Some(failed) = render["failed"].as_str() { - let _ = writeln!(out, "**Projector call failed:** {failed} - -Usage: {} -", usage_line(&render["usage"])); - return; - } - let _ = writeln!(out, "**Narration** ({} words{}):\n", render["words"], if render["cut_at_budget"] == true { ", cut at budget" } else { "" }); - quoted(out, render["narration"].as_str().unwrap_or_default()); - if let Some(names) = render["field_names"].as_array().filter(|names| !names.is_empty()) { - let _ = writeln!(out, "**Field names leaked:** {}\n", Value::Array(names.clone())); - } - let _ = 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::>().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 = 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> { - fn walk(value: &Value, into: &mut BTreeMap>) { - match value { - Value::Object(map) => { - for (key, inner) in map { - if key == "usage" && inner.is_object() { - let model = inner["model"].as_str().unwrap_or("unknown").to_owned(); - let row = into.entry(model).or_default(); - *row.entry("calls".into()).or_default() += 1; - for field in USAGE_FIELDS { - *row.entry(field.into()).or_default() += inner[field].as_u64().unwrap_or(0); - } - } else { - walk(inner, into); - } - } - } - Value::Array(items) => items.iter().for_each(|inner| walk(inner, into)), - _ => {} - } - } - let mut total = BTreeMap::new(); - values.iter().for_each(|value| walk(value, &mut total)); - total -} - -pub(crate) fn usage_markdown(total: &BTreeMap>) -> String { - if total.is_empty() { - return "No model call was counted.".into(); - } - let mut out = String::from("| model | calls | input | output | cache read | cache write | reasoning |\n|---|---|---|---|---|---|---|\n"); - for (model, row) in total { - let get = |field: &str| row.get(field).copied().unwrap_or(0); - let _ = writeln!(out, "| {model} | {} | {} | {} | {} | {} | {} |", get("calls"), get("input_tokens"), get("output_tokens"), get("cache_read_tokens"), get("cache_write_tokens"), get("reasoning_tokens")); - } - out -} - -fn usage_line(usage: &Value) -> String { - if usage.is_null() { - return "none".into(); - } - format!("{} in, {} out, {} cache read", usage["input_tokens"], usage["output_tokens"], usage["cache_read_tokens"]) -} - -/// The words of a text as counted for similarity: lowercased, letters and digits, three characters or more. -fn word_counts(text: &str) -> BTreeMap { - let mut counts = BTreeMap::new(); - for word in text.split(|c: char| !c.is_alphanumeric()).filter(|word| word.chars().count() >= 3) { - *counts.entry(word.to_lowercase()).or_insert(0.0) += 1.0; - } - counts -} - -/// The cosine of two texts' word counts: 1 is the same words in the same proportions, 0 no word shared. A cheap -/// lexical proxy for one voice, not a measure of meaning. -pub(crate) fn cosine(a: &str, b: &str) -> f64 { - let (a, b) = (word_counts(a), word_counts(b)); - let dot: f64 = a.iter().filter_map(|(word, count)| b.get(word).map(|other| count * other)).sum(); - let norm = |counts: &BTreeMap| counts.values().map(|count| count * count).sum::().sqrt(); - let denominator = norm(&a) * norm(&b); - if denominator == 0.0 { 0.0 } else { dot / denominator } -} - -#[cfg(test)] -pub(crate) mod tests; diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs deleted file mode 100644 index 26d63bd..0000000 --- a/crates/mind-body/src/projection/harness/tests.rs +++ /dev/null @@ -1,301 +0,0 @@ -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>, - pub persona: Box String>, - pub interpreter: Box 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 = prose.split('"').enumerate().filter(|(at, part)| at % 2 == 1 && !part.trim().is_empty()).map(|(_, part)| json!({ "spans": [part], "mentions": [], "reply_to": null })).collect(); - json!({ "say": say }).to_string() -} - -impl Model for Scripted { - fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result { - self.calls.borrow_mut().push((model.to_owned(), prompt.to_owned())); - let text = if prompt.starts_with("You decide what one person says aloud") { - (self.interpreter)(prompt) - } else if prompt.starts_with("