diff --git a/epiphany-core/src/heartbeat_state.rs b/epiphany-core/src/heartbeat_state.rs index 0aed3de8..d838a284 100644 --- a/epiphany-core/src/heartbeat_state.rs +++ b/epiphany-core/src/heartbeat_state.rs @@ -1259,47 +1259,28 @@ fn trait_match_score(traits: &[PersonalityTraitProjection], needles: &[&str]) -> } } -fn apply_mood_timing_from_appraisals(state: &mut EpiphanyHeartbeatStateEntry, appraisals: &Value) { - let Some(items) = appraisals - .get("participantAppraisals") - .and_then(Value::as_array) - else { - return; - }; +fn apply_mood_timing_from_appraisals( + state: &mut EpiphanyHeartbeatStateEntry, + appraisals: &HeartbeatAgentThoughtAppraisals, +) { for participant in &mut state.participants { - let Some(appraisal) = items + let Some(appraisal) = appraisals + .participant_appraisals .iter() - .find(|item| item.get("roleId").and_then(Value::as_str) == Some(&participant.role_id)) + .find(|item| item.role_id == participant.role_id) else { continue; }; - let emotional = appraisal - .get("emotionalAppraisal") - .and_then(Value::as_object); - let urgency = emotional - .and_then(|value| value.get("urgency")) - .and_then(Value::as_f64) - .unwrap_or(0.0) - .clamp(0.0, 1.0); - let arousal = emotional - .and_then(|value| value.get("arousal")) - .and_then(Value::as_f64) - .unwrap_or(0.0) - .clamp(0.0, 1.0); - let thought_pressure = emotional - .and_then(|value| value.get("thoughtPressure")) - .and_then(Value::as_f64) - .unwrap_or(0.0) - .clamp(0.0, 1.0); - let guardedness = emotional - .and_then(|value| value.get("guardedness")) - .and_then(Value::as_f64) - .unwrap_or(0.0) + let urgency = appraisal.emotional_appraisal.urgency.clamp(0.0, 1.0); + let arousal = appraisal.emotional_appraisal.arousal.clamp(0.0, 1.0); + let thought_pressure = appraisal + .emotional_appraisal + .thought_pressure .clamp(0.0, 1.0); + let guardedness = appraisal.emotional_appraisal.guardedness.clamp(0.0, 1.0); let reaction_intensity = appraisal - .pointer("/candidateImplications/reactionIntensity") - .and_then(Value::as_f64) - .unwrap_or(0.0) + .candidate_implications + .reaction_intensity .clamp(0.0, 1.0); let anxiety = (urgency * 0.32 + arousal * 0.22 @@ -1311,10 +1292,7 @@ fn apply_mood_timing_from_appraisals(state: &mut EpiphanyHeartbeatStateEntry, ap (1.10 - urgency * 0.24 - anxiety * 0.38 - reaction_intensity * 0.12).clamp(0.55, 1.25); participant.mood_timing = Some(HeartbeatMoodTiming { schema_version: "epiphany.mood_timing.v0".to_string(), - source: appraisal - .get("appraisalId") - .and_then(Value::as_str) - .map(str::to_string), + source: Some(appraisal.appraisal_id.clone()), cooldown_multiplier: round3(multiplier), anxiety: round3(anxiety), urgency: round3(urgency), @@ -1913,7 +1891,7 @@ fn build_agent_appraisals( thought_lanes: &Value, incubation: &Value, bridge: &Value, -) -> Value { +) -> HeartbeatAgentThoughtAppraisals { let thought_tokens = cognition_tokens(thought_lanes, incubation, bridge); let thought_pressure = thought_pressure(thought_lanes, incubation); let bridge_decision = bridge @@ -1933,7 +1911,7 @@ fn build_agent_appraisals( let projection = personality_projection(profile, &thought_tokens); let alignment = projection .iter() - .filter_map(|item| item.get("projection").and_then(Value::as_f64)) + .map(|item| item.projection) .next() .unwrap_or(profile.reactivity); let arousal = round3( @@ -1951,111 +1929,99 @@ fn build_agent_appraisals( let urgency = round3((arousal * 0.65 + guardedness * 0.25 + thought_pressure * 0.1).clamp(0.0, 1.0)); let valence = round3((0.55 + curiosity * 0.2 - guardedness * 0.18).clamp(0.0, 1.0)); let label = interpretation_label(bridge_decision, arousal, guardedness, curiosity); - serde_json::json!({ - "schema_version": "epiphany.agent_thought_appraisal.v0", - "appraisalId": format!("appraisal-{}-{}", profile.role_id, stable_theme_suffix(focus)), - "reviewStatus": "generated_unreviewed", - "participantAgentId": profile.agent_id, - "roleId": profile.role_id, - "currentCharacterStateRef": format!("state/agents.msgpack#{}", profile.role_id), - "thoughtClusterRef": focus, - "participantLocalContext": { - "displayName": profile.display_name, - "values": profile.values, - "reactivity": profile.reactivity, - "plasticity": profile.plasticity, - "expressiveness": profile.expressiveness, - "guardedness": profile.guardedness, + HeartbeatAgentThoughtAppraisal { + schema_version: "epiphany.agent_thought_appraisal.v0".to_string(), + appraisal_id: format!("appraisal-{}-{}", profile.role_id, stable_theme_suffix(focus)), + review_status: "generated_unreviewed".to_string(), + participant_agent_id: profile.agent_id.clone(), + role_id: profile.role_id.clone(), + current_character_state_ref: format!("state/agents.msgpack#{}", profile.role_id), + thought_cluster_ref: focus.to_string(), + participant_local_context: HeartbeatParticipantLocalContext { + display_name: profile.display_name.clone(), + values: profile.values.clone(), + reactivity: profile.reactivity, + plasticity: profile.plasticity, + expressiveness: profile.expressiveness, + guardedness: profile.guardedness, }, - "observableThoughtSummary": strongest_thought_summary(thought_lanes, incubation), - "personalityProjection": projection, - "interpretation": format!("{} appraises {} through its current personality vector; reaction should follow this appraisal rather than a global mood knob.", profile.display_name, focus), - "emotionalAppraisal": { - "valence": valence, - "arousal": arousal, - "urgency": urgency, - "curiosity": curiosity, - "guardedness": guardedness, - "thoughtPressure": round3(thought_pressure), + observable_thought_summary: strongest_thought_summary(thought_lanes, incubation), + personality_projection: projection, + interpretation: format!("{} appraises {} through its current personality vector; reaction should follow this appraisal rather than a global mood knob.", profile.display_name, focus), + emotional_appraisal: HeartbeatEmotionalAppraisal { + valence, + arousal, + urgency, + curiosity, + guardedness, + thought_pressure: round3(thought_pressure), }, - "interpretationLabel": label, - "confidenceNotes": "Deterministic first-pass appraisal from typed role personality vectors and clustered thought state; useful as reaction guidance, not reviewed truth.", - "candidateImplications": { - "reactionMode": reaction_mode(&label, bridge_decision), - "reactionIntensity": round3((urgency * 0.55 + arousal * 0.3 + curiosity * 0.15).clamp(0.0, 1.0)), - "shouldSpeak": bridge_decision == "draft" && profile.role_id == "face" && guardedness < 0.75, - "shouldIncubate": bridge_decision != "silence" && guardedness >= 0.55, + interpretation_label: label.clone(), + confidence_notes: "Deterministic first-pass appraisal from typed role personality vectors and clustered thought state; useful as reaction guidance, not reviewed truth.".to_string(), + candidate_implications: HeartbeatCandidateImplications { + reaction_mode: reaction_mode(&label, bridge_decision).to_string(), + reaction_intensity: round3((urgency * 0.55 + arousal * 0.3 + curiosity * 0.15).clamp(0.0, 1.0)), + should_speak: bridge_decision == "draft" && profile.role_id == "face" && guardedness < 0.75, + should_incubate: bridge_decision != "silence" && guardedness >= 0.55, }, - "review": { - "acceptedForMutation": false, - "rationale": "Appraisal may steer reaction and display; state mutation still requires the explicit selfPatch or project-state review path.", + review: HeartbeatAppraisalReview { + accepted_for_mutation: false, + rationale: "Appraisal may steer reaction and display; state mutation still requires the explicit selfPatch or project-state review path.".to_string(), }, - }) + } }) .collect::>(); - serde_json::json!({ - "schema_version": "epiphany.agent_thought_appraisals.v0", - "updatedAt": now_iso(), - "thoughtClusterRef": focus, - "participantAppraisals": appraisals, - }) + HeartbeatAgentThoughtAppraisals { + schema_version: "epiphany.agent_thought_appraisals.v0".to_string(), + updated_at: now_iso(), + thought_cluster_ref: focus.to_string(), + participant_appraisals: appraisals, + } } -fn build_agent_reactions(appraisals: &Value, bridge: &Value) -> Value { +fn build_agent_reactions( + appraisals: &HeartbeatAgentThoughtAppraisals, + bridge: &Value, +) -> HeartbeatAgentReactions { let bridge_decision = bridge .pointer("/decision/speakDecision") .and_then(Value::as_str) .unwrap_or("silence"); let reactions = appraisals - .get("participantAppraisals") - .and_then(Value::as_array) - .into_iter() - .flatten() + .participant_appraisals + .iter() .map(|appraisal| { - let role_id = appraisal - .get("roleId") - .and_then(Value::as_str) - .unwrap_or("unknown"); - let arousal = appraisal - .pointer("/emotionalAppraisal/arousal") - .and_then(Value::as_f64) - .unwrap_or(0.0); - let guardedness = appraisal - .pointer("/emotionalAppraisal/guardedness") - .and_then(Value::as_f64) - .unwrap_or(0.0); - let curiosity = appraisal - .pointer("/emotionalAppraisal/curiosity") - .and_then(Value::as_f64) - .unwrap_or(0.0); - let mode = appraisal - .pointer("/candidateImplications/reactionMode") - .and_then(Value::as_str) - .unwrap_or("hold"); - let intensity = appraisal - .pointer("/candidateImplications/reactionIntensity") - .and_then(Value::as_f64) - .unwrap_or(0.0); - serde_json::json!({ - "reactionId": format!("reaction-{}-{}", role_id, now_stamp()), - "roleId": role_id, - "participantAgentId": appraisal.get("participantAgentId"), - "appraisalId": appraisal.get("appraisalId"), - "mode": mode, - "moodLabel": mood_label(arousal, guardedness, curiosity), - "intensity": round3(intensity), - "bridgeDecision": bridge_decision, - "surface": if role_id == "face" { "aquarium" } else { "internal" }, - "recommendedUse": reaction_recommended_use(role_id, mode), - }) + let role_id = appraisal.role_id.as_str(); + let arousal = appraisal.emotional_appraisal.arousal; + let guardedness = appraisal.emotional_appraisal.guardedness; + let curiosity = appraisal.emotional_appraisal.curiosity; + let mode = appraisal.candidate_implications.reaction_mode.as_str(); + let intensity = appraisal.candidate_implications.reaction_intensity; + HeartbeatAgentReaction { + reaction_id: format!("reaction-{}-{}", role_id, now_stamp()), + role_id: appraisal.role_id.clone(), + participant_agent_id: appraisal.participant_agent_id.clone(), + appraisal_id: appraisal.appraisal_id.clone(), + mode: mode.to_string(), + mood_label: mood_label(arousal, guardedness, curiosity).to_string(), + intensity: round3(intensity), + bridge_decision: bridge_decision.to_string(), + surface: if role_id == "face" { + "aquarium" + } else { + "internal" + } + .to_string(), + recommended_use: reaction_recommended_use(role_id, mode).to_string(), + } }) .collect::>(); - serde_json::json!({ - "schema_version": "epiphany.agent_reactions.v0", - "updatedAt": now_iso(), - "reactions": reactions, - "contract": "Reaction is appraisal output. It may pace, color, draft, or display behavior; it does not mutate state without review.", - }) + HeartbeatAgentReactions { + schema_version: "epiphany.agent_reactions.v0".to_string(), + updated_at: now_iso(), + reactions, + contract: "Reaction is appraisal output. It may pace, color, draft, or display behavior; it does not mutate state without review.".to_string(), + } } fn cognition_tokens(thought_lanes: &Value, incubation: &Value, bridge: &Value) -> BTreeSet { @@ -2105,7 +2071,7 @@ fn max_number_at(value: &Value, pointer: &str, key: &str) -> f64 { fn personality_projection( profile: &RoleAppraisalProfile, thought_tokens: &BTreeSet, -) -> Vec { +) -> Vec { let mut scored = profile .traits .iter() @@ -2113,22 +2079,17 @@ fn personality_projection( let trait_tokens = summary_tokens(&format!("{} {}", item.group, item.name)); let overlap = token_overlap(&trait_tokens, thought_tokens); let projection = round3((item.weight * (0.55 + overlap * 1.8)).clamp(0.0, 1.0)); - serde_json::json!({ - "group": item.group, - "name": item.name, - "activation": round3(item.activation), - "plasticity": round3(item.plasticity), - "tokenOverlap": round3(overlap), - "projection": projection, - }) + HeartbeatPersonalityProjection { + group: item.group.clone(), + name: item.name.clone(), + activation: round3(item.activation), + plasticity: round3(item.plasticity), + token_overlap: round3(overlap), + projection, + } }) .collect::>(); - scored.sort_by(|left, right| { - right["projection"] - .as_f64() - .unwrap_or_default() - .total_cmp(&left["projection"].as_f64().unwrap_or_default()) - }); + scored.sort_by(|left, right| right.projection.total_cmp(&left.projection)); scored.truncate(6); scored } diff --git a/epiphany-core/src/heartbeat_state/heartbeat_documents.rs b/epiphany-core/src/heartbeat_state/heartbeat_documents.rs index b0bfadea..07183ead 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_documents.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_documents.rs @@ -69,9 +69,9 @@ pub struct EpiphanyHeartbeatCognitionEntry { #[cultcache(key = 10, default)] pub candidate_interventions: Option, #[cultcache(key = 11, default)] - pub appraisals: Option, + pub appraisals: Option, #[cultcache(key = 12, default)] - pub reactions: Option, + pub reactions: Option, #[cultcache(key = 13, default)] pub extra: BTreeMap, } @@ -116,6 +116,112 @@ pub(super) struct LegacyHeartbeatStateWithCognition { pub(super) extra: BTreeMap, } +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatAgentThoughtAppraisals { + #[serde(rename = "schema_version")] + pub schema_version: String, + pub updated_at: String, + pub thought_cluster_ref: String, + pub participant_appraisals: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatAgentThoughtAppraisal { + #[serde(rename = "schema_version")] + pub schema_version: String, + pub appraisal_id: String, + pub review_status: String, + pub participant_agent_id: String, + pub role_id: String, + pub current_character_state_ref: String, + pub thought_cluster_ref: String, + pub participant_local_context: HeartbeatParticipantLocalContext, + pub observable_thought_summary: String, + pub personality_projection: Vec, + pub interpretation: String, + pub emotional_appraisal: HeartbeatEmotionalAppraisal, + pub interpretation_label: String, + pub confidence_notes: String, + pub candidate_implications: HeartbeatCandidateImplications, + pub review: HeartbeatAppraisalReview, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatParticipantLocalContext { + pub display_name: String, + pub values: Vec, + pub reactivity: f64, + pub plasticity: f64, + pub expressiveness: f64, + pub guardedness: f64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatPersonalityProjection { + pub group: String, + pub name: String, + pub activation: f64, + pub plasticity: f64, + pub token_overlap: f64, + pub projection: f64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatEmotionalAppraisal { + pub valence: f64, + pub arousal: f64, + pub urgency: f64, + pub curiosity: f64, + pub guardedness: f64, + pub thought_pressure: f64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatCandidateImplications { + pub reaction_mode: String, + pub reaction_intensity: f64, + pub should_speak: bool, + pub should_incubate: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatAppraisalReview { + pub accepted_for_mutation: bool, + pub rationale: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatAgentReactions { + #[serde(rename = "schema_version")] + pub schema_version: String, + pub updated_at: String, + pub reactions: Vec, + pub contract: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeartbeatAgentReaction { + pub reaction_id: String, + pub role_id: String, + pub participant_agent_id: String, + pub appraisal_id: String, + pub mode: String, + pub mood_label: String, + pub intensity: f64, + pub bridge_decision: String, + pub surface: String, + pub recommended_use: String, +} + #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct HeartbeatSelectionPolicy { pub mode: String, diff --git a/epiphany-core/src/heartbeat_state/heartbeat_projection.rs b/epiphany-core/src/heartbeat_state/heartbeat_projection.rs index 31b4138d..612333d4 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_projection.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_projection.rs @@ -84,8 +84,8 @@ pub fn heartbeat_status_projection( "thoughtLanes": cognition.as_ref().and_then(|entry| entry.thought_lanes.clone()), "bridge": cognition.as_ref().and_then(|entry| entry.bridge.clone()), "candidateInterventions": cognition.as_ref().and_then(|entry| entry.candidate_interventions.clone()), - "appraisals": cognition.as_ref().and_then(|entry| entry.appraisals.clone()), - "reactions": cognition.as_ref().and_then(|entry| entry.reactions.clone()), + "appraisals": cognition.as_ref().and_then(|entry| entry.appraisals.as_ref()).and_then(typed_json), + "reactions": cognition.as_ref().and_then(|entry| entry.reactions.as_ref()).and_then(typed_json), "adaptivePacing": adaptive_pacing, "availableActions": ["init", "tick", "pump", "complete", "status", "routine"], })) @@ -202,6 +202,10 @@ fn heartbeat_cognition_status_json(cognition: &super::EpiphanyHeartbeatCognition }) } +fn typed_json(value: &T) -> Option { + serde_json::to_value(value).ok() +} + fn participant_status_json(participant: &HeartbeatParticipant) -> Value { let personality_timing = participant .personality_timing diff --git a/epiphany-core/src/heartbeat_state/heartbeat_store.rs b/epiphany-core/src/heartbeat_state/heartbeat_store.rs index d451e7ce..67ae8d3c 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_store.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_store.rs @@ -132,8 +132,12 @@ fn legacy_heartbeat_cognition_entry( thought_lanes: legacy.thought_lanes, bridge: legacy.bridge, candidate_interventions: legacy.candidate_interventions, - appraisals: legacy.appraisals, - reactions: legacy.reactions, + appraisals: legacy + .appraisals + .and_then(|value| serde_json::from_value(value).ok()), + reactions: legacy + .reactions + .and_then(|value| serde_json::from_value(value).ok()), extra: BTreeMap::new(), })) } diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 7ee1190a..cd22ad06 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -67,6 +67,7 @@ remembers doctrine; the branch remembers the blade. - Epiphany prompt-state boundary tags now live in `epiphany-state-model` and are re-exported through `codex-protocol`; Codex compatibility may wrap the prompt fragment, but it no longer owns those marker constants. - Heartbeat adaptive pacing now lives as typed CultCache state on `EpiphanyHeartbeatStateEntry` instead of being written into `state.extra["adaptivePacing"]` as JSON. Status projection still emits JSON and reads the old extra pocket as a legacy fallback. - Heartbeat participant scene id, personality timing, mood timing, and pending-turn cooldown multipliers now live as typed fields instead of durable `participant.extra` / `pendingTurn.extra` JSON pockets. Scheduler pacing and status projection read the typed fields first and keep legacy extra fallbacks only as sealed compatibility scars. +- Heartbeat cognition appraisals and reactions now live as typed CultCache fields instead of `Option` blobs. The mood-timing scheduler consumes typed appraisals directly; legacy cognition migration parses old appraisal/reaction JSON only when loading prior stores. - Heartbeat durable document/schema types now live in `epiphany-core/src/heartbeat_state/heartbeat_documents.rs`, role/default construction lives in `epiphany-core/src/heartbeat_state/heartbeat_roles.rs`, persistence/validation lives in `epiphany-core/src/heartbeat_state/heartbeat_store.rs`, and status/artifact JSON projection lives in `epiphany-core/src/heartbeat_state/heartbeat_projection.rs`. The root `heartbeat_state.rs` keeps scheduling and Void cognition orchestration for the next cuts. Focused heartbeat tests and `epiphany-core` check pass after the splits. - Heartbeat role/default and store seams now have module-local unit tests: fixed lane catalog, Ghostlight scene role projection, and typed state/cognition CultCache round-trip. Keep future heartbeat cuts aligned to those seam tests instead of growing root integration-only coverage. - Heartbeat adaptive pacing now lives in `epiphany-core/src/heartbeat_state/heartbeat_pacing.rs`, including running-turn count and effective cooldown multipliers. It has a module-local unit test for pending-turn counting; root scheduling calls the pacing seam instead of owning pressure/concurrency math directly. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 0423ddc9..3d7bb639 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index afa3ff85..aecf1b02 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -50,6 +50,9 @@ objective: pending-turn cooldown multipliers are typed fields with legacy `extra` read fallbacks; scheduler pacing no longer depends on those values as durable JSON pockets. + Heartbeat cognition appraisals and reactions are typed CultCache fields; + legacy cognition blobs are parsed only while migrating old stores, and + status/artifact JSON is projection output. constraints: - No frontier-scale training tithe.