diff --git a/crates/huginn-mind/src/persona.rs b/crates/huginn-mind/src/persona.rs index f9c31fe..9f92455 100644 --- a/crates/huginn-mind/src/persona.rs +++ b/crates/huginn-mind/src/persona.rs @@ -1,579 +1,584 @@ -//! The persona document: one `gamecult.persona_state.v0` per mind, stored -//! opaque and replaced whole. -//! -//! The shape is the published schema's, `schemas/cultnet/`, read here with -//! `include_bytes!`; the mind holds no Rust type for it, only the value that -//! passed the schema. `put_persona` (admission.rs) owns whether a document may -//! enter; this module owns what it is checked against and how it is stored and -//! read back. Nothing here echoes a caller's value: a refusal names a schema -//! location and a keyword, never the text that failed. - -use std::collections::BTreeSet; -use std::sync::OnceLock; - -use cultcache_rs::{CultCacheEnvelope, DatabaseEntry}; -use jsonschema::paths::LocationSegment; -use jsonschema::error::ValidationErrorKind; -use jsonschema::Validator; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -use crate::mind::Mind; -use crate::refusal::MindRefusal; -use crate::store::MindStore; - -const PERSONA_SCHEMA: &[u8] = include_bytes!("../../../schemas/cultnet/gamecult.persona_state.v0.schema.json"); - -/// The stored envelope's payload: the document, one slot, keyed by the mind's -/// instance. The cache needs a registered entry type to hold the envelope; the -/// document inside stays a value. -#[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache(type = "gamecult.persona_state.v0", schema = "HuginnPersonaEntry")] -pub struct HuginnPersonaEntry { - #[cultcache(key = 0)] - pub value: Value, -} - -/// What `PersonaGet` answers: the stored document, its `updatedAt`, and the -/// receipt of the put that wrote it. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub struct PersonaStateView { - pub value: Value, - pub updated_at: String, - pub receipt_id: String, -} - -/// How a put ended. A refusal is an answer, as for `admit`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub enum PersonaPutOutcome { - Committed { receipt_id: String }, - Refused(MindRefusal), -} - -struct Compiled { - validator: Validator, - /// Every property name the schema declares. A path segment outside this - /// set is a caller's key (`traitMap` keys are free), so it is withheld. - declared: BTreeSet, -} - -fn compiled() -> Result<&'static Compiled, MindRefusal> { - static COMPILED: OnceLock> = OnceLock::new(); - COMPILED - .get_or_init(|| { - let schema: Value = serde_json::from_slice(PERSONA_SCHEMA) - .map_err(|error| format!("the published persona schema does not parse: {error}"))?; - let validator = jsonschema::draft7::new(&schema) - .map_err(|error| format!("the published persona schema does not compile: {error}"))?; - let mut declared = BTreeSet::new(); - declared_names(&schema, &mut declared); - Ok(Compiled { validator, declared }) - }) - .as_ref() - .map_err(|detail| MindRefusal::Unavailable { detail: detail.clone() }) -} - -fn declared_names(node: &Value, names: &mut BTreeSet) { - match node { - Value::Object(map) => { - if let Some(Value::Object(properties)) = map.get("properties") { - names.extend(properties.keys().cloned()); - } - map.values().for_each(|child| declared_names(child, names)); - } - Value::Array(items) => items.iter().for_each(|child| declared_names(child, names)), - _ => {} - } -} - -/// Rule 1: the document is valid against the published schema. The first -/// failure is the refusal; it names where and which keyword, never the value. -pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> { - let compiled = compiled()?; - let Err(error) = compiled.validator.validate(state) else { return Ok(()) }; - let mut path = error - .instance_path() - .segments() - .map(|segment| match segment { - LocationSegment::Index(index) => index.to_string(), - LocationSegment::Property(name) if compiled.declared.contains(name.as_ref()) => name.into_owned(), - LocationSegment::Property(_) => "*".to_string(), - }) - .collect::>(); - match error.kind() { - ValidationErrorKind::Required { property } => path.extend(property.as_str().map(str::to_string)), - ValidationErrorKind::AdditionalProperties { .. } => path.push("*".to_string()), - _ => {} - } - Err(MindRefusal::PersonaInvalid { - path: format!("/{}", path.join("/")), - message: format!("fails the published schema's {} rule", error.kind().keyword()), - }) -} - -/// A stored persona envelope's document. -pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result { - rmp_serde::from_slice::(&envelope.payload) - .map(|entry| entry.value) - .map_err(|error| MindRefusal::Unavailable { detail: format!("the stored persona does not decode: {error}") }) -} - -/// A document's `updatedAt`; the schema makes it a required string. -pub(crate) fn updated_at(value: &Value) -> Option<&str> { - value.get("updatedAt").and_then(Value::as_str) -} - -impl Mind { - /// This mind's persona envelope, if one is stored. - pub(crate) fn persona_envelope(&self) -> Option<&CultCacheEnvelope> { - self.raw_envelope(HuginnPersonaEntry::TYPE, &self.instance().0) - } - - /// The stored `updatedAt`; none when no persona is stored. - pub(crate) fn stored_updated_at(&self) -> Result, MindRefusal> { - let Some(envelope) = self.persona_envelope() else { return Ok(None) }; - let value = decode(envelope)?; - updated_at(&value) - .map(|stamp| Some(stamp.to_string())) - .ok_or_else(|| MindRefusal::Unavailable { detail: "the stored persona has no updatedAt".into() }) - } - - /// `PersonaGet`: the document, its `updatedAt` and the receipt of the put - /// that wrote exactly these bytes. - pub fn persona(&self) -> Result, MindRefusal> { - let Some(envelope) = self.persona_envelope() else { return Ok(None) }; - let value = decode(envelope)?; - let integrity = |detail: &str| MindRefusal::Unavailable { detail: detail.into() }; - let updated_at = updated_at(&value).ok_or_else(|| integrity("the stored persona has no updatedAt"))?.to_string(); - let identity = (envelope.r#type.as_str(), envelope.key.as_str()); - let receipt_id = self - .receipts()? - .into_iter() - .filter(|receipt| receipt.writes.iter().any(|write| write.identity() == identity)) - .max_by_key(|receipt| receipt.ordinal) - .ok_or_else(|| integrity("the stored persona has no receipt"))? - .receipt_id; - Ok(Some(PersonaStateView { value, updated_at, receipt_id })) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::fixtures::{INSTANCE, OTHER_INSTANCE, epoch, instance, opened, prepare, provenance, seed, slug}; - use crate::receipt::Faculty; - use crate::store::test_stores::{MemoryStore, RefusingStore, SwapCommand}; - use eureka_pipeline::PipelineKind; - use serde_json::json; - - const T1: &str = "2026-10-10T10:00:00Z"; - const T2: &str = "2026-10-10T10:00:01Z"; - const T3: &str = "2026-10-10T10:00:02Z"; - const CANARY: &str = "CANARY-7f3a91-do-not-echo"; - const NOT_LATER: &str = "must be later than the stored updatedAt"; - - /// A minimal document the published schema accepts. The test that follows - /// holds it to the schema file's own required list. - fn persona(id: &str, updated_at: &str) -> Value { - let traits = json!({ - "underlyingOrganization": {}, "stableDispositions": {}, "behavioralDimensions": {}, - "presentationStrategy": {}, "voiceStyle": {}, "situationalState": {} - }); - json!({ - "schemaVersion": "gamecult.persona_state.v0", - "provenance": { - "sourceSystem": "huginn", "sourceDocumentId": id, "sourceUpdatedAt": updated_at, - "exportedAt": updated_at, "authority": "canonical" - }, - "personaId": id, - "publicName": "Test Persona", - "presentation": { "voiceSummary": "plain" }, - "activationProfile": traits, - "thoughtMemory": { "shortTerm": [], "memories": [], "incubation": [] }, - "agencyPressure": { "pressures": [] }, - "candidateActions": { "actions": [] }, - "affect": { - "needs": [], "socialBonds": [], "statusReads": [], "moodDimensions": [], - "socialBiases": [], "doctrineStances": [] - }, - "updatedAt": updated_at - }) - } - - fn schema_file() -> Value { - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../schemas/cultnet/gamecult.persona_state.v0.schema.json"); - serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() - } - - fn put(mind: &mut Mind, state: Value, expected: Option<&str>) -> PersonaPutOutcome { - let instance = mind.instance().clone(); - mind.put_persona(&instance, state, expected.map(str::to_string), provenance(Faculty::Hands), crate::fixtures::now()) - } - - fn committed(outcome: PersonaPutOutcome) -> String { - match outcome { - PersonaPutOutcome::Committed { receipt_id } => receipt_id, - other => panic!("expected a commit, got {other:?}"), - } - } - - fn refused(outcome: PersonaPutOutcome) -> MindRefusal { - match outcome { - PersonaPutOutcome::Refused(refusal) => refusal, - other => panic!("expected a refusal, got {other:?}"), - } - } - - fn invalid(path: &str, rule: &str) -> MindRefusal { - MindRefusal::PersonaInvalid { path: path.into(), message: format!("fails the published schema's {rule} rule") } - } - - fn not_later() -> MindRefusal { - MindRefusal::PersonaInvalid { path: "/updatedAt".into(), message: NOT_LATER.into() } - } - - fn stale(stored: Option<&str>) -> MindRefusal { - MindRefusal::PersonaStale { stored: stored.map(str::to_string) } - } - - fn seeded_over(store: &MemoryStore) -> Mind { - let mut mind = opened(store.clone(), INSTANCE); - seed(&mut mind); - mind - } - - fn persona_in_status(mind: &Mind) -> crate::wire::PersonaStatus { - mind.status(crate::wire::IndexStatus::Current).persona - } - - #[test] - fn the_fixture_is_valid_against_the_published_file_and_covers_its_required_fields() { - let schema = schema_file(); - let validator = jsonschema::draft7::new(&schema).unwrap(); - let document = persona(INSTANCE, T1); - assert!(validator.is_valid(&document)); - for name in schema["required"].as_array().unwrap() { - assert!(document.get(name.as_str().unwrap()).is_some(), "the fixture lacks {name}"); - } - } - - #[test] - fn declared_names_are_every_property_name_at_any_depth() { - let schema = json!({ - "properties": { "a": { "properties": { "b": {} } } }, - "allOf": [{ "properties": { "c": {} } }], - "definitions": { "d": { "properties": { "e": {} } } }, - "required": ["not-a-property"] - }); - let mut names = BTreeSet::new(); - declared_names(&schema, &mut names); - assert_eq!(names, BTreeSet::from(["a", "b", "c", "e"].map(String::from))); - } - - /// `identity-write-all-visible`: a put may change any field, the identity - /// fields included, and a change the next second is no less admissible. - #[test] - fn a_put_may_rewrite_identity_fields_and_every_change_lands() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - committed(put(&mut mind, persona(INSTANCE, T1), None)); - - let mut renamed = persona(INSTANCE, T2); - renamed["publicName"] = json!("A New Name"); - renamed["publicDescription"] = json!("who she says she is"); - renamed["presentation"] = json!({ "voiceSummary": "warmer", "pronouns": "she/her" }); - renamed["values"] = json!([{ "id": "v1", "label": "candor", "priority": 0.9 }]); - committed(put(&mut mind, renamed.clone(), Some(T1))); - assert_eq!(mind.persona().unwrap().unwrap().value, renamed); - - let mut again = persona(INSTANCE, T3); - again["publicName"] = json!("Another Name"); - committed(put(&mut mind, again.clone(), Some(T2))); - assert_eq!(mind.persona().unwrap().unwrap().value, again); - } - - #[test] - fn the_view_names_the_receipt_of_the_latest_put() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - let mut previous: Option = None; - for second in 0..5 { - let stamp = format!("2026-10-10T10:00:0{second}Z"); - let receipt = committed(put(&mut mind, persona(INSTANCE, &stamp), previous.as_deref())); - assert_eq!(mind.persona().unwrap().unwrap().receipt_id, receipt, "after put {second}"); - previous = Some(stamp); - } - } - - #[test] - fn a_persona_document_is_validated_at_the_door() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - let before = store.rows(); - - for name in schema_file()["required"].as_array().unwrap() { - let name = name.as_str().unwrap(); - let mut document = persona(INSTANCE, T1); - document.as_object_mut().unwrap().remove(name); - assert_eq!(refused(put(&mut mind, document, None)), invalid(&format!("/{name}"), "required"), "{name}"); - } - - let mut extra = persona(INSTANCE, T1); - extra["notInTheSchema"] = json!(1); - assert_eq!(refused(put(&mut mind, extra, None)), invalid("/*", "additionalProperties")); - - let mut wrong_type = persona(INSTANCE, T1); - wrong_type["publicName"] = json!(5); - assert_eq!(refused(put(&mut mind, wrong_type, None)), invalid("/publicName", "type")); - - let mut bad_stamp = persona(INSTANCE, T1); - bad_stamp["updatedAt"] = json!("yesterday"); - assert_eq!(refused(put(&mut mind, bad_stamp, None)), invalid("/updatedAt", "format")); - - let mut nested = persona(INSTANCE, T1); - nested["thoughtMemory"]["memories"] = json!([7]); - assert_eq!(refused(put(&mut mind, nested, None)), invalid("/thoughtMemory/memories/0", "type")); - - let mut free_key = persona(INSTANCE, T1); - free_key["activationProfile"]["voiceStyle"]["any-key"] = json!({}); - assert_eq!( - refused(put(&mut mind, free_key, None)), - invalid("/activationProfile/voiceStyle/*/mean", "required"), - "a key the schema does not declare is withheld from the path" - ); - - assert_eq!(store.rows(), before, "no refusal wrote anything"); - assert_eq!(mind.persona().unwrap(), None); - } - - #[test] - fn a_refusal_never_echoes_what_the_caller_sent() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - committed(put(&mut mind, persona(INSTANCE, T2), None)); - - let mut free_key = persona(INSTANCE, T3); - free_key["activationProfile"]["voiceStyle"][CANARY] = json!({}); - let mut extra_key = persona(INSTANCE, T3); - extra_key[CANARY] = json!(CANARY); - let mut bad_value = persona(INSTANCE, T3); - bad_value["updatedAt"] = json!(CANARY); - let mut bad_enum = persona(INSTANCE, T3); - bad_enum["provenance"]["authority"] = json!(CANARY); - let mut foreign = persona(CANARY, T3); - foreign["publicName"] = json!(CANARY); - let mut imported = persona(INSTANCE, T3); - imported["provenance"]["authority"] = json!("import"); - imported["provenance"]["sourceSystem"] = json!(CANARY); - let mut late = persona(INSTANCE, T1); - late["publicName"] = json!(CANARY); - - let cases: Vec<(Value, Option<&str>)> = vec![ - (free_key, Some(T2)), - (extra_key, Some(T2)), - (bad_value, Some(T2)), - (bad_enum, Some(T2)), - (foreign, Some(T2)), - (imported, Some(T2)), - (late, Some(T2)), - (persona(INSTANCE, T3), Some(CANARY)), - ]; - for (document, expected) in cases { - let refusal = refused(put(&mut mind, document, expected)); - assert!(!format!("{refusal:?}").contains(CANARY), "{refusal:?}"); - assert!(!serde_json::to_string(&refusal).unwrap().contains(CANARY)); - } - } - - #[test] - fn persona_id_must_be_the_instance() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - let before = store.rows(); - let refusal = refused(put(&mut mind, persona(OTHER_INSTANCE, T1), None)); - assert_eq!(refusal, MindRefusal::PersonaForeign { instance: INSTANCE.into() }); - assert_eq!(store.rows(), before); - assert_eq!(mind.persona().unwrap(), None); - } - - #[test] - fn only_a_canonical_document_is_the_minds_persona() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - for authority in ["projection", "import"] { - let mut document = persona(INSTANCE, T1); - document["provenance"]["authority"] = json!(authority); - assert_eq!(refused(put(&mut mind, document, None)), MindRefusal::PersonaNotCanonical, "{authority}"); - } - assert_eq!(mind.persona().unwrap(), None); - } - - #[test] - fn a_persona_waits_for_the_minds_identity() { - let mut mind = opened(MemoryStore::new(), INSTANCE); - assert_eq!(refused(put(&mut mind, persona(INSTANCE, T1), None)), MindRefusal::MissingIdentity); - assert!(mind.is_empty()); - } - - #[test] - fn a_put_must_name_this_mind_and_a_named_asker() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - let before = store.rows(); - let other = slug(OTHER_INSTANCE); - let outcome = mind.put_persona(&other, persona(INSTANCE, T1), None, provenance(Faculty::Hands), crate::fixtures::now()); - assert!(matches!(refused(outcome), MindRefusal::ForeignInstance { .. })); - let mut unnamed = provenance(Faculty::Hands); - unnamed.agent = eureka_pipeline::Short(" ".into()); - let instance = mind.instance().clone(); - let outcome = mind.put_persona(&instance, persona(INSTANCE, T1), None, unnamed, crate::fixtures::now()); - assert!(matches!(refused(outcome), MindRefusal::Document(_))); - assert_eq!(store.rows(), before); - } - - #[test] - fn a_put_is_a_compare_and_swap_on_updated_at() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - assert_eq!(persona_in_status(&mind), crate::wire::PersonaStatus::Absent); - let receipts = |mind: &Mind| mind.receipts().unwrap().len(); - let base = receipts(&mind); - - // A first put expects nothing; claiming a stored document is stale. - assert_eq!(refused(put(&mut mind, persona(INSTANCE, T1), Some(T1))), stale(None)); - let first = committed(put(&mut mind, persona(INSTANCE, T1), None)); - assert_eq!(receipts(&mind), base + 1); - let view = mind.persona().unwrap().unwrap(); - assert_eq!((view.updated_at.as_str(), view.receipt_id.as_str()), (T1, first.as_str())); - assert_eq!(view.value, persona(INSTANCE, T1)); - assert_eq!(persona_in_status(&mind), crate::wire::PersonaStatus::Stored { updated_at: T1.into() }); - - // Two puts that read the same stored document: the second loses. - let second = committed(put(&mut mind, persona(INSTANCE, T2), Some(T1))); - assert_eq!(receipts(&mind), base + 2); - let rows = store.rows(); - assert_eq!(refused(put(&mut mind, persona(INSTANCE, T3), Some(T1))), stale(Some(T2))); - assert_eq!(refused(put(&mut mind, persona(INSTANCE, T3), None)), stale(Some(T2))); - assert_eq!(store.rows(), rows, "a stale put wrote nothing"); - - // The right expectation with an updatedAt that is not later. - assert_eq!(refused(put(&mut mind, persona(INSTANCE, T2), Some(T2))), not_later()); - assert_eq!(refused(put(&mut mind, persona(INSTANCE, T1), Some(T2))), not_later()); - // Instants compare, not spellings: the same instant at another offset is not later. - assert_eq!(refused(put(&mut mind, persona(INSTANCE, "2026-10-10T12:00:01+02:00"), Some(T2))), not_later()); - assert_eq!(store.rows(), rows); - assert_eq!(receipts(&mind), base + 2); - committed(put(&mut mind, persona(INSTANCE, "2026-10-10T12:00:02+02:00"), Some(T2))); - assert_eq!(receipts(&mind), base + 3); - - // The second put's receipt read the first document and wrote the second. - let receipt = mind.receipts().unwrap().into_iter().find(|receipt| receipt.receipt_id == second).unwrap(); - assert_eq!((receipt.strong_reads.len(), receipt.writes.len()), (1, 1)); - assert_eq!(receipt.strong_reads[0].document_key, INSTANCE); - assert_ne!(receipt.strong_reads[0].payload_msgpack, receipt.writes[0].payload_msgpack); - assert_eq!(receipt.provenance, provenance(Faculty::Hands)); - } - - #[test] - fn a_put_whose_swap_is_lost_is_stale_and_changes_nothing() { - let store = RefusingStore::new(); - let mut mind = opened(store.clone(), INSTANCE); - seed(&mut mind); - committed(put(&mut mind, persona(INSTANCE, T1), None)); - let rows = store.rows(); - store.command(SwapCommand::Lose); - assert_eq!(refused(put(&mut mind, persona(INSTANCE, T2), Some(T1))), stale(Some(T1))); - assert_eq!(store.rows(), rows); - } - - #[test] - fn the_persona_is_not_a_pipeline_document_and_a_batch_cannot_carry_it() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - let documents = mind.status(crate::wire::IndexStatus::Current).documents; - committed(put(&mut mind, persona(INSTANCE, T1), None)); - assert_eq!(mind.status(crate::wire::IndexStatus::Current).documents, documents); - assert!(PipelineKind::ALL.iter().all(|kind| kind.type_id() != HuginnPersonaEntry::TYPE)); - let forged = mind.persona_envelope().unwrap().clone(); - let instance = mind.instance().clone(); - let outcome = mind.admit_prepared(&instance, provenance(Faculty::Hands), vec![forged], crate::fixtures::now()); - assert!(matches!(outcome, crate::admission::PipelineAdmissionOutcome::Refused(_)), "{outcome:?}"); - } - - #[test] - fn one_persona_per_mind_and_the_store_still_opens() { - let yggdrasil = slug(INSTANCE); - let cache = crate::mind::schema_cache().unwrap(); - let entry = |key: &str, value: Value| cache.prepare_entry_named(key, &HuginnPersonaEntry { value }).unwrap().0; - let planted = |rows: Vec| { - let store = MemoryStore::new(); - rows.into_iter().for_each(|row| store.plant(row)); - store - }; - let base = || vec![epoch(), prepare(&instance(INSTANCE))]; - - // A store written before this type existed opens unchanged. - assert!(Mind::open_with(planted(base()), &yggdrasil).is_ok()); - - // One persona opens and reads back. - let mut with_one = base(); - with_one.push(entry(INSTANCE, persona(INSTANCE, T1))); - let mind = Mind::open_with(planted(with_one.clone()), &yggdrasil).unwrap(); - assert_eq!(mind.envelopes().len(), 3); - assert_eq!(persona_in_status(&mind), crate::wire::PersonaStatus::Stored { updated_at: T1.into() }); - - // Two are no mind's. - with_one.push(entry("second", persona(INSTANCE, T2))); - assert_eq!( - Mind::open_with(planted(with_one), &yggdrasil).err(), - Some(MindRefusal::ForeignStore { r#type: HuginnPersonaEntry::TYPE.into() }) - ); - // The opener still refuses a type that is not one of the seventeen. - let mut stranger = base(); - let mut foreign = entry(INSTANCE, persona(INSTANCE, T1)); - foreign.r#type = "gamecult.persona_state.v1".into(); - stranger.push(foreign); - assert!(matches!(Mind::open_with(planted(stranger), &yggdrasil).err(), Some(MindRefusal::ForeignStore { .. }))); - } - - /// Status answers in the door's own terms: a stored persona the door - /// cannot read is `Unreadable`, not the `Absent` of a mind with none, while - /// `PersonaGet` answers `Unavailable` for the same bytes. - #[test] - fn status_says_unreadable_where_the_door_says_unavailable() { - let yggdrasil = slug(INSTANCE); - let cache = crate::mind::schema_cache().unwrap(); - let readable = cache.prepare_entry_named(INSTANCE, &HuginnPersonaEntry { value: persona(INSTANCE, T1) }).unwrap().0; - let no_stamp = cache.prepare_entry_named(INSTANCE, &HuginnPersonaEntry { value: json!({}) }).unwrap().0; - let mut undecodable = readable.clone(); - undecodable.payload = vec![0xc1]; - for (row, status) in [ - (readable, crate::wire::PersonaStatus::Stored { updated_at: T1.into() }), - (no_stamp, crate::wire::PersonaStatus::Unreadable), - (undecodable, crate::wire::PersonaStatus::Unreadable), - ] { - let store = MemoryStore::new(); - store.plant(epoch()); - store.plant(prepare(&instance(INSTANCE))); - store.plant(row); - let mind = Mind::open_with(store, &yggdrasil).unwrap(); - assert_eq!(persona_in_status(&mind), status); - if status == crate::wire::PersonaStatus::Unreadable { - assert!(matches!(mind.persona(), Err(MindRefusal::Unavailable { .. })), "the door answers what the status says"); - } - } - assert_eq!(persona_in_status(&seeded_over(&MemoryStore::new())), crate::wire::PersonaStatus::Absent); - } - - #[test] - fn the_stored_bytes_are_the_one_slot_array_the_catalogue_describes() { - let store = MemoryStore::new(); - let mut mind = seeded_over(&store); - committed(put(&mut mind, persona(INSTANCE, T1), None)); - let envelope = mind.persona_envelope().unwrap(); - assert_eq!((envelope.r#type.as_str(), envelope.key.as_str()), ("gamecult.persona_state.v0", INSTANCE)); - let slots: (Value,) = rmp_serde::from_slice(&envelope.payload).unwrap(); - assert_eq!(slots.0, persona(INSTANCE, T1)); - } -} +//! The persona document: one `gamecult.persona_state.v0` per mind, stored +//! opaque and replaced whole. +//! +//! The shape is the published schema's, `schemas/cultnet/`, read here with +//! `include_bytes!`; the mind holds no Rust type for it, only the value that +//! passed the schema. `put_persona` (admission.rs) owns whether a document may +//! enter; this module owns what it is checked against and how it is stored and +//! read back. Nothing here echoes a caller's value: a refusal names a schema +//! location and a keyword, never the text that failed. + +use std::collections::BTreeSet; +use std::sync::OnceLock; + +use cultcache_rs::{CultCacheEnvelope, DatabaseEntry}; +use jsonschema::paths::LocationSegment; +use jsonschema::error::ValidationErrorKind; +use jsonschema::Validator; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::mind::Mind; +use crate::refusal::MindRefusal; +use crate::store::MindStore; + +const PERSONA_SCHEMA: &[u8] = include_bytes!("../../../schemas/cultnet/gamecult.persona_state.v0.schema.json"); + +/// The stored envelope's payload: the document, one slot, keyed by the mind's +/// instance. The cache needs a registered entry type to hold the envelope; the +/// document inside stays a value. +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.persona_state.v0", schema = "HuginnPersonaEntry")] +pub struct HuginnPersonaEntry { + #[cultcache(key = 0)] + pub value: Value, +} + +/// What `PersonaGet` answers: the stored document, its `updatedAt`, and the +/// receipt of the put that wrote it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct PersonaStateView { + pub value: Value, + pub updated_at: String, + pub receipt_id: String, +} + +/// How a put ended. A refusal is an answer, as for `admit`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum PersonaPutOutcome { + Committed { receipt_id: String }, + Refused(MindRefusal), +} + +struct Compiled { + validator: Validator, + /// Every property name the schema declares. A path segment outside this + /// set is a caller's key (`traitMap` keys are free), so it is withheld. + declared: BTreeSet, +} + +fn compiled() -> Result<&'static Compiled, MindRefusal> { + static COMPILED: OnceLock> = OnceLock::new(); + COMPILED + .get_or_init(|| { + let schema: Value = serde_json::from_slice(PERSONA_SCHEMA) + .map_err(|error| format!("the published persona schema does not parse: {error}"))?; + let validator = jsonschema::draft7::new(&schema) + .map_err(|error| format!("the published persona schema does not compile: {error}"))?; + let mut declared = BTreeSet::new(); + declared_names(&schema, &mut declared); + Ok(Compiled { validator, declared }) + }) + .as_ref() + .map_err(|detail| MindRefusal::Unavailable { detail: detail.clone() }) +} + +fn declared_names(node: &Value, names: &mut BTreeSet) { + match node { + Value::Object(map) => { + if let Some(Value::Object(properties)) = map.get("properties") { + names.extend(properties.keys().cloned()); + } + map.values().for_each(|child| declared_names(child, names)); + } + Value::Array(items) => items.iter().for_each(|child| declared_names(child, names)), + _ => {} + } +} + +/// Rule 1: the document is valid against the published schema. The first +/// failure is the refusal; it names where and which keyword, never the value. +pub(crate) fn validate_shape(state: &Value) -> Result<(), MindRefusal> { + let compiled = compiled()?; + let Err(error) = compiled.validator.validate(state) else { return Ok(()) }; + let mut path = error + .instance_path() + .segments() + .map(|segment| match segment { + LocationSegment::Index(index) => index.to_string(), + LocationSegment::Property(name) if compiled.declared.contains(name.as_ref()) => name.into_owned(), + LocationSegment::Property(_) => "*".to_string(), + }) + .collect::>(); + match error.kind() { + ValidationErrorKind::Required { property } => path.extend(property.as_str().map(str::to_string)), + ValidationErrorKind::AdditionalProperties { .. } => path.push("*".to_string()), + _ => {} + } + Err(MindRefusal::PersonaInvalid { + path: format!("/{}", path.join("/")), + message: format!("fails the published schema's {} rule", error.kind().keyword()), + }) +} + +/// A stored persona envelope's document. +pub(crate) fn decode(envelope: &CultCacheEnvelope) -> Result { + rmp_serde::from_slice::(&envelope.payload) + .map(|entry| entry.value) + .map_err(|error| MindRefusal::Unavailable { detail: format!("the stored persona does not decode: {error}") }) +} + +/// A document's `updatedAt`; the schema makes it a required string. +pub(crate) fn updated_at(value: &Value) -> Option<&str> { + value.get("updatedAt").and_then(Value::as_str) +} + +impl Mind { + /// This mind's persona envelope, if one is stored. + pub(crate) fn persona_envelope(&self) -> Option<&CultCacheEnvelope> { + self.raw_envelope(HuginnPersonaEntry::TYPE, &self.instance().0) + } + + /// The stored `updatedAt`; none when no persona is stored. + pub(crate) fn stored_updated_at(&self) -> Result, MindRefusal> { + let Some(envelope) = self.persona_envelope() else { return Ok(None) }; + let value = decode(envelope)?; + updated_at(&value) + .map(|stamp| Some(stamp.to_string())) + .ok_or_else(|| MindRefusal::Unavailable { detail: "the stored persona has no updatedAt".into() }) + } + + /// `PersonaGet`: the document, its `updatedAt` and the receipt of the put + /// that wrote exactly these bytes. + pub fn persona(&self) -> Result, MindRefusal> { + let Some(envelope) = self.persona_envelope() else { return Ok(None) }; + let value = decode(envelope)?; + let integrity = |detail: &str| MindRefusal::Unavailable { detail: detail.into() }; + let updated_at = updated_at(&value).ok_or_else(|| integrity("the stored persona has no updatedAt"))?.to_string(); + let identity = (envelope.r#type.as_str(), envelope.key.as_str()); + let receipt_id = self + .receipts()? + .into_iter() + .filter(|receipt| receipt.writes.iter().any(|write| write.identity() == identity)) + .max_by_key(|receipt| receipt.ordinal) + .ok_or_else(|| integrity("the stored persona has no receipt"))? + .receipt_id; + Ok(Some(PersonaStateView { value, updated_at, receipt_id })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixtures::{INSTANCE, OTHER_INSTANCE, epoch, instance, opened, prepare, provenance, seed, slug}; + use crate::receipt::Faculty; + use crate::store::test_stores::{MemoryStore, RefusingStore, SwapCommand}; + use eureka_pipeline::PipelineKind; + use serde_json::json; + + const T1: &str = "2026-10-10T10:00:00Z"; + const T2: &str = "2026-10-10T10:00:01Z"; + const T3: &str = "2026-10-10T10:00:02Z"; + const CANARY: &str = "CANARY-7f3a91-do-not-echo"; + const NOT_LATER: &str = "must be later than the stored updatedAt"; + + /// A minimal document the published schema accepts. The test that follows + /// holds it to the schema file's own required list. + fn persona(id: &str, updated_at: &str) -> Value { + let traits = json!({ + "underlyingOrganization": {}, "stableDispositions": {}, "behavioralDimensions": {}, + "presentationStrategy": {}, "voiceStyle": {}, "situationalState": {} + }); + json!({ + "schemaVersion": "gamecult.persona_state.v0", + "provenance": { + "sourceSystem": "huginn", "sourceDocumentId": id, "sourceUpdatedAt": updated_at, + "exportedAt": updated_at, "authority": "canonical" + }, + "personaId": id, + "publicName": "Test Persona", + "presentation": { "voiceSummary": "plain" }, + "activationProfile": traits, + "thoughtMemory": { "shortTerm": [], "memories": [], "incubation": [] }, + "agencyPressure": { "pressures": [] }, + "candidateActions": { "actions": [] }, + "affect": { + "needs": [], "socialBonds": [], "statusReads": [], "moodDimensions": [], + "socialBiases": [], "doctrineStances": [] + }, + "updatedAt": updated_at + }) + } + + fn schema_file() -> Value { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../schemas/cultnet/gamecult.persona_state.v0.schema.json"); + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() + } + + fn put(mind: &mut Mind, state: Value, expected: Option<&str>) -> PersonaPutOutcome { + let instance = mind.instance().clone(); + mind.put_persona(&instance, state, expected.map(str::to_string), provenance(Faculty::Hands), crate::fixtures::now()) + } + + fn committed(outcome: PersonaPutOutcome) -> String { + match outcome { + PersonaPutOutcome::Committed { receipt_id } => receipt_id, + other => panic!("expected a commit, got {other:?}"), + } + } + + fn refused(outcome: PersonaPutOutcome) -> MindRefusal { + match outcome { + PersonaPutOutcome::Refused(refusal) => refusal, + other => panic!("expected a refusal, got {other:?}"), + } + } + + fn invalid(path: &str, rule: &str) -> MindRefusal { + MindRefusal::PersonaInvalid { path: path.into(), message: format!("fails the published schema's {rule} rule") } + } + + fn not_later() -> MindRefusal { + MindRefusal::PersonaInvalid { path: "/updatedAt".into(), message: NOT_LATER.into() } + } + + fn stale(stored: Option<&str>) -> MindRefusal { + MindRefusal::PersonaStale { stored: stored.map(str::to_string) } + } + + fn seeded_over(store: &MemoryStore) -> Mind { + let mut mind = opened(store.clone(), INSTANCE); + seed(&mut mind); + mind + } + + fn persona_in_status(mind: &Mind) -> crate::wire::PersonaStatus { + mind.status(crate::wire::IndexStatus::Current).persona + } + + #[test] + fn the_fixture_is_valid_against_the_published_file_and_covers_its_required_fields() { + let schema = schema_file(); + let validator = jsonschema::draft7::new(&schema).unwrap(); + let document = persona(INSTANCE, T1); + assert!(validator.is_valid(&document)); + for name in schema["required"].as_array().unwrap() { + assert!(document.get(name.as_str().unwrap()).is_some(), "the fixture lacks {name}"); + } + } + + #[test] + fn declared_names_are_every_property_name_at_any_depth() { + let schema = json!({ + "properties": { "a": { "properties": { "b": {} } } }, + "allOf": [{ "properties": { "c": {} } }], + "definitions": { "d": { "properties": { "e": {} } } }, + "required": ["not-a-property"] + }); + let mut names = BTreeSet::new(); + declared_names(&schema, &mut names); + assert_eq!(names, BTreeSet::from(["a", "b", "c", "e"].map(String::from))); + } + + /// `identity-write-all-visible`: a put may change any field, the identity + /// fields included, and a change the next second is no less admissible. + #[test] + fn a_put_may_rewrite_identity_fields_and_every_change_lands() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + committed(put(&mut mind, persona(INSTANCE, T1), None)); + + let mut renamed = persona(INSTANCE, T2); + renamed["publicName"] = json!("A New Name"); + renamed["publicDescription"] = json!("who she says she is"); + renamed["presentation"] = json!({ "voiceSummary": "warmer", "pronouns": "she/her" }); + renamed["values"] = json!([{ "id": "v1", "label": "candor", "priority": 0.9 }]); + committed(put(&mut mind, renamed.clone(), Some(T1))); + assert_eq!(mind.persona().unwrap().unwrap().value, renamed); + + let mut again = persona(INSTANCE, T3); + again["publicName"] = json!("Another Name"); + committed(put(&mut mind, again.clone(), Some(T2))); + assert_eq!(mind.persona().unwrap().unwrap().value, again); + } + + #[test] + fn the_view_names_the_receipt_of_the_latest_put() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + let mut previous: Option = None; + for second in 0..5 { + let stamp = format!("2026-10-10T10:00:0{second}Z"); + let receipt = committed(put(&mut mind, persona(INSTANCE, &stamp), previous.as_deref())); + assert_eq!(mind.persona().unwrap().unwrap().receipt_id, receipt, "after put {second}"); + previous = Some(stamp); + } + } + + #[test] + fn a_persona_document_is_validated_at_the_door() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + let before = store.rows(); + + for name in schema_file()["required"].as_array().unwrap() { + let name = name.as_str().unwrap(); + let mut document = persona(INSTANCE, T1); + document.as_object_mut().unwrap().remove(name); + assert_eq!(refused(put(&mut mind, document, None)), invalid(&format!("/{name}"), "required"), "{name}"); + } + + let mut extra = persona(INSTANCE, T1); + extra["notInTheSchema"] = json!(1); + assert_eq!(refused(put(&mut mind, extra, None)), invalid("/*", "additionalProperties")); + + let mut wrong_type = persona(INSTANCE, T1); + wrong_type["publicName"] = json!(5); + assert_eq!(refused(put(&mut mind, wrong_type, None)), invalid("/publicName", "type")); + + let mut bad_stamp = persona(INSTANCE, T1); + bad_stamp["updatedAt"] = json!("yesterday"); + assert_eq!(refused(put(&mut mind, bad_stamp, None)), invalid("/updatedAt", "format")); + + let mut nested = persona(INSTANCE, T1); + nested["thoughtMemory"]["memories"] = json!([7]); + assert_eq!(refused(put(&mut mind, nested, None)), invalid("/thoughtMemory/memories/0", "type")); + + let mut free_key = persona(INSTANCE, T1); + free_key["activationProfile"]["voiceStyle"]["any-key"] = json!({}); + assert_eq!( + refused(put(&mut mind, free_key, None)), + invalid("/activationProfile/voiceStyle/*/mean", "required"), + "a key the schema does not declare is withheld from the path" + ); + + assert_eq!(store.rows(), before, "no refusal wrote anything"); + assert_eq!(mind.persona().unwrap(), None); + } + + #[test] + fn a_refusal_never_echoes_what_the_caller_sent() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + committed(put(&mut mind, persona(INSTANCE, T2), None)); + + let mut free_key = persona(INSTANCE, T3); + free_key["activationProfile"]["voiceStyle"][CANARY] = json!({}); + let mut extra_key = persona(INSTANCE, T3); + extra_key[CANARY] = json!(CANARY); + let mut bad_value = persona(INSTANCE, T3); + bad_value["updatedAt"] = json!(CANARY); + let mut bad_enum = persona(INSTANCE, T3); + bad_enum["provenance"]["authority"] = json!(CANARY); + let mut foreign = persona(CANARY, T3); + foreign["publicName"] = json!(CANARY); + let mut imported = persona(INSTANCE, T3); + imported["provenance"]["authority"] = json!("import"); + imported["provenance"]["sourceSystem"] = json!(CANARY); + let mut late = persona(INSTANCE, T1); + late["publicName"] = json!(CANARY); + + let cases: Vec<(Value, Option<&str>)> = vec![ + (free_key, Some(T2)), + (extra_key, Some(T2)), + (bad_value, Some(T2)), + (bad_enum, Some(T2)), + (foreign, Some(T2)), + (imported, Some(T2)), + (late, Some(T2)), + (persona(INSTANCE, T3), Some(CANARY)), + ]; + for (document, expected) in cases { + let refusal = refused(put(&mut mind, document, expected)); + assert!(!format!("{refusal:?}").contains(CANARY), "{refusal:?}"); + assert!(!serde_json::to_string(&refusal).unwrap().contains(CANARY)); + } + } + + #[test] + fn persona_id_must_be_the_instance() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + let before = store.rows(); + let refusal = refused(put(&mut mind, persona(OTHER_INSTANCE, T1), None)); + assert_eq!(refusal, MindRefusal::PersonaForeign { instance: INSTANCE.into() }); + assert_eq!(store.rows(), before); + assert_eq!(mind.persona().unwrap(), None); + } + + #[test] + fn only_a_canonical_document_is_the_minds_persona() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + for authority in ["projection", "import"] { + let mut document = persona(INSTANCE, T1); + document["provenance"]["authority"] = json!(authority); + assert_eq!(refused(put(&mut mind, document, None)), MindRefusal::PersonaNotCanonical, "{authority}"); + } + assert_eq!(mind.persona().unwrap(), None); + } + + #[test] + fn a_persona_waits_for_the_minds_identity() { + let mut mind = opened(MemoryStore::new(), INSTANCE); + assert_eq!(refused(put(&mut mind, persona(INSTANCE, T1), None)), MindRefusal::MissingIdentity); + assert!(mind.is_empty()); + } + + #[test] + fn a_put_must_name_this_mind_and_a_named_asker() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + let before = store.rows(); + let other = slug(OTHER_INSTANCE); + let outcome = mind.put_persona(&other, persona(INSTANCE, T1), None, provenance(Faculty::Hands), crate::fixtures::now()); + assert!(matches!(refused(outcome), MindRefusal::ForeignInstance { .. })); + let mut unnamed = provenance(Faculty::Hands); + unnamed.agent = eureka_pipeline::Short(" ".into()); + let instance = mind.instance().clone(); + let outcome = mind.put_persona(&instance, persona(INSTANCE, T1), None, unnamed, crate::fixtures::now()); + assert!(matches!(refused(outcome), MindRefusal::Document(_))); + assert_eq!(store.rows(), before); + } + + #[test] + fn a_put_is_a_compare_and_swap_on_updated_at() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + assert_eq!(persona_in_status(&mind), crate::wire::PersonaStatus::Absent); + let receipts = |mind: &Mind| mind.receipts().unwrap().len(); + let base = receipts(&mind); + + // A first put expects nothing; claiming a stored document is stale. + assert_eq!(refused(put(&mut mind, persona(INSTANCE, T1), Some(T1))), stale(None)); + let first = committed(put(&mut mind, persona(INSTANCE, T1), None)); + assert_eq!(receipts(&mind), base + 1); + let view = mind.persona().unwrap().unwrap(); + assert_eq!((view.updated_at.as_str(), view.receipt_id.as_str()), (T1, first.as_str())); + assert_eq!(view.value, persona(INSTANCE, T1)); + assert_eq!(persona_in_status(&mind), crate::wire::PersonaStatus::Stored { updated_at: T1.into() }); + + // Two puts that read the same stored document: the second loses. + let second = committed(put(&mut mind, persona(INSTANCE, T2), Some(T1))); + assert_eq!(receipts(&mind), base + 2); + let rows = store.rows(); + assert_eq!(refused(put(&mut mind, persona(INSTANCE, T3), Some(T1))), stale(Some(T2))); + assert_eq!(refused(put(&mut mind, persona(INSTANCE, T3), None)), stale(Some(T2))); + assert_eq!(store.rows(), rows, "a stale put wrote nothing"); + + // The right expectation with an updatedAt that is not later. + assert_eq!(refused(put(&mut mind, persona(INSTANCE, T2), Some(T2))), not_later()); + assert_eq!(refused(put(&mut mind, persona(INSTANCE, T1), Some(T2))), not_later()); + // Instants compare, not spellings: the same instant at another offset is not later. + assert_eq!(refused(put(&mut mind, persona(INSTANCE, "2026-10-10T12:00:01+02:00"), Some(T2))), not_later()); + assert_eq!(store.rows(), rows); + assert_eq!(receipts(&mind), base + 2); + committed(put(&mut mind, persona(INSTANCE, "2026-10-10T12:00:02+02:00"), Some(T2))); + assert_eq!(receipts(&mind), base + 3); + + // The second put's receipt read the first document and wrote the second. + let receipt = mind.receipts().unwrap().into_iter().find(|receipt| receipt.receipt_id == second).unwrap(); + assert_eq!((receipt.strong_reads.len(), receipt.writes.len()), (1, 1)); + assert_eq!(receipt.strong_reads[0].document_key, INSTANCE); + assert_ne!(receipt.strong_reads[0].payload_msgpack, receipt.writes[0].payload_msgpack); + assert_eq!(receipt.provenance, provenance(Faculty::Hands)); + } + + #[test] + fn a_put_whose_swap_is_lost_is_stale_and_changes_nothing() { + let store = RefusingStore::new(); + let mut mind = opened(store.clone(), INSTANCE); + seed(&mut mind); + committed(put(&mut mind, persona(INSTANCE, T1), None)); + let rows = store.rows(); + store.command(SwapCommand::Lose); + assert_eq!(refused(put(&mut mind, persona(INSTANCE, T2), Some(T1))), stale(Some(T1))); + assert_eq!(store.rows(), rows); + } + + #[test] + fn the_persona_is_not_a_pipeline_document_and_a_batch_cannot_carry_it() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + let documents = mind.status(crate::wire::IndexStatus::Current).documents; + committed(put(&mut mind, persona(INSTANCE, T1), None)); + assert_eq!(mind.status(crate::wire::IndexStatus::Current).documents, documents); + assert!(PipelineKind::ALL.iter().all(|kind| kind.type_id() != HuginnPersonaEntry::TYPE)); + let forged = mind.persona_envelope().unwrap().clone(); + let instance = mind.instance().clone(); + let outcome = mind.admit_prepared(&instance, provenance(Faculty::Hands), vec![forged], crate::fixtures::now()); + assert!(matches!(outcome, crate::admission::PipelineAdmissionOutcome::Refused(_)), "{outcome:?}"); + } + + #[test] + fn one_persona_per_mind_and_the_store_still_opens() { + let yggdrasil = slug(INSTANCE); + let cache = crate::mind::schema_cache().unwrap(); + let entry = |key: &str, value: Value| cache.prepare_entry_named(key, &HuginnPersonaEntry { value }).unwrap().0; + let planted = |rows: Vec| { + let store = MemoryStore::new(); + rows.into_iter().for_each(|row| store.plant(row)); + store + }; + let base = || vec![epoch(), prepare(&instance(INSTANCE))]; + + // A store written before this type existed opens unchanged. + assert!(Mind::open_with(planted(base()), &yggdrasil).is_ok()); + + // One persona opens and reads back. + let mut with_one = base(); + with_one.push(entry(INSTANCE, persona(INSTANCE, T1))); + let mind = Mind::open_with(planted(with_one.clone()), &yggdrasil).unwrap(); + assert_eq!(mind.envelopes().len(), 3); + assert_eq!(persona_in_status(&mind), crate::wire::PersonaStatus::Stored { updated_at: T1.into() }); + + // Two are no mind's. + with_one.push(entry("second", persona(INSTANCE, T2))); + assert_eq!( + Mind::open_with(planted(with_one), &yggdrasil).err(), + Some(MindRefusal::ForeignStore { r#type: HuginnPersonaEntry::TYPE.into() }) + ); + // The opener still refuses a type that is not one of the seventeen. + let mut stranger = base(); + let mut foreign = entry(INSTANCE, persona(INSTANCE, T1)); + foreign.r#type = "gamecult.persona_state.v1".into(); + stranger.push(foreign); + assert!(matches!(Mind::open_with(planted(stranger), &yggdrasil).err(), Some(MindRefusal::ForeignStore { .. }))); + } + + /// Status answers in the door's own terms: a stored persona the door + /// cannot read is `Unreadable`, not the `Absent` of a mind with none, while + /// `PersonaGet` answers `Unavailable` for the same bytes. + #[test] + fn status_says_unreadable_where_the_door_says_unavailable() { + let yggdrasil = slug(INSTANCE); + let cache = crate::mind::schema_cache().unwrap(); + let readable = cache.prepare_entry_named(INSTANCE, &HuginnPersonaEntry { value: persona(INSTANCE, T1) }).unwrap().0; + let no_stamp = cache.prepare_entry_named(INSTANCE, &HuginnPersonaEntry { value: json!({}) }).unwrap().0; + let mut undecodable = readable.clone(); + undecodable.payload = vec![0xc1]; + // Planted rows have no writing receipt: the door cannot read them, so neither may the status. + for (row, status) in [ + (readable, crate::wire::PersonaStatus::Unreadable), + (no_stamp, crate::wire::PersonaStatus::Unreadable), + (undecodable, crate::wire::PersonaStatus::Unreadable), + ] { + let store = MemoryStore::new(); + store.plant(epoch()); + store.plant(prepare(&instance(INSTANCE))); + store.plant(row); + let mind = Mind::open_with(store, &yggdrasil).unwrap(); + assert_eq!(persona_in_status(&mind), status); + assert!(matches!(mind.persona(), Err(MindRefusal::Unavailable { .. })), "the door answers what the status says"); + } + // A row a put wrote: status and door agree it is stored, with one stamp. + let store = MemoryStore::new(); + let mut written = seeded_over(&store); + committed(put(&mut written, persona(INSTANCE, T1), None)); + assert_eq!(persona_in_status(&written), crate::wire::PersonaStatus::Stored { updated_at: T1.into() }); + assert_eq!(written.persona().unwrap().unwrap().updated_at, T1); + assert_eq!(persona_in_status(&seeded_over(&MemoryStore::new())), crate::wire::PersonaStatus::Absent); + } + + #[test] + fn the_stored_bytes_are_the_one_slot_array_the_catalogue_describes() { + let store = MemoryStore::new(); + let mut mind = seeded_over(&store); + committed(put(&mut mind, persona(INSTANCE, T1), None)); + let envelope = mind.persona_envelope().unwrap(); + assert_eq!((envelope.r#type.as_str(), envelope.key.as_str()), ("gamecult.persona_state.v0", INSTANCE)); + let slots: (Value,) = rmp_serde::from_slice(&envelope.payload).unwrap(); + assert_eq!(slots.0, persona(INSTANCE, T1)); + } +} diff --git a/crates/huginn-mind/src/wire.rs b/crates/huginn-mind/src/wire.rs index 00cbce0..ba213b3 100644 --- a/crates/huginn-mind/src/wire.rs +++ b/crates/huginn-mind/src/wire.rs @@ -1,343 +1,343 @@ -//! The organ's request and response vocabulary: one operation per `Mind` -//! method and `whoami`. Payloads are the admission and read types unchanged. -//! The daemon carries these in CultNet's operation envelope; the client -//! constructs them. Nothing here validates a document, derives a status or -//! names a transport. - -use cultcache_rs::DatabaseEntry; -use cultnet_rs::{CultMeshCdnArtifactManifest, Selection}; -use eureka_pipeline::{PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Slug}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -use crate::admission::{PipelineAdmissionBatch, PipelineAdmissionOutcome}; -use crate::mind::Mind; -use crate::persona::{PersonaPutOutcome, PersonaStateView}; -use crate::query::{PipelineDocumentView, PipelineSelectionPage, SemanticQuery}; -use crate::receipt::{HuginnCommitReceipt, PipelineProvenance}; -use crate::refusal::MindRefusal; -use crate::store::MindStore; - -/// The envelope's `service_id`: one service, one mind, whichever mind the -/// process opened. -pub const MIND_SERVICE_ID: &str = "huginn.mind"; -pub const MIND_REQUEST_SCHEMA: &str = "huginn.mind_request.v1"; -pub const MIND_RESPONSE_SCHEMA: &str = "huginn.mind_response.v1"; - -/// The largest answer that is deferred rather than refused, measured on the -/// encoded payload. The daemon refuses past it and a client caps its fetch at -/// it, so both sides read one number. -pub const MAX_DEFERRED_BODY_BYTES: u64 = 64 * 1024 * 1024; - -/// The published JSON schema of each wire type, as the catalog advertises it. -/// The files are derived from the types below and pinned byte for byte by -/// `published_wire_schemas_match_derivation`, so the catalog cannot advertise -/// a shape the crate does not speak. -pub const MIND_REQUEST_SCHEMA_JSON: &str = - include_str!("../../../schemas/cultnet/huginn.mind_request.v1.schema.json"); -pub const MIND_RESPONSE_SCHEMA_JSON: &str = - include_str!("../../../schemas/cultnet/huginn.mind_response.v1.schema.json"); - -/// The request's `selection` is CultNet's, and its published schema is -/// CultLib's: a `$ref` to the `$id` it publishes, so one owner holds the -/// selection's shape and nothing here copies it. -fn selection_ref(_: &mut schemars::SchemaGenerator) -> schemars::Schema { - schemars::json_schema!({ - "$ref": "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json" - }) -} - -/// The deferred answer's manifest is CultMesh's own type, a positional array -/// the C# reference defines (`CultMeshCdnArtifactManifest`, schema version -/// `gamecult.mesh.cdn_artifact_manifest.v1`). CultLib publishes no JSON schema -/// for it, so the schema says what the reference says: an array of its ten -/// fields in order, and nothing here copies their meaning. -fn manifest_array(_: &mut schemars::SchemaGenerator) -> schemars::Schema { - schemars::json_schema!({ - "description": "gamecult.mesh.cdn_artifact_manifest.v1, the C# reference's CultMeshCdnArtifactManifest as its positional array: [artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc, chunks[[chunkHash, offset, sizeBytes, recordKey]], tags, metadata].", - "type": "array" - }) -} - -/// Every operation a mind answers. `Admit` carries the batch whole because the -/// batch already names the instance and the asker; a second `instance` beside -/// it would be two declarations. Every read names the instance because ruling -/// 14 refuses another mind's identity whatever the transport, and a read of -/// the wrong mind is that same collision on the read side. `Whoami` names -/// none: it is how a client learns which mind it reached. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub enum HuginnMindRequest { - Whoami, - Admit(PipelineAdmissionBatch), - View { instance: Slug, id: PipelineRef }, - Query { - instance: Slug, - #[schemars(schema_with = "selection_ref")] - selection: Selection, - semantic: Option, - }, - /// The mind's persona document, if one is stored. - PersonaGet { instance: Slug }, - /// Replaces the mind's persona document whole. `expected_updated_at` is - /// the stored document's `updatedAt`, none for the first put. The - /// provenance is the asker's, as for `Admit`. - PersonaPut { - instance: Slug, - provenance: PipelineProvenance, - state: Value, - expected_updated_at: Option, - }, -} - -impl HuginnMindRequest { - /// The envelope's `operation`. - pub fn operation(&self) -> &'static str { - match self { - Self::Whoami => "whoami", - Self::Admit(_) => "admit", - Self::View { .. } => "view", - Self::Query { .. } => "query", - Self::PersonaGet { .. } => "persona_get", - Self::PersonaPut { .. } => "persona_put", - } - } - - /// The instance the request declares; `Whoami` declares none. - pub fn instance(&self) -> Option<&Slug> { - match self { - Self::Whoami => None, - Self::Admit(batch) => Some(&batch.instance), - Self::View { instance, .. } - | Self::Query { instance, .. } - | Self::PersonaGet { instance } - | Self::PersonaPut { instance, .. } => Some(instance), - } - } -} - -/// Every answer a mind gives. A refusal is data in the response, never a -/// transport failure: the read side carries `Refused`, the write side carries -/// the outcome's own `Refused`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub enum HuginnMindResponse { - Whoami(MindStatus), - Admit(PipelineAdmissionOutcome), - View(Option>), - Query(PipelineSelectionPage), - Refused(MindRefusal), - Persona(Option), - PersonaPut(PersonaPutOutcome), - /// The answer did not fit one send and is being held for the client to - /// fetch. Nothing in a mind produces this: the daemon's serve module does, - /// in place of an answer, and the answer it stands for is the named - /// MessagePack of the `HuginnMindResponse` the mind gave. - Deferred(DeferredAnswer), -} - -/// Where the body of an answer that did not fit one send can be fetched: the -/// reference's own manifest, whose `contentHash` is the SHA-256 of the answer's -/// encoded bytes and whose chunks are asked for, one at a time, on the session -/// this arrived on. Row-level facts come from asking again with a header -/// projection; there is no summary. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub struct DeferredAnswer { - #[schemars(schema_with = "manifest_array")] - pub manifest: CultMeshCdnArtifactManifest, -} - -impl HuginnMindResponse { - /// The envelope's `status`, in the C# reference's vocabulary: `rejected` - /// exactly for a refusal, `accepted` otherwise. `Conflict` and - /// `AlreadyAdmitted` are answers about the mind, not refusals of the - /// request. A `Deferred` is nominally `accepted`; the daemon sets the - /// envelope of a deferred answer to the status of the answer it stands for. - pub fn status(&self) -> &'static str { - match self { - Self::Refused(_) - | Self::Admit(PipelineAdmissionOutcome::Refused(_)) - | Self::PersonaPut(PersonaPutOutcome::Refused(_)) => "rejected", - _ => "accepted", - } - } -} - -/// How far the semantic index has caught up with the mind. The mind decides -/// none of it: the daemon's index worker reports it, in memory, and a restart -/// recomputes it. `pending` counts documents not yet known to be in the index. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub enum IndexStatus { - /// The worker has not yet compared the mind with the collection. - Reconciling { pending: u32 }, - /// Every indexable document is in the collection. - Current, - /// Reconciled, and indexing what is still pending. - Behind { pending: u32 }, - /// The last attempt failed (the embedder or the vector store is - /// unreachable, or refused); it is retried with a backoff and nothing is - /// dropped. `attempts` counts consecutive failures. - Failing { pending: u32, attempts: u32, error: String }, - /// The collection belongs to another writer. The worker never recreates - /// it; it re-reads it on the same backoff. - Refused { pending: u32, attempts: u32, reason: String }, -} - -/// What a mind says about itself: the typed state a dashboard projects. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub struct MindStatus { - pub instance: Slug, - pub schema_epoch: String, - /// Pipeline documents in the image; the epoch record and the receipts are - /// not documents and are not counted here. - pub documents: u32, - pub receipts: u32, - pub index: IndexStatus, - /// The persona door as `PersonaGet` would find it. - pub persona: PersonaStatus, -} - -/// What the persona door holds, in the one vocabulary the door itself answers -/// in: nothing yet, a document with this `updatedAt`, or a stored document the -/// door cannot read (`PersonaGet` and every put answer `Unavailable`). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub enum PersonaStatus { - Absent, - Stored { updated_at: String }, - Unreadable, -} - -impl Mind { - /// `whoami`, derived from the image every time it is asked, and from the - /// index status the caller holds: the mind stores neither. - pub fn status(&self, index: IndexStatus) -> MindStatus { - let mut documents = 0_u32; - let mut receipts = 0_u32; - for envelope in self.envelopes() { - if envelope.r#type == HuginnCommitReceipt::TYPE { - receipts += 1; - } else if PipelineKind::ALL.iter().any(|kind| kind.type_id() == envelope.r#type) { - documents += 1; - } - } - MindStatus { - instance: self.instance().clone(), - schema_epoch: PIPELINE_SCHEMA_EPOCH.to_string(), - documents, - receipts, - index, - persona: match self.stored_updated_at() { - Ok(None) => PersonaStatus::Absent, - Ok(Some(updated_at)) => PersonaStatus::Stored { updated_at }, - Err(_) => PersonaStatus::Unreadable, - }, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::query::PipelinePageItems; - use crate::fixtures::{CAMPAIGN, INSTANCE, OTHER_INSTANCE, instance, provenance, r, seeded, slug}; - use crate::receipt::Faculty; - - fn requests() -> Vec { - let batch = PipelineAdmissionBatch { - instance: slug(INSTANCE), - provenance: provenance(Faculty::Hands), - documents: vec![instance(INSTANCE)], - }; - vec![ - HuginnMindRequest::Whoami, - HuginnMindRequest::Admit(batch), - HuginnMindRequest::View { instance: slug(INSTANCE), id: r(PipelineKind::Campaign, CAMPAIGN) }, - HuginnMindRequest::Query { instance: slug(OTHER_INSTANCE), selection: Selection::default(), semantic: None }, - HuginnMindRequest::PersonaGet { instance: slug(INSTANCE) }, - HuginnMindRequest::PersonaPut { - instance: slug(INSTANCE), - provenance: provenance(Faculty::Hands), - state: serde_json::json!({ "updatedAt": "2026-10-10T10:00:00Z", "n": [1, 2.5, null, "x"] }), - expected_updated_at: Some("2026-10-10T09:00:00Z".into()), - }, - ] - } - - fn responses() -> Vec { - let refusal = MindRefusal::ForeignInstance { declared: OTHER_INSTANCE.into(), mind: INSTANCE.into() }; - vec![ - HuginnMindResponse::Whoami(seeded().status(IndexStatus::Current)), - HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id: "r1".into() }), - HuginnMindResponse::Admit(PipelineAdmissionOutcome::Conflict { identities: vec![] }), - HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal.clone())), - HuginnMindResponse::View(None), - HuginnMindResponse::Query(PipelineSelectionPage { - matched: 0, - as_of: 1, - next: None, - items: PipelinePageItems::Headers(vec![]), - edges: None, - }), - HuginnMindResponse::Refused(refusal), - HuginnMindResponse::Persona(None), - HuginnMindResponse::Persona(Some(PersonaStateView { - value: serde_json::json!({ "personaId": INSTANCE }), - updated_at: "2026-10-10T10:00:00Z".into(), - receipt_id: "mind-commit-1".into(), - })), - HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed { receipt_id: "mind-commit-2".into() }), - HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(MindRefusal::PersonaNotCanonical)), - HuginnMindResponse::Deferred(DeferredAnswer { - manifest: cultnet_rs::pack_content("huginn.mind_response", "package", "", "", "", b"body", 4) - .unwrap() - .0, - }), - ] - } - - /// The vocabulary is the mind's methods, the declared instance is on every - /// request that names a mind, and the envelope's status is derived from - /// the response rather than chosen by whoever sends it. - #[test] - fn the_wire_vocabulary_is_the_minds_methods_and_status_is_derived_from_the_response() { - let names: Vec<&str> = requests().iter().map(|request| request.operation()).collect(); - assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put"]); - for request in requests() { - let declared = request.instance().is_none(); - assert_eq!(declared, matches!(request, HuginnMindRequest::Whoami), "{request:?}"); - let bytes = rmp_serde::to_vec_named(&request).unwrap(); - assert_eq!(rmp_serde::from_slice::(&bytes).unwrap(), request); - } - assert_eq!( - requests()[3].instance(), - Some(&slug(OTHER_INSTANCE)), - "the request's instance is the one it declares, not the mind's" - ); - - for response in responses() { - let rejected = matches!( - response, - HuginnMindResponse::Refused(_) - | HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(_)) - | HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(_)) - ); - assert_eq!(response.status(), if rejected { "rejected" } else { "accepted" }, "{response:?}"); - let bytes = rmp_serde::to_vec_named(&response).unwrap(); - assert_eq!(rmp_serde::from_slice::(&bytes).unwrap(), response); - } - } - - /// The two files the catalog publishes are the derivation of the two - /// types, byte for byte. - #[test] - fn published_wire_schemas_match_derivation() { - let request = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindRequest)).unwrap(); - let response = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindResponse)).unwrap(); - assert_eq!(MIND_REQUEST_SCHEMA_JSON.replace("\r\n", "\n"), request); - assert_eq!(MIND_RESPONSE_SCHEMA_JSON.replace("\r\n", "\n"), response); - // The selection is CultLib's, referenced by the `$id` it publishes and - // not copied into this schema. - let selection = "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json"; - assert!(request.contains(&format!("\"$ref\": \"{selection}\""))); - assert!(!request.contains("\"cursor\""), "no second copy of the selection's shape"); - } -} +//! The organ's request and response vocabulary: one operation per `Mind` +//! method and `whoami`. Payloads are the admission and read types unchanged. +//! The daemon carries these in CultNet's operation envelope; the client +//! constructs them. Nothing here validates a document, derives a status or +//! names a transport. + +use cultcache_rs::DatabaseEntry; +use cultnet_rs::{CultMeshCdnArtifactManifest, Selection}; +use eureka_pipeline::{PIPELINE_SCHEMA_EPOCH, PipelineKind, PipelineRef, Slug}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::admission::{PipelineAdmissionBatch, PipelineAdmissionOutcome}; +use crate::mind::Mind; +use crate::persona::{PersonaPutOutcome, PersonaStateView}; +use crate::query::{PipelineDocumentView, PipelineSelectionPage, SemanticQuery}; +use crate::receipt::{HuginnCommitReceipt, PipelineProvenance}; +use crate::refusal::MindRefusal; +use crate::store::MindStore; + +/// The envelope's `service_id`: one service, one mind, whichever mind the +/// process opened. +pub const MIND_SERVICE_ID: &str = "huginn.mind"; +pub const MIND_REQUEST_SCHEMA: &str = "huginn.mind_request.v1"; +pub const MIND_RESPONSE_SCHEMA: &str = "huginn.mind_response.v1"; + +/// The largest answer that is deferred rather than refused, measured on the +/// encoded payload. The daemon refuses past it and a client caps its fetch at +/// it, so both sides read one number. +pub const MAX_DEFERRED_BODY_BYTES: u64 = 64 * 1024 * 1024; + +/// The published JSON schema of each wire type, as the catalog advertises it. +/// The files are derived from the types below and pinned byte for byte by +/// `published_wire_schemas_match_derivation`, so the catalog cannot advertise +/// a shape the crate does not speak. +pub const MIND_REQUEST_SCHEMA_JSON: &str = + include_str!("../../../schemas/cultnet/huginn.mind_request.v1.schema.json"); +pub const MIND_RESPONSE_SCHEMA_JSON: &str = + include_str!("../../../schemas/cultnet/huginn.mind_response.v1.schema.json"); + +/// The request's `selection` is CultNet's, and its published schema is +/// CultLib's: a `$ref` to the `$id` it publishes, so one owner holds the +/// selection's shape and nothing here copies it. +fn selection_ref(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "$ref": "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json" + }) +} + +/// The deferred answer's manifest is CultMesh's own type, a positional array +/// the C# reference defines (`CultMeshCdnArtifactManifest`, schema version +/// `gamecult.mesh.cdn_artifact_manifest.v1`). CultLib publishes no JSON schema +/// for it, so the schema says what the reference says: an array of its ten +/// fields in order, and nothing here copies their meaning. +fn manifest_array(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "description": "gamecult.mesh.cdn_artifact_manifest.v1, the C# reference's CultMeshCdnArtifactManifest as its positional array: [artifactId, kind, version, contentHash, sizeBytes, mimeType, createdAtUtc, chunks[[chunkHash, offset, sizeBytes, recordKey]], tags, metadata].", + "type": "array" + }) +} + +/// Every operation a mind answers. `Admit` carries the batch whole because the +/// batch already names the instance and the asker; a second `instance` beside +/// it would be two declarations. Every read names the instance because ruling +/// 14 refuses another mind's identity whatever the transport, and a read of +/// the wrong mind is that same collision on the read side. `Whoami` names +/// none: it is how a client learns which mind it reached. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum HuginnMindRequest { + Whoami, + Admit(PipelineAdmissionBatch), + View { instance: Slug, id: PipelineRef }, + Query { + instance: Slug, + #[schemars(schema_with = "selection_ref")] + selection: Selection, + semantic: Option, + }, + /// The mind's persona document, if one is stored. + PersonaGet { instance: Slug }, + /// Replaces the mind's persona document whole. `expected_updated_at` is + /// the stored document's `updatedAt`, none for the first put. The + /// provenance is the asker's, as for `Admit`. + PersonaPut { + instance: Slug, + provenance: PipelineProvenance, + state: Value, + expected_updated_at: Option, + }, +} + +impl HuginnMindRequest { + /// The envelope's `operation`. + pub fn operation(&self) -> &'static str { + match self { + Self::Whoami => "whoami", + Self::Admit(_) => "admit", + Self::View { .. } => "view", + Self::Query { .. } => "query", + Self::PersonaGet { .. } => "persona_get", + Self::PersonaPut { .. } => "persona_put", + } + } + + /// The instance the request declares; `Whoami` declares none. + pub fn instance(&self) -> Option<&Slug> { + match self { + Self::Whoami => None, + Self::Admit(batch) => Some(&batch.instance), + Self::View { instance, .. } + | Self::Query { instance, .. } + | Self::PersonaGet { instance } + | Self::PersonaPut { instance, .. } => Some(instance), + } + } +} + +/// Every answer a mind gives. A refusal is data in the response, never a +/// transport failure: the read side carries `Refused`, the write side carries +/// the outcome's own `Refused`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum HuginnMindResponse { + Whoami(MindStatus), + Admit(PipelineAdmissionOutcome), + View(Option>), + Query(PipelineSelectionPage), + Refused(MindRefusal), + Persona(Option), + PersonaPut(PersonaPutOutcome), + /// The answer did not fit one send and is being held for the client to + /// fetch. Nothing in a mind produces this: the daemon's serve module does, + /// in place of an answer, and the answer it stands for is the named + /// MessagePack of the `HuginnMindResponse` the mind gave. + Deferred(DeferredAnswer), +} + +/// Where the body of an answer that did not fit one send can be fetched: the +/// reference's own manifest, whose `contentHash` is the SHA-256 of the answer's +/// encoded bytes and whose chunks are asked for, one at a time, on the session +/// this arrived on. Row-level facts come from asking again with a header +/// projection; there is no summary. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct DeferredAnswer { + #[schemars(schema_with = "manifest_array")] + pub manifest: CultMeshCdnArtifactManifest, +} + +impl HuginnMindResponse { + /// The envelope's `status`, in the C# reference's vocabulary: `rejected` + /// exactly for a refusal, `accepted` otherwise. `Conflict` and + /// `AlreadyAdmitted` are answers about the mind, not refusals of the + /// request. A `Deferred` is nominally `accepted`; the daemon sets the + /// envelope of a deferred answer to the status of the answer it stands for. + pub fn status(&self) -> &'static str { + match self { + Self::Refused(_) + | Self::Admit(PipelineAdmissionOutcome::Refused(_)) + | Self::PersonaPut(PersonaPutOutcome::Refused(_)) => "rejected", + _ => "accepted", + } + } +} + +/// How far the semantic index has caught up with the mind. The mind decides +/// none of it: the daemon's index worker reports it, in memory, and a restart +/// recomputes it. `pending` counts documents not yet known to be in the index. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum IndexStatus { + /// The worker has not yet compared the mind with the collection. + Reconciling { pending: u32 }, + /// Every indexable document is in the collection. + Current, + /// Reconciled, and indexing what is still pending. + Behind { pending: u32 }, + /// The last attempt failed (the embedder or the vector store is + /// unreachable, or refused); it is retried with a backoff and nothing is + /// dropped. `attempts` counts consecutive failures. + Failing { pending: u32, attempts: u32, error: String }, + /// The collection belongs to another writer. The worker never recreates + /// it; it re-reads it on the same backoff. + Refused { pending: u32, attempts: u32, reason: String }, +} + +/// What a mind says about itself: the typed state a dashboard projects. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct MindStatus { + pub instance: Slug, + pub schema_epoch: String, + /// Pipeline documents in the image; the epoch record and the receipts are + /// not documents and are not counted here. + pub documents: u32, + pub receipts: u32, + pub index: IndexStatus, + /// The persona door as `PersonaGet` would find it. + pub persona: PersonaStatus, +} + +/// What the persona door holds, in the one vocabulary the door itself answers +/// in: nothing yet, a document with this `updatedAt`, or a stored document the +/// door cannot read (`PersonaGet` and every put answer `Unavailable`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum PersonaStatus { + Absent, + Stored { updated_at: String }, + Unreadable, +} + +impl Mind { + /// `whoami`, derived from the image every time it is asked, and from the + /// index status the caller holds: the mind stores neither. + pub fn status(&self, index: IndexStatus) -> MindStatus { + let mut documents = 0_u32; + let mut receipts = 0_u32; + for envelope in self.envelopes() { + if envelope.r#type == HuginnCommitReceipt::TYPE { + receipts += 1; + } else if PipelineKind::ALL.iter().any(|kind| kind.type_id() == envelope.r#type) { + documents += 1; + } + } + MindStatus { + instance: self.instance().clone(), + schema_epoch: PIPELINE_SCHEMA_EPOCH.to_string(), + documents, + receipts, + index, + persona: match self.persona() { + Ok(None) => PersonaStatus::Absent, + Ok(Some(view)) => PersonaStatus::Stored { updated_at: view.updated_at }, + Err(_) => PersonaStatus::Unreadable, + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::query::PipelinePageItems; + use crate::fixtures::{CAMPAIGN, INSTANCE, OTHER_INSTANCE, instance, provenance, r, seeded, slug}; + use crate::receipt::Faculty; + + fn requests() -> Vec { + let batch = PipelineAdmissionBatch { + instance: slug(INSTANCE), + provenance: provenance(Faculty::Hands), + documents: vec![instance(INSTANCE)], + }; + vec![ + HuginnMindRequest::Whoami, + HuginnMindRequest::Admit(batch), + HuginnMindRequest::View { instance: slug(INSTANCE), id: r(PipelineKind::Campaign, CAMPAIGN) }, + HuginnMindRequest::Query { instance: slug(OTHER_INSTANCE), selection: Selection::default(), semantic: None }, + HuginnMindRequest::PersonaGet { instance: slug(INSTANCE) }, + HuginnMindRequest::PersonaPut { + instance: slug(INSTANCE), + provenance: provenance(Faculty::Hands), + state: serde_json::json!({ "updatedAt": "2026-10-10T10:00:00Z", "n": [1, 2.5, null, "x"] }), + expected_updated_at: Some("2026-10-10T09:00:00Z".into()), + }, + ] + } + + fn responses() -> Vec { + let refusal = MindRefusal::ForeignInstance { declared: OTHER_INSTANCE.into(), mind: INSTANCE.into() }; + vec![ + HuginnMindResponse::Whoami(seeded().status(IndexStatus::Current)), + HuginnMindResponse::Admit(PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id: "r1".into() }), + HuginnMindResponse::Admit(PipelineAdmissionOutcome::Conflict { identities: vec![] }), + HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(refusal.clone())), + HuginnMindResponse::View(None), + HuginnMindResponse::Query(PipelineSelectionPage { + matched: 0, + as_of: 1, + next: None, + items: PipelinePageItems::Headers(vec![]), + edges: None, + }), + HuginnMindResponse::Refused(refusal), + HuginnMindResponse::Persona(None), + HuginnMindResponse::Persona(Some(PersonaStateView { + value: serde_json::json!({ "personaId": INSTANCE }), + updated_at: "2026-10-10T10:00:00Z".into(), + receipt_id: "mind-commit-1".into(), + })), + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed { receipt_id: "mind-commit-2".into() }), + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(MindRefusal::PersonaNotCanonical)), + HuginnMindResponse::Deferred(DeferredAnswer { + manifest: cultnet_rs::pack_content("huginn.mind_response", "package", "", "", "", b"body", 4) + .unwrap() + .0, + }), + ] + } + + /// The vocabulary is the mind's methods, the declared instance is on every + /// request that names a mind, and the envelope's status is derived from + /// the response rather than chosen by whoever sends it. + #[test] + fn the_wire_vocabulary_is_the_minds_methods_and_status_is_derived_from_the_response() { + let names: Vec<&str> = requests().iter().map(|request| request.operation()).collect(); + assert_eq!(names, ["whoami", "admit", "view", "query", "persona_get", "persona_put"]); + for request in requests() { + let declared = request.instance().is_none(); + assert_eq!(declared, matches!(request, HuginnMindRequest::Whoami), "{request:?}"); + let bytes = rmp_serde::to_vec_named(&request).unwrap(); + assert_eq!(rmp_serde::from_slice::(&bytes).unwrap(), request); + } + assert_eq!( + requests()[3].instance(), + Some(&slug(OTHER_INSTANCE)), + "the request's instance is the one it declares, not the mind's" + ); + + for response in responses() { + let rejected = matches!( + response, + HuginnMindResponse::Refused(_) + | HuginnMindResponse::Admit(PipelineAdmissionOutcome::Refused(_)) + | HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(_)) + ); + assert_eq!(response.status(), if rejected { "rejected" } else { "accepted" }, "{response:?}"); + let bytes = rmp_serde::to_vec_named(&response).unwrap(); + assert_eq!(rmp_serde::from_slice::(&bytes).unwrap(), response); + } + } + + /// The two files the catalog publishes are the derivation of the two + /// types, byte for byte. + #[test] + fn published_wire_schemas_match_derivation() { + let request = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindRequest)).unwrap(); + let response = serde_json::to_string_pretty(&schemars::schema_for!(HuginnMindResponse)).unwrap(); + assert_eq!(MIND_REQUEST_SCHEMA_JSON.replace("\r\n", "\n"), request); + assert_eq!(MIND_RESPONSE_SCHEMA_JSON.replace("\r\n", "\n"), response); + // The selection is CultLib's, referenced by the `$id` it publishes and + // not copied into this schema. + let selection = "https://github.com/GameCult/CultLib/contracts/cultnet/cultnet.selection.schema.json"; + assert!(request.contains(&format!("\"$ref\": \"{selection}\""))); + assert!(!request.contains("\"cursor\""), "no second copy of the selection's shape"); + } +}