From ca05684412e273d1af448f5179a63859aacd3906 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 23 Aug 2026 05:34:57 +0200 Subject: [PATCH] Split Persona social authority from heartbeat --- .../src/bin/epiphany-heartbeat-store.rs | 31 - epiphany-core/src/bin/epiphany-swarm.rs | 20 +- epiphany-core/src/heartbeat_state.rs | 685 +------------ .../heartbeat_state/heartbeat_documents.rs | 189 ---- .../src/heartbeat_state/heartbeat_roles.rs | 15 +- .../src/heartbeat_state/heartbeat_store.rs | 164 --- epiphany-core/src/lib.rs | 24 +- epiphany-core/src/persona_conversation.rs | 319 +++--- .../src/persona_feedback_admission.rs | 182 ++-- epiphany-core/src/persona_social_state.rs | 966 ++++++++++++++++++ epiphany-core/src/persona_turn.rs | 10 +- epiphany-core/src/resident_self.rs | 3 +- .../src/bin/epiphany-persona-service.rs | 69 +- notes/epiphany-current-algorithmic-map.md | 25 +- notes/fresh-workspace-handoff.md | 26 +- .../epiphany.agent-heartbeat.schema.json | 2 +- schemas/heartbeat-state-schema.md | 20 +- state/ledgers.msgpack | Bin 654488 -> 655046 bytes state/map.yaml | 5 +- 19 files changed, 1357 insertions(+), 1398 deletions(-) create mode 100644 epiphany-core/src/persona_social_state.rs diff --git a/epiphany-core/src/bin/epiphany-heartbeat-store.rs b/epiphany-core/src/bin/epiphany-heartbeat-store.rs index 4aeeef62..59af1bab 100644 --- a/epiphany-core/src/bin/epiphany-heartbeat-store.rs +++ b/epiphany-core/src/bin/epiphany-heartbeat-store.rs @@ -9,7 +9,6 @@ use epiphany_core::heartbeat_status_projection; use epiphany_core::initialize_heartbeat_store; use epiphany_core::load_epiphany_cultmesh_swarm_brake; use epiphany_core::load_heartbeat_state_entry; -use epiphany_core::pulse_persona_heartbeat; use epiphany_core::pulse_resident_self_heartbeat; use epiphany_core::recover_stale_heartbeat_store; use epiphany_core::resident_cognitive_runtime_id; @@ -349,36 +348,6 @@ fn main() -> Result<()> { wait_for_shutdown(&shutdown_requested, Duration::from_secs(interval_seconds)); continue; } - let persona_pulse = pulse_persona_heartbeat( - &store_path, - &iteration_dir, - &format!("{schedule_id}.persona-{iteration:06}"), - &source_scene_ref, - false, - )?; - if persona_pulse["status"] != "idle" { - completed_iterations = iteration; - let retention = retain_heartbeat_pulse_artifacts( - &store_path, - &artifact_dir, - retain_pulse_artifacts, - retention_batch_size, - &chrono::Utc::now().to_rfc3339(), - )?; - println!( - "{}", - serde_json::json!({ - "pulse": persona_pulse, - "retention": retention.as_ref().map(retention_receipt_projection), - "privateStateExposed": false - }) - ); - if max_iterations > 0 && completed_iterations >= max_iterations { - break; - } - wait_for_shutdown(&shutdown_requested, Duration::from_secs(interval_seconds)); - continue; - } completed_iterations = iteration; let retention = retain_heartbeat_pulse_artifacts( &store_path, diff --git a/epiphany-core/src/bin/epiphany-swarm.rs b/epiphany-core/src/bin/epiphany-swarm.rs index ce2a2d3f..913fbb6f 100644 --- a/epiphany-core/src/bin/epiphany-swarm.rs +++ b/epiphany-core/src/bin/epiphany-swarm.rs @@ -5,15 +5,15 @@ use epiphany_core::{ ProcessInstanceObservation, ResidentProviderReadiness, ResidentReadinessRequest, ResidentSelfOutcome, ResidentSelfPolicy, ResidentSelfPorts, ResidentSelfPressure, ResidentSelfState, acknowledge_resident_self_launch, acquire_resident_process_singleton, - authenticate_resident_self_policy, bind_runtime_repository_domain, - bridge_admitted_persona_feedback_to_heartbeat, capture_process_instance, - coordinator_run_receipts, derive_resident_cognition_readiness, - enqueue_resident_self_pressure_idempotent, import_bifrost_persona_feedback_deliveries, - ingest_resident_self_current_work_pressure, live_resident_self_typed_request_ids, - load_epiphany_cultmesh_swarm_brake, load_resident_self_state, - materialize_resident_self_domain_obligations, observe_process_instance, - pending_resident_self_acks, prepare_resident_self_launch, publish_resident_provider_readiness, - reap_exited_child_process, recover_dead_runtime_worker_attempts, resident_cognitive_runtime_id, + admit_persona_feedback_to_social, authenticate_resident_self_policy, + bind_runtime_repository_domain, capture_process_instance, coordinator_run_receipts, + derive_resident_cognition_readiness, enqueue_resident_self_pressure_idempotent, + import_bifrost_persona_feedback_deliveries, ingest_resident_self_current_work_pressure, + live_resident_self_typed_request_ids, load_epiphany_cultmesh_swarm_brake, + load_resident_self_state, materialize_resident_self_domain_obligations, + observe_process_instance, pending_resident_self_acks, prepare_resident_self_launch, + publish_resident_provider_readiness, reap_exited_child_process, + recover_dead_runtime_worker_attempts, resident_cognitive_runtime_id, resident_prepared_launch_thread_id, resident_self_child_claim, resident_self_local_provider_status, retain_completed_runtime_sessions, retain_coordinator_run_receipts, retain_failed_runtime_worker_attempts, @@ -317,7 +317,7 @@ fn cycle( &args.feedback_target_repository, &args.feedback_target_persona, )?; - bridge_admitted_persona_feedback_to_heartbeat( + admit_persona_feedback_to_social( &args.persona_feedback_store, &args.heartbeat_store, &cognitive_runtime_id, diff --git a/epiphany-core/src/heartbeat_state.rs b/epiphany-core/src/heartbeat_state.rs index ab5cf4ba..e418feea 100644 --- a/epiphany-core/src/heartbeat_state.rs +++ b/epiphany-core/src/heartbeat_state.rs @@ -4,8 +4,6 @@ use anyhow::anyhow; use chrono::DateTime; use chrono::Utc; use serde_json::Value; -use sha2::Digest; -use std::collections::BTreeSet; use std::fs; use std::path::Path; @@ -154,80 +152,6 @@ fn tick_heartbeat_store( })) } -pub fn pulse_persona_heartbeat( - store_path: impl AsRef, - artifact_dir: impl AsRef, - schedule_id: &str, - source_scene_ref: &str, - brake_engaged: bool, -) -> Result { - let store_path = store_path.as_ref(); - let artifact_dir = artifact_dir.as_ref(); - if brake_engaged { - return Ok(serde_json::json!({ - "schemaVersion": "epiphany.persona_heartbeat_pulse.v0", - "status": "refused-by-swarm-brake", - "privateStateExposed": false, - })); - } - let state = load_heartbeat_state_entry(store_path)? - .ok_or_else(|| anyhow!("heartbeat state is missing"))?; - let has_mentions = state - .pending_mentions - .iter() - .any(|mention| mention.target_role_id == "Persona"); - if !has_mentions { - return Ok(serde_json::json!({ - "schemaVersion": "epiphany.persona_heartbeat_pulse.v0", - "status": "idle", - "privateStateExposed": false, - })); - } - let persona_running = state - .participants - .iter() - .find(|participant| participant.role_id == "Persona") - .and_then(|participant| participant.pending_turn.as_ref()) - .is_some(); - let request_running = state - .persona_turn_requests - .iter() - .any(|request| request.status == "reserved"); - if persona_running || request_running { - return Ok(serde_json::json!({ - "schemaVersion": "epiphany.persona_heartbeat_pulse.v0", - "status": "already-running", - "privateStateExposed": false, - })); - } - let tick = tick_heartbeat_store( - store_path, - artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: state.target_heartbeat_rate, - schedule_id: schedule_id.to_string(), - source_scene_ref: source_scene_ref.to_string(), - resident_self_store: None, - }, - )?; - let request_id = load_heartbeat_state_entry(store_path)? - .and_then(|state| { - state - .persona_turn_requests - .into_iter() - .find(|request| request.schedule_id == schedule_id) - .map(|request| request.request_id) - }) - .ok_or_else(|| anyhow!("Persona heartbeat pulse did not persist its turn request"))?; - Ok(serde_json::json!({ - "schemaVersion": "epiphany.persona_heartbeat_pulse.v0", - "status": "reserved", - "requestId": request_id, - "schedule": tick["schedule"], - "privateStateExposed": false, - })) -} - pub fn reconcile_resident_self_heartbeat_ack( heartbeat_store: impl AsRef, resident_store: impl AsRef, @@ -398,96 +322,6 @@ pub fn pulse_resident_self_heartbeat( }) } -pub fn queue_heartbeat_pending_mention_store( - store_path: impl AsRef, - options: HeartbeatQueueMentionOptions, -) -> Result { - let store_path = store_path.as_ref(); - let mut state = load_heartbeat_state_entry(store_path)?.unwrap_or_else(|| { - let mut state = default_heartbeat_state(1.0); - patch_missing_participants(&mut state); - state - }); - patch_missing_participants(&mut state); - let participant_index = participant_index_by_role(&state, &options.target_role_id)?; - let participant = &state.participants[participant_index]; - validate_mention_text("content", &options.content, 4, 1200)?; - validate_mention_text("visible_prompt", &options.visible_prompt, 4, 1200)?; - for (label, value) in [ - ("source_surface", &options.source_surface), - ("channel_id", &options.channel_id), - ("message_id", &options.message_id), - ("author_id", &options.author_id), - ("source_visibility", &options.source_visibility), - ("data_classification", &options.data_classification), - ("model_provider_id", &options.model_provider_id), - ] { - validate_mention_text(label, value, 1, 240)?; - } - if !options.model_provider_disclosure_allowed { - return Err(anyhow!( - "pending mention is not authorized for disclosure to the configured model provider" - )); - } - let queued_at = options.queued_at.clone().unwrap_or_else(now_iso); - let mention_id = options.mention_id.clone().unwrap_or_else(|| { - stable_pending_mention_id( - &options.target_role_id, - &options.channel_id, - &options.message_id, - &options.visible_prompt, - ) - }); - if state - .pending_mentions - .iter() - .any(|mention| mention.id == mention_id) - { - return Ok(serde_json::json!({ - "ok": true, - "queued": false, - "reason": "duplicate-pending-mention", - "mentionId": mention_id, - "pendingMentionCount": state.pending_mentions.len(), - })); - } - state.pending_mentions.push(HeartbeatPendingMention { - id: mention_id.clone(), - target_role_id: options.target_role_id.clone(), - target_agent_id: participant.agent_id.clone(), - source_surface: options.source_surface, - channel_id: options.channel_id, - message_id: options.message_id, - author_id: options.author_id, - author_name: options.author_name, - content: options.content, - visible_prompt: options.visible_prompt, - reply_to_message_id: options.reply_to_message_id, - queued_at, - source_visibility: options.source_visibility, - data_classification: options.data_classification, - model_provider_id: options.model_provider_id, - model_provider_disclosure_allowed: options.model_provider_disclosure_allowed, - }); - state.pending_mentions.sort_by(|left, right| { - left.queued_at - .cmp(&right.queued_at) - .then_with(|| left.id.cmp(&right.id)) - }); - state.participants[participant_index].next_ready_at = state.participants[participant_index] - .next_ready_at - .min(state.scene_clock); - write_heartbeat_state_entry(store_path, &state)?; - Ok(serde_json::json!({ - "ok": true, - "queued": true, - "mentionId": mention_id, - "targetRoleId": options.target_role_id, - "pendingMentionCount": state.pending_mentions.len(), - "contract": "Pending Persona mentions live in heartbeat physiology. They pull the Persona turn forward, but the Persona still writes naturally and the Interpreter owns side effects.", - })) -} - pub fn recover_stale_heartbeat_store( store_path: impl AsRef, artifact_dir: impl AsRef, @@ -524,44 +358,6 @@ pub fn recover_stale_heartbeat_store( if stale_age_seconds < options.max_age_seconds { continue; } - if pending.action_type == "persona_turn" - && let Some(request) = state.persona_turn_requests.iter_mut().find(|request| { - request.status == "reserved" - && request.schedule_id == pending.schedule_id - && request.action_id == pending.action_id - }) - { - let mention_ids = request - .mentions - .iter() - .map(|mention| mention.id.clone()) - .collect(); - let mention_cargo_sha256 = format!( - "sha256-{:x}", - sha2::Sha256::digest(rmp_serde::to_vec(&request.mentions)?) - ); - request.status = "terminal".to_string(); - request.terminal_receipt = Some(PersonaTurnTerminalReceipt { - schema_version: PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: format!("{}:terminal", request.request_id), - request_id: request.request_id.clone(), - schedule_id: request.schedule_id.clone(), - action_id: request.action_id.clone(), - outcome: "failed".to_string(), - mention_disposition: "retained".to_string(), - mention_ids, - mention_cargo_sha256, - delivery_evidence_id: None, - crossing_receipt_id: None, - bridge_receipt_sha256: None, - blocked_crossing_status: None, - blocked_reason: None, - completed_at: repaired_at.clone(), - private_state_exposed: false, - }); - request.mentions.clear(); - request.semantic_memory_recall = Value::Null; - } participant.pending_turn = None; participant.current_load = 0.0; participant.next_ready_at = round6(state.scene_clock.max(pending.started_scene_clock)); @@ -697,16 +493,6 @@ fn tick_once( state.participants[selected_index].current_load = round6((state.participants[selected_index].current_load * 0.75).clamp(0.0, 1.0)); state.scene_clock = round6(scene_clock); - let selected_pending_mentions = pending_mentions_for_role(state, &selected.role_id); - if action.action_type == "persona_turn" { - reserve_persona_turn_request( - state, - &pending, - &selected_after_identity(&selected), - selected_pending_mentions.clone(), - Value::Null, - )?; - } let selected_after = state.participants[selected_index].clone(); let event = HeartbeatHistoryEvent { ts: now_iso(), @@ -748,7 +534,6 @@ fn tick_once( "interruptibility": action.interruptibility, "commitment": action.commitment, "local_affordance_basis": action.local_affordance_basis, - "pending_mentions": selected_pending_mentions, }], "reaction_windows": if work_role.is_some() { serde_json::json!([{ @@ -773,9 +558,8 @@ fn tick_once( "override_reason": null, "readiness_snapshot": readiness_snapshot, }, - "pending_mentions": state.pending_mentions.clone(), "review_notes": [ - "Epiphany heartbeat records coordinator and Persona scheduling receipts.", + "Epiphany heartbeat records Resident Self scheduling receipts.", "A selected idle lane records scheduling opportunity; it does not invent project work or mutate durable memory.", "When no coordinator work is active, cooldown and sleep pacing keep the swarm from thrashing." ], @@ -786,231 +570,6 @@ fn tick_once( })) } -fn selected_after_identity(selected: &HeartbeatParticipant) -> (String, String) { - (selected.role_id.clone(), selected.agent_id.clone()) -} - -fn reserve_persona_turn_request( - state: &mut EpiphanyHeartbeatStateEntry, - pending: &HeartbeatPendingTurn, - identity: &(String, String), - mentions: Vec, - semantic_memory_recall: Value, -) -> Result<()> { - let request_id = format!("persona-turn:{}:{}", pending.schedule_id, pending.action_id); - let request = PersonaTurnRequest { - schema_version: PERSONA_TURN_REQUEST_SCHEMA_VERSION.to_string(), - request_id: request_id.clone(), - schedule_id: pending.schedule_id.clone(), - action_id: pending.action_id.clone(), - role_id: identity.0.clone(), - agent_id: identity.1.clone(), - status: "reserved".to_string(), - reserved_at: pending.started_at.clone(), - mentions, - semantic_memory_recall, - terminal_receipt: None, - private_state_exposed: false, - }; - if let Some(head) = &state.persona_conversation_retention_head { - let frontier = chrono::DateTime::parse_from_rfc3339(&head.through_reserved_at) - .map_err(|_| anyhow!("Persona conversation retention frontier is invalid"))?; - let reserved = chrono::DateTime::parse_from_rfc3339(&request.reserved_at) - .map_err(|_| anyhow!("Persona turn reservation time is invalid"))?; - if reserved <= frontier { - return Err(anyhow!( - "Persona turn reservation is at or behind the retired replay frontier" - )); - } - } - if let Some(existing) = state - .persona_turn_requests - .iter() - .find(|existing| existing.request_id == request_id) - { - if existing != &request { - return Err(anyhow!("conflicting Persona turn request {request_id:?}")); - } - return Ok(()); - } - state.persona_turn_requests.push(request); - Ok(()) -} - -pub fn complete_persona_turn_request_store( - store_path: impl AsRef, - options: PersonaTurnTerminalOptions, -) -> Result { - let mention_disposition = match options.outcome.as_str() { - "delivered" | "silence" | "dropped" => "consumed", - "failed" => "retained", - "blocked" => "quarantined", - other => { - return Err(anyhow!( - "unsupported Persona turn terminal outcome {other:?}" - )); - } - }; - let store_path = store_path.as_ref(); - let (loaded, expected) = load_heartbeat_state_transaction(store_path)?; - let mut state = loaded.ok_or_else(|| anyhow!("heartbeat state is missing"))?; - let request_index = state - .persona_turn_requests - .iter() - .position(|request| request.request_id == options.request_id) - .ok_or_else(|| anyhow!("Persona turn request {:?} is missing", options.request_id))?; - if let Some(receipt) = &state.persona_turn_requests[request_index].terminal_receipt { - if receipt.outcome == options.outcome { - return Ok(receipt.clone()); - } - return Err(anyhow!( - "Persona turn request {:?} already terminated as {:?}", - options.request_id, - receipt.outcome - )); - } - let request = state.persona_turn_requests[request_index].clone(); - let delivery_evidence = options.delivery_evidence.as_ref(); - let blocked_evidence = options.blocked_evidence.as_ref(); - if options.outcome == "delivered" { - let evidence = delivery_evidence.ok_or_else(|| { - anyhow!("delivered Persona turn requires typed Discord delivery evidence") - })?; - if evidence.schema_version != crate::PERSONA_DISCORD_DELIVERY_EVIDENCE_SCHEMA_VERSION - || evidence.private_state_exposed - || evidence.evidence_id.trim().is_empty() - || evidence.message_id.trim().is_empty() - || evidence.crossing_receipt_id.trim().is_empty() - || evidence.bridge_receipt_sha256.trim().is_empty() - || !request - .mentions - .iter() - .any(|mention| mention.channel_id == evidence.channel_id) - { - return Err(anyhow!( - "Discord delivery evidence is not bound to the Persona turn" - )); - } - } else if delivery_evidence.is_some() { - return Err(anyhow!( - "non-delivered Persona terminal outcome must not carry delivery evidence" - )); - } - if options.outcome == "blocked" { - let evidence = blocked_evidence - .ok_or_else(|| anyhow!("blocked Persona turn requires typed crossing evidence"))?; - if !matches!( - evidence.evidence_source.as_str(), - "bifrost_crossing" | "local_effect" - ) || !matches!(evidence.crossing_status.as_str(), "unknown" | "failed") - || (evidence.evidence_source == "local_effect" - && (evidence.crossing_receipt_id.is_some() - || evidence.bridge_receipt_sha256.is_some())) - || evidence.reason.trim().is_empty() - || evidence - .crossing_receipt_id - .as_deref() - .is_some_and(|value| value.trim().is_empty()) - || evidence - .bridge_receipt_sha256 - .as_deref() - .is_some_and(|value| { - !value.strip_prefix("sha256:").is_some_and(|digest| { - digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) - }) - { - return Err(anyhow!("blocked Persona crossing evidence is invalid")); - } - } else if blocked_evidence.is_some() { - return Err(anyhow!( - "non-blocked Persona terminal outcome must not carry blocked evidence" - )); - } - let participant_index = participant_index_by_role(&state, &request.role_id)?; - let pending = state.participants[participant_index] - .pending_turn - .as_ref() - .ok_or_else(|| anyhow!("Persona has no running heartbeat turn"))?; - if pending.schedule_id != request.schedule_id || pending.action_id != request.action_id { - return Err(anyhow!( - "Persona running turn does not match reserved request" - )); - } - if mention_disposition != "retained" { - let ids = request - .mentions - .iter() - .map(|mention| mention.id.as_str()) - .collect::>(); - state - .pending_mentions - .retain(|mention| !ids.contains(mention.id.as_str())); - } - complete_pending_turn(&mut state, participant_index)?; - let receipt = PersonaTurnTerminalReceipt { - schema_version: PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: format!("{}:terminal", request.request_id), - request_id: request.request_id.clone(), - schedule_id: request.schedule_id.clone(), - action_id: request.action_id.clone(), - outcome: options.outcome, - mention_disposition: mention_disposition.to_string(), - mention_ids: request - .mentions - .iter() - .map(|mention| mention.id.clone()) - .collect(), - mention_cargo_sha256: format!( - "sha256-{:x}", - sha2::Sha256::digest(rmp_serde::to_vec(&request.mentions)?) - ), - delivery_evidence_id: delivery_evidence.map(|evidence| evidence.evidence_id.clone()), - crossing_receipt_id: delivery_evidence.map(|evidence| evidence.crossing_receipt_id.clone()), - bridge_receipt_sha256: delivery_evidence - .map(|evidence| evidence.bridge_receipt_sha256.clone()), - blocked_crossing_status: blocked_evidence.map(|evidence| evidence.crossing_status.clone()), - blocked_reason: blocked_evidence.map(|evidence| evidence.reason.clone()), - completed_at: now_iso(), - private_state_exposed: false, - }; - if mention_disposition == "quarantined" { - let evidence = blocked_evidence.expect("validated blocked evidence"); - let quarantine = PersonaBlockedConversationPressure { - schema_version: "epiphany.persona_blocked_conversation_pressure.v0".to_string(), - quarantine_id: format!("{}:quarantine", request.request_id), - request_id: request.request_id.clone(), - terminal_receipt_id: receipt.receipt_id.clone(), - crossing_status: evidence.crossing_status.clone(), - evidence_source: evidence.evidence_source.clone(), - reason: evidence.reason.clone(), - mentions: request.mentions.clone(), - mention_cargo_sha256: receipt.mention_cargo_sha256.clone(), - crossing_receipt_id: evidence.crossing_receipt_id.clone(), - bridge_receipt_sha256: evidence.bridge_receipt_sha256.clone(), - quarantined_at: receipt.completed_at.clone(), - private_state_exposed: false, - }; - if let Some(existing) = state - .blocked_persona_pressures - .iter() - .find(|existing| existing.quarantine_id == quarantine.quarantine_id) - { - if existing != &quarantine { - return Err(anyhow!("Persona blocked pressure identity collision")); - } - } else { - state.blocked_persona_pressures.push(quarantine); - } - } - state.persona_turn_requests[request_index].status = "terminal".to_string(); - state.persona_turn_requests[request_index].terminal_receipt = Some(receipt.clone()); - state.persona_turn_requests[request_index].mentions.clear(); - state.persona_turn_requests[request_index].semantic_memory_recall = Value::Null; - commit_heartbeat_state_transaction(store_path, expected, &state)?; - Ok(receipt) -} - fn complete_pending_turn( state: &mut EpiphanyHeartbeatStateEntry, participant_index: usize, @@ -1095,17 +654,6 @@ fn select_participant( )); } } - if let Some(index) = active.iter().copied().find(|index| { - let participant = &state.participants[*index]; - participant.role_id == "Persona" - && !pending_mentions_for_role(state, &participant.role_id).is_empty() - }) { - return Ok(( - index, - "reaction_interrupt", - "Pending addressed Persona mention pulled Persona forward; Projector and Interpreter remain the side-effect boundaries.".to_string(), - )); - } let selected = active .into_iter() .min_by(|left, right| { @@ -1137,29 +685,6 @@ fn action_for_selection( target_heartbeat_rate: f64, ) -> HeartbeatAction { let minimum_rate = state.pacing_policy.minimum_effective_rate.max(0.001); - let pending_mentions = pending_mentions_for_role(state, &selected.role_id); - if !pending_mentions.is_empty() && selected.role_id == "Persona" { - let heartbeat_rate = target_heartbeat_rate.max(minimum_rate); - return HeartbeatAction { - action_id: "heartbeat.Persona.turn".to_string(), - action_type: "persona_turn", - action_scale: "standard", - base_recovery: state.pacing_policy.work_base_recovery / heartbeat_rate, - initiative_cost: 4.0, - interruptibility: 0.35, - commitment: 0.7, - local_affordance_basis: vec![ - format!( - "Wake {} for {} pending addressed mention(s).", - selected.display_name, - pending_mentions.len() - ), - "Projector owns state-to-narrative prompting before Persona sees context.".to_string(), - "Persona writes natural narrative thought; Interpreter owns memory, draft, SAY, route, or drop side effects.".to_string(), - "Pending mentions are consumed only after this Persona turn is queued.".to_string(), - ], - }; - } if Some(selected.role_id.as_str()) == work_role { let heartbeat_rate = target_heartbeat_rate.max(minimum_rate); let action_id = format!("heartbeat.{}.work", selected.role_id); @@ -1203,42 +728,6 @@ fn action_for_selection( } } -fn pending_mentions_for_role( - state: &EpiphanyHeartbeatStateEntry, - role_id: &str, -) -> Vec { - state - .pending_mentions - .iter() - .filter(|mention| mention.target_role_id == role_id) - .filter(|mention| mention.model_provider_disclosure_allowed) - .cloned() - .collect() -} - -fn validate_mention_text(label: &str, value: &str, min_len: usize, max_len: usize) -> Result<()> { - let trimmed = value.trim(); - if trimmed.len() < min_len || value.len() > max_len { - return Err(anyhow!( - "pending mention {label} must be between {min_len} and {max_len} UTF-8 bytes" - )); - } - Ok(()) -} - -fn stable_pending_mention_id( - role_id: &str, - channel_id: &str, - message_id: &str, - visible_prompt: &str, -) -> String { - let mut hash = 5381_u64; - for byte in format!("{role_id}\0{channel_id}\0{message_id}\0{visible_prompt}").as_bytes() { - hash = ((hash << 5).wrapping_add(hash)).wrapping_add(*byte as u64); - } - format!("mention-{hash:016x}") -} - fn patch_missing_participants(state: &mut EpiphanyHeartbeatStateEntry) { let present: Vec = state .participants @@ -1365,6 +854,7 @@ pub(super) fn round6(value: f64) -> f64 { #[cfg(test)] mod tests { use super::*; + use crate::{PersonaTurnBlockedEvidence, PersonaTurnTerminalOptions}; use pretty_assertions::assert_eq; #[test] @@ -1500,11 +990,10 @@ mod tests { fn pending_persona_mention_is_reserved_until_terminal_delivery() -> Result<()> { let temp = tempfile::tempdir()?; let store_path = temp.path().join("Persona-heartbeats.msgpack"); - let artifact_dir = temp.path().join("artifacts"); initialize_heartbeat_store(&store_path, 1.0)?; - let queued = queue_heartbeat_pending_mention_store( + let queued = crate::queue_persona_social_mention( &store_path, - HeartbeatQueueMentionOptions { + crate::PersonaSocialQueueMentionOptions { target_role_id: "Persona".to_string(), source_surface: "discord".to_string(), channel_id: "aquarium".to_string(), @@ -1524,42 +1013,25 @@ mod tests { )?; assert_eq!(queued["queued"], true); - let pulse = pulse_persona_heartbeat( - &store_path, - &artifact_dir, - "Persona-mentioned", - "test/Persona-mentioned", - false, - )?; + let pulse = crate::pulse_persona_social(&store_path, false)?; assert_eq!(pulse["status"], "reserved"); assert_eq!( pulse["schedule"]["action_catalog"][0]["pending_mentions"][0]["id"], "mention-Persona-test" ); - assert_eq!( - pulse["schedule"]["pending_mentions"] - .as_array() - .map(Vec::len), - Some(1) + let mentions = crate::pending_persona_mentions(&store_path)?; + let requests = crate::persona_turn_requests(&store_path)?; + assert!( + mentions.is_empty(), + "reserved mentions are not pending work" ); - let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - assert_eq!(state.pending_mentions.len(), 1); - assert_eq!(state.persona_turn_requests.len(), 1); - let request = &state.persona_turn_requests[0]; + assert_eq!(requests.len(), 1); + let request = &requests[0]; assert_eq!(request.status, "reserved"); - assert_eq!(request.mentions, state.pending_mentions); - assert_eq!( - state - .participants - .iter() - .find(|participant| participant.role_id == "Persona") - .and_then(|participant| participant.pending_turn.as_ref()) - .map(|pending| pending.status.as_str()), - Some("running") - ); + assert_eq!(request.mentions[0].id, "mention-Persona-test"); - let terminal = complete_persona_turn_request_store( + let terminal = crate::complete_persona_social_turn( &store_path, PersonaTurnTerminalOptions { request_id: request.request_id.clone(), @@ -1569,7 +1041,7 @@ mod tests { }, )?; assert_eq!(terminal.mention_disposition, "consumed"); - let replay = complete_persona_turn_request_store( + let replay = crate::complete_persona_social_turn( &store_path, PersonaTurnTerminalOptions { request_id: request.request_id.clone(), @@ -1579,17 +1051,10 @@ mod tests { }, )?; assert_eq!(replay, terminal); - let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - assert!(state.pending_mentions.is_empty()); - assert_eq!(state.persona_turn_requests[0].status, "terminal"); - assert!( - state - .participants - .iter() - .find(|participant| participant.role_id == "Persona") - .and_then(|participant| participant.pending_turn.as_ref()) - .is_none() - ); + assert!(crate::pending_persona_mentions(&store_path)?.is_empty()); + let requests = crate::persona_turn_requests(&store_path)?; + assert_eq!(requests[0].status, "terminal"); + assert!(requests[0].terminal_receipt.is_some()); Ok(()) } @@ -1597,11 +1062,10 @@ mod tests { fn failed_persona_turn_releases_lane_but_retains_mention_for_retry() -> Result<()> { let temp = tempfile::tempdir()?; let store_path = temp.path().join("Persona-heartbeats.msgpack"); - let artifact_dir = temp.path().join("artifacts"); initialize_heartbeat_store(&store_path, 1.0)?; - queue_heartbeat_pending_mention_store( + crate::queue_persona_social_mention( &store_path, - HeartbeatQueueMentionOptions { + crate::PersonaSocialQueueMentionOptions { target_role_id: "Persona".to_string(), source_surface: "discord".to_string(), channel_id: "aquarium".to_string(), @@ -1619,16 +1083,11 @@ mod tests { model_provider_disclosure_allowed: true, }, )?; - pulse_persona_heartbeat( - &store_path, - &artifact_dir, - "Persona-failure", - "test/Persona-failure", - false, - )?; - let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - let request_id = state.persona_turn_requests[0].request_id.clone(); - let terminal = complete_persona_turn_request_store( + crate::pulse_persona_social(&store_path, false)?; + let request_id = crate::persona_turn_requests(&store_path)?[0] + .request_id + .clone(); + let terminal = crate::complete_persona_social_turn( &store_path, PersonaTurnTerminalOptions { request_id, @@ -1638,15 +1097,10 @@ mod tests { }, )?; assert_eq!(terminal.mention_disposition, "retained"); - let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - assert_eq!(state.pending_mentions.len(), 1); - assert!( - state - .participants - .iter() - .find(|participant| participant.role_id == "Persona") - .and_then(|participant| participant.pending_turn.as_ref()) - .is_none() + assert_eq!(crate::pending_persona_mentions(&store_path)?.len(), 1); + assert_eq!( + crate::persona_turn_requests(&store_path)?[0].status, + "terminal" ); Ok(()) } @@ -1655,11 +1109,10 @@ mod tests { fn indeterminate_local_effect_quarantines_pressure_and_cannot_reschedule() -> Result<()> { let temp = tempfile::tempdir()?; let store_path = temp.path().join("Persona-heartbeats.msgpack"); - let artifact_dir = temp.path().join("artifacts"); initialize_heartbeat_store(&store_path, 1.0)?; - queue_heartbeat_pending_mention_store( + crate::queue_persona_social_mention( &store_path, - HeartbeatQueueMentionOptions { + crate::PersonaSocialQueueMentionOptions { target_role_id: "Persona".to_string(), source_surface: "bifrost-discord".to_string(), channel_id: "aquarium".to_string(), @@ -1677,16 +1130,10 @@ mod tests { model_provider_disclosure_allowed: true, }, )?; - let pulse = pulse_persona_heartbeat( - &store_path, - &artifact_dir, - "Persona-unknown", - "test/Persona-unknown", - false, - )?; + let pulse = crate::pulse_persona_social(&store_path, false)?; let request_id = pulse["requestId"].as_str().expect("request id").to_string(); assert!( - complete_persona_turn_request_store( + crate::complete_persona_social_turn( &store_path, PersonaTurnTerminalOptions { request_id: request_id.clone(), @@ -1697,7 +1144,7 @@ mod tests { ) .is_err() ); - let terminal = complete_persona_turn_request_store( + let terminal = crate::complete_persona_social_turn( &store_path, PersonaTurnTerminalOptions { request_id, @@ -1714,34 +1161,24 @@ mod tests { }, )?; assert_eq!(terminal.mention_disposition, "quarantined"); - let next = pulse_persona_heartbeat( - &store_path, - &artifact_dir, - "Persona-unknown-repeat", - "test/Persona-unknown", - false, - )?; + let next = crate::pulse_persona_social(&store_path, false)?; assert_eq!(next["status"], "idle"); - let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - assert!(state.pending_mentions.is_empty()); - assert_eq!(state.persona_turn_requests.len(), 1); - assert_eq!(state.blocked_persona_pressures.len(), 1); - assert_eq!( - state.blocked_persona_pressures[0].mentions[0].id, - "mention-Persona-unknown" - ); + assert!(crate::pending_persona_mentions(&store_path)?.is_empty()); + assert_eq!(crate::persona_turn_requests(&store_path)?.len(), 1); + let blocked = crate::blocked_persona_pressures(&store_path)?; + assert_eq!(blocked.len(), 1); + assert_eq!(blocked[0].mentions[0].id, "mention-Persona-unknown"); Ok(()) } #[test] - fn persona_heartbeat_pulse_reserves_once_and_obeys_brake() -> Result<()> { + fn persona_social_pulse_reserves_once_and_obeys_brake() -> Result<()> { let temp = tempfile::tempdir()?; let store_path = temp.path().join("Persona-heartbeats.msgpack"); - let artifact_dir = temp.path().join("artifacts"); initialize_heartbeat_store(&store_path, 1.0)?; - queue_heartbeat_pending_mention_store( + crate::queue_persona_social_mention( &store_path, - HeartbeatQueueMentionOptions { + crate::PersonaSocialQueueMentionOptions { target_role_id: "Persona".to_string(), source_surface: "bifrost-discord".to_string(), channel_id: "aquarium".to_string(), @@ -1759,39 +1196,15 @@ mod tests { model_provider_disclosure_allowed: true, }, )?; - let braked = pulse_persona_heartbeat( - &store_path, - &artifact_dir, - "persona-pulse-braked", - "test/persona-pulse", - true, - )?; + let braked = crate::pulse_persona_social(&store_path, true)?; assert_eq!(braked["status"], "refused-by-swarm-brake"); - assert!( - load_heartbeat_state_entry(&store_path)? - .expect("heartbeat state") - .persona_turn_requests - .is_empty() - ); + assert!(crate::persona_turn_requests(&store_path)?.is_empty()); - let first = pulse_persona_heartbeat( - &store_path, - &artifact_dir, - "persona-pulse-one", - "test/persona-pulse", - false, - )?; + let first = crate::pulse_persona_social(&store_path, false)?; assert_eq!(first["status"], "reserved"); - let second = pulse_persona_heartbeat( - &store_path, - &artifact_dir, - "persona-pulse-two", - "test/persona-pulse", - false, - )?; + let second = crate::pulse_persona_social(&store_path, false)?; assert_eq!(second["status"], "already-running"); - let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - assert_eq!(state.persona_turn_requests.len(), 1); + assert_eq!(crate::persona_turn_requests(&store_path)?.len(), 1); Ok(()) } } diff --git a/epiphany-core/src/heartbeat_state/heartbeat_documents.rs b/epiphany-core/src/heartbeat_state/heartbeat_documents.rs index f9a238a7..c245b166 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_documents.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_documents.rs @@ -1,7 +1,6 @@ use cultcache_rs::DatabaseEntry; use serde::Deserialize; use serde::Serialize; -use serde_json::Value; pub const HEARTBEAT_STATE_TYPE: &str = "epiphany.agent_heartbeat"; pub const HEARTBEAT_STATE_KEY: &str = "default"; @@ -24,13 +23,6 @@ pub const HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_SCHEMA_VERSION: &str = "epiphany.heartbeat.artifact_retention_receipt.v0"; pub const HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_LATEST_KEY: &str = "heartbeat/artifact-retention-receipt/latest"; -pub const PERSONA_TURN_REQUEST_SCHEMA_VERSION: &str = "epiphany.persona_turn_request.v0"; -pub const PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.persona_turn_terminal_receipt.v0"; -pub const PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION: &str = - "epiphany.persona_conversation_retention_head.v0"; -pub const PERSONA_CONVERSATION_RETENTION_PLAN_SCHEMA_VERSION: &str = - "epiphany.persona_conversation_retention_plan.v0"; #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache( @@ -52,16 +44,6 @@ pub struct EpiphanyHeartbeatStateEntry { pub participants: Vec, #[cultcache(key = 6)] pub history: Vec, - #[cultcache(key = 19, default)] - pub pending_mentions: Vec, - #[cultcache(key = 20, default)] - pub persona_turn_requests: Vec, - #[cultcache(key = 21, default)] - pub blocked_persona_pressures: Vec, - #[cultcache(key = 22, default)] - pub persona_conversation_retention_head: Option, - #[cultcache(key = 23, default)] - pub persona_conversation_retention_plan: Option, } #[derive(Clone, Debug, PartialEq, DatabaseEntry)] @@ -231,158 +213,6 @@ pub struct HeartbeatPendingTurn { pub initiative_freeze_reason: Option, } -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct HeartbeatPendingMention { - pub id: String, - pub target_role_id: String, - pub target_agent_id: String, - pub source_surface: String, - pub channel_id: String, - pub message_id: String, - pub author_id: String, - #[serde(default)] - pub author_name: Option, - pub content: String, - pub visible_prompt: String, - #[serde(default)] - pub reply_to_message_id: Option, - pub queued_at: String, - #[serde(default)] - pub source_visibility: String, - #[serde(default)] - pub data_classification: String, - #[serde(default)] - pub model_provider_id: String, - #[serde(default)] - pub model_provider_disclosure_allowed: bool, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaTurnRequest { - pub schema_version: String, - pub request_id: String, - pub schedule_id: String, - pub action_id: String, - pub role_id: String, - pub agent_id: String, - pub status: String, - pub reserved_at: String, - pub mentions: Vec, - #[serde(default)] - pub semantic_memory_recall: Value, - #[serde(default)] - pub terminal_receipt: Option, - pub private_state_exposed: bool, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaTurnTerminalReceipt { - pub schema_version: String, - pub receipt_id: String, - pub request_id: String, - pub schedule_id: String, - pub action_id: String, - pub outcome: String, - pub mention_disposition: String, - pub mention_ids: Vec, - pub mention_cargo_sha256: String, - #[serde(default)] - pub delivery_evidence_id: Option, - #[serde(default)] - pub crossing_receipt_id: Option, - #[serde(default)] - pub bridge_receipt_sha256: Option, - #[serde(default)] - pub blocked_crossing_status: Option, - #[serde(default)] - pub blocked_reason: Option, - pub completed_at: String, - pub private_state_exposed: bool, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct PersonaTurnTerminalOptions { - pub request_id: String, - pub outcome: String, - pub delivery_evidence: Option, - pub blocked_evidence: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaConversationRetentionHead { - pub schema_version: String, - pub revision: u64, - pub retired_turn_count: u64, - pub through_reserved_at: String, - pub chained_digest: String, - pub retained_at: String, - pub private_state_exposed: bool, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaConversationRetentionEnvelope { - pub envelope_type: String, - pub key: String, - pub envelope_sha256: String, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaConversationRetentionMember { - pub request_id: String, - pub reserved_at: String, - pub completed_at: String, - pub outcome: String, - pub terminal_receipt_sha256: String, - pub runtime_envelopes: Vec, - pub crossing_request_envelopes: Vec, - pub crossing_receipt_envelopes: Vec, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaConversationRetentionPlan { - pub schema_version: String, - pub plan_id: String, - pub members: Vec, - pub planned_at: String, - pub private_state_exposed: bool, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct PersonaTurnBlockedEvidence { - pub evidence_source: String, - pub crossing_status: String, - pub reason: String, - pub crossing_receipt_id: Option, - pub bridge_receipt_sha256: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PersonaBlockedConversationPressure { - pub schema_version: String, - pub quarantine_id: String, - pub request_id: String, - pub terminal_receipt_id: String, - pub crossing_status: String, - pub evidence_source: String, - pub reason: String, - pub mentions: Vec, - pub mention_cargo_sha256: String, - #[serde(default)] - pub crossing_receipt_id: Option, - #[serde(default)] - pub bridge_receipt_sha256: Option, - pub quarantined_at: String, - pub private_state_exposed: bool, -} - #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct HeartbeatHistoryEvent { pub ts: String, @@ -426,25 +256,6 @@ pub(super) struct HeartbeatTickOptions { pub(super) resident_self_store: Option, } -#[derive(Clone, Debug, PartialEq)] -pub struct HeartbeatQueueMentionOptions { - pub target_role_id: String, - pub source_surface: String, - pub channel_id: String, - pub message_id: String, - pub author_id: String, - pub author_name: Option, - pub content: String, - pub visible_prompt: String, - pub reply_to_message_id: Option, - pub queued_at: Option, - pub mention_id: Option, - pub source_visibility: String, - pub data_classification: String, - pub model_provider_id: String, - pub model_provider_disclosure_allowed: bool, -} - #[derive(Clone, Debug, PartialEq)] pub struct HeartbeatStaleTurnRepairOptions { pub max_age_seconds: i64, diff --git a/epiphany-core/src/heartbeat_state/heartbeat_roles.rs b/epiphany-core/src/heartbeat_state/heartbeat_roles.rs index dde2b26d..cfc97183 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_roles.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_roles.rs @@ -9,7 +9,7 @@ use super::write_heartbeat_state_entry; use anyhow::Result; use std::path::Path; -pub(super) const ROLE_ORDER: &[&str] = &["coordinator", "Persona"]; +pub(super) const ROLE_ORDER: &[&str] = &["coordinator"]; pub fn default_heartbeat_state(target_heartbeat_rate: f64) -> EpiphanyHeartbeatStateEntry { EpiphanyHeartbeatStateEntry { @@ -39,11 +39,6 @@ pub fn default_heartbeat_state(target_heartbeat_rate: f64) -> EpiphanyHeartbeatS .map(|role_id| default_participant(role_id)) .collect(), history: Vec::new(), - pending_mentions: Vec::new(), - persona_turn_requests: Vec::new(), - blocked_persona_pressures: Vec::new(), - persona_conversation_retention_head: None, - persona_conversation_retention_plan: None, } } @@ -81,7 +76,6 @@ pub(super) fn default_participant(role_id: &str) -> HeartbeatParticipant { pub(super) fn agent_id_for_role(role_id: &str) -> &'static str { match role_id { "coordinator" => "epiphany.self", - "Persona" => "epiphany.Persona", _ => "epiphany.unknown", } } @@ -89,7 +83,6 @@ pub(super) fn agent_id_for_role(role_id: &str) -> &'static str { pub(super) fn display_name_for_role(role_id: &str) -> &'static str { match role_id { "coordinator" => "Self", - "Persona" => "Persona", _ => "Unknown", } } @@ -97,7 +90,6 @@ pub(super) fn display_name_for_role(role_id: &str) -> &'static str { fn initiative_speed_for_role(role_id: &str) -> f64 { match role_id { "coordinator" => 1.28, - "Persona" => 1.12, _ => 1.0, } } @@ -105,7 +97,6 @@ fn initiative_speed_for_role(role_id: &str) -> f64 { fn reaction_bias_for_role(role_id: &str) -> f64 { match role_id { "coordinator" => 0.88, - "Persona" => 0.84, _ => 0.5, } } @@ -113,7 +104,6 @@ fn reaction_bias_for_role(role_id: &str) -> f64 { fn interrupt_threshold_for_role(role_id: &str) -> f64 { match role_id { "coordinator" => 0.42, - "Persona" => 0.52, _ => 0.5, } } @@ -123,9 +113,6 @@ fn participant_constraints(role_id: &str) -> Vec<&'static str> { "coordinator" => { "Routes and reviews; must not implement, verify, or accept its own comfort." } - "Persona" => { - "Publicly translates agent thought into #aquarium only; must not moderate or speak outside the room." - } _ => "Unknown role.", }; vec![role_specific] diff --git a/epiphany-core/src/heartbeat_state/heartbeat_store.rs b/epiphany-core/src/heartbeat_state/heartbeat_store.rs index 8d03cb9b..f25aaa51 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_store.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_store.rs @@ -8,10 +8,6 @@ use super::HEARTBEAT_STALE_TURN_REPAIR_SCHEMA_VERSION; use super::HEARTBEAT_STATE_KEY; use super::HEARTBEAT_STATE_SCHEMA_VERSION; use super::PARTICIPANT_KIND_AGENT; -use super::PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION; -use super::PERSONA_CONVERSATION_RETENTION_PLAN_SCHEMA_VERSION; -use super::PERSONA_TURN_REQUEST_SCHEMA_VERSION; -use super::PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION; use super::participant_arena; use super::participant_kind; use anyhow::Result; @@ -273,169 +269,9 @@ pub fn validate_heartbeat_state(state: &EpiphanyHeartbeatStateEntry) -> Result<( )); } } - let mut request_ids = std::collections::BTreeSet::new(); - for request in &state.persona_turn_requests { - if request.schema_version != PERSONA_TURN_REQUEST_SCHEMA_VERSION { - return Err(anyhow!( - "Persona turn request {} has unsupported schema {:?}", - request.request_id, - request.schema_version - )); - } - if request.private_state_exposed { - return Err(anyhow!( - "Persona turn request must not expose private state" - )); - } - if request.request_id.trim().is_empty() - || request.schedule_id.trim().is_empty() - || request.action_id.trim().is_empty() - || request.role_id != "Persona" - || request.agent_id.trim().is_empty() - { - return Err(anyhow!("Persona turn request identity is incomplete")); - } - if !request_ids.insert(request.request_id.as_str()) { - return Err(anyhow!( - "duplicate Persona turn request {:?}", - request.request_id - )); - } - match (&*request.status, &request.terminal_receipt) { - ("reserved", None) | ("terminal", Some(_)) => {} - _ => return Err(anyhow!("Persona turn request status/receipt disagree")), - } - if let Some(receipt) = &request.terminal_receipt { - if receipt.schema_version != PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION - || receipt.private_state_exposed - || receipt.request_id != request.request_id - || receipt.schedule_id != request.schedule_id - || receipt.action_id != request.action_id - || receipt.mention_cargo_sha256.trim().is_empty() - || !request.mentions.is_empty() - || !request.semantic_memory_recall.is_null() - { - return Err(anyhow!("Persona turn terminal receipt binding is invalid")); - } - } - } - if let Some(head) = &state.persona_conversation_retention_head { - if head.schema_version != PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION - || head.revision == 0 - || head.retired_turn_count == 0 - || chrono::DateTime::parse_from_rfc3339(&head.through_reserved_at).is_err() - || chrono::DateTime::parse_from_rfc3339(&head.retained_at).is_err() - || !head - .chained_digest - .strip_prefix("sha256:") - .is_some_and(|digest| { - digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) - || head.private_state_exposed - { - return Err(anyhow!("Persona conversation retention head is invalid")); - } - let frontier = chrono::DateTime::parse_from_rfc3339(&head.through_reserved_at)?; - if state.persona_turn_requests.iter().any(|request| { - request.terminal_receipt.is_none() - && chrono::DateTime::parse_from_rfc3339(&request.reserved_at) - .is_ok_and(|reserved| reserved <= frontier) - }) { - return Err(anyhow!( - "Persona conversation retention frontier overlaps a live turn request" - )); - } - } - if let Some(plan) = &state.persona_conversation_retention_plan { - if plan.schema_version != PERSONA_CONVERSATION_RETENTION_PLAN_SCHEMA_VERSION - || plan.plan_id.trim().is_empty() - || plan.members.is_empty() - || chrono::DateTime::parse_from_rfc3339(&plan.planned_at).is_err() - || plan.private_state_exposed - { - return Err(anyhow!("Persona conversation retention plan is invalid")); - } - let mut planned = std::collections::BTreeSet::new(); - for member in &plan.members { - let request = state - .persona_turn_requests - .iter() - .find(|request| request.request_id == member.request_id) - .ok_or_else(|| anyhow!("Persona retention plan member has no turn request"))?; - let terminal = request - .terminal_receipt - .as_ref() - .ok_or_else(|| anyhow!("Persona retention plan member is not terminal"))?; - if !planned.insert(member.request_id.as_str()) - || member.reserved_at != request.reserved_at - || member.completed_at != terminal.completed_at - || member.outcome != terminal.outcome - || !matches!(member.outcome.as_str(), "delivered" | "silence" | "dropped") - || member.runtime_envelopes.is_empty() - || !valid_persona_retention_digest(&member.terminal_receipt_sha256) - || member - .runtime_envelopes - .iter() - .chain(&member.crossing_request_envelopes) - .chain(&member.crossing_receipt_envelopes) - .any(|envelope| { - envelope.envelope_type.trim().is_empty() - || envelope.key.trim().is_empty() - || !valid_persona_retention_digest(&envelope.envelope_sha256) - }) - { - return Err(anyhow!("Persona conversation retention member is invalid")); - } - } - } - let mut quarantine_ids = std::collections::BTreeSet::new(); - for pressure in &state.blocked_persona_pressures { - if pressure.schema_version != "epiphany.persona_blocked_conversation_pressure.v0" - || pressure.private_state_exposed - || pressure.quarantine_id.trim().is_empty() - || pressure.request_id.trim().is_empty() - || pressure.terminal_receipt_id.trim().is_empty() - || !matches!(pressure.crossing_status.as_str(), "unknown" | "failed") - || pressure.reason.trim().is_empty() - || pressure.mentions.is_empty() - || pressure.mention_cargo_sha256.trim().is_empty() - { - return Err(anyhow!("Persona blocked conversation pressure is invalid")); - } - if !quarantine_ids.insert(pressure.quarantine_id.as_str()) { - return Err(anyhow!("duplicate Persona blocked conversation pressure")); - } - let request = state - .persona_turn_requests - .iter() - .find(|request| request.request_id == pressure.request_id) - .ok_or_else(|| anyhow!("blocked Persona pressure has no bound turn request"))?; - let receipt = request - .terminal_receipt - .as_ref() - .filter(|receipt| { - receipt.receipt_id == pressure.terminal_receipt_id - && receipt.mention_disposition == "quarantined" - && receipt.mention_cargo_sha256 == pressure.mention_cargo_sha256 - }) - .ok_or_else(|| anyhow!("blocked Persona pressure terminal binding is invalid"))?; - if receipt.blocked_crossing_status.as_deref() != Some(&pressure.crossing_status) - || receipt.blocked_reason.as_deref() != Some(&pressure.reason) - { - return Err(anyhow!( - "blocked Persona pressure provenance does not match terminal receipt" - )); - } - } Ok(()) } -fn valid_persona_retention_digest(value: &str) -> bool { - value.strip_prefix("sha256:").is_some_and(|digest| { - digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) -} - #[cfg(test)] mod tests { use super::*; diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index eb5f9dd7..ad5fe1b0 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -24,6 +24,7 @@ mod persona_conversation; mod persona_discord_crossing; mod persona_discord_permit; mod persona_feedback_admission; +mod persona_social_state; mod persona_turn; mod process_observation; mod promotion; @@ -507,27 +508,17 @@ pub use heartbeat_state::HeartbeatArtifactRetentionMember; pub use heartbeat_state::HeartbeatHistoryEvent; pub use heartbeat_state::HeartbeatPacingPolicy; pub use heartbeat_state::HeartbeatParticipant; -pub use heartbeat_state::HeartbeatPendingMention; pub use heartbeat_state::HeartbeatPendingTurn; -pub use heartbeat_state::HeartbeatQueueMentionOptions; pub use heartbeat_state::HeartbeatSelectionPolicy; pub use heartbeat_state::HeartbeatStaleTurnRepairOptions; -pub use heartbeat_state::PersonaBlockedConversationPressure; -pub use heartbeat_state::PersonaTurnBlockedEvidence; -pub use heartbeat_state::PersonaTurnRequest; -pub use heartbeat_state::PersonaTurnTerminalOptions; -pub use heartbeat_state::PersonaTurnTerminalReceipt; pub use heartbeat_state::ResidentSelfHeartbeatPulse; -pub use heartbeat_state::complete_persona_turn_request_store; pub use heartbeat_state::default_heartbeat_state; pub use heartbeat_state::heartbeat_state_cache; pub use heartbeat_state::heartbeat_status_projection; pub use heartbeat_state::initialize_heartbeat_store; pub use heartbeat_state::load_heartbeat_state_entry; pub use heartbeat_state::load_latest_heartbeat_stale_turn_repair_receipt; -pub use heartbeat_state::pulse_persona_heartbeat; pub use heartbeat_state::pulse_resident_self_heartbeat; -pub use heartbeat_state::queue_heartbeat_pending_mention_store; pub use heartbeat_state::reconcile_resident_self_heartbeat_ack; pub use heartbeat_state::recover_stale_heartbeat_store; pub use heartbeat_state::retain_heartbeat_pulse_artifacts; @@ -683,14 +674,15 @@ pub use persona_feedback_admission::{ BIFROST_PERSONA_FEEDBACK_ADMISSION_SCHEMA_VERSION, BIFROST_PERSONA_FEEDBACK_DELIVERY_TYPE, BIFROST_PERSONA_FEEDBACK_RECEIPT_SCHEMA_VERSION, BifrostPersonaFeedbackAdmission, LOCAL_PERSONA_FEEDBACK_SCHEMA_VERSION, LocalAdmittedPersonaFeedback, - PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION, PersonaFeedbackHeartbeatBridgeReceipt, - PersonaFeedbackPacket, admit_bifrost_persona_feedback, admitted_persona_feedback, - apply_bifrost_persona_feedback_snapshot, bridge_admitted_persona_feedback_to_heartbeat, - bridged_persona_feedback_ready_for_cognition, import_bifrost_persona_feedback_deliveries, + PERSONA_FEEDBACK_SOCIAL_ADMISSION_SCHEMA_VERSION, PersonaFeedbackPacket, + PersonaFeedbackSocialAdmissionReceipt, admit_bifrost_persona_feedback, + admit_persona_feedback_to_social, admitted_persona_feedback, + apply_bifrost_persona_feedback_snapshot, import_bifrost_persona_feedback_deliveries, persona_feedback_admission_signing_payload, persona_feedback_admission_signing_purpose, - persona_feedback_packet_sha256, validate_bifrost_persona_feedback_source, - validate_persona_feedback_store_separation, + persona_feedback_packet_sha256, persona_feedback_ready_for_cognition, + validate_bifrost_persona_feedback_source, validate_persona_feedback_store_separation, }; +pub use persona_social_state::*; pub use persona_turn::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION; pub use persona_turn::PERSONA_INTERPRETER_EFFECT_SET_SCHEMA_VERSION; pub use persona_turn::PERSONA_INTERPRETER_PROMPT_SCHEMA_VERSION; diff --git a/epiphany-core/src/persona_conversation.rs b/epiphany-core/src/persona_conversation.rs index fb3a25a1..35c12ac2 100644 --- a/epiphany-core/src/persona_conversation.rs +++ b/epiphany-core/src/persona_conversation.rs @@ -8,26 +8,23 @@ use cultcache_rs::{ use cultnet_rs::{GameCultServiceTrustAnchorRecord, ServiceIdentitySigner}; use sha2::{Digest, Sha256}; -use crate::heartbeat_state::{ +use crate::{ + EpiphanyDecisionContext, EpiphanyPersonaDeliveryRequestIdentity, EpiphanyReasoningBasis, PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION, PERSONA_CONVERSATION_RETENTION_PLAN_SCHEMA_VERSION, PersonaConversationRetentionEnvelope, PersonaConversationRetentionHead, PersonaConversationRetentionMember, - PersonaConversationRetentionPlan, commit_heartbeat_state_transaction, - load_heartbeat_state_transaction, -}; -use crate::{ - EpiphanyDecisionContext, EpiphanyPersonaDeliveryRequestIdentity, EpiphanyReasoningBasis, - PersonaInterpreterEffect, PersonaInterpreterEffectDocument, PersonaModelStageReceipt, - PersonaModelTerminalReceipt, PersonaTurnRequest, PersonaTurnTerminalOptions, - complete_persona_turn_request_store, insert_persona_discord_delivery_request, - load_persona_discord_delivery_receipt, runtime_spine_cache, - sign_persona_discord_delivery_request, verify_persona_discord_delivery_receipt, + PersonaConversationRetentionPlan, PersonaInterpreterEffect, PersonaInterpreterEffectDocument, + PersonaModelStageReceipt, PersonaModelTerminalReceipt, PersonaTurnRequest, + PersonaTurnTerminalOptions, complete_persona_social_turn, + insert_persona_discord_delivery_request, load_persona_discord_delivery_receipt, + runtime_spine_cache, sign_persona_discord_delivery_request, + verify_persona_discord_delivery_receipt, }; pub const PERSONA_DISCORD_DELIVERY_EVIDENCE_SCHEMA_VERSION: &str = "epiphany.persona_discord_delivery_evidence.v0"; pub const PERSONA_CONVERSATION_EXECUTION_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.persona_conversation_execution_receipt.v0"; + "epiphany.persona_conversation_execution_receipt.v1"; pub const PERSONA_EFFECT_EXECUTION_INTENT_SCHEMA_VERSION: &str = "epiphany.persona_effect_execution_intent.v0"; pub const PERSONA_CONVERSATION_STORE_RETIREMENT_RECEIPT_SCHEMA_VERSION: &str = @@ -183,7 +180,7 @@ pub struct PersonaDiscordDeliveryEvidence { #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache( - type = "epiphany.persona_conversation_execution_receipt.v0", + type = "epiphany.persona_conversation_execution_receipt.v1", schema = "PersonaConversationExecutionReceipt" )] pub struct PersonaConversationExecutionReceipt { @@ -203,8 +200,8 @@ pub struct PersonaConversationExecutionReceipt { pub state_effect_reasons: Vec, #[cultcache(key = 7, default)] pub delivery_evidence_ids: Vec, - #[cultcache(key = 8, default)] - pub heartbeat_terminal_receipt_id: Option, + #[cultcache(key = 8)] + pub social_terminal_receipt_id: Option, #[cultcache(key = 9)] pub private_state_exposed: bool, #[cultcache(key = 10)] @@ -218,7 +215,7 @@ pub struct PersonaConversationExecutionReceipt { #[allow(clippy::too_many_arguments)] pub fn poll_persona_discord_crossing( runtime_store: &Path, - heartbeat_store: &Path, + social_store: &Path, cultmesh_store: &Path, runtime_id: &str, request_store: &Path, @@ -234,7 +231,7 @@ pub fn poll_persona_discord_crossing( { return Ok(Some(existing)); } - let request = load_reserved_request(heartbeat_store, request_id)?; + let request = load_reserved_request(social_store, request_id)?; let effects = runtime_document::(runtime_store, effect_document_id)? .ok_or_else(|| anyhow!("Persona Interpreter effect document is missing"))?; @@ -270,7 +267,7 @@ pub fn poll_persona_discord_crossing( Err(error) if error.to_string().contains("quarantined") => { return terminalize_local_effect_quarantine( runtime_store, - heartbeat_store, + social_store, &request, &effects, error, @@ -287,8 +284,8 @@ pub fn poll_persona_discord_crossing( } else { "silence" }; - let terminal = complete_persona_turn_request_store( - heartbeat_store, + let terminal = complete_persona_social_turn( + social_store, PersonaTurnTerminalOptions { request_id: request_id.into(), outcome: outcome.into(), @@ -305,7 +302,7 @@ pub fn poll_persona_discord_crossing( state_effect_status: state_status, state_effect_reasons: reasons, delivery_evidence_ids: vec![], - heartbeat_terminal_receipt_id: Some(terminal.receipt_id), + social_terminal_receipt_id: Some(terminal.receipt_id), private_state_exposed: false, model_terminal_receipt_id: Some(model_terminal.receipt_id.clone()), interpreter_decision_context_id: Some(effects.decision_context_id.clone()), @@ -330,7 +327,7 @@ pub fn poll_persona_discord_crossing( if error.to_string().contains("quarantined") { return terminalize_local_effect_quarantine( runtime_store, - heartbeat_store, + social_store, &request, &effects, error, @@ -402,8 +399,8 @@ pub fn poll_persona_discord_crossing( if let Some(value) = &evidence { put_runtime_document(runtime_store, &value.evidence_id, value)?; } - let terminal = complete_persona_turn_request_store( - heartbeat_store, + let terminal = complete_persona_social_turn( + social_store, PersonaTurnTerminalOptions { request_id: request_id.into(), outcome: outcome.into(), @@ -429,7 +426,7 @@ pub fn poll_persona_discord_crossing( .iter() .map(|value| value.evidence_id.clone()) .collect(), - heartbeat_terminal_receipt_id: Some(terminal.receipt_id), + social_terminal_receipt_id: Some(terminal.receipt_id), private_state_exposed: false, model_terminal_receipt_id: Some(model_terminal.receipt_id.clone()), interpreter_decision_context_id: Some(effects.decision_context_id.clone()), @@ -440,14 +437,14 @@ pub fn poll_persona_discord_crossing( fn terminalize_local_effect_quarantine( runtime_store: &Path, - heartbeat_store: &Path, + social_store: &Path, request: &PersonaTurnRequest, effects: &PersonaInterpreterEffectDocument, error: anyhow::Error, ) -> Result> { let model_terminal = validate_model_terminal(runtime_store, request, effects)?; - let terminal = complete_persona_turn_request_store( - heartbeat_store, + let terminal = complete_persona_social_turn( + social_store, PersonaTurnTerminalOptions { request_id: request.request_id.clone(), outcome: "blocked".into(), @@ -470,7 +467,7 @@ fn terminalize_local_effect_quarantine( state_effect_status: "quarantined_ambiguous_local_effect".into(), state_effect_reasons: vec![error.to_string()], delivery_evidence_ids: vec![], - heartbeat_terminal_receipt_id: Some(terminal.receipt_id), + social_terminal_receipt_id: Some(terminal.receipt_id), private_state_exposed: false, model_terminal_receipt_id: Some(model_terminal.receipt_id), interpreter_decision_context_id: Some(effects.decision_context_id.clone()), @@ -479,25 +476,19 @@ fn terminalize_local_effect_quarantine( Ok(Some(receipt)) } -/// Repairs the local execution projection after the heartbeat terminal commit -/// won a crash race. The heartbeat terminal remains authority; this function +/// Repairs the local execution projection after the social terminal commit +/// won a crash race. The social terminal remains authority; this function /// only finishes matching typed intents and restores its derived receipt. pub fn reconcile_terminal_persona_conversation( runtime_store: &Path, - heartbeat_store: &Path, + social_store: &Path, request_id: &str, ) -> Result> { let receipt_id = format!("persona-conversation:{request_id}"); if let Some(existing) = runtime_document(runtime_store, &receipt_id)? { return Ok(Some(existing)); } - let state = crate::heartbeat_state::load_heartbeat_state_entry(heartbeat_store)? - .ok_or_else(|| anyhow!("heartbeat state is missing"))?; - let Some(request) = state - .persona_turn_requests - .into_iter() - .find(|value| value.request_id == request_id) - else { + let Some(request) = crate::persona_turn_request(social_store, request_id)? else { return Ok(None); }; let Some(terminal) = request.terminal_receipt.as_ref() else { @@ -526,10 +517,10 @@ pub fn reconcile_terminal_persona_conversation( request_id: request_id.into(), effect_document_id, outcome: terminal.outcome.clone(), - state_effect_status: "reconciled_from_heartbeat_terminal".into(), + state_effect_status: "reconciled_from_social_terminal".into(), state_effect_reasons: vec![], delivery_evidence_ids: terminal.delivery_evidence_id.clone().into_iter().collect(), - heartbeat_terminal_receipt_id: Some(terminal.receipt_id.clone()), + social_terminal_receipt_id: Some(terminal.receipt_id.clone()), private_state_exposed: false, model_terminal_receipt_id: Some(model_terminal.receipt_id), interpreter_decision_context_id: Some(effects.decision_context_id.clone()), @@ -605,7 +596,7 @@ pub fn pending_persona_discord_delivery_request_for_turn( #[allow(clippy::too_many_arguments)] pub fn retain_terminal_persona_conversations( runtime_store: &Path, - heartbeat_store: &Path, + social_store: &Path, request_store: &Path, receipt_store: &Path, receipt_anchor: &GameCultServiceTrustAnchorRecord, @@ -614,17 +605,35 @@ pub fn retain_terminal_persona_conversations( ) -> Result> { chrono::DateTime::parse_from_rfc3339(retained_at) .map_err(|_| anyhow!("Persona conversation retention time must be RFC3339"))?; - let (loaded, expected) = load_heartbeat_state_transaction(heartbeat_store)?; - let mut state = loaded.ok_or_else(|| anyhow!("heartbeat state is missing"))?; - if state.persona_conversation_retention_plan.is_none() { - let mut terminal = state - .persona_turn_requests + if crate::persona_retention_plan(social_store)?.is_none() { + let requests = crate::persona_turn_requests(social_store)?; + let retired_through = crate::persona_retention_head(social_store)? + .map(|head| { + chrono::DateTime::parse_from_rfc3339(&head.through_reserved_at) + .map_err(|_| anyhow!("Persona conversation retention frontier is invalid")) + }) + .transpose()?; + let mut terminal = requests .iter() .filter(|request| request.terminal_receipt.is_some()) - .collect::>(); + .filter_map(|request| { + let reserved = chrono::DateTime::parse_from_rfc3339(&request.reserved_at) + .map_err(|_| anyhow!("Persona turn reservation time is invalid")); + match reserved { + Ok(reserved) + if retired_through + .as_ref() + .is_none_or(|frontier| reserved > *frontier) => + { + Some(Ok(request)) + } + Ok(_) => None, + Err(error) => Some(Err(error)), + } + }) + .collect::>>()?; terminal.sort_by(|left, right| left.reserved_at.cmp(&right.reserved_at)); - let oldest_live = state - .persona_turn_requests + let oldest_live = requests .iter() .filter(|request| request.terminal_receipt.is_none()) .map(|request| request.reserved_at.as_str()) @@ -660,12 +669,11 @@ pub fn retain_terminal_persona_conversations( planned_at: retained_at.into(), private_state_exposed: false, }; - state.persona_conversation_retention_plan = Some(plan); - commit_heartbeat_state_transaction(heartbeat_store, expected, &state)?; + crate::put_persona_retention_plan(social_store, &plan)?; } reconcile_persona_conversation_retention( runtime_store, - heartbeat_store, + social_store, request_store, receipt_store, retained_at, @@ -699,8 +707,7 @@ fn build_persona_retention_member( let model_terminal_id = format!("persona-terminal:{}", request.request_id); if conversation.request_id != request.request_id || conversation.outcome != terminal.outcome - || conversation.heartbeat_terminal_receipt_id.as_deref() - != Some(terminal.receipt_id.as_str()) + || conversation.social_terminal_receipt_id.as_deref() != Some(terminal.receipt_id.as_str()) || conversation.model_terminal_receipt_id.as_deref() != Some(model_terminal_id.as_str()) || conversation.private_state_exposed { @@ -836,16 +843,12 @@ fn retention_envelopes( fn reconcile_persona_conversation_retention( runtime_store: &Path, - heartbeat_store: &Path, + social_store: &Path, request_store: &Path, receipt_store: &Path, retained_at: &str, ) -> Result { - let state = crate::heartbeat_state::load_heartbeat_state_entry(heartbeat_store)? - .ok_or_else(|| anyhow!("heartbeat state is missing"))?; - let plan = state - .persona_conversation_retention_plan - .clone() + let plan = crate::persona_retention_plan(social_store)? .ok_or_else(|| anyhow!("Persona conversation retention plan is missing"))?; let runtime_members = plan .members @@ -884,21 +887,14 @@ fn reconcile_persona_conversation_retention( .collect::>(), )?; - let (loaded, expected) = load_heartbeat_state_transaction(heartbeat_store)?; - let mut state = loaded.ok_or_else(|| anyhow!("heartbeat state is missing"))?; - if state.persona_conversation_retention_plan.as_ref() != Some(&plan) { + if crate::persona_retention_plan(social_store)?.as_ref() != Some(&plan) { return Err(anyhow!( "Persona conversation retention plan changed before commit" )); } - let ids = plan - .members - .iter() - .map(|member| member.request_id.as_str()) - .collect::>(); + let requests = crate::persona_turn_requests(social_store)?; for member in &plan.members { - let request = state - .persona_turn_requests + let request = requests .iter() .find(|request| request.request_id == member.request_id) .ok_or_else(|| anyhow!("Persona retention turn disappeared before commit"))?; @@ -914,14 +910,12 @@ fn reconcile_persona_conversation_retention( )); } } - state - .persona_turn_requests - .retain(|request| !ids.contains(request.request_id.as_str())); - let prior = state.persona_conversation_retention_head.as_ref(); + let prior = crate::persona_retention_head(social_store)?; let mut digest = Sha256::new(); digest.update(b"epiphany.persona-conversation-retention-head.v0\0"); digest.update( prior + .as_ref() .map(|head| head.chained_digest.as_str()) .unwrap_or("persona-conversation-retention-root") .as_bytes(), @@ -935,6 +929,7 @@ fn reconcile_persona_conversation_retention( .max() .unwrap_or_default(); let through_reserved_at = prior + .as_ref() .map(|head| head.through_reserved_at.as_str()) .into_iter() .chain(std::iter::once(retired_through)) @@ -943,8 +938,10 @@ fn reconcile_persona_conversation_retention( .to_string(); let head = PersonaConversationRetentionHead { schema_version: PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION.into(), - revision: prior.map_or(1, |head| head.revision.saturating_add(1)), - retired_turn_count: prior.map_or(plan.members.len() as u64, |head| { + revision: prior + .as_ref() + .map_or(1, |head| head.revision.saturating_add(1)), + retired_turn_count: prior.as_ref().map_or(plan.members.len() as u64, |head| { head.retired_turn_count .saturating_add(plan.members.len() as u64) }), @@ -953,9 +950,7 @@ fn reconcile_persona_conversation_retention( retained_at: retained_at.into(), private_state_exposed: false, }; - state.persona_conversation_retention_head = Some(head.clone()); - state.persona_conversation_retention_plan = None; - commit_heartbeat_state_transaction(heartbeat_store, expected, &state)?; + crate::complete_persona_retention_plan(social_store, &plan, &head)?; Ok(head) } @@ -1309,12 +1304,7 @@ fn resolve_reply_target( } fn load_reserved_request(store: &Path, request_id: &str) -> Result { - let state = crate::heartbeat_state::load_heartbeat_state_entry(store)? - .ok_or_else(|| anyhow!("heartbeat state is missing"))?; - let request = state - .persona_turn_requests - .into_iter() - .find(|request| request.request_id == request_id) + let request = crate::persona_turn_request(store, request_id)? .ok_or_else(|| anyhow!("reserved Persona turn request is missing"))?; if request.status != "reserved" || request.terminal_receipt.is_some() { return Err(anyhow!("Persona turn request is not reserved")); @@ -1344,6 +1334,40 @@ fn stable_memory_id(document_id: &str, index: usize) -> String { mod tests { use super::*; + fn insert_terminal_persona_request( + store_path: &Path, + mut request: PersonaTurnRequest, + ) -> Result<()> { + let terminal = request + .terminal_receipt + .take() + .ok_or_else(|| anyhow!("terminal Persona test request requires its receipt"))?; + request.status = "reserved".into(); + let cache = crate::persona_social_cache(store_path)?; + let request_id = request.request_id.clone(); + let terminal_request_id = terminal.request_id.clone(); + let writes = vec![ + cache + .prepare_entry( + &request_id, + &crate::PersonaSocialTurnRequestDocument { request }, + )? + .0, + cache + .prepare_entry( + &terminal_request_id, + &crate::PersonaSocialTurnTerminalDocument { receipt: terminal }, + )? + .0, + ]; + if !SingleFileMessagePackBackingStore::new(store_path) + .compare_and_swap_batch(&[], writes)? + { + return Err(anyhow!("terminal Persona test request identity collided")); + } + Ok(()) + } + fn unused_anchor() -> GameCultServiceTrustAnchorRecord { GameCultServiceTrustAnchorRecord { schema_version: cultnet_rs::GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(), @@ -1364,7 +1388,7 @@ mod tests { fn seed_closed_silence_turn( runtime_store: &Path, - state: &mut crate::heartbeat_state::EpiphanyHeartbeatStateEntry, + social_store: &Path, suffix: &str, reserved_at: &str, ) -> Result<()> { @@ -1372,9 +1396,8 @@ mod tests { let effect_id = format!("persona-effects:{request_id}"); let stage_ids = ["projector", "persona", "interpreter"] .map(|stage| format!("persona-stage:{request_id}:{stage}")); - let terminal = crate::heartbeat_state::PersonaTurnTerminalReceipt { - schema_version: crate::heartbeat_state::PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION - .into(), + let terminal = crate::PersonaTurnTerminalReceipt { + schema_version: crate::PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION.into(), receipt_id: format!("{request_id}:terminal"), request_id: request_id.clone(), schedule_id: format!("schedule-{suffix}"), @@ -1387,20 +1410,23 @@ mod tests { private_state_exposed: false, ..Default::default() }; - state.persona_turn_requests.push(PersonaTurnRequest { - schema_version: crate::heartbeat_state::PERSONA_TURN_REQUEST_SCHEMA_VERSION.into(), - request_id: request_id.clone(), - schedule_id: format!("schedule-{suffix}"), - action_id: format!("action-{suffix}"), - role_id: "Persona".into(), - agent_id: "epiphany.Persona".into(), - status: "terminal".into(), - reserved_at: reserved_at.into(), - mentions: vec![], - semantic_memory_recall: serde_json::Value::Null, - terminal_receipt: Some(terminal.clone()), - private_state_exposed: false, - }); + insert_terminal_persona_request( + social_store, + PersonaTurnRequest { + schema_version: crate::PERSONA_TURN_REQUEST_SCHEMA_VERSION.into(), + request_id: request_id.clone(), + schedule_id: format!("schedule-{suffix}"), + action_id: format!("action-{suffix}"), + role_id: "Persona".into(), + agent_id: "epiphany.Persona".into(), + status: "terminal".into(), + reserved_at: reserved_at.into(), + mentions: vec![], + semantic_memory_recall: serde_json::Value::Null, + terminal_receipt: Some(terminal.clone()), + private_state_exposed: false, + }, + )?; let mut effects = PersonaInterpreterEffectDocument { schema_version: crate::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION.into(), document_id: effect_id.clone(), @@ -1506,7 +1532,7 @@ mod tests { state_effect_status: "none".into(), state_effect_reasons: vec![], delivery_evidence_ids: vec![], - heartbeat_terminal_receipt_id: Some(terminal.receipt_id), + social_terminal_receipt_id: Some(terminal.receipt_id), private_state_exposed: false, model_terminal_receipt_id: Some(format!("persona-terminal:{request_id}")), interpreter_decision_context_id: Some(context_ids[2].clone()), @@ -1742,38 +1768,38 @@ mod tests { let heartbeat = temp.path().join("heartbeat.cc"); let requests = temp.path().join("requests.cc"); let receipts = temp.path().join("receipts.cc"); - let mut state = crate::heartbeat_state::default_heartbeat_state(1.0); - state.persona_turn_requests.push(PersonaTurnRequest { - schema_version: crate::heartbeat_state::PERSONA_TURN_REQUEST_SCHEMA_VERSION.into(), - request_id: "turn-failed".into(), - schedule_id: "schedule-failed".into(), - action_id: "action-failed".into(), - role_id: "Persona".into(), - agent_id: "epiphany.Persona".into(), - status: "terminal".into(), - reserved_at: "2026-08-09T23:59:59Z".into(), - mentions: vec![], - semantic_memory_recall: serde_json::Value::Null, - terminal_receipt: Some(crate::heartbeat_state::PersonaTurnTerminalReceipt { - schema_version: - crate::heartbeat_state::PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: "turn-failed:terminal".into(), + insert_terminal_persona_request( + &heartbeat, + PersonaTurnRequest { + schema_version: crate::PERSONA_TURN_REQUEST_SCHEMA_VERSION.into(), request_id: "turn-failed".into(), schedule_id: "schedule-failed".into(), action_id: "action-failed".into(), - outcome: "failed".into(), - mention_disposition: "retained".into(), - mention_ids: vec!["mention-failed".into()], - mention_cargo_sha256: format!("sha256-{}", "f".repeat(64)), - completed_at: "2026-08-09T23:59:59Z".into(), + role_id: "Persona".into(), + agent_id: "epiphany.Persona".into(), + status: "terminal".into(), + reserved_at: "2026-08-09T23:59:59Z".into(), + mentions: vec![], + semantic_memory_recall: serde_json::Value::Null, + terminal_receipt: Some(crate::PersonaTurnTerminalReceipt { + schema_version: crate::PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION.into(), + receipt_id: "turn-failed:terminal".into(), + request_id: "turn-failed".into(), + schedule_id: "schedule-failed".into(), + action_id: "action-failed".into(), + outcome: "failed".into(), + mention_disposition: "retained".into(), + mention_ids: vec!["mention-failed".into()], + mention_cargo_sha256: format!("sha256-{}", "f".repeat(64)), + completed_at: "2026-08-09T23:59:59Z".into(), + private_state_exposed: false, + ..Default::default() + }), private_state_exposed: false, - ..Default::default() - }), - private_state_exposed: false, - }); - seed_closed_silence_turn(&runtime, &mut state, "old", "2026-08-10T00:00:00Z")?; - seed_closed_silence_turn(&runtime, &mut state, "new", "2026-08-10T00:00:01Z")?; - crate::heartbeat_state::write_heartbeat_state_entry(&heartbeat, &state)?; + }, + )?; + seed_closed_silence_turn(&runtime, &heartbeat, "old", "2026-08-10T00:00:00Z")?; + seed_closed_silence_turn(&runtime, &heartbeat, "new", "2026-08-10T00:00:01Z")?; let head = retain_terminal_persona_conversations( &runtime, @@ -1787,9 +1813,9 @@ mod tests { .expect("oldest closed turn should retire"); assert_eq!(head.retired_turn_count, 1); assert_eq!(head.through_reserved_at, "2026-08-10T00:00:00Z"); - let retained = crate::heartbeat_state::load_heartbeat_state_entry(&heartbeat)?.unwrap(); - assert_eq!(retained.persona_turn_requests.len(), 2); - assert!(retained.persona_turn_requests.iter().any(|request| { + let retained = crate::persona_turn_requests(&heartbeat)?; + assert_eq!(retained.len(), 3); + assert!(retained.iter().any(|request| { request.request_id == "turn-failed" && request .terminal_receipt @@ -1798,11 +1824,10 @@ mod tests { })); assert!( retained - .persona_turn_requests .iter() .any(|request| request.request_id == "turn-new") ); - assert!(retained.persona_conversation_retention_plan.is_none()); + assert!(crate::persona_retention_plan(&heartbeat)?.is_none()); let retired_conversation = runtime_document::( &runtime, "persona-conversation:turn-old", @@ -1860,22 +1885,6 @@ mod tests { .is_none() ); - let mut hostile = retained; - hostile.persona_turn_requests.push(PersonaTurnRequest { - schema_version: crate::heartbeat_state::PERSONA_TURN_REQUEST_SCHEMA_VERSION.into(), - request_id: "turn-old".into(), - schedule_id: "schedule-old".into(), - action_id: "action-old".into(), - role_id: "Persona".into(), - agent_id: "epiphany.Persona".into(), - status: "reserved".into(), - reserved_at: "2026-08-10T00:00:00Z".into(), - mentions: vec![], - semantic_memory_recall: serde_json::Value::Null, - terminal_receipt: None, - private_state_exposed: false, - }); - assert!(crate::heartbeat_state::validate_heartbeat_state(&hostile).is_err()); Ok(()) } @@ -1893,7 +1902,7 @@ mod tests { state_effect_status: "none".into(), state_effect_reasons: vec![], delivery_evidence_ids: vec![], - heartbeat_terminal_receipt_id: Some("retry:terminal".into()), + social_terminal_receipt_id: Some("retry:terminal".into()), private_state_exposed: false, model_terminal_receipt_id: Some("persona-terminal:retry".into()), interpreter_decision_context_id: Some("decision-context-retry-interpreter".into()), diff --git a/epiphany-core/src/persona_feedback_admission.rs b/epiphany-core/src/persona_feedback_admission.rs index 6f869e1a..9a8cfdc4 100644 --- a/epiphany-core/src/persona_feedback_admission.rs +++ b/epiphany-core/src/persona_feedback_admission.rs @@ -23,8 +23,8 @@ pub const BIFROST_PERSONA_FEEDBACK_RECEIPT_SCHEMA_VERSION: &str = "bifrost.persona_feedback.admission_receipt.v0"; pub const LOCAL_PERSONA_FEEDBACK_SCHEMA_VERSION: &str = "epiphany.persona_feedback.admitted_pressure.v0"; -pub const PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION: &str = - "epiphany.persona_feedback.heartbeat_bridge.v0"; +pub const PERSONA_FEEDBACK_SOCIAL_ADMISSION_SCHEMA_VERSION: &str = + "epiphany.persona_feedback.social_admission.v1"; const SIGNING_PURPOSE: &str = "bifrost.persona-feedback.delivery.v0"; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -127,10 +127,10 @@ pub struct LocalAdmittedPersonaFeedback { #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache( - type = "epiphany.persona_feedback.heartbeat_bridge.v0", - schema = "PersonaFeedbackHeartbeatBridgeReceipt" + type = "epiphany.persona_feedback.social_admission.v1", + schema = "PersonaFeedbackSocialAdmissionReceipt" )] -pub struct PersonaFeedbackHeartbeatBridgeReceipt { +pub struct PersonaFeedbackSocialAdmissionReceipt { #[cultcache(key = 0)] pub schema_version: String, #[cultcache(key = 1)] @@ -142,7 +142,7 @@ pub struct PersonaFeedbackHeartbeatBridgeReceipt { #[cultcache(key = 4)] pub packet_sha256: String, #[cultcache(key = 5)] - pub heartbeat_mention_id: String, + pub social_mention_id: String, #[cultcache(key = 6)] pub discord_channel_id: String, #[cultcache(key = 7)] @@ -305,18 +305,18 @@ fn validate_bifrost_persona_feedback_admission( Ok(()) } -pub fn bridge_admitted_persona_feedback_to_heartbeat( +pub fn admit_persona_feedback_to_social( feedback_store: &Path, - heartbeat_store: &Path, + social_store: &Path, runtime_id: &str, model_provider_id: &str, allowed_data_classifications: &[String], -) -> Result> { +) -> Result> { if model_provider_id.trim().is_empty() || allowed_data_classifications.is_empty() { bail!("Persona feedback bridge requires an explicit model-provider disclosure policy"); } - if paths_share_storage(feedback_store, heartbeat_store)? { - bail!("Persona feedback and heartbeat stores must be physically separate"); + if paths_share_storage(feedback_store, social_store)? { + bail!("Persona feedback and social stores must be physically separate"); } let feedback = admitted_persona_feedback(feedback_store, runtime_id)?; let mut bridged = Vec::new(); @@ -328,42 +328,42 @@ pub fn bridge_admitted_persona_feedback_to_heartbeat( continue; } let mention_id = format!("bifrost-feedback:{}", admitted.feedback_id); - let receipt_id = format!("persona-feedback-heartbeat:{}", admitted.feedback_id); - let existing = load_persona_feedback_bridge_receipt(feedback_store, &receipt_id)?; + let receipt_id = format!("persona-feedback-social:{}", admitted.feedback_id); + let existing = load_persona_feedback_social_receipt(feedback_store, &receipt_id)?; let (mut receipt, expected) = if let Some((receipt, envelope)) = existing { if receipt.admission_id != admitted.admission_id || receipt.packet_sha256 != admitted.packet_sha256 - || receipt.heartbeat_mention_id != mention_id + || receipt.social_mention_id != mention_id { - bail!("Persona feedback heartbeat bridge identity collision"); + bail!("Persona feedback social admission identity collision"); } if receipt.status == "queued" { continue; } if receipt.status != "pending" { - bail!("Persona feedback heartbeat bridge has invalid status"); + bail!("Persona feedback social admission has invalid status"); } (receipt, envelope) } else { - let receipt = PersonaFeedbackHeartbeatBridgeReceipt { - schema_version: PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION.into(), + let receipt = PersonaFeedbackSocialAdmissionReceipt { + schema_version: PERSONA_FEEDBACK_SOCIAL_ADMISSION_SCHEMA_VERSION.into(), receipt_id: receipt_id.clone(), feedback_id: admitted.feedback_id.clone(), admission_id: admitted.admission_id.clone(), packet_sha256: admitted.packet_sha256.clone(), - heartbeat_mention_id: mention_id.clone(), + social_mention_id: mention_id.clone(), discord_channel_id: admitted.discord_channel_id.clone(), discord_message_id: admitted.discord_message_id.clone(), status: "pending".into(), private_state_exposed: false, }; let envelope = - insert_pending_persona_feedback_bridge_receipt(feedback_store, &receipt)?; + insert_pending_persona_feedback_social_receipt(feedback_store, &receipt)?; (receipt, envelope) }; - crate::queue_heartbeat_pending_mention_store( - heartbeat_store, - crate::HeartbeatQueueMentionOptions { + crate::queue_persona_social_mention( + social_store, + crate::PersonaSocialQueueMentionOptions { target_role_id: "Persona".into(), source_surface: "bifrost-discord".into(), channel_id: admitted.discord_channel_id.clone(), @@ -383,15 +383,15 @@ pub fn bridge_admitted_persona_feedback_to_heartbeat( )?; receipt.status = "queued".into(); let mut cache = CultCache::new(); - cache.register_entry_type::()?; + cache.register_entry_type::()?; let (replacement, _) = cache.prepare_entry(&receipt.receipt_id, &receipt)?; if !SingleFileMessagePackBackingStore::new(feedback_store) .compare_and_swap_entry(&expected, replacement)? { - let raced = load_persona_feedback_bridge_receipt(feedback_store, &receipt.receipt_id)? + let raced = load_persona_feedback_social_receipt(feedback_store, &receipt.receipt_id)? .map(|(receipt, _)| receipt); if raced.as_ref() != Some(&receipt) { - bail!("Persona feedback heartbeat bridge receipt lost exact CAS"); + bail!("Persona feedback social admission receipt lost exact CAS"); } } bridged.push(receipt); @@ -399,20 +399,20 @@ pub fn bridge_admitted_persona_feedback_to_heartbeat( Ok(bridged) } -fn load_persona_feedback_bridge_receipt( +fn load_persona_feedback_social_receipt( feedback_store: &Path, receipt_id: &str, -) -> Result> { +) -> Result> { let matches = SingleFileMessagePackBackingStore::new(feedback_store) .pull_all()? .into_iter() .filter(|entry| { - entry.r#type == ::TYPE + entry.r#type == ::TYPE && entry.key == receipt_id }) .collect::>(); if matches.len() > 1 { - bail!("duplicate Persona feedback heartbeat bridge receipt"); + bail!("duplicate Persona feedback social admission receipt"); } matches .into_iter() @@ -424,20 +424,20 @@ fn load_persona_feedback_bridge_receipt( .transpose() } -fn insert_pending_persona_feedback_bridge_receipt( +fn insert_pending_persona_feedback_social_receipt( feedback_store: &Path, - receipt: &PersonaFeedbackHeartbeatBridgeReceipt, + receipt: &PersonaFeedbackSocialAdmissionReceipt, ) -> Result { let mut cache = CultCache::new(); - cache.register_entry_type::()?; + cache.register_entry_type::()?; let (entry, _) = cache.prepare_entry(&receipt.receipt_id, receipt)?; if !SingleFileMessagePackBackingStore::new(feedback_store) .insert_entry_if_absent(entry.clone())? { - return load_persona_feedback_bridge_receipt(feedback_store, &receipt.receipt_id)? + return load_persona_feedback_social_receipt(feedback_store, &receipt.receipt_id)? .filter(|(existing, _)| existing == receipt) .map(|(_, envelope)| envelope) - .ok_or_else(|| anyhow!("Persona feedback heartbeat bridge pending receipt collision")); + .ok_or_else(|| anyhow!("Persona feedback social admission pending receipt collision")); } Ok(entry) } @@ -468,10 +468,10 @@ pub fn admitted_persona_feedback( Ok(feedback) } -/// Returns only admitted feedback whose exact Heartbeat bridge receipt proves +/// Returns only admitted feedback whose exact social-admission receipt proves /// that the configured provider disclosure policy allowed it to enter /// cognition. Admission authenticates transport; it does not grant disclosure. -pub fn bridged_persona_feedback_ready_for_cognition( +pub fn persona_feedback_ready_for_cognition( path: &Path, runtime_id: &str, ) -> Result> { @@ -480,17 +480,17 @@ pub fn bridged_persona_feedback_ready_for_cognition( if feedback.target_runtime_id != runtime_id { bail!("admitted Persona feedback escaped its target runtime"); } - let receipt_id = format!("persona-feedback-heartbeat:{}", feedback.feedback_id); - let Some((receipt, _)) = load_persona_feedback_bridge_receipt(path, &receipt_id)? else { + let receipt_id = format!("persona-feedback-social:{}", feedback.feedback_id); + let Some((receipt, _)) = load_persona_feedback_social_receipt(path, &receipt_id)? else { continue; }; let expected_mention_id = format!("bifrost-feedback:{}", feedback.feedback_id); - if receipt.schema_version != PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION + if receipt.schema_version != PERSONA_FEEDBACK_SOCIAL_ADMISSION_SCHEMA_VERSION || receipt.receipt_id != receipt_id || receipt.feedback_id != feedback.feedback_id || receipt.admission_id != feedback.admission_id || receipt.packet_sha256 != feedback.packet_sha256 - || receipt.heartbeat_mention_id != expected_mention_id + || receipt.social_mention_id != expected_mention_id || receipt.discord_channel_id != feedback.discord_channel_id || receipt.discord_message_id != feedback.discord_message_id || receipt.private_state_exposed @@ -940,10 +940,10 @@ mod tests { } #[test] - fn pending_bridge_receipt_recovers_once_and_preserves_discord_coordinates() -> Result<()> { + fn pending_social_admission_recovers_once_and_preserves_discord_coordinates() -> Result<()> { let temp = tempfile::tempdir()?; let feedback_store = temp.path().join("local.cc"); - let heartbeat_store = temp.path().join("heartbeat.cc"); + let social_store = temp.path().join("persona-social.cc"); let signer = crate::enroll_host_identity_at(&temp.path().join("bifrost.cc"))?; let anchor = crate::export_host_identity_trust_anchor( &signer, @@ -958,28 +958,26 @@ mod tests { "GameCult/Epiphany", "epiphany", )?; - crate::initialize_heartbeat_store(&heartbeat_store, 1.0)?; - let pending = PersonaFeedbackHeartbeatBridgeReceipt { - schema_version: PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION.into(), - receipt_id: format!("persona-feedback-heartbeat:{}", admitted.feedback_id), + let pending = PersonaFeedbackSocialAdmissionReceipt { + schema_version: PERSONA_FEEDBACK_SOCIAL_ADMISSION_SCHEMA_VERSION.into(), + receipt_id: format!("persona-feedback-social:{}", admitted.feedback_id), feedback_id: admitted.feedback_id.clone(), admission_id: admitted.admission_id.clone(), packet_sha256: admitted.packet_sha256.clone(), - heartbeat_mention_id: format!("bifrost-feedback:{}", admitted.feedback_id), + social_mention_id: format!("bifrost-feedback:{}", admitted.feedback_id), discord_channel_id: admitted.discord_channel_id.clone(), discord_message_id: admitted.discord_message_id.clone(), status: "pending".into(), private_state_exposed: false, }; - insert_pending_persona_feedback_bridge_receipt(&feedback_store, &pending)?; + insert_pending_persona_feedback_social_receipt(&feedback_store, &pending)?; assert!( - bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")? - .is_empty() + persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?.is_empty() ); - let recovered = bridge_admitted_persona_feedback_to_heartbeat( + let recovered = admit_persona_feedback_to_social( &feedback_store, - &heartbeat_store, + &social_store, "epiphany-yggdrasil", "openai-codex", &["public_feedback".to_string()], @@ -987,46 +985,38 @@ mod tests { assert_eq!(recovered.len(), 1); assert_eq!(recovered[0].status, "queued"); assert_eq!( - bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?, + persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?, vec![admitted] ); - let state = crate::load_heartbeat_state_entry(&heartbeat_store)?.expect("heartbeat state"); - assert_eq!(state.pending_mentions.len(), 1); - assert_eq!(state.pending_mentions[0].source_surface, "bifrost-discord"); - assert_eq!(state.pending_mentions[0].channel_id, "channel-1"); - assert_eq!(state.pending_mentions[0].message_id, "message-1"); + let mentions = crate::pending_persona_mentions(&social_store)?; + assert_eq!(mentions.len(), 1); + assert_eq!(mentions[0].source_surface, "bifrost-discord"); + assert_eq!(mentions[0].channel_id, "channel-1"); + assert_eq!(mentions[0].message_id, "message-1"); assert_eq!( - state.pending_mentions[0].reply_to_message_id.as_deref(), + mentions[0].reply_to_message_id.as_deref(), Some("message-1") ); - let mut consumed = state; - consumed.pending_mentions.clear(); - crate::write_heartbeat_state_entry(&heartbeat_store, &consumed)?; assert!( - bridge_admitted_persona_feedback_to_heartbeat( + admit_persona_feedback_to_social( &feedback_store, - &heartbeat_store, + &social_store, "epiphany-yggdrasil", "openai-codex", &["public_feedback".to_string()], )? .is_empty() ); - assert!( - crate::load_heartbeat_state_entry(&heartbeat_store)? - .expect("heartbeat state") - .pending_mentions - .is_empty() - ); + assert_eq!(crate::pending_persona_mentions(&social_store)?, mentions); Ok(()) } #[test] - fn bridge_refuses_receipt_substitution_before_queueing() -> Result<()> { + fn social_admission_refuses_receipt_substitution_before_queueing() -> Result<()> { let temp = tempfile::tempdir()?; let feedback_store = temp.path().join("local.cc"); - let heartbeat_store = temp.path().join("heartbeat.cc"); + let social_store = temp.path().join("persona-social.cc"); let signer = crate::enroll_host_identity_at(&temp.path().join("bifrost.cc"))?; let anchor = crate::export_host_identity_trust_anchor( &signer, @@ -1041,17 +1031,16 @@ mod tests { "GameCult/Epiphany", "epiphany", )?; - crate::initialize_heartbeat_store(&heartbeat_store, 1.0)?; - insert_pending_persona_feedback_bridge_receipt( + insert_pending_persona_feedback_social_receipt( &feedback_store, - &PersonaFeedbackHeartbeatBridgeReceipt { - schema_version: PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION.into(), - receipt_id: format!("persona-feedback-heartbeat:{}", admitted.feedback_id), + &PersonaFeedbackSocialAdmissionReceipt { + schema_version: PERSONA_FEEDBACK_SOCIAL_ADMISSION_SCHEMA_VERSION.into(), + receipt_id: format!("persona-feedback-social:{}", admitted.feedback_id), feedback_id: admitted.feedback_id, admission_id: admitted.admission_id, packet_sha256: "sha256-ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".into(), - heartbeat_mention_id: "bifrost-feedback:feedback-1".into(), + social_mention_id: "bifrost-feedback:feedback-1".into(), discord_channel_id: admitted.discord_channel_id, discord_message_id: admitted.discord_message_id, status: "pending".into(), @@ -1059,25 +1048,19 @@ mod tests { }, )?; assert!( - bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil") - .is_err() + persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil").is_err() ); assert!( - bridge_admitted_persona_feedback_to_heartbeat( + admit_persona_feedback_to_social( &feedback_store, - &heartbeat_store, + &social_store, "epiphany-yggdrasil", "openai-codex", &["public_feedback".to_string()], ) .is_err() ); - assert!( - crate::load_heartbeat_state_entry(&heartbeat_store)? - .expect("heartbeat state") - .pending_mentions - .is_empty() - ); + assert!(crate::pending_persona_mentions(&social_store)?.is_empty()); Ok(()) } @@ -1085,7 +1068,7 @@ mod tests { fn disclosure_policy_leaves_unapproved_feedback_admitted_but_unscheduled() -> Result<()> { let temp = tempfile::tempdir()?; let feedback_store = temp.path().join("local.cc"); - let heartbeat_store = temp.path().join("heartbeat.cc"); + let social_store = temp.path().join("persona-social.cc"); let signer = crate::enroll_host_identity_at(&temp.path().join("bifrost.cc"))?; let anchor = crate::export_host_identity_trust_anchor( &signer, @@ -1100,11 +1083,10 @@ mod tests { "GameCult/Epiphany", "epiphany", )?; - crate::initialize_heartbeat_store(&heartbeat_store, 1.0)?; assert!( - bridge_admitted_persona_feedback_to_heartbeat( + admit_persona_feedback_to_social( &feedback_store, - &heartbeat_store, + &social_store, "epiphany-yggdrasil", "openai-codex", &["organization_feedback".to_string()], @@ -1116,19 +1098,13 @@ mod tests { 1 ); assert!( - bridged_persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")? - .is_empty() + persona_feedback_ready_for_cognition(&feedback_store, "epiphany-yggdrasil")?.is_empty() ); + assert!(crate::pending_persona_mentions(&social_store)?.is_empty()); assert!( - crate::load_heartbeat_state_entry(&heartbeat_store)? - .expect("heartbeat state") - .pending_mentions - .is_empty() - ); - assert!( - load_persona_feedback_bridge_receipt( + load_persona_feedback_social_receipt( &feedback_store, - "persona-feedback-heartbeat:feedback-1" + "persona-feedback-social:feedback-1" )? .is_none() ); diff --git a/epiphany-core/src/persona_social_state.rs b/epiphany-core/src/persona_social_state.rs new file mode 100644 index 00000000..b62e58a1 --- /dev/null +++ b/epiphany-core/src/persona_social_state.rs @@ -0,0 +1,966 @@ +use anyhow::{Result, anyhow}; +use cultcache_rs::{ + CacheBackingStore, CultCache, CultCacheEnvelope, DatabaseEntry, + SingleFileMessagePackBackingStore, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::Digest; +use std::collections::{BTreeMap, HashSet}; +use std::path::Path; + +pub const PERSONA_TURN_REQUEST_SCHEMA_VERSION: &str = "epiphany.persona_turn_request.v1"; +pub const PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION: &str = + "epiphany.persona_turn_terminal_receipt.v1"; +pub const PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION: &str = + "epiphany.persona_conversation_retention_head.v1"; +pub const PERSONA_CONVERSATION_RETENTION_PLAN_SCHEMA_VERSION: &str = + "epiphany.persona_conversation_retention_plan.v1"; + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaSocialMention { + pub id: String, + pub target_role_id: String, + pub target_agent_id: String, + pub source_surface: String, + pub channel_id: String, + pub message_id: String, + pub author_id: String, + #[serde(default)] + pub author_name: Option, + pub content: String, + pub visible_prompt: String, + #[serde(default)] + pub reply_to_message_id: Option, + pub queued_at: String, + #[serde(default)] + pub source_visibility: String, + #[serde(default)] + pub data_classification: String, + #[serde(default)] + pub model_provider_id: String, + #[serde(default)] + pub model_provider_disclosure_allowed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaTurnRequest { + pub schema_version: String, + pub request_id: String, + pub schedule_id: String, + pub action_id: String, + pub role_id: String, + pub agent_id: String, + pub status: String, + pub reserved_at: String, + pub mentions: Vec, + #[serde(default)] + pub semantic_memory_recall: Value, + #[serde(default)] + pub terminal_receipt: Option, + pub private_state_exposed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaTurnTerminalReceipt { + pub schema_version: String, + pub receipt_id: String, + pub request_id: String, + pub schedule_id: String, + pub action_id: String, + pub outcome: String, + pub mention_disposition: String, + pub mention_ids: Vec, + pub mention_cargo_sha256: String, + #[serde(default)] + pub delivery_evidence_id: Option, + #[serde(default)] + pub crossing_receipt_id: Option, + #[serde(default)] + pub bridge_receipt_sha256: Option, + #[serde(default)] + pub blocked_crossing_status: Option, + #[serde(default)] + pub blocked_reason: Option, + pub completed_at: String, + pub private_state_exposed: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PersonaTurnTerminalOptions { + pub request_id: String, + pub outcome: String, + pub delivery_evidence: Option, + pub blocked_evidence: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaConversationRetentionHead { + pub schema_version: String, + pub revision: u64, + pub retired_turn_count: u64, + pub through_reserved_at: String, + pub chained_digest: String, + pub retained_at: String, + pub private_state_exposed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaConversationRetentionEnvelope { + pub envelope_type: String, + pub key: String, + pub envelope_sha256: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaConversationRetentionMember { + pub request_id: String, + pub reserved_at: String, + pub completed_at: String, + pub outcome: String, + pub terminal_receipt_sha256: String, + pub runtime_envelopes: Vec, + pub crossing_request_envelopes: Vec, + pub crossing_receipt_envelopes: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaConversationRetentionPlan { + pub schema_version: String, + pub plan_id: String, + pub members: Vec, + pub planned_at: String, + pub private_state_exposed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PersonaTurnBlockedEvidence { + pub evidence_source: String, + pub crossing_status: String, + pub reason: String, + pub crossing_receipt_id: Option, + pub bridge_receipt_sha256: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersonaBlockedConversationPressure { + pub schema_version: String, + pub quarantine_id: String, + pub request_id: String, + pub terminal_receipt_id: String, + pub crossing_status: String, + pub evidence_source: String, + pub reason: String, + pub mentions: Vec, + pub mention_cargo_sha256: String, + #[serde(default)] + pub crossing_receipt_id: Option, + #[serde(default)] + pub bridge_receipt_sha256: Option, + pub quarantined_at: String, + pub private_state_exposed: bool, +} + +pub const PERSONA_SOCIAL_MENTION_TYPE: &str = "epiphany.persona.social_mention.v1"; +pub const PERSONA_SOCIAL_TURN_REQUEST_TYPE: &str = "epiphany.persona.turn_request.v1"; +pub const PERSONA_SOCIAL_TURN_TERMINAL_TYPE: &str = "epiphany.persona.turn_terminal.v1"; +pub const PERSONA_SOCIAL_QUARANTINE_TYPE: &str = "epiphany.persona.quarantine.v1"; +pub const PERSONA_SOCIAL_RETENTION_HEAD_TYPE: &str = "epiphany.persona.retention_head.v1"; +pub const PERSONA_SOCIAL_RETENTION_PLAN_TYPE: &str = "epiphany.persona.retention_plan.v1"; +pub const PERSONA_SOCIAL_RETENTION_HEAD_KEY: &str = "persona"; +pub const PERSONA_SOCIAL_RETENTION_PLAN_KEY: &str = "active"; + +#[derive(Clone, Debug, PartialEq)] +pub struct PersonaSocialQueueMentionOptions { + pub target_role_id: String, + pub source_surface: String, + pub channel_id: String, + pub message_id: String, + pub author_id: String, + pub author_name: Option, + pub content: String, + pub visible_prompt: String, + pub reply_to_message_id: Option, + pub queued_at: Option, + pub mention_id: Option, + pub source_visibility: String, + pub data_classification: String, + pub model_provider_id: String, + pub model_provider_disclosure_allowed: bool, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.persona.social_mention.v1", + schema = "PersonaSocialMentionDocument" +)] +pub struct PersonaSocialMentionDocument { + #[cultcache(key = 0)] + pub status: String, + #[cultcache(key = 1)] + pub mention: PersonaSocialMention, + #[cultcache(key = 2)] + pub terminal_receipt_id: Option, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.persona.turn_request.v1", + schema = "PersonaSocialTurnRequestDocument" +)] +pub struct PersonaSocialTurnRequestDocument { + #[cultcache(key = 0)] + pub request: PersonaTurnRequest, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.persona.turn_terminal.v1", + schema = "PersonaSocialTurnTerminalDocument" +)] +pub struct PersonaSocialTurnTerminalDocument { + #[cultcache(key = 0)] + pub receipt: PersonaTurnTerminalReceipt, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.persona.quarantine.v1", + schema = "PersonaSocialQuarantineDocument" +)] +pub struct PersonaSocialQuarantineDocument { + #[cultcache(key = 0)] + pub pressure: PersonaBlockedConversationPressure, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.persona.retention_head.v1", + schema = "PersonaSocialRetentionHeadDocument" +)] +pub struct PersonaSocialRetentionHeadDocument { + #[cultcache(key = 0)] + pub head: PersonaConversationRetentionHead, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "epiphany.persona.retention_plan.v1", + schema = "PersonaSocialRetentionPlanDocument" +)] +pub struct PersonaSocialRetentionPlanDocument { + #[cultcache(key = 0)] + pub status: String, + #[cultcache(key = 1)] + pub plan: PersonaConversationRetentionPlan, +} + +pub fn persona_social_cache(store_path: impl AsRef) -> Result { + let mut cache = CultCache::new(); + register_persona_social_types(&mut cache)?; + let mut identities = HashSet::new(); + for envelope in SingleFileMessagePackBackingStore::new(store_path.as_ref()).pull_all()? { + if !is_persona_social_type(&envelope.r#type) { + continue; + } + if !identities.insert((envelope.r#type.clone(), envelope.key.clone())) { + return Err(anyhow!( + "Persona social store contains duplicate document type {:?} key {:?}", + envelope.r#type, + envelope.key + )); + } + load_persona_social_envelope(&mut cache, envelope)?; + } + Ok(cache) +} + +pub fn queue_persona_social_mention( + store_path: impl AsRef, + options: PersonaSocialQueueMentionOptions, +) -> Result { + if options.target_role_id != "Persona" { + return Err(anyhow!( + "Persona social mention target role must be Persona" + )); + } + validate_mention_text("content", &options.content, 4, 1200)?; + validate_mention_text("visible_prompt", &options.visible_prompt, 4, 1200)?; + for (label, value) in [ + ("source_surface", &options.source_surface), + ("channel_id", &options.channel_id), + ("message_id", &options.message_id), + ("author_id", &options.author_id), + ("source_visibility", &options.source_visibility), + ("data_classification", &options.data_classification), + ("model_provider_id", &options.model_provider_id), + ] { + validate_mention_text(label, value, 1, 240)?; + } + if !options.model_provider_disclosure_allowed { + return Err(anyhow!( + "pending mention is not authorized for disclosure to the configured model provider" + )); + } + let mention_id = options.mention_id.clone().unwrap_or_else(|| { + stable_pending_mention_id( + &options.target_role_id, + &options.channel_id, + &options.message_id, + &options.visible_prompt, + ) + }); + let document = PersonaSocialMentionDocument { + status: "pending".into(), + mention: PersonaSocialMention { + id: mention_id.clone(), + target_role_id: options.target_role_id.clone(), + target_agent_id: "epiphany.Persona".into(), + source_surface: options.source_surface, + channel_id: options.channel_id, + message_id: options.message_id, + author_id: options.author_id, + author_name: options.author_name, + content: options.content, + visible_prompt: options.visible_prompt, + reply_to_message_id: options.reply_to_message_id, + queued_at: options.queued_at.unwrap_or_else(now_iso), + source_visibility: options.source_visibility, + data_classification: options.data_classification, + model_provider_id: options.model_provider_id, + model_provider_disclosure_allowed: true, + }, + terminal_receipt_id: None, + }; + let store_path = store_path.as_ref(); + let cache = persona_social_cache(store_path)?; + if let Some(existing) = cache.get::(&mention_id)? { + if existing != document { + return Err(anyhow!( + "Persona social mention identity collision for {mention_id:?}" + )); + } + return Ok(serde_json::json!({ + "ok": true, + "queued": false, + "reason": "duplicate-pending-mention", + "mentionId": mention_id, + "pendingMentionCount": pending_persona_mentions(store_path)?.len(), + })); + } + let envelope = cache.prepare_entry(&mention_id, &document)?.0; + if !persona_social_backing(store_path).compare_and_swap_batch(&[], vec![envelope])? { + let current = + persona_social_cache(store_path)?.get::(&mention_id)?; + if current.as_ref() != Some(&document) { + return Err(anyhow!( + "Persona social mention lost exact insert compare-and-swap" + )); + } + } + Ok(serde_json::json!({ + "ok": true, + "queued": true, + "mentionId": mention_id, + "targetRoleId": options.target_role_id, + "pendingMentionCount": pending_persona_mentions(store_path)?.len(), + })) +} + +pub fn pulse_persona_social( + store_path: impl AsRef, + brake_engaged: bool, +) -> Result { + if brake_engaged { + return Ok(serde_json::json!({ + "schemaVersion": "epiphany.persona_social_pulse.v1", + "status": "refused-by-swarm-brake", + "privateStateExposed": false, + })); + } + let store_path = store_path.as_ref(); + let cache = persona_social_cache(store_path)?; + let mut mention_documents = cache + .get_all::()? + .into_iter() + .filter(|document| document.status == "pending") + .collect::>(); + mention_documents.sort_by(|left, right| { + left.mention + .queued_at + .cmp(&right.mention.queued_at) + .then_with(|| left.mention.id.cmp(&right.mention.id)) + }); + if persona_turn_requests(store_path)? + .iter() + .any(|request| request.terminal_receipt.is_none()) + { + return Ok(serde_json::json!({ + "schemaVersion": "epiphany.persona_social_pulse.v1", + "status": "already-running", + "privateStateExposed": false, + })); + } + if mention_documents.is_empty() { + return Ok(serde_json::json!({ + "schemaVersion": "epiphany.persona_social_pulse.v1", + "status": "idle", + "privateStateExposed": false, + })); + } + let mut schedule_digest = sha2::Sha256::new(); + schedule_digest.update(b"epiphany.persona-social-schedule.v1\0"); + schedule_digest.update(rmp_serde::to_vec(&mention_documents)?); + let schedule_id = format!("persona-schedule:sha256:{:x}", schedule_digest.finalize()); + let request_id = format!("persona-turn:{schedule_id}"); + let request = PersonaTurnRequest { + schema_version: PERSONA_TURN_REQUEST_SCHEMA_VERSION.into(), + request_id: request_id.clone(), + schedule_id: schedule_id.clone(), + action_id: "persona.turn".into(), + role_id: "Persona".into(), + agent_id: "epiphany.Persona".into(), + status: "reserved".into(), + reserved_at: now_iso(), + mentions: mention_documents + .iter() + .map(|document| document.mention.clone()) + .collect(), + semantic_memory_recall: serde_json::Value::Null, + terminal_receipt: None, + private_state_exposed: false, + }; + if let Some(head) = persona_retention_head(store_path)? { + let frontier = chrono::DateTime::parse_from_rfc3339(&head.through_reserved_at) + .map_err(|_| anyhow!("Persona conversation retention frontier is invalid"))?; + let reserved = chrono::DateTime::parse_from_rfc3339(&request.reserved_at) + .map_err(|_| anyhow!("Persona turn reservation time is invalid"))?; + if reserved <= frontier { + return Err(anyhow!( + "Persona turn reservation is at or behind the retired replay frontier" + )); + } + } + let mut expected = Vec::new(); + let mut writes = Vec::new(); + for mut document in mention_documents { + expected.push( + persona_social_envelope::(&cache, &document.mention.id) + .ok_or_else(|| anyhow!("pending Persona mention envelope disappeared"))?, + ); + document.status = "reserved".into(); + writes.push(cache.prepare_entry(&document.mention.id, &document)?.0); + } + writes.push( + cache + .prepare_entry( + &request_id, + &PersonaSocialTurnRequestDocument { + request: request.clone(), + }, + )? + .0, + ); + if !persona_social_backing(store_path).compare_and_swap_batch(&expected, writes)? { + return Err(anyhow!( + "Persona social pulse lost exact mention reservation compare-and-swap" + )); + } + Ok(serde_json::json!({ + "schemaVersion": "epiphany.persona_social_pulse.v1", + "status": "reserved", + "requestId": request_id, + "schedule": { + "schema_version": "epiphany.persona_social_schedule.v1", + "schedule_id": schedule_id, + "source_ref": "persona-social:pending", + "action_catalog": [{ + "action_id": request.action_id, + "actor_id": request.agent_id, + "action_type": "persona_turn", + "pending_mentions": request.mentions, + }], + }, + "privateStateExposed": false, + })) +} + +pub fn complete_persona_social_turn( + store_path: impl AsRef, + options: PersonaTurnTerminalOptions, +) -> Result { + let mention_disposition = match options.outcome.as_str() { + "delivered" | "silence" | "dropped" => "consumed", + "failed" => "retained", + "blocked" => "quarantined", + other => { + return Err(anyhow!( + "unsupported Persona turn terminal outcome {other:?}" + )); + } + }; + let store_path = store_path.as_ref(); + let cache = persona_social_cache(store_path)?; + let request_document = cache + .get::(&options.request_id)? + .ok_or_else(|| anyhow!("Persona turn request {:?} is missing", options.request_id))?; + let request = request_document.request; + if let Some(existing) = cache + .get::(&options.request_id)? + .map(|document| document.receipt) + { + if existing.outcome == options.outcome { + return Ok(existing); + } + return Err(anyhow!( + "Persona turn request {:?} already terminated as {:?}", + options.request_id, + existing.outcome + )); + } + let delivery_evidence = options.delivery_evidence.as_ref(); + let blocked_evidence = options.blocked_evidence.as_ref(); + if options.outcome == "delivered" { + let evidence = delivery_evidence.ok_or_else(|| { + anyhow!("delivered Persona turn requires typed Discord delivery evidence") + })?; + if evidence.schema_version != crate::PERSONA_DISCORD_DELIVERY_EVIDENCE_SCHEMA_VERSION + || evidence.private_state_exposed + || evidence.evidence_id.trim().is_empty() + || evidence.message_id.trim().is_empty() + || evidence.crossing_receipt_id.trim().is_empty() + || evidence.bridge_receipt_sha256.trim().is_empty() + || !request + .mentions + .iter() + .any(|mention| mention.channel_id == evidence.channel_id) + { + return Err(anyhow!( + "Discord delivery evidence is not bound to the Persona turn" + )); + } + } else if delivery_evidence.is_some() { + return Err(anyhow!( + "non-delivered Persona terminal outcome must not carry delivery evidence" + )); + } + if options.outcome == "blocked" { + let evidence = blocked_evidence + .ok_or_else(|| anyhow!("blocked Persona turn requires typed crossing evidence"))?; + if !matches!( + evidence.evidence_source.as_str(), + "bifrost_crossing" | "local_effect" + ) || !matches!(evidence.crossing_status.as_str(), "unknown" | "failed") + || (evidence.evidence_source == "local_effect" + && (evidence.crossing_receipt_id.is_some() + || evidence.bridge_receipt_sha256.is_some())) + || evidence.reason.trim().is_empty() + || evidence + .crossing_receipt_id + .as_deref() + .is_some_and(|value| value.trim().is_empty()) + || evidence + .bridge_receipt_sha256 + .as_deref() + .is_some_and(|value| { + !value.strip_prefix("sha256:").is_some_and(|digest| { + digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) + }) + { + return Err(anyhow!("blocked Persona crossing evidence is invalid")); + } + } else if blocked_evidence.is_some() { + return Err(anyhow!( + "non-blocked Persona terminal outcome must not carry blocked evidence" + )); + } + let receipt = PersonaTurnTerminalReceipt { + schema_version: PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION.into(), + receipt_id: format!("{}:terminal", request.request_id), + request_id: request.request_id.clone(), + schedule_id: request.schedule_id.clone(), + action_id: request.action_id.clone(), + outcome: options.outcome, + mention_disposition: mention_disposition.into(), + mention_ids: request + .mentions + .iter() + .map(|mention| mention.id.clone()) + .collect(), + mention_cargo_sha256: format!( + "sha256-{:x}", + sha2::Sha256::digest(rmp_serde::to_vec(&request.mentions)?) + ), + delivery_evidence_id: delivery_evidence.map(|evidence| evidence.evidence_id.clone()), + crossing_receipt_id: delivery_evidence.map(|evidence| evidence.crossing_receipt_id.clone()), + bridge_receipt_sha256: delivery_evidence + .map(|evidence| evidence.bridge_receipt_sha256.clone()), + blocked_crossing_status: blocked_evidence.map(|evidence| evidence.crossing_status.clone()), + blocked_reason: blocked_evidence.map(|evidence| evidence.reason.clone()), + completed_at: now_iso(), + private_state_exposed: false, + }; + let request_envelope = + persona_social_envelope::(&cache, &request.request_id) + .ok_or_else(|| anyhow!("Persona turn request envelope disappeared"))?; + let mut expected = vec![request_envelope.clone()]; + let mut writes = vec![ + request_envelope, + cache + .prepare_entry( + &request.request_id, + &PersonaSocialTurnTerminalDocument { + receipt: receipt.clone(), + }, + )? + .0, + ]; + for mention in &request.mentions { + let mut document = cache + .get::(&mention.id)? + .ok_or_else(|| anyhow!("Persona reserved mention {:?} is missing", mention.id))?; + if document.status != "reserved" || document.mention != *mention { + return Err(anyhow!( + "Persona reserved mention {:?} changed before terminalization", + mention.id + )); + } + expected.push( + persona_social_envelope::(&cache, &mention.id) + .ok_or_else(|| anyhow!("Persona mention envelope disappeared"))?, + ); + document.status = match mention_disposition { + "retained" => "pending", + "consumed" => "consumed", + "quarantined" => "quarantined", + _ => unreachable!("closed mention disposition"), + } + .into(); + document.terminal_receipt_id = Some(receipt.receipt_id.clone()); + writes.push(cache.prepare_entry(&mention.id, &document)?.0); + } + if mention_disposition == "quarantined" { + let evidence = blocked_evidence.expect("validated blocked evidence"); + let pressure = PersonaBlockedConversationPressure { + schema_version: "epiphany.persona_blocked_conversation_pressure.v1".into(), + quarantine_id: format!("{}:quarantine", request.request_id), + request_id: request.request_id.clone(), + terminal_receipt_id: receipt.receipt_id.clone(), + crossing_status: evidence.crossing_status.clone(), + evidence_source: evidence.evidence_source.clone(), + reason: evidence.reason.clone(), + mentions: request.mentions.clone(), + mention_cargo_sha256: receipt.mention_cargo_sha256.clone(), + crossing_receipt_id: evidence.crossing_receipt_id.clone(), + bridge_receipt_sha256: evidence.bridge_receipt_sha256.clone(), + quarantined_at: receipt.completed_at.clone(), + private_state_exposed: false, + }; + let quarantine_id = pressure.quarantine_id.clone(); + writes.push( + cache + .prepare_entry( + &quarantine_id, + &PersonaSocialQuarantineDocument { pressure }, + )? + .0, + ); + } + if !persona_social_backing(store_path).compare_and_swap_batch(&expected, writes)? { + return Err(anyhow!( + "Persona terminal decision lost exact document compare-and-swap" + )); + } + Ok(receipt) +} + +pub fn pending_persona_mentions(store_path: impl AsRef) -> Result> { + let cache = persona_social_cache(store_path)?; + let mut mentions = cache + .get_all::()? + .into_iter() + .filter(|document| document.status == "pending") + .map(|document| document.mention) + .collect::>(); + mentions.sort_by(|left, right| { + left.queued_at + .cmp(&right.queued_at) + .then_with(|| left.id.cmp(&right.id)) + }); + Ok(mentions) +} + +pub fn persona_turn_requests(store_path: impl AsRef) -> Result> { + let cache = persona_social_cache(store_path)?; + let terminals = cache + .get_all::()? + .into_iter() + .map(|document| (document.receipt.request_id.clone(), document.receipt)) + .collect::>(); + let mut requests = cache + .get_all::()? + .into_iter() + .map(|document| { + let mut request = document.request; + if let Some(terminal) = terminals.get(&request.request_id) { + request.status = "terminal".into(); + request.terminal_receipt = Some(terminal.clone()); + request.mentions.clear(); + request.semantic_memory_recall = serde_json::Value::Null; + } + request + }) + .collect::>(); + requests.sort_by(|left, right| { + left.reserved_at + .cmp(&right.reserved_at) + .then_with(|| left.request_id.cmp(&right.request_id)) + }); + Ok(requests) +} + +pub fn persona_turn_request( + store_path: impl AsRef, + request_id: &str, +) -> Result> { + Ok(persona_turn_requests(store_path)? + .into_iter() + .find(|request| request.request_id == request_id)) +} + +pub fn persona_turn_request_source( + store_path: impl AsRef, + request_id: &str, +) -> Result { + let cache = persona_social_cache(store_path)?; + let envelope = persona_social_envelope::(&cache, request_id) + .ok_or_else(|| anyhow!("Persona social request {request_id:?} is missing"))?; + crate::EpiphanyMindDocumentVersion::from_envelope("epiphany-persona-social", &envelope) +} + +pub fn blocked_persona_pressures( + store_path: impl AsRef, +) -> Result> { + let cache = persona_social_cache(store_path)?; + let mut pressures = cache + .get_all::()? + .into_iter() + .map(|document| document.pressure) + .collect::>(); + pressures.sort_by(|left, right| left.quarantine_id.cmp(&right.quarantine_id)); + Ok(pressures) +} + +pub fn persona_retention_head( + store_path: impl AsRef, +) -> Result> { + Ok(persona_social_cache(store_path)? + .get::(PERSONA_SOCIAL_RETENTION_HEAD_KEY)? + .map(|document| document.head)) +} + +pub fn persona_retention_plan( + store_path: impl AsRef, +) -> Result> { + Ok(persona_social_cache(store_path)? + .get::(PERSONA_SOCIAL_RETENTION_PLAN_KEY)? + .filter(|document| document.status == "active") + .map(|document| document.plan)) +} + +pub fn put_persona_retention_plan( + store_path: impl AsRef, + plan: &PersonaConversationRetentionPlan, +) -> Result<()> { + let store_path = store_path.as_ref(); + let cache = persona_social_cache(store_path)?; + if let Some(existing) = + cache.get::(PERSONA_SOCIAL_RETENTION_PLAN_KEY)? + { + if existing.status == "active" { + if existing.plan == *plan { + return Ok(()); + } + return Err(anyhow!( + "a different Persona retention plan is already active" + )); + } + } + let expected = persona_social_envelope::( + &cache, + PERSONA_SOCIAL_RETENTION_PLAN_KEY, + ) + .into_iter() + .collect::>(); + let replacement = cache + .prepare_entry( + PERSONA_SOCIAL_RETENTION_PLAN_KEY, + &PersonaSocialRetentionPlanDocument { + status: "active".into(), + plan: plan.clone(), + }, + )? + .0; + if !persona_social_backing(store_path).compare_and_swap_batch(&expected, vec![replacement])? { + return Err(anyhow!( + "Persona retention plan lost exact compare-and-swap" + )); + } + Ok(()) +} + +pub fn complete_persona_retention_plan( + store_path: impl AsRef, + plan: &PersonaConversationRetentionPlan, + head: &PersonaConversationRetentionHead, +) -> Result<()> { + let store_path = store_path.as_ref(); + let cache = persona_social_cache(store_path)?; + let current = cache + .get::(PERSONA_SOCIAL_RETENTION_PLAN_KEY)? + .ok_or_else(|| anyhow!("Persona retention plan is missing"))?; + if current.status == "completed" + && current.plan == *plan + && persona_retention_head(store_path)?.as_ref() == Some(head) + { + return Ok(()); + } + if current.status != "active" || current.plan != *plan { + return Err(anyhow!("Persona retention plan changed before completion")); + } + let mut expected = vec![ + persona_social_envelope::( + &cache, + PERSONA_SOCIAL_RETENTION_PLAN_KEY, + ) + .ok_or_else(|| anyhow!("Persona retention plan envelope disappeared"))?, + ]; + if let Some(envelope) = persona_social_envelope::( + &cache, + PERSONA_SOCIAL_RETENTION_HEAD_KEY, + ) { + expected.push(envelope); + } + let writes = vec![ + cache + .prepare_entry( + PERSONA_SOCIAL_RETENTION_PLAN_KEY, + &PersonaSocialRetentionPlanDocument { + status: "completed".into(), + plan: plan.clone(), + }, + )? + .0, + cache + .prepare_entry( + PERSONA_SOCIAL_RETENTION_HEAD_KEY, + &PersonaSocialRetentionHeadDocument { head: head.clone() }, + )? + .0, + ]; + if !persona_social_backing(store_path).compare_and_swap_batch(&expected, writes)? { + return Err(anyhow!( + "Persona retention completion lost exact compare-and-swap" + )); + } + Ok(()) +} + +pub(crate) fn persona_social_envelope( + cache: &CultCache, + key: &str, +) -> Option { + cache + .snapshot_envelopes() + .into_iter() + .find(|envelope| envelope.r#type == T::TYPE && envelope.key == key) +} + +pub(crate) fn persona_social_backing( + store_path: impl AsRef, +) -> SingleFileMessagePackBackingStore { + SingleFileMessagePackBackingStore::new(store_path.as_ref()) +} + +fn register_persona_social_types(cache: &mut CultCache) -> Result<()> { + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + cache.register_entry_type::()?; + Ok(()) +} + +fn is_persona_social_type(document_type: &str) -> bool { + [ + PERSONA_SOCIAL_MENTION_TYPE, + PERSONA_SOCIAL_TURN_REQUEST_TYPE, + PERSONA_SOCIAL_TURN_TERMINAL_TYPE, + PERSONA_SOCIAL_QUARANTINE_TYPE, + PERSONA_SOCIAL_RETENTION_HEAD_TYPE, + PERSONA_SOCIAL_RETENTION_PLAN_TYPE, + ] + .contains(&document_type) +} + +fn load_persona_social_envelope(cache: &mut CultCache, envelope: CultCacheEnvelope) -> Result<()> { + match envelope.r#type.as_str() { + PERSONA_SOCIAL_MENTION_TYPE => { + cache.load_envelope::(envelope)?; + } + PERSONA_SOCIAL_TURN_REQUEST_TYPE => { + cache.load_envelope::(envelope)?; + } + PERSONA_SOCIAL_TURN_TERMINAL_TYPE => { + cache.load_envelope::(envelope)?; + } + PERSONA_SOCIAL_QUARANTINE_TYPE => { + cache.load_envelope::(envelope)?; + } + PERSONA_SOCIAL_RETENTION_HEAD_TYPE => { + cache.load_envelope::(envelope)?; + } + PERSONA_SOCIAL_RETENTION_PLAN_TYPE => { + cache.load_envelope::(envelope)?; + } + _ => unreachable!("caller filtered Persona social document types"), + } + Ok(()) +} + +fn validate_mention_text(label: &str, value: &str, min_len: usize, max_len: usize) -> Result<()> { + let trimmed = value.trim(); + if trimmed.len() < min_len || value.len() > max_len { + return Err(anyhow!( + "pending mention {label} must be between {min_len} and {max_len} UTF-8 bytes" + )); + } + Ok(()) +} + +fn stable_pending_mention_id( + role_id: &str, + channel_id: &str, + message_id: &str, + visible_prompt: &str, +) -> String { + let mut hash = 5381_u64; + for byte in format!("{role_id}\0{channel_id}\0{message_id}\0{visible_prompt}").as_bytes() { + hash = ((hash << 5).wrapping_add(hash)).wrapping_add(*byte as u64); + } + format!("mention-{hash:016x}") +} + +fn now_iso() -> String { + chrono::Utc::now().to_rfc3339() +} diff --git a/epiphany-core/src/persona_turn.rs b/epiphany-core/src/persona_turn.rs index 1cae4b5b..5b708d85 100644 --- a/epiphany-core/src/persona_turn.rs +++ b/epiphany-core/src/persona_turn.rs @@ -1,6 +1,6 @@ use crate::EpiphanyMindPersonaMemoryDocument; use crate::EpiphanyOrganDependency; -use crate::HeartbeatPendingMention; +use crate::PersonaSocialMention; use crate::default_organ_dependencies_for; use crate::render_organ_dependencies; use anyhow::Result; @@ -243,7 +243,7 @@ pub struct PersonaProjectorInput { #[serde(default)] pub semantic_memory_recall: String, #[serde(default)] - pub pending_mentions: Vec, + pub pending_mentions: Vec, #[serde(default)] pub repo_activity: Vec, #[serde(default)] @@ -270,7 +270,7 @@ pub struct PersonaInterpreterInput { #[serde(default)] pub dynamic_semantic_memory_recall: String, #[serde(default)] - pub pending_mentions: Vec, + pub pending_mentions: Vec, #[serde(default)] pub allowed_channel_ids: Vec, } @@ -615,7 +615,7 @@ fn render_memory_packet(memories: &[EpiphanyMindPersonaMemoryDocument]) -> Strin .join("\n") } -fn render_pending_mentions(mentions: &[HeartbeatPendingMention]) -> String { +fn render_pending_mentions(mentions: &[PersonaSocialMention]) -> String { if mentions.is_empty() { return "- none".to_string(); } @@ -732,7 +732,7 @@ mod tests { #[test] fn persona_turn_has_projector_and_interpreter_membranes() { - let pending = HeartbeatPendingMention { + let pending = PersonaSocialMention { id: "mention-1".to_string(), target_role_id: "Persona".to_string(), target_agent_id: "epiphany.Persona".to_string(), diff --git a/epiphany-core/src/resident_self.rs b/epiphany-core/src/resident_self.rs index f8f2a322..3747f5a7 100644 --- a/epiphany-core/src/resident_self.rs +++ b/epiphany-core/src/resident_self.rs @@ -955,8 +955,7 @@ pub fn materialize_resident_self_domain_obligations( workspace, &requested_at, )?; - for feedback in - crate::bridged_persona_feedback_ready_for_cognition(persona_feedback_store, runtime_id)? + for feedback in crate::persona_feedback_ready_for_cognition(persona_feedback_store, runtime_id)? { let Some(_request) = crate::commit_imagination_consideration_request( runtime_store, diff --git a/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs b/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs index 30381010..93b1f4b3 100644 --- a/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs +++ b/epiphany-openai-runtime/src/bin/epiphany-persona-service.rs @@ -1,21 +1,21 @@ use std::{env, net::SocketAddr, path::PathBuf, thread, time::Duration}; use anyhow::{Context, Result, anyhow}; -use cultcache_rs::{CacheBackingStore, DatabaseEntry, SingleFileMessagePackBackingStore}; +use cultcache_rs::DatabaseEntry; +#[cfg(test)] +use epiphany_core::EpiphanyMindDocumentVersion; use epiphany_core::{ - EpiphanyHeartbeatStateEntry, EpiphanyMindDocumentVersion, EpiphanyMindPersonaMemoryDocument, - EpiphanyMindPersonaPassInputDocument, PersonaIdentity, PersonaProjectorInput, - PersonaRepoActivity, PersonaSocialAffordance, PersonaTranscriptMessage, PersonaTurnRequest, - PersonaTurnTerminalOptions, admit_persona_pass_input, assemble_mind_view, - complete_persona_turn_request_store, default_organ_dependencies_for, + EpiphanyMindPersonaMemoryDocument, EpiphanyMindPersonaPassInputDocument, PersonaIdentity, + PersonaProjectorInput, PersonaRepoActivity, PersonaSocialAffordance, PersonaTranscriptMessage, + PersonaTurnRequest, PersonaTurnTerminalOptions, admit_persona_pass_input, assemble_mind_view, + complete_persona_social_turn, default_organ_dependencies_for, exchange_persona_discord_delivery_rudp, load_admitted_persona_pass_input, - load_epiphany_cultmesh_swarm_brake, - load_heartbeat_state_entry, load_persona_discord_receipt_anchor, + load_epiphany_cultmesh_swarm_brake, load_persona_discord_receipt_anchor, load_persona_discord_service_anchor, open_persona_discord_request_identity, pending_persona_discord_delivery_request_for_turn, persona_delivery_receipt_exists_for_turn, - persona_model_terminal_exists, poll_persona_discord_crossing, - reconcile_terminal_persona_conversation, retain_terminal_persona_conversations, - semantic_memory_recall_from_heartbeat_action, validate_persona_discord_request_anchor, + persona_model_terminal_exists, persona_turn_request_source, persona_turn_requests, + poll_persona_discord_crossing, pulse_persona_social, reconcile_terminal_persona_conversation, + retain_terminal_persona_conversations, validate_persona_discord_request_anchor, }; use epiphany_openai_runtime::{ NativePersonaModelRunner, PersonaModelExecutionPlan, execute_persona_model_turn, @@ -42,32 +42,29 @@ async fn poll_once(options: &Options) -> Result { if brake.status != "released" { return Ok(false); } + let pulse = pulse_persona_social(&options.social_store, false)?; let receipt_anchor = load_persona_discord_receipt_anchor(&options.mouth_receipt_anchor)?; retain_terminal_persona_conversations( &options.runtime_store, - &options.heartbeat_store, + &options.social_store, &options.mouth_request_store, &options.mouth_receipt_store, &receipt_anchor, options.retained_terminal_conversations, &chrono::Utc::now().to_rfc3339(), )?; - let Some(state) = load_heartbeat_state_entry(&options.heartbeat_store)? else { - return Ok(false); - }; - for request in state - .persona_turn_requests + let requests = persona_turn_requests(&options.social_store)?; + for request in requests .iter() .filter(|request| request.terminal_receipt.is_some()) { reconcile_terminal_persona_conversation( &options.runtime_store, - &options.heartbeat_store, + &options.social_store, &request.request_id, )?; } - let mut candidates = state - .persona_turn_requests + let mut candidates = requests .into_iter() .filter(|request| request.status == "reserved" && request.terminal_receipt.is_none()) .collect::>(); @@ -88,7 +85,7 @@ async fn poll_once(options: &Options) -> Result { } }); let Some(request) = candidates.into_iter().next() else { - return Ok(false); + return Ok(pulse["status"] != "idle"); }; ensure_persona_pass_input_admitted(options, &request)?; let plan = PersonaModelExecutionPlan::from_admitted_input( @@ -111,8 +108,8 @@ async fn poll_once(options: &Options) -> Result { Ok(receipt) => receipt, Err(error) if error.to_string().contains("braked") => return Ok(false), Err(error) => { - complete_persona_turn_request_store( - &options.heartbeat_store, + complete_persona_social_turn( + &options.social_store, PersonaTurnTerminalOptions { request_id: request.request_id, outcome: "failed".into(), @@ -133,7 +130,7 @@ async fn poll_once(options: &Options) -> Result { } let mut result = poll_persona_discord_crossing( &options.runtime_store, - &options.heartbeat_store, + &options.social_store, &options.cultmesh_store, &options.runtime_id, &options.mouth_request_store, @@ -161,7 +158,7 @@ async fn poll_once(options: &Options) -> Result { Ok(_) => { result = poll_persona_discord_crossing( &options.runtime_store, - &options.heartbeat_store, + &options.social_store, &options.cultmesh_store, &options.runtime_id, &options.mouth_request_store, @@ -216,9 +213,7 @@ fn ensure_persona_pass_input_admitted( timestamp: mention.queued_at.clone(), }) .collect::>(); - let semantic_recall = semantic_memory_recall_from_heartbeat_action( - &serde_json::json!({"persona_memory_recall": request.semantic_memory_recall}), - ); + let semantic_recall = String::new(); let social_affordances = request .mentions .iter() @@ -253,14 +248,8 @@ fn ensure_persona_pass_input_admitted( social_affordances, organ_dependencies: vec![default_organ_dependencies_for("Persona")], }; - let heartbeat_envelope = SingleFileMessagePackBackingStore::new(&options.heartbeat_store) - .pull_all()? - .into_iter() - .find(|entry| entry.r#type == EpiphanyHeartbeatStateEntry::TYPE) - .ok_or_else(|| anyhow!("Persona pass input lost its heartbeat source"))?; - let heartbeat_source = - EpiphanyMindDocumentVersion::from_envelope("epiphany-heartbeat", &heartbeat_envelope)?; - let mut observed_sources = vec![heartbeat_source.clone()]; + let social_source = persona_turn_request_source(&options.social_store, &request.request_id)?; + let mut observed_sources = vec![social_source.clone()]; for memory in &memories { let source = mind .source_documents @@ -294,7 +283,7 @@ fn ensure_persona_pass_input_admitted( observed_sources, admitted_at: request.reserved_at.clone(), }; - admit_persona_pass_input(&options.runtime_store, heartbeat_source, &document)?; + admit_persona_pass_input(&options.runtime_store, social_source, &document)?; load_admitted_persona_pass_input(&options.runtime_store, &request.request_id)? .ok_or_else(|| anyhow!("Persona pass input admission was not durable"))?; Ok(()) @@ -302,7 +291,7 @@ fn ensure_persona_pass_input_admitted( struct Options { runtime_store: PathBuf, - heartbeat_store: PathBuf, + social_store: PathBuf, cultmesh_store: PathBuf, codex_home: PathBuf, provider_credential_path: Option, @@ -349,7 +338,7 @@ impl Options { }; Ok(Self { runtime_store: path("--runtime-store")?, - heartbeat_store: path("--heartbeat-store")?, + social_store: path("--persona-social-store")?, cultmesh_store: path("--cultmesh-store")?, codex_home: path("--codex-home")?, provider_credential_path: values.get("--provider-credential").map(PathBuf::from), @@ -449,7 +438,7 @@ mod tests { let absent = temp.path().join("intentionally-absent"); let options = Options { runtime_store: runtime_store.clone(), - heartbeat_store: absent.join("heartbeat.cc"), + social_store: absent.join("persona-social.cc"), cultmesh_store: absent.join("cultmesh.cc"), codex_home: absent.join("codex-home"), provider_credential_path: None, diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 2973d556..9e5e4dd9 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -286,19 +286,20 @@ identity/generation store, utterance vector, and generic self-patch admission. When no explicit typed pressure exists, heartbeat sleeps and authors no Mind state. -Exact `2164bd0a` removes the unowned scheduler generality. Heartbeat has only -two live participants: Resident Self and Persona. Ghostlight scene scheduling, -generic tick/pump/heat/complete controls, adaptive pacing, initiative heat, and -their public intent schemas are gone. Modeling, Eyes, Hands, Soul, and -Imagination route from typed current-work obligations and never acquire idle -heartbeat lanes. +Exact `2164bd0a` removes the unowned scheduler generality. Heartbeat has one +live participant: Resident Self. Ghostlight scene scheduling, generic +tick/pump/heat/complete controls, adaptive pacing, initiative heat, and their +public intent schemas are gone. Modeling, Eyes, Hands, Soul, and Imagination +route from typed current-work obligations and never acquire idle heartbeat +lanes. -One conflict domain remains under audit: `EpiphanyHeartbeatStateEntry` stores -coordinator/Persona readiness and history together with pending Persona -mentions, Persona turn requests, blocked social pressure, and Persona retention -state. These are not one invariant. The social collection members must become -keyed identities so Persona transport cannot make scheduler acknowledgement -stale or be blocked by it. +Persona owns a separate keyed social corpus. Each mention, immutable turn +request, terminal receipt, quarantine record, retention head, and retention +plan has its own CultCache identity. The Persona daemon derives an exact request +from pending mentions, reserves them through batch CAS, and cites that request +envelope as the observed source of its admitted pass input. Failed turns make +the mention pending with the terminal receipt bound into its next deterministic +request identity. Heartbeat cannot launch, block, or terminalize Persona work. ## RepoModel and semantic projection diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 438255ab..036c3774 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -491,20 +491,30 @@ passes 455/455 and the provider runtime passes 27/27. The obsolete repository- local Cargo target was 2.5 GiB and was removed; compilation remains in the shared target. -Exact `2164bd0a` collapses heartbeat to Resident Self and Persona scheduling. +Exact `2164bd0a` first collapsed heartbeat to Resident Self and Persona scheduling. It deletes Ghostlight scene scheduling, manual tick/pump/heat/complete and queue-mention controls, adaptive pacing/initiative heat, five fake organ lanes, five dead schemas, and eight self-referential tests: 2,145 deletions against 118 additions. The strict heartbeat state is now `v1`; the owning binary checks cleanly and the surviving core suite passes 448/448. -Next split pending Persona mentions, turn requests/terminal receipts, blocked -social pressure, and retention head/plan from the heartbeat singleton into -keyed CultCache identities. Heartbeat may consume a derived pressure view but -must not own social state. Continue deleting constructor/projection-copy tests -as their dead surfaces are exposed. Do not run a full-workspace compile, -package, deployment, or Ox root until the subtraction audit closes. Never -resume Ox10, Ox12, Ox13, Ox15, or Ox16. +The current source cut completes the separation. Pending Persona mentions, +immutable requests, terminal receipts, quarantine records, and retention state +are keyed CultCache documents. Persona derives and reserves its own work; the +heartbeat daemon has no Persona path. The exact social request envelope is the +pass-input provenance. Failed turns produce a new deterministic retry identity, +and retention excludes its immutable retired frontier instead of deleting +decision history. The old heartbeat bridge/terminal names and writable types +have no compatibility reader. + +Next audit whether a singleton one-participant heartbeat scheduler still earns +its state, selection, projection, artifact-retention, stale-repair, grant, and +ack machinery. Map the Resident Self grant lifecycle first; delete heartbeat +state if Resident Self already owns exclusion and terminality. Continue +deleting tests that prove constructors, field copies, or boolean helpers rather +than named invariants. Do not run a full-workspace compile, package, deployment, +or Ox root until the subtraction audit closes. Never resume Ox10, Ox12, Ox13, +Ox15, or Ox16. ## Operational state that matters diff --git a/schemas/cultnet/epiphany.agent-heartbeat.schema.json b/schemas/cultnet/epiphany.agent-heartbeat.schema.json index c2866a08..c7806efa 100644 --- a/schemas/cultnet/epiphany.agent-heartbeat.schema.json +++ b/schemas/cultnet/epiphany.agent-heartbeat.schema.json @@ -2,7 +2,7 @@ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.agent-heartbeat.schema.json", "title": "Epiphany Heartbeat State", - "description": "Typed scheduling physiology for Resident Self grants and Persona turns.", + "description": "Typed scheduling physiology for Resident Self grants.", "type": "object", "additionalProperties": false, "properties": { diff --git a/schemas/heartbeat-state-schema.md b/schemas/heartbeat-state-schema.md index cf39628e..8f84390c 100644 --- a/schemas/heartbeat-state-schema.md +++ b/schemas/heartbeat-state-schema.md @@ -14,11 +14,10 @@ law lives in `heartbeat_state.rs` and `heartbeat_store.rs`. - schema version: `epiphany.agent_heartbeat.v1` - key: `default` -The singleton currently carries coordinator/Persona readiness, pending turns, -bounded scheduling history, explicit Persona transport pressure, and retention -bookkeeping. The remaining social fields are the next ownership cut: they must -become keyed Persona documents so social writes do not share the scheduler CAS -identity. +The singleton carries Resident Self scheduler readiness, one pending turn, and +bounded scheduling history. Persona social state is not part of this document. +Pending mentions, immutable turn requests, terminal receipts, quarantine +records, and retention state are keyed CultCache documents owned by Persona. ## Scheduling invariants @@ -26,16 +25,17 @@ identity. - Cooldown begins after terminal completion, not at launch. - Resident Self pressure may wake the coordinator; heartbeat does not create that pressure. -- Persona may wake only from explicit queued social pressure. -- The swarm brake prevents new Persona cognition while allowing terminal +- The swarm brake prevents new Resident Self cognition while allowing terminal acknowledgement and recovery physiology to settle. -- When no typed obligation or social pressure exists, the scheduler sleeps. +- When no typed obligation exists, the scheduler sleeps. Heartbeat owns no personality, mood, appraisal, rumination, dreaming, memory graph, utterance vector, or generic self-modification surface. Durable Persona memory and social interpretation are keyed Mind documents admitted through the -Persona decision context. Work for Modeling, Eyes, Hands, Soul, and Imagination -comes from the pure current-work projection over typed state obligations. +Persona decision context. Persona derives its own current turn from pending +keyed social documents; heartbeat cannot launch, block, or terminalize it. Work +for Modeling, Eyes, Hands, Soul, and Imagination comes from the pure +current-work projection over typed state obligations. JSON emitted by the heartbeat CLI is an operator artifact only. CultCache documents remain authority. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index b8f617c9b0ba455fc41b328d7396154f90850a70..4c9b2c10d8302c056d1507a5c56409c4b7203083 100644 GIT binary patch delta 591 zcmYLGJ#Q016y$6INkKt_l!E9<6ru1r{t}AfDp;Zhkt*H0y=T12-tKwdu4AWhk%B*f z6?*;v5(VN9QT`-|jR|D-=S>GsZVAMM?J`|&E7 zCdu#XRpaxjkqD}_DR?Z{5j+t*73}_8HTIf+pMUw)>-65Fo#V9EKkJCr&4+{L%VqNK zJ$ZH(ft}K50ArXqufqZ~1D8ez7<*U1gwThKFo3qf!38ZShfy?Pgla-ikPX_|7I>OQ z;?ROXzR(s;3#Ji0%C)5ypv`3@tfwJgIu$D_w_)qUU0Q}*Mk>1Ipp_7q{0yrHY5|&~ z3J(v!==9?df|w|g88T#Xu5=)-57)z+bQ^a-c1FgP^tui2qA_4ad`6(0C*UaDT1ylL zgX1H?@Md|nyT9a1^aW%R%WJum;Ob)d;M`LxQT$@d?H+a8a3;Pm=29cgOUF`LRl!)# zWmjlsZ9i>0leIJ`#ao%J5@s0Gq>3lKDKYq#(mJB>l##4@tX190x>sEkF<@rsf5WN# LoitB=quss-FO$=h delta 71 zcmX^1SAE7$^$lW-yhc{WKx71JidLPo}S%~P4$r!p}DF^FacViq7~1!6WJ PW(Q)9?NgaJnSTKQbzv7f diff --git a/state/map.yaml b/state/map.yaml index 841fe39c..27d6e671 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -49,6 +49,7 @@ current_status: summary: The keyed RepoModel hard cut, decision-context foundation, Model Atlas code slice, complete Body, Proposal, frontier-verdict Modeling, frontier Research, frontier Verification, frontier Planning/PlanMind, Reorientation, and Persona decision-context lifecycles are landed on codex/epiphany-shakedown-live. Keyed Mind plus exact runtime receipts own coordinator presence, work discovery, deterministic launch, job-bound continuation, review, typed failure, semantic admission, and retained decision reachability. Exact 07d891ba and ec1431ff delete the persisted/global thread aggregate and its generic coordinator/prompt/revision surfaces. Exact f7948795 deletes MindGatewayReview, MindStateCommitReceipt v0, the generic interpreter prompt, runtime registration/read APIs, false thought/state-effect/adoption CultNet mouths, and stale launch proof profiles. CultMesh now projects only reasoning basis, decision context, and exact Mind commit receipt, read-only. Exact 1c9aafd8 seals the terminal decision context before model-backed frontier-Planning failure and binds the typed failure plus generic job result to it. Exact e0e75a30 deletes the residual aggregate role patch/parser/policy surface, gives Research one closed typed decision, and deletes the unowned generic Imagination planning patch. Exact 12b1b285 makes runtime model/tool binding validation the shared owner for execution and decision sealing; hostile provider, receipt, and stored-binding substitutions refuse, while retained basis/context audit survives transcript-delta deletion. Exact 01602fd3 advances Mind/runtime to v2/v1 and refuses historical or split writable identity pairs before registered writers see them. Exact 26b6a5bf proves simultaneous disjoint Modeling writes, simultaneous Verification+Modeling admission, same-identity conflict, exact replay, and reopened graph assembly; raw mutation primitives are crate-private. Exact 7c2ebd81 moves Persona state-note admission from the legacy agent-memory aggregate into keyed Mind documents and proves a concrete Hands consequence can commit simultaneously. Exact 79c0e373 seals the assembled Persona input and observed source versions in Mind before inference. Exact d3300bba authenticates that input through its one exact Mind commit, refuses naked typed documents, re-enters without external observation or model inference, and proves current-work reconstruction is identical and read-only across Launch, Wait, completed, and post-Research boundaries. No compatibility reader, bootstrap aggregate, schema migrator, or dual reader survives. The source-level Decision-Auditable Concurrent Mind migration is accepted; the fresh exact-package capstone remains open. The machine remains a supervised engineering alpha; Model Atlas operational Gate 1 stays paused. public_positioning: docs/positioning.md is the current public claim owner. Epiphany is the organizational layer above frontier AI workers; global coherence collapse is the primary failure; prompts are bounded projections of governed organizational state; humans retain purpose, judgment, authority, disagreement, exceptions, and acceptance. GameCult is the forge and longitudinal evidence program for a target federation of one locally owned Epiphany project organism per living project Body. Model Atlas carries typed offers, claims, evidence, and derived technical relationships; Bifrost is the intended external work, membership, governance, attribution, and identity-linked receipt rail. Public Persona relationships and visitor surfaces are intended social infrastructure, while private Mind and consequence authority remain local. The fleet, real three-repository Gate 1, complete Bifrost attribution, sustained autonomous production, visitor experience, and external design-partner pilots remain gated alpha targets. latest_phase: The fresh-package Ox17 lane remains paused for source subtraction. Exact 1d5a1f17 removed 19,252 net non-vendor lines, exact 387afe49 removed 25,317, exact bf516f99 removed 2,701, exact 360073a3 removed 1,726, exact d1685df8 removed 4,389, and exact 39dd9fdb removes 6,433 net lines. The latest cuts delete heartbeat-authored personality, appraisal, rumination, dreaming, void-routine cognition, the aggregate agent-memory identity/generation store, the 64-float utterance vector, generic selfPatch decoding/admission, phantom sleep-distillation contracts, stale aggregate/thread schemas, and tests that only copied DTOs or inspected static contract vectors. Heartbeat now schedules explicit pressure only; keyed Mind owns durable Persona memory. Native core check passes, the library suite passes 455/455, and the provider-runtime suite passes 27/27. No Idunn build, package, deployment, or Ox root is authorized yet. Ox16 remains sealed historical evidence and must never resume. + persona_social_cut: The current source cut removes Persona from heartbeat authority. Pending mentions, immutable requests, terminal receipts, quarantine records, retention heads, and retention plans are separate keyed CultCache documents. Persona derives its own deterministic work identity, reserves and terminalizes through exact batch CAS, cites the exact request envelope as pass-input provenance, and retries failed mentions without a timestamp or global revision. The old heartbeat bridge and terminal receipt types have no writable compatibility path. Core passes 448/448; the heartbeat, Persona, and swarm binaries check; Persona re-entry passes 1/1. operational_state: local_worktree: subtraction_commit_360073a3_pushed_modeling_only_semantic_projection_verified_ox17_and_deployment_paused docker_engine_access: starfire_compiler_retired_all_yggdrasil_epiphany_transient_containers_volumes_package_roots_and_per_run_test_target_removed_future_idunn_epiphany_builds_native_rust_1_95_0_via_gamecult_ops_89f0d78 @@ -90,8 +91,8 @@ current_status: starfire_linux_modeling_peak: 109887488_bytes_resident_body_plus_modeling_circuit yggdrasil_epiphany_service_contract: idunn_source_change_owner_eve_and_local_typed_operator_surfaces_no_discord_control_plane resident_physiology: historical_c011_exact_465af24d_zero_zombie_proof_accepted_current_containers_exited_255 - unresolved_authority: Exact `2164bd0a` collapses heartbeat to its two live physiological participants, Resident Self and Persona, and deletes Ghostlight scene scheduling, generic tick/pump/heat/complete operator controls, initiative heat/adaptive pacing, five dead intent/cognition schemas, and eight tests that existed only to exercise those dead surfaces. `EpiphanyHeartbeatStateEntry` still combines scheduler readiness/history with pending Persona mentions, Persona turn requests, blocked social pressure, and Persona retention state. That shared identity can still make social transport mutations contend with scheduler acknowledgement, contrary to the disjoint-document concurrency law. Fresh exact-package Ox17 and Model Atlas Gate 1 remain paused until this final scheduler/social conflict domain is split. Bifrost remains Persona and governed external-consequence transport. Historical c011 and partial Gate roots stay untouched/read-only. - next_action: Split pending Persona mentions, Persona turn requests/terminal receipts, blocked social pressure, and Persona retention head/plan into keyed CultCache documents with their existing semantic identities. Heartbeat may read a derived Persona-pressure projection but must not own those documents. Preserve only tests that falsify queue idempotency, disclosure admission, single reservation, terminal replay/disposition, indeterminate-effect quarantine, scheduler exclusion, brake behavior, CAS conflict/replay, or retention refusal. Delete constructor/projection-copy tests encountered during the split. Do not run a full-workspace compile, package, deployment, or Ox root before this subtraction audit closes. + unresolved_authority: Persona social state is now a keyed CultCache corpus owned and scheduled by Persona. Heartbeat cannot launch, block, terminalize, retain, or provide pass provenance for Persona. The remaining heartbeat singleton has only Resident Self, yet still carries selection, pacing, history, artifact retention, stale repair, and cross-store grant/ack reconciliation machinery. A one-participant scheduler may no longer protect an invariant that Resident Self does not already own. Fresh exact-package Ox17 and Model Atlas Gate 1 remain paused until this scheduler audit closes. Bifrost remains Persona and governed external-consequence transport. Historical c011 and partial Gate roots stay untouched/read-only. + next_action: Map the Resident Self grant lifecycle from typed pressure through grant, lease, launch, terminal ack, and retention. Decide whether any heartbeat state remains necessary. If Resident Self already owns exclusion and terminality, replace the singleton scheduler with a stateless physiological pulse and delete heartbeat state, selection/projection, artifact retention, stale repair, and tests that only preserve those mechanisms. Do not run a full-workspace compile, package, deployment, or Ox root before this subtraction audit closes. active_subgoals: - Complete the fresh exact-package Decision-Auditable Concurrent Mind capstone before any further operational Gate run.