diff --git a/epiphany-core/src/agent_utterance_state.rs b/epiphany-core/src/agent_utterance_state.rs new file mode 100644 index 00000000..b2c5e4cd --- /dev/null +++ b/epiphany-core/src/agent_utterance_state.rs @@ -0,0 +1,1357 @@ +use crate::agent_memory::EpiphanyAgentMemoryEntry; +use crate::agent_memory::EpiphanyDossierProfile; +use crate::agent_memory::GhostlightCanonicalState; +use crate::agent_memory::GhostlightTraitVector; +use crate::agent_memory::dossier_profile_for_role; +use crate::heartbeat_state::HeartbeatParticipant; +use serde::Deserialize; +use serde::Serialize; +use std::collections::BTreeMap; + +pub const AGENT_UTTERANCE_STATE_SCHEMA_VERSION: &str = "epiphany.agent_utterance_state.v0"; +pub const WEKSA_UTTERANCE_HANDOFF_SCHEMA_VERSION: &str = "weksa.utterance_embedding_handoff.v0.1"; +pub const AGENT_CHARACTER_STATE_VECTOR_SIZE: usize = 64; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceState { + pub schema_version: String, + pub source: String, + pub role_id: String, + pub agent_id: String, + pub dossier_profile: EpiphanyDossierProfile, + pub identity: AgentUtteranceIdentity, + pub personality_vectors: AgentUtterancePersonalityVectors, + pub values: Vec, + pub current_mood: AgentUtteranceMood, + pub activation: AgentUtteranceActivation, + pub character_state_vector: AgentUtteranceCharacterStateVector, + pub utterance_embedding_basis: Vec, + pub contract: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceIdentity { + pub name: String, + pub roles: Vec, + pub origin: String, + pub public_description: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtterancePersonalityVectors { + pub underlying_organization: BTreeMap, + pub stable_dispositions: BTreeMap, + pub behavioral_dimensions: BTreeMap, + pub presentation_strategy: BTreeMap, + pub voice_style: BTreeMap, + pub situational_state: BTreeMap, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceValue { + pub value_id: String, + pub label: String, + pub priority: f64, + pub unforgivable_if_betrayed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceMood { + pub label: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + pub emotional_dimensions: Vec, + pub anxiety: f64, + pub urgency: f64, + pub arousal: f64, + pub thought_pressure: f64, + pub guardedness: f64, + pub reaction_intensity: f64, + pub cooldown_multiplier: f64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceMoodDimension { + pub name: String, + pub value: f64, + pub source_path: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceActivation { + pub status: String, + pub current_load: f64, + pub initiative_speed: f64, + pub reaction_bias: f64, + pub interrupt_threshold: f64, + pub personality_cooldown_multiplier: f64, + pub mood_cooldown_multiplier: f64, + pub initiative_heat_multiplier: f64, + pub effective_cooldown_multiplier: f64, + pub pending_turn_active: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub scene_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub last_woke_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub last_finished_at: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceEmbeddingBasis { + pub kind: String, + pub path: String, + pub weight: f64, + pub text: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceCharacterStateVector { + pub schema_version: String, + pub compatible_handoff_schema: String, + pub source: String, + pub dimensionality: usize, + pub values: Vec, + pub slots: Vec, + pub audit_projection: AgentUtteranceCharacterStateAudit, + pub uncertainties: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceCharacterStateSlot { + pub index: usize, + pub name: String, + pub value: f64, + pub source_path: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentUtteranceCharacterStateAudit { + pub current_state_pressure: Vec, + pub speaker_trait_pressure: Vec, + pub delivery_shape: String, +} + +pub fn derive_agent_utterance_state( + entry: &EpiphanyAgentMemoryEntry, + participant: Option<&HeartbeatParticipant>, + mood_label: Option<&str>, + source: impl Into, +) -> AgentUtteranceState { + let canonical = &entry.agent.canonical_state; + let personality_vectors = AgentUtterancePersonalityVectors { + underlying_organization: canonical.underlying_organization.clone(), + stable_dispositions: canonical.stable_dispositions.clone(), + behavioral_dimensions: canonical.behavioral_dimensions.clone(), + presentation_strategy: canonical.presentation_strategy.clone(), + voice_style: canonical.voice_style.clone(), + situational_state: canonical.situational_state.clone(), + }; + let values = canonical + .values + .iter() + .map(|value| AgentUtteranceValue { + value_id: value.value_id.clone(), + label: value.label.clone(), + priority: value.priority, + unforgivable_if_betrayed: value.unforgivable_if_betrayed, + }) + .collect::>(); + let mood = derive_utterance_mood(participant, mood_label, canonical); + let activation = derive_utterance_activation(participant); + let vector_source = source.into(); + let identity = AgentUtteranceIdentity { + name: entry.agent.identity.name.clone(), + roles: entry.agent.identity.roles.clone(), + origin: entry.agent.identity.origin.clone(), + public_description: entry.agent.identity.public_description.clone(), + }; + let utterance_embedding_basis = utterance_embedding_basis( + &entry.role_id, + &identity, + &personality_vectors, + &values, + &mood, + &activation, + ); + let character_state_vector = character_state_vector( + &personality_vectors, + &values, + &mood, + &activation, + &vector_source, + ); + + AgentUtteranceState { + schema_version: AGENT_UTTERANCE_STATE_SCHEMA_VERSION.to_string(), + source: vector_source, + role_id: entry.role_id.clone(), + agent_id: entry.agent.agent_id.clone(), + dossier_profile: dossier_profile_for_role(&entry.role_id), + identity, + personality_vectors, + values, + current_mood: mood, + activation, + character_state_vector, + utterance_embedding_basis, + contract: "Derived speech-conditioning state for Weksa/AquaSynth utterance embedding and voice rendering. The 64-float characterStateVector is the machine-consumable handoff lane; the surrounding fields are audit and source context. This is not canonical memory and deliberately excludes episodic, semantic, and relationship memory records.".to_string(), + } +} + +fn derive_utterance_mood( + participant: Option<&HeartbeatParticipant>, + mood_label: Option<&str>, + canonical: &GhostlightCanonicalState, +) -> AgentUtteranceMood { + let timing = participant.and_then(|participant| participant.mood_timing.as_ref()); + let situational = &canonical.situational_state; + let anxiety = timing + .map(|mood| mood.anxiety) + .unwrap_or_else(|| trait_activation(situational, "anxiety")); + let urgency = timing + .map(|mood| mood.urgency) + .unwrap_or_else(|| trait_activation(situational, "urgency")); + let arousal = timing + .map(|mood| mood.arousal) + .unwrap_or_else(|| trait_activation(situational, "arousal")); + let thought_pressure = timing + .map(|mood| mood.thought_pressure) + .unwrap_or_else(|| trait_activation(situational, "thought_pressure")); + let guardedness = timing + .map(|mood| mood.guardedness) + .unwrap_or_else(|| trait_activation(situational, "guardedness")); + let reaction_intensity = timing + .map(|mood| mood.reaction_intensity) + .unwrap_or_else(|| trait_activation(situational, "reaction_intensity")); + AgentUtteranceMood { + label: mood_label + .map(str::to_string) + .unwrap_or_else(|| inferred_mood_label(timing.map(|mood| mood.arousal), situational)), + source: timing.and_then(|mood| mood.source.clone()), + emotional_dimensions: emotional_dimensions( + situational, + anxiety, + urgency, + arousal, + thought_pressure, + guardedness, + reaction_intensity, + ), + anxiety, + urgency, + arousal, + thought_pressure, + guardedness, + reaction_intensity, + cooldown_multiplier: timing.map(|mood| mood.cooldown_multiplier).unwrap_or(1.0), + } +} + +fn emotional_dimensions( + situational: &BTreeMap, + anxiety: f64, + urgency: f64, + arousal: f64, + thought_pressure: f64, + guardedness: f64, + reaction_intensity: f64, +) -> Vec { + let derived = [ + ( + "valence", + (trait_activation(situational, "joy") + + trait_activation(situational, "warmth") + + trait_activation(situational, "tenderness")) + / 3.0, + ), + ("arousal", arousal), + ( + "dominance", + trait_activation(situational, "dominance") + .max(trait_activation(situational, "command_force")), + ), + ("urgency", urgency), + ("anger", trait_activation(situational, "anger")), + ("despair", trait_activation(situational, "despair")), + ( + "sadness", + trait_activation(situational, "sadness").max(trait_activation(situational, "grief")), + ), + ("fear", trait_activation(situational, "fear").max(anxiety)), + ("anxiety", anxiety), + ("disgust", trait_activation(situational, "disgust")), + ("contempt", trait_activation(situational, "contempt")), + ("annoyance", trait_activation(situational, "annoyance")), + ("dismissal", trait_activation(situational, "dismissal")), + ( + "flippancy", + trait_activation(situational, "flippancy") + .max(trait_activation(situational, "playfulness")), + ), + ("playfulness", trait_activation(situational, "playfulness")), + ("irony", trait_activation(situational, "irony")), + ("tenderness", trait_activation(situational, "tenderness")), + ("warmth", trait_activation(situational, "warmth")), + ("joy", trait_activation(situational, "joy")), + ( + "excitement", + trait_activation(situational, "excitement") + .max(arousal * trait_activation(situational, "joy")), + ), + ("fatigue", trait_activation(situational, "fatigue")), + ("guardedness", guardedness), + ("confidence", trait_activation(situational, "confidence")), + ("shame", trait_activation(situational, "shame")), + ("pride", trait_activation(situational, "pride")), + ("threat", trait_activation(situational, "threat")), + ("secrecy", trait_activation(situational, "secrecy")), + ("hesitation", trait_activation(situational, "hesitation")), + ( + "emotionalContainment", + trait_activation(situational, "emotional_containment"), + ), + ("thoughtPressure", thought_pressure), + ("reactionIntensity", reaction_intensity), + ( + "commandForce", + trait_activation(situational, "command_force"), + ), + ]; + derived + .into_iter() + .map(|(name, value)| AgentUtteranceMoodDimension { + name: name.to_string(), + value: clamp_unit(value), + source_path: format!("currentMood.emotionalDimensions.{name}"), + }) + .collect() +} + +fn derive_utterance_activation( + participant: Option<&HeartbeatParticipant>, +) -> AgentUtteranceActivation { + let Some(participant) = participant else { + return AgentUtteranceActivation { + status: "unknown".to_string(), + initiative_speed: 1.0, + reaction_bias: 0.0, + interrupt_threshold: 0.0, + personality_cooldown_multiplier: 1.0, + mood_cooldown_multiplier: 1.0, + initiative_heat_multiplier: 1.0, + effective_cooldown_multiplier: 1.0, + ..AgentUtteranceActivation::default() + }; + }; + let effective_cooldown_multiplier = participant.personality_cooldown_multiplier + * participant.mood_cooldown_multiplier + / participant.initiative_heat_multiplier.max(0.001); + AgentUtteranceActivation { + status: participant.status.clone(), + current_load: participant.current_load, + initiative_speed: participant.initiative_speed, + reaction_bias: participant.reaction_bias, + interrupt_threshold: participant.interrupt_threshold, + personality_cooldown_multiplier: participant.personality_cooldown_multiplier, + mood_cooldown_multiplier: participant.mood_cooldown_multiplier, + initiative_heat_multiplier: participant.initiative_heat_multiplier, + effective_cooldown_multiplier, + pending_turn_active: participant.pending_turn.is_some(), + scene_id: participant.scene_id.clone(), + last_woke_at: participant.last_woke_at.clone(), + last_finished_at: participant.last_finished_at.clone(), + } +} + +fn inferred_mood_label( + arousal: Option, + situational: &BTreeMap, +) -> String { + let arousal = arousal.unwrap_or_else(|| trait_activation(situational, "arousal")); + if arousal >= 0.75 { + "activated".to_string() + } else if arousal <= 0.25 { + "quiet".to_string() + } else { + "attentive".to_string() + } +} + +fn trait_activation(vectors: &BTreeMap, name: &str) -> f64 { + vectors + .get(name) + .map(|vector| vector.current_activation) + .unwrap_or(0.0) +} + +fn utterance_embedding_basis( + role_id: &str, + identity: &AgentUtteranceIdentity, + personality_vectors: &AgentUtterancePersonalityVectors, + values: &[AgentUtteranceValue], + mood: &AgentUtteranceMood, + activation: &AgentUtteranceActivation, +) -> Vec { + let mut basis = Vec::new(); + basis.push(AgentUtteranceEmbeddingBasis { + kind: "identity".to_string(), + path: format!("agent.{role_id}.identity"), + weight: 1.0, + text: format!( + "{}: {} Origin: {} Roles: {}.", + identity.name, + identity.public_description, + identity.origin, + identity.roles.join(", ") + ), + }); + for value in values.iter().filter(|value| value.priority > 0.0) { + basis.push(AgentUtteranceEmbeddingBasis { + kind: "value".to_string(), + path: format!("agent.{role_id}.values.{}", value.value_id), + weight: value.priority, + text: value.label.clone(), + }); + } + push_trait_basis( + &mut basis, + role_id, + "underlying_organization", + &personality_vectors.underlying_organization, + ); + push_trait_basis( + &mut basis, + role_id, + "stable_dispositions", + &personality_vectors.stable_dispositions, + ); + push_trait_basis( + &mut basis, + role_id, + "behavioral_dimensions", + &personality_vectors.behavioral_dimensions, + ); + push_trait_basis( + &mut basis, + role_id, + "presentation_strategy", + &personality_vectors.presentation_strategy, + ); + push_trait_basis( + &mut basis, + role_id, + "voice_style", + &personality_vectors.voice_style, + ); + push_trait_basis( + &mut basis, + role_id, + "situational_state", + &personality_vectors.situational_state, + ); + basis.push(AgentUtteranceEmbeddingBasis { + kind: "mood".to_string(), + path: format!("agent.{role_id}.current_mood"), + weight: mood.reaction_intensity.max(mood.arousal).max(0.1), + text: format!( + "Mood {}: arousal {:.2}, urgency {:.2}, anxiety {:.2}, guardedness {:.2}, thought pressure {:.2}.", + mood.label, mood.arousal, mood.urgency, mood.anxiety, mood.guardedness, mood.thought_pressure + ), + }); + basis.push(AgentUtteranceEmbeddingBasis { + kind: "activation".to_string(), + path: format!("agent.{role_id}.activation"), + weight: activation + .current_load + .max(activation.initiative_heat_multiplier) + .max(0.1), + text: format!( + "Activation {}: load {:.2}, heat {:.2}, pending turn {}.", + activation.status, + activation.current_load, + activation.initiative_heat_multiplier, + activation.pending_turn_active + ), + }); + basis.sort_by(|left, right| { + right + .weight + .partial_cmp(&left.weight) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| left.path.cmp(&right.path)) + }); + basis.truncate(32); + basis +} + +fn character_state_vector( + personality_vectors: &AgentUtterancePersonalityVectors, + values: &[AgentUtteranceValue], + mood: &AgentUtteranceMood, + activation: &AgentUtteranceActivation, + source: &str, +) -> AgentUtteranceCharacterStateVector { + let slot_specs = character_state_slot_specs(); + let mut uncertainties = Vec::new(); + let mut values_out = Vec::with_capacity(AGENT_CHARACTER_STATE_VECTOR_SIZE); + let mut slots = Vec::with_capacity(AGENT_CHARACTER_STATE_VECTOR_SIZE); + for (index, spec) in slot_specs.iter().enumerate() { + let value = resolve_character_state_slot( + spec, + personality_vectors, + mood, + activation, + &mut uncertainties, + ); + let value = clamp_unit(value); + values_out.push(value); + slots.push(AgentUtteranceCharacterStateSlot { + index, + name: spec.name.to_string(), + value, + source_path: spec.source_path.to_string(), + }); + } + + AgentUtteranceCharacterStateVector { + schema_version: "epiphany.agent_character_state_vector.v0".to_string(), + compatible_handoff_schema: WEKSA_UTTERANCE_HANDOFF_SCHEMA_VERSION.to_string(), + source: source.to_string(), + dimensionality: AGENT_CHARACTER_STATE_VECTOR_SIZE, + values: values_out, + slots, + audit_projection: character_state_audit(mood, activation, personality_vectors, values), + uncertainties, + } +} + +struct CharacterStateSlotSpec { + name: &'static str, + source_path: &'static str, + source: CharacterStateSlotSource, +} + +enum CharacterStateSlotSource { + EmotionDimension(&'static str), + Activation(&'static str), + Trait { + group: CharacterTraitGroup, + name: &'static str, + }, + KnownZero(&'static str), +} + +#[derive(Clone, Copy)] +enum CharacterTraitGroup { + UnderlyingOrganization, + StableDispositions, + BehavioralDimensions, + PresentationStrategy, + VoiceStyle, +} + +fn character_state_slot_specs() -> [CharacterStateSlotSpec; AGENT_CHARACTER_STATE_VECTOR_SIZE] { + use CharacterStateSlotSource as Source; + use CharacterTraitGroup as Group; + [ + slot( + "valence", + "currentMood.emotionalDimensions.valence", + Source::EmotionDimension("valence"), + ), + slot( + "arousal", + "currentMood.emotionalDimensions.arousal", + Source::EmotionDimension("arousal"), + ), + slot( + "dominance", + "currentMood.emotionalDimensions.dominance", + Source::EmotionDimension("dominance"), + ), + slot( + "urgency", + "currentMood.emotionalDimensions.urgency", + Source::EmotionDimension("urgency"), + ), + slot( + "anger", + "currentMood.emotionalDimensions.anger", + Source::EmotionDimension("anger"), + ), + slot( + "despair", + "currentMood.emotionalDimensions.despair", + Source::EmotionDimension("despair"), + ), + slot( + "sadness", + "currentMood.emotionalDimensions.sadness", + Source::EmotionDimension("sadness"), + ), + slot( + "fear", + "currentMood.emotionalDimensions.fear", + Source::EmotionDimension("fear"), + ), + slot( + "anxiety", + "currentMood.emotionalDimensions.anxiety", + Source::EmotionDimension("anxiety"), + ), + slot( + "disgust", + "currentMood.emotionalDimensions.disgust", + Source::EmotionDimension("disgust"), + ), + slot( + "contempt", + "currentMood.emotionalDimensions.contempt", + Source::EmotionDimension("contempt"), + ), + slot( + "annoyance", + "currentMood.emotionalDimensions.annoyance", + Source::EmotionDimension("annoyance"), + ), + slot( + "dismissal", + "currentMood.emotionalDimensions.dismissal", + Source::EmotionDimension("dismissal"), + ), + slot( + "flippancy", + "currentMood.emotionalDimensions.flippancy", + Source::EmotionDimension("flippancy"), + ), + slot( + "playfulness", + "currentMood.emotionalDimensions.playfulness", + Source::EmotionDimension("playfulness"), + ), + slot( + "irony", + "currentMood.emotionalDimensions.irony", + Source::EmotionDimension("irony"), + ), + slot( + "tenderness", + "currentMood.emotionalDimensions.tenderness", + Source::EmotionDimension("tenderness"), + ), + slot( + "warmth", + "currentMood.emotionalDimensions.warmth", + Source::EmotionDimension("warmth"), + ), + slot( + "joy", + "currentMood.emotionalDimensions.joy", + Source::EmotionDimension("joy"), + ), + slot( + "excitement", + "currentMood.emotionalDimensions.excitement", + Source::EmotionDimension("excitement"), + ), + slot( + "fatigue", + "currentMood.emotionalDimensions.fatigue", + Source::EmotionDimension("fatigue"), + ), + slot( + "guardedness", + "currentMood.emotionalDimensions.guardedness", + Source::EmotionDimension("guardedness"), + ), + slot( + "confidence", + "currentMood.emotionalDimensions.confidence", + Source::EmotionDimension("confidence"), + ), + slot( + "shame", + "currentMood.emotionalDimensions.shame", + Source::EmotionDimension("shame"), + ), + slot( + "pride", + "currentMood.emotionalDimensions.pride", + Source::EmotionDimension("pride"), + ), + slot( + "threat", + "currentMood.emotionalDimensions.threat", + Source::EmotionDimension("threat"), + ), + slot( + "secrecy", + "currentMood.emotionalDimensions.secrecy", + Source::EmotionDimension("secrecy"), + ), + slot( + "hesitation", + "currentMood.emotionalDimensions.hesitation", + Source::EmotionDimension("hesitation"), + ), + slot( + "emotionalContainment", + "currentMood.emotionalDimensions.emotionalContainment", + Source::EmotionDimension("emotionalContainment"), + ), + slot( + "thoughtPressure", + "currentMood.emotionalDimensions.thoughtPressure", + Source::EmotionDimension("thoughtPressure"), + ), + slot( + "reactionIntensity", + "currentMood.emotionalDimensions.reactionIntensity", + Source::EmotionDimension("reactionIntensity"), + ), + slot( + "commandForce", + "currentMood.emotionalDimensions.commandForce", + Source::EmotionDimension("commandForce"), + ), + slot( + "currentLoad", + "activation.currentLoad", + Source::Activation("current_load"), + ), + slot( + "initiativeHeat", + "activation.initiativeHeatMultiplier", + Source::Activation("initiative_heat_multiplier"), + ), + slot( + "pendingTurn", + "activation.pendingTurnActive", + Source::Activation("pending_turn_active"), + ), + slot( + "cooldownPressure", + "activation.effectiveCooldownMultiplier", + Source::Activation("cooldown_pressure"), + ), + slot( + "reactionBias", + "activation.reactionBias", + Source::Activation("reaction_bias"), + ), + slot( + "interruptThreshold", + "activation.interruptThreshold", + Source::Activation("interrupt_threshold"), + ), + slot( + "initiativeSpeed", + "activation.initiativeSpeed", + Source::Activation("initiative_speed"), + ), + slot( + "voiceBubbly", + "personalityVectors.voiceStyle.bubbly_pushiness", + Source::Trait { + group: Group::VoiceStyle, + name: "bubbly_pushiness", + }, + ), + slot( + "voiceDryness", + "personalityVectors.voiceStyle.dryness", + Source::Trait { + group: Group::VoiceStyle, + name: "dryness", + }, + ), + slot( + "voiceFormality", + "personalityVectors.voiceStyle.formality", + Source::Trait { + group: Group::VoiceStyle, + name: "formality", + }, + ), + slot( + "voiceDirectness", + "personalityVectors.voiceStyle.directness", + Source::Trait { + group: Group::VoiceStyle, + name: "directness", + }, + ), + slot( + "voiceIntensity", + "personalityVectors.voiceStyle.intensity", + Source::Trait { + group: Group::VoiceStyle, + name: "intensity", + }, + ), + slot( + "voiceWarmth", + "personalityVectors.voiceStyle.warmth", + Source::Trait { + group: Group::VoiceStyle, + name: "warmth", + }, + ), + slot( + "voicePrecision", + "personalityVectors.voiceStyle.precision", + Source::Trait { + group: Group::VoiceStyle, + name: "precision", + }, + ), + slot( + "voiceRitualRegister", + "personalityVectors.voiceStyle.ritual_register", + Source::Trait { + group: Group::VoiceStyle, + name: "ritual_register", + }, + ), + slot( + "presentationPushiness", + "personalityVectors.presentationStrategy.pushiness", + Source::Trait { + group: Group::PresentationStrategy, + name: "pushiness", + }, + ), + slot( + "presentationSelfFocus", + "personalityVectors.presentationStrategy.self_focus", + Source::Trait { + group: Group::PresentationStrategy, + name: "self_focus", + }, + ), + slot( + "presentationPlay", + "personalityVectors.presentationStrategy.play", + Source::Trait { + group: Group::PresentationStrategy, + name: "play", + }, + ), + slot( + "presentationCareDemand", + "personalityVectors.presentationStrategy.care_demand", + Source::Trait { + group: Group::PresentationStrategy, + name: "care_demand", + }, + ), + slot( + "behaviorWorkDrive", + "personalityVectors.behavioralDimensions.work_drive", + Source::Trait { + group: Group::BehavioralDimensions, + name: "work_drive", + }, + ), + slot( + "behaviorBoundaryDefense", + "personalityVectors.behavioralDimensions.boundary_defense", + Source::Trait { + group: Group::BehavioralDimensions, + name: "boundary_defense", + }, + ), + slot( + "behaviorPurityDrive", + "personalityVectors.behavioralDimensions.purity_drive", + Source::Trait { + group: Group::BehavioralDimensions, + name: "purity_drive", + }, + ), + slot( + "behaviorPatience", + "personalityVectors.behavioralDimensions.patience", + Source::Trait { + group: Group::BehavioralDimensions, + name: "patience", + }, + ), + slot( + "stableAgreeableness", + "personalityVectors.stableDispositions.agreeableness", + Source::Trait { + group: Group::StableDispositions, + name: "agreeableness", + }, + ), + slot( + "stableConscientiousness", + "personalityVectors.stableDispositions.conscientiousness", + Source::Trait { + group: Group::StableDispositions, + name: "conscientiousness", + }, + ), + slot( + "stableNeuroticism", + "personalityVectors.stableDispositions.neuroticism", + Source::Trait { + group: Group::StableDispositions, + name: "neuroticism", + }, + ), + slot( + "stableOpenness", + "personalityVectors.stableDispositions.openness", + Source::Trait { + group: Group::StableDispositions, + name: "openness", + }, + ), + slot( + "organizationCoherence", + "personalityVectors.underlyingOrganization.coherence", + Source::Trait { + group: Group::UnderlyingOrganization, + name: "coherence", + }, + ), + slot( + "organizationRigidity", + "personalityVectors.underlyingOrganization.rigidity", + Source::Trait { + group: Group::UnderlyingOrganization, + name: "rigidity", + }, + ), + slot( + "slowTraitReserved62", + "reserved.slowTrait.62", + Source::KnownZero("Reserved slow-trait/context slot."), + ), + slot( + "slowTraitReserved63", + "reserved.slowTrait.63", + Source::KnownZero("Reserved slow-trait/context slot."), + ), + slot( + "slowTraitReserved64", + "reserved.slowTrait.64", + Source::KnownZero("Reserved slow-trait/context slot."), + ), + ] +} + +const fn slot( + name: &'static str, + source_path: &'static str, + source: CharacterStateSlotSource, +) -> CharacterStateSlotSpec { + CharacterStateSlotSpec { + name, + source_path, + source, + } +} + +fn resolve_character_state_slot( + spec: &CharacterStateSlotSpec, + personality_vectors: &AgentUtterancePersonalityVectors, + mood: &AgentUtteranceMood, + activation: &AgentUtteranceActivation, + uncertainties: &mut Vec, +) -> f64 { + match spec.source { + CharacterStateSlotSource::EmotionDimension(name) => mood + .emotional_dimensions + .iter() + .find(|dimension| dimension.name == name) + .map(|dimension| dimension.value) + .unwrap_or_else(|| { + uncertainties.push(format!("{} is unknown; emitted 0.", spec.source_path)); + 0.0 + }), + CharacterStateSlotSource::Activation(name) => activation_value(activation, name), + CharacterStateSlotSource::Trait { group, name } => { + trait_vector_group(personality_vectors, group) + .get(name) + .map(|vector| vector.current_activation.max(vector.mean)) + .unwrap_or_else(|| { + uncertainties.push(format!("{} is unknown; emitted 0.", spec.source_path)); + 0.0 + }) + } + CharacterStateSlotSource::KnownZero(reason) => { + uncertainties.push(format!("{} is 0: {reason}", spec.name)); + 0.0 + } + } +} + +fn activation_value(activation: &AgentUtteranceActivation, name: &str) -> f64 { + match name { + "current_load" => activation.current_load, + "initiative_heat_multiplier" => multiplier_pressure(activation.initiative_heat_multiplier), + "pending_turn_active" => { + if activation.pending_turn_active { + 1.0 + } else { + 0.0 + } + } + "cooldown_pressure" => multiplier_pressure(activation.effective_cooldown_multiplier), + "reaction_bias" => activation.reaction_bias, + "interrupt_threshold" => activation.interrupt_threshold, + "personality_cooldown_multiplier" => { + multiplier_pressure(activation.personality_cooldown_multiplier) + } + "mood_cooldown_multiplier" => multiplier_pressure(activation.mood_cooldown_multiplier), + "initiative_speed" => multiplier_pressure(activation.initiative_speed), + _ => 0.0, + } +} + +fn multiplier_pressure(value: f64) -> f64 { + if !value.is_finite() { + return 0.0; + } + (value / (value.abs() + 1.0)).clamp(0.0, 1.0) +} + +fn trait_vector_group( + personality_vectors: &AgentUtterancePersonalityVectors, + group: CharacterTraitGroup, +) -> &BTreeMap { + match group { + CharacterTraitGroup::UnderlyingOrganization => &personality_vectors.underlying_organization, + CharacterTraitGroup::StableDispositions => &personality_vectors.stable_dispositions, + CharacterTraitGroup::BehavioralDimensions => &personality_vectors.behavioral_dimensions, + CharacterTraitGroup::PresentationStrategy => &personality_vectors.presentation_strategy, + CharacterTraitGroup::VoiceStyle => &personality_vectors.voice_style, + } +} + +fn character_state_audit( + mood: &AgentUtteranceMood, + activation: &AgentUtteranceActivation, + personality_vectors: &AgentUtterancePersonalityVectors, + values: &[AgentUtteranceValue], +) -> AgentUtteranceCharacterStateAudit { + let mut current_state_pressure = vec![ + format!("mood={}", mood.label), + format!("arousal={:.2}", mood.arousal), + format!("urgency={:.2}", mood.urgency), + format!("thought_pressure={:.2}", mood.thought_pressure), + format!("load={:.2}", activation.current_load), + ]; + if activation.pending_turn_active { + current_state_pressure.push("pending_turn=true".to_string()); + } + + let mut speaker_trait_pressure = strongest_trait_notes(personality_vectors); + if let Some(value) = values + .iter() + .max_by(|left, right| left.priority.total_cmp(&right.priority)) + { + speaker_trait_pressure.push(format!("top_value={} ({:.2})", value.label, value.priority)); + } + + AgentUtteranceCharacterStateAudit { + current_state_pressure, + speaker_trait_pressure, + delivery_shape: format!( + "Voice should preserve identity while bending toward {} delivery with heat {:.2} and cooldown {:.2}.", + mood.label, + activation.initiative_heat_multiplier, + activation.effective_cooldown_multiplier + ), + } +} + +fn strongest_trait_notes(personality_vectors: &AgentUtterancePersonalityVectors) -> Vec { + let groups = [ + ( + "underlying_organization", + &personality_vectors.underlying_organization, + ), + ( + "stable_dispositions", + &personality_vectors.stable_dispositions, + ), + ( + "behavioral_dimensions", + &personality_vectors.behavioral_dimensions, + ), + ( + "presentation_strategy", + &personality_vectors.presentation_strategy, + ), + ("voice_style", &personality_vectors.voice_style), + ("situational_state", &personality_vectors.situational_state), + ]; + let mut traits = groups + .iter() + .flat_map(|(group, vectors)| { + vectors.iter().map(move |(name, vector)| { + ( + format!("{group}.{name}"), + vector.mean.max(vector.current_activation), + ) + }) + }) + .collect::>(); + traits.sort_by(|left, right| { + right + .1 + .total_cmp(&left.1) + .then_with(|| left.0.cmp(&right.0)) + }); + traits + .into_iter() + .take(6) + .map(|(name, weight)| format!("{name}={weight:.2}")) + .collect() +} + +fn clamp_unit(value: f64) -> f64 { + if value.is_finite() { + value.clamp(0.0, 1.0) + } else { + 0.0 + } +} + +fn push_trait_basis( + basis: &mut Vec, + role_id: &str, + group: &str, + vectors: &BTreeMap, +) { + let mut active = vectors.iter().collect::>(); + active.sort_by(|(left_name, left), (right_name, right)| { + trait_weight(right) + .partial_cmp(&trait_weight(left)) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| left_name.cmp(right_name)) + }); + for (name, vector) in active.into_iter().take(4) { + let weight = trait_weight(vector); + if weight <= 0.0 { + continue; + } + basis.push(AgentUtteranceEmbeddingBasis { + kind: "traitVector".to_string(), + path: format!("agent.{role_id}.canonicalState.{group}.{name}"), + weight, + text: format!( + "{group}.{name}: mean {:.2}, current activation {:.2}, plasticity {:.2}.", + vector.mean, vector.current_activation, vector.plasticity + ), + }); + } +} + +fn trait_weight(vector: &GhostlightTraitVector) -> f64 { + vector + .mean + .max(vector.current_activation) + .max(vector.plasticity * 0.25) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::agent_memory::EpiphanyDossierProfileKind; + use crate::agent_memory::GhostlightAgent; + use crate::agent_memory::GhostlightIdentity; + use crate::agent_memory::GhostlightMemories; + use crate::agent_memory::GhostlightValue; + use crate::agent_memory::GhostlightWorld; + use crate::heartbeat_state::HeartbeatMoodTiming; + + #[test] + fn utterance_state_projects_voice_without_memories() -> anyhow::Result<()> { + let mut voice_style = BTreeMap::new(); + voice_style.insert( + "bubbly_pushiness".to_string(), + GhostlightTraitVector { + mean: 0.88, + plasticity: 0.2, + current_activation: 0.91, + }, + ); + let mut situational_state = BTreeMap::new(); + for (name, activation) in [ + ("anger", 0.61), + ("despair", 0.22), + ("annoyance", 0.73), + ("dismissal", 0.58), + ("flippancy", 0.67), + ("emotional_containment", 0.49), + ] { + situational_state.insert( + name.to_string(), + GhostlightTraitVector { + mean: activation, + plasticity: 0.4, + current_activation: activation, + }, + ); + } + let entry = EpiphanyAgentMemoryEntry { + schema_version: "ghostlight.agent_state.v0".to_string(), + role_id: "face".to_string(), + world: GhostlightWorld::default(), + agent: GhostlightAgent { + agent_id: "epiphany.face".to_string(), + identity: GhostlightIdentity { + name: "Epiphany".to_string(), + roles: vec!["Face".to_string()], + origin: "Epiphany local harness".to_string(), + public_description: "Cute, pushy public machine-spirit.".to_string(), + private_notes: vec!["must not leak".to_string()], + }, + canonical_state: GhostlightCanonicalState { + voice_style, + situational_state, + values: vec![GhostlightValue { + value_id: "purity".to_string(), + label: "Protect typed purity.".to_string(), + priority: 0.93, + unforgivable_if_betrayed: true, + }], + ..GhostlightCanonicalState::default() + }, + memories: GhostlightMemories { + semantic: vec![crate::agent_memory::GhostlightMemory { + memory_id: "mem-secret".to_string(), + summary: "This should not enter utterance state.".to_string(), + salience: 1.0, + confidence: 1.0, + linked_event_ids: None, + linked_relationship_id: None, + }], + ..GhostlightMemories::default() + }, + ..GhostlightAgent::default() + }, + relationships: Vec::new(), + events: Vec::new(), + scenes: Vec::new(), + }; + let participant = HeartbeatParticipant { + agent_id: "epiphany.face".to_string(), + role_id: "face".to_string(), + display_name: "Epiphany".to_string(), + initiative_speed: 1.4, + reaction_bias: 0.7, + interrupt_threshold: 0.25, + current_load: 0.42, + status: "awake".to_string(), + constraints: Vec::new(), + last_action_id: None, + last_woke_at: Some("2026-05-20T12:00:00+00:00".to_string()), + last_finished_at: None, + pending_turn: None, + personality_cooldown_multiplier: 0.8, + mood_cooldown_multiplier: 0.7, + initiative_heat_multiplier: 1.5, + mood_timing: Some(HeartbeatMoodTiming { + source: Some("heartbeat appraisal".to_string()), + anxiety: 0.33, + urgency: 0.74, + arousal: 0.82, + thought_pressure: 0.69, + guardedness: 0.21, + reaction_intensity: 0.77, + cooldown_multiplier: 0.7, + ..HeartbeatMoodTiming::default() + }), + ..HeartbeatParticipant::default() + }; + + let utterance = derive_agent_utterance_state( + &entry, + Some(&participant), + Some("sparkly-urgent"), + "test", + ); + assert_eq!( + utterance.schema_version, + AGENT_UTTERANCE_STATE_SCHEMA_VERSION + ); + assert_eq!( + utterance.dossier_profile.profile_kind, + EpiphanyDossierProfileKind::EmbodiedActor + ); + assert_eq!(utterance.identity.name, "Epiphany"); + assert_eq!(utterance.current_mood.label, "sparkly-urgent"); + assert_eq!(utterance.current_mood.urgency, 0.74); + assert_eq!(mood_dimension(&utterance.current_mood, "anger"), Some(0.61)); + assert_eq!( + mood_dimension(&utterance.current_mood, "annoyance"), + Some(0.73) + ); + assert_eq!( + mood_dimension(&utterance.current_mood, "flippancy"), + Some(0.67) + ); + assert_eq!(utterance.activation.status, "awake"); + assert_eq!( + utterance.character_state_vector.compatible_handoff_schema, + WEKSA_UTTERANCE_HANDOFF_SCHEMA_VERSION + ); + assert_eq!( + utterance.character_state_vector.dimensionality, + AGENT_CHARACTER_STATE_VECTOR_SIZE + ); + assert_eq!( + utterance.character_state_vector.values.len(), + AGENT_CHARACTER_STATE_VECTOR_SIZE + ); + assert_eq!(utterance.character_state_vector.values[1], 0.82); + assert_eq!(utterance.character_state_vector.values[3], 0.74); + assert_eq!(utterance.character_state_vector.values[4], 0.61); + assert_eq!(utterance.character_state_vector.values[11], 0.73); + assert_eq!(utterance.character_state_vector.values[13], 0.67); + assert!( + utterance + .personality_vectors + .voice_style + .contains_key("bubbly_pushiness") + ); + assert!( + utterance + .utterance_embedding_basis + .iter() + .any(|basis| basis.path.contains("voice_style.bubbly_pushiness")) + ); + + let wire = serde_json::to_value(&utterance)?; + assert!(wire.get("memories").is_none()); + assert!(wire.pointer("/agent/memories").is_none()); + assert!(wire.get("relationships").is_none()); + assert!(!wire.to_string().contains("mem-secret")); + Ok(()) + } + + fn mood_dimension(mood: &AgentUtteranceMood, name: &str) -> Option { + mood.emotional_dimensions + .iter() + .find(|dimension| dimension.name == name) + .map(|dimension| dimension.value) + } +} diff --git a/epiphany-core/src/bin/epiphany-character-loop.rs b/epiphany-core/src/bin/epiphany-character-loop.rs index a2965f8a..6dc74703 100644 --- a/epiphany-core/src/bin/epiphany-character-loop.rs +++ b/epiphany-core/src/bin/epiphany-character-loop.rs @@ -3,7 +3,6 @@ use anyhow::Result; use anyhow::anyhow; use chrono::SecondsFormat; use epiphany_core::EpiphanyAgentMemoryEntry; -use epiphany_core::GhostlightMemory; use epiphany_core::GhostlightPerceivedStateOverlay; use epiphany_core::GhostlightTraitVector; use epiphany_core::HeartbeatAgentReaction; @@ -11,8 +10,10 @@ use epiphany_core::HeartbeatAgentThoughtAppraisal; use epiphany_core::HeartbeatAppraisalReview; use epiphany_core::HeartbeatCandidateImplications; use epiphany_core::HeartbeatEmotionalAppraisal; +use epiphany_core::HeartbeatParticipant; use epiphany_core::HeartbeatParticipantLocalContext; use epiphany_core::HeartbeatPersonalityProjection; +use epiphany_core::derive_agent_utterance_state; use epiphany_core::dossier_profile_for_role; use epiphany_core::load_agent_memory_entry_for_role; use serde::Serialize; @@ -129,6 +130,9 @@ fn character_turn_packet( mood: &str, ) -> Value { let dossier_profile = dossier_profile_for_role(&entry.role_id); + let participant = character_loop_participant(entry, status); + let utterance_state = + derive_agent_utterance_state(entry, Some(&participant), Some(mood), source); let projection_seed = deterministic_projection_seed(entry, stimulus, source, mode, status, mood); let appraisal_seed = deterministic_appraisal_seed(entry, &projection_seed, stimulus, source); @@ -153,6 +157,7 @@ fn character_turn_packet( "status": status, "mood": mood, }, + "utteranceState": utterance_state, "projectedLocalContext": { "identity": { "name": entry.agent.identity.name, @@ -181,9 +186,6 @@ fn character_turn_packet( "priority": value.priority, "unforgivableIfBetrayed": value.unforgivable_if_betrayed, })).collect::>(), - "semanticMemories": entry.agent.memories.semantic.iter().map(memory_projection).collect::>(), - "episodicMemories": entry.agent.memories.episodic.iter().map(memory_projection).collect::>(), - "relationshipMemories": entry.agent.memories.relationship_summaries.iter().map(memory_projection).collect::>(), "perceivedStateOverlays": entry.agent.perceived_state_overlays.iter().take(6).map(perceived_overlay_projection).collect::>(), "privateNoteCount": entry.agent.identity.private_notes.len(), }, @@ -252,13 +254,23 @@ fn character_turn_packet( }) } -fn memory_projection(memory: &GhostlightMemory) -> Value { - serde_json::json!({ - "memoryId": memory.memory_id, - "summary": memory.summary, - "salience": memory.salience, - "confidence": memory.confidence, - }) +fn character_loop_participant( + entry: &EpiphanyAgentMemoryEntry, + status: &str, +) -> HeartbeatParticipant { + HeartbeatParticipant { + agent_id: entry.agent.agent_id.clone(), + role_id: entry.role_id.clone(), + display_name: entry.agent.identity.name.clone(), + initiative_speed: 1.0, + reaction_bias: 0.5, + interrupt_threshold: 0.5, + status: status.to_string(), + personality_cooldown_multiplier: 1.0, + mood_cooldown_multiplier: 1.0, + initiative_heat_multiplier: 1.0, + ..HeartbeatParticipant::default() + } } #[derive(Clone, Debug)] @@ -772,6 +784,24 @@ fn run_smoke() -> Result { && packet["protocol"]["roleId"] == "face" && packet["protocol"]["dossierProfile"]["profileKind"] == "embodied_actor" && packet["projectedLocalContext"]["dossierProfile"]["profileKind"] == "embodied_actor" + && packet["utteranceState"]["schemaVersion"] == "epiphany.agent_utterance_state.v0" + && packet["utteranceState"]["identity"]["name"] + == packet["projectedLocalContext"]["identity"]["name"] + && packet["utteranceState"]["personalityVectors"]["voiceStyle"].is_object() + && packet["utteranceState"]["characterStateVector"]["compatibleHandoffSchema"] + == "weksa.utterance_embedding_handoff.v0.1" + && packet["utteranceState"]["characterStateVector"]["values"] + .as_array() + .is_some_and(|values| values.len() == 64) + && packet["projectedLocalContext"] + .get("semanticMemories") + .is_none() + && packet["projectedLocalContext"] + .get("episodicMemories") + .is_none() + && packet["projectedLocalContext"] + .get("relationshipMemories") + .is_none() && packet["projectionSeed"]["schema_version"] == "epiphany.personality_projection.v0" && packet["appraisalSeed"]["schema_version"] == "epiphany.agent_thought_appraisal.v0" && packet["reactionSeed"]["schema_version"] == "epiphany.agent_reaction.v0" @@ -797,6 +827,7 @@ fn run_smoke() -> Result { "projectionSchema": packet["projectionSeed"]["schema_version"], "appraisalSchema": packet["appraisalSeed"]["schema_version"], "reactionSchema": packet["reactionSeed"]["schema_version"], + "utteranceStateSchema": packet["utteranceState"]["schemaVersion"], "identityName": packet["projectedLocalContext"]["identity"]["name"], "allowedOutputs": packet["allowedOutputs"], "cognitionLanes": packet["cognitionLanes"]["schema_version"], diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 892ad48e..143f796d 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1,4 +1,5 @@ mod agent_memory; +mod agent_utterance_state; mod distillation; mod heartbeat_state; mod memory_graph; @@ -35,6 +36,20 @@ pub use agent_memory::project_agent_memory_to_json_dir; pub use agent_memory::review_agent_self_patch; pub use agent_memory::review_agent_self_patch_document; pub use agent_memory::validate_agent_memory_store; +pub use agent_utterance_state::AGENT_CHARACTER_STATE_VECTOR_SIZE; +pub use agent_utterance_state::AGENT_UTTERANCE_STATE_SCHEMA_VERSION; +pub use agent_utterance_state::AgentUtteranceActivation; +pub use agent_utterance_state::AgentUtteranceCharacterStateAudit; +pub use agent_utterance_state::AgentUtteranceCharacterStateSlot; +pub use agent_utterance_state::AgentUtteranceCharacterStateVector; +pub use agent_utterance_state::AgentUtteranceEmbeddingBasis; +pub use agent_utterance_state::AgentUtteranceIdentity; +pub use agent_utterance_state::AgentUtteranceMood; +pub use agent_utterance_state::AgentUtterancePersonalityVectors; +pub use agent_utterance_state::AgentUtteranceState; +pub use agent_utterance_state::AgentUtteranceValue; +pub use agent_utterance_state::WEKSA_UTTERANCE_HANDOFF_SCHEMA_VERSION; +pub use agent_utterance_state::derive_agent_utterance_state; pub use cultcache_rs::CacheBackingStore; pub use cultcache_rs::CultCache; pub use cultcache_rs::CultCacheEnvelope; diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 1cd64f16..ebd7ac3b 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -154,7 +154,7 @@ remembers doctrine; the branch remembers the blade. - Manual Codex-run rumination still has an explicit aftercare rule until Epiphany owns the full sleep consolidator. In the intended Epiphany cycle, sub-agents ruminate when idle and distill when they sleep; in this supervising Codex thread, a heartbeat/routine vigil is only physiology until a separate closing pass reviews the receipts and decides whether map, handoff, evidence, or role self-memory should change. - The Face public-surface pass is landed as a bounded lane. Face's role dossier lives in `state/agents.msgpack`; `epiphany_specialists.toml` gives it a VoidBot-heartbeat-derived prompt stripped of moderation authority; `state/face-discord.toml` and the native `epiphany-face-discord` binary enforce that Face may interact only through #aquarium. Missing channel id or token writes candidate chat artifacts instead of posting elsewhere. If a Face has a persona name/avatar, `post` uses the shared Discord webhook pipe so each Epiphany can speak with its own nickname and avatar without a separate bot identity. - The Void memory bridge is now native enough to keep the useful organs attached. `state/void-memory.toml` and `epiphany-void-memory` can check Void's Docker Postgres state spine, query Qdrant Discord-history and source/lore collections with the configured Ollama embedding model, and fetch raw archive context windows from Void's file-backed Discord archive. Native `epiphany-mvp-status` includes a `voidMemory` block so Aquarium/backend clients can inspect whether the mouth and memory are actually wired. -- The first Epiphany-native character-loop pass is landed. `epiphany-character-loop turn --role face --stimulus ` loads Face's typed dossier from `state/agents.msgpack`, builds typed projection/appraisal/reaction seeds from the shared heartbeat cognition documents, and emits an auditable `epiphany.character_turn_packet.v0` packet with projected local context, visible stimulus, allowed outputs, and guardrails. The same packet builder works for other role ids, because every organ already has a Ghostlight-shaped dossier. +- The Epiphany-native character-loop now emits a Weksa/AquaSynth-ready utterance-state seam. `epiphany-character-loop turn --role face --stimulus ` loads Face's typed dossier from `state/agents.msgpack`, builds typed projection/appraisal/reaction seeds from the shared heartbeat cognition documents, and emits an auditable `epiphany.character_turn_packet.v0` packet with `epiphany.agent_utterance_state.v0`. That utterance state is memory-free: identity, personality vectors, values, current mood, activation, 32 named affect dimensions, and the fixed 64-float `weksa.utterance_embedding_handoff.v0.1` character-state vector for AquaSynth/Weksa speech embedding. The same packet builder works for other role ids, because every organ already has a Ghostlight-shaped dossier. - The heartbeat/Face operator API pass is landed. Native `epiphany-heartbeat-store status` returns machine-readable initiative state plus CultCache store presence, thought appraisals, and derived reactions; native `epiphany-face-discord bubble` writes Discord-independent `epiphany.face_bubble.v0` artifacts, and native `epiphany-mvp-status` includes `heartbeat` and `face` blocks. Aquarium should call native/backend surfaces rather than resurrecting deleted Python action shims. - The native runtime-spine pass is landed as a first vertebra, not a full daemon. `state/runtime-spine.msgpack` is the default store, `.epiphany-dogfood/runtime-spine-job/runtime.msgpack` and `hello.cultnet` are the latest job/result smoke artifacts, and specialist launch/result flows now route through typed heartbeat/runtime-spine documents. Its CultNet hello advertises mutation contracts for runtime/session/job/memory/heartbeat/ledger documents, with coordinator-owned intent/receipt paths for writes. - The Aetheria dogfood run has a contamination scar. The supervising Codex session directly edited and committed target-repo work on `E:\Projects\Aetheria-Economy` instead of only driving Epiphany lanes. Treat those Aetheria commits as supervisor-seeded implementation, not clean evidence that Epiphany coordinated the work. Future dogfood must run through the GUI/coordinator/fixed role lanes with auditable artifacts unless the user explicitly authorizes an operator intervention. Remember the sunburn: do not stare into the worker's objective until you become it. diff --git a/schemas/README.md b/schemas/README.md index 29ebdb52..25414e52 100644 --- a/schemas/README.md +++ b/schemas/README.md @@ -21,6 +21,10 @@ developer's damp recollection. - [dossier-profiles.md](./dossier-profiles.md): explicit split between lean Epiphany work-organ dossiers and embodied Ghostlight/Face personalities. +- [agent-utterance-state-schema.md](./agent-utterance-state-schema.md): + derived speech-conditioning subset for Weks, Aquarium, and other utterance + surfaces; it carries identity, trait vectors, mood, and activation without + memory records. - [repo-personality-birth-projection.md](./repo-personality-birth-projection.md): deterministic birth-time path from repo terrain to newborn trait lattice and heartbeat seeds. diff --git a/schemas/agent-utterance-state-schema.md b/schemas/agent-utterance-state-schema.md new file mode 100644 index 00000000..3b87f032 --- /dev/null +++ b/schemas/agent-utterance-state-schema.md @@ -0,0 +1,57 @@ +# Agent Utterance State Schema + +`epiphany.agent_utterance_state.v0` is the compact speech-conditioning view for +Weks, Aquarium, Discord/voice bridges, and any other surface that needs an agent +to sound like itself without ingesting the whole Ghostlight dossier. + +It is a derived document. The durable source of truth stays split where it +belongs: + +- canonical identity, values, and trait vectors live in the Ghostlight-shaped + role dossier (`EpiphanyAgentMemoryEntry`) +- current load, heartbeat heat, cooldown multipliers, pending-turn state, and + mood pressure live in heartbeat participant state +- utterance systems consume the derived subset and do not read memories, + events, scenes, or relationship-memory records + +## Shape + +The document carries: + +- `identity`: public name, roles, origin, and public description only +- `personalityVectors`: the six canonical trait-vector families used for voice + and behavior projection +- `values`: value labels and priorities that should bend speech tone +- `currentMood`: mood label plus a 32-axis named emotional state projection + covering valence, arousal, dominance, urgency, anger, despair, sadness, fear, + anxiety, disgust, contempt, annoyance, dismissal, flippancy, playfulness, + irony, tenderness, warmth, joy, excitement, fatigue, guardedness, confidence, + shame, pride, threat, secrecy, hesitation, emotional containment, thought + pressure, reaction intensity, and command force +- `activation`: awake/running status, current load, initiative speed, + interruptibility, cooldown multipliers, heat multiplier, pending-turn flag, + and last wake/finish timestamps +- `characterStateVector`: the 64-float deterministic + `weksa.utterance_embedding_handoff.v0.1` speaker-state lane; first 32 slots + are the current emotional state projection, later slots add activation and + slower speaker traits/context, with slot labels and uncertainties kept beside + the values +- `utteranceEmbeddingBasis`: bounded weighted text snippets generated from the + same typed fields for utterance embedding input + +## Invariants + +- No episodic memories. +- No semantic memories. +- No relationship summaries or linked memory ids. +- No private notes. +- No hidden JSON cargo. +- The `characterStateVector.values` array is exactly 64 floats. Resizing or + reordering slots is a schema-version change. +- The document may be serialized for CultNet, but in-process callers should use + the typed Rust structs. + +If a caller needs autobiographical recall, it should ask the memory graph for a +separate context cut. Do not fatten this document until it becomes a second +dossier wearing stage makeup. That is how the old machine learned to lie +politely. diff --git a/schemas/cultnet/README.md b/schemas/cultnet/README.md index 236243fe..a53e567c 100644 --- a/schemas/cultnet/README.md +++ b/schemas/cultnet/README.md @@ -28,7 +28,9 @@ server object deserves to be duplicated into a second baroque schema maze. - `epiphany.runtime.*`: native runtime-spine identity, session, job, job result, and event documents. - `epiphany.agent_*` and `epiphany.state-ledger`: durable typed state the swarm - actually lives on. + actually lives on, plus derived agent views such as + `epiphany.agent_utterance_state.v0` for speech-conditioning without memory + payloads. - `epiphany.surface.*`: operator-safe projections for scene, freshness, context, graph query, coordinator, roles, jobs, Face, Rider, Unity, repo initialization, and related live surfaces. diff --git a/schemas/cultnet/epiphany.agent-utterance-state.schema.json b/schemas/cultnet/epiphany.agent-utterance-state.schema.json new file mode 100644 index 00000000..8bdb716a --- /dev/null +++ b/schemas/cultnet/epiphany.agent-utterance-state.schema.json @@ -0,0 +1,451 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.agent-utterance-state.schema.json", + "title": "Epiphany Agent Utterance State", + "description": "Derived speech-conditioning subset of a Ghostlight agent dossier plus heartbeat mood/activation. Excludes memories.", + "type": "object", + "additionalProperties": false, + "properties": { + "schemaVersion": { + "const": "epiphany.agent_utterance_state.v0" + }, + "source": { + "type": "string" + }, + "roleId": { + "type": "string" + }, + "agentId": { + "type": "string" + }, + "dossierProfile": { + "type": "object", + "additionalProperties": false, + "properties": { + "profileKind": { + "enum": [ + "lane_core", + "embodied_actor" + ] + }, + "canonicalDensity": { + "type": "string" + }, + "relationshipModel": { + "type": "string" + }, + "perceivedOverlayMode": { + "type": "string" + }, + "growthChannels": { + "type": "array", + "items": { + "type": "string" + } + }, + "notes": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "profileKind", + "canonicalDensity", + "relationshipModel", + "perceivedOverlayMode", + "growthChannels", + "notes" + ] + }, + "identity": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "roles": { + "type": "array", + "items": { + "type": "string" + } + }, + "origin": { + "type": "string" + }, + "publicDescription": { + "type": "string" + } + }, + "required": [ + "name", + "roles", + "origin", + "publicDescription" + ] + }, + "personalityVectors": { + "$ref": "#/definitions/personalityVectors" + }, + "values": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "valueId": { + "type": "string" + }, + "label": { + "type": "string" + }, + "priority": { + "type": "number" + }, + "unforgivableIfBetrayed": { + "type": "boolean" + } + }, + "required": [ + "valueId", + "label", + "priority", + "unforgivableIfBetrayed" + ] + } + }, + "currentMood": { + "type": "object", + "additionalProperties": false, + "properties": { + "label": { + "type": "string" + }, + "source": { + "type": "string" + }, + "emotionalDimensions": { + "type": "array", + "minItems": 32, + "maxItems": 32, + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "number" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "name", + "value", + "sourcePath" + ] + } + }, + "anxiety": { + "type": "number" + }, + "urgency": { + "type": "number" + }, + "arousal": { + "type": "number" + }, + "thoughtPressure": { + "type": "number" + }, + "guardedness": { + "type": "number" + }, + "reactionIntensity": { + "type": "number" + }, + "cooldownMultiplier": { + "type": "number" + } + }, + "required": [ + "label", + "emotionalDimensions", + "anxiety", + "urgency", + "arousal", + "thoughtPressure", + "guardedness", + "reactionIntensity", + "cooldownMultiplier" + ] + }, + "activation": { + "type": "object", + "additionalProperties": false, + "properties": { + "status": { + "type": "string" + }, + "currentLoad": { + "type": "number" + }, + "initiativeSpeed": { + "type": "number" + }, + "reactionBias": { + "type": "number" + }, + "interruptThreshold": { + "type": "number" + }, + "personalityCooldownMultiplier": { + "type": "number" + }, + "moodCooldownMultiplier": { + "type": "number" + }, + "initiativeHeatMultiplier": { + "type": "number" + }, + "effectiveCooldownMultiplier": { + "type": "number" + }, + "pendingTurnActive": { + "type": "boolean" + }, + "sceneId": { + "type": "string" + }, + "lastWokeAt": { + "type": "string" + }, + "lastFinishedAt": { + "type": "string" + } + }, + "required": [ + "status", + "currentLoad", + "initiativeSpeed", + "reactionBias", + "interruptThreshold", + "personalityCooldownMultiplier", + "moodCooldownMultiplier", + "initiativeHeatMultiplier", + "effectiveCooldownMultiplier", + "pendingTurnActive" + ] + }, + "characterStateVector": { + "type": "object", + "additionalProperties": false, + "properties": { + "schemaVersion": { + "const": "epiphany.agent_character_state_vector.v0" + }, + "compatibleHandoffSchema": { + "const": "weksa.utterance_embedding_handoff.v0.1" + }, + "source": { + "type": "string" + }, + "dimensionality": { + "const": 64 + }, + "values": { + "type": "array", + "minItems": 64, + "maxItems": 64, + "items": { + "type": "number" + } + }, + "slots": { + "type": "array", + "minItems": 64, + "maxItems": 64, + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "index": { + "type": "integer", + "minimum": 0, + "maximum": 63 + }, + "name": { + "type": "string" + }, + "value": { + "type": "number" + }, + "sourcePath": { + "type": "string" + } + }, + "required": [ + "index", + "name", + "value", + "sourcePath" + ] + } + }, + "auditProjection": { + "type": "object", + "additionalProperties": false, + "properties": { + "currentStatePressure": { + "type": "array", + "items": { + "type": "string" + } + }, + "speakerTraitPressure": { + "type": "array", + "items": { + "type": "string" + } + }, + "deliveryShape": { + "type": "string" + } + }, + "required": [ + "currentStatePressure", + "speakerTraitPressure", + "deliveryShape" + ] + }, + "uncertainties": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "schemaVersion", + "compatibleHandoffSchema", + "source", + "dimensionality", + "values", + "slots", + "auditProjection", + "uncertainties" + ] + }, + "utteranceEmbeddingBasis": { + "type": "array", + "maxItems": 32, + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "kind": { + "type": "string" + }, + "path": { + "type": "string" + }, + "weight": { + "type": "number" + }, + "text": { + "type": "string" + } + }, + "required": [ + "kind", + "path", + "weight", + "text" + ] + } + }, + "contract": { + "type": "string" + } + }, + "required": [ + "schemaVersion", + "source", + "roleId", + "agentId", + "dossierProfile", + "identity", + "personalityVectors", + "values", + "currentMood", + "activation", + "characterStateVector", + "utteranceEmbeddingBasis", + "contract" + ], + "definitions": { + "personalityVectors": { + "type": "object", + "additionalProperties": false, + "properties": { + "underlyingOrganization": { + "$ref": "#/definitions/traitVectorMap" + }, + "stableDispositions": { + "$ref": "#/definitions/traitVectorMap" + }, + "behavioralDimensions": { + "$ref": "#/definitions/traitVectorMap" + }, + "presentationStrategy": { + "$ref": "#/definitions/traitVectorMap" + }, + "voiceStyle": { + "$ref": "#/definitions/traitVectorMap" + }, + "situationalState": { + "$ref": "#/definitions/traitVectorMap" + } + }, + "required": [ + "underlyingOrganization", + "stableDispositions", + "behavioralDimensions", + "presentationStrategy", + "voiceStyle", + "situationalState" + ] + }, + "traitVectorMap": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/traitVector" + } + }, + "traitVector": { + "type": "object", + "additionalProperties": false, + "properties": { + "mean": { + "type": "number" + }, + "plasticity": { + "type": "number" + }, + "current_activation": { + "type": "number" + } + }, + "required": [ + "mean", + "plasticity", + "current_activation" + ] + } + } +} diff --git a/schemas/cultnet/epiphany.character-turn-packet.schema.json b/schemas/cultnet/epiphany.character-turn-packet.schema.json index c3539326..5ee1be3c 100644 --- a/schemas/cultnet/epiphany.character-turn-packet.schema.json +++ b/schemas/cultnet/epiphany.character-turn-packet.schema.json @@ -23,6 +23,9 @@ "type": "object", "additionalProperties": true }, + "utteranceState": { + "$ref": "epiphany.agent-utterance-state.schema.json" + }, "projectedLocalContext": { "type": "object", "additionalProperties": true @@ -66,6 +69,7 @@ "source", "createdAt", "stimulus", + "utteranceState", "projectedLocalContext", "projectionSeed", "appraisalSeed", diff --git a/schemas/cultnet/index.json b/schemas/cultnet/index.json index dd833d25..b3abcb94 100644 --- a/schemas/cultnet/index.json +++ b/schemas/cultnet/index.json @@ -111,6 +111,17 @@ "title": "Epiphany Agent Memory", "path": "epiphany.agent.memory.schema.json" }, + { + "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.agent-utterance-state.schema.json", + "kind": "document_payload", + "wireContracts": [ + "cultnet.schema.v0" + ], + "schemaVersion": "epiphany.agent_utterance_state.v0", + "documentType": "epiphany.agent_utterance_state", + "title": "Epiphany Agent Utterance State", + "path": "epiphany.agent-utterance-state.schema.json" + }, { "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.agent-heartbeat.schema.json", "kind": "document_payload", diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 531b43e1..8623c8eb 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 534802b3..e219d740 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -145,7 +145,7 @@ accepted_design: - Epiphany publishes its Aquarium-facing CultNet receipts locally under `schemas/cultnet/`, and `epiphany-runtime-spine schema-catalog --include-schema-json true` emits a merged builtin-plus-local schema catalog for consumers. The local receipts cover runtime-spine documents, durable agent/heartbeat/ledger state, `epiphany.surface.*` operator projections, control intents, and receipt/artifact payloads. Vendored `cultnet-rs` is aligned to the canonical C# CultNet raw record shapes: replication uses `schemaId` plus `recordKey`, snapshot filters use `schemaIds` / `recordKeys`, and hello advertises typed mutation contracts. - Epiphany now owns the canonical schema paperwork in `schemas/`: a local mirror of `ghostlight.agent-state.schema.json`, plus human-facing receipts for canonical agent-state shape, standing role-trait glossary, heartbeat store shape, and repo-personality birth projection. Trait names like `routing_discipline` are now documented at the source instead of existing only in live dossiers, startup templates, or stale Ghostlight notes. - The dossier doctrine now distinguishes `lane_core` from `embodied_actor`. Most Epiphany sub-agents want a lean role lattice plus memory/goals/values/private-note growth, because effectiveness matters more than theatrical density. Face and Ghostlight-style characters want dense Ghostlight-family personality, relationship pressure, perceived overlays, and appraisal-shaped fallibility. The classification is now queryable through native agent-memory status and character-loop packets instead of hiding only in docs. - - Face packets now expose deterministic Ghostlight-style projection, appraisal, and reaction seeds built from local canonical traits, relationship memories, perceived overlays, and visible stimulus. This makes embodied response machinery available to the public mouth without granting omniscience or silent state mutation. Multiple Face actors remain part of the long-plan; the current singular `face` role is an MVP simplification, not the intended endpoint. + - Face packets now expose deterministic Ghostlight-style projection, appraisal, and reaction seeds built from local canonical traits, relationship pressure, perceived overlays, and visible stimulus. They also carry `epiphany.agent_utterance_state.v0`: a memory-free speech-conditioning document derived from the role dossier plus heartbeat physiology, including a 32-axis current emotional-state projection and the fixed 64-float `weksa.utterance_embedding_handoff.v0.1` character-state vector for AquaSynth/Weksa utterance embedding. This makes embodied response machinery available to the public mouth without granting omniscience, leaking memories into speech embeddings, or silently mutating state. Multiple Face actors remain part of the long-plan; the current singular `face` role is an MVP simplification, not the intended endpoint. - Repo personality initialization is now specified as a map-reduce projection, not a hand-written vibe pass: read-only scouts score body taxonomy, history temperament, and memory doctrine across nearby repos, reduce them into normalized variance criteria, and emit reviewable `repoTerrainReport`, `repoPersonalityProfile`, and `rolePersonalityProjection` candidates before touching agent memory. - Native `epiphany-repo-personality` is the first startup-personality scout and birth-only distiller packet renderer: it deterministically inventories local git repos, scores repo terrain/history/state surfaces, writes typed CultCache terrain/profile/role-projection MessagePack stores, emits JSON/Markdown inspection glass, and renders a Repo Personality Distiller specialist prompt packet for Self-reviewed first role-memory petitions. The distiller must run only when a repo/swarm has no accepted personality initialization; after that, personality drift belongs to heartbeat, mood, rumination, sleep consolidation, lived evidence, and reviewed `selfPatch`. Startup routing now checks accepted initialization records, generates missing startup-only packets only once, applies reviewed birth memory and heartbeat physiology seeds, and leaves later drift alone. Birth specialists are not heartbeat lanes; heartbeat receives only accepted seed pressure. - Repo memory initialization is a separate birth-only organ from repo personality initialization. `epiphany-repo-personality memory-packet` uses the typed terrain/profile/projection store plus bounded source excerpts from doctrine, docs, state, research, contracts, verification, runtime, and code surfaces to render a Repo Memory Distiller packet with one mission-specific brief for Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life. It petitions Self with role-specific Ghostlight-shaped memory candidates; it does not mutate memory, set objectives, copy raw dumps, or reset living memory after startup. @@ -177,7 +177,7 @@ accepted_design: - `state/ledgers.msgpack`, `epiphany-core::EpiphanyStateLedgerEntry`, the `epiphany-state-ledger-store` binary, and the native `epiphany-state` CLI now own durable branch and evidence ledgers. The old tracked JSON ledger files and the migration/projection CLI hatches are gone. - CultCache inspection, cross-language schema synchronization, and debug display tooling belong in CultLib, not in EpiphanyAgent. Epiphany should consume typed CultCache documents and expose product-specific status through its API, while general polyglot domain loading/inspection lives with the shared CultCache ecosystem. - VoidBot's current routine is reference lineage only. Epiphany's native routine pass lives in Rust as `epiphany-heartbeat-store routine`: it reads typed role dossiers, projects typed memory-resonance pair documents, maintains incubation themes, runs analytic and associative cognition lanes, writes bridge syntheses/saturation/tension, produces reviewed candidate interventions, advances typed sleep/dream-cycle state, and writes an auditable routine receipt while leaving project truth and role memory mutation on their dedicated reviewed surfaces. Qdrant-backed memory vectors remain a future enhancement; the current native pass uses bounded local resonance over typed memories. - - `epiphany-character-loop` now advertises `epiphany.cognition_lanes.v0` and `epiphany.cognition_bridge.v0` in every character-turn packet, and its projection/appraisal/reaction seeds reuse the typed heartbeat cognition documents before artifact serialization. Face and future role-local actors must run an analytic lane and an associative lane, then let the bridge choose bubble, draft, finding, silence, or bounded `selfPatch`; those lanes shape attention but do not mutate project truth. + - `epiphany-character-loop` now advertises `epiphany.cognition_lanes.v0` and `epiphany.cognition_bridge.v0` in every character-turn packet, and its projection/appraisal/reaction seeds reuse the typed heartbeat cognition documents before artifact serialization. Its utterance-state projection is the Weksa/AquaSynth speech seam: typed identity, trait vectors, values, current mood, activation, 32 named affect dimensions, and a 64-float character-state vector, with episodic/semantic/relationship memories deliberately excluded. Face and future role-local actors must run an analytic lane and an associative lane, then let the bridge choose bubble, draft, finding, silence, or bounded `selfPatch`; those lanes shape attention but do not mutate project truth. - The Rust CultCache-compatible contract now lives in dedicated upstream `https://github.com/GameCult/cultcache-rs` and is vendored as `vendor/cultcache-rs`. Epiphany should consume it as the canonical typed MessagePack persistence seam instead of growing an embedded local copy like an unsanctioned organ. - `state/face-discord.toml` and the native `epiphany-face-discord` binary are the Face Discord boundary. Face may interact only through #aquarium; missing or mismatched channel configuration produces candidate chat artifacts instead of posting elsewhere. When a Face has a configured persona name/avatar, posting uses the shared Discord webhook pipe so each Epiphany can speak with its own nickname and avatar without needing a separate bot identity. - `state/void-memory.toml` and the native `epiphany-void-memory` binary are the first Void memory bridge: Epiphany can check Void's Docker Postgres state spine, query Qdrant Discord-history and source/lore vector collections through the configured Ollama embedding model, and fetch raw archive context windows from Void's Discord archive. Raw archive rows remain evidence for Face and Eyes, not public speech.