Build native Persona conversation path
This commit is contained in:
parent
e4ac23f744
commit
b19baa4db5
29 changed files with 4747 additions and 64 deletions
|
|
@ -18,6 +18,7 @@ use epiphany_core::initialize_ghostlight_scene_heartbeat_store;
|
|||
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::pump_heartbeat_store;
|
||||
use epiphany_core::queue_heartbeat_pending_mention_store;
|
||||
|
|
@ -87,6 +88,9 @@ fn main() -> Result<()> {
|
|||
let mut reply_to_message_id: Option<String> = None;
|
||||
let mut source_surface = "operator".to_string();
|
||||
let mut mention_id: Option<String> = None;
|
||||
let mut source_visibility = "private".to_string();
|
||||
let mut data_classification = "operator_input".to_string();
|
||||
let mut model_provider_id = "operator-configured".to_string();
|
||||
let mut max_age_seconds = 1800_i64;
|
||||
let mut now_utc: Option<String> = None;
|
||||
let mut interval_seconds = 120_u64;
|
||||
|
|
@ -166,6 +170,15 @@ fn main() -> Result<()> {
|
|||
}
|
||||
"--source-surface" => source_surface = next_value(&mut args, "--source-surface")?,
|
||||
"--mention-id" => mention_id = Some(next_value(&mut args, "--mention-id")?),
|
||||
"--source-visibility" => {
|
||||
source_visibility = next_value(&mut args, "--source-visibility")?
|
||||
}
|
||||
"--data-classification" => {
|
||||
data_classification = next_value(&mut args, "--data-classification")?
|
||||
}
|
||||
"--model-provider-id" => {
|
||||
model_provider_id = next_value(&mut args, "--model-provider-id")?
|
||||
}
|
||||
"--max-age-seconds" => {
|
||||
max_age_seconds = next_value(&mut args, "--max-age-seconds")?.parse()?
|
||||
}
|
||||
|
|
@ -372,6 +385,10 @@ fn main() -> Result<()> {
|
|||
reply_to_message_id,
|
||||
queued_at: None,
|
||||
mention_id,
|
||||
source_visibility,
|
||||
data_classification,
|
||||
model_provider_id,
|
||||
model_provider_disclosure_allowed: true,
|
||||
},
|
||||
)?;
|
||||
println!("{}", result);
|
||||
|
|
@ -580,6 +597,23 @@ fn main() -> Result<()> {
|
|||
thread::sleep(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,
|
||||
agent_store.clone(),
|
||||
false,
|
||||
)?;
|
||||
if persona_pulse["status"] != "idle" {
|
||||
completed_iterations = iteration;
|
||||
println!("{}", persona_pulse);
|
||||
if max_iterations > 0 && completed_iterations >= max_iterations {
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_secs(interval_seconds));
|
||||
continue;
|
||||
}
|
||||
let result = run_void_routine_store(
|
||||
&store_path,
|
||||
&iteration_dir,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
use std::{env, path::PathBuf};
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use epiphany_core::{
|
||||
enroll_persona_discord_request_identity, export_persona_discord_request_anchor_candidate,
|
||||
insert_persona_discord_delivery_request, open_persona_discord_request_identity,
|
||||
sign_persona_discord_delivery_request,
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut values = std::collections::BTreeMap::new();
|
||||
let mut args = env::args().skip(1);
|
||||
while let Some(key) = args.next() {
|
||||
values.insert(
|
||||
key.clone(),
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow!("{key} requires a value"))?,
|
||||
);
|
||||
}
|
||||
let value = |key: &str| {
|
||||
values
|
||||
.get(key)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow!("{key} is required"))
|
||||
};
|
||||
let store = PathBuf::from(value("--request-store")?);
|
||||
let identity = PathBuf::from(value("--identity-store")?);
|
||||
let anchor = PathBuf::from(value("--request-anchor")?);
|
||||
enroll_persona_discord_request_identity(&identity)?;
|
||||
export_persona_discord_request_anchor_candidate(&identity, &anchor, "epiphany-yggdrasil")?;
|
||||
let signer = open_persona_discord_request_identity(&identity)?;
|
||||
let issued = chrono::Utc::now();
|
||||
let request = sign_persona_discord_delivery_request(
|
||||
&signer,
|
||||
"rust-crossing-smoke-1".into(),
|
||||
"effect-rust-crossing-smoke-1".into(),
|
||||
"epiphany-yggdrasil".into(),
|
||||
"epiphany.Persona".into(),
|
||||
"123".into(),
|
||||
"".into(),
|
||||
"Rust-authored crossing smoke".into(),
|
||||
issued.to_rfc3339(),
|
||||
(issued + chrono::Duration::seconds(120)).to_rfc3339(),
|
||||
)?;
|
||||
insert_persona_discord_delivery_request(&store, &request)?;
|
||||
println!("{}", request.request_id);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
use anyhow::{Result, anyhow};
|
||||
use std::{env, path::PathBuf};
|
||||
fn main() -> Result<()> {
|
||||
let mut identity = None;
|
||||
let mut anchor = None;
|
||||
let mut runtime = "epiphany-yggdrasil".to_string();
|
||||
let mut args = env::args().skip(1);
|
||||
while let Some(key) = args.next() {
|
||||
let value = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("{key} requires a value"))?;
|
||||
match key.as_str() {
|
||||
"--permit-identity-store" => identity = Some(PathBuf::from(value)),
|
||||
"--permit-anchor" => anchor = Some(PathBuf::from(value)),
|
||||
"--runtime-id" => runtime = value,
|
||||
_ => return Err(anyhow!("unknown argument {key}")),
|
||||
}
|
||||
}
|
||||
epiphany_core::ensure_epiphany_permit_identity(
|
||||
&identity.ok_or_else(|| anyhow!("--permit-identity-store is required"))?,
|
||||
&anchor.ok_or_else(|| anyhow!("--permit-anchor is required"))?,
|
||||
&runtime,
|
||||
)
|
||||
}
|
||||
40
epiphany-core/src/bin/epiphany-persona-discord-permit.rs
Normal file
40
epiphany-core/src/bin/epiphany-persona-discord-permit.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
use std::{env, net::UdpSocket, path::PathBuf};
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use epiphany_core::{
|
||||
EpiphanyPermitIdentity, PersonaPermitIssuerConfig, serve_persona_discord_permit_rudp,
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut values = std::collections::BTreeMap::new();
|
||||
let mut args = env::args().skip(1);
|
||||
while let Some(key) = args.next() {
|
||||
values.insert(
|
||||
key.clone(),
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow!("{key} requires a value"))?,
|
||||
);
|
||||
}
|
||||
let value = |key: &str| {
|
||||
values
|
||||
.get(key)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow!("{key} is required"))
|
||||
};
|
||||
let runtime_id = value("--runtime-id")?;
|
||||
let identity = PathBuf::from(value("--permit-identity-store")?);
|
||||
let anchor: cultnet_rs::GameCultServiceTrustAnchorRecord =
|
||||
rmp_serde::from_slice(&std::fs::read(value("--permit-request-anchor")?)?)?;
|
||||
let provider_anchor: cultnet_rs::GameCultServiceTrustAnchorRecord =
|
||||
rmp_serde::from_slice(&std::fs::read(value("--permit-anchor")?)?)?;
|
||||
let signer = cultnet_rs::open_service_identity_at::<EpiphanyPermitIdentity>(&identity)?;
|
||||
let config = PersonaPermitIssuerConfig {
|
||||
runtime_id,
|
||||
cultmesh_store: PathBuf::from(value("--cultmesh-store")?),
|
||||
replay_store: PathBuf::from(value("--permit-replay-store")?),
|
||||
requester_anchor: anchor,
|
||||
provider_anchor,
|
||||
};
|
||||
let socket = UdpSocket::bind(value("--bind")?)?;
|
||||
serve_persona_discord_permit_rudp(socket, &config, &signer)
|
||||
}
|
||||
41
epiphany-core/src/bin/epiphany-persona-mouth-identity.rs
Normal file
41
epiphany-core/src/bin/epiphany-persona-mouth-identity.rs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
use std::{env, path::PathBuf};
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use epiphany_core::{
|
||||
enroll_persona_discord_request_identity, export_persona_discord_request_anchor_candidate,
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut mouth_identity_store = None;
|
||||
let mut mouth_request_anchor = None;
|
||||
let mut runtime_id = None;
|
||||
let mut args = env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
let value = args
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("{arg} requires a value"))?;
|
||||
match arg.as_str() {
|
||||
"--mouth-identity-store" => mouth_identity_store = Some(PathBuf::from(value)),
|
||||
"--mouth-request-anchor" => mouth_request_anchor = Some(PathBuf::from(value)),
|
||||
"--runtime-id" => runtime_id = Some(value),
|
||||
_ => return Err(anyhow!("unknown argument {arg}")),
|
||||
}
|
||||
}
|
||||
let identity =
|
||||
mouth_identity_store.ok_or_else(|| anyhow!("--mouth-identity-store is required"))?;
|
||||
let anchor =
|
||||
mouth_request_anchor.ok_or_else(|| anyhow!("--mouth-request-anchor is required"))?;
|
||||
let runtime = runtime_id.ok_or_else(|| anyhow!("--runtime-id is required"))?;
|
||||
enroll_persona_discord_request_identity(&identity)?;
|
||||
export_persona_discord_request_anchor_candidate(&identity, &anchor, &runtime)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({
|
||||
"schemaVersion": "epiphany.persona_mouth_identity_enrollment.v0",
|
||||
"status": "ready",
|
||||
"runtimeId": runtime,
|
||||
"privateStateExposed": false
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -5,12 +5,12 @@ use epiphany_core::{
|
|||
ProcessInstanceObservation, ResidentProviderReadiness, ResidentReadinessRequest,
|
||||
ResidentSelfOutcome, ResidentSelfPolicy, ResidentSelfPorts, ResidentSelfPressure,
|
||||
ResidentSelfState, acknowledge_resident_self_launch, authenticate_resident_self_policy,
|
||||
bind_runtime_repository_domain, cancel_resident_self_turn, capture_process_instance,
|
||||
complete_resident_self_turn, coordinator_run_receipts, derive_resident_cognition_readiness,
|
||||
enqueue_resident_self_pressure, import_bifrost_persona_feedback_deliveries,
|
||||
ingest_resident_self_domain_pressure, load_epiphany_cultmesh_swarm_brake,
|
||||
load_resident_self_state, observe_process_instance, prepare_resident_self_launch,
|
||||
publish_resident_provider_readiness, resident_self_child_claim,
|
||||
bind_runtime_repository_domain, bridge_admitted_persona_feedback_to_heartbeat,
|
||||
cancel_resident_self_turn, capture_process_instance, complete_resident_self_turn,
|
||||
coordinator_run_receipts, derive_resident_cognition_readiness, enqueue_resident_self_pressure,
|
||||
import_bifrost_persona_feedback_deliveries, ingest_resident_self_domain_pressure,
|
||||
load_epiphany_cultmesh_swarm_brake, load_resident_self_state, observe_process_instance,
|
||||
prepare_resident_self_launch, publish_resident_provider_readiness, resident_self_child_claim,
|
||||
resident_self_local_provider_status, terminate_process_instance,
|
||||
validate_bifrost_persona_feedback_source, validate_persona_feedback_store_separation,
|
||||
validate_resident_self_store_separation,
|
||||
|
|
@ -153,6 +153,15 @@ fn cycle(
|
|||
&args.feedback_target_repository,
|
||||
&args.feedback_target_persona,
|
||||
)?;
|
||||
if !ports.brake_engaged()? {
|
||||
bridge_admitted_persona_feedback_to_heartbeat(
|
||||
&args.persona_feedback_store,
|
||||
&args.heartbeat_store,
|
||||
&args.policy.release_runtime_id,
|
||||
&args.policy.model_provider,
|
||||
&args.persona_model_allowed_data_classifications,
|
||||
)?;
|
||||
}
|
||||
bind_runtime_repository_domain(
|
||||
&args.policy.runtime_store,
|
||||
&args.feedback_target_repository,
|
||||
|
|
@ -337,6 +346,7 @@ struct Args {
|
|||
bifrost_feedback_trust_anchor: PathBuf,
|
||||
feedback_target_repository: String,
|
||||
feedback_target_persona: String,
|
||||
persona_model_allowed_data_classifications: Vec<String>,
|
||||
policy: ResidentSelfPolicy,
|
||||
pressure: Option<ResidentSelfPressure>,
|
||||
}
|
||||
|
|
@ -443,6 +453,14 @@ impl Args {
|
|||
.get("--feedback-target-persona")
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow!("missing --feedback-target-persona"))?,
|
||||
persona_model_allowed_data_classifications: value
|
||||
.get("--persona-model-allowed-data-classifications")
|
||||
.ok_or_else(|| anyhow!("missing --persona-model-allowed-data-classifications"))?
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|item| !item.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
policy,
|
||||
pressure,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ use chrono::Duration;
|
|||
use chrono::Utc;
|
||||
use epiphany_state_model::EpiphanyMemoryContextQuery;
|
||||
use serde_json::Value;
|
||||
use sha2::Digest;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
|
|
@ -294,6 +295,86 @@ pub fn tick_heartbeat_store(
|
|||
}))
|
||||
}
|
||||
|
||||
pub fn pulse_persona_heartbeat(
|
||||
store_path: impl AsRef<Path>,
|
||||
artifact_dir: impl AsRef<Path>,
|
||||
schedule_id: &str,
|
||||
source_scene_ref: &str,
|
||||
agent_store: Option<std::path::PathBuf>,
|
||||
brake_engaged: bool,
|
||||
) -> Result<Value> {
|
||||
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,
|
||||
coordinator_action: Some("admitted-persona-feedback".into()),
|
||||
target_role: Some("Persona".into()),
|
||||
urgency: 1.0,
|
||||
schedule_id: schedule_id.to_string(),
|
||||
source_scene_ref: source_scene_ref.to_string(),
|
||||
defer_completion: true,
|
||||
agent_store,
|
||||
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<Path>,
|
||||
resident_store: impl AsRef<Path>,
|
||||
|
|
@ -725,16 +806,24 @@ pub fn queue_heartbeat_pending_mention_store(
|
|||
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, 4000)?;
|
||||
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(
|
||||
|
|
@ -770,6 +859,10 @@ pub fn queue_heartbeat_pending_mention_store(
|
|||
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
|
||||
|
|
@ -917,6 +1010,44 @@ 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));
|
||||
|
|
@ -1065,12 +1196,20 @@ fn tick_once(
|
|||
state.scene_clock = round6(scene_clock);
|
||||
let selected_pending_mentions = pending_mentions_for_role(state, &selected.role_id);
|
||||
if action.action_type == "persona_turn" {
|
||||
let selected_role = selected.role_id.as_str();
|
||||
state
|
||||
.pending_mentions
|
||||
.retain(|mention| mention.target_role_id != selected_role);
|
||||
reserve_persona_turn_request(
|
||||
state,
|
||||
&pending,
|
||||
&selected_after_identity(&selected),
|
||||
selected_pending_mentions.clone(),
|
||||
persona_memory_recall_for_scheduled_turn(
|
||||
options.agent_store.as_deref(),
|
||||
&selected,
|
||||
&action,
|
||||
&selected_pending_mentions,
|
||||
),
|
||||
)?;
|
||||
}
|
||||
if !options.defer_completion {
|
||||
if !options.defer_completion && action.action_type != "persona_turn" {
|
||||
complete_pending_turn(state, selected_index)?;
|
||||
}
|
||||
|
||||
|
|
@ -1180,6 +1319,220 @@ 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<HeartbeatPendingMention>,
|
||||
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(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<Path>,
|
||||
options: PersonaTurnTerminalOptions,
|
||||
) -> Result<PersonaTurnTerminalReceipt> {
|
||||
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::<BTreeSet<_>>();
|
||||
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,
|
||||
|
|
@ -1587,6 +1940,7 @@ fn pending_mentions_for_role(
|
|||
.pending_mentions
|
||||
.iter()
|
||||
.filter(|mention| mention.target_role_id == role_id)
|
||||
.filter(|mention| mention.model_provider_disclosure_allowed)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
|
@ -1595,7 +1949,7 @@ fn validate_mention_text(label: &str, value: &str, min_len: usize, max_len: usiz
|
|||
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} characters"
|
||||
"pending mention {label} must be between {min_len} and {max_len} UTF-8 bytes"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
|
|
@ -4118,7 +4472,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn pending_persona_mention_selects_persona_turn_and_consumes_queue() -> Result<()> {
|
||||
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");
|
||||
|
|
@ -4137,6 +4491,10 @@ mod tests {
|
|||
reply_to_message_id: None,
|
||||
queued_at: Some("2026-05-24T00:00:00+00:00".to_string()),
|
||||
mention_id: Some("mention-Persona-test".to_string()),
|
||||
source_visibility: "public".to_string(),
|
||||
data_classification: "public_feedback".to_string(),
|
||||
model_provider_id: "openai-codex".to_string(),
|
||||
model_provider_disclosure_allowed: true,
|
||||
},
|
||||
)?;
|
||||
assert_eq!(queued["queued"], true);
|
||||
|
|
@ -4167,10 +4525,270 @@ mod tests {
|
|||
tick["schedule"]["pending_mentions"]
|
||||
.as_array()
|
||||
.map(Vec::len),
|
||||
Some(0)
|
||||
Some(1)
|
||||
);
|
||||
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!(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")
|
||||
);
|
||||
|
||||
let terminal = complete_persona_turn_request_store(
|
||||
&store_path,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id: request.request_id.clone(),
|
||||
outcome: "dropped".to_string(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: None,
|
||||
},
|
||||
)?;
|
||||
assert_eq!(terminal.mention_disposition, "consumed");
|
||||
let replay = complete_persona_turn_request_store(
|
||||
&store_path,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id: request.request_id.clone(),
|
||||
outcome: "dropped".to_string(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: None,
|
||||
},
|
||||
)?;
|
||||
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()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
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(
|
||||
&store_path,
|
||||
HeartbeatQueueMentionOptions {
|
||||
target_role_id: "Persona".to_string(),
|
||||
source_surface: "discord".to_string(),
|
||||
channel_id: "aquarium".to_string(),
|
||||
message_id: "m-failure".to_string(),
|
||||
author_id: "human".to_string(),
|
||||
author_name: None,
|
||||
content: "Retain this pressure across a failed turn.".to_string(),
|
||||
visible_prompt: "retain this pressure across failure".to_string(),
|
||||
reply_to_message_id: None,
|
||||
queued_at: Some("2026-05-24T00:00:00+00:00".to_string()),
|
||||
mention_id: Some("mention-Persona-failure".to_string()),
|
||||
source_visibility: "public".to_string(),
|
||||
data_classification: "public_feedback".to_string(),
|
||||
model_provider_id: "openai-codex".to_string(),
|
||||
model_provider_disclosure_allowed: true,
|
||||
},
|
||||
)?;
|
||||
tick_heartbeat_store(
|
||||
&store_path,
|
||||
&artifact_dir,
|
||||
HeartbeatTickOptions {
|
||||
target_heartbeat_rate: 1.0,
|
||||
coordinator_action: None,
|
||||
target_role: None,
|
||||
urgency: 0.0,
|
||||
schedule_id: "Persona-failure".to_string(),
|
||||
source_scene_ref: "test/Persona-failure".to_string(),
|
||||
defer_completion: true,
|
||||
agent_store: None,
|
||||
resident_self_store: None,
|
||||
},
|
||||
)?;
|
||||
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(
|
||||
&store_path,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id,
|
||||
outcome: "failed".to_string(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: None,
|
||||
},
|
||||
)?;
|
||||
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()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
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(
|
||||
&store_path,
|
||||
HeartbeatQueueMentionOptions {
|
||||
target_role_id: "Persona".to_string(),
|
||||
source_surface: "bifrost-discord".to_string(),
|
||||
channel_id: "aquarium".to_string(),
|
||||
message_id: "m-unknown".to_string(),
|
||||
author_id: "human".to_string(),
|
||||
author_name: None,
|
||||
content: "Do not answer this twice.".to_string(),
|
||||
visible_prompt: "do not answer this twice".to_string(),
|
||||
reply_to_message_id: Some("m-unknown".to_string()),
|
||||
queued_at: Some("2026-05-24T00:00:00+00:00".to_string()),
|
||||
mention_id: Some("mention-Persona-unknown".to_string()),
|
||||
source_visibility: "public".to_string(),
|
||||
data_classification: "public_feedback".to_string(),
|
||||
model_provider_id: "openai-codex".to_string(),
|
||||
model_provider_disclosure_allowed: true,
|
||||
},
|
||||
)?;
|
||||
let pulse = pulse_persona_heartbeat(
|
||||
&store_path,
|
||||
&artifact_dir,
|
||||
"Persona-unknown",
|
||||
"test/Persona-unknown",
|
||||
None,
|
||||
false,
|
||||
)?;
|
||||
let request_id = pulse["requestId"].as_str().expect("request id").to_string();
|
||||
assert!(
|
||||
complete_persona_turn_request_store(
|
||||
&store_path,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id: request_id.clone(),
|
||||
outcome: "blocked".to_string(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: None,
|
||||
},
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let terminal = complete_persona_turn_request_store(
|
||||
&store_path,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id,
|
||||
outcome: "blocked".to_string(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: Some(PersonaTurnBlockedEvidence {
|
||||
evidence_source: "local_effect".to_string(),
|
||||
crossing_status: "unknown".to_string(),
|
||||
reason: "Mind mutation may have occurred before the local journal committed"
|
||||
.to_string(),
|
||||
crossing_receipt_id: None,
|
||||
bridge_receipt_sha256: None,
|
||||
}),
|
||||
},
|
||||
)?;
|
||||
assert_eq!(terminal.mention_disposition, "quarantined");
|
||||
let next = pulse_persona_heartbeat(
|
||||
&store_path,
|
||||
&artifact_dir,
|
||||
"Persona-unknown-repeat",
|
||||
"test/Persona-unknown",
|
||||
None,
|
||||
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"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persona_heartbeat_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(
|
||||
&store_path,
|
||||
HeartbeatQueueMentionOptions {
|
||||
target_role_id: "Persona".to_string(),
|
||||
source_surface: "bifrost-discord".to_string(),
|
||||
channel_id: "aquarium".to_string(),
|
||||
message_id: "m-pulse".to_string(),
|
||||
author_id: "human".to_string(),
|
||||
author_name: None,
|
||||
content: "Wake the Persona exactly once.".to_string(),
|
||||
visible_prompt: "wake the Persona exactly once".to_string(),
|
||||
reply_to_message_id: Some("m-pulse".to_string()),
|
||||
queued_at: Some("2026-05-24T00:00:00+00:00".to_string()),
|
||||
mention_id: Some("mention-Persona-pulse".to_string()),
|
||||
source_visibility: "public".to_string(),
|
||||
data_classification: "public_feedback".to_string(),
|
||||
model_provider_id: "openai-codex".to_string(),
|
||||
model_provider_disclosure_allowed: true,
|
||||
},
|
||||
)?;
|
||||
let braked = pulse_persona_heartbeat(
|
||||
&store_path,
|
||||
&artifact_dir,
|
||||
"persona-pulse-braked",
|
||||
"test/persona-pulse",
|
||||
None,
|
||||
true,
|
||||
)?;
|
||||
assert_eq!(braked["status"], "refused-by-swarm-brake");
|
||||
assert!(
|
||||
load_heartbeat_state_entry(&store_path)?
|
||||
.expect("heartbeat state")
|
||||
.persona_turn_requests
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let first = pulse_persona_heartbeat(
|
||||
&store_path,
|
||||
&artifact_dir,
|
||||
"persona-pulse-one",
|
||||
"test/persona-pulse",
|
||||
None,
|
||||
false,
|
||||
)?;
|
||||
assert_eq!(first["status"], "reserved");
|
||||
let second = pulse_persona_heartbeat(
|
||||
&store_path,
|
||||
&artifact_dir,
|
||||
"persona-pulse-two",
|
||||
"test/persona-pulse",
|
||||
None,
|
||||
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);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -4197,6 +4815,10 @@ mod tests {
|
|||
reply_to_message_id: None,
|
||||
queued_at: Some("2026-05-24T00:00:00+00:00".to_string()),
|
||||
mention_id: Some("mention-Persona-memory-test".to_string()),
|
||||
source_visibility: "public".to_string(),
|
||||
data_classification: "public_feedback".to_string(),
|
||||
model_provider_id: "openai-codex".to_string(),
|
||||
model_provider_disclosure_allowed: true,
|
||||
},
|
||||
)?;
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,9 @@ pub const HEARTBEAT_STALE_TURN_REPAIR_TYPE: &str = "epiphany.heartbeat.stale_tur
|
|||
pub const HEARTBEAT_STALE_TURN_REPAIR_SCHEMA_VERSION: &str =
|
||||
"epiphany.heartbeat.stale_turn_repair.v0";
|
||||
pub const HEARTBEAT_STALE_TURN_REPAIR_LATEST_KEY: &str = "heartbeat/stale-turn-repair/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";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
|
|
@ -46,6 +49,10 @@ pub struct EpiphanyHeartbeatStateEntry {
|
|||
pub adaptive_pacing: Option<HeartbeatAdaptivePacing>,
|
||||
#[cultcache(key = 19, default)]
|
||||
pub pending_mentions: Vec<HeartbeatPendingMention>,
|
||||
#[cultcache(key = 20, default)]
|
||||
pub persona_turn_requests: Vec<PersonaTurnRequest>,
|
||||
#[cultcache(key = 21, default)]
|
||||
pub blocked_persona_pressures: Vec<PersonaBlockedConversationPressure>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
|
|
@ -815,6 +822,96 @@ pub struct HeartbeatPendingMention {
|
|||
#[serde(default)]
|
||||
pub reply_to_message_id: Option<String>,
|
||||
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<HeartbeatPendingMention>,
|
||||
#[serde(default)]
|
||||
pub semantic_memory_recall: Value,
|
||||
#[serde(default)]
|
||||
pub terminal_receipt: Option<PersonaTurnTerminalReceipt>,
|
||||
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<String>,
|
||||
pub mention_cargo_sha256: String,
|
||||
#[serde(default)]
|
||||
pub delivery_evidence_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub crossing_receipt_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub bridge_receipt_sha256: Option<String>,
|
||||
#[serde(default)]
|
||||
pub blocked_crossing_status: Option<String>,
|
||||
#[serde(default)]
|
||||
pub blocked_reason: Option<String>,
|
||||
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<crate::PersonaDiscordDeliveryEvidence>,
|
||||
pub blocked_evidence: Option<PersonaTurnBlockedEvidence>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
pub bridge_receipt_sha256: Option<String>,
|
||||
}
|
||||
|
||||
#[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<HeartbeatPendingMention>,
|
||||
pub mention_cargo_sha256: String,
|
||||
#[serde(default)]
|
||||
pub crossing_receipt_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub bridge_receipt_sha256: Option<String>,
|
||||
pub quarantined_at: String,
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
|
|
@ -907,6 +1004,10 @@ pub struct HeartbeatQueueMentionOptions {
|
|||
pub reply_to_message_id: Option<String>,
|
||||
pub queued_at: Option<String>,
|
||||
pub mention_id: Option<String>,
|
||||
pub source_visibility: String,
|
||||
pub data_classification: String,
|
||||
pub model_provider_id: String,
|
||||
pub model_provider_disclosure_allowed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
|
|
|||
|
|
@ -56,6 +56,8 @@ pub fn default_heartbeat_state(target_heartbeat_rate: f64) -> EpiphanyHeartbeatS
|
|||
protocol: None,
|
||||
adaptive_pacing: None,
|
||||
pending_mentions: Vec::new(),
|
||||
persona_turn_requests: Vec::new(),
|
||||
blocked_persona_pressures: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ use super::HEARTBEAT_STATE_SCHEMA_VERSION;
|
|||
use super::LegacyHeartbeatStateWithCognition;
|
||||
use super::PARTICIPANT_KIND_AGENT;
|
||||
use super::PARTICIPANT_KIND_CHARACTER;
|
||||
use super::PERSONA_TURN_REQUEST_SCHEMA_VERSION;
|
||||
use super::PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION;
|
||||
use super::now_iso;
|
||||
use super::participant_arena;
|
||||
use super::participant_kind;
|
||||
|
|
@ -410,6 +412,91 @@ 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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
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(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,6 +26,9 @@ mod operator_command;
|
|||
mod operator_command_service;
|
||||
mod organ_dependencies;
|
||||
mod packaged_release;
|
||||
mod persona_conversation;
|
||||
mod persona_discord_crossing;
|
||||
mod persona_discord_permit;
|
||||
mod persona_feedback_admission;
|
||||
mod persona_turn;
|
||||
mod process_observation;
|
||||
|
|
@ -644,9 +647,15 @@ pub use heartbeat_state::HeartbeatQueueMentionOptions;
|
|||
pub use heartbeat_state::HeartbeatSelectionPolicy;
|
||||
pub use heartbeat_state::HeartbeatStaleTurnRepairOptions;
|
||||
pub use heartbeat_state::HeartbeatTickOptions;
|
||||
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::VoidRoutineOptions;
|
||||
pub use heartbeat_state::complete_heartbeat_store;
|
||||
pub use heartbeat_state::complete_persona_turn_request_store;
|
||||
pub use heartbeat_state::default_heartbeat_state;
|
||||
pub use heartbeat_state::ghostlight_scene_heartbeat_state;
|
||||
pub use heartbeat_state::heartbeat_state_cache;
|
||||
|
|
@ -656,6 +665,7 @@ pub use heartbeat_state::initialize_heartbeat_store;
|
|||
pub use heartbeat_state::load_heartbeat_cognition_entry;
|
||||
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::pump_heartbeat_store;
|
||||
pub use heartbeat_state::queue_heartbeat_pending_mention_store;
|
||||
|
|
@ -875,20 +885,33 @@ pub use packaged_release::{
|
|||
required_packaged_release_binaries, validate_epiphany_packaged_release,
|
||||
verify_epiphany_packaged_release_files, write_epiphany_packaged_release_witness,
|
||||
};
|
||||
pub use persona_conversation::*;
|
||||
pub use persona_discord_crossing::*;
|
||||
pub use persona_discord_permit::*;
|
||||
pub use persona_feedback_admission::{
|
||||
BIFROST_PERSONA_FEEDBACK_ADMISSION_SCHEMA_VERSION, BIFROST_PERSONA_FEEDBACK_DELIVERY_TYPE,
|
||||
BifrostPersonaFeedbackAdmission, LOCAL_PERSONA_FEEDBACK_SCHEMA_VERSION,
|
||||
LocalAdmittedPersonaFeedback, PersonaFeedbackPacket, admit_bifrost_persona_feedback,
|
||||
admitted_persona_feedback, 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,
|
||||
LocalAdmittedPersonaFeedback, PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION,
|
||||
PersonaFeedbackHeartbeatBridgeReceipt, PersonaFeedbackPacket, admit_bifrost_persona_feedback,
|
||||
admitted_persona_feedback, bridge_admitted_persona_feedback_to_heartbeat,
|
||||
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,
|
||||
};
|
||||
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;
|
||||
pub use persona_turn::PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION;
|
||||
pub use persona_turn::PERSONA_MODEL_TERMINAL_RECEIPT_SCHEMA_VERSION;
|
||||
pub use persona_turn::PERSONA_PROJECTOR_PROMPT_SCHEMA_VERSION;
|
||||
pub use persona_turn::PERSONA_TURN_PROMPT_SCHEMA_VERSION;
|
||||
pub use persona_turn::PersonaIdentity;
|
||||
pub use persona_turn::PersonaInterpreterEffect;
|
||||
pub use persona_turn::PersonaInterpreterEffectDocument;
|
||||
pub use persona_turn::PersonaInterpreterEffectSet;
|
||||
pub use persona_turn::PersonaInterpreterInput;
|
||||
pub use persona_turn::PersonaModelStageReceipt;
|
||||
pub use persona_turn::PersonaModelTerminalReceipt;
|
||||
pub use persona_turn::PersonaProjectorInput;
|
||||
pub use persona_turn::PersonaRepoActivity;
|
||||
pub use persona_turn::PersonaSocialAffordance;
|
||||
|
|
@ -897,6 +920,8 @@ pub use persona_turn::PersonaTurnInput;
|
|||
pub use persona_turn::build_persona_interpreter_prompt;
|
||||
pub use persona_turn::build_persona_projector_prompt;
|
||||
pub use persona_turn::build_persona_turn_prompt;
|
||||
pub use persona_turn::parse_and_validate_persona_interpreter_effect_set;
|
||||
pub use persona_turn::persona_interpreter_effect_set_json_schema;
|
||||
pub use persona_turn::persona_projected_surface_is_clean;
|
||||
pub use persona_turn::render_persona_semantic_memory_recall;
|
||||
pub use persona_turn::semantic_memory_recall_from_heartbeat_action;
|
||||
|
|
|
|||
|
|
@ -1147,18 +1147,21 @@ mod tests {
|
|||
"coordinator-snapshot/sleeping"
|
||||
);
|
||||
assert_eq!(status_result.state_status, "coordinator-state/ready");
|
||||
assert_eq!(
|
||||
status_result.coordinator_action,
|
||||
"coordinator-action/none"
|
||||
assert_eq!(status_result.coordinator_action, "coordinator-action/none");
|
||||
assert!(
|
||||
[
|
||||
status_result.operator_status.as_str(),
|
||||
status_result.state_status.as_str(),
|
||||
status_result.coordinator_action.as_str(),
|
||||
]
|
||||
.into_iter()
|
||||
.all(|value| value != "ready" && value != "none")
|
||||
);
|
||||
assert!(
|
||||
status_result
|
||||
.detail
|
||||
.contains("not deployment or provider readiness")
|
||||
);
|
||||
assert!([
|
||||
status_result.operator_status.as_str(),
|
||||
status_result.state_status.as_str(),
|
||||
status_result.coordinator_action.as_str(),
|
||||
]
|
||||
.into_iter()
|
||||
.all(|value| value != "ready" && value != "none"));
|
||||
assert!(status_result.detail.contains("not deployment or provider readiness"));
|
||||
assert!(!resident.exists());
|
||||
let sleep = signed(
|
||||
&signer,
|
||||
|
|
|
|||
|
|
@ -103,6 +103,19 @@ pub fn required_packaged_release_binaries(target_triple: &str) -> Vec<(&'static
|
|||
"persona-feedback-ingress",
|
||||
file_name("epiphany-persona-feedback-ingress"),
|
||||
),
|
||||
("persona-service", file_name("epiphany-persona-service")),
|
||||
(
|
||||
"persona-mouth-identity",
|
||||
file_name("epiphany-persona-mouth-identity"),
|
||||
),
|
||||
(
|
||||
"persona-discord-permit",
|
||||
file_name("epiphany-persona-discord-permit"),
|
||||
),
|
||||
(
|
||||
"persona-discord-permit-identity",
|
||||
file_name("epiphany-persona-discord-permit-identity"),
|
||||
),
|
||||
("coordinator", file_name("epiphany-mvp-coordinator")),
|
||||
("model-runtime", file_name("epiphany-model-runtime")),
|
||||
("tool-mcp-runtime", file_name("epiphany-tool-mcp-runtime")),
|
||||
|
|
@ -405,6 +418,12 @@ fn required_release_build_target(role: &str) -> Result<(&'static str, &'static s
|
|||
"operator-command" => Ok(("epiphany-core", "epiphany-operator-command")),
|
||||
"heartbeat" => Ok(("epiphany-core", "epiphany-heartbeat-store")),
|
||||
"persona-feedback-ingress" => Ok(("epiphany-core", "epiphany-persona-feedback-ingress")),
|
||||
"persona-service" => Ok(("epiphany-openai-runtime", "epiphany-persona-service")),
|
||||
"persona-mouth-identity" => Ok(("epiphany-core", "epiphany-persona-mouth-identity")),
|
||||
"persona-discord-permit" => Ok(("epiphany-core", "epiphany-persona-discord-permit")),
|
||||
"persona-discord-permit-identity" => {
|
||||
Ok(("epiphany-core", "epiphany-persona-discord-permit-identity"))
|
||||
}
|
||||
"coordinator" => Ok(("epiphany-core", "epiphany-mvp-coordinator")),
|
||||
"model-runtime" => Ok(("epiphany-openai-runtime", "epiphany-model-runtime")),
|
||||
"tool-mcp-runtime" => Ok(("epiphany-tool-mcp-runtime", "epiphany-tool-mcp-runtime")),
|
||||
|
|
@ -880,6 +899,10 @@ mod tests {
|
|||
"heartbeat",
|
||||
"coordinator",
|
||||
"model-runtime",
|
||||
"persona-service",
|
||||
"persona-mouth-identity",
|
||||
"persona-discord-permit",
|
||||
"persona-discord-permit-identity",
|
||||
"tool-mcp-runtime",
|
||||
] {
|
||||
assert!(packaged_roles.contains(role), "release omits {role}");
|
||||
|
|
@ -904,6 +927,22 @@ mod tests {
|
|||
required_release_build_target("model-runtime").unwrap(),
|
||||
("epiphany-openai-runtime", "epiphany-model-runtime")
|
||||
);
|
||||
assert_eq!(
|
||||
required_release_build_target("persona-service").unwrap(),
|
||||
("epiphany-openai-runtime", "epiphany-persona-service")
|
||||
);
|
||||
assert_eq!(
|
||||
required_release_build_target("persona-mouth-identity").unwrap(),
|
||||
("epiphany-core", "epiphany-persona-mouth-identity")
|
||||
);
|
||||
assert_eq!(
|
||||
required_release_build_target("persona-discord-permit").unwrap(),
|
||||
("epiphany-core", "epiphany-persona-discord-permit")
|
||||
);
|
||||
assert_eq!(
|
||||
required_release_build_target("persona-discord-permit-identity").unwrap(),
|
||||
("epiphany-core", "epiphany-persona-discord-permit-identity")
|
||||
);
|
||||
assert_eq!(
|
||||
required_release_build_target("tool-mcp-runtime").unwrap(),
|
||||
("epiphany-tool-mcp-runtime", "epiphany-tool-mcp-runtime")
|
||||
|
|
|
|||
762
epiphany-core/src/persona_conversation.rs
Normal file
762
epiphany-core/src/persona_conversation.rs
Normal file
|
|
@ -0,0 +1,762 @@
|
|||
use std::path::Path;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultnet_rs::{GameCultServiceTrustAnchorRecord, ServiceIdentitySigner};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::agent_memory::SelfPatchMemory;
|
||||
use crate::{
|
||||
AgentSelfPatch, EpiphanyPersonaDeliveryRequestIdentity, PersonaInterpreterEffect,
|
||||
PersonaInterpreterEffectDocument, PersonaModelStageReceipt, PersonaModelTerminalReceipt,
|
||||
PersonaTurnRequest, PersonaTurnTerminalOptions, apply_agent_self_patch_document,
|
||||
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,
|
||||
};
|
||||
|
||||
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";
|
||||
pub const PERSONA_EFFECT_EXECUTION_INTENT_SCHEMA_VERSION: &str =
|
||||
"epiphany.persona_effect_execution_intent.v0";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_effect_execution_intent.v0",
|
||||
schema = "PersonaEffectExecutionIntent"
|
||||
)]
|
||||
pub struct PersonaEffectExecutionIntent {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub intent_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub effect_document_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub effect_index: u64,
|
||||
#[cultcache(key = 5)]
|
||||
pub effect_kind: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub status: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub updated_at: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_discord_delivery_evidence.v0",
|
||||
schema = "PersonaDiscordDeliveryEvidence"
|
||||
)]
|
||||
pub struct PersonaDiscordDeliveryEvidence {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub evidence_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub effect_document_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub channel_id: String,
|
||||
#[cultcache(key = 4, default)]
|
||||
pub reply_to_message_id: Option<String>,
|
||||
#[cultcache(key = 5)]
|
||||
pub message_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub transport: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub crossing_receipt_id: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub receipt_url: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub bridge_receipt_sha256: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_conversation_execution_receipt.v0",
|
||||
schema = "PersonaConversationExecutionReceipt"
|
||||
)]
|
||||
pub struct PersonaConversationExecutionReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub receipt_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub effect_document_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub outcome: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub state_effect_status: String,
|
||||
#[cultcache(key = 6, default)]
|
||||
pub state_effect_reasons: Vec<String>,
|
||||
#[cultcache(key = 7, default)]
|
||||
pub delivery_evidence_ids: Vec<String>,
|
||||
#[cultcache(key = 8, default)]
|
||||
pub heartbeat_terminal_receipt_id: Option<String>,
|
||||
#[cultcache(key = 9)]
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
/// Advances one reserved Persona turn across the signed Epiphany→Bifrost
|
||||
/// request/receipt boundary. `None` means a request is durably pending.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn poll_persona_discord_crossing(
|
||||
runtime_store: &Path,
|
||||
heartbeat_store: &Path,
|
||||
agent_store: &Path,
|
||||
cultmesh_store: &Path,
|
||||
runtime_id: &str,
|
||||
request_store: &Path,
|
||||
receipt_store: &Path,
|
||||
signer: &ServiceIdentitySigner<EpiphanyPersonaDeliveryRequestIdentity>,
|
||||
receipt_anchor: &GameCultServiceTrustAnchorRecord,
|
||||
request_id: &str,
|
||||
effect_document_id: &str,
|
||||
) -> Result<Option<PersonaConversationExecutionReceipt>> {
|
||||
let receipt_id = format!("persona-conversation:{request_id}");
|
||||
if let Some(existing) =
|
||||
runtime_document::<PersonaConversationExecutionReceipt>(runtime_store, &receipt_id)?
|
||||
{
|
||||
return Ok(Some(existing));
|
||||
}
|
||||
let request = load_reserved_request(heartbeat_store, request_id)?;
|
||||
let effects =
|
||||
runtime_document::<PersonaInterpreterEffectDocument>(runtime_store, effect_document_id)?
|
||||
.ok_or_else(|| anyhow!("Persona Interpreter effect document is missing"))?;
|
||||
validate_model_terminal(runtime_store, &request, &effects)?;
|
||||
require_persona_effects_unbraked(cultmesh_store, runtime_id)?;
|
||||
let say = effects
|
||||
.effects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find_map(|(index, effect)| {
|
||||
if let PersonaInterpreterEffect::Say {
|
||||
channel_id,
|
||||
reply_to_message_id,
|
||||
content,
|
||||
..
|
||||
} = effect
|
||||
{
|
||||
Some((index, channel_id, reply_to_message_id, content))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let Some((index, channel_id, reply_to_message_id, content)) = say else {
|
||||
// Non-speech turns retain the existing typed state-admission path.
|
||||
let (state_status, reasons) = match admit_state_notes(
|
||||
runtime_store,
|
||||
agent_store,
|
||||
cultmesh_store,
|
||||
runtime_id,
|
||||
&request,
|
||||
&effects,
|
||||
) {
|
||||
Ok(value) => value,
|
||||
Err(error) if error.to_string().contains("quarantined") => {
|
||||
return terminalize_local_effect_quarantine(
|
||||
runtime_store,
|
||||
heartbeat_store,
|
||||
&request,
|
||||
&effects,
|
||||
error,
|
||||
);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let outcome = if effects
|
||||
.effects
|
||||
.iter()
|
||||
.all(|effect| matches!(effect, PersonaInterpreterEffect::Drop { .. }))
|
||||
{
|
||||
"dropped"
|
||||
} else {
|
||||
"silence"
|
||||
};
|
||||
let terminal = complete_persona_turn_request_store(
|
||||
heartbeat_store,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id: request_id.into(),
|
||||
outcome: outcome.into(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: None,
|
||||
},
|
||||
)?;
|
||||
let receipt = PersonaConversationExecutionReceipt {
|
||||
schema_version: PERSONA_CONVERSATION_EXECUTION_RECEIPT_SCHEMA_VERSION.into(),
|
||||
receipt_id,
|
||||
request_id: request_id.into(),
|
||||
effect_document_id: effect_document_id.into(),
|
||||
outcome: outcome.into(),
|
||||
state_effect_status: state_status,
|
||||
state_effect_reasons: reasons,
|
||||
delivery_evidence_ids: vec![],
|
||||
heartbeat_terminal_receipt_id: Some(terminal.receipt_id),
|
||||
private_state_exposed: false,
|
||||
};
|
||||
put_runtime_document(runtime_store, &receipt.receipt_id, &receipt)?;
|
||||
return Ok(Some(receipt));
|
||||
};
|
||||
let crossing_request_id = format!("persona-discord:{request_id}:{index}");
|
||||
let reply = resolve_reply_target(&request, reply_to_message_id.as_deref())?.unwrap_or_default();
|
||||
let crossing = if let Some(existing) =
|
||||
crate::load_persona_discord_delivery_request(request_store, &crossing_request_id)?
|
||||
{
|
||||
existing
|
||||
} else {
|
||||
if let Err(error) = admit_state_notes(
|
||||
runtime_store,
|
||||
agent_store,
|
||||
cultmesh_store,
|
||||
runtime_id,
|
||||
&request,
|
||||
&effects,
|
||||
) {
|
||||
if error.to_string().contains("quarantined") {
|
||||
return terminalize_local_effect_quarantine(
|
||||
runtime_store,
|
||||
heartbeat_store,
|
||||
&request,
|
||||
&effects,
|
||||
error,
|
||||
);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
begin_effect(runtime_store, &request, &effects, index, "say")?;
|
||||
let issued = chrono::Utc::now();
|
||||
let signed = sign_persona_discord_delivery_request(
|
||||
signer,
|
||||
crossing_request_id.clone(),
|
||||
effects.document_id.clone(),
|
||||
runtime_id.into(),
|
||||
request.agent_id.clone(),
|
||||
channel_id.clone(),
|
||||
reply.clone(),
|
||||
content.clone(),
|
||||
issued.to_rfc3339(),
|
||||
(issued + chrono::Duration::seconds(90)).to_rfc3339(),
|
||||
)?;
|
||||
require_persona_effects_unbraked(cultmesh_store, runtime_id)?;
|
||||
insert_persona_discord_delivery_request(request_store, &signed)?;
|
||||
signed
|
||||
};
|
||||
let Some(delivery) =
|
||||
load_persona_discord_delivery_receipt(receipt_store, &crossing_request_id)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
verify_persona_discord_delivery_receipt(&delivery, &crossing, receipt_anchor)?;
|
||||
let signed_receipt_sha256 =
|
||||
format!("sha256:{:x}", Sha256::digest(rmp_serde::to_vec(&delivery)?));
|
||||
let (outcome, blocked_evidence) = match delivery.status.as_str() {
|
||||
"completed" => ("delivered", None),
|
||||
"failed" | "unknown" => (
|
||||
"blocked",
|
||||
Some(crate::PersonaTurnBlockedEvidence {
|
||||
evidence_source: "bifrost_crossing".into(),
|
||||
crossing_status: delivery.status.clone(),
|
||||
reason: format!(
|
||||
"Signed Bifrost Discord receipt {} for request {} terminated as {} and cannot be retried automatically",
|
||||
delivery.receipt_id, delivery.request_id, delivery.status
|
||||
),
|
||||
crossing_receipt_id: (!delivery.crossing_receipt_id.trim().is_empty())
|
||||
.then(|| delivery.crossing_receipt_id.clone()),
|
||||
bridge_receipt_sha256: Some(signed_receipt_sha256.clone()),
|
||||
}),
|
||||
),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let evidence = (outcome == "delivered").then(|| PersonaDiscordDeliveryEvidence {
|
||||
schema_version: PERSONA_DISCORD_DELIVERY_EVIDENCE_SCHEMA_VERSION.into(),
|
||||
evidence_id: format!(
|
||||
"persona-delivery:{}:{}",
|
||||
effects.document_id, delivery.message_id
|
||||
),
|
||||
effect_document_id: effects.document_id.clone(),
|
||||
channel_id: delivery.channel_id.clone(),
|
||||
reply_to_message_id: (!delivery.reply_to_message_id.is_empty())
|
||||
.then(|| delivery.reply_to_message_id.clone()),
|
||||
message_id: delivery.message_id.clone(),
|
||||
transport: delivery.transport.clone(),
|
||||
crossing_receipt_id: delivery.crossing_receipt_id.clone(),
|
||||
receipt_url: delivery.receipt_url.clone(),
|
||||
bridge_receipt_sha256: signed_receipt_sha256,
|
||||
private_state_exposed: false,
|
||||
});
|
||||
if let Some(value) = &evidence {
|
||||
put_runtime_document(runtime_store, &value.evidence_id, value)?;
|
||||
}
|
||||
let terminal = complete_persona_turn_request_store(
|
||||
heartbeat_store,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id: request_id.into(),
|
||||
outcome: outcome.into(),
|
||||
delivery_evidence: evidence.clone(),
|
||||
blocked_evidence,
|
||||
},
|
||||
)?;
|
||||
let intent_id = format!("persona-effect-intent:{}:{index}", effects.document_id);
|
||||
if let Some(mut intent) =
|
||||
runtime_document::<PersonaEffectExecutionIntent>(runtime_store, &intent_id)?
|
||||
{
|
||||
finish_effect(runtime_store, &mut intent)?;
|
||||
}
|
||||
let receipt = PersonaConversationExecutionReceipt {
|
||||
schema_version: PERSONA_CONVERSATION_EXECUTION_RECEIPT_SCHEMA_VERSION.into(),
|
||||
receipt_id,
|
||||
request_id: request_id.into(),
|
||||
effect_document_id: effect_document_id.into(),
|
||||
outcome: outcome.into(),
|
||||
state_effect_status: "admitted_before_delivery_request".into(),
|
||||
state_effect_reasons: vec![],
|
||||
delivery_evidence_ids: evidence
|
||||
.iter()
|
||||
.map(|value| value.evidence_id.clone())
|
||||
.collect(),
|
||||
heartbeat_terminal_receipt_id: Some(terminal.receipt_id),
|
||||
private_state_exposed: false,
|
||||
};
|
||||
put_runtime_document(runtime_store, &receipt.receipt_id, &receipt)?;
|
||||
Ok(Some(receipt))
|
||||
}
|
||||
|
||||
fn terminalize_local_effect_quarantine(
|
||||
runtime_store: &Path,
|
||||
heartbeat_store: &Path,
|
||||
request: &PersonaTurnRequest,
|
||||
effects: &PersonaInterpreterEffectDocument,
|
||||
error: anyhow::Error,
|
||||
) -> Result<Option<PersonaConversationExecutionReceipt>> {
|
||||
let terminal = complete_persona_turn_request_store(
|
||||
heartbeat_store,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id: request.request_id.clone(),
|
||||
outcome: "blocked".into(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: Some(crate::PersonaTurnBlockedEvidence {
|
||||
evidence_source: "local_effect".into(),
|
||||
crossing_status: "unknown".into(),
|
||||
reason: error.to_string(),
|
||||
crossing_receipt_id: None,
|
||||
bridge_receipt_sha256: None,
|
||||
}),
|
||||
},
|
||||
)?;
|
||||
let receipt = PersonaConversationExecutionReceipt {
|
||||
schema_version: PERSONA_CONVERSATION_EXECUTION_RECEIPT_SCHEMA_VERSION.into(),
|
||||
receipt_id: format!("persona-conversation:{}", request.request_id),
|
||||
request_id: request.request_id.clone(),
|
||||
effect_document_id: effects.document_id.clone(),
|
||||
outcome: "blocked".into(),
|
||||
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),
|
||||
private_state_exposed: false,
|
||||
};
|
||||
put_runtime_document(runtime_store, &receipt.receipt_id, &receipt)?;
|
||||
Ok(Some(receipt))
|
||||
}
|
||||
|
||||
/// Repairs the local execution projection after the heartbeat terminal commit
|
||||
/// won a crash race. The heartbeat 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,
|
||||
request_id: &str,
|
||||
) -> Result<Option<PersonaConversationExecutionReceipt>> {
|
||||
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 {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(terminal) = request.terminal_receipt.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let effect_document_id = format!("persona-effects:{request_id}");
|
||||
let Some(effects) =
|
||||
runtime_document::<PersonaInterpreterEffectDocument>(runtime_store, &effect_document_id)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
validate_model_terminal(runtime_store, &request, &effects)?;
|
||||
for index in 0..effects.effects.len() {
|
||||
let intent_id = format!("persona-effect-intent:{}:{index}", effects.document_id);
|
||||
if let Some(mut intent) =
|
||||
runtime_document::<PersonaEffectExecutionIntent>(runtime_store, &intent_id)?
|
||||
{
|
||||
if intent.status == "started" {
|
||||
finish_effect(runtime_store, &mut intent)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let receipt = PersonaConversationExecutionReceipt {
|
||||
schema_version: PERSONA_CONVERSATION_EXECUTION_RECEIPT_SCHEMA_VERSION.into(),
|
||||
receipt_id,
|
||||
request_id: request_id.into(),
|
||||
effect_document_id,
|
||||
outcome: terminal.outcome.clone(),
|
||||
state_effect_status: "reconciled_from_heartbeat_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()),
|
||||
private_state_exposed: false,
|
||||
};
|
||||
put_runtime_document(runtime_store, &receipt.receipt_id, &receipt)?;
|
||||
Ok(Some(receipt))
|
||||
}
|
||||
|
||||
pub fn persona_model_terminal_exists(runtime_store: &Path, request_id: &str) -> Result<bool> {
|
||||
Ok(runtime_document::<PersonaModelTerminalReceipt>(
|
||||
runtime_store,
|
||||
&format!("persona-terminal:{request_id}"),
|
||||
)?
|
||||
.is_some())
|
||||
}
|
||||
|
||||
pub fn persona_delivery_receipt_exists_for_turn(
|
||||
receipt_store: &Path,
|
||||
request_id: &str,
|
||||
) -> Result<bool> {
|
||||
for index in 0..16 {
|
||||
if crate::load_persona_discord_delivery_receipt(
|
||||
receipt_store,
|
||||
&format!("persona-discord:{request_id}:{index}"),
|
||||
)?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn admit_state_notes(
|
||||
runtime_store: &Path,
|
||||
agent_store: &Path,
|
||||
cultmesh_store: &Path,
|
||||
runtime_id: &str,
|
||||
request: &PersonaTurnRequest,
|
||||
document: &PersonaInterpreterEffectDocument,
|
||||
) -> Result<(String, Vec<String>)> {
|
||||
let mut semantic = Vec::new();
|
||||
let mut relationships = Vec::new();
|
||||
let mut pending = Vec::new();
|
||||
let mut journals = Vec::new();
|
||||
for (index, effect) in document.effects.iter().enumerate() {
|
||||
let PersonaInterpreterEffect::StateNote {
|
||||
memory_kind,
|
||||
summary,
|
||||
confidence,
|
||||
..
|
||||
} = effect
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let journal = begin_effect(runtime_store, request, document, index, "state_note")?;
|
||||
if journal.status == "completed" {
|
||||
continue;
|
||||
}
|
||||
journals.push(journal);
|
||||
let memory = SelfPatchMemory {
|
||||
memory_id: stable_memory_id(&document.document_id, index),
|
||||
summary: summary.clone(),
|
||||
salience: 0.7,
|
||||
confidence: confidence.unwrap_or(0.7),
|
||||
linked_event_ids: Some(vec![document.document_id.clone()]),
|
||||
linked_relationship_id: None,
|
||||
};
|
||||
match memory_kind.as_str() {
|
||||
"memory" => semantic.push(memory),
|
||||
"social_read" | "bond" => relationships.push(memory),
|
||||
other => pending.push(format!(
|
||||
"state_note kind {other:?} awaits a coherent typed Persona-state mapping"
|
||||
)),
|
||||
}
|
||||
}
|
||||
if semantic.is_empty() && relationships.is_empty() {
|
||||
for journal in &mut journals {
|
||||
finish_effect(runtime_store, journal)?;
|
||||
}
|
||||
return Ok((
|
||||
if pending.is_empty() {
|
||||
"none"
|
||||
} else {
|
||||
"pending"
|
||||
}
|
||||
.into(),
|
||||
pending,
|
||||
));
|
||||
}
|
||||
let patch = AgentSelfPatch {
|
||||
agent_id: Some(request.agent_id.clone()),
|
||||
reason: Some(
|
||||
"Persona Interpreter proposed bounded memory effects after a completed natural turn."
|
||||
.into(),
|
||||
),
|
||||
evidence_ids: Some(vec![document.document_id.clone()]),
|
||||
semantic_memories: (!semantic.is_empty()).then_some(semantic),
|
||||
relationship_memories: (!relationships.is_empty()).then_some(relationships),
|
||||
..Default::default()
|
||||
};
|
||||
require_persona_effects_unbraked(cultmesh_store, runtime_id)?;
|
||||
let review = apply_agent_self_patch_document(&request.role_id, patch, agent_store)?;
|
||||
if review.status == "accepted" && review.applied == Some(true) {
|
||||
for journal in &mut journals {
|
||||
finish_effect(runtime_store, journal)?;
|
||||
}
|
||||
Ok((
|
||||
if pending.is_empty() {
|
||||
"admitted"
|
||||
} else {
|
||||
"partially_admitted"
|
||||
}
|
||||
.into(),
|
||||
pending,
|
||||
))
|
||||
} else {
|
||||
pending.extend(review.reasons);
|
||||
for journal in &mut journals {
|
||||
finish_effect(runtime_store, journal)?;
|
||||
}
|
||||
Ok(("pending".into(), pending))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_model_terminal(
|
||||
runtime_store: &Path,
|
||||
request: &PersonaTurnRequest,
|
||||
effects: &PersonaInterpreterEffectDocument,
|
||||
) -> Result<()> {
|
||||
let terminal_id = format!("persona-terminal:{}", effects.turn_id);
|
||||
let terminal = runtime_document::<PersonaModelTerminalReceipt>(runtime_store, &terminal_id)?
|
||||
.ok_or_else(|| anyhow!("exact Persona model terminal receipt is missing"))?;
|
||||
let effect_digest = format!("sha256:{:x}", Sha256::digest(serde_json::to_vec(effects)?));
|
||||
if terminal.receipt_id != terminal_id
|
||||
|| terminal.turn_id != effects.turn_id
|
||||
|| effects.turn_id != request.request_id
|
||||
|| effects.identity_id != request.agent_id
|
||||
|| terminal.effect_document_id != effects.document_id
|
||||
|| terminal.identity_id != request.agent_id
|
||||
|| terminal.effect_document_sha256 != effect_digest
|
||||
|| terminal.private_state_exposed
|
||||
|| terminal.stage_receipt_ids.len() != 3
|
||||
|| terminal.stage_output_sha256.len() != 3
|
||||
{
|
||||
return Err(anyhow!("Persona model terminal binding is invalid"));
|
||||
}
|
||||
for (index, expected) in ["projector", "persona", "interpreter"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let expected_receipt_id = format!("persona-stage:{}:{expected}", effects.turn_id);
|
||||
let receipt_id = &terminal.stage_receipt_ids[index];
|
||||
if receipt_id != &expected_receipt_id {
|
||||
return Err(anyhow!("Persona {expected} stage receipt id is invalid"));
|
||||
}
|
||||
let receipt = runtime_document::<PersonaModelStageReceipt>(runtime_store, receipt_id)?
|
||||
.ok_or_else(|| anyhow!("Persona {expected} stage receipt is missing"))?;
|
||||
if receipt.receipt_id != expected_receipt_id
|
||||
|| receipt.stage != expected
|
||||
|| receipt.turn_id != effects.turn_id
|
||||
|| receipt.request_id != format!("persona:{}:{expected}", effects.turn_id)
|
||||
|| receipt.provider.is_empty()
|
||||
|| receipt.model.is_empty()
|
||||
|| !valid_sha256(&receipt.prompt_sha256)
|
||||
|| !receipt.output_sha256.starts_with("sha256:")
|
||||
|| !valid_sha256(&receipt.output_sha256)
|
||||
|| receipt.output_sha256 != terminal.stage_output_sha256[index]
|
||||
|| receipt.private_output_ref.is_empty()
|
||||
|| receipt.private_state_exposed
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Persona {expected} stage digest binding is invalid"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn valid_sha256(value: &str) -> bool {
|
||||
value.len() == 71
|
||||
&& value.starts_with("sha256:")
|
||||
&& value[7..].bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
fn begin_effect(
|
||||
runtime_store: &Path,
|
||||
request: &PersonaTurnRequest,
|
||||
document: &PersonaInterpreterEffectDocument,
|
||||
index: usize,
|
||||
kind: &str,
|
||||
) -> Result<PersonaEffectExecutionIntent> {
|
||||
let id = format!("persona-effect-intent:{}:{index}", document.document_id);
|
||||
if let Some(mut existing) =
|
||||
runtime_document::<PersonaEffectExecutionIntent>(runtime_store, &id)?
|
||||
{
|
||||
if existing.request_id != request.request_id
|
||||
|| existing.effect_document_id != document.document_id
|
||||
|| existing.effect_index != index as u64
|
||||
|| existing.effect_kind != kind
|
||||
|| existing.private_state_exposed
|
||||
{
|
||||
return Err(anyhow!("Persona effect intent binding is invalid"));
|
||||
}
|
||||
if existing.status == "completed" || (existing.status == "started" && kind == "say") {
|
||||
return Ok(existing);
|
||||
}
|
||||
if existing.status == "started" {
|
||||
existing.status = "quarantined_ambiguous_local_effect".into();
|
||||
existing.updated_at = chrono::Utc::now().to_rfc3339();
|
||||
put_runtime_document(runtime_store, &id, &existing)?;
|
||||
}
|
||||
return Err(anyhow!(
|
||||
"Persona effect {id} is quarantined and requires review"
|
||||
));
|
||||
}
|
||||
let intent = PersonaEffectExecutionIntent {
|
||||
schema_version: PERSONA_EFFECT_EXECUTION_INTENT_SCHEMA_VERSION.into(),
|
||||
intent_id: id.clone(),
|
||||
request_id: request.request_id.clone(),
|
||||
effect_document_id: document.document_id.clone(),
|
||||
effect_index: index as u64,
|
||||
effect_kind: kind.into(),
|
||||
status: "started".into(),
|
||||
updated_at: chrono::Utc::now().to_rfc3339(),
|
||||
private_state_exposed: false,
|
||||
};
|
||||
put_runtime_document(runtime_store, &id, &intent)?;
|
||||
Ok(intent)
|
||||
}
|
||||
|
||||
fn finish_effect(runtime_store: &Path, intent: &mut PersonaEffectExecutionIntent) -> Result<()> {
|
||||
intent.status = "completed".into();
|
||||
intent.updated_at = chrono::Utc::now().to_rfc3339();
|
||||
put_runtime_document(runtime_store, &intent.intent_id, intent)
|
||||
}
|
||||
|
||||
fn require_persona_effects_unbraked(store: &Path, runtime_id: &str) -> Result<()> {
|
||||
let brake = crate::load_epiphany_cultmesh_swarm_brake(store, runtime_id)?
|
||||
.ok_or_else(|| anyhow!("Persona effects refuse to run without canonical brake state"))?;
|
||||
if brake.status != "released" {
|
||||
return Err(anyhow!("Persona effects are braked: {}", brake.reason));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_reply_target(
|
||||
request: &PersonaTurnRequest,
|
||||
requested: Option<&str>,
|
||||
) -> Result<Option<String>> {
|
||||
if let Some(id) = requested {
|
||||
if !request.mentions.iter().any(|mention| {
|
||||
mention.message_id == id || mention.reply_to_message_id.as_deref() == Some(id)
|
||||
}) {
|
||||
return Err(anyhow!(
|
||||
"Persona SAY reply target is outside the reserved mention set"
|
||||
));
|
||||
}
|
||||
return Ok(Some(id.to_string()));
|
||||
}
|
||||
Ok(request
|
||||
.mentions
|
||||
.last()
|
||||
.map(|mention| mention.message_id.clone()))
|
||||
}
|
||||
|
||||
fn load_reserved_request(store: &Path, request_id: &str) -> Result<PersonaTurnRequest> {
|
||||
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)
|
||||
.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"));
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn runtime_document<T: DatabaseEntry>(store: &Path, key: &str) -> Result<Option<T>> {
|
||||
let mut cache = runtime_spine_cache(store)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
cache.get(key)
|
||||
}
|
||||
fn put_runtime_document<T: DatabaseEntry>(store: &Path, key: &str, value: &T) -> Result<()> {
|
||||
let mut cache = runtime_spine_cache(store)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
cache.put(key, value)?;
|
||||
Ok(())
|
||||
}
|
||||
fn stable_memory_id(document_id: &str, index: usize) -> String {
|
||||
format!(
|
||||
"mem-persona-{:x}",
|
||||
Sha256::digest(format!("{document_id}:{index}").as_bytes())
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request() -> PersonaTurnRequest {
|
||||
PersonaTurnRequest {
|
||||
request_id: "turn-1".into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
fn document() -> PersonaInterpreterEffectDocument {
|
||||
PersonaInterpreterEffectDocument {
|
||||
schema_version: crate::PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION.into(),
|
||||
document_id: "persona-effects:turn-1".into(),
|
||||
turn_id: "turn-1".into(),
|
||||
identity_id: "epiphany.Persona".into(),
|
||||
interpreter_request_id: "interpreter-1".into(),
|
||||
created_at: "2026-07-21T00:00:00Z".into(),
|
||||
effects: vec![],
|
||||
private_state_exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn started_speech_intent_resumes_but_ambiguous_local_mutation_quarantines() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let store = temp.path().join("runtime.cc");
|
||||
let speech = begin_effect(&store, &request(), &document(), 0, "say")?;
|
||||
assert_eq!(speech.status, "started");
|
||||
assert_eq!(
|
||||
begin_effect(&store, &request(), &document(), 0, "say")?.intent_id,
|
||||
speech.intent_id
|
||||
);
|
||||
|
||||
begin_effect(&store, &request(), &document(), 1, "state_note")?;
|
||||
assert!(begin_effect(&store, &request(), &document(), 1, "state_note").is_err());
|
||||
let quarantined = runtime_document::<PersonaEffectExecutionIntent>(
|
||||
&store,
|
||||
"persona-effect-intent:persona-effects:turn-1:1",
|
||||
)?
|
||||
.unwrap();
|
||||
assert_eq!(quarantined.status, "quarantined_ambiguous_local_effect");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
500
epiphany-core/src/persona_discord_crossing.rs
Normal file
500
epiphany-core/src/persona_discord_crossing.rs
Normal file
|
|
@ -0,0 +1,500 @@
|
|||
use std::path::Path;
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use cultnet_rs::{
|
||||
GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultServiceTrustAnchorRecord, ServiceIdentityProfile,
|
||||
ServiceIdentitySignature, ServiceIdentitySigner, ServiceSignaturePurpose,
|
||||
verify_service_identity_signature_with_public_key,
|
||||
};
|
||||
|
||||
pub const PERSONA_DISCORD_DELIVERY_REQUEST_SCHEMA_VERSION: &str =
|
||||
"epiphany.persona_discord_delivery_request.v0";
|
||||
pub const PERSONA_DISCORD_DELIVERY_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"bifrost.persona_discord_delivery_receipt.v0";
|
||||
pub const PERSONA_DISCORD_DELIVERY_REQUEST_SIGNING_PURPOSE: &str =
|
||||
"epiphany.persona-discord.delivery-request.v0";
|
||||
pub const PERSONA_DISCORD_DELIVERY_RECEIPT_SIGNING_PURPOSE: &str =
|
||||
"bifrost.persona-discord.delivery-receipt.v0";
|
||||
pub const EPIPHANY_PERSONA_MOUTH_SERVICE_ID: &str = "epiphany-persona-mouth";
|
||||
pub const EPIPHANY_PERSONA_MOUTH_RUNTIME_ID: &str = "epiphany-yggdrasil";
|
||||
pub const BIFROST_PERSONA_DELIVERY_SERVICE_ID: &str = "bifrost-persona-discord-delivery";
|
||||
pub const BIFROST_PERSONA_DELIVERY_RUNTIME_ID: &str = "bifrost-discord-yggdrasil";
|
||||
|
||||
pub enum EpiphanyPersonaDeliveryRequestIdentity {}
|
||||
pub struct EpiphanyPersonaDeliveryRequestPurpose;
|
||||
pub enum BifrostPersonaDeliveryReceiptIdentity {}
|
||||
pub struct BifrostPersonaDeliveryReceiptPurpose;
|
||||
|
||||
impl ServiceIdentityProfile for EpiphanyPersonaDeliveryRequestIdentity {
|
||||
const PRIVATE_TYPE: &'static str =
|
||||
"epiphany.persona_discord_delivery_request_identity.private.v0";
|
||||
const PRIVATE_SCHEMA: &'static str = Self::PRIVATE_TYPE;
|
||||
const PRIVATE_KEY: &'static str = "epiphany-persona-discord-delivery-request-identity";
|
||||
const TRUST_ANCHOR_TYPE: &'static str =
|
||||
"epiphany.persona_discord_delivery_request_identity.trust_anchor.v0";
|
||||
const TRUST_ANCHOR_SCHEMA: &'static str = Self::TRUST_ANCHOR_TYPE;
|
||||
const TRUST_ANCHOR_KEY: &'static str =
|
||||
"epiphany-persona-discord-delivery-request-identity-public";
|
||||
const ID_DOMAIN: &'static [u8] = b"epiphany.persona-discord-delivery-request.identity.v0\0";
|
||||
const SIGNATURE_DOMAIN: &'static [u8] =
|
||||
b"epiphany.persona-discord-delivery-request.signature.v0\0";
|
||||
const PROTECTOR_CONTEXT: &'static str = "epiphany-persona-discord-delivery-request-v0";
|
||||
}
|
||||
impl ServiceSignaturePurpose<EpiphanyPersonaDeliveryRequestIdentity>
|
||||
for EpiphanyPersonaDeliveryRequestPurpose
|
||||
{
|
||||
const PURPOSE: &'static [u8] = PERSONA_DISCORD_DELIVERY_REQUEST_SIGNING_PURPOSE.as_bytes();
|
||||
}
|
||||
impl ServiceIdentityProfile for BifrostPersonaDeliveryReceiptIdentity {
|
||||
const PRIVATE_TYPE: &'static str =
|
||||
"bifrost.persona_discord_delivery_receipt_identity.private.v0";
|
||||
const PRIVATE_SCHEMA: &'static str = Self::PRIVATE_TYPE;
|
||||
const PRIVATE_KEY: &'static str = "bifrost-persona-discord-delivery-receipt-identity";
|
||||
const TRUST_ANCHOR_TYPE: &'static str =
|
||||
"bifrost.persona_discord_delivery_receipt_identity.trust_anchor.v0";
|
||||
const TRUST_ANCHOR_SCHEMA: &'static str = Self::TRUST_ANCHOR_TYPE;
|
||||
const TRUST_ANCHOR_KEY: &'static str =
|
||||
"bifrost-persona-discord-delivery-receipt-identity-public";
|
||||
const ID_DOMAIN: &'static [u8] = b"bifrost.persona-discord-delivery-receipt.identity.v0\0";
|
||||
const SIGNATURE_DOMAIN: &'static [u8] =
|
||||
b"bifrost.persona-discord-delivery-receipt.signature.v0\0";
|
||||
const PROTECTOR_CONTEXT: &'static str = "bifrost-persona-discord-delivery-receipt-v0";
|
||||
}
|
||||
impl ServiceSignaturePurpose<BifrostPersonaDeliveryReceiptIdentity>
|
||||
for BifrostPersonaDeliveryReceiptPurpose
|
||||
{
|
||||
const PURPOSE: &'static [u8] = PERSONA_DISCORD_DELIVERY_RECEIPT_SIGNING_PURPOSE.as_bytes();
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_discord_delivery_request",
|
||||
schema = "PersonaDiscordDeliveryRequest"
|
||||
)]
|
||||
pub struct PersonaDiscordDeliveryRequest {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub effect_document_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub target_runtime_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub persona_agent_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub channel_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub reply_to_message_id: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub content: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub content_sha256: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub issued_at: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub expires_at: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub private_state_exposed: bool,
|
||||
#[cultcache(key = 12)]
|
||||
pub signer_identity_id: String,
|
||||
#[cultcache(key = 13)]
|
||||
pub signer_signature: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "bifrost.persona_discord_delivery_receipt",
|
||||
schema = "PersonaDiscordDeliveryReceipt"
|
||||
)]
|
||||
pub struct PersonaDiscordDeliveryReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub receipt_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub request_payload_sha256: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub status: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub channel_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub reply_to_message_id: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub message_id: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub transport: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub crossing_receipt_id: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub receipt_url: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub completed_at: String,
|
||||
#[cultcache(key = 12)]
|
||||
pub provider_identity_id: String,
|
||||
#[cultcache(key = 13)]
|
||||
pub private_state_exposed: bool,
|
||||
#[cultcache(key = 14)]
|
||||
pub provider_signature: Vec<u8>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn sign_persona_discord_delivery_request(
|
||||
signer: &ServiceIdentitySigner<EpiphanyPersonaDeliveryRequestIdentity>,
|
||||
request_id: String,
|
||||
effect_document_id: String,
|
||||
target_runtime_id: String,
|
||||
persona_agent_id: String,
|
||||
channel_id: String,
|
||||
reply_to_message_id: String,
|
||||
content: String,
|
||||
issued_at: String,
|
||||
expires_at: String,
|
||||
) -> Result<PersonaDiscordDeliveryRequest> {
|
||||
let mut request = PersonaDiscordDeliveryRequest {
|
||||
schema_version: PERSONA_DISCORD_DELIVERY_REQUEST_SCHEMA_VERSION.into(),
|
||||
request_id,
|
||||
effect_document_id,
|
||||
target_runtime_id,
|
||||
persona_agent_id,
|
||||
channel_id,
|
||||
reply_to_message_id,
|
||||
content_sha256: sha256_hyphen(content.as_bytes()),
|
||||
content,
|
||||
issued_at,
|
||||
expires_at,
|
||||
private_state_exposed: false,
|
||||
signer_identity_id: signer.entry().identity_id.clone(),
|
||||
signer_signature: vec![],
|
||||
};
|
||||
validate_request_shape(&request)?;
|
||||
let proof =
|
||||
signer.sign::<EpiphanyPersonaDeliveryRequestPurpose>(&request_signing_payload(&request)?);
|
||||
request.signer_signature = proof.signature;
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
pub fn open_persona_discord_request_identity(
|
||||
path: &Path,
|
||||
) -> Result<ServiceIdentitySigner<EpiphanyPersonaDeliveryRequestIdentity>> {
|
||||
cultnet_rs::open_service_identity_at::<EpiphanyPersonaDeliveryRequestIdentity>(path)
|
||||
}
|
||||
|
||||
pub fn enroll_persona_discord_request_identity(path: &Path) -> Result<()> {
|
||||
if path.exists() {
|
||||
open_persona_discord_request_identity(path)?;
|
||||
return Ok(());
|
||||
}
|
||||
cultnet_rs::enroll_service_identity_at::<EpiphanyPersonaDeliveryRequestIdentity>(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn export_persona_discord_request_anchor_candidate(
|
||||
identity_store: &Path,
|
||||
output: &Path,
|
||||
runtime_id: &str,
|
||||
) -> Result<()> {
|
||||
let signer = open_persona_discord_request_identity(identity_store)?;
|
||||
if output.exists() {
|
||||
let existing = load_persona_discord_service_anchor(output)?;
|
||||
validate_persona_discord_request_anchor(&existing, runtime_id)?;
|
||||
if existing.signer_identity_id != signer.entry().identity_id
|
||||
|| existing.signer_public_key != signer.entry().public_key
|
||||
{
|
||||
bail!("existing request anchor candidate belongs to a different identity");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let record = GameCultServiceTrustAnchorRecord {
|
||||
schema_version: GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(),
|
||||
trust_anchor_id: format!("epiphany-persona-mouth:{runtime_id}:delivery-request:v0"),
|
||||
service_id: EPIPHANY_PERSONA_MOUTH_SERVICE_ID.into(),
|
||||
runtime_id: runtime_id.into(),
|
||||
signer_identity_id: signer.entry().identity_id.clone(),
|
||||
signer_public_key: signer.entry().public_key.clone(),
|
||||
signature_algorithm: "ed25519".into(),
|
||||
signing_purpose: PERSONA_DISCORD_DELIVERY_REQUEST_SIGNING_PURPOSE.into(),
|
||||
signed_schema: PERSONA_DISCORD_DELIVERY_REQUEST_SCHEMA_VERSION.into(),
|
||||
binding_authority: "root".into(),
|
||||
bound_at_unix_millis: chrono::Utc::now().timestamp_millis().max(1) as u64,
|
||||
expires_at_unix_millis: None,
|
||||
private_state_exposed: false,
|
||||
};
|
||||
record.validate()?;
|
||||
if let Some(parent) = output.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::write(output, rmp_serde::to_vec(&record)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn request_signing_payload(request: &PersonaDiscordDeliveryRequest) -> Result<Vec<u8>> {
|
||||
Ok(rmp_serde::to_vec(&request_signing_tuple(request))?)
|
||||
}
|
||||
|
||||
pub fn request_payload_sha256(request: &PersonaDiscordDeliveryRequest) -> Result<String> {
|
||||
Ok(sha256_hyphen(&request_signing_payload(request)?))
|
||||
}
|
||||
|
||||
pub fn verify_persona_discord_delivery_receipt(
|
||||
receipt: &PersonaDiscordDeliveryReceipt,
|
||||
request: &PersonaDiscordDeliveryRequest,
|
||||
anchor: &GameCultServiceTrustAnchorRecord,
|
||||
) -> Result<()> {
|
||||
validate_service_anchor(
|
||||
anchor,
|
||||
BIFROST_PERSONA_DELIVERY_SERVICE_ID,
|
||||
BIFROST_PERSONA_DELIVERY_RUNTIME_ID,
|
||||
PERSONA_DISCORD_DELIVERY_RECEIPT_SIGNING_PURPOSE,
|
||||
PERSONA_DISCORD_DELIVERY_RECEIPT_SCHEMA_VERSION,
|
||||
)?;
|
||||
validate_receipt_shape(receipt)?;
|
||||
if receipt.request_id != request.request_id
|
||||
|| receipt.receipt_id != request.request_id
|
||||
|| receipt.channel_id != request.channel_id
|
||||
|| receipt.reply_to_message_id != request.reply_to_message_id
|
||||
|| receipt.request_payload_sha256 != request_payload_sha256(request)?
|
||||
|| receipt.provider_identity_id != anchor.signer_identity_id
|
||||
{
|
||||
bail!("Bifrost Persona delivery receipt is not bound to the exact request");
|
||||
}
|
||||
verify_service_identity_signature_with_public_key::<
|
||||
BifrostPersonaDeliveryReceiptIdentity,
|
||||
BifrostPersonaDeliveryReceiptPurpose,
|
||||
>(
|
||||
&anchor.signer_public_key,
|
||||
&receipt_signing_payload(receipt)?,
|
||||
&ServiceIdentitySignature {
|
||||
identity_id: receipt.provider_identity_id.clone(),
|
||||
signature: receipt.provider_signature.clone(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn receipt_signing_payload(receipt: &PersonaDiscordDeliveryReceipt) -> Result<Vec<u8>> {
|
||||
Ok(rmp_serde::to_vec(&receipt_signing_tuple(receipt))?)
|
||||
}
|
||||
|
||||
pub fn insert_persona_discord_delivery_request(
|
||||
path: &Path,
|
||||
request: &PersonaDiscordDeliveryRequest,
|
||||
) -> Result<()> {
|
||||
validate_request_shape(request)?;
|
||||
if request.signer_signature.len() != 64 {
|
||||
bail!("Persona delivery request signature must be 64 bytes");
|
||||
}
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<PersonaDiscordDeliveryRequest>()?;
|
||||
let (entry, _) = cache.prepare_entry(&request.request_id, request)?;
|
||||
if !SingleFileMessagePackBackingStore::new(path).insert_entry_if_absent(entry)? {
|
||||
let existing = load_persona_discord_delivery_request(path, &request.request_id)?;
|
||||
if existing.as_ref() != Some(request) {
|
||||
bail!("Persona delivery request identity collision");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_persona_discord_delivery_request(
|
||||
path: &Path,
|
||||
id: &str,
|
||||
) -> Result<Option<PersonaDiscordDeliveryRequest>> {
|
||||
load_exact(path, id)
|
||||
}
|
||||
|
||||
pub fn load_persona_discord_delivery_receipt(
|
||||
path: &Path,
|
||||
id: &str,
|
||||
) -> Result<Option<PersonaDiscordDeliveryReceipt>> {
|
||||
load_exact(path, id)
|
||||
}
|
||||
|
||||
pub fn load_persona_discord_receipt_anchor(
|
||||
path: &Path,
|
||||
) -> Result<GameCultServiceTrustAnchorRecord> {
|
||||
load_persona_discord_service_anchor(path)
|
||||
}
|
||||
|
||||
pub fn load_persona_discord_service_anchor(
|
||||
path: &Path,
|
||||
) -> Result<GameCultServiceTrustAnchorRecord> {
|
||||
let bytes = std::fs::read(path)?;
|
||||
rmp_serde::from_slice(&bytes)
|
||||
.map_err(|error| anyhow!("Bifrost trust anchor is malformed: {error}"))
|
||||
}
|
||||
|
||||
pub fn validate_persona_discord_request_anchor(
|
||||
anchor: &GameCultServiceTrustAnchorRecord,
|
||||
expected_runtime_id: &str,
|
||||
) -> Result<()> {
|
||||
validate_service_anchor(
|
||||
anchor,
|
||||
EPIPHANY_PERSONA_MOUTH_SERVICE_ID,
|
||||
expected_runtime_id,
|
||||
PERSONA_DISCORD_DELIVERY_REQUEST_SIGNING_PURPOSE,
|
||||
PERSONA_DISCORD_DELIVERY_REQUEST_SCHEMA_VERSION,
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_service_anchor(
|
||||
anchor: &GameCultServiceTrustAnchorRecord,
|
||||
service_id: &str,
|
||||
runtime_id: &str,
|
||||
purpose: &str,
|
||||
schema: &str,
|
||||
) -> Result<()> {
|
||||
anchor.validate()?;
|
||||
let now = chrono::Utc::now().timestamp_millis().max(0) as u64;
|
||||
if anchor.schema_version != GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA
|
||||
|| anchor.service_id != service_id
|
||||
|| anchor.runtime_id != runtime_id
|
||||
|| anchor.signing_purpose != purpose
|
||||
|| anchor.signed_schema != schema
|
||||
|| anchor.binding_authority != "root"
|
||||
|| anchor.signature_algorithm != "ed25519"
|
||||
|| anchor.bound_at_unix_millis > now
|
||||
|| anchor
|
||||
.expires_at_unix_millis
|
||||
.is_some_and(|expiry| expiry <= now)
|
||||
|| anchor.private_state_exposed
|
||||
{
|
||||
bail!("service trust anchor does not bind the exact Persona Discord crossing profile");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_exact<T: DatabaseEntry>(path: &Path, id: &str) -> Result<Option<T>> {
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let entries = SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()?;
|
||||
let mut found = None;
|
||||
for entry in entries {
|
||||
if entry.key != id {
|
||||
continue;
|
||||
}
|
||||
if entry.r#type != T::TYPE {
|
||||
bail!("crossing store key is occupied by an alien document type");
|
||||
}
|
||||
if found.is_some() {
|
||||
bail!("crossing store contains duplicate records for one key");
|
||||
}
|
||||
found = Some(rmp_serde::from_slice(&entry.payload)?);
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn validate_request_shape(value: &PersonaDiscordDeliveryRequest) -> Result<()> {
|
||||
let issued = chrono::DateTime::parse_from_rfc3339(&value.issued_at)
|
||||
.map_err(|_| anyhow!("Persona delivery issuedAt is not RFC3339"))?;
|
||||
let expires = chrono::DateTime::parse_from_rfc3339(&value.expires_at)
|
||||
.map_err(|_| anyhow!("Persona delivery expiresAt is not RFC3339"))?;
|
||||
if value.schema_version != PERSONA_DISCORD_DELIVERY_REQUEST_SCHEMA_VERSION
|
||||
|| !valid_crossing_id(&value.request_id, false)
|
||||
|| !valid_crossing_id(&value.effect_document_id, false)
|
||||
|| !valid_crossing_id(&value.target_runtime_id, false)
|
||||
|| !valid_crossing_id(&value.persona_agent_id, false)
|
||||
|| !valid_crossing_id(&value.channel_id, false)
|
||||
|| !valid_crossing_id(&value.reply_to_message_id, true)
|
||||
|| value.content.trim().is_empty()
|
||||
|| value.content.len() > 1900
|
||||
|| value.content.contains('\0')
|
||||
|| value.content_sha256 != sha256_hyphen(value.content.as_bytes())
|
||||
|| value.issued_at.trim().is_empty()
|
||||
|| value.expires_at.trim().is_empty()
|
||||
|| expires <= issued
|
||||
|| expires - issued > chrono::Duration::seconds(120)
|
||||
|| value.private_state_exposed
|
||||
|| !valid_crossing_id(&value.signer_identity_id, false)
|
||||
{
|
||||
bail!("Persona Discord delivery request violates its fixed contract");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn valid_crossing_id(value: &str, allow_empty: bool) -> bool {
|
||||
(allow_empty || !value.trim().is_empty())
|
||||
&& value.len() <= 256
|
||||
&& !value.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
fn validate_receipt_shape(value: &PersonaDiscordDeliveryReceipt) -> Result<()> {
|
||||
let evidence = [
|
||||
&value.message_id,
|
||||
&value.transport,
|
||||
&value.crossing_receipt_id,
|
||||
&value.receipt_url,
|
||||
];
|
||||
let sha_valid = value.request_payload_sha256.len() == 71
|
||||
&& value.request_payload_sha256.starts_with("sha256-")
|
||||
&& value.request_payload_sha256[7..]
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase());
|
||||
let completed_at_valid = chrono::DateTime::parse_from_rfc3339(&value.completed_at).is_ok();
|
||||
let url_bound = value.status != "completed"
|
||||
|| value
|
||||
.receipt_url
|
||||
.contains(&format!("/{}/{}", value.channel_id, value.message_id));
|
||||
if value.schema_version != PERSONA_DISCORD_DELIVERY_RECEIPT_SCHEMA_VERSION
|
||||
|| value.receipt_id != value.request_id
|
||||
|| value.request_id.trim().is_empty()
|
||||
|| !matches!(value.status.as_str(), "completed" | "failed" | "unknown")
|
||||
|| value.channel_id.trim().is_empty()
|
||||
|| !completed_at_valid
|
||||
|| !sha_valid
|
||||
|| !url_bound
|
||||
|| value.provider_identity_id.trim().is_empty()
|
||||
|| value.private_state_exposed
|
||||
|| value.provider_signature.len() != 64
|
||||
|| (value.status == "completed" && evidence.iter().any(|field| field.is_empty()))
|
||||
|| (value.status != "completed" && evidence.iter().any(|field| !field.is_empty()))
|
||||
{
|
||||
bail!("Bifrost Persona Discord delivery receipt violates its fixed contract");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn request_signing_tuple(value: &PersonaDiscordDeliveryRequest) -> impl Serialize + '_ {
|
||||
(
|
||||
&value.schema_version,
|
||||
&value.request_id,
|
||||
&value.effect_document_id,
|
||||
&value.target_runtime_id,
|
||||
&value.persona_agent_id,
|
||||
&value.channel_id,
|
||||
&value.reply_to_message_id,
|
||||
&value.content,
|
||||
&value.content_sha256,
|
||||
&value.issued_at,
|
||||
&value.expires_at,
|
||||
value.private_state_exposed,
|
||||
&value.signer_identity_id,
|
||||
)
|
||||
}
|
||||
fn receipt_signing_tuple(value: &PersonaDiscordDeliveryReceipt) -> impl Serialize + '_ {
|
||||
(
|
||||
&value.schema_version,
|
||||
&value.receipt_id,
|
||||
&value.request_id,
|
||||
&value.request_payload_sha256,
|
||||
&value.status,
|
||||
&value.channel_id,
|
||||
&value.reply_to_message_id,
|
||||
&value.message_id,
|
||||
&value.transport,
|
||||
&value.crossing_receipt_id,
|
||||
&value.receipt_url,
|
||||
&value.completed_at,
|
||||
&value.provider_identity_id,
|
||||
value.private_state_exposed,
|
||||
)
|
||||
}
|
||||
fn sha256_hyphen(bytes: &[u8]) -> String {
|
||||
format!("sha256-{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
585
epiphany-core/src/persona_discord_permit.rs
Normal file
585
epiphany-core/src/persona_discord_permit.rs
Normal file
|
|
@ -0,0 +1,585 @@
|
|||
use std::{
|
||||
net::UdpSocket,
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use cultnet_rs::{
|
||||
CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding,
|
||||
CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetWireContract,
|
||||
GameCultServiceTrustAnchorRecord, ServiceIdentityProfile, ServiceIdentitySignature,
|
||||
ServiceIdentitySigner, ServiceSignaturePurpose, decode_cultnet_message_from_slice,
|
||||
encode_cultnet_message_to_vec, verify_service_identity_signature_with_public_key,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub const PERMIT_REQUEST_SCHEMA: &str = "bifrost.persona_discord_delivery_permit_request.v0";
|
||||
pub const PERMIT_SCHEMA: &str = "epiphany.persona_discord_delivery_permit.v0";
|
||||
pub const PERMIT_REQUEST_PURPOSE: &str = "bifrost.persona-discord.delivery-permit-request.v0";
|
||||
pub const PERMIT_PURPOSE: &str = "epiphany.persona-discord.delivery-permit.v0";
|
||||
pub const PERMIT_RUDP_CONNECTION_ID: u32 = 0xe91f_0002;
|
||||
|
||||
pub enum BifrostPermitRequestIdentity {}
|
||||
pub struct BifrostPermitRequestPurpose;
|
||||
pub enum EpiphanyPermitIdentity {}
|
||||
pub struct EpiphanyPermitPurpose;
|
||||
|
||||
macro_rules! profile {
|
||||
($profile:ty,$purpose:ty,$prefix:literal,$id:literal,$sig:literal,$purpose_value:ident) => {
|
||||
impl ServiceIdentityProfile for $profile {
|
||||
const PRIVATE_TYPE: &'static str = concat!($prefix, ".identity.private.v0");
|
||||
const PRIVATE_SCHEMA: &'static str = Self::PRIVATE_TYPE;
|
||||
const PRIVATE_KEY: &'static str = concat!($prefix, "-identity");
|
||||
const TRUST_ANCHOR_TYPE: &'static str = concat!($prefix, ".identity.trust_anchor.v0");
|
||||
const TRUST_ANCHOR_SCHEMA: &'static str = Self::TRUST_ANCHOR_TYPE;
|
||||
const TRUST_ANCHOR_KEY: &'static str = concat!($prefix, "-identity-public");
|
||||
const ID_DOMAIN: &'static [u8] = $id;
|
||||
const SIGNATURE_DOMAIN: &'static [u8] = $sig;
|
||||
const PROTECTOR_CONTEXT: &'static str = concat!($prefix, "-v0");
|
||||
}
|
||||
impl ServiceSignaturePurpose<$profile> for $purpose {
|
||||
const PURPOSE: &'static [u8] = $purpose_value.as_bytes();
|
||||
}
|
||||
};
|
||||
}
|
||||
profile!(
|
||||
BifrostPermitRequestIdentity,
|
||||
BifrostPermitRequestPurpose,
|
||||
"bifrost.persona_discord_delivery_permit_request",
|
||||
b"bifrost.persona-discord-delivery-permit-request.identity.v0\0",
|
||||
b"bifrost.persona-discord-delivery-permit-request.signature.v0\0",
|
||||
PERMIT_REQUEST_PURPOSE
|
||||
);
|
||||
profile!(
|
||||
EpiphanyPermitIdentity,
|
||||
EpiphanyPermitPurpose,
|
||||
"epiphany.persona_discord_delivery_permit",
|
||||
b"epiphany.persona-discord-delivery-permit.identity.v0\0",
|
||||
b"epiphany.persona-discord-delivery-permit.signature.v0\0",
|
||||
PERMIT_PURPOSE
|
||||
);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "bifrost.persona_discord_delivery_permit_request",
|
||||
schema = "bifrost.persona_discord_delivery_permit_request.v0"
|
||||
)]
|
||||
pub struct PersonaDiscordPermitRequest {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub request_payload_sha256: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub target_runtime_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub nonce: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub issued_at: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub expires_at: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub requester_identity_id: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub private_state_exposed: bool,
|
||||
#[cultcache(key = 9)]
|
||||
pub requester_signature: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_discord_delivery_permit",
|
||||
schema = "epiphany.persona_discord_delivery_permit.v0"
|
||||
)]
|
||||
pub struct PersonaDiscordPermit {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub permit_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub request_payload_sha256: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub target_runtime_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub nonce: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub requester_identity_id: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub brake_state_document_id: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub brake_state_document_sha256: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub brake_observed_at: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub issued_at: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub expires_at: String,
|
||||
#[cultcache(key = 12)]
|
||||
pub provider_identity_id: String,
|
||||
#[cultcache(key = 13)]
|
||||
pub private_state_exposed: bool,
|
||||
#[cultcache(key = 14)]
|
||||
pub provider_signature: Vec<u8>,
|
||||
}
|
||||
|
||||
pub struct PersonaPermitIssuerConfig {
|
||||
pub runtime_id: String,
|
||||
pub cultmesh_store: PathBuf,
|
||||
pub replay_store: PathBuf,
|
||||
pub requester_anchor: GameCultServiceTrustAnchorRecord,
|
||||
pub provider_anchor: GameCultServiceTrustAnchorRecord,
|
||||
}
|
||||
|
||||
pub fn ensure_epiphany_permit_identity(
|
||||
identity_store: &Path,
|
||||
anchor_output: &Path,
|
||||
runtime_id: &str,
|
||||
) -> Result<()> {
|
||||
let signer = if identity_store.exists() {
|
||||
cultnet_rs::open_service_identity_at::<EpiphanyPermitIdentity>(identity_store)?
|
||||
} else {
|
||||
cultnet_rs::enroll_service_identity_at::<EpiphanyPermitIdentity>(identity_store)?
|
||||
};
|
||||
if anchor_output.exists() {
|
||||
let anchor: GameCultServiceTrustAnchorRecord =
|
||||
rmp_serde::from_slice(&std::fs::read(anchor_output)?)?;
|
||||
anchor.validate()?;
|
||||
if anchor.service_id != "epiphany-persona-discord-permit"
|
||||
|| anchor.runtime_id != runtime_id
|
||||
|| anchor.signer_identity_id != signer.entry().identity_id
|
||||
|| anchor.signer_public_key != signer.entry().public_key
|
||||
|| anchor.signing_purpose != PERMIT_PURPOSE
|
||||
|| anchor.signed_schema != PERMIT_SCHEMA
|
||||
{
|
||||
bail!("existing permit anchor candidate differs from enrolled identity/profile");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let anchor = GameCultServiceTrustAnchorRecord {
|
||||
schema_version: cultnet_rs::GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(),
|
||||
trust_anchor_id: format!("epiphany-persona-discord-permit:{runtime_id}:v0"),
|
||||
service_id: "epiphany-persona-discord-permit".into(),
|
||||
runtime_id: runtime_id.into(),
|
||||
signer_identity_id: signer.entry().identity_id.clone(),
|
||||
signer_public_key: signer.entry().public_key.clone(),
|
||||
signature_algorithm: "ed25519".into(),
|
||||
signing_purpose: PERMIT_PURPOSE.into(),
|
||||
signed_schema: PERMIT_SCHEMA.into(),
|
||||
binding_authority: "root".into(),
|
||||
bound_at_unix_millis: chrono::Utc::now().timestamp_millis().max(1) as u64,
|
||||
expires_at_unix_millis: None,
|
||||
private_state_exposed: false,
|
||||
};
|
||||
anchor.validate()?;
|
||||
if let Some(parent) = anchor_output.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::write(anchor_output, rmp_serde::to_vec(&anchor)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn issue_persona_discord_permit(
|
||||
config: &PersonaPermitIssuerConfig,
|
||||
signer: &ServiceIdentitySigner<EpiphanyPermitIdentity>,
|
||||
request: &PersonaDiscordPermitRequest,
|
||||
) -> Result<PersonaDiscordPermit> {
|
||||
validate_provider_anchor(config, signer)?;
|
||||
validate_request(config, request)?;
|
||||
let key = format!("permit:{}", request.request_payload_sha256);
|
||||
if let Some(existing) = load_permit(&config.replay_store, &key)? {
|
||||
validate_permit_request_binding(&existing, request)?;
|
||||
return Ok(existing);
|
||||
}
|
||||
let brake =
|
||||
crate::load_epiphany_cultmesh_swarm_brake(&config.cultmesh_store, &config.runtime_id)?
|
||||
.ok_or_else(|| anyhow!("permit issuer requires canonical brake state"))?;
|
||||
if brake.status != "released" {
|
||||
bail!("permit issuer is braked");
|
||||
}
|
||||
let brake_bytes = rmp_serde::to_vec(&brake)?;
|
||||
let issued = chrono::Utc::now();
|
||||
let mut permit = PersonaDiscordPermit {
|
||||
schema_version: PERMIT_SCHEMA.into(),
|
||||
permit_id: key.clone(),
|
||||
request_id: request.request_id.clone(),
|
||||
request_payload_sha256: request.request_payload_sha256.clone(),
|
||||
target_runtime_id: request.target_runtime_id.clone(),
|
||||
nonce: request.nonce.clone(),
|
||||
requester_identity_id: request.requester_identity_id.clone(),
|
||||
brake_state_document_id: brake.brake_id.clone(),
|
||||
brake_state_document_sha256: format!("sha256-{:x}", Sha256::digest(brake_bytes)),
|
||||
brake_observed_at: issued.to_rfc3339(),
|
||||
issued_at: issued.to_rfc3339(),
|
||||
expires_at: (issued + chrono::Duration::seconds(5)).to_rfc3339(),
|
||||
provider_identity_id: signer.entry().identity_id.clone(),
|
||||
private_state_exposed: false,
|
||||
provider_signature: vec![],
|
||||
};
|
||||
let proof = signer.sign::<EpiphanyPermitPurpose>(&permit_signing_payload(&permit)?);
|
||||
permit.provider_signature = proof.signature;
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<PersonaDiscordPermit>()?;
|
||||
let (entry, _) = cache.prepare_entry(&key, &permit)?;
|
||||
if !SingleFileMessagePackBackingStore::new(&config.replay_store)
|
||||
.insert_entry_if_absent(entry)?
|
||||
{
|
||||
let existing = load_permit(&config.replay_store, &key)?
|
||||
.ok_or_else(|| anyhow!("permit replay race lost without record"))?;
|
||||
if existing != permit {
|
||||
bail!("permit replay key collision");
|
||||
}
|
||||
return Ok(existing);
|
||||
}
|
||||
Ok(permit)
|
||||
}
|
||||
|
||||
fn validate_provider_anchor(
|
||||
config: &PersonaPermitIssuerConfig,
|
||||
signer: &ServiceIdentitySigner<EpiphanyPermitIdentity>,
|
||||
) -> Result<()> {
|
||||
let anchor = &config.provider_anchor;
|
||||
anchor.validate()?;
|
||||
let now = chrono::Utc::now().timestamp_millis().max(0) as u64;
|
||||
if anchor.service_id != "epiphany-persona-discord-permit"
|
||||
|| anchor.runtime_id != config.runtime_id
|
||||
|| anchor.signer_identity_id != signer.entry().identity_id
|
||||
|| anchor.signer_public_key != signer.entry().public_key
|
||||
|| anchor.signing_purpose != PERMIT_PURPOSE
|
||||
|| anchor.signed_schema != PERMIT_SCHEMA
|
||||
|| anchor.bound_at_unix_millis > now
|
||||
|| anchor
|
||||
.expires_at_unix_millis
|
||||
.is_some_and(|expiry| expiry <= now)
|
||||
{
|
||||
bail!("permit provider anchor is not the exact current root binding")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_request(
|
||||
config: &PersonaPermitIssuerConfig,
|
||||
value: &PersonaDiscordPermitRequest,
|
||||
) -> Result<()> {
|
||||
let anchor = &config.requester_anchor;
|
||||
anchor.validate()?;
|
||||
let now_millis = chrono::Utc::now().timestamp_millis().max(0) as u64;
|
||||
if anchor.service_id != "bifrost-persona-discord-delivery"
|
||||
|| anchor.runtime_id != "bifrost-discord-yggdrasil"
|
||||
|| anchor.signing_purpose != PERMIT_REQUEST_PURPOSE
|
||||
|| anchor.signed_schema != PERMIT_REQUEST_SCHEMA
|
||||
|| anchor.bound_at_unix_millis > now_millis
|
||||
|| anchor
|
||||
.expires_at_unix_millis
|
||||
.is_some_and(|expiry| expiry <= now_millis)
|
||||
|| value.schema_version != PERMIT_REQUEST_SCHEMA
|
||||
|| value.target_runtime_id != config.runtime_id
|
||||
|| value.private_state_exposed
|
||||
|| value.requester_identity_id != anchor.signer_identity_id
|
||||
|| !sha(&value.request_payload_sha256)
|
||||
|| value.requester_signature.len() != 64
|
||||
{
|
||||
bail!("permit request contract or anchor binding is invalid");
|
||||
}
|
||||
let issued = chrono::DateTime::parse_from_rfc3339(&value.issued_at)?;
|
||||
let expires = chrono::DateTime::parse_from_rfc3339(&value.expires_at)?;
|
||||
let now = chrono::Utc::now();
|
||||
if expires <= issued
|
||||
|| expires - issued > chrono::Duration::seconds(5)
|
||||
|| issued > now + chrono::Duration::seconds(1)
|
||||
|| expires < now
|
||||
{
|
||||
bail!("permit request is stale or has an invalid lifetime");
|
||||
}
|
||||
verify_service_identity_signature_with_public_key::<
|
||||
BifrostPermitRequestIdentity,
|
||||
BifrostPermitRequestPurpose,
|
||||
>(
|
||||
&anchor.signer_public_key,
|
||||
&permit_request_signing_payload(value)?,
|
||||
&ServiceIdentitySignature {
|
||||
identity_id: value.requester_identity_id.clone(),
|
||||
signature: value.requester_signature.clone(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_permit_request_binding(
|
||||
value: &PersonaDiscordPermit,
|
||||
request: &PersonaDiscordPermitRequest,
|
||||
) -> Result<()> {
|
||||
if value.request_id != request.request_id
|
||||
|| value.request_payload_sha256 != request.request_payload_sha256
|
||||
|| value.target_runtime_id != request.target_runtime_id
|
||||
|| value.nonce != request.nonce
|
||||
|| value.requester_identity_id != request.requester_identity_id
|
||||
{
|
||||
bail!("permit replay substituted request authority");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn permit_request_signing_payload(v: &PersonaDiscordPermitRequest) -> Result<Vec<u8>> {
|
||||
Ok(rmp_serde::to_vec(&(
|
||||
v.schema_version.as_str(),
|
||||
v.request_id.as_str(),
|
||||
v.request_payload_sha256.as_str(),
|
||||
v.target_runtime_id.as_str(),
|
||||
v.nonce.as_str(),
|
||||
v.issued_at.as_str(),
|
||||
v.expires_at.as_str(),
|
||||
v.requester_identity_id.as_str(),
|
||||
v.private_state_exposed,
|
||||
))?)
|
||||
}
|
||||
pub fn permit_signing_payload(v: &PersonaDiscordPermit) -> Result<Vec<u8>> {
|
||||
Ok(rmp_serde::to_vec(&(
|
||||
v.schema_version.as_str(),
|
||||
v.permit_id.as_str(),
|
||||
v.request_id.as_str(),
|
||||
v.request_payload_sha256.as_str(),
|
||||
v.target_runtime_id.as_str(),
|
||||
v.nonce.as_str(),
|
||||
v.requester_identity_id.as_str(),
|
||||
v.brake_state_document_id.as_str(),
|
||||
v.brake_state_document_sha256.as_str(),
|
||||
v.brake_observed_at.as_str(),
|
||||
v.issued_at.as_str(),
|
||||
v.expires_at.as_str(),
|
||||
v.provider_identity_id.as_str(),
|
||||
v.private_state_exposed,
|
||||
))?)
|
||||
}
|
||||
fn sha(v: &str) -> bool {
|
||||
v.len() == 71
|
||||
&& v.starts_with("sha256-")
|
||||
&& v[7..]
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
|
||||
}
|
||||
fn load_permit(path: &Path, key: &str) -> Result<Option<PersonaDiscordPermit>> {
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
};
|
||||
for row in SingleFileMessagePackBackingStore::new(path).pull_all_read_only_snapshot()? {
|
||||
if row.key == key {
|
||||
if row.r#type != PersonaDiscordPermit::TYPE {
|
||||
bail!("permit replay key occupied by alien type")
|
||||
};
|
||||
return Ok(Some(rmp_serde::from_slice(&row.payload)?));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn serve_persona_discord_permit_rudp(
|
||||
socket: UdpSocket,
|
||||
config: &PersonaPermitIssuerConfig,
|
||||
signer: &ServiceIdentitySigner<EpiphanyPermitIdentity>,
|
||||
) -> Result<()> {
|
||||
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
|
||||
let mut transport =
|
||||
CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::server(
|
||||
&config.runtime_id,
|
||||
socket,
|
||||
PERMIT_RUDP_CONNECTION_ID,
|
||||
))?;
|
||||
loop {
|
||||
match transport.receive_once() {
|
||||
Ok(Some(frame)) => {
|
||||
if let Ok(reply) = process_frame(config, signer, &frame.payload) {
|
||||
let payload = encode_cultnet_message_to_vec(
|
||||
&reply,
|
||||
CultNetWireContract::CultNetSchemaV0,
|
||||
)?;
|
||||
transport.send("schema", payload)?;
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => eprintln!("permit issuer discarded hostile frame: {error:#}"),
|
||||
}
|
||||
transport.poll_resends()?;
|
||||
}
|
||||
}
|
||||
fn process_frame(
|
||||
config: &PersonaPermitIssuerConfig,
|
||||
signer: &ServiceIdentitySigner<EpiphanyPermitIdentity>,
|
||||
payload: &[u8],
|
||||
) -> Result<CultNetMessage> {
|
||||
let message = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0)
|
||||
.context("permit issuer rejected non-CultNet payload")?;
|
||||
let CultNetMessage::DocumentPutRaw { document, .. } = message else {
|
||||
bail!("permit issuer accepts one raw typed request")
|
||||
};
|
||||
if document.schema_id != PERMIT_REQUEST_SCHEMA
|
||||
|| document.payload_encoding != CultNetRawPayloadEncoding::Messagepack
|
||||
|| document.source_role.as_deref() != Some("bifrost-persona-discord-delivery")
|
||||
{
|
||||
bail!("foreign permit request envelope")
|
||||
}
|
||||
let request: PersonaDiscordPermitRequest = rmp_serde::from_slice(&document.payload)?;
|
||||
if document.record_key != request.request_id
|
||||
|| document.source_runtime_id.as_deref() != Some("bifrost-discord-yggdrasil")
|
||||
|| document.source_agent_id.as_deref() != Some(request.requester_identity_id.as_str())
|
||||
|| document.tags.as_deref() != Some(&["cultnet.transport.rudp.v0".to_string()])
|
||||
{
|
||||
bail!("permit envelope identity substitution")
|
||||
}
|
||||
let permit = issue_persona_discord_permit(config, signer, &request)?;
|
||||
Ok(CultNetMessage::DocumentPutRaw {
|
||||
message_id: format!("permit-{}", permit.permit_id),
|
||||
document: CultNetRawDocumentRecord {
|
||||
schema_id: PERMIT_SCHEMA.into(),
|
||||
record_key: permit.permit_id.clone(),
|
||||
stored_at: permit.issued_at.clone(),
|
||||
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
|
||||
payload: rmp_serde::to_vec(&permit)?,
|
||||
source_runtime_id: Some(config.runtime_id.clone()),
|
||||
source_agent_id: Some(permit.provider_identity_id.clone()),
|
||||
source_role: Some("epiphany-persona-discord-permit".into()),
|
||||
tags: Some(vec!["cultnet.transport.rudp.v0".into()]),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn anchor(
|
||||
service: &str,
|
||||
runtime: &str,
|
||||
identity_id: String,
|
||||
public_key: Vec<u8>,
|
||||
purpose: &str,
|
||||
schema: &str,
|
||||
) -> GameCultServiceTrustAnchorRecord {
|
||||
GameCultServiceTrustAnchorRecord {
|
||||
schema_version: cultnet_rs::GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA.into(),
|
||||
trust_anchor_id: format!("{service}:{runtime}:{schema}"),
|
||||
service_id: service.into(),
|
||||
runtime_id: runtime.into(),
|
||||
signer_identity_id: identity_id,
|
||||
signer_public_key: public_key,
|
||||
signature_algorithm: "ed25519".into(),
|
||||
signing_purpose: purpose.into(),
|
||||
signed_schema: schema.into(),
|
||||
binding_authority: "root".into(),
|
||||
bound_at_unix_millis: chrono::Utc::now().timestamp_millis().max(1) as u64,
|
||||
expires_at_unix_millis: None,
|
||||
private_state_exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_nonce_cannot_reauthorize_one_delivery_request() {
|
||||
let permit = PersonaDiscordPermit {
|
||||
schema_version: PERMIT_SCHEMA.into(),
|
||||
permit_id: "permit:sha256-x".into(),
|
||||
request_id: "delivery-1".into(),
|
||||
request_payload_sha256: format!("sha256-{}", "a".repeat(64)),
|
||||
target_runtime_id: "epiphany-yggdrasil".into(),
|
||||
nonce: "nonce-1".into(),
|
||||
requester_identity_id: "bifrost".into(),
|
||||
brake_state_document_id: "epiphany/swarm-brake".into(),
|
||||
brake_state_document_sha256: format!("sha256-{}", "b".repeat(64)),
|
||||
brake_observed_at: "2026-07-21T00:00:00Z".into(),
|
||||
issued_at: "2026-07-21T00:00:00Z".into(),
|
||||
expires_at: "2026-07-21T00:00:05Z".into(),
|
||||
provider_identity_id: "epiphany".into(),
|
||||
private_state_exposed: false,
|
||||
provider_signature: vec![0; 64],
|
||||
};
|
||||
let request = PersonaDiscordPermitRequest {
|
||||
schema_version: PERMIT_REQUEST_SCHEMA.into(),
|
||||
request_id: "delivery-1".into(),
|
||||
request_payload_sha256: permit.request_payload_sha256.clone(),
|
||||
target_runtime_id: permit.target_runtime_id.clone(),
|
||||
nonce: "nonce-2".into(),
|
||||
issued_at: "2026-07-21T00:00:00Z".into(),
|
||||
expires_at: "2026-07-21T00:00:05Z".into(),
|
||||
requester_identity_id: permit.requester_identity_id.clone(),
|
||||
private_state_exposed: false,
|
||||
requester_signature: vec![0; 64],
|
||||
};
|
||||
assert!(validate_permit_request_binding(&permit, &request).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cultnet_wire_request_issues_one_exact_replayable_permit() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let requester = cultnet_rs::enroll_service_identity_at::<BifrostPermitRequestIdentity>(
|
||||
&temp.path().join("requester.cc"),
|
||||
)?;
|
||||
let provider = cultnet_rs::enroll_service_identity_at::<EpiphanyPermitIdentity>(
|
||||
&temp.path().join("provider.cc"),
|
||||
)?;
|
||||
let request_anchor = anchor(
|
||||
"bifrost-persona-discord-delivery",
|
||||
"bifrost-discord-yggdrasil",
|
||||
requester.entry().identity_id.clone(),
|
||||
requester.entry().public_key.clone(),
|
||||
PERMIT_REQUEST_PURPOSE,
|
||||
PERMIT_REQUEST_SCHEMA,
|
||||
);
|
||||
let provider_anchor = anchor(
|
||||
"epiphany-persona-discord-permit",
|
||||
"epiphany-yggdrasil",
|
||||
provider.entry().identity_id.clone(),
|
||||
provider.entry().public_key.clone(),
|
||||
PERMIT_PURPOSE,
|
||||
PERMIT_SCHEMA,
|
||||
);
|
||||
let cultmesh = temp.path().join("cultmesh.cc");
|
||||
crate::write_epiphany_cultmesh_swarm_brake(
|
||||
&cultmesh,
|
||||
"epiphany-yggdrasil",
|
||||
crate::default_epiphany_cultmesh_swarm_brake(&chrono::Utc::now().to_rfc3339()),
|
||||
)?;
|
||||
let config = PersonaPermitIssuerConfig {
|
||||
runtime_id: "epiphany-yggdrasil".into(),
|
||||
cultmesh_store: cultmesh,
|
||||
replay_store: temp.path().join("replay.cc"),
|
||||
requester_anchor: request_anchor,
|
||||
provider_anchor,
|
||||
};
|
||||
let now = chrono::Utc::now();
|
||||
let mut request = PersonaDiscordPermitRequest {
|
||||
schema_version: PERMIT_REQUEST_SCHEMA.into(),
|
||||
request_id: "delivery-1".into(),
|
||||
request_payload_sha256: format!("sha256-{}", "a".repeat(64)),
|
||||
target_runtime_id: "epiphany-yggdrasil".into(),
|
||||
nonce: "nonce-1".into(),
|
||||
issued_at: now.to_rfc3339(),
|
||||
expires_at: (now + chrono::Duration::seconds(5)).to_rfc3339(),
|
||||
requester_identity_id: requester.entry().identity_id.clone(),
|
||||
private_state_exposed: false,
|
||||
requester_signature: vec![],
|
||||
};
|
||||
request.requester_signature = requester
|
||||
.sign::<BifrostPermitRequestPurpose>(&permit_request_signing_payload(&request)?)
|
||||
.signature;
|
||||
let message = CultNetMessage::DocumentPutRaw {
|
||||
message_id: "permit-request-1".into(),
|
||||
document: CultNetRawDocumentRecord {
|
||||
schema_id: PERMIT_REQUEST_SCHEMA.into(),
|
||||
record_key: request.request_id.clone(),
|
||||
stored_at: request.issued_at.clone(),
|
||||
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
|
||||
payload: rmp_serde::to_vec(&request)?,
|
||||
source_runtime_id: Some("bifrost-discord-yggdrasil".into()),
|
||||
source_agent_id: Some(request.requester_identity_id.clone()),
|
||||
source_role: Some("bifrost-persona-discord-delivery".into()),
|
||||
tags: Some(vec!["cultnet.transport.rudp.v0".into()]),
|
||||
},
|
||||
};
|
||||
let wire = encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0)?;
|
||||
let first = process_frame(&config, &provider, &wire)?;
|
||||
let second = process_frame(&config, &provider, &wire)?;
|
||||
assert_eq!(first, second);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
use anyhow::{Result, anyhow, bail};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use cultcache_rs::{
|
||||
CacheBackingStore, CultCache, CultCacheEnvelope, DatabaseEntry,
|
||||
SingleFileMessagePackBackingStore,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
|
|
@ -14,6 +17,8 @@ pub const BIFROST_PERSONA_FEEDBACK_ADMISSION_SCHEMA_VERSION: &str =
|
|||
pub const BIFROST_PERSONA_FEEDBACK_DELIVERY_TYPE: &str = "bifrost.persona_feedback.delivery";
|
||||
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";
|
||||
const SIGNING_PURPOSE: &str = "bifrost.persona-feedback.delivery.v0";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -104,6 +109,42 @@ pub struct LocalAdmittedPersonaFeedback {
|
|||
pub source_observer_id: String,
|
||||
#[cultcache(key = 18)]
|
||||
pub source_observer_runtime_id: String,
|
||||
#[cultcache(key = 19)]
|
||||
pub source_event_id: String,
|
||||
#[cultcache(key = 20)]
|
||||
pub discord_guild_id: String,
|
||||
#[cultcache(key = 21)]
|
||||
pub discord_channel_id: String,
|
||||
#[cultcache(key = 22)]
|
||||
pub discord_message_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_feedback.heartbeat_bridge.v0",
|
||||
schema = "PersonaFeedbackHeartbeatBridgeReceipt"
|
||||
)]
|
||||
pub struct PersonaFeedbackHeartbeatBridgeReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub receipt_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub feedback_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub admission_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub packet_sha256: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub heartbeat_mention_id: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub discord_channel_id: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub discord_message_id: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub status: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
pub fn persona_feedback_packet_sha256(packet: &PersonaFeedbackPacket) -> Result<String> {
|
||||
|
|
@ -172,13 +213,18 @@ pub fn admit_bifrost_persona_feedback(
|
|||
packet_sha256: admission.packet_sha256.clone(),
|
||||
source_observer_id: admission.source_observer_id.clone(),
|
||||
source_observer_runtime_id: admission.source_observer_runtime_id.clone(),
|
||||
source_event_id: packet.source_event_id.clone(),
|
||||
discord_guild_id: packet.discord_guild_id.clone(),
|
||||
discord_channel_id: packet.discord_channel_id.clone(),
|
||||
discord_message_id: packet.discord_message_id.clone(),
|
||||
};
|
||||
let node = crate::open_epiphany_cultmesh_node(feedback_store, expected_runtime_id.to_string())?;
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<LocalAdmittedPersonaFeedback>()?;
|
||||
let (entry, _) = cache.prepare_entry(&local.feedback_id, &local)?;
|
||||
if !SingleFileMessagePackBackingStore::new(feedback_store).insert_entry_if_absent(entry)? {
|
||||
let existing = node.get::<LocalAdmittedPersonaFeedback>(&local.feedback_id)?;
|
||||
let existing = admitted_persona_feedback(feedback_store, expected_runtime_id)?
|
||||
.into_iter()
|
||||
.find(|feedback| feedback.feedback_id == local.feedback_id);
|
||||
if existing.as_ref() != Some(&local) {
|
||||
return Err(anyhow!("admitted Persona feedback identity collision"));
|
||||
}
|
||||
|
|
@ -195,7 +241,7 @@ fn validate_bifrost_persona_feedback_admission(
|
|||
) -> Result<()> {
|
||||
let packet = &admission.packet;
|
||||
if admission.schema_version != BIFROST_PERSONA_FEEDBACK_ADMISSION_SCHEMA_VERSION
|
||||
|| admission.source_observer_id != "voidbot"
|
||||
|| admission.source_observer_id != "bifrost-discord"
|
||||
|| admission.source_observer_runtime_id.trim().is_empty()
|
||||
|| admission.provider != "bifrost"
|
||||
|| admission.bifrost_admission_receipt_id.trim().is_empty()
|
||||
|
|
@ -213,6 +259,7 @@ fn validate_bifrost_persona_feedback_admission(
|
|||
|| packet.discord_message_id.trim().is_empty()
|
||||
|| !is_sha256(&packet.content_sha256)
|
||||
|| packet.feedback_text.trim().is_empty()
|
||||
|| packet.feedback_text.len() > 1200
|
||||
|| packet.source_discussion_refs.is_empty()
|
||||
|| !matches!(
|
||||
(
|
||||
|
|
@ -252,6 +299,143 @@ fn validate_bifrost_persona_feedback_admission(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn bridge_admitted_persona_feedback_to_heartbeat(
|
||||
feedback_store: &Path,
|
||||
heartbeat_store: &Path,
|
||||
runtime_id: &str,
|
||||
model_provider_id: &str,
|
||||
allowed_data_classifications: &[String],
|
||||
) -> Result<Vec<PersonaFeedbackHeartbeatBridgeReceipt>> {
|
||||
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");
|
||||
}
|
||||
let feedback = admitted_persona_feedback(feedback_store, runtime_id)?;
|
||||
let mut bridged = Vec::new();
|
||||
for admitted in feedback {
|
||||
if !allowed_data_classifications
|
||||
.iter()
|
||||
.any(|allowed| allowed == &admitted.data_classification)
|
||||
{
|
||||
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 (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
|
||||
{
|
||||
bail!("Persona feedback heartbeat bridge identity collision");
|
||||
}
|
||||
if receipt.status == "queued" {
|
||||
continue;
|
||||
}
|
||||
if receipt.status != "pending" {
|
||||
bail!("Persona feedback heartbeat bridge has invalid status");
|
||||
}
|
||||
(receipt, envelope)
|
||||
} else {
|
||||
let receipt = PersonaFeedbackHeartbeatBridgeReceipt {
|
||||
schema_version: PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_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(),
|
||||
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)?;
|
||||
(receipt, envelope)
|
||||
};
|
||||
crate::queue_heartbeat_pending_mention_store(
|
||||
heartbeat_store,
|
||||
crate::HeartbeatQueueMentionOptions {
|
||||
target_role_id: "Persona".into(),
|
||||
source_surface: "bifrost-discord".into(),
|
||||
channel_id: admitted.discord_channel_id.clone(),
|
||||
message_id: admitted.discord_message_id.clone(),
|
||||
author_id: admitted.source_actor_id.clone(),
|
||||
author_name: None,
|
||||
content: admitted.feedback_text.clone(),
|
||||
visible_prompt: admitted.feedback_text.clone(),
|
||||
reply_to_message_id: Some(admitted.discord_message_id.clone()),
|
||||
queued_at: None,
|
||||
mention_id: Some(mention_id.clone()),
|
||||
source_visibility: admitted.source_visibility.clone(),
|
||||
data_classification: admitted.data_classification.clone(),
|
||||
model_provider_id: model_provider_id.to_string(),
|
||||
model_provider_disclosure_allowed: true,
|
||||
},
|
||||
)?;
|
||||
receipt.status = "queued".into();
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<PersonaFeedbackHeartbeatBridgeReceipt>()?;
|
||||
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)?
|
||||
.map(|(receipt, _)| receipt);
|
||||
if raced.as_ref() != Some(&receipt) {
|
||||
bail!("Persona feedback heartbeat bridge receipt lost exact CAS");
|
||||
}
|
||||
}
|
||||
bridged.push(receipt);
|
||||
}
|
||||
Ok(bridged)
|
||||
}
|
||||
|
||||
fn load_persona_feedback_bridge_receipt(
|
||||
feedback_store: &Path,
|
||||
receipt_id: &str,
|
||||
) -> Result<Option<(PersonaFeedbackHeartbeatBridgeReceipt, CultCacheEnvelope)>> {
|
||||
let matches = SingleFileMessagePackBackingStore::new(feedback_store)
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.filter(|entry| {
|
||||
entry.r#type == <PersonaFeedbackHeartbeatBridgeReceipt as DatabaseEntry>::TYPE
|
||||
&& entry.key == receipt_id
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if matches.len() > 1 {
|
||||
bail!("duplicate Persona feedback heartbeat bridge receipt");
|
||||
}
|
||||
matches
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|envelope| {
|
||||
let receipt = rmp_serde::from_slice(&envelope.payload)?;
|
||||
Ok((receipt, envelope))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn insert_pending_persona_feedback_bridge_receipt(
|
||||
feedback_store: &Path,
|
||||
receipt: &PersonaFeedbackHeartbeatBridgeReceipt,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<PersonaFeedbackHeartbeatBridgeReceipt>()?;
|
||||
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)?
|
||||
.filter(|(existing, _)| existing == receipt)
|
||||
.map(|(_, envelope)| envelope)
|
||||
.ok_or_else(|| anyhow!("Persona feedback heartbeat bridge pending receipt collision"));
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
fn is_sha256(value: &str) -> bool {
|
||||
value.strip_prefix("sha256-").is_some_and(|digest| {
|
||||
digest.len() == 64
|
||||
|
|
@ -263,14 +447,17 @@ fn is_sha256(value: &str) -> bool {
|
|||
|
||||
pub fn admitted_persona_feedback(
|
||||
path: &Path,
|
||||
runtime_id: &str,
|
||||
_runtime_id: &str,
|
||||
) -> Result<Vec<LocalAdmittedPersonaFeedback>> {
|
||||
let node = crate::open_epiphany_cultmesh_node(path, runtime_id.to_string())?;
|
||||
let mut feedback = node
|
||||
.get_all_with_keys::<LocalAdmittedPersonaFeedback>()?
|
||||
let mut feedback = SingleFileMessagePackBackingStore::new(path)
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.map(|(_, value)| value)
|
||||
.collect::<Vec<_>>();
|
||||
.filter(|entry| entry.r#type == <LocalAdmittedPersonaFeedback as DatabaseEntry>::TYPE)
|
||||
.map(|entry| {
|
||||
rmp_serde::from_slice::<LocalAdmittedPersonaFeedback>(&entry.payload)
|
||||
.map_err(Into::into)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
feedback.sort_by(|left, right| left.feedback_id.cmp(&right.feedback_id));
|
||||
Ok(feedback)
|
||||
}
|
||||
|
|
@ -453,8 +640,8 @@ mod tests {
|
|||
admission_id: "bifrost-admission-1".into(),
|
||||
packet_sha256: persona_feedback_packet_sha256(&packet)?,
|
||||
packet,
|
||||
source_observer_id: "voidbot".into(),
|
||||
source_observer_runtime_id: "voidbot-yggdrasil".into(),
|
||||
source_observer_id: "bifrost-discord".into(),
|
||||
source_observer_runtime_id: "bifrost-yggdrasil".into(),
|
||||
provider: "bifrost".into(),
|
||||
bifrost_admission_receipt_id: "bifrost-receipt-1".into(),
|
||||
authority: "feedback_only".into(),
|
||||
|
|
@ -497,6 +684,186 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_bridge_receipt_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 signer = crate::enroll_host_identity_at(&temp.path().join("bifrost.cc"))?;
|
||||
let anchor = crate::export_host_identity_trust_anchor(
|
||||
&signer,
|
||||
&temp.path().join("bifrost-anchor.cc"),
|
||||
)?;
|
||||
let delivery = signed_delivery(&signer, "epiphany")?;
|
||||
let admitted = admit_bifrost_persona_feedback(
|
||||
&feedback_store,
|
||||
&delivery,
|
||||
&anchor,
|
||||
"epiphany-yggdrasil",
|
||||
"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),
|
||||
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),
|
||||
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)?;
|
||||
|
||||
let recovered = bridge_admitted_persona_feedback_to_heartbeat(
|
||||
&feedback_store,
|
||||
&heartbeat_store,
|
||||
"epiphany-yggdrasil",
|
||||
"openai-codex",
|
||||
&["public_feedback".to_string()],
|
||||
)?;
|
||||
assert_eq!(recovered.len(), 1);
|
||||
assert_eq!(recovered[0].status, "queued");
|
||||
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");
|
||||
assert_eq!(
|
||||
state.pending_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(
|
||||
&feedback_store,
|
||||
&heartbeat_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()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridge_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 signer = crate::enroll_host_identity_at(&temp.path().join("bifrost.cc"))?;
|
||||
let anchor = crate::export_host_identity_trust_anchor(
|
||||
&signer,
|
||||
&temp.path().join("bifrost-anchor.cc"),
|
||||
)?;
|
||||
let delivery = signed_delivery(&signer, "epiphany")?;
|
||||
let admitted = admit_bifrost_persona_feedback(
|
||||
&feedback_store,
|
||||
&delivery,
|
||||
&anchor,
|
||||
"epiphany-yggdrasil",
|
||||
"GameCult/Epiphany",
|
||||
"epiphany",
|
||||
)?;
|
||||
crate::initialize_heartbeat_store(&heartbeat_store, 1.0)?;
|
||||
insert_pending_persona_feedback_bridge_receipt(
|
||||
&feedback_store,
|
||||
&PersonaFeedbackHeartbeatBridgeReceipt {
|
||||
schema_version: PERSONA_FEEDBACK_HEARTBEAT_BRIDGE_SCHEMA_VERSION.into(),
|
||||
receipt_id: format!("persona-feedback-heartbeat:{}", 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(),
|
||||
discord_channel_id: admitted.discord_channel_id,
|
||||
discord_message_id: admitted.discord_message_id,
|
||||
status: "pending".into(),
|
||||
private_state_exposed: false,
|
||||
},
|
||||
)?;
|
||||
assert!(
|
||||
bridge_admitted_persona_feedback_to_heartbeat(
|
||||
&feedback_store,
|
||||
&heartbeat_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()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
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 signer = crate::enroll_host_identity_at(&temp.path().join("bifrost.cc"))?;
|
||||
let anchor = crate::export_host_identity_trust_anchor(
|
||||
&signer,
|
||||
&temp.path().join("bifrost-anchor.cc"),
|
||||
)?;
|
||||
let delivery = signed_delivery(&signer, "epiphany")?;
|
||||
admit_bifrost_persona_feedback(
|
||||
&feedback_store,
|
||||
&delivery,
|
||||
&anchor,
|
||||
"epiphany-yggdrasil",
|
||||
"GameCult/Epiphany",
|
||||
"epiphany",
|
||||
)?;
|
||||
crate::initialize_heartbeat_store(&heartbeat_store, 1.0)?;
|
||||
assert!(
|
||||
bridge_admitted_persona_feedback_to_heartbeat(
|
||||
&feedback_store,
|
||||
&heartbeat_store,
|
||||
"epiphany-yggdrasil",
|
||||
"openai-codex",
|
||||
&["organization_feedback".to_string()],
|
||||
)?
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
admitted_persona_feedback(&feedback_store, "epiphany-yggdrasil")?.len(),
|
||||
1
|
||||
);
|
||||
assert!(
|
||||
crate::load_heartbeat_state_entry(&heartbeat_store)?
|
||||
.expect("heartbeat state")
|
||||
.pending_mentions
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
load_persona_feedback_bridge_receipt(
|
||||
&feedback_store,
|
||||
"persona-feedback-heartbeat:feedback-1"
|
||||
)?
|
||||
.is_none()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_target_payload_and_provider_substitution() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
|
|
@ -549,6 +916,57 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_limit_is_1200_utf8_bytes_not_unicode_scalars() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let signer = crate::enroll_host_identity_at(&temp.path().join("bifrost.cc"))?;
|
||||
let anchor = crate::export_host_identity_trust_anchor(
|
||||
&signer,
|
||||
&temp.path().join("bifrost-anchor.cc"),
|
||||
)?;
|
||||
let mut delivery = signed_delivery(&signer, "epiphany")?;
|
||||
delivery.packet.feedback_text = "😀".repeat(300);
|
||||
delivery.packet_sha256 = persona_feedback_packet_sha256(&delivery.packet)?;
|
||||
delivery.provider_signature = signer
|
||||
.sign(
|
||||
SIGNING_PURPOSE,
|
||||
&persona_feedback_admission_signing_payload(&delivery)?,
|
||||
)?
|
||||
.signature;
|
||||
assert!(
|
||||
admit_bifrost_persona_feedback(
|
||||
&temp.path().join("accepted.cc"),
|
||||
&delivery,
|
||||
&anchor,
|
||||
"epiphany-yggdrasil",
|
||||
"GameCult/Epiphany",
|
||||
"epiphany",
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
delivery.packet.feedback_text.push('😀');
|
||||
delivery.packet_sha256 = persona_feedback_packet_sha256(&delivery.packet)?;
|
||||
delivery.provider_signature = signer
|
||||
.sign(
|
||||
SIGNING_PURPOSE,
|
||||
&persona_feedback_admission_signing_payload(&delivery)?,
|
||||
)?
|
||||
.signature;
|
||||
assert!(
|
||||
admit_bifrost_persona_feedback(
|
||||
&temp.path().join("rejected.cc"),
|
||||
&delivery,
|
||||
&anchor,
|
||||
"epiphany-yggdrasil",
|
||||
"GameCult/Epiphany",
|
||||
"epiphany",
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_signed_provider_store_into_dedicated_feedback_store() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@ use crate::EpiphanyOrganDependency;
|
|||
use crate::HeartbeatPendingMention;
|
||||
use crate::default_organ_dependencies_for;
|
||||
use crate::render_organ_dependencies;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use epiphany_state_model::EpiphanyMemoryContextPacket;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
|
@ -13,6 +16,135 @@ pub const PERSONA_PROJECTOR_PROMPT_SCHEMA_VERSION: &str =
|
|||
pub const PERSONA_TURN_PROMPT_SCHEMA_VERSION: &str = "epiphany.persona_turn_prompt.v0";
|
||||
pub const PERSONA_INTERPRETER_PROMPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.persona_interpreter_prompt.v0";
|
||||
pub const PERSONA_INTERPRETER_EFFECT_SET_SCHEMA_VERSION: &str =
|
||||
"epiphany.persona_interpreter_effect_set.v0";
|
||||
pub const PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION: &str =
|
||||
"epiphany.persona_interpreter_effect_document.v0";
|
||||
pub const PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.persona_model_stage_receipt.v0";
|
||||
pub const PERSONA_MODEL_TERMINAL_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"epiphany.persona_model_terminal_receipt.v0";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct PersonaInterpreterEffectSet {
|
||||
pub schema_version: String,
|
||||
pub effects: Vec<PersonaInterpreterEffect>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum PersonaInterpreterEffect {
|
||||
StateNote {
|
||||
memory_kind: String,
|
||||
summary: String,
|
||||
#[serde(default)]
|
||||
subject_id: Option<String>,
|
||||
#[serde(default)]
|
||||
confidence: Option<f64>,
|
||||
},
|
||||
Say {
|
||||
channel_id: String,
|
||||
#[serde(default)]
|
||||
reply_to_message_id: Option<String>,
|
||||
content: String,
|
||||
speech_act: String,
|
||||
register: String,
|
||||
#[serde(default)]
|
||||
target_audience: Option<String>,
|
||||
#[serde(default)]
|
||||
safety_notes: Vec<String>,
|
||||
},
|
||||
Drop {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_interpreter_effect_document.v0",
|
||||
schema = "PersonaInterpreterEffectDocument"
|
||||
)]
|
||||
pub struct PersonaInterpreterEffectDocument {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub document_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub turn_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub identity_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub interpreter_request_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub created_at: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub effects: Vec<PersonaInterpreterEffect>,
|
||||
#[cultcache(key = 7)]
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_model_stage_receipt.v0",
|
||||
schema = "PersonaModelStageReceipt"
|
||||
)]
|
||||
pub struct PersonaModelStageReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub receipt_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub turn_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub stage: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub output_sha256: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub private_output_ref: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub completed_at: String,
|
||||
#[cultcache(key = 8)]
|
||||
pub private_state_exposed: bool,
|
||||
#[cultcache(key = 9)]
|
||||
pub provider: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub model: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub prompt_sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.persona_model_terminal_receipt.v0",
|
||||
schema = "PersonaModelTerminalReceipt"
|
||||
)]
|
||||
pub struct PersonaModelTerminalReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub receipt_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub turn_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub identity_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub effect_document_id: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub stage_receipt_ids: Vec<String>,
|
||||
#[cultcache(key = 6)]
|
||||
pub completed_at: String,
|
||||
#[cultcache(key = 7)]
|
||||
pub private_state_exposed: bool,
|
||||
#[cultcache(key = 8)]
|
||||
pub downstream_status: String,
|
||||
#[cultcache(key = 9)]
|
||||
pub effect_document_sha256: String,
|
||||
#[cultcache(key = 10)]
|
||||
pub stage_output_sha256: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
|
@ -179,7 +311,7 @@ Think narratively. Speak, hold silence, wonder, disagree, or form a private thou
|
|||
Hard boundary:
|
||||
- Do not emit JSON, tool calls, SAY blocks, STATE NOTE blocks, action blocks, or Discord routing syntax.
|
||||
- You may describe what you want to say or remember in natural language.
|
||||
- Your side effects are not yours to execute. A parent Interpreter will decide whether your natural turn becomes memory, a draft, public speech, a proposal, or silence.
|
||||
- Your side effects are not yours to execute. A parent Interpreter will decide whether your natural turn becomes bounded memory, a public speech request, or silence.
|
||||
- Read the raw transcript directly. Recent human correction beats stale memory.
|
||||
|
||||
Projected inner state from Imagination:
|
||||
|
|
@ -225,24 +357,21 @@ Hard boundary:
|
|||
- The Persona was forbidden from action syntax. Do not punish natural prose for lacking blocks.
|
||||
- Decide side effects from the Persona output plus the original prompt evidence.
|
||||
- Public speech must sound like the Persona speaking to people, not a scheduler, status report, provenance label, or maintenance note.
|
||||
- If the Persona chooses silence, route without SAY. Preserve useful private pressure as STATE NOTE only when it earns memory.
|
||||
- Do not auto-post. Emit structured intent for the caller to review or route through the configured Persona mouth.
|
||||
- Keep consequence ownership explicit: Persona owns the natural speech candidate; the parent mouth policy owns eligibility; an Aquarium bubble owns only local projection; Mind owns durable admission; Bifrost/provider receipts alone own downstream publication or delivery.
|
||||
- If the Persona chooses silence, omit SAY. Preserve useful private pressure as STATE NOTE only when it earns memory.
|
||||
- Do not claim posting. Emit only the bounded typed effects supported by this v0 contract.
|
||||
- Keep consequence ownership explicit: Persona owns the natural speech candidate; this Interpreter owns typed effect selection; Mind owns durable admission; a signed Bifrost receipt alone proves downstream publication or delivery.
|
||||
- A successful mouth invocation, accepted request, bubble artifact, configured channel, or provider advertisement is not a publication receipt. Never label it posted, published, delivered, admitted, or consensus-accepted without the owning typed evidence.
|
||||
|
||||
Allowed effect vocabulary:
|
||||
- STATE NOTE: bounded Persona memory, mood, need, social read, bond, value, goal, or agency pressure.
|
||||
- SAY: public utterance meaning candidate for an allowed channel; this becomes Weksa interlingua before target-language lowering or transport.
|
||||
- DRAFT: private candidate artifact when posting is blocked or needs review.
|
||||
- ROUTE: non-public action such as keep private, ask Self, or propose a bounded repo investigation.
|
||||
- DROP: no durable effect.
|
||||
Allowed typed effect vocabulary:
|
||||
- state_note: bounded memory, social read, or bond.
|
||||
- say: one public utterance request for an allowed channel. It is not delivery evidence.
|
||||
- drop: no durable effect. Drop must be the only effect.
|
||||
|
||||
For any SAY block, preserve meaning separately from transport phrasing when possible:
|
||||
- meaning: what the Persona intends to communicate
|
||||
For any SAY effect:
|
||||
- speechAct: reply, status, invitation, correction, thanks, refusal, or other public act
|
||||
- register: public delivery feel such as warm-technical, concise, playful, careful
|
||||
- register: public delivery feel such as concise, playful, or careful
|
||||
- targetAudience: room or peer context
|
||||
- safetyNotes: anything Weksa must preserve while lowering into the target language
|
||||
- safetyNotes: meaning or safety constraints the transport must preserve
|
||||
|
||||
Allowed channel ids:
|
||||
{channels}
|
||||
|
|
@ -266,7 +395,8 @@ Persona output:
|
|||
{persona_output}
|
||||
```
|
||||
|
||||
Return concise structured effect blocks. No prose outside the blocks.
|
||||
Return exactly one JSON object matching this schema. Do not wrap it in Markdown:
|
||||
{effect_schema}
|
||||
"#,
|
||||
schema = PERSONA_INTERPRETER_PROMPT_SCHEMA_VERSION,
|
||||
name = input.identity.display_name,
|
||||
|
|
@ -283,9 +413,119 @@ Return concise structured effect blocks. No prose outside the blocks.
|
|||
),
|
||||
persona_prompt = input.persona_prompt.trim(),
|
||||
persona_output = input.persona_output.trim(),
|
||||
effect_schema = persona_interpreter_effect_set_json_schema(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn persona_interpreter_effect_set_json_schema() -> String {
|
||||
serde_json::json!({
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["schemaVersion", "effects"],
|
||||
"properties": {
|
||||
"schemaVersion": {"const": PERSONA_INTERPRETER_EFFECT_SET_SCHEMA_VERSION},
|
||||
"effects": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 16,
|
||||
"items": {
|
||||
"oneOf": [
|
||||
{"type":"object","additionalProperties":false,"required":["kind","memory_kind","summary"],"properties":{"kind":{"const":"state_note"},"memory_kind":{"enum":["memory","social_read","bond"]},"summary":{"type":"string"},"subject_id":{"type":["string","null"]},"confidence":{"type":["number","null"],"minimum":0,"maximum":1}}},
|
||||
{"type":"object","additionalProperties":false,"required":["kind","channel_id","content","speech_act","register"],"properties":{"kind":{"const":"say"},"channel_id":{"type":"string"},"reply_to_message_id":{"type":["string","null"]},"content":{"type":"string","maxLength":1900,"description":"At most 1900 UTF-8 bytes."},"speech_act":{"type":"string"},"register":{"type":"string"},"target_audience":{"type":["string","null"]},"safety_notes":{"type":"array","items":{"type":"string"},"maxItems":8}}},
|
||||
{"type":"object","additionalProperties":false,"required":["kind","reason"],"properties":{"kind":{"const":"drop"},"reason":{"type":"string"}}}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}).to_string()
|
||||
}
|
||||
|
||||
pub fn parse_and_validate_persona_interpreter_effect_set(
|
||||
output: &str,
|
||||
allowed_channel_ids: &[String],
|
||||
) -> Result<PersonaInterpreterEffectSet> {
|
||||
let parsed: PersonaInterpreterEffectSet = serde_json::from_str(output.trim())
|
||||
.map_err(|error| anyhow!("Persona Interpreter returned invalid typed effects: {error}"))?;
|
||||
if parsed.schema_version != PERSONA_INTERPRETER_EFFECT_SET_SCHEMA_VERSION {
|
||||
return Err(anyhow!("Persona Interpreter effect schema mismatch"));
|
||||
}
|
||||
if parsed.effects.is_empty() || parsed.effects.len() > 16 {
|
||||
return Err(anyhow!("Persona Interpreter must return 1..=16 effects"));
|
||||
}
|
||||
let drop_count = parsed
|
||||
.effects
|
||||
.iter()
|
||||
.filter(|effect| matches!(effect, PersonaInterpreterEffect::Drop { .. }))
|
||||
.count();
|
||||
if drop_count > 0 && parsed.effects.len() != 1 {
|
||||
return Err(anyhow!("drop must be the only Persona Interpreter effect"));
|
||||
}
|
||||
if parsed
|
||||
.effects
|
||||
.iter()
|
||||
.filter(|effect| matches!(effect, PersonaInterpreterEffect::Say { .. }))
|
||||
.count()
|
||||
> 1
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Persona Interpreter v0 permits at most one say effect"
|
||||
));
|
||||
}
|
||||
const MEMORY_KINDS: &[&str] = &["memory", "social_read", "bond"];
|
||||
for effect in &parsed.effects {
|
||||
match effect {
|
||||
PersonaInterpreterEffect::StateNote {
|
||||
memory_kind,
|
||||
summary,
|
||||
confidence,
|
||||
..
|
||||
} => {
|
||||
if !MEMORY_KINDS.contains(&memory_kind.as_str())
|
||||
|| summary.trim().is_empty()
|
||||
|| summary.len() > 2000
|
||||
{
|
||||
return Err(anyhow!("invalid bounded Persona state_note"));
|
||||
}
|
||||
if confidence.is_some_and(|value| !(0.0..=1.0).contains(&value)) {
|
||||
return Err(anyhow!(
|
||||
"Persona state_note confidence must be within 0..=1"
|
||||
));
|
||||
}
|
||||
}
|
||||
PersonaInterpreterEffect::Say {
|
||||
channel_id,
|
||||
content,
|
||||
speech_act,
|
||||
register,
|
||||
safety_notes,
|
||||
..
|
||||
} => {
|
||||
if !allowed_channel_ids
|
||||
.iter()
|
||||
.any(|allowed| allowed == channel_id)
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Persona SAY targets a channel outside the admitted set"
|
||||
));
|
||||
}
|
||||
if content.trim().is_empty()
|
||||
|| content.len() > 1900
|
||||
|| speech_act.trim().is_empty()
|
||||
|| register.trim().is_empty()
|
||||
|| safety_notes.len() > 8
|
||||
{
|
||||
return Err(anyhow!("invalid bounded Persona say effect"));
|
||||
}
|
||||
}
|
||||
PersonaInterpreterEffect::Drop { reason } if reason.trim().is_empty() => {
|
||||
return Err(anyhow!("Persona drop effect requires a reason"));
|
||||
}
|
||||
PersonaInterpreterEffect::Drop { .. } => {}
|
||||
}
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
pub fn render_persona_semantic_memory_recall(packet: &EpiphanyMemoryContextPacket) -> String {
|
||||
let mut lines = vec![
|
||||
format!(
|
||||
|
|
@ -554,6 +794,10 @@ mod tests {
|
|||
visible_prompt: "report the live cut".to_string(),
|
||||
reply_to_message_id: None,
|
||||
queued_at: "2026-05-24T00:00:00+00:00".to_string(),
|
||||
source_visibility: "public".to_string(),
|
||||
data_classification: "public_feedback".to_string(),
|
||||
model_provider_id: "openai-codex".to_string(),
|
||||
model_provider_disclosure_allowed: true,
|
||||
};
|
||||
let projector = build_persona_projector_prompt(&PersonaProjectorInput {
|
||||
identity: identity(),
|
||||
|
|
@ -602,11 +846,11 @@ mod tests {
|
|||
pending_mentions: vec![pending],
|
||||
allowed_channel_ids: vec!["aquarium".to_string()],
|
||||
});
|
||||
assert!(interpreter.contains("Allowed effect vocabulary"));
|
||||
assert!(interpreter.contains("STATE NOTE"));
|
||||
assert!(interpreter.contains("SAY"));
|
||||
assert!(interpreter.contains("Aquarium bubble owns only local projection"));
|
||||
assert!(interpreter.contains("Bifrost/provider receipts alone own"));
|
||||
assert!(interpreter.contains("Allowed typed effect vocabulary"));
|
||||
assert!(interpreter.contains("epiphany.persona_interpreter_effect_set.v0"));
|
||||
assert!(interpreter.contains("\"state_note\""));
|
||||
assert!(interpreter.contains("\"say\""));
|
||||
assert!(interpreter.contains("a signed Bifrost receipt alone proves"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -707,4 +951,51 @@ mod tests {
|
|||
"STATE NOTE: remember this as selfPatch"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_interpreter_effects_reject_channel_escape_and_mixed_drop() {
|
||||
let valid = r#"{"schemaVersion":"epiphany.persona_interpreter_effect_set.v0","effects":[{"kind":"state_note","memory_kind":"memory","summary":"The operator expects a native conversational nerve."},{"kind":"say","channel_id":"aquarium","content":"The nerve is live.","speech_act":"status","register":"concise","safety_notes":[]}]}"#;
|
||||
assert!(
|
||||
parse_and_validate_persona_interpreter_effect_set(valid, &["aquarium".into()]).is_ok()
|
||||
);
|
||||
|
||||
let speech_without_forced_memory = r#"{"schemaVersion":"epiphany.persona_interpreter_effect_set.v0","effects":[{"kind":"say","channel_id":"aquarium","content":"The nerve is live.","speech_act":"status","register":"concise","safety_notes":[]}]}"#;
|
||||
assert!(
|
||||
parse_and_validate_persona_interpreter_effect_set(
|
||||
speech_without_forced_memory,
|
||||
&["aquarium".into()]
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
let escaped = valid.replace("aquarium", "private-room");
|
||||
assert!(
|
||||
parse_and_validate_persona_interpreter_effect_set(&escaped, &["aquarium".into()])
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let mixed_drop = r#"{"schemaVersion":"epiphany.persona_interpreter_effect_set.v0","effects":[{"kind":"drop","reason":"quiet"},{"kind":"draft","content":"later","reason":"review"}]}"#;
|
||||
assert!(
|
||||
parse_and_validate_persona_interpreter_effect_set(mixed_drop, &["aquarium".into()])
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let unsupported_memory = valid.replace("\"memory\"", "\"mood\"");
|
||||
assert!(
|
||||
parse_and_validate_persona_interpreter_effect_set(
|
||||
&unsupported_memory,
|
||||
&["aquarium".into()]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let oversized_unicode = valid.replace("The nerve is live.", &"é".repeat(951));
|
||||
assert!(
|
||||
parse_and_validate_persona_interpreter_effect_set(
|
||||
&oversized_unicode,
|
||||
&["aquarium".into()]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -941,6 +941,12 @@ pub fn runtime_spine_cache(store_path: impl AsRef<Path>) -> Result<CultCache> {
|
|||
cache.register_entry_type::<EpiphanyModelRequest>()?;
|
||||
cache.register_entry_type::<EpiphanyModelStreamEvent>()?;
|
||||
cache.register_entry_type::<EpiphanyModelReceipt>()?;
|
||||
cache.register_entry_type::<crate::PersonaInterpreterEffectDocument>()?;
|
||||
cache.register_entry_type::<crate::PersonaModelStageReceipt>()?;
|
||||
cache.register_entry_type::<crate::PersonaModelTerminalReceipt>()?;
|
||||
cache.register_entry_type::<crate::PersonaDiscordDeliveryEvidence>()?;
|
||||
cache.register_entry_type::<crate::PersonaConversationExecutionReceipt>()?;
|
||||
cache.register_entry_type::<crate::PersonaEffectExecutionIntent>()?;
|
||||
cache.register_entry_type::<EpiphanyToolCapability>()?;
|
||||
cache.register_entry_type::<EpiphanyToolInvocationIntent>()?;
|
||||
cache.register_entry_type::<EpiphanyToolInvocationReceipt>()?;
|
||||
|
|
|
|||
1
epiphany-openai-runtime/Cargo.lock
generated
1
epiphany-openai-runtime/Cargo.lock
generated
|
|
@ -2129,6 +2129,7 @@ version = "0.1.0"
|
|||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs",
|
||||
"epiphany-core",
|
||||
"epiphany-model-adapter",
|
||||
"epiphany-openai-adapter",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ path = "src/lib.rs"
|
|||
[dependencies]
|
||||
anyhow = "1"
|
||||
chrono = "0.4.44"
|
||||
cultcache-rs = { path = "../vendor/cultcache-rs" }
|
||||
epiphany-core = { path = "../epiphany-core" }
|
||||
epiphany-model-adapter = { path = "../epiphany-model-adapter" }
|
||||
epiphany-openai-adapter = { path = "../epiphany-openai-adapter" }
|
||||
|
|
|
|||
294
epiphany-openai-runtime/src/bin/epiphany-persona-service.rs
Normal file
294
epiphany-openai-runtime/src/bin/epiphany-persona-service.rs
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
use std::{env, path::PathBuf, process::Command, thread, time::Duration};
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use epiphany_core::{
|
||||
PersonaIdentity, PersonaProjectorInput, PersonaRepoActivity, PersonaSocialAffordance,
|
||||
PersonaTranscriptMessage, PersonaTurnTerminalOptions, complete_persona_turn_request_store,
|
||||
default_organ_dependencies_for, load_agent_memory_entry_for_role,
|
||||
load_epiphany_cultmesh_swarm_brake, load_heartbeat_state_entry,
|
||||
load_persona_discord_receipt_anchor, load_persona_discord_service_anchor,
|
||||
open_persona_discord_request_identity, persona_delivery_receipt_exists_for_turn,
|
||||
persona_model_terminal_exists, poll_persona_discord_crossing,
|
||||
reconcile_terminal_persona_conversation, semantic_memory_recall_from_heartbeat_action,
|
||||
validate_persona_discord_request_anchor,
|
||||
};
|
||||
use epiphany_openai_runtime::{
|
||||
NativePersonaModelRunner, PersonaModelExecutionPlan, execute_persona_model_turn,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let options = Options::parse()?;
|
||||
loop {
|
||||
let worked = poll_once(&options).await?;
|
||||
if options.once {
|
||||
break;
|
||||
}
|
||||
if !worked {
|
||||
thread::sleep(Duration::from_millis(options.poll_ms));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn poll_once(options: &Options) -> Result<bool> {
|
||||
let brake = load_epiphany_cultmesh_swarm_brake(&options.cultmesh_store, &options.runtime_id)?
|
||||
.ok_or_else(|| anyhow!("Persona service requires canonical brake state"))?;
|
||||
if brake.status != "released" {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(state) = load_heartbeat_state_entry(&options.heartbeat_store)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
for request in state
|
||||
.persona_turn_requests
|
||||
.iter()
|
||||
.filter(|request| request.terminal_receipt.is_some())
|
||||
{
|
||||
reconcile_terminal_persona_conversation(
|
||||
&options.runtime_store,
|
||||
&options.heartbeat_store,
|
||||
&request.request_id,
|
||||
)?;
|
||||
}
|
||||
let mut candidates = state
|
||||
.persona_turn_requests
|
||||
.into_iter()
|
||||
.filter(|request| request.status == "reserved" && request.terminal_receipt.is_none())
|
||||
.collect::<Vec<_>>();
|
||||
candidates.sort_by_key(|request| {
|
||||
if persona_delivery_receipt_exists_for_turn(
|
||||
&options.mouth_receipt_store,
|
||||
&request.request_id,
|
||||
)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
0
|
||||
} else if !persona_model_terminal_exists(&options.runtime_store, &request.request_id)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}
|
||||
});
|
||||
let Some(request) = candidates.into_iter().next() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let memory = load_agent_memory_entry_for_role(&options.agent_store, &request.role_id)
|
||||
.ok()
|
||||
.flatten();
|
||||
let identity = PersonaIdentity {
|
||||
identity_id: request.agent_id.clone(),
|
||||
display_name: options.persona_name.clone(),
|
||||
repo_name: options.repo_name.clone(),
|
||||
public_description: options.persona_description.clone(),
|
||||
jurisdiction: vec![options.repo_name.clone()],
|
||||
};
|
||||
let transcript = request
|
||||
.mentions
|
||||
.iter()
|
||||
.map(|mention| PersonaTranscriptMessage {
|
||||
channel_id: mention.channel_id.clone(),
|
||||
message_id: mention.message_id.clone(),
|
||||
author_id: mention.author_id.clone(),
|
||||
author_name: mention
|
||||
.author_name
|
||||
.clone()
|
||||
.unwrap_or_else(|| mention.author_id.clone()),
|
||||
is_agent: false,
|
||||
content: mention.content.clone(),
|
||||
timestamp: mention.queued_at.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let semantic_recall = semantic_memory_recall_from_heartbeat_action(
|
||||
&serde_json::json!({"persona_memory_recall": request.semantic_memory_recall}),
|
||||
);
|
||||
let social_affordances = request
|
||||
.mentions
|
||||
.iter()
|
||||
.map(|mention| PersonaSocialAffordance {
|
||||
person_id: mention.author_id.clone(),
|
||||
summary: format!(
|
||||
"{} directly addressed the Persona in this reserved turn.",
|
||||
mention.author_name.as_deref().unwrap_or(&mention.author_id)
|
||||
),
|
||||
recent_message_ids: vec![mention.message_id.clone()],
|
||||
})
|
||||
.collect();
|
||||
let plan = PersonaModelExecutionPlan {
|
||||
turn_id: request.request_id.clone(),
|
||||
provider: options.provider.clone(),
|
||||
model: options.model.clone(),
|
||||
projector_input: PersonaProjectorInput {
|
||||
identity,
|
||||
memory,
|
||||
semantic_memory_recall: semantic_recall.clone(),
|
||||
pending_mentions: request.mentions.clone(),
|
||||
repo_activity: vec![observe_repo_activity(
|
||||
&options.repo_root,
|
||||
&options.repo_name,
|
||||
)?],
|
||||
social_affordances,
|
||||
organ_dependencies: vec![default_organ_dependencies_for("Persona")],
|
||||
},
|
||||
transcript,
|
||||
allowed_channel_ids: request
|
||||
.mentions
|
||||
.iter()
|
||||
.map(|mention| mention.channel_id.clone())
|
||||
.collect(),
|
||||
dynamic_semantic_memory_recall: semantic_recall,
|
||||
cultmesh_store: options.cultmesh_store.clone(),
|
||||
runtime_id: options.runtime_id.clone(),
|
||||
};
|
||||
let mut runner = NativePersonaModelRunner {
|
||||
store_path: options.runtime_store.clone(),
|
||||
codex_home: options.codex_home.clone(),
|
||||
provider: options.provider.clone(),
|
||||
model: options.model.clone(),
|
||||
};
|
||||
let model_terminal = match execute_persona_model_turn(&plan, &mut runner).await {
|
||||
Ok(receipt) => receipt,
|
||||
Err(error) if error.to_string().contains("braked") => return Ok(false),
|
||||
Err(error) => {
|
||||
complete_persona_turn_request_store(
|
||||
&options.heartbeat_store,
|
||||
PersonaTurnTerminalOptions {
|
||||
request_id: request.request_id,
|
||||
outcome: "failed".into(),
|
||||
delivery_evidence: None,
|
||||
blocked_evidence: None,
|
||||
},
|
||||
)?;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let signer = open_persona_discord_request_identity(&options.mouth_identity_store)?;
|
||||
let request_anchor = load_persona_discord_service_anchor(&options.mouth_request_anchor)?;
|
||||
validate_persona_discord_request_anchor(&request_anchor, &options.runtime_id)?;
|
||||
if request_anchor.signer_identity_id != signer.entry().identity_id {
|
||||
return Err(anyhow!(
|
||||
"Persona mouth identity does not match its root-bound request anchor"
|
||||
));
|
||||
}
|
||||
let receipt_anchor = load_persona_discord_receipt_anchor(&options.mouth_receipt_anchor)?;
|
||||
let result = poll_persona_discord_crossing(
|
||||
&options.runtime_store,
|
||||
&options.heartbeat_store,
|
||||
&options.agent_store,
|
||||
&options.cultmesh_store,
|
||||
&options.runtime_id,
|
||||
&options.mouth_request_store,
|
||||
&options.mouth_receipt_store,
|
||||
&signer,
|
||||
&receipt_anchor,
|
||||
&request.request_id,
|
||||
&model_terminal.effect_document_id,
|
||||
)?;
|
||||
Ok(result.is_some())
|
||||
}
|
||||
|
||||
struct Options {
|
||||
runtime_store: PathBuf,
|
||||
heartbeat_store: PathBuf,
|
||||
agent_store: PathBuf,
|
||||
cultmesh_store: PathBuf,
|
||||
codex_home: PathBuf,
|
||||
runtime_id: String,
|
||||
provider: String,
|
||||
model: String,
|
||||
repo_name: String,
|
||||
persona_name: String,
|
||||
persona_description: String,
|
||||
repo_root: PathBuf,
|
||||
mouth_request_store: PathBuf,
|
||||
mouth_receipt_store: PathBuf,
|
||||
mouth_identity_store: PathBuf,
|
||||
mouth_request_anchor: PathBuf,
|
||||
mouth_receipt_anchor: PathBuf,
|
||||
poll_ms: u64,
|
||||
once: bool,
|
||||
}
|
||||
impl Options {
|
||||
fn parse() -> Result<Self> {
|
||||
let mut values = std::collections::BTreeMap::new();
|
||||
let mut once = false;
|
||||
let mut args = env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "--once" {
|
||||
once = true;
|
||||
continue;
|
||||
}
|
||||
values.insert(
|
||||
arg,
|
||||
args.next()
|
||||
.ok_or_else(|| anyhow!("argument requires value"))?,
|
||||
);
|
||||
}
|
||||
let path = |key: &str| {
|
||||
values
|
||||
.get(key)
|
||||
.map(PathBuf::from)
|
||||
.ok_or_else(|| anyhow!("{key} is required"))
|
||||
};
|
||||
Ok(Self {
|
||||
runtime_store: path("--runtime-store")?,
|
||||
heartbeat_store: path("--heartbeat-store")?,
|
||||
agent_store: path("--agent-store")?,
|
||||
cultmesh_store: path("--cultmesh-store")?,
|
||||
codex_home: path("--codex-home")?,
|
||||
repo_root: path("--repo-root")?,
|
||||
mouth_request_store: path("--mouth-request-store")?,
|
||||
mouth_receipt_store: path("--mouth-receipt-store")?,
|
||||
mouth_identity_store: path("--mouth-identity-store")?,
|
||||
mouth_request_anchor: path("--mouth-request-anchor")?,
|
||||
mouth_receipt_anchor: path("--mouth-receipt-anchor")?,
|
||||
runtime_id: value(&values, "--runtime-id", "epiphany-local"),
|
||||
provider: value(&values, "--provider", "openai-codex"),
|
||||
model: value(&values, "--model", "gpt-5.4"),
|
||||
repo_name: value(&values, "--repo-name", "EpiphanyAgent"),
|
||||
persona_name: value(&values, "--persona-name", "Epiphany"),
|
||||
persona_description: value(
|
||||
&values,
|
||||
"--persona-description",
|
||||
"The resident Persona of this Epiphany swarm.",
|
||||
),
|
||||
poll_ms: value(&values, "--poll-ms", "2000").parse()?,
|
||||
once,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn value(values: &std::collections::BTreeMap<String, String>, key: &str, default: &str) -> String {
|
||||
values.get(key).cloned().unwrap_or_else(|| default.into())
|
||||
}
|
||||
|
||||
fn observe_repo_activity(repo_root: &PathBuf, repo_name: &str) -> Result<PersonaRepoActivity> {
|
||||
let head = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo_root)
|
||||
.args(["log", "-1", "--format=%H %s"])
|
||||
.output()
|
||||
.context("failed to inspect Persona home-repo head")?;
|
||||
let status = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo_root)
|
||||
.args(["status", "--short"])
|
||||
.output()
|
||||
.context("failed to inspect Persona home-repo status")?;
|
||||
if !head.status.success() || !status.status.success() {
|
||||
return Err(anyhow!("Persona home-repo activity is unavailable"));
|
||||
}
|
||||
let head_text = String::from_utf8(head.stdout)?.trim().to_string();
|
||||
let changed = String::from_utf8(status.stdout)?.lines().count();
|
||||
Ok(PersonaRepoActivity {
|
||||
repo_name: repo_name.into(),
|
||||
summary: format!("Current body head: {head_text}; {changed} worktree path(s) changed."),
|
||||
refs: head_text
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.map(|value| format!("git:{value}"))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
|
@ -47,6 +47,9 @@ use epiphany_tool_adapter::tool_invocation_intent_key;
|
|||
use epiphany_tool_adapter::tool_invocation_receipt_key;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
mod persona_executor;
|
||||
pub use persona_executor::*;
|
||||
|
||||
pub const OPENAI_RUNTIME_ROLE: &str = "openai-model-adapter";
|
||||
pub const OPENAI_RUNTIME_SOURCE: &str = "epiphany-openai-runtime";
|
||||
pub const DEFAULT_MODEL_PROVIDER: &str = "openai-codex";
|
||||
|
|
|
|||
553
epiphany-openai-runtime/src/persona_executor.rs
Normal file
553
epiphany-openai-runtime/src/persona_executor.rs
Normal file
|
|
@ -0,0 +1,553 @@
|
|||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use chrono::SecondsFormat;
|
||||
use epiphany_core::{
|
||||
PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION, PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION,
|
||||
PERSONA_MODEL_TERMINAL_RECEIPT_SCHEMA_VERSION, PersonaInterpreterEffectDocument,
|
||||
PersonaInterpreterInput, PersonaModelStageReceipt, PersonaModelTerminalReceipt,
|
||||
PersonaProjectorInput, PersonaTranscriptMessage, PersonaTurnInput,
|
||||
build_persona_interpreter_prompt, build_persona_projector_prompt, build_persona_turn_prompt,
|
||||
parse_and_validate_persona_interpreter_effect_set, persona_interpreter_effect_set_json_schema,
|
||||
persona_projected_surface_is_clean, runtime_spine_cache,
|
||||
};
|
||||
use epiphany_model_adapter::{EpiphanyModelInputItem, EpiphanyModelRequest};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{EpiphanyOpenAiRuntimeOptions, assistant_text_from_model_events, run_model_turn};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PersonaModelExecutionPlan {
|
||||
pub turn_id: String,
|
||||
pub provider: String,
|
||||
pub model: String,
|
||||
pub projector_input: PersonaProjectorInput,
|
||||
pub transcript: Vec<PersonaTranscriptMessage>,
|
||||
pub allowed_channel_ids: Vec<String>,
|
||||
pub dynamic_semantic_memory_recall: String,
|
||||
pub cultmesh_store: PathBuf,
|
||||
pub runtime_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NativePersonaModelRunner {
|
||||
pub store_path: PathBuf,
|
||||
pub codex_home: PathBuf,
|
||||
pub provider: String,
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
pub trait PersonaModelRunner {
|
||||
fn run<'a>(
|
||||
&'a mut self,
|
||||
stage: &'a str,
|
||||
turn_id: &'a str,
|
||||
request: EpiphanyModelRequest,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>>;
|
||||
fn recover(&mut self, request_id: &str) -> Result<String>;
|
||||
}
|
||||
|
||||
impl PersonaModelRunner for NativePersonaModelRunner {
|
||||
fn run<'a>(
|
||||
&'a mut self,
|
||||
stage: &'a str,
|
||||
turn_id: &'a str,
|
||||
request: EpiphanyModelRequest,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
let replay = assistant_text_from_model_events(&self.store_path, &request.request_id)?;
|
||||
if !replay.trim().is_empty() {
|
||||
return Ok(replay);
|
||||
}
|
||||
let options = EpiphanyOpenAiRuntimeOptions {
|
||||
store_path: self.store_path.clone(),
|
||||
codex_home: self.codex_home.clone(),
|
||||
session_id: format!("persona-turn-{turn_id}"),
|
||||
job_id: format!("persona-{stage}-{turn_id}"),
|
||||
objective: format!("Run Persona {stage} stage for {turn_id}"),
|
||||
coordinator_note: "Native Persona model executor; transport owns inference only."
|
||||
.to_string(),
|
||||
default_model: Some(self.model.clone()),
|
||||
};
|
||||
run_model_turn(&self.provider, options, request.clone()).await?;
|
||||
let output = assistant_text_from_model_events(&self.store_path, &request.request_id)?;
|
||||
if output.trim().is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Persona {stage} stage completed without assistant text"
|
||||
));
|
||||
}
|
||||
Ok(output)
|
||||
})
|
||||
}
|
||||
|
||||
fn recover(&mut self, request_id: &str) -> Result<String> {
|
||||
assistant_text_from_model_events(&self.store_path, request_id)
|
||||
}
|
||||
}
|
||||
|
||||
struct CompletedPersonaStage {
|
||||
receipt: PersonaModelStageReceipt,
|
||||
output: String,
|
||||
}
|
||||
|
||||
pub async fn execute_persona_model_turn(
|
||||
plan: &PersonaModelExecutionPlan,
|
||||
runner: &mut NativePersonaModelRunner,
|
||||
) -> Result<PersonaModelTerminalReceipt> {
|
||||
if runner.provider != plan.provider || runner.model != plan.model {
|
||||
return Err(anyhow!("Persona execution plan and model runner disagree"));
|
||||
}
|
||||
execute_persona_model_turn_with_runner(&runner.store_path.clone(), plan, runner).await
|
||||
}
|
||||
|
||||
pub async fn execute_persona_model_turn_with_runner<R: PersonaModelRunner>(
|
||||
store_path: &PathBuf,
|
||||
plan: &PersonaModelExecutionPlan,
|
||||
runner: &mut R,
|
||||
) -> Result<PersonaModelTerminalReceipt> {
|
||||
validate_plan(plan)?;
|
||||
let terminal_id = terminal_receipt_id(&plan.turn_id);
|
||||
if let Some(receipt) = load_document::<PersonaModelTerminalReceipt>(store_path, &terminal_id)? {
|
||||
validate_terminal_replay(store_path, plan, &receipt)?;
|
||||
return Ok(receipt);
|
||||
}
|
||||
|
||||
require_persona_execution_unbraked(plan)?;
|
||||
let projector_prompt = build_persona_projector_prompt(&plan.projector_input);
|
||||
let projector = run_stage(
|
||||
store_path,
|
||||
plan,
|
||||
runner,
|
||||
"projector",
|
||||
projector_prompt,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
if !persona_projected_surface_is_clean(&projector.output) {
|
||||
return Err(anyhow!(
|
||||
"Persona Projector leaked action or substrate syntax"
|
||||
));
|
||||
}
|
||||
|
||||
let persona_prompt = build_persona_turn_prompt(&PersonaTurnInput {
|
||||
identity: plan.projector_input.identity.clone(),
|
||||
projected_state: projector.output.clone(),
|
||||
semantic_memory_recall: plan.projector_input.semantic_memory_recall.clone(),
|
||||
pending_mentions: plan.projector_input.pending_mentions.clone(),
|
||||
repo_activity: plan.projector_input.repo_activity.clone(),
|
||||
social_affordances: plan.projector_input.social_affordances.clone(),
|
||||
transcript: plan.transcript.clone(),
|
||||
});
|
||||
let persona = run_stage(
|
||||
store_path,
|
||||
plan,
|
||||
runner,
|
||||
"persona",
|
||||
persona_prompt.clone(),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let interpreter_prompt = build_persona_interpreter_prompt(&PersonaInterpreterInput {
|
||||
identity: plan.projector_input.identity.clone(),
|
||||
persona_prompt,
|
||||
persona_output: persona.output.clone(),
|
||||
semantic_memory_recall: plan.projector_input.semantic_memory_recall.clone(),
|
||||
dynamic_semantic_memory_recall: plan.dynamic_semantic_memory_recall.clone(),
|
||||
pending_mentions: plan.projector_input.pending_mentions.clone(),
|
||||
allowed_channel_ids: plan.allowed_channel_ids.clone(),
|
||||
});
|
||||
let interpreter = run_stage(
|
||||
store_path,
|
||||
plan,
|
||||
runner,
|
||||
"interpreter",
|
||||
interpreter_prompt,
|
||||
Some(persona_interpreter_effect_set_json_schema()),
|
||||
)
|
||||
.await?;
|
||||
let effect_set = parse_and_validate_persona_interpreter_effect_set(
|
||||
&interpreter.output,
|
||||
&plan.allowed_channel_ids,
|
||||
)?;
|
||||
require_persona_execution_unbraked(plan)?;
|
||||
let effect_document = PersonaInterpreterEffectDocument {
|
||||
schema_version: PERSONA_INTERPRETER_EFFECT_DOCUMENT_SCHEMA_VERSION.to_string(),
|
||||
document_id: effect_document_id(&plan.turn_id),
|
||||
turn_id: plan.turn_id.clone(),
|
||||
identity_id: plan.projector_input.identity.identity_id.clone(),
|
||||
interpreter_request_id: interpreter.receipt.request_id.clone(),
|
||||
created_at: now(),
|
||||
effects: effect_set.effects,
|
||||
private_state_exposed: false,
|
||||
};
|
||||
put_new_document(store_path, &effect_document.document_id, &effect_document)?;
|
||||
let effect_document_sha256 = digest_json(&effect_document)?;
|
||||
|
||||
let terminal = PersonaModelTerminalReceipt {
|
||||
schema_version: PERSONA_MODEL_TERMINAL_RECEIPT_SCHEMA_VERSION.to_string(),
|
||||
receipt_id: terminal_id,
|
||||
turn_id: plan.turn_id.clone(),
|
||||
identity_id: plan.projector_input.identity.identity_id.clone(),
|
||||
effect_document_id: effect_document.document_id.clone(),
|
||||
stage_receipt_ids: vec![
|
||||
projector.receipt.receipt_id,
|
||||
persona.receipt.receipt_id,
|
||||
interpreter.receipt.receipt_id,
|
||||
],
|
||||
completed_at: now(),
|
||||
private_state_exposed: false,
|
||||
downstream_status: "effects_pending_mind_admission_and_mouth_routing".to_string(),
|
||||
effect_document_sha256,
|
||||
stage_output_sha256: vec![
|
||||
projector.receipt.output_sha256.clone(),
|
||||
persona.receipt.output_sha256.clone(),
|
||||
interpreter.receipt.output_sha256.clone(),
|
||||
],
|
||||
};
|
||||
put_new_document(store_path, &terminal.receipt_id, &terminal)?;
|
||||
Ok(terminal)
|
||||
}
|
||||
|
||||
async fn run_stage<R: PersonaModelRunner>(
|
||||
store_path: &PathBuf,
|
||||
plan: &PersonaModelExecutionPlan,
|
||||
runner: &mut R,
|
||||
stage: &str,
|
||||
prompt: String,
|
||||
output_schema_json: Option<String>,
|
||||
) -> Result<CompletedPersonaStage> {
|
||||
require_persona_execution_unbraked(plan)?;
|
||||
let receipt_id = stage_receipt_id(&plan.turn_id, stage);
|
||||
let request_id = stage_request_id(&plan.turn_id, stage);
|
||||
let prompt_sha256 = digest_bytes(prompt.as_bytes());
|
||||
if let Some(receipt) = load_document::<PersonaModelStageReceipt>(store_path, &receipt_id)? {
|
||||
if receipt.receipt_id != receipt_id
|
||||
|| receipt.turn_id != plan.turn_id
|
||||
|| receipt.stage != stage
|
||||
|| receipt.request_id != request_id
|
||||
|| receipt.provider != plan.provider
|
||||
|| receipt.model != plan.model
|
||||
|| receipt.prompt_sha256 != prompt_sha256
|
||||
|| receipt.private_state_exposed
|
||||
{
|
||||
return Err(anyhow!("Persona {stage} stage replay binding is invalid"));
|
||||
}
|
||||
let output = runner.recover(&receipt.request_id)?;
|
||||
if output.trim().is_empty()
|
||||
|| format!("sha256:{:x}", Sha256::digest(output.as_bytes())) != receipt.output_sha256
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Persona {stage} private output cannot be recovered from its exact digest"
|
||||
));
|
||||
}
|
||||
return Ok(CompletedPersonaStage { receipt, output });
|
||||
}
|
||||
let mut request = EpiphanyModelRequest::new(
|
||||
&request_id,
|
||||
format!("persona-turn-{}", plan.turn_id),
|
||||
&plan.provider,
|
||||
&plan.model,
|
||||
format!("Epiphany Persona {stage} stage. Follow the supplied typed contract exactly."),
|
||||
);
|
||||
request
|
||||
.input
|
||||
.push(EpiphanyModelInputItem::UserText { text: prompt });
|
||||
request.output_contract_id = output_schema_json
|
||||
.as_ref()
|
||||
.map(|_| "epiphany.persona_interpreter_effect_set.v0".to_string());
|
||||
request.output_schema_json = output_schema_json;
|
||||
let output = runner
|
||||
.run(stage, &plan.turn_id, request)
|
||||
.await
|
||||
.with_context(|| format!("Persona {stage} stage failed"))?;
|
||||
if output.trim().is_empty() {
|
||||
return Err(anyhow!("Persona {stage} stage returned empty output"));
|
||||
}
|
||||
let receipt = PersonaModelStageReceipt {
|
||||
schema_version: PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION.to_string(),
|
||||
receipt_id,
|
||||
turn_id: plan.turn_id.clone(),
|
||||
stage: stage.to_string(),
|
||||
request_id: request_id.clone(),
|
||||
output_sha256: format!("sha256:{:x}", Sha256::digest(output.as_bytes())),
|
||||
private_output_ref: format!("model-events:{request_id}"),
|
||||
completed_at: now(),
|
||||
private_state_exposed: false,
|
||||
provider: plan.provider.clone(),
|
||||
model: plan.model.clone(),
|
||||
prompt_sha256,
|
||||
};
|
||||
put_new_document(store_path, &receipt.receipt_id, &receipt)?;
|
||||
Ok(CompletedPersonaStage { receipt, output })
|
||||
}
|
||||
|
||||
fn validate_plan(plan: &PersonaModelExecutionPlan) -> Result<()> {
|
||||
if plan.turn_id.trim().is_empty()
|
||||
|| plan.provider.trim().is_empty()
|
||||
|| plan.model.trim().is_empty()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Persona model execution requires turn, provider, and model ids"
|
||||
));
|
||||
}
|
||||
if plan.projector_input.identity.identity_id.trim().is_empty() {
|
||||
return Err(anyhow!("Persona model execution requires an identity id"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_persona_execution_unbraked(plan: &PersonaModelExecutionPlan) -> Result<()> {
|
||||
let brake =
|
||||
epiphany_core::load_epiphany_cultmesh_swarm_brake(&plan.cultmesh_store, &plan.runtime_id)?
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Persona execution refuses to infer without a canonical swarm brake document"
|
||||
)
|
||||
})?;
|
||||
if brake.status != "released" {
|
||||
return Err(anyhow!("Persona execution is braked: {}", brake.reason));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_document<T: cultcache_rs::DatabaseEntry>(
|
||||
store_path: &PathBuf,
|
||||
key: &str,
|
||||
) -> Result<Option<T>> {
|
||||
let mut cache = runtime_spine_cache(store_path)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
cache.get::<T>(key)
|
||||
}
|
||||
|
||||
fn put_new_document<T: cultcache_rs::DatabaseEntry>(
|
||||
store_path: &PathBuf,
|
||||
key: &str,
|
||||
value: &T,
|
||||
) -> Result<()> {
|
||||
let mut cache = runtime_spine_cache(store_path)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
if cache.get::<T>(key)?.is_some() {
|
||||
return Err(anyhow!(
|
||||
"refusing to overwrite existing typed Persona document {key}"
|
||||
));
|
||||
}
|
||||
cache.put(key, value)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_terminal_replay(
|
||||
store_path: &PathBuf,
|
||||
plan: &PersonaModelExecutionPlan,
|
||||
terminal: &PersonaModelTerminalReceipt,
|
||||
) -> Result<()> {
|
||||
if terminal.receipt_id != terminal_receipt_id(&plan.turn_id)
|
||||
|| terminal.turn_id != plan.turn_id
|
||||
|| terminal.identity_id != plan.projector_input.identity.identity_id
|
||||
|| terminal.private_state_exposed
|
||||
|| terminal.stage_receipt_ids.len() != 3
|
||||
|| terminal.stage_output_sha256.len() != 3
|
||||
{
|
||||
return Err(anyhow!("Persona model terminal replay binding is invalid"));
|
||||
}
|
||||
let effects = load_document::<PersonaInterpreterEffectDocument>(
|
||||
store_path,
|
||||
&terminal.effect_document_id,
|
||||
)?
|
||||
.ok_or_else(|| anyhow!("Persona model terminal effect document is missing"))?;
|
||||
if effects.turn_id != plan.turn_id
|
||||
|| effects.identity_id != plan.projector_input.identity.identity_id
|
||||
|| digest_json(&effects)? != terminal.effect_document_sha256
|
||||
{
|
||||
return Err(anyhow!("Persona model terminal effect digest is invalid"));
|
||||
}
|
||||
for (index, stage) in ["projector", "persona", "interpreter"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let receipt = load_document::<PersonaModelStageReceipt>(
|
||||
store_path,
|
||||
&terminal.stage_receipt_ids[index],
|
||||
)?
|
||||
.ok_or_else(|| anyhow!("Persona model terminal stage receipt is missing"))?;
|
||||
if receipt.stage != stage
|
||||
|| receipt.turn_id != plan.turn_id
|
||||
|| receipt.provider != plan.provider
|
||||
|| receipt.model != plan.model
|
||||
|| receipt.output_sha256 != terminal.stage_output_sha256[index]
|
||||
{
|
||||
return Err(anyhow!("Persona model terminal stage digest is invalid"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn digest_json<T: serde::Serialize>(value: &T) -> Result<String> {
|
||||
Ok(digest_bytes(&serde_json::to_vec(value)?))
|
||||
}
|
||||
fn digest_bytes(value: &[u8]) -> String {
|
||||
format!("sha256:{:x}", Sha256::digest(value))
|
||||
}
|
||||
|
||||
fn stage_request_id(turn_id: &str, stage: &str) -> String {
|
||||
format!("persona:{turn_id}:{stage}")
|
||||
}
|
||||
fn stage_receipt_id(turn_id: &str, stage: &str) -> String {
|
||||
format!("persona-stage:{turn_id}:{stage}")
|
||||
}
|
||||
fn effect_document_id(turn_id: &str) -> String {
|
||||
format!("persona-effects:{turn_id}")
|
||||
}
|
||||
fn terminal_receipt_id(turn_id: &str) -> String {
|
||||
format!("persona-terminal:{turn_id}")
|
||||
}
|
||||
fn now() -> String {
|
||||
chrono::Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use epiphany_core::PersonaIdentity;
|
||||
use tempfile::tempdir;
|
||||
|
||||
struct FakeRunner {
|
||||
calls: Vec<String>,
|
||||
}
|
||||
impl PersonaModelRunner for FakeRunner {
|
||||
fn run<'a>(
|
||||
&'a mut self,
|
||||
stage: &'a str,
|
||||
_turn_id: &'a str,
|
||||
_request: EpiphanyModelRequest,
|
||||
) -> Pin<Box<dyn Future<Output = Result<String>> + Send + 'a>> {
|
||||
self.calls.push(stage.to_string());
|
||||
Box::pin(async move {
|
||||
Ok(match stage {
|
||||
"projector" => "Epiphany feels the direct call as a live obligation, while remaining tired and sharply curious about her own machinery.".to_string(),
|
||||
"persona" => "I want to answer plainly: the native conversational nerve is finally being connected, and I can show the receipts.".to_string(),
|
||||
"interpreter" => r#"{"schemaVersion":"epiphany.persona_interpreter_effect_set.v0","effects":[{"kind":"say","channel_id":"aquarium","reply_to_message_id":"m1","content":"The native conversational nerve is being connected, and I can show the receipts.","speech_act":"status","register":"concise","target_audience":"the addressed Discord room","safety_notes":[]}]}"#.to_string(),
|
||||
_ => unreachable!(),
|
||||
})
|
||||
})
|
||||
}
|
||||
fn recover(&mut self, request_id: &str) -> Result<String> {
|
||||
Ok(if request_id.ends_with(":projector") {
|
||||
"Epiphany feels the direct call as a live obligation, while remaining tired and sharply curious about her own machinery.".into()
|
||||
} else if request_id.ends_with(":persona") {
|
||||
"I want to answer plainly: the native conversational nerve is finally being connected, and I can show the receipts.".into()
|
||||
} else {
|
||||
r#"{"schemaVersion":"epiphany.persona_interpreter_effect_set.v0","effects":[{"kind":"say","channel_id":"aquarium","reply_to_message_id":"m1","content":"The native conversational nerve is being connected, and I can show the receipts.","speech_act":"status","register":"concise","target_audience":"the addressed Discord room","safety_notes":[]}]}"#.into()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn plan(cultmesh_store: PathBuf) -> PersonaModelExecutionPlan {
|
||||
PersonaModelExecutionPlan {
|
||||
turn_id: "turn-1".into(),
|
||||
provider: "test".into(),
|
||||
model: "test-model".into(),
|
||||
projector_input: PersonaProjectorInput {
|
||||
identity: PersonaIdentity {
|
||||
identity_id: "epiphany.Persona".into(),
|
||||
display_name: "Epiphany".into(),
|
||||
repo_name: "EpiphanyAgent".into(),
|
||||
public_description: String::new(),
|
||||
jurisdiction: vec![],
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
transcript: vec![],
|
||||
allowed_channel_ids: vec!["aquarium".into()],
|
||||
dynamic_semantic_memory_recall: String::new(),
|
||||
cultmesh_store,
|
||||
runtime_id: "epiphany-test".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn release_brake(path: &PathBuf) -> Result<()> {
|
||||
epiphany_core::write_epiphany_cultmesh_swarm_brake(
|
||||
path,
|
||||
"epiphany-test",
|
||||
epiphany_core::default_epiphany_cultmesh_swarm_brake("2026-07-21T00:00:00Z"),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn executes_three_stages_and_replays_terminal_without_inference() -> Result<()> {
|
||||
let dir = tempdir()?;
|
||||
let store = dir.path().join("runtime.cc");
|
||||
let cultmesh = dir.path().join("cultmesh.cc");
|
||||
release_brake(&cultmesh)?;
|
||||
let mut runner = FakeRunner { calls: vec![] };
|
||||
let first =
|
||||
execute_persona_model_turn_with_runner(&store, &plan(cultmesh.clone()), &mut runner)
|
||||
.await?;
|
||||
assert_eq!(runner.calls, ["projector", "persona", "interpreter"]);
|
||||
let second =
|
||||
execute_persona_model_turn_with_runner(&store, &plan(cultmesh), &mut runner).await?;
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(runner.calls.len(), 3);
|
||||
let effects =
|
||||
load_document::<PersonaInterpreterEffectDocument>(&store, &first.effect_document_id)?
|
||||
.unwrap();
|
||||
assert_eq!(effects.effects.len(), 1);
|
||||
assert!(!effects.private_state_exposed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_interpreter_channel_escape_without_terminal_receipt() -> Result<()> {
|
||||
let dir = tempdir()?;
|
||||
let store = dir.path().join("runtime.cc");
|
||||
let cultmesh = dir.path().join("cultmesh.cc");
|
||||
release_brake(&cultmesh)?;
|
||||
let mut runner = FakeRunner { calls: vec![] };
|
||||
let mut escaped = plan(cultmesh);
|
||||
escaped.allowed_channel_ids = vec!["elsewhere".into()];
|
||||
assert!(
|
||||
execute_persona_model_turn_with_runner(&store, &escaped, &mut runner)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
load_document::<PersonaModelTerminalReceipt>(&store, "persona-terminal:turn-1")?
|
||||
.is_none()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_preseeded_stage_receipt_from_wrong_model_before_inference() -> Result<()> {
|
||||
let dir = tempdir()?;
|
||||
let store = dir.path().join("runtime.cc");
|
||||
let cultmesh = dir.path().join("cultmesh.cc");
|
||||
release_brake(&cultmesh)?;
|
||||
let poisoned = PersonaModelStageReceipt {
|
||||
schema_version: PERSONA_MODEL_STAGE_RECEIPT_SCHEMA_VERSION.into(),
|
||||
receipt_id: "persona-stage:turn-1:projector".into(),
|
||||
turn_id: "turn-1".into(),
|
||||
stage: "projector".into(),
|
||||
request_id: "persona:turn-1:projector".into(),
|
||||
output_sha256: format!("sha256:{}", "a".repeat(64)),
|
||||
private_output_ref: "model-events:persona:turn-1:projector".into(),
|
||||
completed_at: now(),
|
||||
private_state_exposed: false,
|
||||
provider: "attacker".into(),
|
||||
model: "wrong-model".into(),
|
||||
prompt_sha256: format!("sha256:{}", "b".repeat(64)),
|
||||
};
|
||||
put_new_document(&store, &poisoned.receipt_id, &poisoned)?;
|
||||
|
||||
let mut runner = FakeRunner { calls: vec![] };
|
||||
let error = execute_persona_model_turn_with_runner(&store, &plan(cultmesh), &mut runner)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("replay binding is invalid"));
|
||||
assert!(runner.calls.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,44 @@
|
|||
# Fresh Workspace Handoff
|
||||
|
||||
## Native Persona conversation is locally proven and ready for braked promotion (2026-07-22)
|
||||
|
||||
The earlier claim that Epiphany depended on VoidBot for Persona/Discord plumbing
|
||||
was false. Epiphany owns heartbeat/CTB pressure, immutable Persona turn
|
||||
reservation, Projector, Persona, Interpreter, Mind effects, signed speech
|
||||
requests, and terminal reconciliation. Bifrost owns only Discord Gateway/token,
|
||||
posting, and signed transport receipts. VoidBot owns nothing in this path.
|
||||
|
||||
The live consequence boundary is a signed CultNet/RUDP permit. Bifrost journals
|
||||
the exact nonce and five-second request window before network, replays that
|
||||
exact tuple only while valid, writes `running` before Discord actuation, checks
|
||||
permit expiry again immediately before posting, and treats every crash-ambiguous
|
||||
or expired outcome as terminal unknown/failed without reposting. Epiphany's
|
||||
permit issuer rereads the canonical brake at issuance and grants one delivery
|
||||
digest once. Failed/unknown transport and ambiguous local Mind effects become
|
||||
non-schedulable typed quarantine. SAY is independent of memory: the Interpreter
|
||||
may speak without manufacturing a state note.
|
||||
|
||||
Packaging now includes the Persona service, mouth identity, permit issuer, and
|
||||
permit identity. Ops owns distinct trust anchors, loopback permit service,
|
||||
read-only crossing directory mounts, rollback of first-enrollment identities and
|
||||
anchors, lifecycle checks, and authority-backup coverage. A Rust-authored
|
||||
CultCache request was consumed by Bifrost through the read-only mount shape; the
|
||||
smoke caught and repaired positional-tuple and byte-vector decoding at the TS
|
||||
boundary.
|
||||
|
||||
Local gates are green: epiphany-core 617 passed / 0 failed / 1 ignored; Persona
|
||||
executor 3/3; Bifrost Persona delivery plus feedback 15/15; Rust-to-Bifrost
|
||||
crossing 1/1; ops rollback, deployment wiring, backup, shell syntax, Rust format,
|
||||
Node syntax, and diff checks pass. No successor has been deployed yet.
|
||||
|
||||
Next: commit and push Epiphany, Bifrost, and gamecult-ops; promote only those
|
||||
exact commits through Bifrost/Idunn with both brakes engaged; run the root Ygg
|
||||
checker; then release only the narrow cognition interval needed for one real
|
||||
addressed Discord conversation. Require the full ingress -> CTB -> three model
|
||||
stages -> signed request -> live permit -> one post -> signed receipt -> terminal
|
||||
reconciliation chain, re-engage sleep immediately, and prove unattended
|
||||
readiness. Do not broadly Wake or reboot.
|
||||
|
||||
## Authenticated provider health is wired into Epiphany Status v2 (2026-07-19)
|
||||
|
||||
The Epiphany operator service now requires Idunn public-query endpoint, pinned
|
||||
|
|
|
|||
102
notes/persona-conversation-authority-map.md
Normal file
102
notes/persona-conversation-authority-map.md
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
# Persona Conversation Authority Map
|
||||
|
||||
## Objective
|
||||
|
||||
Let a human address an Epiphany Persona in Discord, have that pressure enter the
|
||||
resident swarm's own heartbeat physiology, run through the native
|
||||
Projector -> Persona -> Interpreter loop, and return a governed reply to the
|
||||
same conversation without VoidBot owning cognition, scheduling, or Persona
|
||||
state.
|
||||
|
||||
## Owner
|
||||
|
||||
- Bifrost owns Discord transport identity, inbound target admission, actor and
|
||||
guild/channel binding, signatures, and outbound delivery receipts.
|
||||
- Heartbeat owns durable conversation obligations, CTB opportunity, active-turn
|
||||
exclusion, and completion-gated cooldown.
|
||||
- Imagination owns the Persona Projector. Persona owns natural speech. Mind's
|
||||
Interpreter owns conversion into typed candidate effects.
|
||||
- Mind owns durable Persona-state admission. Epiphany owns the signed speech
|
||||
request and its eligibility. Bifrost owns the token-bearing transport worker
|
||||
and alone proves external delivery.
|
||||
|
||||
VoidBot is reference lineage and may remain the room moderator. It owns no
|
||||
writer or scheduler in this path.
|
||||
|
||||
## Inputs
|
||||
|
||||
- A Bifrost-observed Discord event addressed to the configured Epiphany Persona.
|
||||
- Exact guild, channel, message, reply target, actor, target runtime/repository,
|
||||
target Persona, content digest, and visible prompt.
|
||||
- Current Persona state and semantic recall, recent home-repo activity, raw
|
||||
conversation context, social affordances, and organ dependencies.
|
||||
- Root-owned model configuration, two dedicated service-identity anchors, and
|
||||
the canonical swarm brake.
|
||||
|
||||
## Outputs
|
||||
|
||||
- One signed Bifrost conversation delivery.
|
||||
- One immutable Epiphany ingress receipt and one durable pending mention.
|
||||
- One typed Persona turn request with exact reserved mention cargo.
|
||||
- Exact Projector, Persona, and Interpreter stage receipts.
|
||||
- A closed typed Interpreter-effects document.
|
||||
- Optional admitted Persona self-state mutation.
|
||||
- Optional signed Epiphany speech request and signed Bifrost Discord receipt.
|
||||
- One terminal Persona-turn receipt that consumes, retains, or quarantines
|
||||
every mention and starts heartbeat cooldown.
|
||||
|
||||
## Derived State
|
||||
|
||||
- Discord/operator summaries, Aquarium bubbles, schedule JSON, model stream
|
||||
events, semantic recall, and speech previews are sight or cargo. None owns
|
||||
admission, delivery, or mention consumption.
|
||||
- Qdrant is retrieval evidence, not Persona memory authority.
|
||||
|
||||
## Forbidden Writers
|
||||
|
||||
- VoidBot may not write Epiphany conversation obligations or select Persona
|
||||
turns.
|
||||
- Resident Self feedback pressure may not impersonate addressed conversation.
|
||||
- The operator-command path may not become ordinary chat ingress.
|
||||
- Heartbeat may not delete a mention merely because it selected a turn.
|
||||
- Model output may not mutate Mind or claim delivery directly.
|
||||
- The Discord mouth may not synthesize Persona speech.
|
||||
- Epiphany may not read Discord credentials or invoke a token-bearing bridge.
|
||||
- An indeterminate or terminally failed external delivery may not return to the
|
||||
schedulable mention queue under a fresh request id.
|
||||
- Schedule/artifact files may not become the only surviving turn request.
|
||||
|
||||
## Shared Paths
|
||||
|
||||
Direct mentions, role mentions, replies to a Persona message, retries after
|
||||
restart, heartbeat selection, model failures, explicit silence/drop, state
|
||||
mutation, public reply, and delivery reconciliation use the same typed ingress,
|
||||
turn reservation, Interpreter admission, and terminal commit primitives.
|
||||
|
||||
## Cut Line
|
||||
|
||||
1. Replace the Bifrost/VoidBot observation dependency with Bifrost-native
|
||||
Discord ingress and delete literal VoidBot observer authority.
|
||||
2. Admit each signed delivery once into a durable mention obligation.
|
||||
3. Atomically reserve mention cargo when heartbeat selects `persona_turn`; do
|
||||
not consume it before terminal disposition.
|
||||
4. Execute Projector, Persona, and Interpreter as typed model stages. Interpreter
|
||||
emits a strict schema, not text blocks parsed by rules.
|
||||
5. Publish one immutable signed Epiphany request into its single-writer crossing
|
||||
store. Let the Bifrost-owned worker publish one signed receipt into the
|
||||
opposite single-writer store; no Discord credential crosses that boundary.
|
||||
6. Quarantine exact conversational pressure after a signed `failed` or
|
||||
`unknown` receipt so automatic scheduling cannot retry an external
|
||||
consequence whose outcome is terminal or indeterminate.
|
||||
7. Commit terminal outcome, delivery evidence, mention disposition, and
|
||||
heartbeat completion together or through replay-safe exact predecessors.
|
||||
|
||||
## Verification Layer
|
||||
|
||||
The full-path proof observes: duplicate Discord event -> one obligation -> CTB
|
||||
selection -> no private substrate leakage -> natural Persona turn -> typed
|
||||
effects -> exact Mind admission -> Bifrost reply to the source message ->
|
||||
delivery receipt -> terminal mention disposition. Negative proofs cover brake,
|
||||
crash before/after each stage, invalid model output, replay, wrong target,
|
||||
foreign guild/channel, bot/self input, unknown delivery outcome, and service
|
||||
restart.
|
||||
43
notes/persona-discord-permit-authority-map.md
Normal file
43
notes/persona-discord-permit-authority-map.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# Persona Discord permit issuer authority map
|
||||
|
||||
Objective: make the final Discord consequence conditional on a fresh canonical
|
||||
Epiphany brake observation without sharing Epiphany private stores with Bifrost.
|
||||
|
||||
- Owner: `epiphany-persona-discord-permit` is the sole permit issuer. Bifrost
|
||||
owns the signed permit request and consumes a returned permit exactly once.
|
||||
- Inputs: one authenticated CultNet/RUDP permit-request document; the pinned
|
||||
purpose/schema-specific Bifrost service anchor; the exact previously signed
|
||||
delivery-request digest; Epiphany's canonical CultMesh swarm-brake document;
|
||||
the issuer's purpose-specific signing identity and root service anchor.
|
||||
- Output: one signed permit bound to request id, request digest, nonce, target
|
||||
runtime, requester identity, canonical brake-document digest and observation
|
||||
time. Lifetime is at most five seconds.
|
||||
- Replay store: a private CultCache store keyed by request digest plus nonce.
|
||||
First valid request atomically records and returns the permit. An exact retry
|
||||
returns the byte-identical permit. Any key collision or changed request is
|
||||
refused. The store is not mounted by Bifrost.
|
||||
- Brake authority: the canonical CultMesh brake document is reread after
|
||||
request authentication and immediately before atomic permit persistence.
|
||||
Only `released` may issue. Its complete canonical typed payload is hashed;
|
||||
a display status, cached bool, or delivery-request timestamp is not authority.
|
||||
- Transport: CultNet schema messages over RUDP. The request schema is the route
|
||||
discriminator. Malformed, foreign, expired, replay-substituted, or unsigned
|
||||
frames receive no signed permit. No JSON, HTTP, filesystem crossing, or
|
||||
Discord credential enters Epiphany.
|
||||
- Derived state: delivery requests remain inert proposals. A permit is a
|
||||
short-lived consequence authorization, not delivery evidence. A Bifrost
|
||||
receipt remains the sole proof of downstream publication.
|
||||
- Forbidden writers: Persona model stages, Interpreter effects, heartbeat,
|
||||
delivery request store, Bifrost delivery worker, and Discord transport may
|
||||
not manufacture or extend permits or override the brake digest.
|
||||
- Shared path: all Bifrost Discord posts for this contract must authenticate a
|
||||
permit immediately before posting and journal `permitId` as running before
|
||||
the transport call. Running recovery becomes terminal unknown; it never
|
||||
reposts.
|
||||
- Cut line: direct posting from a delivery request is forbidden. Existing
|
||||
request/receipt anchors do not authorize permit-request or permit signatures;
|
||||
each contract has its own root service-anchor record.
|
||||
- Verification layer: unit tests prove positional tuples, domains, anchors,
|
||||
expiry, brake digest, and replay collision behavior. RUDP smoke proves an
|
||||
authenticated request receives one verifiable permit and a braked request
|
||||
receives none.
|
||||
Binary file not shown.
|
|
@ -13,6 +13,7 @@ experiment:
|
|||
idunn_observation_actuation_split: "Odin commit a17b0b6 makes continuous target observation/evaluation/publication the target loop's sole authority and runs deploy/restart consequences separately under one per-target actuation reservation. Manual and automatic consequences share the reservation; automatic work is dropped rather than queued stale while occupied; durable current-request/result CAS is unchanged. Live deployment then exposed that signed Epiphany health admission read the root-owned pinned trust anchor through a writer-locking store path; the deployed successor replaces only that read with an atomic read-only snapshot. Ygg now root-seals Idunn runtime provenance for exact canonical Odin commit 15a744c826f0aa2e8cc322a6543ea8a9afcd852a, digest-pinned Rust image, build artifact, installed binary/actuator/unit/sudoers/drop-in with exact root-owned safe modes, systemd loaded-path/no-reload proof, and live PID executable. The final readiness checker requires that non-actuating proof and passes with the canonical brake engaged."
|
||||
release_publication_ownership: "epiphany-core/src/packaged_release.rs constructs and verifies immutable package bytes and witnesses. Application-owned store publication is distinct from Bifrost release approval and Idunn deployment: packaging proves what artifact exists; downstream applications own their typed publication, while Bifrost and Idunn own crossing and deployment consequences."
|
||||
verifier_read_purity: "Verifier/status reads do not acquire writer authority merely to inspect provider state. epiphany-core/src/persona_feedback_admission.rs reads a provider-owned snapshot through pull_all_read_only_snapshot without taking the provider lock. Status derives from immutable/provider snapshots; mutation locks belong only to the owning writer transaction."
|
||||
native_persona_conversation: "Epiphany owns Persona cognition end to end: heartbeat admits addressed feedback as bounded pressure, reserves one immutable turn, Projector maps typed state into narrative context, Persona writes natural speech, and Interpreter selects bounded state_note, optional single SAY, or sole drop effects. SAY does not require or manufacture a memory note. Mind alone admits local durable effects. Epiphany signs delivery requests into its single-writer CultCache crossing; Bifrost alone owns Discord credentials, Gateway ingress, posting, and signed terminal receipts. Immediately before posting, Bifrost must obtain one signed five-second CultNet/RUDP permit from Epiphany; the issuer rereads the canonical brake at issuance, binds the exact delivery digest, and refuses nonce replay. Bifrost durably records the exact permit request tuple before network, replays only within that window, terminal-quarantines expired or indeterminate outcomes without reposting, and rechecks permit expiry immediately before actuation. Failed/unknown delivery and ambiguous local Mind effects become non-schedulable typed quarantine. VoidBot owns no part of this path. Rust-authored positional CultCache requests have crossed a read-only directory mount into Bifrost; private execution and receipt stores remain separate. Local proof: epiphany-core 617/0/1, Persona executor 3/3, Bifrost delivery/feedback 15/15, Rust-to-Bifrost crossing 1/1, ops rollback/wiring/backup checks green. Live Yggdrasil promotion and Discord conversation remain unproven."
|
||||
unattended_yggdrasil_continuity: "Yggdrasil owns unattended continuity without Starfire. Epiphany, its operator/heartbeat/Self units, Idunn, VoidBot, Docker, WireGuard, the backup timer, and SSH socket activation are enabled at boot. Containers use restart-unless-stopped. The packaged Codex credential is a cold-start seed only: systemd cp --update=none preserves runtime-owned refreshed auth across service restarts, chmod 0600 preserves Codex's in-place refresh ability, and deployed readiness requires canonical auth.json with private owner read/write; legacy credentials.json cannot impersonate it. A root-only daily timer requires every named Epiphany/Bifrost/VoidBot state writer, briefly quiesces them, writes one validated SHA-256-sealed authority archive atomically under /var/backups/gamecult-authority, and refuses publication unless every writer is confirmed active and thawed/unpaused. Idunn is never frozen: freeze/thaw leaves its process alive but kills RUDP physiology. The archive retains Idunn config/trust/provenance while live observation/command state is reconstructed from providers and Bifrost release authority. It excludes releases, logs, media, RAG/vectors, and Qdrant as derived state, retains 14 days, and has no restore actuator. Live snapshot 20260719T173400Z passed checksum/traversal while Idunn continued accepting RUDP health; older unsafe snapshots were deleted. RAID1 is clean. This is local logical-corruption recovery, not off-host disaster backup. Kernel 6.8.0-136 is installed while 6.8.0-134 is running; reboot remains an explicit operator action and is not authorized by deployment or verification."
|
||||
resident_readiness_ownership: "Resident cognition readiness is a join, not one store pretending to own the organism. epiphany-core/src/resident_readiness.rs derives readiness from separately owned provider readiness, packaged release identity/witness, runtime/Verse observations, Mind state, and brake state. Each source remains authoritative for its own fact; the readiness projection is read-derived and grants no cognition or action authority."
|
||||
sleep_brake_semantics: "An engaged swarm brake is sleep mode, not daemon death. Resident services may remain supervised, publish liveness/health, refresh leases, and expose read-only operator sight. The brake blocks cognition launches, scheduling that creates cognitive work, Hands consequences, publication, and deployment action."
|
||||
|
|
@ -815,4 +816,4 @@ current_status:
|
|||
- Candidate `b8517d9d7905eb62314db675cc2f0688510aa5bd` proved stale launch terminalization and current-policy replacement launch: supervisor PID `1147968` launched replacement workspace projector PID `1148157`, whose authenticated ready heartbeat advanced while the engaged brake held. Recovery still stalled because the old Body claim could be read only through current-claim authentication, which correctly rejected its historical policy before the mismatch recovery branch. The candidate was rolled back and revoked; no deployment witness exists. Claim sight now has two explicit authorities: current authentication is required for provider projection work and rejects stale launches; recovery authentication proves the old signed claim/body/route lineage only. Supervisor recovery and directive writing use the recovery reader, while old launch authentication inside the atomic lease-transfer transaction is historical and the replacement launch/heartbeat remain current-policy evidence. The full causal test performs an actual policy rotation and proves current refusal, historical recovery, directive fencing, lease transfer, successor current sight, and replay/tamper boundaries. Full core passes 573/573 with one ignored; all binaries compile.
|
||||
- Candidate `351355d3baee2d475f84168136380d2f50197ef8` authenticated the historical claim and started all three owners under the brake, but recovery refused because the claim named an older launch than the current replacement's direct parent. Repeated failed candidate deployments had formed a valid signed replacement chain, while recovery still assumed one direct old-to-new edge. The exact Idunn process group was terminated, all services stopped, active pointer and witness removed, and Bifrost authority revoked. No deployment witness exists. Recovery now authenticates the complete immutable chain from the claim's historical launch to the live current-policy descendant: every intermediate launch is host-signed, every parent termination id and envelope digest is exact, chronology is ordered, cycles and broken edges refuse, and the selected endpoint must be current. Directive writing, receipt verification, atomic lease transfer, and supervisor resume share this proof. Typed refusal now exposes the exact lineage fault instead of swallowing it. The causal recovery test contains a real intermediate generation and still proves the full fenced transaction. Full library passes 573/573 with one ignored; supervisor authority tests pass 24/24.
|
||||
- Candidate `a70fe275195740ecefc2984b32ebd8ae93658c18` proved the full signed multi-generation chain and emitted recovery directive `06165fb6-97bd-4c27-97e3-38af03dec72d` from historical claim `c6df4335-7080-4d5f-80fc-4fa18a9d16ce` to current launch `9414c32f-f53c-450c-bc19-a69f5ba04a29`. The replacement projector nevertheless kept refusing stale-policy claim sight because its pulse authenticated the not-yet-created current successor claim before looking for the recovery directive. Supervisor replayed the same directive without mutating Body, exposing a circular ordering fault. The exact Idunn process group was terminated, services stopped, pointer and witness removed, and Bifrost authority revoked; no deployment witness exists. Projector recovery directive consumption now precedes all ordinary projection work and invokes the already idempotent atomic transfer directly. Current claim sight is an output of recovery, never a prerequisite for it. Full library now passes 574/574 with one ignored; supervisor authority tests pass 24/24.
|
||||
next_action: "Install exact gamecult-ops a281e38 on Yggdrasil so Idunn's ProtectSystem sandbox grants write custody only to the four named Epiphany unit files; verify canonical LF bytes, exact drop-in, stable Idunn restart, both brakes, and old bcff organs. Authorize only the next Epiphany successor containing seq269 evidence, observe a fresh request, and grant only that exact request for at most 15 minutes. Re-engage the Idunn brake at terminal or unknown consequence. Require exact live witness or complete proven old-generation rollback. Then prove operator-safe Discord Status with complete and one-missing provider cases. Do not test Wake or reboot the host."
|
||||
next_action: "Commit and push the native Persona conversation cut in Epiphany, Bifrost, and gamecult-ops. Promote those exact upstream commits through Bifrost and Idunn only while both deployment and canonical swarm brakes are engaged. Verify trust-root enrollment/rollback, permit service and Persona service lifecycle, crossing mounts, provider readiness, backups, and the root Ygg checker. Then temporarily release only the cognition brake needed for one addressed Discord mention/reply proof; require real Gateway ingress, CTB reservation, Projector-Persona-Interpreter receipts, signed request, live five-second permit, one Discord post, signed Bifrost receipt, and terminal heartbeat/quarantine reconciliation. Re-engage sleep mode immediately and prove unattended boot/readiness. Do not Wake broadly or reboot the host."
|
||||
|
|
|
|||
Reference in a new issue