From 2164bd0a2131e408973310f7cf3d38beb5d76848 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 23 Aug 2026 04:31:28 +0200 Subject: [PATCH] Collapse heartbeat to owned physiology --- .../src/bin/epiphany-heartbeat-store.rs | 310 +------ epiphany-core/src/heartbeat_state.rs | 843 ++---------------- .../heartbeat_state/heartbeat_documents.rs | 183 +--- .../src/heartbeat_state/heartbeat_pacing.rs | 239 ----- .../heartbeat_state/heartbeat_projection.rs | 30 +- .../src/heartbeat_state/heartbeat_roles.rs | 199 +---- .../src/heartbeat_state/heartbeat_store.rs | 32 +- epiphany-core/src/lib.rs | 13 - epiphany-core/src/runtime_spine.rs | 23 +- ...hany.agent-heartbeat-cognition.schema.json | 65 -- .../epiphany.agent-heartbeat.schema.json | 13 +- ...any.circadian_rhythm_intent.v0.schema.json | 26 - ...phany.heartbeat_heat_intent.v0.schema.json | 82 -- ...y.heartbeat_initiative_heat.v0.schema.json | 91 -- ...phany.heartbeat_pump_intent.v0.schema.json | 46 - schemas/cultnet/index.json | 57 +- schemas/heartbeat-state-schema.md | 15 +- 17 files changed, 120 insertions(+), 2147 deletions(-) delete mode 100644 epiphany-core/src/heartbeat_state/heartbeat_pacing.rs delete mode 100644 schemas/cultnet/epiphany.agent-heartbeat-cognition.schema.json delete mode 100644 schemas/cultnet/epiphany.circadian_rhythm_intent.v0.schema.json delete mode 100644 schemas/cultnet/epiphany.heartbeat_heat_intent.v0.schema.json delete mode 100644 schemas/cultnet/epiphany.heartbeat_initiative_heat.v0.schema.json delete mode 100644 schemas/cultnet/epiphany.heartbeat_pump_intent.v0.schema.json diff --git a/epiphany-core/src/bin/epiphany-heartbeat-store.rs b/epiphany-core/src/bin/epiphany-heartbeat-store.rs index e1ed27da..4aeeef62 100644 --- a/epiphany-core/src/bin/epiphany-heartbeat-store.rs +++ b/epiphany-core/src/bin/epiphany-heartbeat-store.rs @@ -3,29 +3,17 @@ use anyhow::Result; use anyhow::anyhow; use epiphany_core::EpiphanyCultMeshSwarmBrakeEntry; use epiphany_core::EpiphanyHeartbeatArtifactRetentionReceipt; -use epiphany_core::GhostlightSceneParticipantSeed; -use epiphany_core::HeartbeatCompleteOptions; -use epiphany_core::HeartbeatHeatUpdateOptions; -use epiphany_core::HeartbeatPumpOptions; -use epiphany_core::HeartbeatQueueMentionOptions; use epiphany_core::HeartbeatStaleTurnRepairOptions; -use epiphany_core::HeartbeatTickOptions; -use epiphany_core::complete_heartbeat_store; use epiphany_core::heartbeat_local_provider_status; use epiphany_core::heartbeat_status_projection; -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; use epiphany_core::recover_stale_heartbeat_store; use epiphany_core::resident_cognitive_runtime_id; use epiphany_core::retain_heartbeat_pulse_artifacts; -use epiphany_core::tick_heartbeat_store; -use epiphany_core::update_heartbeat_heat_store; use epiphany_core::{ ResidentProviderReadiness, acquire_resident_process_singleton, authenticate_epiphany_packaged_release, capture_process_instance, @@ -51,46 +39,12 @@ fn main() -> Result<()> { let mut artifact_dir: Option = None; let mut local_verse_store: Option = None; let mut target_heartbeat_rate = 1.0_f64; - let mut min_heartbeat_rate = 0.05_f64; - let mut max_heartbeat_rate = 4.0_f64; - let mut min_concurrency = 1_usize; - let mut max_concurrency = 8_usize; - let mut max_ticks = 8_usize; - let mut coordinator_action: Option = None; - let mut target_role: Option = None; - let mut urgency = 0.75_f64; - let mut urgency_explicit = false; let mut schedule_id = "epiphany-heartbeat".to_string(); let mut source_scene_ref = "epiphany/coordinator".to_string(); - let mut defer_completion = false; - let mut role: Option = None; - let mut action_id: Option = None; let mut limit = 8_usize; let mut resident_self_store: Option = None; let mut resident_runtime_store: Option = None; - let mut profile = "epiphany".to_string(); - let mut scene_id = "ghostlight.scene".to_string(); - let mut scene_participants = Vec::::new(); - let mut heat_scope = "global".to_string(); - let mut heat_selector = String::new(); - let mut heat_multiplier = 1.0_f64; - let mut heat_id: Option = None; - let mut heat_label: Option = None; - let mut heat_reason: Option = None; - let mut heat_expires_after: Option = None; - let mut heat_clear = false; - let mut channel_id: Option = None; - let mut message_id: Option = None; - let mut author_id: Option = None; - let mut author_name: Option = None; - let mut content: Option = None; - let mut visible_prompt: Option = None; - let mut reply_to_message_id: Option = None; - let mut source_surface = "operator".to_string(); - let mut mention_id: Option = 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 repair_reason: Option = None; let mut max_age_seconds = 1800_i64; let mut now_utc: Option = None; let mut interval_seconds = 120_u64; @@ -112,32 +66,8 @@ fn main() -> Result<()> { "--target-heartbeat-rate" => { target_heartbeat_rate = next_value(&mut args, "--target-heartbeat-rate")?.parse()? } - "--min-heartbeat-rate" => { - min_heartbeat_rate = next_value(&mut args, "--min-heartbeat-rate")?.parse()? - } - "--max-heartbeat-rate" => { - max_heartbeat_rate = next_value(&mut args, "--max-heartbeat-rate")?.parse()? - } - "--min-concurrency" => { - min_concurrency = next_value(&mut args, "--min-concurrency")?.parse()? - } - "--max-concurrency" => { - max_concurrency = next_value(&mut args, "--max-concurrency")?.parse()? - } - "--max-ticks" => max_ticks = next_value(&mut args, "--max-ticks")?.parse()?, - "--coordinator-action" => { - coordinator_action = Some(next_value(&mut args, "--coordinator-action")?) - } - "--target-role" => target_role = Some(next_value(&mut args, "--target-role")?), - "--urgency" => { - urgency = next_value(&mut args, "--urgency")?.parse()?; - urgency_explicit = true; - } "--schedule-id" => schedule_id = next_value(&mut args, "--schedule-id")?, "--source-scene-ref" => source_scene_ref = next_value(&mut args, "--source-scene-ref")?, - "--defer-completion" => defer_completion = true, - "--role" => role = Some(next_value(&mut args, "--role")?), - "--action-id" => action_id = Some(next_value(&mut args, "--action-id")?), "--limit" => limit = next_value(&mut args, "--limit")?.parse()?, "--resident-self-store" => { resident_self_store = Some(next_path(&mut args, "--resident-self-store")?) @@ -145,41 +75,7 @@ fn main() -> Result<()> { "--resident-runtime-store" => { resident_runtime_store = Some(next_path(&mut args, "--resident-runtime-store")?) } - "--profile" => profile = next_value(&mut args, "--profile")?, - "--scene-id" => scene_id = next_value(&mut args, "--scene-id")?, - "--scene-participant" => scene_participants.push(parse_scene_participant( - &next_value(&mut args, "--scene-participant")?, - )?), - "--scope" => heat_scope = next_value(&mut args, "--scope")?, - "--selector" => heat_selector = next_value(&mut args, "--selector")?, - "--multiplier" => heat_multiplier = next_value(&mut args, "--multiplier")?.parse()?, - "--id" => heat_id = Some(next_value(&mut args, "--id")?), - "--label" => heat_label = Some(next_value(&mut args, "--label")?), - "--reason" => heat_reason = Some(next_value(&mut args, "--reason")?), - "--expires-after" => { - heat_expires_after = Some(next_value(&mut args, "--expires-after")?.parse()?) - } - "--clear" => heat_clear = true, - "--channel-id" => channel_id = Some(next_value(&mut args, "--channel-id")?), - "--message-id" => message_id = Some(next_value(&mut args, "--message-id")?), - "--author-id" => author_id = Some(next_value(&mut args, "--author-id")?), - "--author-name" => author_name = Some(next_value(&mut args, "--author-name")?), - "--content" => content = Some(next_value(&mut args, "--content")?), - "--visible-prompt" => visible_prompt = Some(next_value(&mut args, "--visible-prompt")?), - "--reply-to-message-id" => { - reply_to_message_id = Some(next_value(&mut args, "--reply-to-message-id")?) - } - "--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")? - } + "--reason" => repair_reason = Some(next_value(&mut args, "--reason")?), "--max-age-seconds" => { max_age_seconds = next_value(&mut args, "--max-age-seconds")?.parse()? } @@ -212,22 +108,12 @@ fn main() -> Result<()> { match command.as_str() { "init" => { let store_path = store_path.ok_or_else(|| anyhow!("init requires --store"))?; - let state = match profile.as_str() { - "epiphany" => initialize_heartbeat_store(&store_path, target_heartbeat_rate)?, - "ghostlight-scene" => initialize_ghostlight_scene_heartbeat_store( - &store_path, - target_heartbeat_rate, - scene_id.clone(), - scene_participants, - )?, - other => return Err(anyhow!("unknown heartbeat profile {other:?}")), - }; + let state = initialize_heartbeat_store(&store_path, target_heartbeat_rate)?; println!( "{}", serde_json::json!({ "ok": true, "command": "init", - "profile": profile, "storeFile": store_path, "schemaVersion": state.schema_version, "participants": state.participants.len(), @@ -235,44 +121,6 @@ fn main() -> Result<()> { }) ); } - "tick" => { - assert_swarm_brake_allows_heartbeat( - &local_verse_store, - release_runtime_id.as_deref(), - "tick", - )?; - let store_path = store_path.ok_or_else(|| anyhow!("tick requires --store"))?; - let artifact_dir = - artifact_dir.ok_or_else(|| anyhow!("tick requires --artifact-dir"))?; - let tick_schedule_id = schedule_id.clone(); - let mut result = tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate, - coordinator_action, - target_role, - urgency, - schedule_id: tick_schedule_id, - source_scene_ref, - defer_completion, - resident_self_store: resident_self_store.clone(), - }, - )?; - println!("{}", result); - } - "complete" => { - let store_path = store_path.ok_or_else(|| anyhow!("complete requires --store"))?; - let artifact_dir = - artifact_dir.ok_or_else(|| anyhow!("complete requires --artifact-dir"))?; - let role = role.ok_or_else(|| anyhow!("complete requires --role"))?; - let result = complete_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatCompleteOptions { role, action_id }, - )?; - println!("{}", result); - } "repair-stale" => { let store_path = store_path.ok_or_else(|| anyhow!("repair-stale requires --store"))?; let artifact_dir = @@ -283,7 +131,7 @@ fn main() -> Result<()> { HeartbeatStaleTurnRepairOptions { max_age_seconds, now_utc, - reason: heat_reason.unwrap_or_else(|| { + reason: repair_reason.unwrap_or_else(|| { "Operator requested stale heartbeat turn recovery.".to_string() }), }, @@ -312,91 +160,6 @@ fn main() -> Result<()> { }) ); } - "pump" => { - assert_swarm_brake_allows_heartbeat( - &local_verse_store, - release_runtime_id.as_deref(), - "pump", - )?; - let store_path = store_path.ok_or_else(|| anyhow!("pump requires --store"))?; - let artifact_dir = - artifact_dir.ok_or_else(|| anyhow!("pump requires --artifact-dir"))?; - let result = pump_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatPumpOptions { - base_heartbeat_rate: target_heartbeat_rate, - min_heartbeat_rate, - max_heartbeat_rate, - min_concurrency, - max_concurrency, - max_ticks, - external_urgency: if urgency_explicit { urgency } else { 0.0 }, - coordinator_action, - target_role, - schedule_id, - source_scene_ref, - resident_self_store, - }, - )?; - println!("{}", result); - } - "heat" => { - assert_swarm_brake_allows_heartbeat( - &local_verse_store, - release_runtime_id.as_deref(), - "heat", - )?; - let store_path = store_path.ok_or_else(|| anyhow!("heat requires --store"))?; - let result = update_heartbeat_heat_store( - &store_path, - HeartbeatHeatUpdateOptions { - scope: heat_scope, - selector: heat_selector, - multiplier: heat_multiplier, - id: heat_id, - label: heat_label, - reason: heat_reason, - expires_after_scene_clock: heat_expires_after, - clear: heat_clear, - }, - )?; - println!("{}", result); - } - "queue-mention" => { - assert_swarm_brake_allows_heartbeat( - &local_verse_store, - release_runtime_id.as_deref(), - "queue-mention", - )?; - let store_path = store_path.ok_or_else(|| anyhow!("queue-mention requires --store"))?; - let target_role_id = role.unwrap_or_else(|| "Persona".to_string()); - let result = queue_heartbeat_pending_mention_store( - &store_path, - HeartbeatQueueMentionOptions { - target_role_id, - source_surface, - channel_id: channel_id - .ok_or_else(|| anyhow!("queue-mention requires --channel-id"))?, - message_id: message_id - .ok_or_else(|| anyhow!("queue-mention requires --message-id"))?, - author_id: author_id - .ok_or_else(|| anyhow!("queue-mention requires --author-id"))?, - author_name, - content: content.ok_or_else(|| anyhow!("queue-mention requires --content"))?, - visible_prompt: visible_prompt - .ok_or_else(|| anyhow!("queue-mention requires --visible-prompt"))?, - reply_to_message_id, - queued_at: None, - mention_id, - source_visibility, - data_classification, - model_provider_id, - model_provider_disclosure_allowed: true, - }, - )?; - println!("{}", result); - } "status" => { let store_path = store_path.ok_or_else(|| anyhow!("status requires --store"))?; if let Some(artifact_dir) = artifact_dir { @@ -752,36 +515,14 @@ fn next_value(args: &mut impl Iterator, name: &str) -> Result Result<()> { Err(anyhow!(concat!( - "usage: epiphany-heartbeat-store init --store [--profile epiphany|ghostlight-scene] [--scene-id ] [--scene-participant ]\n", - " epiphany-heartbeat-store tick --store --artifact-dir [options]\n", - " epiphany-heartbeat-store pump --store --artifact-dir [options]\n", - " epiphany-heartbeat-store heat --store [options]\n", - " epiphany-heartbeat-store complete --store --artifact-dir --role [--action-id ]\n", + "usage: epiphany-heartbeat-store init --store [--target-heartbeat-rate ]\n", " epiphany-heartbeat-store repair-stale --store --artifact-dir [options]\n", " epiphany-heartbeat-store retain-artifacts --store --artifact-dir [--retain-pulse-artifacts ] [--retention-batch-size ]\n", - " epiphany-heartbeat-store queue-mention --store [options]\n", " epiphany-heartbeat-store status --store [--artifact-dir ]\n", " epiphany-heartbeat-store serve --store --artifact-dir [--local-verse-store ] [--resident-self-store --resident-runtime-store ] [--interval-seconds ] [--max-iterations ]" ))) } -fn assert_swarm_brake_allows_heartbeat( - local_verse_store: &Option, - runtime_id: Option<&str>, - command: &str, -) -> Result<()> { - if let Some(brake) = active_swarm_brake(local_verse_store, runtime_id)? { - anyhow::bail!( - "epiphany-heartbeat-store {command} refusing to run: local Verse swarm brake engaged; scope={}; protected={}; affected={}; reason={}", - brake.scope, - brake.protected_surfaces.join(","), - brake.affected_clusters.join(","), - brake.reason - ); - } - Ok(()) -} - fn heartbeat_brake_runtime_id( resident_self_store: &Option, resident_runtime_store: &Option, @@ -878,25 +619,6 @@ mod brake_tests { Ok(()) } - #[test] - fn retention_receipt_projection_names_operator_fields() { - let projection = retention_receipt_projection(&EpiphanyHeartbeatArtifactRetentionReceipt { - schema_version: "epiphany.heartbeat.artifact_retention_receipt.v0".into(), - receipt_id: "receipt-1".into(), - plan_id: "plan-1".into(), - status: "completed".into(), - deleted_directories: vec!["pulse-000001".into()], - deleted_file_count: 2, - deleted_byte_count: 3, - completed_at_utc: "2026-08-08T21:00:00Z".into(), - private_state_exposed: false, - }); - assert_eq!(projection["receiptId"], "receipt-1"); - assert_eq!(projection["deletedDirectories"][0], "pulse-000001"); - assert_eq!(projection["deletedFileCount"], 2); - assert!(projection.as_array().is_none()); - } - #[test] fn resident_heartbeat_resumes_after_highest_artifact_sequence() -> Result<()> { let temp = tempfile::tempdir()?; @@ -908,25 +630,3 @@ mod brake_tests { Ok(()) } } - -fn parse_scene_participant(raw: &str) -> Result { - let parts = raw.split('|').collect::>(); - if parts.len() != 6 { - return Err(anyhow!( - "--scene-participant must be id|name|speed|reaction|threshold|constraint;constraint" - )); - } - Ok(GhostlightSceneParticipantSeed { - agent_id: parts[0].trim().to_string(), - display_name: parts[1].trim().to_string(), - initiative_speed: parts[2].trim().parse()?, - reaction_bias: parts[3].trim().parse()?, - interrupt_threshold: parts[4].trim().parse()?, - constraints: parts[5] - .split(';') - .map(str::trim) - .filter(|item| !item.is_empty()) - .map(str::to_string) - .collect(), - }) -} diff --git a/epiphany-core/src/heartbeat_state.rs b/epiphany-core/src/heartbeat_state.rs index 30b40dab..ab5cf4ba 100644 --- a/epiphany-core/src/heartbeat_state.rs +++ b/epiphany-core/src/heartbeat_state.rs @@ -10,29 +10,19 @@ use std::fs; use std::path::Path; mod heartbeat_documents; -mod heartbeat_pacing; mod heartbeat_projection; mod heartbeat_retention; mod heartbeat_roles; mod heartbeat_store; pub use heartbeat_documents::*; -use heartbeat_pacing::adaptive_swarm_pacing; -use heartbeat_pacing::apply_initiative_heat_policy; -use heartbeat_pacing::effective_cooldown_multiplier; -use heartbeat_pacing::initiative_heat_multiplier; -use heartbeat_pacing::running_turn_count; pub use heartbeat_projection::heartbeat_status_projection; use heartbeat_projection::history_event_json; -use heartbeat_projection::pending_turn_json; use heartbeat_projection::schedule_participant_json; use heartbeat_projection::selection_policy_json; pub use heartbeat_retention::retain_heartbeat_pulse_artifacts; use heartbeat_roles::ROLE_ORDER; -use heartbeat_roles::agent_id_for_role; pub use heartbeat_roles::default_heartbeat_state; use heartbeat_roles::default_participant; -pub use heartbeat_roles::ghostlight_scene_heartbeat_state; -pub use heartbeat_roles::initialize_ghostlight_scene_heartbeat_store; pub use heartbeat_roles::initialize_heartbeat_store; pub use heartbeat_store::commit_heartbeat_state_transaction; pub use heartbeat_store::heartbeat_state_cache; @@ -44,9 +34,7 @@ pub use heartbeat_store::write_heartbeat_stale_turn_repair_receipt; pub use heartbeat_store::write_heartbeat_state_entry; pub(super) const HEARTBEAT_ARENA_MAINTENANCE: &str = "maintenance"; -pub(super) const HEARTBEAT_ARENA_SCENE: &str = "scene"; pub(super) const PARTICIPANT_KIND_AGENT: &str = "agent"; -pub(super) const PARTICIPANT_KIND_CHARACTER: &str = "character"; #[derive(Clone, Debug, PartialEq)] struct HeartbeatAction { @@ -60,7 +48,7 @@ struct HeartbeatAction { local_affordance_basis: Vec, } -pub fn tick_heartbeat_store( +fn tick_heartbeat_store( store_path: impl AsRef, artifact_dir: impl AsRef, options: HeartbeatTickOptions, @@ -78,7 +66,6 @@ pub fn tick_heartbeat_store( state.target_heartbeat_rate = options.target_heartbeat_rate; } patch_missing_participants(&mut state); - apply_initiative_heat_policy(&mut state); if let Some(resident_store) = options.resident_self_store.as_deref() && crate::pending_resident_self_pressure(resident_store)? && let Some(pending) = state @@ -117,22 +104,15 @@ pub fn tick_heartbeat_store( } else { false }; - let mut effective_options = options.clone(); - if resident_pressure_pending { - effective_options.coordinator_action = Some("resident-self-pressure".to_string()); - effective_options.target_role = Some("coordinator".to_string()); - effective_options.defer_completion = true; - } - let result = tick_once(&mut state, &effective_options, resident_pressure_pending)?; + let result = tick_once(&mut state, &options, resident_pressure_pending)?; commit_heartbeat_state_transaction(store_path, expected_state, &state)?; if result["event"]["selectedRole"] == "coordinator" - && effective_options.defer_completion - && let Some(resident_store) = effective_options.resident_self_store.as_deref() + && let Some(resident_store) = options.resident_self_store.as_deref() { let schedule_id = result["event"]["schedule_id"] .as_str() .or_else(|| result["event"]["scheduleId"].as_str()) - .unwrap_or(&effective_options.schedule_id); + .unwrap_or(&options.schedule_id); let action_id = result["event"]["action_id"] .as_str() .or_else(|| result["event"]["actionId"].as_str()) @@ -225,12 +205,8 @@ pub fn pulse_persona_heartbeat( 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, resident_self_store: None, }, )?; @@ -408,12 +384,8 @@ pub fn pulse_resident_self_heartbeat( artifact_dir, HeartbeatTickOptions { target_heartbeat_rate: 1.0, - coordinator_action: None, - target_role: None, - urgency: 0.0, schedule_id: schedule_id.into(), source_scene_ref: source_scene_ref.into(), - defer_completion: true, resident_self_store: Some(resident_store.to_path_buf()), }, )?; @@ -426,236 +398,6 @@ pub fn pulse_resident_self_heartbeat( }) } -pub fn pump_heartbeat_store( - store_path: impl AsRef, - artifact_dir: impl AsRef, - options: HeartbeatPumpOptions, -) -> Result { - let store_path = store_path.as_ref(); - if let Some(resident_store) = options.resident_self_store.as_deref() { - let heartbeat = load_heartbeat_state_entry(store_path)?; - let pending_ack = if let Some(pending) = heartbeat - .as_ref() - .and_then(|state| { - state - .participants - .iter() - .find(|p| p.role_id == "coordinator") - }) - .and_then(|p| p.pending_turn.as_ref()) - { - crate::pending_resident_self_ack_for( - resident_store, - &pending.schedule_id, - &pending.action_id, - )? - .is_some() - } else { - false - }; - if crate::pending_resident_self_pressure(resident_store)? || pending_ack { - let tick = tick_heartbeat_store( - store_path, - artifact_dir.as_ref(), - HeartbeatTickOptions { - target_heartbeat_rate: options.base_heartbeat_rate.max(0.001), - coordinator_action: None, - target_role: None, - urgency: options.external_urgency, - schedule_id: format!("{}.resident-self", options.schedule_id), - source_scene_ref: options.source_scene_ref.clone(), - defer_completion: true, - resident_self_store: Some(resident_store.to_path_buf()), - }, - )?; - return Ok(serde_json::json!({ - "schema_version": "epiphany.adaptive_heartbeat_pump.v0", "storeFile": store_path, - "artifactDir": artifact_dir.as_ref(), "sourceSceneRef": options.source_scene_ref, - "scheduleId": options.schedule_id, "launched": 1, "ticks": [tick], - "residentSelfDelegatedToTransactionalTick": true, "errors": [] - })); - } - } - let mut state = load_heartbeat_state_entry(store_path)? - .unwrap_or_else(|| default_heartbeat_state(options.base_heartbeat_rate.max(0.001))); - if options.base_heartbeat_rate > 0.0 { - state.target_heartbeat_rate = options.base_heartbeat_rate; - } - patch_missing_participants(&mut state); - apply_initiative_heat_policy(&mut state); - - let pacing = adaptive_swarm_pacing(&state, &options); - state.target_heartbeat_rate = pacing.effective_heartbeat_rate; - state.adaptive_pacing = Some(HeartbeatAdaptivePacing { - schema_version: "epiphany.adaptive_heartbeat_pacing.v0".to_string(), - contract: "Swarm pressure controls both heartbeat tempo and concurrency. Relaxed systems sleep slow; urgent systems fill more lanes without re-waking unfinished turns.".to_string(), - pressure: pacing.pressure, - effective_heartbeat_rate: pacing.effective_heartbeat_rate, - target_concurrency: pacing.target_concurrency, - running_turns: pacing.running_turns, - active_participants: pacing.active_participants, - signals: pacing.signals.clone(), - }); - - let artifact_dir = artifact_dir.as_ref(); - fs::create_dir_all(artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let mut tick_results = Vec::new(); - let mut errors = Vec::new(); - let ticks_allowed = options.max_ticks.min(pacing.target_concurrency); - for index in 0..ticks_allowed { - if running_turn_count(&state) >= pacing.target_concurrency { - break; - } - let use_coordinator_action = index == 0; - let tick_options = HeartbeatTickOptions { - target_heartbeat_rate: pacing.effective_heartbeat_rate, - coordinator_action: use_coordinator_action - .then(|| options.coordinator_action.clone()) - .flatten(), - target_role: use_coordinator_action - .then(|| options.target_role.clone()) - .flatten(), - urgency: pacing - .pressure - .max(options.external_urgency.clamp(0.0, 1.0)), - schedule_id: format!("{}.pump-{:03}", options.schedule_id, index + 1), - source_scene_ref: options.source_scene_ref.clone(), - defer_completion: true, - resident_self_store: options.resident_self_store.clone(), - }; - match tick_once(&mut state, &tick_options, false) { - Ok(result) => { - write_json_artifact( - artifact_dir.join(format!("{}.initiative.json", tick_options.schedule_id)), - &result["schedule"], - )?; - write_json_artifact( - artifact_dir.join(format!("{}.event.json", tick_options.schedule_id)), - &result["event"], - )?; - tick_results.push(serde_json::json!({ - "event": result["event"], - "schedule": result["schedule"], - })); - } - Err(error) => { - errors.push(error.to_string()); - break; - } - } - } - let launched = tick_results.len(); - let final_running_turns = running_turn_count(&state); - write_heartbeat_state_entry(store_path, &state)?; - - let pump = serde_json::json!({ - "schema_version": "epiphany.adaptive_heartbeat_pump.v0", - "storeFile": store_path, - "artifactDir": artifact_dir, - "sourceSceneRef": options.source_scene_ref, - "scheduleId": options.schedule_id, - "pacing": { - "schema_version": "epiphany.adaptive_heartbeat_pacing.v0", - "pressure": pacing.pressure, - "effectiveHeartbeatRate": pacing.effective_heartbeat_rate, - "targetConcurrency": pacing.target_concurrency, - "runningTurnsBefore": pacing.running_turns, - "runningTurnsAfter": final_running_turns, - "activeParticipants": pacing.active_participants, - "signals": pacing.signals, - }, - "launched": launched, - "ticks": tick_results, - "errors": errors, - "reviewNotes": [ - "The pump controls opportunity pressure, not authority.", - "A relaxed swarm may launch nothing; an urgent swarm may fill most available lanes.", - "Per-lane pending turns remain hard locks, so no agent is re-heartbeaten while its previous turn is running." - ], - }); - write_json_artifact( - artifact_dir.join(format!("{}.pump.json", options.schedule_id)), - &pump, - )?; - - Ok(serde_json::json!({ - "ok": errors.is_empty(), - "pump": pump, - })) -} - -pub fn update_heartbeat_heat_store( - store_path: impl AsRef, - options: HeartbeatHeatUpdateOptions, -) -> Result { - let store_path = store_path.as_ref(); - let mut state = load_heartbeat_state_entry(store_path)?.unwrap_or_else(|| { - let mut state = default_heartbeat_state(1.0); - patch_missing_participants(&mut state); - state - }); - patch_missing_participants(&mut state); - let scope = options.scope.trim().to_lowercase(); - let selector = options.selector.trim().to_string(); - let id = options.id.clone().unwrap_or_else(|| { - if scope == "global" { - "global".to_string() - } else { - format!("{scope}:{selector}") - } - }); - - if options.clear { - if scope == "global" || id == "global" { - state.initiative_heat.global_multiplier = 1.0; - } - state - .initiative_heat - .multipliers - .retain(|multiplier| multiplier.id != id); - } else if scope == "global" { - state.initiative_heat.global_multiplier = options.multiplier.clamp(0.05, 25.0); - } else { - if selector.is_empty() && scope != "all" { - return Err(anyhow!( - "heartbeat heat selector is required for scope {scope}" - )); - } - let multiplier = HeartbeatInitiativeMultiplier { - id: id.clone(), - label: options.label.clone().unwrap_or_default(), - scope: scope.clone(), - selector: selector.clone(), - multiplier: options.multiplier.clamp(0.05, 25.0), - reason: options.reason.clone().unwrap_or_default(), - updated_at: Some(now_iso()), - expires_at_scene_clock: options - .expires_after_scene_clock - .map(|delta| round6(state.scene_clock + delta.max(0.0))), - }; - state - .initiative_heat - .multipliers - .retain(|existing| existing.id != id); - state.initiative_heat.multipliers.push(multiplier); - state - .initiative_heat - .multipliers - .sort_by(|left, right| left.id.cmp(&right.id)); - } - apply_initiative_heat_policy(&mut state); - write_heartbeat_state_entry(store_path, &state)?; - Ok(serde_json::json!({ - "ok": true, - "command": "heat", - "storeFile": store_path, - "heat": initiative_heat_json(&state), - "participants": state.participants.iter().map(schedule_participant_json).collect::>(), - })) -} - pub fn queue_heartbeat_pending_mention_store( store_path: impl AsRef, options: HeartbeatQueueMentionOptions, @@ -746,97 +488,6 @@ pub fn queue_heartbeat_pending_mention_store( })) } -fn initiative_heat_json(state: &EpiphanyHeartbeatStateEntry) -> Value { - serde_json::json!({ - "schemaVersion": state.initiative_heat.schema_version, - "globalMultiplier": state.initiative_heat.global_multiplier, - "multipliers": state.initiative_heat.multipliers.iter().map(|multiplier| { - serde_json::json!({ - "id": multiplier.id, - "label": multiplier.label, - "scope": multiplier.scope, - "selector": multiplier.selector, - "multiplier": multiplier.multiplier, - "reason": multiplier.reason, - "updatedAt": multiplier.updated_at, - "expiresAtSceneClock": multiplier.expires_at_scene_clock, - }) - }).collect::>(), - }) -} - -pub fn complete_heartbeat_store( - store_path: impl AsRef, - artifact_dir: impl AsRef, - options: HeartbeatCompleteOptions, -) -> Result { - let store_path = store_path.as_ref(); - let mut state = load_heartbeat_state_entry(store_path)?.ok_or_else(|| { - anyhow!( - "CultCache store {} has no heartbeat state entry", - store_path.display() - ) - })?; - let participant_index = participant_index_by_role(&state, &options.role)?; - let pending = state.participants[participant_index] - .pending_turn - .clone() - .ok_or_else(|| anyhow!("{} has no running heartbeat turn", options.role))?; - if pending.status != "running" { - return Err(anyhow!("{} has no running heartbeat turn", options.role)); - } - if let Some(action_id) = &options.action_id - && pending.action_id != *action_id - { - return Err(anyhow!( - "{} pending heartbeat action is {}, not {}", - options.role, - pending.action_id, - action_id - )); - } - let completed = complete_pending_turn(&mut state, participant_index)?; - let participant = &state.participants[participant_index]; - let event = HeartbeatHistoryEvent { - ts: now_iso(), - schedule_id: completed.schedule_id.clone(), - selected_role: options.role, - selected_agent_id: participant.agent_id.clone(), - action_id: completed.action_id.clone(), - action_type: completed.action_type.clone(), - arena: participant_arena(participant).to_string(), - participant_kind: participant_kind(participant).to_string(), - action_scale: completed.action_scale.clone(), - coordinator_action: None, - target_role: None, - work_role: None, - scene_clock: Some(state.scene_clock), - next_ready_at: Some(participant.next_ready_at), - turn_status: Some("completed".to_string()), - cooldown_started_after_completion: Some(true), - }; - state.history.push(event.clone()); - trim_history(&mut state); - write_heartbeat_state_entry(store_path, &state)?; - - let artifact_dir = artifact_dir.as_ref(); - fs::create_dir_all(artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - if !completed.schedule_id.is_empty() { - write_json_artifact( - artifact_dir.join(format!("{}.completion.json", completed.schedule_id)), - &serde_json::json!({"event": history_event_json(event.clone()), "turn": pending_turn_json(&completed)}), - )?; - } - - Ok(serde_json::json!({ - "ok": true, - "storeFile": store_path, - "event": history_event_json(event), - "completedTurn": pending_turn_json(&completed), - })) -} - pub fn recover_stale_heartbeat_store( store_path: impl AsRef, artifact_dir: impl AsRef, @@ -1005,29 +656,17 @@ pub fn recover_stale_heartbeat_store( fn tick_once( state: &mut EpiphanyHeartbeatStateEntry, options: &HeartbeatTickOptions, - force_work_role: bool, + resident_pressure_pending: bool, ) -> Result { let rate = state.target_heartbeat_rate.max(0.001); - let work_role = work_role_for_action( - options.coordinator_action.as_deref(), - options.target_role.as_deref(), - ); - let (selected_index, selection_kind, selection_reason) = select_participant( - state, - work_role.as_deref(), - options.urgency, - force_work_role, - )?; + let work_role = resident_pressure_pending.then_some("coordinator"); + let urgency = if resident_pressure_pending { 1.0 } else { 0.0 }; + let (selected_index, selection_kind, selection_reason) = + select_participant(state, work_role, urgency, resident_pressure_pending)?; let selected = state.participants[selected_index].clone(); - let action = action_for_selection( - state, - &selected, - work_role.as_deref(), - options.coordinator_action.as_deref(), - rate, - ); + let action = action_for_selection(state, &selected, work_role, rate); let scene_clock = state.scene_clock.max(selected.next_ready_at); - let recovery = action.base_recovery * effective_cooldown_multiplier(&selected) + let recovery = action.base_recovery / selected .initiative_speed .max(state.selection_policy.minimum_speed); @@ -1046,8 +685,6 @@ fn tick_once( completed_at: None, completed_scene_clock: None, next_ready_at: None, - initiative_heat_multiplier: initiative_heat_multiplier(&selected), - effective_cooldown_multiplier: effective_cooldown_multiplier(&selected), initiative_frozen: true, initiative_freeze_reason: Some( "Participant has an active heartbeat turn; initiative cannot queue it again until the turn completes." @@ -1070,10 +707,6 @@ fn tick_once( Value::Null, )?; } - if !options.defer_completion && action.action_type != "persona_turn" { - complete_pending_turn(state, selected_index)?; - } - let selected_after = state.participants[selected_index].clone(); let event = HeartbeatHistoryEvent { ts: now_iso(), @@ -1085,22 +718,18 @@ fn tick_once( arena: participant_arena(&selected_after).to_string(), participant_kind: participant_kind(&selected_after).to_string(), action_scale: action.action_scale.to_string(), - coordinator_action: options.coordinator_action.clone(), - target_role: options.target_role.clone(), - work_role: work_role.clone(), + coordinator_action: None, + target_role: work_role.map(str::to_string), + work_role: work_role.map(str::to_string), scene_clock: Some(state.scene_clock), next_ready_at: Some(selected_after.next_ready_at), - turn_status: Some(if options.defer_completion { - "running".to_string() - } else { - "completed".to_string() - }), + turn_status: Some("running".to_string()), cooldown_started_after_completion: Some(true), }; state.history.push(event.clone()); trim_history(state); - let readiness_snapshot = readiness_snapshot(state, work_role.as_deref(), options.urgency); + let readiness_snapshot = readiness_snapshot(state, work_role, urgency); let schedule = serde_json::json!({ "schema_version": INITIATIVE_SCHEMA_VERSION, "schedule_id": options.schedule_id, @@ -1115,20 +744,18 @@ fn tick_once( "action_type": action.action_type, "action_scale": action.action_scale, "base_recovery": action.base_recovery, - "initiative_heat_multiplier": initiative_heat_multiplier(&selected_after), - "effective_cooldown_multiplier": effective_cooldown_multiplier(&selected_after), "initiative_cost": action.initiative_cost, "interruptibility": action.interruptibility, "commitment": action.commitment, "local_affordance_basis": action.local_affordance_basis, "pending_mentions": selected_pending_mentions, }], - "reaction_windows": if let Some(work_role) = &work_role { + "reaction_windows": if work_role.is_some() { serde_json::json!([{ "window_id": format!("{}.pending-work", options.schedule_id), "trigger_event_ref": options.source_scene_ref, - "urgency": options.urgency, - "eligible_actor_ids": [agent_id_for_work_role(state, work_role)], + "urgency": urgency, + "eligible_actor_ids": [selected_after.agent_id.clone()], "allowed_action_scales": ["short", "standard"], "expires_at": round6(state.scene_clock + 1.0), "notes": "Pending coordinator work can pull its owning lane forward only if readiness clears threshold." @@ -1148,7 +775,7 @@ fn tick_once( }, "pending_mentions": state.pending_mentions.clone(), "review_notes": [ - "Epiphany heartbeat uses Ghostlight initiative timing as a harness scheduling receipt.", + "Epiphany heartbeat records coordinator and Persona scheduling receipts.", "A selected idle lane records scheduling opportunity; it does not invent project work or mutate durable memory.", "When no coordinator work is active, cooldown and sleep pacing keep the swarm from thrashing." ], @@ -1507,32 +1134,9 @@ fn action_for_selection( state: &EpiphanyHeartbeatStateEntry, selected: &HeartbeatParticipant, work_role: Option<&str>, - coordinator_action: Option<&str>, target_heartbeat_rate: f64, ) -> HeartbeatAction { let minimum_rate = state.pacing_policy.minimum_effective_rate.max(0.001); - if participant_arena(selected) == HEARTBEAT_ARENA_SCENE { - let heartbeat_rate = target_heartbeat_rate.max(minimum_rate); - return HeartbeatAction { - action_id: format!("heartbeat.{}.scene-turn", selected.role_id), - action_type: "scene_turn", - action_scale: "standard", - base_recovery: state.pacing_policy.work_base_recovery / heartbeat_rate, - initiative_cost: 4.0, - interruptibility: 0.5, - commitment: 0.7, - local_affordance_basis: vec![ - format!( - "Project {} from current Ghostlight scene state and run one local character turn.", - selected.display_name - ), - "Selected actor receives only projected local context, not omniscient coordinator state." - .to_string(), - "The same heartbeat timing law schedules scene characters and maintenance organs." - .to_string(), - ], - }; - } let pending_mentions = pending_mentions_for_role(state, &selected.role_id); if !pending_mentions.is_empty() && selected.role_id == "Persona" { let heartbeat_rate = target_heartbeat_rate.max(minimum_rate); @@ -1568,11 +1172,7 @@ fn action_for_selection( interruptibility: 0.45, commitment: 0.65, local_affordance_basis: vec![ - format!( - "Wake {} for coordinator action {}.", - selected.display_name, - coordinator_action.unwrap_or("pending work") - ), + format!("Wake {} for admitted Resident Self pressure.", selected.display_name), "Heartbeat slots control opportunity, not project authority.".to_string(), "Cooldown starts only after the heartbeat turn completes, so an unfinished sub-agent thread cannot be heartbeaten again.".to_string(), ], @@ -1603,31 +1203,6 @@ fn action_for_selection( } } -fn work_role_for_action(action: Option<&str>, target_role: Option<&str>) -> Option { - if let Some(target_role) = target_role - && (ROLE_ORDER.contains(&target_role) || target_role.starts_with("ghostlight.character.")) - { - return Some(target_role.to_string()); - } - let role = match action? { - "prepareCheckpoint" => "coordinator", - "surfaceAgentThoughts" | "discordAquariumChat" => "Persona", - "continueImplementation" => "implementation", - "launchImagination" | "readImaginationResult" | "reviewImaginationResult" => "imagination", - "launchModeling" | "readModelingResult" | "reviewModelingResult" => "modeling", - "launchVerification" | "readVerificationResult" | "reviewVerificationResult" => { - "verification" - } - "launchReorientWorker" - | "readReorientResult" - | "acceptReorientResult" - | "compactRehydrateReorient" - | "regatherManually" => "reorientation", - _ => return None, - }; - Some(role.to_string()) -} - fn pending_mentions_for_role( state: &EpiphanyHeartbeatStateEntry, role_id: &str, @@ -1665,16 +1240,14 @@ fn stable_pending_mention_id( } fn patch_missing_participants(state: &mut EpiphanyHeartbeatStateEntry) { - if !is_ghostlight_scene_state(state) { - let present: Vec = state - .participants - .iter() - .map(|item| item.role_id.clone()) - .collect(); - for role_id in ROLE_ORDER { - if !present.iter().any(|present| present == role_id) { - state.participants.push(default_participant(role_id)); - } + let present: Vec = state + .participants + .iter() + .map(|item| item.role_id.clone()) + .collect(); + for role_id in ROLE_ORDER { + if !present.iter().any(|present| present == role_id) { + state.participants.push(default_participant(role_id)); } } for participant in &mut state.participants { @@ -1694,13 +1267,6 @@ fn patch_missing_participants(state: &mut EpiphanyHeartbeatStateEntry) { } } -fn is_ghostlight_scene_state(state: &EpiphanyHeartbeatStateEntry) -> bool { - state - .protocol - .as_ref() - .is_some_and(|protocol| protocol.domain == "ghostlight") -} - fn participant_index_by_role(state: &EpiphanyHeartbeatStateEntry, role_id: &str) -> Result { state .participants @@ -1761,15 +1327,6 @@ pub(super) fn participant_kind(participant: &HeartbeatParticipant) -> &str { } } -fn agent_id_for_work_role(state: &EpiphanyHeartbeatStateEntry, role_id: &str) -> String { - state - .participants - .iter() - .find(|participant| participant.role_id == role_id) - .map(|participant| participant.agent_id.clone()) - .unwrap_or_else(|| agent_id_for_role(role_id).to_string()) -} - fn trim_history(state: &mut EpiphanyHeartbeatStateEntry) { let len = state.history.len(); if len > 128 { @@ -1805,91 +1362,11 @@ pub(super) fn round6(value: f64) -> f64 { (value * 1_000_000.0).round() / 1_000_000.0 } -pub(super) fn round3(value: f64) -> f64 { - (value * 1_000.0).round() / 1_000.0 -} - #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; - #[test] - fn native_heartbeat_store_ticks_and_completes_without_json_state() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("heartbeats.msgpack"); - let artifact_dir = temp.path().join("artifacts"); - initialize_heartbeat_store(&store_path, 1.0)?; - - let work = tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 1.0, - coordinator_action: Some("continueImplementation".to_string()), - target_role: None, - urgency: 0.95, - schedule_id: "native-work".to_string(), - source_scene_ref: "test/native".to_string(), - defer_completion: true, - resident_self_store: None, - }, - )?; - assert_eq!(work["event"]["selectedRole"], "implementation"); - assert_eq!(work["event"]["turnStatus"], "running"); - let implementation = work["schedule"]["participants"] - .as_array() - .and_then(|participants| { - participants - .iter() - .find(|participant| participant["role_id"] == "implementation") - }) - .expect("implementation participant should be projected"); - assert_eq!(implementation["initiative_frozen"], true); - assert_eq!( - implementation["pending_turn"]["initiativeFrozen"], - serde_json::json!(true) - ); - assert!(artifact_dir.join("native-work.initiative.json").exists()); - - let blocked = tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 1.0, - coordinator_action: Some("continueImplementation".to_string()), - target_role: None, - urgency: 0.95, - schedule_id: "native-work-repeat".to_string(), - source_scene_ref: "test/native".to_string(), - defer_completion: false, - resident_self_store: None, - }, - ) - .unwrap_err(); - assert!( - blocked - .to_string() - .contains("already has running heartbeat turn") - ); - - let completed = complete_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatCompleteOptions { - role: "implementation".to_string(), - action_id: Some("heartbeat.implementation.work".to_string()), - }, - )?; - assert_eq!(completed["event"]["turnStatus"], "completed"); - assert_eq!( - completed["event"]["cooldownStartedAfterCompletion"], - serde_json::json!(true) - ); - assert!(artifact_dir.join("native-work.completion.json").exists()); - Ok(()) - } - #[test] fn resident_pressure_selects_self_before_idle_lane_initiative() -> Result<()> { let temp = tempfile::tempdir()?; @@ -1947,212 +1424,75 @@ mod tests { Ok(()) } - #[test] - fn high_heat_cannot_requeue_running_participant() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("hot-heartbeats.msgpack"); - let artifact_dir = temp.path().join("artifacts"); - initialize_heartbeat_store(&store_path, 1.0)?; - update_heartbeat_heat_store( - &store_path, - HeartbeatHeatUpdateOptions { - scope: "role".to_string(), - selector: "implementation".to_string(), - multiplier: 25.0, - id: Some("implementation-overheat".to_string()), - label: None, - reason: Some("High heat must still respect active thought freeze.".to_string()), - expires_after_scene_clock: None, - clear: false, - }, - )?; - - let work = tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 4.0, - coordinator_action: Some("continueImplementation".to_string()), - target_role: None, - urgency: 1.0, - schedule_id: "hot-work".to_string(), - source_scene_ref: "test/high-heat".to_string(), - defer_completion: true, - resident_self_store: None, - }, - )?; - assert_eq!( - work["schedule"]["action_catalog"][0]["initiative_heat_multiplier"], - serde_json::json!(25.0) - ); - let implementation = work["schedule"]["participants"] - .as_array() - .and_then(|participants| { - participants - .iter() - .find(|participant| participant["role_id"] == "implementation") - }) - .expect("implementation participant should be projected"); - assert_eq!(implementation["initiative_frozen"], true); - assert_eq!( - implementation["pending_turn"]["initiativeFrozen"], - serde_json::json!(true) - ); - - let blocked = tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 4.0, - coordinator_action: Some("continueImplementation".to_string()), - target_role: None, - urgency: 1.0, - schedule_id: "hot-work-repeat".to_string(), - source_scene_ref: "test/high-heat".to_string(), - defer_completion: true, - resident_self_store: None, - }, - ) - .unwrap_err(); - assert!( - blocked - .to_string() - .contains("already has running heartbeat turn") - ); - Ok(()) - } - #[test] fn stale_heartbeat_repair_receipt_clears_running_turn() -> Result<()> { let temp = tempfile::tempdir()?; - let store_path = temp.path().join("stale-heartbeats.msgpack"); + let heartbeat_store = temp.path().join("stale-heartbeats.msgpack"); + let resident_store = temp.path().join("resident.cc"); let artifact_dir = temp.path().join("artifacts"); - initialize_heartbeat_store(&store_path, 1.0)?; - tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 1.0, - coordinator_action: Some("continueImplementation".to_string()), - target_role: None, - urgency: 0.95, - schedule_id: "stale-work".to_string(), - source_scene_ref: "test/stale".to_string(), - defer_completion: true, - resident_self_store: None, + initialize_heartbeat_store(&heartbeat_store, 1.0)?; + crate::enqueue_resident_self_pressure( + &resident_store, + &crate::ResidentSelfPressure { + schema_version: crate::RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), + pressure_id: "stale-work".into(), + kind: "operator-objective".into(), + provenance_ref: "test://stale".into(), + objective: "Exercise stale grant recovery.".into(), + created_at_millis: 1, + status: "pending".into(), + consumed_by_grant_id: None, + private_state_exposed: false, }, )?; - let mut state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - let implementation = state + pulse_resident_self_heartbeat( + &heartbeat_store, + &resident_store, + &artifact_dir, + false, + "stale-work", + "test://stale", + )?; + + let mut state = load_heartbeat_state_entry(&heartbeat_store)?.expect("heartbeat state"); + let coordinator = state .participants .iter_mut() - .find(|participant| participant.role_id == "implementation") - .expect("implementation participant exists"); - implementation + .find(|participant| participant.role_id == "coordinator") + .expect("coordinator participant exists"); + coordinator .pending_turn .as_mut() - .expect("running implementation turn exists") + .expect("running coordinator turn exists") .started_at = "2026-06-17T00:00:00+00:00".to_string(); - write_heartbeat_state_entry(&store_path, &state)?; + write_heartbeat_state_entry(&heartbeat_store, &state)?; let repaired = recover_stale_heartbeat_store( - &store_path, + &heartbeat_store, &artifact_dir, HeartbeatStaleTurnRepairOptions { max_age_seconds: 60, now_utc: Some("2026-06-17T00:05:00+00:00".to_string()), - reason: - "Unit test simulates a stale worker lane that needs operator-safe recovery." - .to_string(), + reason: "Test stale Resident Self grant recovery.".to_string(), }, )?; assert_eq!(repaired["repaired"], serde_json::json!(1)); - let receipt = load_latest_heartbeat_stale_turn_repair_receipt(&store_path)? + let receipt = load_latest_heartbeat_stale_turn_repair_receipt(&heartbeat_store)? .expect("stale-turn repair receipt exists"); - assert_eq!(receipt.role_id, "implementation"); - assert_eq!(receipt.action_id, "heartbeat.implementation.work"); + assert_eq!(receipt.role_id, "coordinator"); + assert_eq!(receipt.action_id, "heartbeat.coordinator.work"); assert_eq!(receipt.stale_age_seconds, 300); assert!(!receipt.private_state_exposed); - let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); - let implementation = state - .participants - .iter() - .find(|participant| participant.role_id == "implementation") - .expect("implementation participant exists"); - assert!(implementation.pending_turn.is_none()); - - let next = tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 1.0, - coordinator_action: Some("continueImplementation".to_string()), - target_role: None, - urgency: 0.95, - schedule_id: "after-stale-repair".to_string(), - source_scene_ref: "test/stale".to_string(), - defer_completion: true, - resident_self_store: None, - }, - )?; - assert_eq!(next["event"]["selectedRole"], "implementation"); - assert_eq!(next["event"]["turnStatus"], "running"); - Ok(()) - } - - #[test] - fn ghostlight_scene_heartbeat_selects_character_turns() -> Result<()> { - let temp = tempfile::tempdir()?; - let store_path = temp.path().join("ghostlight-heartbeats.msgpack"); - let artifact_dir = temp.path().join("artifacts"); - initialize_ghostlight_scene_heartbeat_store( - &store_path, - 1.0, - "pallas-training-loop-v0", - vec![ - GhostlightSceneParticipantSeed { - agent_id: "nara-7".to_string(), - display_name: "Nara-7".to_string(), - initiative_speed: 1.1, - reaction_bias: 0.6, - interrupt_threshold: 0.35, - constraints: vec!["Receives only projected local context.".to_string()], - }, - GhostlightSceneParticipantSeed { - agent_id: "orrin-dax".to_string(), - display_name: "Orrin Dax".to_string(), - initiative_speed: 0.9, - reaction_bias: 0.55, - interrupt_threshold: 0.4, - constraints: vec!["Acts from current scene pressure.".to_string()], - }, - ], - )?; - - let tick = tick_heartbeat_store( - &store_path, - &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 1.0, - coordinator_action: None, - target_role: None, - urgency: 0.75, - schedule_id: "pallas.turn-001".to_string(), - source_scene_ref: "ghostlight/pallas-training-loop-v0".to_string(), - defer_completion: true, - resident_self_store: None, - }, - )?; - - assert_eq!(tick["event"]["arena"], "scene"); - assert_eq!(tick["event"]["participantKind"], "character"); - assert_eq!(tick["event"]["actionType"], "scene_turn"); - assert_eq!( - tick["schedule"]["action_catalog"][0]["action_type"], - "scene_turn" + let state = load_heartbeat_state_entry(&heartbeat_store)?.expect("heartbeat state"); + assert!( + state + .participants + .iter() + .find(|participant| participant.role_id == "coordinator") + .and_then(|participant| participant.pending_turn.as_ref()) + .is_none() ); - assert_eq!(tick["schedule"]["participants"][0]["arena"], "scene"); Ok(()) } @@ -2184,29 +1524,21 @@ mod tests { )?; assert_eq!(queued["queued"], true); - let tick = tick_heartbeat_store( + let pulse = pulse_persona_heartbeat( &store_path, &artifact_dir, - HeartbeatTickOptions { - target_heartbeat_rate: 1.0, - coordinator_action: None, - target_role: None, - urgency: 0.0, - schedule_id: "Persona-mentioned".to_string(), - source_scene_ref: "test/Persona-mentioned".to_string(), - defer_completion: true, - resident_self_store: None, - }, + "Persona-mentioned", + "test/Persona-mentioned", + false, )?; - assert_eq!(tick["event"]["selectedRole"], "Persona"); - assert_eq!(tick["event"]["actionType"], "persona_turn"); + assert_eq!(pulse["status"], "reserved"); assert_eq!( - tick["schedule"]["action_catalog"][0]["pending_mentions"][0]["id"], + pulse["schedule"]["action_catalog"][0]["pending_mentions"][0]["id"], "mention-Persona-test" ); assert_eq!( - tick["schedule"]["pending_mentions"] + pulse["schedule"]["pending_mentions"] .as_array() .map(Vec::len), Some(1) @@ -2287,19 +1619,12 @@ mod tests { model_provider_disclosure_allowed: true, }, )?; - tick_heartbeat_store( + pulse_persona_heartbeat( &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, - resident_self_store: None, - }, + "Persona-failure", + "test/Persona-failure", + false, )?; let state = load_heartbeat_state_entry(&store_path)?.expect("heartbeat state"); let request_id = state.persona_turn_requests[0].request_id.clone(); diff --git a/epiphany-core/src/heartbeat_state/heartbeat_documents.rs b/epiphany-core/src/heartbeat_state/heartbeat_documents.rs index 1d0f39fc..f9a238a7 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_documents.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_documents.rs @@ -5,9 +5,9 @@ use serde_json::Value; pub const HEARTBEAT_STATE_TYPE: &str = "epiphany.agent_heartbeat"; pub const HEARTBEAT_STATE_KEY: &str = "default"; -pub const HEARTBEAT_STATE_SCHEMA_VERSION: &str = "epiphany.agent_heartbeat.v0"; +pub const HEARTBEAT_STATE_SCHEMA_VERSION: &str = "epiphany.agent_heartbeat.v1"; pub const HEARTBEAT_STATUS_SCHEMA_VERSION: &str = "epiphany.agent_heartbeat_status.v0"; -pub const INITIATIVE_SCHEMA_VERSION: &str = "ghostlight.initiative_schedule.v0"; +pub const INITIATIVE_SCHEMA_VERSION: &str = "epiphany.heartbeat_schedule.v0"; pub const HEARTBEAT_STALE_TURN_REPAIR_TYPE: &str = "epiphany.heartbeat.stale_turn_repair"; pub const HEARTBEAT_STALE_TURN_REPAIR_SCHEMA_VERSION: &str = "epiphany.heartbeat.stale_turn_repair.v0"; @@ -52,12 +52,6 @@ pub struct EpiphanyHeartbeatStateEntry { pub participants: Vec, #[cultcache(key = 6)] pub history: Vec, - #[cultcache(key = 16, default)] - pub initiative_heat: HeartbeatInitiativeHeatPolicy, - #[cultcache(key = 17, default)] - pub protocol: Option, - #[cultcache(key = 18, default)] - pub adaptive_pacing: Option, #[cultcache(key = 19, default)] pub pending_mentions: Vec, #[cultcache(key = 20, default)] @@ -181,73 +175,6 @@ pub struct HeartbeatPacingPolicy { pub minimum_effective_rate: f64, } -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct HeartbeatProtocol { - pub domain: String, - #[serde(default)] - pub scene_id: Option, - pub arena: String, - pub contract: String, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct HeartbeatAdaptivePacing { - pub schema_version: String, - pub contract: String, - pub pressure: f64, - pub effective_heartbeat_rate: f64, - pub target_concurrency: usize, - pub running_turns: usize, - pub active_participants: usize, - pub signals: HeartbeatAdaptivePacingSignals, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct HeartbeatAdaptivePacingSignals { - pub external_urgency: f64, - pub pending_pressure: f64, - pub contract: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct HeartbeatInitiativeHeatPolicy { - #[serde(default = "default_heat_schema_version")] - pub schema_version: String, - #[serde(default = "default_heat_global_multiplier")] - pub global_multiplier: f64, - #[serde(default)] - pub multipliers: Vec, -} - -impl Default for HeartbeatInitiativeHeatPolicy { - fn default() -> Self { - Self { - schema_version: default_heat_schema_version(), - global_multiplier: default_heat_global_multiplier(), - multipliers: Vec::new(), - } - } -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct HeartbeatInitiativeMultiplier { - pub id: String, - #[serde(default)] - pub label: String, - #[serde(default = "default_heat_scope")] - pub scope: String, - #[serde(default)] - pub selector: String, - #[serde(default = "default_heat_global_multiplier")] - pub multiplier: f64, - #[serde(default)] - pub reason: String, - #[serde(default)] - pub updated_at: Option, - #[serde(default)] - pub expires_at_scene_clock: Option, -} - #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct HeartbeatParticipant { pub agent_id: String, @@ -268,32 +195,6 @@ pub struct HeartbeatParticipant { pub last_woke_at: Option, pub last_finished_at: Option, pub pending_turn: Option, - #[serde(default)] - pub scene_id: Option, - #[serde(default)] - pub groups: Vec, - #[serde(default = "default_heat_global_multiplier")] - pub initiative_heat_multiplier: f64, - #[serde(default)] - pub initiative_heat: Option, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct HeartbeatInitiativeHeatProjection { - pub schema_version: String, - pub global_multiplier: f64, - pub effective_multiplier: f64, - pub basis: Vec, - pub contract: String, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct HeartbeatInitiativeHeatBasis { - pub id: String, - pub scope: String, - pub selector: String, - pub multiplier: f64, - pub reason: String, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -324,16 +225,6 @@ pub struct HeartbeatPendingTurn { pub completed_scene_clock: Option, #[serde(rename = "nextReadyAt", default)] pub next_ready_at: Option, - #[serde( - rename = "initiativeHeatMultiplier", - default = "default_heat_global_multiplier" - )] - pub initiative_heat_multiplier: f64, - #[serde( - rename = "effectiveCooldownMultiplier", - default = "default_heat_global_multiplier" - )] - pub effective_cooldown_multiplier: f64, #[serde(rename = "initiativeFrozen", default)] pub initiative_frozen: bool, #[serde(rename = "initiativeFreezeReason", default)] @@ -528,43 +419,11 @@ pub struct HeartbeatHistoryEvent { } #[derive(Clone, Debug, PartialEq)] -pub struct HeartbeatTickOptions { - pub target_heartbeat_rate: f64, - pub coordinator_action: Option, - pub target_role: Option, - pub urgency: f64, - pub schedule_id: String, - pub source_scene_ref: String, - pub defer_completion: bool, - pub resident_self_store: Option, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct HeartbeatPumpOptions { - pub base_heartbeat_rate: f64, - pub min_heartbeat_rate: f64, - pub max_heartbeat_rate: f64, - pub min_concurrency: usize, - pub max_concurrency: usize, - pub max_ticks: usize, - pub external_urgency: f64, - pub coordinator_action: Option, - pub target_role: Option, - pub schedule_id: String, - pub source_scene_ref: String, - pub resident_self_store: Option, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct HeartbeatHeatUpdateOptions { - pub scope: String, - pub selector: String, - pub multiplier: f64, - pub id: Option, - pub label: Option, - pub reason: Option, - pub expires_after_scene_clock: Option, - pub clear: bool, +pub(super) struct HeartbeatTickOptions { + pub(super) target_heartbeat_rate: f64, + pub(super) schedule_id: String, + pub(super) source_scene_ref: String, + pub(super) resident_self_store: Option, } #[derive(Clone, Debug, PartialEq)] @@ -586,37 +445,9 @@ pub struct HeartbeatQueueMentionOptions { pub model_provider_disclosure_allowed: bool, } -#[derive(Clone, Debug, PartialEq)] -pub struct HeartbeatCompleteOptions { - pub role: String, - pub action_id: Option, -} - #[derive(Clone, Debug, PartialEq)] pub struct HeartbeatStaleTurnRepairOptions { pub max_age_seconds: i64, pub now_utc: Option, pub reason: String, } - -#[derive(Clone, Debug, PartialEq)] -pub struct GhostlightSceneParticipantSeed { - pub agent_id: String, - pub display_name: String, - pub initiative_speed: f64, - pub reaction_bias: f64, - pub interrupt_threshold: f64, - pub constraints: Vec, -} - -fn default_heat_schema_version() -> String { - "epiphany.heartbeat_initiative_heat.v0".to_string() -} - -fn default_heat_global_multiplier() -> f64 { - 1.0 -} - -fn default_heat_scope() -> String { - "agent".to_string() -} diff --git a/epiphany-core/src/heartbeat_state/heartbeat_pacing.rs b/epiphany-core/src/heartbeat_state/heartbeat_pacing.rs deleted file mode 100644 index fd86550f..00000000 --- a/epiphany-core/src/heartbeat_state/heartbeat_pacing.rs +++ /dev/null @@ -1,239 +0,0 @@ -use super::EpiphanyHeartbeatStateEntry; -use super::HeartbeatAdaptivePacingSignals; -use super::HeartbeatInitiativeHeatBasis; -use super::HeartbeatInitiativeHeatProjection; -use super::HeartbeatInitiativeMultiplier; -use super::HeartbeatParticipant; -use super::HeartbeatPumpOptions; -use super::round3; -use super::round6; - -#[derive(Clone, Debug)] -pub(super) struct AdaptiveSwarmPacing { - pub(super) pressure: f64, - pub(super) effective_heartbeat_rate: f64, - pub(super) target_concurrency: usize, - pub(super) running_turns: usize, - pub(super) active_participants: usize, - pub(super) signals: HeartbeatAdaptivePacingSignals, -} - -pub(super) fn adaptive_swarm_pacing( - state: &EpiphanyHeartbeatStateEntry, - options: &HeartbeatPumpOptions, -) -> AdaptiveSwarmPacing { - let active_participants = state - .participants - .iter() - .filter(|participant| participant.status == "active") - .count(); - let running_turns = running_turn_count(state); - let external_urgency = options.external_urgency.clamp(0.0, 1.0); - let pending_pressure = if active_participants == 0 { - 0.0 - } else { - (running_turns as f64 / active_participants as f64).clamp(0.0, 1.0) - }; - let pressure = [external_urgency, pending_pressure * 0.65] - .into_iter() - .fold(0.0_f64, f64::max) - .clamp(0.0, 1.0); - - let base_rate = options - .base_heartbeat_rate - .max(state.pacing_policy.minimum_effective_rate) - .max(0.001); - let min_rate = options.min_heartbeat_rate.max(0.001).min(base_rate); - let max_rate = options.max_heartbeat_rate.max(base_rate).max(min_rate); - let pressure_curve = pressure * pressure; - let effective_heartbeat_rate = round6(min_rate + (max_rate - min_rate) * pressure_curve); - - let max_concurrency = options - .max_concurrency - .max(1) - .min(active_participants.max(1)); - let relaxed_floor = if pressure < 0.18 { - 0 - } else { - options.min_concurrency.min(max_concurrency) - }; - let target_concurrency = if pressure < 0.18 { - relaxed_floor - } else { - let span = max_concurrency.saturating_sub(relaxed_floor); - (relaxed_floor + (span as f64 * pressure).ceil() as usize).min(max_concurrency) - }; - AdaptiveSwarmPacing { - pressure: round3(pressure), - effective_heartbeat_rate, - target_concurrency, - running_turns, - active_participants, - signals: HeartbeatAdaptivePacingSignals { - external_urgency: round3(external_urgency), - pending_pressure: round3(pending_pressure), - contract: "Explicit external urgency and running-turn pressure determine scheduler tempo and concurrency.".to_string(), - }, - } -} - -pub(super) fn running_turn_count(state: &EpiphanyHeartbeatStateEntry) -> usize { - state - .participants - .iter() - .filter(|participant| { - participant - .pending_turn - .as_ref() - .is_some_and(|turn| turn.status == "running") - }) - .count() -} - -pub(super) fn effective_cooldown_multiplier(participant: &HeartbeatParticipant) -> f64 { - round3(1.0 / initiative_heat_multiplier(participant)).clamp(0.05, 8.0) -} - -pub(super) fn initiative_heat_multiplier(participant: &HeartbeatParticipant) -> f64 { - nonzero_multiplier(participant.initiative_heat_multiplier).clamp(0.05, 25.0) -} - -fn nonzero_multiplier(value: f64) -> f64 { - if value.is_finite() && value > 0.0 { - value - } else { - 1.0 - } -} - -pub(super) fn apply_initiative_heat_policy(state: &mut EpiphanyHeartbeatStateEntry) { - let global = state.initiative_heat.global_multiplier.clamp(0.05, 25.0); - let active_multipliers = state - .initiative_heat - .multipliers - .iter() - .filter(|multiplier| { - multiplier - .expires_at_scene_clock - .is_none_or(|expires| expires > state.scene_clock) - }) - .cloned() - .collect::>(); - for participant in &mut state.participants { - let mut heat = global; - let mut basis = Vec::::new(); - for multiplier in &active_multipliers { - if multiplier_matches_participant(multiplier, participant) { - let value = multiplier.multiplier.clamp(0.05, 25.0); - heat *= value; - basis.push(HeartbeatInitiativeHeatBasis { - id: multiplier.id.clone(), - scope: multiplier.scope.clone(), - selector: multiplier.selector.clone(), - multiplier: value, - reason: multiplier.reason.clone(), - }); - } - } - let heat = round3(heat.clamp(0.05, 25.0)); - participant.initiative_heat_multiplier = heat; - participant.initiative_heat = Some(HeartbeatInitiativeHeatProjection { - schema_version: "epiphany.heartbeat_initiative_heat_projection.v0".to_string(), - global_multiplier: global, - effective_multiplier: heat, - basis, - contract: "Initiative heat accelerates turn recovery. Proximity or agency pressure may raise heat, but the typed heat policy remains the authority.".to_string(), - }); - } -} - -fn multiplier_matches_participant( - multiplier: &HeartbeatInitiativeMultiplier, - participant: &HeartbeatParticipant, -) -> bool { - let selector = multiplier.selector.trim(); - match multiplier.scope.as_str() { - "all" => true, - "agent" | "agent_id" => eq_key(&participant.agent_id, selector), - "role" | "role_id" => eq_key(&participant.role_id, selector), - "arena" => eq_key(participant.arena.as_str(), selector), - "participant_kind" | "kind" => eq_key(participant.participant_kind.as_str(), selector), - "group" | "constraint" => { - participant - .constraints - .iter() - .any(|constraint| eq_key(constraint, selector)) - || participant - .groups - .iter() - .any(|group| eq_key(group, selector)) - } - _ => false, - } -} - -fn eq_key(left: &str, right: &str) -> bool { - left.trim().eq_ignore_ascii_case(right.trim()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::heartbeat_state::default_heartbeat_state; - use pretty_assertions::assert_eq; - - #[test] - fn running_turn_count_reads_only_running_pending_turns() { - let mut state = default_heartbeat_state(1.0); - state.participants[0].pending_turn = Some(crate::heartbeat_state::HeartbeatPendingTurn { - status: "running".to_string(), - ..Default::default() - }); - state.participants[1].pending_turn = Some(crate::heartbeat_state::HeartbeatPendingTurn { - status: "completed".to_string(), - ..Default::default() - }); - - assert_eq!(running_turn_count(&state), 1); - } - - #[test] - fn initiative_heat_multiplies_agent_and_group_recovery_speed() { - let mut state = default_heartbeat_state(1.0); - state.initiative_heat.global_multiplier = 2.0; - state.initiative_heat.multipliers = vec![ - HeartbeatInitiativeMultiplier { - id: "hands".to_string(), - scope: "role".to_string(), - selector: "implementation".to_string(), - multiplier: 3.0, - ..Default::default() - }, - HeartbeatInitiativeMultiplier { - id: "all-maintenance".to_string(), - scope: "arena".to_string(), - selector: "maintenance".to_string(), - multiplier: 1.5, - ..Default::default() - }, - ]; - - apply_initiative_heat_policy(&mut state); - let implementation = state - .participants - .iter() - .find(|participant| participant.role_id == "implementation") - .expect("implementation participant"); - let research = state - .participants - .iter() - .find(|participant| participant.role_id == "research") - .expect("research participant"); - - assert_eq!(initiative_heat_multiplier(implementation), 9.0); - assert_eq!(initiative_heat_multiplier(research), 3.0); - assert!( - effective_cooldown_multiplier(implementation) < effective_cooldown_multiplier(research) - ); - } -} diff --git a/epiphany-core/src/heartbeat_state/heartbeat_projection.rs b/epiphany-core/src/heartbeat_state/heartbeat_projection.rs index 94b43f2e..a158ea36 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_projection.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_projection.rs @@ -5,8 +5,6 @@ use super::HeartbeatHistoryEvent; use super::HeartbeatParticipant; use super::HeartbeatPendingTurn; use super::HeartbeatSelectionPolicy; -use super::effective_cooldown_multiplier; -use super::initiative_heat_multiplier; use super::load_heartbeat_state_entry; use super::participant_arena; use super::participant_kind; @@ -39,7 +37,7 @@ pub fn heartbeat_status_projection( "latestEvent": null, "history": [], "latestArtifacts": latest_json_artifacts(artifact_dir, artifact_limit), - "availableActions": ["init", "tick", "pump", "complete", "status"], + "availableActions": ["init", "repair-stale", "retain-artifacts", "status", "serve"], })); }; let scheduler_status = if state.participants.is_empty() { @@ -77,28 +75,11 @@ pub fn heartbeat_status_projection( "artifactDir": artifact_dir.as_ref(), "targetHeartbeatRate": state.target_heartbeat_rate, "sceneClock": state.scene_clock, - "initiativeHeat": { - "schemaVersion": state.initiative_heat.schema_version, - "globalMultiplier": state.initiative_heat.global_multiplier, - "multipliers": state.initiative_heat.multipliers.iter().map(|multiplier| { - serde_json::json!({ - "id": multiplier.id, - "label": multiplier.label, - "scope": multiplier.scope, - "selector": multiplier.selector, - "multiplier": multiplier.multiplier, - "reason": multiplier.reason, - "updatedAt": multiplier.updated_at, - "expiresAtSceneClock": multiplier.expires_at_scene_clock, - }) - }).collect::>(), - }, "participants": state.participants.iter().map(participant_status_json).collect::>(), "latestEvent": history.last().cloned(), "history": history, "latestArtifacts": latest_json_artifacts(artifact_dir, artifact_limit), - "adaptivePacing": state.adaptive_pacing.as_ref(), - "availableActions": ["init", "tick", "pump", "heat", "complete", "status"], + "availableActions": ["init", "repair-stale", "retain-artifacts", "status", "serve"], })) } @@ -196,9 +177,6 @@ fn participant_status_json(participant: &HeartbeatParticipant) -> Value { "arena": participant_arena(participant), "participantKind": participant_kind(participant), "initiativeSpeed": participant.initiative_speed, - "initiativeHeatMultiplier": initiative_heat_multiplier(participant), - "initiativeHeat": participant.initiative_heat.as_ref(), - "effectiveCooldownMultiplier": effective_cooldown_multiplier(participant), "initiativeFrozen": participant .pending_turn .as_ref() @@ -227,8 +205,6 @@ pub(super) fn schedule_participant_json(participant: &HeartbeatParticipant) -> V "arena": participant_arena(participant), "participant_kind": participant_kind(participant), "initiative_speed": participant.initiative_speed, - "initiative_heat_multiplier": initiative_heat_multiplier(participant), - "effective_cooldown_multiplier": effective_cooldown_multiplier(participant), "initiative_frozen": participant .pending_turn .as_ref() @@ -267,8 +243,6 @@ pub(super) fn pending_turn_json(turn: &HeartbeatPendingTurn) -> Value { "startedAt": turn.started_at, "startedSceneClock": turn.started_scene_clock, "baseRecovery": turn.base_recovery, - "initiativeHeatMultiplier": turn.initiative_heat_multiplier, - "effectiveCooldownMultiplier": turn.effective_cooldown_multiplier, "initiativeFrozen": turn.initiative_frozen, "initiativeFreezeReason": turn.initiative_freeze_reason.as_ref(), "recovery": turn.recovery, diff --git a/epiphany-core/src/heartbeat_state/heartbeat_roles.rs b/epiphany-core/src/heartbeat_state/heartbeat_roles.rs index b673fc73..dde2b26d 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_roles.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_roles.rs @@ -1,28 +1,15 @@ use super::EpiphanyHeartbeatStateEntry; -use super::GhostlightSceneParticipantSeed; use super::HEARTBEAT_ARENA_MAINTENANCE; -use super::HEARTBEAT_ARENA_SCENE; use super::HEARTBEAT_STATE_SCHEMA_VERSION; use super::HeartbeatPacingPolicy; use super::HeartbeatParticipant; -use super::HeartbeatProtocol; use super::HeartbeatSelectionPolicy; use super::PARTICIPANT_KIND_AGENT; -use super::PARTICIPANT_KIND_CHARACTER; use super::write_heartbeat_state_entry; use anyhow::Result; -use anyhow::anyhow; use std::path::Path; -pub(super) const ROLE_ORDER: &[&str] = &[ - "coordinator", - "Persona", - "imagination", - "research", - "modeling", - "implementation", - "verification", -]; +pub(super) const ROLE_ORDER: &[&str] = &["coordinator", "Persona"]; pub fn default_heartbeat_state(target_heartbeat_rate: f64) -> EpiphanyHeartbeatStateEntry { EpiphanyHeartbeatStateEntry { @@ -52,9 +39,6 @@ pub fn default_heartbeat_state(target_heartbeat_rate: f64) -> EpiphanyHeartbeatS .map(|role_id| default_participant(role_id)) .collect(), history: Vec::new(), - initiative_heat: Default::default(), - protocol: None, - adaptive_pacing: None, pending_mentions: Vec::new(), persona_turn_requests: Vec::new(), blocked_persona_pressures: Vec::new(), @@ -70,42 +54,6 @@ pub fn initialize_heartbeat_store( write_heartbeat_state_entry(store_path, &default_heartbeat_state(target_heartbeat_rate)) } -pub fn ghostlight_scene_heartbeat_state( - target_heartbeat_rate: f64, - scene_id: impl Into, - participants: Vec, -) -> Result { - if participants.is_empty() { - return Err(anyhow!( - "Ghostlight scene heartbeat requires at least one participant" - )); - } - let scene_id = scene_id.into(); - let mut state = default_heartbeat_state(target_heartbeat_rate); - state.participants = participants - .into_iter() - .map(|seed| ghostlight_scene_participant(&scene_id, seed)) - .collect(); - state.protocol = Some(HeartbeatProtocol { - domain: "ghostlight".to_string(), - scene_id: Some(scene_id), - arena: HEARTBEAT_ARENA_SCENE.to_string(), - contract: "Characters and maintenance organs use one initiative timing law; scene participants receive only projected local context.".to_string(), - }); - super::validate_heartbeat_state(&state)?; - Ok(state) -} - -pub fn initialize_ghostlight_scene_heartbeat_store( - store_path: impl AsRef, - target_heartbeat_rate: f64, - scene_id: impl Into, - participants: Vec, -) -> Result { - let state = ghostlight_scene_heartbeat_state(target_heartbeat_rate, scene_id, participants)?; - write_heartbeat_state_entry(store_path, &state) -} - pub(super) fn default_participant(role_id: &str) -> HeartbeatParticipant { HeartbeatParticipant { agent_id: agent_id_for_role(role_id).to_string(), @@ -127,67 +75,13 @@ pub(super) fn default_participant(role_id: &str) -> HeartbeatParticipant { last_woke_at: None, last_finished_at: None, pending_turn: None, - scene_id: None, - groups: Vec::new(), - initiative_heat_multiplier: 1.0, - initiative_heat: None, } } -fn ghostlight_scene_participant( - scene_id: &str, - seed: GhostlightSceneParticipantSeed, -) -> HeartbeatParticipant { - let role_id = ghostlight_role_id(seed.agent_id.as_str()); - HeartbeatParticipant { - agent_id: seed.agent_id, - role_id, - display_name: seed.display_name, - arena: HEARTBEAT_ARENA_SCENE.to_string(), - participant_kind: PARTICIPANT_KIND_CHARACTER.to_string(), - initiative_speed: seed.initiative_speed, - next_ready_at: 0.0, - reaction_bias: seed.reaction_bias, - interrupt_threshold: seed.interrupt_threshold, - current_load: 0.0, - status: "active".to_string(), - constraints: seed.constraints, - last_action_id: None, - last_woke_at: None, - last_finished_at: None, - pending_turn: None, - scene_id: Some(scene_id.to_string()), - groups: Vec::new(), - initiative_heat_multiplier: 1.0, - initiative_heat: None, - } -} - -fn ghostlight_role_id(agent_id: &str) -> String { - let sanitized = agent_id - .chars() - .map(|character| { - if character.is_ascii_alphanumeric() { - character.to_ascii_lowercase() - } else { - '-' - } - }) - .collect::() - .trim_matches('-') - .to_string(); - format!("ghostlight.character.{sanitized}") -} - pub(super) fn agent_id_for_role(role_id: &str) -> &'static str { match role_id { "coordinator" => "epiphany.self", "Persona" => "epiphany.Persona", - "imagination" => "epiphany.imagination", - "research" => "epiphany.eyes", - "modeling" => "epiphany.modeling", - "implementation" => "epiphany.hands", - "verification" => "epiphany.soul", _ => "epiphany.unknown", } } @@ -196,11 +90,6 @@ pub(super) fn display_name_for_role(role_id: &str) -> &'static str { match role_id { "coordinator" => "Self", "Persona" => "Persona", - "imagination" => "Imagination", - "research" => "Eyes", - "modeling" => "Modeling", - "implementation" => "Hands", - "verification" => "Soul", _ => "Unknown", } } @@ -209,11 +98,6 @@ fn initiative_speed_for_role(role_id: &str) -> f64 { match role_id { "coordinator" => 1.28, "Persona" => 1.12, - "imagination" => 0.82, - "research" => 0.78, - "modeling" => 0.92, - "implementation" => 0.74, - "verification" => 0.88, _ => 1.0, } } @@ -222,11 +106,6 @@ fn reaction_bias_for_role(role_id: &str) -> f64 { match role_id { "coordinator" => 0.88, "Persona" => 0.84, - "imagination" => 0.54, - "research" => 0.62, - "modeling" => 0.74, - "implementation" => 0.58, - "verification" => 0.82, _ => 0.5, } } @@ -235,11 +114,6 @@ fn interrupt_threshold_for_role(role_id: &str) -> f64 { match role_id { "coordinator" => 0.42, "Persona" => 0.52, - "imagination" => 0.64, - "research" => 0.58, - "modeling" => 0.5, - "implementation" => 0.5, - "verification" => 0.48, _ => 0.5, } } @@ -252,78 +126,7 @@ fn participant_constraints(role_id: &str) -> Vec<&'static str> { "Persona" => { "Publicly translates agent thought into #aquarium only; must not moderate or speak outside the room." } - "imagination" => "Synthesizes futures; must not adopt objectives.", - "research" => "Scouts known work; must not turn research into procrastination.", - "modeling" => { - "Grows source-grounded maps and checkpoints; must not edit implementation code." - } - "implementation" => { - "Touches source only with accepted guidance and verifier-readable evidence." - } - "verification" => "Falsifies promises; must not bless theater.", _ => "Unknown role.", }; vec![role_specific] } - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn default_state_defines_the_fixed_lane_catalog() { - let state = default_heartbeat_state(1.5); - - assert_eq!(state.target_heartbeat_rate, 1.5); - assert_eq!(state.pacing_policy.work_base_recovery, 6.0); - assert_eq!(state.pacing_policy.idle_base_recovery, 2.0); - assert_eq!( - state - .participants - .iter() - .map(|participant| participant.role_id.as_str()) - .collect::>(), - ROLE_ORDER - ); - assert_eq!( - state - .participants - .iter() - .find(|participant| participant.role_id == "Persona") - .map(|participant| participant.agent_id.as_str()), - Some("epiphany.Persona") - ); - } - - #[test] - fn ghostlight_scene_state_replaces_maintenance_lanes_with_scene_characters() -> Result<()> { - let state = ghostlight_scene_heartbeat_state( - 0.5, - "room", - vec![GhostlightSceneParticipantSeed { - agent_id: "Ariadne Prime".to_string(), - display_name: "Ariadne".to_string(), - initiative_speed: 1.2, - reaction_bias: 0.8, - interrupt_threshold: 0.4, - constraints: vec!["Speak only in the room.".to_string()], - }], - )?; - - assert_eq!(state.participants.len(), 1); - let participant = &state.participants[0]; - assert_eq!(participant.role_id, "ghostlight.character.ariadne-prime"); - assert_eq!(participant.arena, HEARTBEAT_ARENA_SCENE); - assert_eq!(participant.participant_kind, PARTICIPANT_KIND_CHARACTER); - assert_eq!(participant.scene_id.as_deref(), Some("room")); - assert_eq!( - state - .protocol - .as_ref() - .map(|protocol| protocol.domain.as_str()), - Some("ghostlight") - ); - Ok(()) - } -} diff --git a/epiphany-core/src/heartbeat_state/heartbeat_store.rs b/epiphany-core/src/heartbeat_state/heartbeat_store.rs index 3a7dae0a..8d03cb9b 100644 --- a/epiphany-core/src/heartbeat_state/heartbeat_store.rs +++ b/epiphany-core/src/heartbeat_state/heartbeat_store.rs @@ -3,13 +3,11 @@ use super::EpiphanyHeartbeatArtifactRetentionReceipt; use super::EpiphanyHeartbeatStaleTurnRepairReceipt; use super::EpiphanyHeartbeatStateEntry; use super::HEARTBEAT_ARENA_MAINTENANCE; -use super::HEARTBEAT_ARENA_SCENE; use super::HEARTBEAT_STALE_TURN_REPAIR_LATEST_KEY; use super::HEARTBEAT_STALE_TURN_REPAIR_SCHEMA_VERSION; use super::HEARTBEAT_STATE_KEY; use super::HEARTBEAT_STATE_SCHEMA_VERSION; use super::PARTICIPANT_KIND_AGENT; -use super::PARTICIPANT_KIND_CHARACTER; use super::PERSONA_CONVERSATION_RETENTION_HEAD_SCHEMA_VERSION; use super::PERSONA_CONVERSATION_RETENTION_PLAN_SCHEMA_VERSION; use super::PERSONA_TURN_REQUEST_SCHEMA_VERSION; @@ -242,29 +240,6 @@ pub fn validate_heartbeat_state(state: &EpiphanyHeartbeatStateEntry) -> Result<( "heartbeat target_heartbeat_rate must be non-negative" )); } - if state.initiative_heat.global_multiplier <= 0.0 { - return Err(anyhow!( - "heartbeat initiative_heat global_multiplier must be positive" - )); - } - for multiplier in &state.initiative_heat.multipliers { - if multiplier.id.trim().is_empty() { - return Err(anyhow!("heartbeat initiative heat multiplier has empty id")); - } - if multiplier.multiplier <= 0.0 { - return Err(anyhow!( - "heartbeat initiative heat multiplier {} must be positive", - multiplier.id - )); - } - if multiplier.selector.trim().is_empty() && multiplier.scope != "all" { - return Err(anyhow!( - "heartbeat initiative heat multiplier {} selector is empty for scope {}", - multiplier.id, - multiplier.scope - )); - } - } for participant in &state.participants { if participant.agent_id.trim().is_empty() { return Err(anyhow!("heartbeat participant has empty agent_id")); @@ -282,7 +257,7 @@ pub fn validate_heartbeat_state(state: &EpiphanyHeartbeatStateEntry) -> Result<( )); } let arena = participant_arena(participant); - if !matches!(arena, HEARTBEAT_ARENA_MAINTENANCE | HEARTBEAT_ARENA_SCENE) { + if arena != HEARTBEAT_ARENA_MAINTENANCE { return Err(anyhow!( "heartbeat participant {} arena {:?} is unsupported", participant.agent_id, @@ -290,10 +265,7 @@ pub fn validate_heartbeat_state(state: &EpiphanyHeartbeatStateEntry) -> Result<( )); } let participant_kind = participant_kind(participant); - if !matches!( - participant_kind, - PARTICIPANT_KIND_AGENT | PARTICIPANT_KIND_CHARACTER - ) { + if participant_kind != PARTICIPANT_KIND_AGENT { return Err(anyhow!( "heartbeat participant {} participant_kind {:?} is unsupported", participant.agent_id, diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index a0272213..eb5f9dd7 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -491,7 +491,6 @@ pub use heartbeat_state::EpiphanyHeartbeatArtifactRetentionPlan; pub use heartbeat_state::EpiphanyHeartbeatArtifactRetentionReceipt; pub use heartbeat_state::EpiphanyHeartbeatStaleTurnRepairReceipt; pub use heartbeat_state::EpiphanyHeartbeatStateEntry; -pub use heartbeat_state::GhostlightSceneParticipantSeed; pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_PLAN_LATEST_KEY; pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_PLAN_SCHEMA_VERSION; pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_PLAN_TYPE; @@ -505,45 +504,33 @@ pub use heartbeat_state::HEARTBEAT_STATE_KEY; pub use heartbeat_state::HEARTBEAT_STATE_SCHEMA_VERSION; pub use heartbeat_state::HEARTBEAT_STATE_TYPE; pub use heartbeat_state::HeartbeatArtifactRetentionMember; -pub use heartbeat_state::HeartbeatCompleteOptions; -pub use heartbeat_state::HeartbeatHeatUpdateOptions; pub use heartbeat_state::HeartbeatHistoryEvent; -pub use heartbeat_state::HeartbeatInitiativeHeatPolicy; -pub use heartbeat_state::HeartbeatInitiativeMultiplier; pub use heartbeat_state::HeartbeatPacingPolicy; pub use heartbeat_state::HeartbeatParticipant; pub use heartbeat_state::HeartbeatPendingMention; pub use heartbeat_state::HeartbeatPendingTurn; -pub use heartbeat_state::HeartbeatPumpOptions; 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::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; pub use heartbeat_state::heartbeat_status_projection; -pub use heartbeat_state::initialize_ghostlight_scene_heartbeat_store; pub use heartbeat_state::initialize_heartbeat_store; pub use heartbeat_state::load_heartbeat_state_entry; pub use heartbeat_state::load_latest_heartbeat_stale_turn_repair_receipt; pub use heartbeat_state::pulse_persona_heartbeat; pub use heartbeat_state::pulse_resident_self_heartbeat; -pub use heartbeat_state::pump_heartbeat_store; pub use heartbeat_state::queue_heartbeat_pending_mention_store; pub use heartbeat_state::reconcile_resident_self_heartbeat_ack; pub use heartbeat_state::recover_stale_heartbeat_store; pub use heartbeat_state::retain_heartbeat_pulse_artifacts; -pub use heartbeat_state::tick_heartbeat_store; -pub use heartbeat_state::update_heartbeat_heat_store; pub use heartbeat_state::validate_heartbeat_state; pub use heartbeat_state::write_heartbeat_stale_turn_repair_receipt; pub use heartbeat_state::write_heartbeat_state_entry; diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index 2867ea63..9893c39f 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -13195,14 +13195,13 @@ fn epiphany_mutation_contracts() -> Vec { RUNTIME_SPINE_SCHEMA_VERSION, vec![ CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::IntentSubmit, CultNetDocumentOperation::ReceiptWatch, ], - CultNetMutationAuthority::Coordinator, - vec!["epiphany.heartbeat_pump_intent.v0"], - vec!["epiphany.swarm_control_receipt.v0"], + CultNetMutationAuthority::ReadOnly, + vec![], + vec![], vec![ - "Heartbeat activation owns agent work; external callers submit intents and watch receipts.", + "Runtime jobs are lifecycle receipts derived from admitted worker-launch requests.", ], ), mutation_contract( @@ -13951,19 +13950,13 @@ fn epiphany_mutation_contracts() -> Vec { HEARTBEAT_STATE_SCHEMA_VERSION, vec![ CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::IntentSubmit, CultNetDocumentOperation::ReceiptWatch, ], - CultNetMutationAuthority::Coordinator, + CultNetMutationAuthority::ReadOnly, + vec![], + vec![], vec![ - "epiphany.heartbeat_pump_intent.v0", - "epiphany.heartbeat_heat_intent.v0", - "epiphany.circadian_rhythm_intent.v0", - ], - vec!["epiphany.swarm_control_receipt.v0"], - vec![ - "Aquarium controls heartbeat and circadian rhythm through typed intents, not blind state replacement.", - "Initiative heat is heartbeat policy: global, group, role, and agent tempo changes enter through the heartbeat heat intent.", + "Heartbeat is internal scheduling physiology for Resident Self grants and Persona turns; external callers may inspect it but cannot steer it.", ], ), mutation_contract( diff --git a/schemas/cultnet/epiphany.agent-heartbeat-cognition.schema.json b/schemas/cultnet/epiphany.agent-heartbeat-cognition.schema.json deleted file mode 100644 index cd18b3ff..00000000 --- a/schemas/cultnet/epiphany.agent-heartbeat-cognition.schema.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.agent-heartbeat-cognition.schema.json", - "title": "Epiphany Heartbeat Cognition Quarantine", - "description": "Experimental Void/Ghostlight routine thought-weather kept outside stable heartbeat scheduler state. These values are inspectable receipts, not project truth or scheduling authority.", - "type": "object", - "additionalProperties": true, - "properties": { - "schemaVersion": { - "type": "string" - }, - "updatedAt": { - "type": "string" - }, - "latestRunId": { - "type": ["string", "null"] - }, - "latestArtifactRef": { - "type": ["string", "null"] - }, - "source": { - "type": ["string", "null"] - }, - "sleepCycle": { - "type": "object", - "additionalProperties": true - }, - "memoryResonance": { - "type": "object", - "additionalProperties": true - }, - "incubation": { - "type": "object", - "additionalProperties": true - }, - "thoughtLanes": { - "type": "object", - "additionalProperties": true - }, - "bridge": { - "type": "object", - "additionalProperties": true - }, - "candidateInterventions": { - "type": "object", - "additionalProperties": true - }, - "appraisals": { - "type": "object", - "additionalProperties": true - }, - "reactions": { - "type": "object", - "additionalProperties": true - }, - "extra": { - "type": "object", - "additionalProperties": true - } - }, - "required": [ - "schemaVersion", - "updatedAt" - ] -} diff --git a/schemas/cultnet/epiphany.agent-heartbeat.schema.json b/schemas/cultnet/epiphany.agent-heartbeat.schema.json index c327aa29..c2866a08 100644 --- a/schemas/cultnet/epiphany.agent-heartbeat.schema.json +++ b/schemas/cultnet/epiphany.agent-heartbeat.schema.json @@ -2,12 +2,12 @@ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.agent-heartbeat.schema.json", "title": "Epiphany Heartbeat State", - "description": "Stable typed heartbeat scheduler state for initiative, readiness, pacing, pending turns, and history. Experimental cognition thought-weather lives in epiphany.agent-heartbeat-cognition.", + "description": "Typed scheduling physiology for Resident Self grants and Persona turns.", "type": "object", - "additionalProperties": true, + "additionalProperties": false, "properties": { "schemaVersion": { - "type": "string" + "const": "epiphany.agent_heartbeat.v1" }, "targetHeartbeatRate": { "type": "number" @@ -23,9 +23,6 @@ "type": "object", "additionalProperties": true }, - "initiativeHeat": { - "$ref": "epiphany.heartbeat_initiative_heat.v0.schema.json" - }, "participants": { "type": "array", "items": { @@ -39,10 +36,6 @@ "type": "object", "additionalProperties": true } - }, - "extra": { - "type": "object", - "additionalProperties": true } }, "required": [ diff --git a/schemas/cultnet/epiphany.circadian_rhythm_intent.v0.schema.json b/schemas/cultnet/epiphany.circadian_rhythm_intent.v0.schema.json deleted file mode 100644 index a19ede90..00000000 --- a/schemas/cultnet/epiphany.circadian_rhythm_intent.v0.schema.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.circadian_rhythm_intent.v0.schema.json", - "title": "epiphany circadian_rhythm_intent v0", - "description": "Circadian rhythm intent for letting the swarm sleep or wake.", - "type": "object", - "additionalProperties": true, - "properties": { - "threadId": { - "type": "string" - }, - "sleeping": { - "type": "boolean" - }, - "targetHeartbeatRate": { - "type": "number" - }, - "allowDream": { - "type": "boolean" - } - }, - "required": [ - "threadId", - "sleeping" - ] -} diff --git a/schemas/cultnet/epiphany.heartbeat_heat_intent.v0.schema.json b/schemas/cultnet/epiphany.heartbeat_heat_intent.v0.schema.json deleted file mode 100644 index d750a0fe..00000000 --- a/schemas/cultnet/epiphany.heartbeat_heat_intent.v0.schema.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.heartbeat_heat_intent.v0.schema.json", - "title": "epiphany heartbeat_heat_intent v0", - "description": "Coordinator intent for changing heartbeat initiative heat at global, group, arena, role, or agent scope.", - "type": "object", - "additionalProperties": true, - "properties": { - "threadId": { - "type": "string" - }, - "storeKey": { - "type": [ - "string", - "null" - ], - "description": "Optional heartbeat store key when the coordinator hosts more than one heartbeat arena." - }, - "scope": { - "$ref": "epiphany.heartbeat_initiative_heat.v0.schema.json#/definitions/scope" - }, - "selector": { - "type": "string", - "description": "Agent id, role id, arena, participant kind, group, or constraint selected by scope. Empty only for global/all." - }, - "multiplier": { - "type": "number", - "exclusiveMinimum": 0, - "description": "Recovery-speed multiplier. Values above 1 turn up heat; values below 1 cool the selected lane." - }, - "id": { - "type": [ - "string", - "null" - ], - "description": "Stable policy id. Defaults to global or scope:selector when omitted." - }, - "label": { - "type": [ - "string", - "null" - ] - }, - "reason": { - "type": [ - "string", - "null" - ] - }, - "expiresAfterSceneClock": { - "type": [ - "number", - "null" - ], - "description": "Relative scene-clock duration before the multiplier stops affecting participants." - }, - "clear": { - "type": "boolean", - "default": false - } - }, - "required": [ - "threadId", - "scope" - ], - "allOf": [ - { - "if": { - "properties": { - "clear": { - "const": false - } - } - }, - "then": { - "required": [ - "multiplier" - ] - } - } - ] -} diff --git a/schemas/cultnet/epiphany.heartbeat_initiative_heat.v0.schema.json b/schemas/cultnet/epiphany.heartbeat_initiative_heat.v0.schema.json deleted file mode 100644 index 434fed25..00000000 --- a/schemas/cultnet/epiphany.heartbeat_initiative_heat.v0.schema.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.heartbeat_initiative_heat.v0.schema.json", - "title": "epiphany heartbeat_initiative_heat v0", - "description": "Heartbeat initiative heat policy. Multipliers accelerate or relax turn recovery without granting project authority.", - "type": "object", - "additionalProperties": true, - "properties": { - "schemaVersion": { - "const": "epiphany.heartbeat_initiative_heat.v0" - }, - "globalMultiplier": { - "type": "number", - "exclusiveMinimum": 0 - }, - "multipliers": { - "type": "array", - "items": { - "$ref": "#/definitions/multiplier" - } - } - }, - "required": [ - "schemaVersion", - "globalMultiplier", - "multipliers" - ], - "definitions": { - "scope": { - "type": "string", - "enum": [ - "global", - "all", - "agent", - "agent_id", - "role", - "role_id", - "arena", - "participant_kind", - "kind", - "group", - "constraint" - ] - }, - "multiplier": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string" - }, - "scope": { - "$ref": "#/definitions/scope" - }, - "selector": { - "type": "string" - }, - "multiplier": { - "type": "number", - "exclusiveMinimum": 0 - }, - "reason": { - "type": "string" - }, - "updatedAt": { - "type": [ - "string", - "null" - ], - "format": "date-time" - }, - "expiresAtSceneClock": { - "type": [ - "number", - "null" - ] - } - }, - "required": [ - "id", - "scope", - "selector", - "multiplier" - ] - } - } -} diff --git a/schemas/cultnet/epiphany.heartbeat_pump_intent.v0.schema.json b/schemas/cultnet/epiphany.heartbeat_pump_intent.v0.schema.json deleted file mode 100644 index 8c77bf3e..00000000 --- a/schemas/cultnet/epiphany.heartbeat_pump_intent.v0.schema.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "https://gamecult.dev/epiphany/cultnet/epiphany.heartbeat_pump_intent.v0.schema.json", - "title": "epiphany heartbeat_pump_intent v0", - "description": "Heartbeat pump intent for waking lanes and pacing the swarm.", - "type": "object", - "additionalProperties": true, - "properties": { - "threadId": { - "type": "string" - }, - "scheduleId": { - "type": [ - "string", - "null" - ] - }, - "sourceSceneRef": { - "type": [ - "string", - "null" - ] - }, - "coordinatorAction": { - "type": [ - "string", - "null" - ] - }, - "targetRole": { - "type": [ - "string", - "null" - ] - }, - "externalUrgency": { - "type": "number" - }, - "maxTicks": { - "type": "integer" - } - }, - "required": [ - "threadId" - ] -} diff --git a/schemas/cultnet/index.json b/schemas/cultnet/index.json index 52e02a0f..5de8c3e0 100644 --- a/schemas/cultnet/index.json +++ b/schemas/cultnet/index.json @@ -263,33 +263,11 @@ "wireContracts": [ "cultnet.schema.v0" ], - "schemaVersion": "epiphany.agent_heartbeat.v0", + "schemaVersion": "epiphany.agent_heartbeat.v1", "documentType": "epiphany.agent_heartbeat", "title": "Epiphany Heartbeat State", "path": "epiphany.agent-heartbeat.schema.json" }, - { - "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.heartbeat_initiative_heat.v0.schema.json", - "kind": "document_payload", - "wireContracts": [ - "cultnet.schema.v0" - ], - "schemaVersion": "epiphany.heartbeat_initiative_heat.v0", - "documentType": "epiphany.heartbeat_initiative_heat.v0", - "title": "epiphany heartbeat_initiative_heat v0", - "path": "epiphany.heartbeat_initiative_heat.v0.schema.json" - }, - { - "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.agent-heartbeat-cognition.schema.json", - "kind": "document_payload", - "wireContracts": [ - "cultnet.schema.v0" - ], - "schemaVersion": "epiphany.agent_heartbeat_cognition.v0", - "documentType": "epiphany.agent_heartbeat_cognition", - "title": "Epiphany Heartbeat Cognition Quarantine", - "path": "epiphany.agent-heartbeat-cognition.schema.json" - }, { "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.state-ledger.schema.json", "kind": "document_payload", @@ -510,39 +488,6 @@ "title": "epiphany runtime session_intent v0", "path": "epiphany.runtime.session_intent.v0.schema.json" }, - { - "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.heartbeat_pump_intent.v0.schema.json", - "kind": "document_payload", - "wireContracts": [ - "cultnet.schema.v0" - ], - "schemaVersion": "epiphany.heartbeat_pump_intent.v0", - "documentType": "epiphany.heartbeat_pump_intent.v0", - "title": "epiphany heartbeat_pump_intent v0", - "path": "epiphany.heartbeat_pump_intent.v0.schema.json" - }, - { - "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.heartbeat_heat_intent.v0.schema.json", - "kind": "document_payload", - "wireContracts": [ - "cultnet.schema.v0" - ], - "schemaVersion": "epiphany.heartbeat_heat_intent.v0", - "documentType": "epiphany.heartbeat_heat_intent.v0", - "title": "epiphany heartbeat_heat_intent v0", - "path": "epiphany.heartbeat_heat_intent.v0.schema.json" - }, - { - "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.circadian_rhythm_intent.v0.schema.json", - "kind": "document_payload", - "wireContracts": [ - "cultnet.schema.v0" - ], - "schemaVersion": "epiphany.circadian_rhythm_intent.v0", - "documentType": "epiphany.circadian_rhythm_intent.v0", - "title": "epiphany circadian_rhythm_intent v0", - "path": "epiphany.circadian_rhythm_intent.v0.schema.json" - }, { "schemaId": "https://gamecult.dev/epiphany/cultnet/epiphany.job_launch_intent.v0.schema.json", "kind": "document_payload", diff --git a/schemas/heartbeat-state-schema.md b/schemas/heartbeat-state-schema.md index 71183c86..cf39628e 100644 --- a/schemas/heartbeat-state-schema.md +++ b/schemas/heartbeat-state-schema.md @@ -6,18 +6,19 @@ the organism believes or invent cognition to fill idle time. The executable contract lives in `epiphany-core/src/heartbeat_state/heartbeat_documents.rs` and the scheduling -law lives in `heartbeat_state.rs`, `heartbeat_pacing.rs`, and -`heartbeat_store.rs`. +law lives in `heartbeat_state.rs` and `heartbeat_store.rs`. ## Store identity - document type: `epiphany.agent_heartbeat` -- schema version: `epiphany.agent_heartbeat.v0` +- schema version: `epiphany.agent_heartbeat.v1` - key: `default` -The singleton carries pacing policy, participant readiness, pending turns, -bounded scheduling history, initiative heat, explicit Persona transport -pressure, and retention bookkeeping. +The singleton currently carries coordinator/Persona readiness, pending turns, +bounded scheduling history, explicit Persona transport pressure, and retention +bookkeeping. The remaining social fields are the next ownership cut: they must +become keyed Persona documents so social writes do not share the scheduler CAS +identity. ## Scheduling invariants @@ -28,8 +29,6 @@ pressure, and retention bookkeeping. - Persona may wake only from explicit queued social pressure. - The swarm brake prevents new Persona cognition while allowing terminal acknowledgement and recovery physiology to settle. -- Initiative heat changes scheduling tempo only. It cannot create Mind state, - route an organ, or make a semantic decision. - When no typed obligation or social pressure exists, the scheduler sleeps. Heartbeat owns no personality, mood, appraisal, rumination, dreaming, memory