From 5c9f37ed59589239e94ad383a479d3d1cc76d7da Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 6 May 2026 05:29:28 +0100 Subject: [PATCH] Make heartbeat state native CultCache --- .gitignore | 1 + .../src/bin/epiphany-heartbeat-store.rs | 123 +- epiphany-core/src/heartbeat_state.rs | 1012 +++++++++++++++++ epiphany-core/src/lib.rs | 7 + epiphany-core/src/proposal.rs | 6 +- epiphany-core/src/retrieval.rs | 4 +- notes/fresh-workspace-handoff.md | 2 +- notes/voidbot-routine-adoption-plan.md | 6 +- state/agent-heartbeats.json | 231 ---- state/evidence.jsonl | 1 + state/map.yaml | 4 +- tools/epiphany_agent_heartbeat.py | 791 ++----------- 12 files changed, 1254 insertions(+), 934 deletions(-) delete mode 100644 state/agent-heartbeats.json diff --git a/.gitignore b/.gitignore index 67e6e6e5..f9bd5f15 100644 --- a/.gitignore +++ b/.gitignore @@ -11,5 +11,6 @@ apps/epiphany-gui/src-tauri/target/ .epiphany-dogfood/ .epiphany-heartbeats/ .epiphany-face/ +state/agent-heartbeats.json state/*.msgpack.lock state/*.projection.json diff --git a/epiphany-core/src/bin/epiphany-heartbeat-store.rs b/epiphany-core/src/bin/epiphany-heartbeat-store.rs index 2b4e6fb0..a4af5d3c 100644 --- a/epiphany-core/src/bin/epiphany-heartbeat-store.rs +++ b/epiphany-core/src/bin/epiphany-heartbeat-store.rs @@ -1,7 +1,13 @@ use anyhow::Result; use anyhow::anyhow; +use epiphany_core::HeartbeatCompleteOptions; +use epiphany_core::HeartbeatTickOptions; +use epiphany_core::complete_heartbeat_store; +use epiphany_core::heartbeat_status_projection; +use epiphany_core::initialize_heartbeat_store; use epiphany_core::load_heartbeat_state_entry; use epiphany_core::migrate_heartbeat_json_to_cultcache; +use epiphany_core::tick_heartbeat_store; use epiphany_core::write_heartbeat_json_projection; use std::env; use std::path::PathBuf; @@ -14,17 +20,89 @@ fn main() -> Result<()> { let mut json_path: Option = None; let mut store_path: Option = None; let mut projection_path: Option = None; + let mut artifact_dir: Option = None; + let mut target_heartbeat_rate = 1.0_f64; + let mut coordinator_action: Option = None; + let mut target_role: Option = None; + let mut urgency = 0.75_f64; + 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; while let Some(arg) = args.next() { match arg.as_str() { "--json" => json_path = Some(next_path(&mut args, "--json")?), "--store" => store_path = Some(next_path(&mut args, "--store")?), "--projection" => projection_path = Some(next_path(&mut args, "--projection")?), + "--artifact-dir" => artifact_dir = Some(next_path(&mut args, "--artifact-dir")?), + "--target-heartbeat-rate" => { + target_heartbeat_rate = next_value(&mut args, "--target-heartbeat-rate")?.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()?, + "--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()?, _ => return Err(anyhow!("unknown argument {arg:?}")), } } match command.as_str() { + "init" => { + let store_path = store_path.ok_or_else(|| anyhow!("init requires --store"))?; + let state = initialize_heartbeat_store(&store_path, target_heartbeat_rate)?; + println!( + "{}", + serde_json::json!({ + "ok": true, + "command": "init", + "storeFile": store_path, + "schemaVersion": state.schema_version, + "participants": state.participants.len(), + "history": state.history.len(), + }) + ); + } + "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 result = tick_heartbeat_store( + &store_path, + &artifact_dir, + HeartbeatTickOptions { + target_heartbeat_rate, + coordinator_action, + target_role, + urgency, + schedule_id, + source_scene_ref, + defer_completion, + }, + )?; + 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); + } "migrate-json" => { let json_path = json_path.ok_or_else(|| anyhow!("migrate-json requires --json"))?; let store_path = store_path.ok_or_else(|| anyhow!("migrate-json requires --store"))?; @@ -65,19 +143,31 @@ fn main() -> Result<()> { } "status" => { let store_path = store_path.ok_or_else(|| anyhow!("status requires --store"))?; - let state = load_heartbeat_state_entry(&store_path)?; - println!( - "{}", - serde_json::json!({ - "ok": true, - "command": "status", - "store": store_path, - "present": state.is_some(), - "schemaVersion": state.as_ref().map(|value| value.schema_version.as_str()), - "participants": state.as_ref().map(|value| value.participants.len()), - "history": state.as_ref().map(|value| value.history.len()), - }) - ); + if let Some(artifact_dir) = artifact_dir { + println!( + "{}", + heartbeat_status_projection( + &store_path, + artifact_dir, + target_heartbeat_rate, + limit + )? + ); + } else { + let state = load_heartbeat_state_entry(&store_path)?; + println!( + "{}", + serde_json::json!({ + "ok": true, + "command": "status", + "store": store_path, + "present": state.is_some(), + "schemaVersion": state.as_ref().map(|value| value.schema_version.as_str()), + "participants": state.as_ref().map(|value| value.participants.len()), + "history": state.as_ref().map(|value| value.history.len()), + }) + ); + } } _ => return usage(), } @@ -86,13 +176,16 @@ fn main() -> Result<()> { } fn next_path(args: &mut impl Iterator, name: &str) -> Result { + Ok(PathBuf::from(next_value(args, name)?)) +} + +fn next_value(args: &mut impl Iterator, name: &str) -> Result { args.next() - .map(PathBuf::from) .ok_or_else(|| anyhow!("{name} requires a value")) } fn usage() -> Result<()> { Err(anyhow!( - "usage: epiphany-heartbeat-store migrate-json --json --store [--projection ]\n epiphany-heartbeat-store project --store --projection \n epiphany-heartbeat-store status --store " + "usage: epiphany-heartbeat-store init --store \n epiphany-heartbeat-store tick --store --artifact-dir [--coordinator-action ] [--defer-completion]\n epiphany-heartbeat-store complete --store --artifact-dir --role [--action-id ]\n epiphany-heartbeat-store status --store [--artifact-dir ]\n epiphany-heartbeat-store migrate-json --json --store [--projection ]\n epiphany-heartbeat-store project --store --projection " )) } diff --git a/epiphany-core/src/heartbeat_state.rs b/epiphany-core/src/heartbeat_state.rs index a4e3f110..e2c7b5f5 100644 --- a/epiphany-core/src/heartbeat_state.rs +++ b/epiphany-core/src/heartbeat_state.rs @@ -7,6 +7,7 @@ use cultcache_rs::SingleFileMessagePackBackingStore; use serde::Deserialize; use serde::Serialize; use serde_json::Value; +use std::cmp::Reverse; use std::collections::BTreeMap; use std::fs; use std::path::Path; @@ -14,6 +15,19 @@ use std::path::Path; 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_STATUS_SCHEMA_VERSION: &str = "epiphany.agent_heartbeat_status.v0"; +pub const INITIATIVE_SCHEMA_VERSION: &str = "ghostlight.initiative_schedule.v0"; + +const ROLE_ORDER: &[&str] = &[ + "coordinator", + "face", + "imagination", + "research", + "modeling", + "implementation", + "verification", + "reorientation", +]; #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache( @@ -145,6 +159,23 @@ pub struct HeartbeatHistoryEvent { pub extra: BTreeMap, } +#[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, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HeartbeatCompleteOptions { + pub role: String, + pub action_id: Option, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct EpiphanyHeartbeatStateProjection { pub schema_version: String, @@ -313,6 +344,930 @@ pub fn validate_heartbeat_state(state: &EpiphanyHeartbeatStateEntry) -> Result<( Ok(()) } +pub fn default_heartbeat_state(target_heartbeat_rate: f64) -> EpiphanyHeartbeatStateEntry { + EpiphanyHeartbeatStateEntry { + schema_version: HEARTBEAT_STATE_SCHEMA_VERSION.to_string(), + target_heartbeat_rate, + scene_clock: 0.0, + selection_policy: HeartbeatSelectionPolicy { + mode: "readiness_queue".to_string(), + reaction_precedence: true, + minimum_speed: 0.2, + tie_breakers: vec![ + "reaction_readiness_desc".to_string(), + "next_ready_at_asc".to_string(), + "initiative_speed_desc".to_string(), + "stable_actor_id_asc".to_string(), + ], + extra: BTreeMap::new(), + }, + pacing_policy: HeartbeatPacingPolicy { + cooldown_starts_after_turn_completion: true, + work_base_recovery: 6.0, + idle_base_recovery: 2.0, + sleep_heartbeat_rate_multiplier: 0.05, + minimum_effective_rate: 0.001, + extra: BTreeMap::new(), + }, + participants: ROLE_ORDER + .iter() + .map(|role_id| default_participant(role_id)) + .collect(), + history: Vec::new(), + sleep_cycle: None, + memory_resonance: None, + incubation: None, + extra: BTreeMap::new(), + } +} + +pub fn initialize_heartbeat_store( + store_path: impl AsRef, + target_heartbeat_rate: f64, +) -> Result { + write_heartbeat_state_entry(store_path, &default_heartbeat_state(target_heartbeat_rate)) +} + +pub fn heartbeat_status_projection( + store_path: impl AsRef, + artifact_dir: impl AsRef, + target_heartbeat_rate: f64, + artifact_limit: usize, +) -> Result { + let store_path = store_path.as_ref(); + let Some(state) = load_heartbeat_state_entry(store_path)? else { + return Ok(serde_json::json!({ + "schema_version": HEARTBEAT_STATUS_SCHEMA_VERSION, + "ok": true, + "status": "missing", + "stateFile": null, + "storeFile": store_path, + "cultCacheStore": cultcache_status(store_path), + "artifactDir": artifact_dir.as_ref(), + "targetHeartbeatRate": if target_heartbeat_rate > 0.0 { Some(target_heartbeat_rate) } else { None }, + "sceneClock": null, + "participants": [], + "latestEvent": null, + "history": [], + "latestArtifacts": latest_json_artifacts(artifact_dir, artifact_limit), + "availableActions": ["init", "tick", "complete", "status"], + })); + }; + let history: Vec<_> = state + .history + .iter() + .rev() + .take(artifact_limit) + .cloned() + .collect::>() + .into_iter() + .rev() + .map(history_event_json) + .collect(); + Ok(serde_json::json!({ + "schema_version": HEARTBEAT_STATUS_SCHEMA_VERSION, + "ok": true, + "status": "ready", + "stateFile": null, + "storeFile": store_path, + "cultCacheStore": cultcache_status(store_path), + "artifactDir": artifact_dir.as_ref(), + "targetHeartbeatRate": state.target_heartbeat_rate, + "sceneClock": state.scene_clock, + "participants": state.participants.iter().map(participant_status_json).collect::>(), + "latestEvent": history.last().cloned(), + "history": history, + "latestArtifacts": latest_json_artifacts(artifact_dir, artifact_limit), + "availableActions": ["init", "tick", "complete", "status"], + })) +} + +pub fn tick_heartbeat_store( + store_path: impl AsRef, + artifact_dir: impl AsRef, + options: HeartbeatTickOptions, +) -> Result { + let store_path = store_path.as_ref(); + let mut state = load_heartbeat_state_entry(store_path)? + .unwrap_or_else(|| default_heartbeat_state(options.target_heartbeat_rate)); + if options.target_heartbeat_rate > 0.0 { + state.target_heartbeat_rate = options.target_heartbeat_rate; + } + patch_missing_participants(&mut state); + let result = tick_once(&mut state, &options)?; + 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()))?; + write_json_artifact( + artifact_dir.join(format!("{}.initiative.json", options.schedule_id)), + &result["schedule"], + )?; + write_json_artifact( + artifact_dir.join(format!("{}.event.json", options.schedule_id)), + &result["event"], + )?; + + Ok(serde_json::json!({ + "ok": true, + "storeFile": store_path, + "artifactDir": artifact_dir, + "stateFile": null, + "event": result["event"].clone(), + "schedule": result["schedule"].clone(), + "rumination": result["rumination"].clone(), + })) +} + +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(), + 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: None, + extra: BTreeMap::new(), + }; + 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), + })) +} + +fn tick_once( + state: &mut EpiphanyHeartbeatStateEntry, + options: &HeartbeatTickOptions, +) -> 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)?; + let selected = state.participants[selected_index].clone(); + let (action_id, action_type, base_recovery, initiative_cost, interruptibility, action_reason) = + action_for_selection( + state, + &selected, + work_role.as_deref(), + options.coordinator_action.as_deref(), + rate, + ); + let scene_clock = state.scene_clock.max(selected.next_ready_at); + let recovery = base_recovery + / selected + .initiative_speed + .max(state.selection_policy.minimum_speed); + let pending = HeartbeatPendingTurn { + status: "running".to_string(), + schedule_id: options.schedule_id.clone(), + action_id: action_id.clone(), + action_type: if action_id.ends_with(".ruminate") { + "ruminate_memory".to_string() + } else { + "role_work".to_string() + }, + started_at: now_iso(), + started_scene_clock: round6(scene_clock), + base_recovery: round6(base_recovery), + recovery: round6(recovery), + cooldown_policy: "after_turn_completion".to_string(), + completed_at: None, + completed_scene_clock: None, + next_ready_at: None, + extra: BTreeMap::new(), + }; + state.participants[selected_index].pending_turn = Some(pending.clone()); + state.participants[selected_index].last_action_id = Some(action_id.clone()); + state.participants[selected_index].last_woke_at = Some(now_iso()); + state.participants[selected_index].current_load = + round6((state.participants[selected_index].current_load * 0.75).clamp(0.0, 1.0)); + state.scene_clock = round6(scene_clock); + if !options.defer_completion { + complete_pending_turn(state, selected_index)?; + } + + let selected_after = state.participants[selected_index].clone(); + let action_event_type = if action_id.ends_with(".ruminate") { + "ruminate_memory" + } else { + "role_work" + }; + let event = HeartbeatHistoryEvent { + ts: now_iso(), + schedule_id: options.schedule_id.clone(), + selected_role: selected_after.role_id.clone(), + selected_agent_id: selected_after.agent_id.clone(), + action_id: action_id.clone(), + action_type: action_event_type.to_string(), + coordinator_action: options.coordinator_action.clone(), + target_role: options.target_role.clone(), + work_role: work_role.clone(), + 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() + }), + cooldown_started_after_completion: Some(true), + extra: BTreeMap::new(), + }; + state.history.push(event.clone()); + trim_history(state); + + let readiness_snapshot = readiness_snapshot(state, work_role.as_deref(), options.urgency); + let schedule = serde_json::json!({ + "schema_version": INITIATIVE_SCHEMA_VERSION, + "schedule_id": options.schedule_id, + "source_scene_ref": options.source_scene_ref, + "scene_clock": state.scene_clock, + "participants": state.participants.iter().map(schedule_participant_json).collect::>(), + "action_catalog": [{ + "action_id": action_id, + "actor_id": selected_after.agent_id, + "action_type": action_type, + "action_scale": if action_id.ends_with(".ruminate") { "short" } else { "standard" }, + "base_recovery": base_recovery, + "initiative_cost": initiative_cost, + "interruptibility": interruptibility, + "commitment": if action_id.ends_with(".ruminate") { 0.25 } else { 0.65 }, + "local_affordance_basis": [ + action_reason, + "Heartbeat slots control opportunity, not project authority.", + "Cooldown starts only after the heartbeat turn completes, so an unfinished sub-agent thread cannot be heartbeaten again." + ], + }], + "reaction_windows": if let Some(work_role) = &work_role { + 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_role(work_role)], + "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." + }]) + } else { + serde_json::json!([]) + }, + "selection_policy": selection_policy_json(&state.selection_policy), + "next_actor_selection": { + "selection_kind": selection_kind, + "selected_actor_id": selected_after.agent_id, + "selected_action_ids": [action_id], + "scene_clock_after_selection": state.scene_clock, + "selection_reason": selection_reason, + "override_reason": null, + "readiness_snapshot": readiness_snapshot, + }, + "review_notes": [ + "Epiphany heartbeat uses Ghostlight initiative timing as a harness scheduling receipt.", + "A selected idle lane may ruminate and request bounded self-memory mutation; it may not invent project work.", + "When no coordinator work is active, idle rumination uses the sleep heartbeat multiplier so the swarm dreams slowly instead of thrashing." + ], + }); + + let rumination = if action_id.ends_with(".ruminate") { + serde_json::json!({ + "roleId": selected_after.role_id, + "selfPatch": rumination_patch(&selected_after.role_id, &action_id), + "result": null, + "applied": false, + }) + } else { + Value::Null + }; + Ok(serde_json::json!({ + "event": history_event_json(event), + "schedule": schedule, + "rumination": if rumination.is_null() { Value::Null } else { rumination }, + })) +} + +fn complete_pending_turn( + state: &mut EpiphanyHeartbeatStateEntry, + participant_index: usize, +) -> Result { + let pending = state.participants[participant_index] + .pending_turn + .clone() + .ok_or_else(|| { + anyhow!( + "{} has no running heartbeat turn", + state.participants[participant_index].role_id + ) + })?; + if pending.status != "running" { + return Err(anyhow!( + "{} has no running heartbeat turn", + state.participants[participant_index].role_id + )); + } + let scene_clock = state.scene_clock.max(pending.started_scene_clock); + state.participants[participant_index].next_ready_at = round6(scene_clock + pending.recovery); + state.participants[participant_index].last_finished_at = Some(now_iso()); + let mut completed = pending; + completed.status = "completed".to_string(); + completed.completed_at = state.participants[participant_index] + .last_finished_at + .clone(); + completed.completed_scene_clock = Some(round6(scene_clock)); + completed.next_ready_at = Some(state.participants[participant_index].next_ready_at); + state.participants[participant_index].pending_turn = None; + Ok(completed) +} + +fn select_participant( + state: &EpiphanyHeartbeatStateEntry, + work_role: Option<&str>, + urgency: f64, +) -> Result<(usize, &'static str, String)> { + let active: Vec = state + .participants + .iter() + .enumerate() + .filter_map(|(index, item)| { + (item.status == "active" && !is_turn_pending(item)).then_some(index) + }) + .collect(); + if active.is_empty() { + return Err(anyhow!("heartbeat has no active participants")); + } + if let Some(work_role) = work_role { + let index = participant_index_by_role(state, work_role)?; + let candidate = &state.participants[index]; + if is_turn_pending(candidate) { + let pending = candidate.pending_turn.as_ref(); + return Err(anyhow!( + "{} already has running heartbeat turn {}; complete it before scheduling another", + candidate.display_name, + pending + .map(|item| item.action_id.as_str()) + .unwrap_or("unknown") + )); + } + let reaction_readiness = candidate.reaction_bias * urgency - candidate.current_load; + if candidate.status == "active" && reaction_readiness >= candidate.interrupt_threshold { + return Ok(( + index, + "reaction_interrupt", + format!( + "{} won a heartbeat reaction window for pending {} work.", + candidate.display_name, work_role + ), + )); + } + } + let selected = active + .into_iter() + .min_by(|left, right| { + let left_item = &state.participants[*left]; + let right_item = &state.participants[*right]; + left_item + .next_ready_at + .total_cmp(&right_item.next_ready_at) + .then_with(|| { + right_item + .initiative_speed + .total_cmp(&left_item.initiative_speed) + }) + .then_with(|| left_item.agent_id.cmp(&right_item.agent_id)) + }) + .expect("active participant exists"); + Ok(( + selected, + "scheduled_turn", + "No pending work cleared a reaction threshold; earliest ready active lane won the heartbeat slot." + .to_string(), + )) +} + +fn action_for_selection( + state: &EpiphanyHeartbeatStateEntry, + selected: &HeartbeatParticipant, + work_role: Option<&str>, + coordinator_action: Option<&str>, + target_heartbeat_rate: f64, +) -> (String, &'static str, f64, f64, f64, String) { + let minimum_rate = state.pacing_policy.minimum_effective_rate.max(0.001); + if Some(selected.role_id.as_str()) == work_role { + let heartbeat_rate = target_heartbeat_rate.max(minimum_rate); + let action_id = format!("heartbeat.{}.work", selected.role_id); + return ( + action_id, + "mixed", + state.pacing_policy.work_base_recovery / heartbeat_rate, + 4.0, + 0.45, + format!( + "Wake {} for coordinator action {}.", + selected.display_name, + coordinator_action.unwrap_or("pending work") + ), + ); + } + let sleep_multiplier = state + .pacing_policy + .sleep_heartbeat_rate_multiplier + .max(minimum_rate); + let heartbeat_rate = (target_heartbeat_rate * sleep_multiplier).max(minimum_rate); + let action_id = format!("heartbeat.{}.ruminate", selected.role_id); + ( + action_id, + "wait", + state.pacing_policy.idle_base_recovery / heartbeat_rate, + 1.0, + 0.9, + format!( + "{} has no actionable lane work; ruminate and distill role memory.", + selected.display_name + ), + ) +} + +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) + { + return Some(target_role.to_string()); + } + let role = match action? { + "prepareCheckpoint" => "coordinator", + "surfaceAgentThoughts" | "discordAquariumChat" => "face", + "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 patch_missing_participants(state: &mut EpiphanyHeartbeatStateEntry) { + 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 { + participant + .pending_turn + .get_or_insert_with(|| HeartbeatPendingTurn { + status: String::new(), + ..HeartbeatPendingTurn::default() + }); + if participant + .pending_turn + .as_ref() + .is_some_and(|turn| turn.status.is_empty()) + { + participant.pending_turn = None; + } + } +} + +fn default_participant(role_id: &str) -> HeartbeatParticipant { + HeartbeatParticipant { + agent_id: agent_id_for_role(role_id).to_string(), + role_id: role_id.to_string(), + display_name: display_name_for_role(role_id).to_string(), + initiative_speed: initiative_speed_for_role(role_id), + next_ready_at: 0.0, + reaction_bias: reaction_bias_for_role(role_id), + interrupt_threshold: interrupt_threshold_for_role(role_id), + current_load: 0.0, + status: "active".to_string(), + constraints: participant_constraints(role_id) + .into_iter() + .map(str::to_string) + .collect(), + last_action_id: None, + last_woke_at: None, + last_finished_at: None, + pending_turn: None, + extra: BTreeMap::new(), + } +} + +fn participant_index_by_role(state: &EpiphanyHeartbeatStateEntry, role_id: &str) -> Result { + state + .participants + .iter() + .position(|item| item.role_id == role_id) + .ok_or_else(|| anyhow!("heartbeat participant role {:?} is missing", role_id)) +} + +fn is_turn_pending(participant: &HeartbeatParticipant) -> bool { + participant + .pending_turn + .as_ref() + .is_some_and(|turn| turn.status == "running") +} + +fn readiness_snapshot( + state: &EpiphanyHeartbeatStateEntry, + work_role: Option<&str>, + urgency: f64, +) -> Vec { + state + .participants + .iter() + .filter(|item| item.status == "active" && !is_turn_pending(item)) + .map(|item| { + let eligible = Some(item.role_id.as_str()) == work_role && work_role.is_some(); + let reaction_readiness = + eligible.then_some(round6(item.reaction_bias * urgency - item.current_load)); + serde_json::json!({ + "agent_id": item.agent_id, + "next_ready_at": item.next_ready_at, + "reaction_readiness": reaction_readiness, + "eligible_for_reaction": eligible, + }) + }) + .collect() +} + +fn trim_history(state: &mut EpiphanyHeartbeatStateEntry) { + let len = state.history.len(); + if len > 128 { + state.history.drain(0..(len - 128)); + } +} + +fn write_json_artifact(path: impl AsRef, value: &Value) -> Result<()> { + let path = path.as_ref(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("failed to create {}", parent.display()))?; + } + fs::write(path, format!("{}\n", serde_json::to_string_pretty(value)?)) + .with_context(|| format!("failed to write {}", path.display())) +} + +fn latest_json_artifacts(artifact_dir: impl AsRef, limit: usize) -> Vec { + let artifact_dir = artifact_dir.as_ref(); + let Ok(read_dir) = fs::read_dir(artifact_dir) else { + return Vec::new(); + }; + let mut paths: Vec<_> = read_dir + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "json") + }) + .filter_map(|path| { + let modified = path.metadata().and_then(|meta| meta.modified()).ok()?; + Some((path, modified)) + }) + .collect(); + paths.sort_by_key(|item| Reverse(item.1)); + paths + .into_iter() + .take(limit) + .filter_map(|(path, modified)| { + let raw = fs::read_to_string(&path).ok()?; + let payload: Value = serde_json::from_str(&raw).ok()?; + let modified_at: chrono::DateTime = modified.into(); + Some(serde_json::json!({ + "path": path, + "name": path.file_name().and_then(|name| name.to_str()), + "modifiedAt": modified_at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), + "schemaVersion": payload.get("schema_version"), + "kind": path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit('.').next()).unwrap_or("json"), + "summary": artifact_summary(&payload), + })) + }) + .collect() +} + +fn artifact_summary(payload: &Value) -> Value { + let event = if payload.get("actionId").is_some() { + Some(payload) + } else { + payload.get("event") + }; + if let Some(event) = event { + return serde_json::json!({ + "selectedRole": event.get("selectedRole"), + "actionType": event.get("actionType"), + "actionId": event.get("actionId"), + "coordinatorAction": event.get("coordinatorAction"), + }); + } + if let Some(selection) = payload + .get("next_actor_selection") + .or_else(|| payload.get("nextActorSelection")) + { + return serde_json::json!({ + "selectionKind": selection.get("selection_kind").or_else(|| selection.get("selectionKind")), + "selectedActorId": selection.get("selected_actor_id").or_else(|| selection.get("selectedActorId")), + }); + } + let keys = payload + .as_object() + .map(|object| object.keys().take(8).cloned().collect::>()) + .unwrap_or_default(); + serde_json::json!({ "keys": keys }) +} + +fn cultcache_status(store_path: &Path) -> Value { + let metadata = store_path.metadata().ok(); + let modified_at = metadata + .as_ref() + .and_then(|meta| meta.modified().ok()) + .map(|time| { + let time: chrono::DateTime = time.into(); + time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) + }); + serde_json::json!({ + "storeFile": store_path, + "present": metadata.is_some(), + "sizeBytes": metadata.as_ref().map(|meta| meta.len()), + "modifiedAt": modified_at, + "entryType": HEARTBEAT_STATE_TYPE, + "entryKey": HEARTBEAT_STATE_KEY, + }) +} + +fn participant_status_json(participant: &HeartbeatParticipant) -> Value { + serde_json::json!({ + "agentId": participant.agent_id, + "roleId": participant.role_id, + "displayName": participant.display_name, + "initiativeSpeed": participant.initiative_speed, + "nextReadyAt": participant.next_ready_at, + "reactionBias": participant.reaction_bias, + "interruptThreshold": participant.interrupt_threshold, + "currentLoad": participant.current_load, + "status": participant.status, + "lastActionId": participant.last_action_id, + "lastWokeAt": participant.last_woke_at, + "lastFinishedAt": participant.last_finished_at, + "pendingTurn": participant.pending_turn.as_ref().map(pending_turn_json), + }) +} + +fn schedule_participant_json(participant: &HeartbeatParticipant) -> Value { + serde_json::json!({ + "agent_id": participant.agent_id, + "display_name": participant.display_name, + "initiative_speed": participant.initiative_speed, + "next_ready_at": participant.next_ready_at, + "reaction_bias": participant.reaction_bias, + "interrupt_threshold": participant.interrupt_threshold, + "current_load": participant.current_load, + "status": participant.status, + "pending_turn": participant.pending_turn.as_ref().map(pending_turn_json), + "constraints": participant.constraints, + }) +} + +fn selection_policy_json(policy: &HeartbeatSelectionPolicy) -> Value { + serde_json::json!({ + "mode": policy.mode, + "reaction_precedence": policy.reaction_precedence, + "minimum_speed": policy.minimum_speed, + "tie_breakers": policy.tie_breakers, + }) +} + +fn pending_turn_json(turn: &HeartbeatPendingTurn) -> Value { + serde_json::json!({ + "status": turn.status, + "scheduleId": turn.schedule_id, + "actionId": turn.action_id, + "actionType": turn.action_type, + "startedAt": turn.started_at, + "startedSceneClock": turn.started_scene_clock, + "baseRecovery": turn.base_recovery, + "recovery": turn.recovery, + "cooldownPolicy": turn.cooldown_policy, + "completedAt": turn.completed_at, + "completedSceneClock": turn.completed_scene_clock, + "nextReadyAt": turn.next_ready_at, + }) +} + +fn history_event_json(event: HeartbeatHistoryEvent) -> Value { + serde_json::json!({ + "ts": event.ts, + "scheduleId": event.schedule_id, + "selectedRole": event.selected_role, + "selectedAgentId": event.selected_agent_id, + "actionId": event.action_id, + "actionType": event.action_type, + "coordinatorAction": event.coordinator_action, + "targetRole": event.target_role, + "workRole": event.work_role, + "sceneClock": event.scene_clock, + "nextReadyAt": event.next_ready_at, + "turnStatus": event.turn_status, + "cooldownStartedAfterCompletion": event.cooldown_started_after_completion, + }) +} + +fn rumination_patch(role_id: &str, action_id: &str) -> Value { + let display_name = display_name_for_role(role_id); + serde_json::json!({ + "agentId": agent_id_for_role(role_id), + "reason": format!("{display_name} won an idle heartbeat slot and should preserve the habit of using idle wakeups to distill role memory instead of manufacturing project work."), + "semanticMemories": [{ + "memoryId": format!("mem-{role_id}-heartbeat-rumination"), + "summary": "When a heartbeat wakes this lane and no coordinator-approved work is available, the correct move is to ruminate on role quality, cut stale memory, and return a bounded self-memory improvement rather than inventing project authority.", + "salience": 0.78, + "confidence": 0.88, + }], + "goals": [{ + "goalId": format!("goal-{role_id}-heartbeat-self-distill"), + "description": "Use idle heartbeat slots to become sharper at this lane's own work before touching project state.", + "scope": "life", + "priority": 0.82, + "emotionalStake": "An idle organ that invents work becomes noise in the bloodstream.", + "status": "active", + }], + "privateNotes": [format!("Last idle heartbeat action `{action_id}` chose rumination over fake urgency.")], + }) +} + +fn now_iso() -> String { + chrono::Utc::now() + .to_rfc3339_opts(chrono::SecondsFormat::Secs, false) + .replace('Z', "+00:00") +} + +fn round6(value: f64) -> f64 { + (value * 1_000_000.0).round() / 1_000_000.0 +} + +fn agent_id_for_role(role_id: &str) -> &'static str { + match role_id { + "coordinator" => "epiphany.self", + "face" => "epiphany.face", + "imagination" => "epiphany.imagination", + "research" => "epiphany.eyes", + "modeling" => "epiphany.body", + "implementation" => "epiphany.hands", + "verification" => "epiphany.soul", + "reorientation" => "epiphany.life", + _ => "epiphany.unknown", + } +} + +fn display_name_for_role(role_id: &str) -> &'static str { + match role_id { + "coordinator" => "Self", + "face" => "Face", + "imagination" => "Imagination", + "research" => "Eyes", + "modeling" => "Body", + "implementation" => "Hands", + "verification" => "Soul", + "reorientation" => "Life", + _ => "Unknown", + } +} + +fn initiative_speed_for_role(role_id: &str) -> f64 { + match role_id { + "coordinator" => 1.28, + "face" => 1.12, + "imagination" => 0.82, + "research" => 0.78, + "modeling" => 0.92, + "implementation" => 0.74, + "verification" => 0.88, + "reorientation" => 1.04, + _ => 1.0, + } +} + +fn reaction_bias_for_role(role_id: &str) -> f64 { + match role_id { + "coordinator" => 0.88, + "face" => 0.84, + "imagination" => 0.54, + "research" => 0.62, + "modeling" => 0.74, + "implementation" => 0.58, + "verification" => 0.82, + "reorientation" => 0.86, + _ => 0.5, + } +} + +fn interrupt_threshold_for_role(role_id: &str) -> f64 { + match role_id { + "coordinator" => 0.42, + "face" => 0.52, + "imagination" => 0.64, + "research" => 0.58, + "modeling" => 0.5, + "implementation" => 0.5, + "verification" => 0.48, + "reorientation" => 0.44, + _ => 0.5, + } +} + +fn participant_constraints(role_id: &str) -> Vec<&'static str> { + let role_specific = match role_id { + "coordinator" => { + "Routes and reviews; must not implement, verify, or accept its own comfort." + } + "face" => { + "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.", + "reorientation" => "Protects continuity; must not fake survived context.", + _ => "Unknown role.", + }; + vec![ + "Runs Ghostlight-shaped persistent role memory.", + "May improve lane memory when awake and idle.", + "Project truth belongs in EpiphanyThreadState, not role memory.", + role_specific, + ] +} + #[cfg(test)] mod tests { use super::*; @@ -357,6 +1312,63 @@ mod tests { Ok(()) } + #[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, + }, + )?; + assert_eq!(work["event"]["selectedRole"], "implementation"); + assert_eq!(work["event"]["turnStatus"], "running"); + 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, + }, + ) + .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!(artifact_dir.join("native-work.completion.json").exists()); + Ok(()) + } + fn sample_json() -> &'static str { r#"{ "schema_version": "epiphany.agent_heartbeat.v0", diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 7b91278a..75f5d9b4 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -19,15 +19,22 @@ pub use heartbeat_state::EpiphanyHeartbeatStateEntry; 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::HeartbeatCompleteOptions; pub use heartbeat_state::HeartbeatHistoryEvent; pub use heartbeat_state::HeartbeatPacingPolicy; pub use heartbeat_state::HeartbeatParticipant; pub use heartbeat_state::HeartbeatPendingTurn; pub use heartbeat_state::HeartbeatSelectionPolicy; +pub use heartbeat_state::HeartbeatTickOptions; +pub use heartbeat_state::complete_heartbeat_store; +pub use heartbeat_state::default_heartbeat_state; pub use heartbeat_state::heartbeat_state_cache; +pub use heartbeat_state::heartbeat_status_projection; +pub use heartbeat_state::initialize_heartbeat_store; pub use heartbeat_state::load_heartbeat_state_entry; pub use heartbeat_state::migrate_heartbeat_json_to_cultcache; pub use heartbeat_state::read_heartbeat_json_projection; +pub use heartbeat_state::tick_heartbeat_store; pub use heartbeat_state::validate_heartbeat_state; pub use heartbeat_state::write_heartbeat_json_projection; pub use heartbeat_state::write_heartbeat_state_entry; diff --git a/epiphany-core/src/proposal.rs b/epiphany-core/src/proposal.rs index ae9f30c2..ad8ee045 100644 --- a/epiphany-core/src/proposal.rs +++ b/epiphany-core/src/proposal.rs @@ -134,8 +134,8 @@ pub fn propose_map_update(input: EpiphanyMapProposalInput) -> Result Result NonZero { .map(NonZero::get) .unwrap_or(1); #[expect(clippy::expect_used)] - NonZero::new(cores.min(FILE_SEARCH_MAX_THREADS).max(1)) + NonZero::new(cores.clamp(1, FILE_SEARCH_MAX_THREADS)) .expect("file-search threads should be non-zero") } @@ -1877,7 +1877,7 @@ mod tests { ); assert!(response.results.iter().any(|result| { result.kind == EpiphanyRetrieveResultKind::SemanticChunk - && result.path == PathBuf::from("src/router.rs") + && result.path == Path::new("src/router.rs") })); drop(qdrant); drop(ollama); diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 9d97c0b0..ad51b9a1 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -41,7 +41,7 @@ Do not trust this file for the exact live HEAD. Always check git. - The prompt doctrine pass is landed. Shared Epiphany prompts now carry distilled memory/evidence discipline. Rendered state intro/doctrine text lives in `epiphany-core/src/prompts/`, and lane/control prompt text lives in `vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml`: modeling is the Body, implementation is the Hands and GUI-launched main coding lane, verification is the Soul, reorientation is Life, coordinator remains the read-only Self, and CRRC owns the pre-compaction intervention template. - The Ghostlight memory pass is landed. `epiphany_specialists.toml` now has a shared persistent-memory projection prepended by the harness to fixed role specialists, reorientation workers, coordinator notes, and CRRC checkpoint interventions; `tools/epiphany_gui_action.py` prepends the same memory to GUI-launched implementation prompts. The rendered base doctrine also states the Perfect Machine rule directly: prompt is projection, durable typed state is the mind, every lane must improve its own memory/model/prompt/evidence habit or name the repair, and each lane phrases that duty in its own organ language so the salience sticks. - The role self-memory persistence pass is landed. Each lane has a Ghostlight-shaped dossier under `state/agents`, and specialists may return optional `selfPatch` requests beside their normal role result. `roleResult`/`roleAccept` project coordinator review as `selfPersistence`: accepted requests are role-matched, bounded lane memory/goal/value/private-note mutations; refused requests explain wrong role, project-truth smuggling, authority grabs, bloat, missing reason, or malformed records. GUI/coordinator accept paths apply accepted `selfPatch` requests through `tools/epiphany_agent_memory.py`; project truth still belongs only in `EpiphanyThreadState`. -- The heartbeat initiative pass is landed as a bounded tool seam. `state/agent-heartbeats.json` tracks Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life as Ghostlight-style initiative participants with speed, next-ready time, reaction bias, interrupt threshold, load, status, and constraints. `state/agent-heartbeats.msgpack` is now the first typed CultCache-backed MessagePack store for that same state, through `epiphany-core::EpiphanyHeartbeatStateEntry` and the `epiphany-heartbeat-store` bridge binary. `tools/epiphany_agent_heartbeat.py` still operates on JSON for compatibility, reports the CultCache store status, lets the harness set a target heartbeat rate, emits Ghostlight-shaped initiative receipts, pulls pending coordinator work through reaction windows, and makes idle winners ruminate into bounded self-memory instead of inventing project work. JSON is a Python-tool shim, not the desired inspection layer. General CultCache schema sync, polyglot domain loading, and debug display tools belong in CultLib. This is a callable scheduler seam, not yet an always-on daemon. +- The heartbeat initiative pass is landed as a bounded tool seam. `state/agent-heartbeats.msgpack` tracks Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life as Ghostlight-style initiative participants with speed, next-ready time, reaction bias, interrupt threshold, load, status, constraints, history, and pending turns through `epiphany-core::EpiphanyHeartbeatStateEntry` and the native `epiphany-heartbeat-store` binary. `tools/epiphany_agent_heartbeat.py` delegates init/status/tick/complete to that Rust CultCache store, then only handles Python-owned role memory patch application and artifact glue. JSON heartbeat state is gone; general CultCache schema sync, polyglot domain loading, and debug display tools belong in CultLib. This is a callable scheduler seam, not yet an always-on daemon. - The Face public-surface pass is landed as a bounded lane. `state/agents/face.agent-state.json` gives Face a Ghostlight-shaped dossier; `epiphany_specialists.toml` gives it a VoidBot-heartbeat-derived prompt stripped of moderation authority; `state/face-discord.json` and `tools/epiphany_face_discord.py` enforce that Face may interact only through #aquarium. Missing channel id or token writes candidate chat artifacts instead of posting elsewhere. - The heartbeat/Face operator API pass is landed. `tools/epiphany_agent_heartbeat.py status` returns machine-readable initiative state plus CultCache store presence, `tools/epiphany_face_discord.py bubble` writes Discord-independent `epiphany.face_bubble.v0` artifacts, `tools/epiphany_mvp_status.py` includes `heartbeat` and `face` blocks, and `tools/epiphany_gui_action.py` exposes `heartbeatStatus`, `runHeartbeat`, and `faceBubble`. `runHeartbeat` advances one slot and emits a Face bubble so Aquarium can show chat even before Discord posting is configured. - The Aetheria dogfood run has a contamination scar. The supervising Codex session directly edited and committed target-repo work on `E:\Projects\Aetheria-Economy` instead of only driving Epiphany lanes. Treat those Aetheria commits as supervisor-seeded implementation, not clean evidence that Epiphany coordinated the work. Future dogfood must run through the GUI/coordinator/fixed role lanes with auditable artifacts unless the user explicitly authorizes an operator intervention. diff --git a/notes/voidbot-routine-adoption-plan.md b/notes/voidbot-routine-adoption-plan.md index 1537bce0..893c76f5 100644 --- a/notes/voidbot-routine-adoption-plan.md +++ b/notes/voidbot-routine-adoption-plan.md @@ -115,9 +115,9 @@ rumination, Face surfacing, and sleep consolidation. and CultCache inspection compatibility. 2. **Heartbeat state migration** - - Move `state/agent-heartbeats.json` into a typed MessagePack document, then - retire JSON once the heartbeat tool reads and writes the typed store - directly. + - Move `state/agent-heartbeats.json` into a typed MessagePack document. + Landed: the tracked JSON state file is retired and heartbeat + init/status/tick/complete now route through the native CultCache store. - Add `sleep_cycle`, `memory_resonance`, and `incubation` fields. - Keep the current CLI contract stable while the backing store changes. diff --git a/state/agent-heartbeats.json b/state/agent-heartbeats.json deleted file mode 100644 index 23d23532..00000000 --- a/state/agent-heartbeats.json +++ /dev/null @@ -1,231 +0,0 @@ -{ - "schema_version": "epiphany.agent_heartbeat.v0", - "target_heartbeat_rate": 1.0, - "scene_clock": 5.357143, - "selection_policy": { - "mode": "readiness_queue", - "reaction_precedence": true, - "minimum_speed": 0.2, - "tie_breakers": [ - "reaction_readiness_desc", - "next_ready_at_asc", - "initiative_speed_desc", - "stable_actor_id_asc" - ] - }, - "pacing_policy": { - "cooldown_starts_after_turn_completion": true, - "work_base_recovery": 6.0, - "idle_base_recovery": 2.0, - "sleep_heartbeat_rate_multiplier": 0.05, - "minimum_effective_rate": 0.001 - }, - "participants": [ - { - "agent_id": "epiphany.self", - "role_id": "coordinator", - "display_name": "Self", - "initiative_speed": 1.28, - "next_ready_at": 1.5625, - "reaction_bias": 0.88, - "interrupt_threshold": 0.42, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Routes and reviews; must not implement, verify, or accept its own comfort." - ], - "last_action_id": "heartbeat.coordinator.ruminate", - "last_woke_at": "2026-05-05T12:25:10+00:00" - }, - { - "agent_id": "epiphany.imagination", - "role_id": "imagination", - "display_name": "Imagination", - "initiative_speed": 0.82, - "next_ready_at": 0.0, - "reaction_bias": 0.54, - "interrupt_threshold": 0.64, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Synthesizes futures; must not adopt objectives." - ], - "last_action_id": null, - "last_woke_at": null - }, - { - "agent_id": "epiphany.eyes", - "role_id": "research", - "display_name": "Eyes", - "initiative_speed": 0.78, - "next_ready_at": 0.0, - "reaction_bias": 0.62, - "interrupt_threshold": 0.58, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Scouts known work; must not turn research into procrastination." - ], - "last_action_id": null, - "last_woke_at": null - }, - { - "agent_id": "epiphany.body", - "role_id": "modeling", - "display_name": "Body", - "initiative_speed": 0.92, - "next_ready_at": 0.0, - "reaction_bias": 0.74, - "interrupt_threshold": 0.5, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Grows source-grounded maps and checkpoints; must not edit implementation code." - ], - "last_action_id": null, - "last_woke_at": null - }, - { - "agent_id": "epiphany.hands", - "role_id": "implementation", - "display_name": "Hands", - "initiative_speed": 0.74, - "next_ready_at": 8.108108, - "reaction_bias": 0.58, - "interrupt_threshold": 0.5, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Touches source only with accepted guidance and verifier-readable evidence." - ], - "last_action_id": "heartbeat.implementation.work", - "last_woke_at": "2026-05-05T12:17:57+00:00" - }, - { - "agent_id": "epiphany.soul", - "role_id": "verification", - "display_name": "Soul", - "initiative_speed": 0.88, - "next_ready_at": 0.0, - "reaction_bias": 0.82, - "interrupt_threshold": 0.48, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Falsifies promises; must not bless theater." - ], - "last_action_id": null, - "last_woke_at": null - }, - { - "agent_id": "epiphany.life", - "role_id": "reorientation", - "display_name": "Life", - "initiative_speed": 1.04, - "next_ready_at": 0.0, - "reaction_bias": 0.86, - "interrupt_threshold": 0.44, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Protects continuity; must not fake survived context." - ], - "last_action_id": null, - "last_woke_at": null - }, - { - "agent_id": "epiphany.face", - "role_id": "face", - "display_name": "Face", - "initiative_speed": 1.12, - "next_ready_at": 10.714286, - "reaction_bias": 0.84, - "interrupt_threshold": 0.52, - "current_load": 0.0, - "status": "active", - "constraints": [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - "Publicly translates agent thought into #aquarium only; must not moderate or speak outside the room." - ], - "last_action_id": "heartbeat.face.work", - "last_woke_at": "2026-05-05T12:40:47+00:00" - } - ], - "history": [ - { - "ts": "2026-05-05T12:17:57+00:00", - "scheduleId": "epiphany-heartbeat-implementation", - "selectedRole": "implementation", - "selectedAgentId": "epiphany.hands", - "actionId": "heartbeat.implementation.work", - "actionType": "role_work", - "coordinatorAction": "continueImplementation", - "targetRole": null, - "workRole": "implementation", - "sceneClock": 0.0, - "nextReadyAt": 8.108108 - }, - { - "ts": "2026-05-05T12:25:10+00:00", - "scheduleId": "epiphany-heartbeat-idle-self", - "selectedRole": "coordinator", - "selectedAgentId": "epiphany.self", - "actionId": "heartbeat.coordinator.ruminate", - "actionType": "ruminate_memory", - "coordinatorAction": null, - "targetRole": null, - "workRole": null, - "sceneClock": 0.0, - "nextReadyAt": 1.5625 - }, - { - "ts": "2026-05-05T12:30:31+00:00", - "scheduleId": "epiphany-heartbeat-face", - "selectedRole": "face", - "selectedAgentId": "epiphany.face", - "actionId": "heartbeat.face.work", - "actionType": "role_work", - "coordinatorAction": "surfaceAgentThoughts", - "targetRole": null, - "workRole": "face", - "sceneClock": 0.0, - "nextReadyAt": 5.357143 - }, - { - "ts": "2026-05-05T12:40:47+00:00", - "scheduleId": "epiphany-gui-heartbeat-1777984847982915800-2820", - "selectedRole": "face", - "selectedAgentId": "epiphany.face", - "actionId": "heartbeat.face.work", - "actionType": "role_work", - "coordinatorAction": "surfaceAgentThoughts", - "targetRole": null, - "workRole": "face", - "sceneClock": 5.357143, - "nextReadyAt": 10.714286 - } - ] -} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 203bb6af..71cf3df1 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -84,3 +84,4 @@ {"ts": "2026-05-06T03:05:00+00:00", "type": "implementation", "status": "ok", "note": "Created the dedicated GameCult/cultcache-rs repo and wired it into EpiphanyAgent as vendor/cultcache-rs. The Rust API follows CultCache ergonomics: domain structs implement CultCacheDocument, consumers register/get/put typed domain values directly, entries are keyed by type::key, backing stores are persistence adapters, and SingleFileMessagePackBackingStore provides the initial canonical MessagePack store."} {"ts": "2026-05-06T03:46:28+00:00", "type": "implementation", "status": "ok", "note": "Integrated CultCache into the first live Epiphany state surface: heartbeat initiative state now has epiphany-core::EpiphanyHeartbeatStateEntry, an epiphany-heartbeat-store migrate/project/status bridge, committed state/agent-heartbeats.msgpack, and heartbeat status reflects the backing store while JSON remains the reviewable projection."} {"ts": "2026-05-06T04:00:43+00:00", "type": "architecture", "status": "ok", "note": "Clarified CultCache integration boundary: Epiphany should treat JSON heartbeat state as a temporary Python-tool compatibility shim. General CultCache inspection, polyglot schema sync, domain-type loading, and debug display tooling belong in CultLib/CultCache rather than becoming Epiphany-specific JSON shadow state."} +{"ts": "2026-05-06T04:17:45+00:00", "type": "implementation", "status": "ok", "note": "Heartbeat initiative state is now native CultCache: epiphany-core owns init/status/tick/complete over state/agent-heartbeats.msgpack, tools/epiphany_agent_heartbeat.py delegates to the Rust binary and only handles Python-owned role-memory patch glue, and the tracked JSON heartbeat state file was removed."} diff --git a/state/map.yaml b/state/map.yaml index 9c5c18c7..c5fe89f1 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -127,7 +127,7 @@ accepted_design: - Specialist prompts are role-distilled instead of generic and their live text is config-backed in app-server: modeling/checkpoint is the Body of code, dataflow, seams, and frontier; research/scout is the Eyes prompt surface for existing work, vendor guidance, libraries, papers, and anti-Greenspun source selection; implementation is the Hands, the main coding lane and actuator rather than a `roleLaunch` specialist; verification/review is the Soul of promise, invariants, evidence, and user truth; reorientation is Life across compaction and source drift; coordinator is the read-only Self that routes attention without implementing, verifying, promoting, or accepting; Face is the public Discord #aquarium surface that translates agent thought-weather without moderating or leaking sealed thought. - Epiphany prompt surfaces now carry a shared Ghostlight-derived persistent memory projection before lane-specific text: prompt is not memory, durable typed state is the mind, personality and protected values are first-class salience handles, and every lane is explicitly responsible for making its own memory/model/prompt/evidence habit sharper or naming the needed repair. Each lane also states that self-improvement in its own role language: Imagination selects futures, Body clarifies anatomy, Eyes sees earlier, Hands touches source more precisely, Soul becomes harder to fool, Life loses less continuity, Self routes repair, and Face becomes clearer at turning inner weather into useful social presence. - Specialist self-memory now has a bounded Ghostlight-shaped persistence surface under `state/agents`: Imagination, Body, Eyes, Hands, Soul, Life, Self, and Face each have an individual role dossier for identity, personality, semantic/episodic/relationship memory, goals, and values. These files are lane memory only; project truth remains in authoritative `EpiphanyThreadState`. - - `state/agent-heartbeats.json`, `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, and `tools/epiphany_agent_heartbeat.py` are the first Ghostlight-derived heartbeat initiative seam. The harness sets a target heartbeat rate; participants carry initiative speed, next-ready time, reaction bias, interrupt threshold, current load, status, and constraints; pending coordinator work can pull its owning lane through a reaction window; otherwise the earliest ready active lane wins the slot. If the winner has no routeable work, it ruminates on role quality and may apply a bounded selfPatch through the normal coordinator-reviewed memory rules. Face can win `surfaceAgentThoughts` or `discordAquariumChat` work slots. The typed CultCache MessagePack store is the durable Rust persistence seam; JSON remains only a temporary Python-tool compatibility shim, not the desired inspection surface. + - `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, the `epiphany-heartbeat-store` binary, and `tools/epiphany_agent_heartbeat.py` are the first Ghostlight-derived heartbeat initiative seam. The harness sets a target heartbeat rate; participants carry initiative speed, next-ready time, reaction bias, interrupt threshold, current load, status, and constraints; pending coordinator work can pull its owning lane through a reaction window; otherwise the earliest ready active lane wins the slot. If the winner has no routeable work, it ruminates on role quality and may apply a bounded selfPatch through the normal coordinator-reviewed memory rules. Face can win `surfaceAgentThoughts` or `discordAquariumChat` work slots. The typed CultCache MessagePack store is the durable persistence seam; JSON state is gone. - CultCache inspection, cross-language schema synchronization, and debug display tooling belong in CultLib, not in EpiphanyAgent. Epiphany should consume typed CultCache documents and expose product-specific status through its API, while general polyglot domain loading/inspection lives with the shared CultCache ecosystem. - VoidBot's current routine is the reference for the next Epiphany heartbeat/state substrate: work, rumination, and sleep turns; completion-gated cooldown; typed CultCache state; Qdrant-backed memory vectors; resonance/incubation/dream state; and Aquarium-visible internals. The first MessagePack canonical state slice is now the heartbeat store through CultCache-compatible typed Rust state. See `notes/voidbot-routine-adoption-plan.md`. - The Rust CultCache-compatible contract now lives in dedicated upstream `https://github.com/GameCult/cultcache-rs` and is vendored as `vendor/cultcache-rs`. Epiphany should consume it as the canonical typed MessagePack persistence seam instead of growing an embedded local copy. @@ -187,7 +187,7 @@ landed_baseline: - Phase 6 Aquarium graph and Rider bridge slice: the Tauri/React/WebGL Aquarium embeds the adjacent EpiphanyGraph viewer over typed graph state, `tools/epiphany_rider_bridge.py` writes Rider/source-context artifacts, Aquarium Inspect Rider surfaces those artifacts, and `integrations/rider` scaffolds the first frontend-only Rider tool-window/context-action plugin. - Phase 6 role self-memory slice: Ghostlight-shaped role dossiers live under `state/agents`, specialists may request bounded `selfPatch` lane-memory mutations, coordinator review projects acceptance/refusal reasons through `selfPersistence`, and GUI/coordinator accept paths apply accepted requests with `tools/epiphany_agent_memory.py`. - Phase 6 Face public-surface slice: `state/agents/face.agent-state.json`, Face prompt text, `state/face-discord.json`, and `tools/epiphany_face_discord.py` establish Face as the public #aquarium-only translator of Epiphany agent thought-weather, without VoidBot's moderation authority. - - Phase 6 heartbeat initiative slice: `tools/epiphany_agent_heartbeat.py`, `state/agent-heartbeats.json`, `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, the `epiphany-heartbeat-store` bridge binary, and heartbeat smoke coverage borrow Ghostlight initiative scheduling so Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life compete for heartbeat slots; idle slots become bounded memory rumination instead of fake project work, and the first live state surface can round-trip through typed CultCache MessagePack. + - Phase 6 heartbeat initiative slice: `tools/epiphany_agent_heartbeat.py`, `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, the `epiphany-heartbeat-store` binary, and heartbeat smoke coverage borrow Ghostlight initiative scheduling so Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life compete for heartbeat slots; idle slots become bounded memory rumination instead of fake project work, and the first live state surface now ticks/completes through typed CultCache MessagePack instead of JSON state. guardrails: - Use `tools/epiphany_phase5_smoke.py` before modifying update, distill, propose, promote, read-projection, or notification behavior. - Use `tools/epiphany_phase6_scene_smoke.py` before modifying scene projection behavior. diff --git a/tools/epiphany_agent_heartbeat.py b/tools/epiphany_agent_heartbeat.py index ea9e682b..8da584b1 100644 --- a/tools/epiphany_agent_heartbeat.py +++ b/tools/epiphany_agent_heartbeat.py @@ -1,9 +1,10 @@ from __future__ import annotations import argparse -from datetime import datetime, timezone import json +import os from pathlib import Path +import subprocess import sys from tempfile import TemporaryDirectory from typing import Any @@ -18,8 +19,8 @@ ROOT = Path(__file__).resolve().parents[1] DEFAULT_HEARTBEAT_STATE = ROOT / "state" / "agent-heartbeats.json" DEFAULT_HEARTBEAT_STORE = ROOT / "state" / "agent-heartbeats.msgpack" DEFAULT_ARTIFACT_DIR = ROOT / ".epiphany-heartbeats" -SCHEMA_VERSION = "epiphany.agent_heartbeat.v0" -STATUS_SCHEMA_VERSION = "epiphany.agent_heartbeat_status.v0" +HEARTBEAT_STORE_BIN = "epiphany-heartbeat-store" +HEARTBEAT_STORE_EXE = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / "epiphany-heartbeat-store.exe" INITIATIVE_SCHEMA_VERSION = "ghostlight.initiative_schedule.v0" GHOSTLIGHT_ACTION_TYPES = { "speak", @@ -62,230 +63,40 @@ DISPLAY_NAMES = { "reorientation": "Life", } -INITIATIVE_SPEEDS = { - "coordinator": 1.28, - "face": 1.12, - "imagination": 0.82, - "research": 0.78, - "modeling": 0.92, - "implementation": 0.74, - "verification": 0.88, - "reorientation": 1.04, -} - -REACTION_BIAS = { - "coordinator": 0.88, - "face": 0.84, - "imagination": 0.54, - "research": 0.62, - "modeling": 0.74, - "implementation": 0.58, - "verification": 0.82, - "reorientation": 0.86, -} - -INTERRUPT_THRESHOLD = { - "coordinator": 0.42, - "face": 0.52, - "imagination": 0.64, - "research": 0.58, - "modeling": 0.5, - "implementation": 0.5, - "verification": 0.48, - "reorientation": 0.44, -} - -WORK_ACTIONS = { - "prepareCheckpoint": "coordinator", - "surfaceAgentThoughts": "face", - "discordAquariumChat": "face", - "continueImplementation": "implementation", - "launchImagination": "imagination", - "readImaginationResult": "imagination", - "reviewImaginationResult": "imagination", - "launchModeling": "modeling", - "readModelingResult": "modeling", - "reviewModelingResult": "modeling", - "launchVerification": "verification", - "readVerificationResult": "verification", - "reviewVerificationResult": "verification", - "launchReorientWorker": "reorientation", - "readReorientResult": "reorientation", - "acceptReorientResult": "reorientation", - "compactRehydrateReorient": "reorientation", - "regatherManually": "reorientation", -} - - -def now_iso() -> str: - return datetime.now(timezone.utc).replace(microsecond=0).isoformat() - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8")) - - def write_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, indent=2, sort_keys=False) + "\n", encoding="utf-8") -def latest_json_artifacts(artifact_dir: Path, *, limit: int = 8) -> list[dict[str, Any]]: - if not artifact_dir.exists(): - return [] - artifacts: list[dict[str, Any]] = [] - for path in sorted(artifact_dir.glob("*.json"), key=lambda item: item.stat().st_mtime, reverse=True): - try: - payload = load_json(path) - except (OSError, json.JSONDecodeError): - continue - artifacts.append( - { - "path": str(path), - "name": path.name, - "modifiedAt": datetime.fromtimestamp( - path.stat().st_mtime, timezone.utc - ).replace(microsecond=0).isoformat(), - "schemaVersion": payload.get("schema_version") if isinstance(payload, dict) else None, - "kind": path.suffixes[-2].lstrip(".") if len(path.suffixes) > 1 else "json", - "summary": artifact_summary(payload), - } - ) - if len(artifacts) >= limit: - break - return artifacts - - -def cultcache_store_status(store_file: Path = DEFAULT_HEARTBEAT_STORE) -> dict[str, Any]: - if not store_file.exists(): - return { - "storeFile": str(store_file), - "present": False, - "sizeBytes": None, - "modifiedAt": None, - } - stat = store_file.stat() - return { - "storeFile": str(store_file), - "present": True, - "sizeBytes": stat.st_size, - "modifiedAt": datetime.fromtimestamp(stat.st_mtime, timezone.utc).replace(microsecond=0).isoformat(), - "entryType": "epiphany.agent_heartbeat", - "entryKey": "default", - } - - -def artifact_summary(payload: Any) -> dict[str, Any]: - if not isinstance(payload, dict): - return {"type": type(payload).__name__} - event = payload if payload.get("actionId") else payload.get("event") - selection = payload.get("next_actor_selection") or payload.get("nextActorSelection") - if isinstance(event, dict): - return { - "selectedRole": event.get("selectedRole"), - "actionType": event.get("actionType"), - "actionId": event.get("actionId"), - "coordinatorAction": event.get("coordinatorAction"), - } - if isinstance(selection, dict): - return { - "selectionKind": selection.get("selection_kind") or selection.get("selectionKind"), - "selectedActorId": selection.get("selected_actor_id") or selection.get("selectedActorId"), - } - return { - "keys": sorted(str(key) for key in payload.keys())[:8], - } - - -def default_state(*, target_heartbeat_rate: float = 1.0) -> dict[str, Any]: - return { - "schema_version": SCHEMA_VERSION, - "target_heartbeat_rate": target_heartbeat_rate, - "scene_clock": 0.0, - "selection_policy": { - "mode": "readiness_queue", - "reaction_precedence": True, - "minimum_speed": 0.2, - "tie_breakers": [ - "reaction_readiness_desc", - "next_ready_at_asc", - "initiative_speed_desc", - "stable_actor_id_asc", - ], - }, - "pacing_policy": { - "cooldown_starts_after_turn_completion": True, - "work_base_recovery": 6.0, - "idle_base_recovery": 2.0, - "sleep_heartbeat_rate_multiplier": 0.05, - "minimum_effective_rate": 0.001, - }, - "participants": [ - { - "agent_id": agent_id_for_role(role_id), - "role_id": role_id, - "display_name": DISPLAY_NAMES[role_id], - "initiative_speed": INITIATIVE_SPEEDS[role_id], - "next_ready_at": 0.0, - "reaction_bias": REACTION_BIAS[role_id], - "interrupt_threshold": INTERRUPT_THRESHOLD[role_id], - "current_load": 0.0, - "status": "active", - "constraints": participant_constraints(role_id), - "last_action_id": None, - "last_woke_at": None, - "last_finished_at": None, - "pending_turn": None, - } - for role_id in ROLE_ORDER - ], - "history": [], - } - - -def agent_id_for_role(role_id: str) -> str: - return ROLE_TARGETS[role_id][0] - - -def participant_constraints(role_id: str) -> list[str]: - base = [ - "Runs Ghostlight-shaped persistent role memory.", - "May improve lane memory when awake and idle.", - "Project truth belongs in EpiphanyThreadState, not role memory.", - ] - role_specific = { - "coordinator": "Routes and reviews; must not implement, verify, or accept its own comfort.", - "face": "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.", - "reorientation": "Protects continuity; must not fake survived context.", - } - return [*base, role_specific[role_id]] - - -def load_state(path: Path, *, target_heartbeat_rate: float) -> dict[str, Any]: - if not path.exists(): - state = default_state(target_heartbeat_rate=target_heartbeat_rate) - write_json(path, state) - return state - state = load_json(path) - if state.get("schema_version") != SCHEMA_VERSION: - raise ValueError(f"{path} has wrong schema_version") - if target_heartbeat_rate > 0: - state["target_heartbeat_rate"] = target_heartbeat_rate - present = {item.get("role_id") for item in state.get("participants", []) if isinstance(item, dict)} - for role_id in ROLE_ORDER: - if role_id not in present: - state.setdefault("participants", []).append(default_state()["participants"][ROLE_ORDER.index(role_id)]) - state.setdefault("pacing_policy", default_state()["pacing_policy"]) - for participant in state.get("participants", []): - if isinstance(participant, dict): - participant.setdefault("last_finished_at", None) - participant.setdefault("pending_turn", None) - return state +def native_heartbeat_command(*args: str) -> dict[str, Any]: + if HEARTBEAT_STORE_EXE.exists(): + command = [str(HEARTBEAT_STORE_EXE), *args] + else: + command = [ + "cargo", + "run", + "--quiet", + "--manifest-path", + str(ROOT / "epiphany-core" / "Cargo.toml"), + "--bin", + HEARTBEAT_STORE_BIN, + "--", + *args, + ] + completed = subprocess.run( + command, + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + if completed.returncode != 0: + message = completed.stderr.strip() or completed.stdout.strip() or f"{HEARTBEAT_STORE_BIN} failed" + raise ValueError(message) + try: + return json.loads(completed.stdout) + except json.JSONDecodeError as exc: + raise ValueError(f"{HEARTBEAT_STORE_BIN} returned non-JSON output: {completed.stdout}") from exc def heartbeat_status( @@ -296,466 +107,80 @@ def heartbeat_status( target_heartbeat_rate: float = 0.0, artifact_limit: int = 8, ) -> dict[str, Any]: - if not state_file.exists(): - return { - "schema_version": STATUS_SCHEMA_VERSION, - "ok": True, - "status": "missing", - "stateFile": str(state_file), - "cultCacheStore": cultcache_store_status(store_file), - "artifactDir": str(artifact_dir), - "targetHeartbeatRate": target_heartbeat_rate if target_heartbeat_rate > 0 else None, - "sceneClock": None, - "participants": [], - "latestEvent": None, - "history": [], - "latestArtifacts": latest_json_artifacts(artifact_dir, limit=artifact_limit), - "availableActions": ["init", "tick", "complete", "status"], - } - state = load_json(state_file) - if state.get("schema_version") != SCHEMA_VERSION: - raise ValueError(f"{state_file} has wrong schema_version") - participants = [] - for participant in state.get("participants", []): - if not isinstance(participant, dict): - continue - participants.append( - { - "agentId": participant.get("agent_id"), - "roleId": participant.get("role_id"), - "displayName": participant.get("display_name"), - "initiativeSpeed": participant.get("initiative_speed"), - "nextReadyAt": participant.get("next_ready_at"), - "reactionBias": participant.get("reaction_bias"), - "interruptThreshold": participant.get("interrupt_threshold"), - "currentLoad": participant.get("current_load"), - "status": participant.get("status"), - "lastActionId": participant.get("last_action_id"), - "lastWokeAt": participant.get("last_woke_at"), - "lastFinishedAt": participant.get("last_finished_at"), - "pendingTurn": participant.get("pending_turn"), - } - ) - history = [ - item - for item in state.get("history", [])[-artifact_limit:] - if isinstance(item, dict) - ] - return { - "schema_version": STATUS_SCHEMA_VERSION, - "ok": True, - "status": "ready", - "stateFile": str(state_file), - "cultCacheStore": cultcache_store_status(store_file), - "artifactDir": str(artifact_dir), - "targetHeartbeatRate": state.get("target_heartbeat_rate"), - "sceneClock": state.get("scene_clock"), - "participants": participants, - "latestEvent": history[-1] if history else None, - "history": history, - "latestArtifacts": latest_json_artifacts(artifact_dir, limit=artifact_limit), - "availableActions": ["init", "tick", "complete", "status"], - } - - -def work_role_for_action(action: str | None, target_role: str | None) -> str | None: - if target_role in ROLE_TARGETS: - return target_role - if action in WORK_ACTIONS: - return WORK_ACTIONS[action] - return None - - -def participant_by_role(state: dict[str, Any], role_id: str) -> dict[str, Any]: - for participant in state["participants"]: - if participant.get("role_id") == role_id: - return participant - raise KeyError(role_id) - - -def active_participants(state: dict[str, Any]) -> list[dict[str, Any]]: - return [ - item - for item in state["participants"] - if item.get("status") == "active" and not is_turn_pending(item) - ] - - -def is_turn_pending(participant: dict[str, Any]) -> bool: - pending = participant.get("pending_turn") - return isinstance(pending, dict) and pending.get("status") == "running" - - -def readiness_snapshot( - participants: list[dict[str, Any]], - *, - work_role: str | None, - urgency: float, -) -> list[dict[str, Any]]: - snapshot: list[dict[str, Any]] = [] - for participant in participants: - eligible = participant.get("role_id") == work_role and work_role is not None - reaction_readiness = None - if eligible: - reaction_readiness = round( - float(participant["reaction_bias"]) * urgency - float(participant.get("current_load", 0.0)), - 6, - ) - snapshot.append( - { - "agent_id": participant["agent_id"], - "next_ready_at": participant["next_ready_at"], - "reaction_readiness": reaction_readiness, - "eligible_for_reaction": eligible, - } - ) - return snapshot - - -def select_participant( - state: dict[str, Any], - *, - work_role: str | None, - urgency: float, -) -> tuple[dict[str, Any], str, str | None]: - participants = active_participants(state) - if not participants: - raise ValueError("heartbeat has no active participants") - if work_role: - candidate = participant_by_role(state, work_role) - if is_turn_pending(candidate): - pending = candidate.get("pending_turn") or {} - raise ValueError( - f"{candidate['display_name']} already has running heartbeat turn {pending.get('actionId')}; complete it before scheduling another" - ) - reaction_readiness = float(candidate["reaction_bias"]) * urgency - float(candidate.get("current_load", 0.0)) - if ( - candidate.get("status") == "active" - and not is_turn_pending(candidate) - and reaction_readiness >= float(candidate["interrupt_threshold"]) - ): - return candidate, "reaction_interrupt", ( - f"{candidate['display_name']} won a heartbeat reaction window for pending {work_role} work." - ) - selected = min( - participants, - key=lambda item: ( - float(item["next_ready_at"]), - -float(item["initiative_speed"]), - str(item["agent_id"]), - ), + return native_heartbeat_command( + "status", + "--store", + str(store_file), + "--artifact-dir", + str(artifact_dir), + "--target-heartbeat-rate", + str(target_heartbeat_rate), + "--limit", + str(artifact_limit), ) - return selected, "scheduled_turn", ( - "No pending work cleared a reaction threshold; earliest ready active lane won the heartbeat slot." - ) - - -def action_for_selection( - selected: dict[str, Any], - *, - work_role: str | None, - coordinator_action: str | None, - target_heartbeat_rate: float, - pacing_policy: dict[str, Any], -) -> tuple[str, str, float, float, float, str]: - role_id = selected["role_id"] - minimum_rate = max(float(pacing_policy.get("minimum_effective_rate", 0.001)), 0.001) - if role_id == work_role: - heartbeat_rate = max(target_heartbeat_rate, minimum_rate) - action_id = f"heartbeat.{role_id}.work" - return ( - action_id, - "mixed", - float(pacing_policy.get("work_base_recovery", 6.0)) / heartbeat_rate, - 4.0, - 0.45, - f"Wake {selected['display_name']} for coordinator action {coordinator_action or 'pending work'}.", - ) - sleep_multiplier = max(float(pacing_policy.get("sleep_heartbeat_rate_multiplier", 0.18)), minimum_rate) - heartbeat_rate = max(target_heartbeat_rate * sleep_multiplier, minimum_rate) - action_id = f"heartbeat.{role_id}.ruminate" - return ( - action_id, - "wait", - float(pacing_policy.get("idle_base_recovery", 2.0)) / heartbeat_rate, - 1.0, - 0.9, - f"{selected['display_name']} has no actionable lane work; ruminate and distill role memory.", - ) - - -def rumination_patch(role_id: str, action_id: str) -> dict[str, Any]: - agent_id = agent_id_for_role(role_id) - display_name = DISPLAY_NAMES[role_id] - memory_id = f"mem-{role_id}-heartbeat-rumination" - goal_id = f"goal-{role_id}-heartbeat-self-distill" - return { - "agentId": agent_id, - "reason": ( - f"{display_name} won an idle heartbeat slot and should preserve the habit of using idle wakeups " - "to distill role memory instead of manufacturing project work." - ), - "semanticMemories": [ - { - "memoryId": memory_id, - "summary": ( - "When a heartbeat wakes this lane and no coordinator-approved work is available, " - "the correct move is to ruminate on role quality, cut stale memory, and return a bounded " - "self-memory improvement rather than inventing project authority." - ), - "salience": 0.78, - "confidence": 0.88, - } - ], - "goals": [ - { - "goalId": goal_id, - "description": "Use idle heartbeat slots to become sharper at this lane's own work before touching project state.", - "scope": "life", - "priority": 0.82, - "emotionalStake": "An idle organ that invents work becomes noise in the bloodstream.", - "status": "active", - } - ], - "privateNotes": [ - f"Last idle heartbeat action `{action_id}` chose rumination over fake urgency.", - ], - } - - -def tick_once( - state: dict[str, Any], - *, - coordinator_action: str | None, - target_role: str | None, - urgency: float, - apply_rumination: bool, - agent_dir: Path, - schedule_id: str, - source_scene_ref: str, - defer_completion: bool = False, -) -> dict[str, Any]: - rate = max(float(state.get("target_heartbeat_rate", 1.0)), 0.001) - pacing_policy = state.setdefault("pacing_policy", default_state()["pacing_policy"]) - work_role = work_role_for_action(coordinator_action, target_role) - selected, selection_kind, selection_reason = select_participant( - state, - work_role=work_role, - urgency=urgency, - ) - action_id, action_type, base_recovery, initiative_cost, interruptibility, action_reason = ( - action_for_selection( - selected, - work_role=work_role, - coordinator_action=coordinator_action, - target_heartbeat_rate=rate, - pacing_policy=pacing_policy, - ) - ) - scene_clock = max(float(state["scene_clock"]), float(selected["next_ready_at"])) - recovery = base_recovery / max(float(selected["initiative_speed"]), float(state["selection_policy"]["minimum_speed"])) - pending_turn = { - "status": "running", - "scheduleId": schedule_id, - "actionId": action_id, - "actionType": "ruminate_memory" if action_id.endswith(".ruminate") else "role_work", - "startedAt": now_iso(), - "startedSceneClock": round(scene_clock, 6), - "baseRecovery": round(base_recovery, 6), - "recovery": round(recovery, 6), - "cooldownPolicy": "after_turn_completion", - } - selected["pending_turn"] = pending_turn - selected["last_action_id"] = action_id - selected["last_woke_at"] = now_iso() - selected["current_load"] = round(min(1.0, max(0.0, float(selected.get("current_load", 0.0)) * 0.75)), 6) - state["scene_clock"] = round(scene_clock, 6) - if not defer_completion: - complete_pending_turn(state, selected) - - snapshot = readiness_snapshot(active_participants(state), work_role=work_role, urgency=urgency) - schedule = { - "schema_version": INITIATIVE_SCHEMA_VERSION, - "schedule_id": schedule_id, - "source_scene_ref": source_scene_ref, - "scene_clock": state["scene_clock"], - "participants": [ - { - "agent_id": item["agent_id"], - "display_name": item["display_name"], - "initiative_speed": item["initiative_speed"], - "next_ready_at": item["next_ready_at"], - "reaction_bias": item["reaction_bias"], - "interrupt_threshold": item["interrupt_threshold"], - "current_load": item["current_load"], - "status": item["status"], - "pending_turn": item.get("pending_turn"), - "constraints": item["constraints"], - } - for item in state["participants"] - ], - "action_catalog": [ - { - "action_id": action_id, - "actor_id": selected["agent_id"], - "action_type": action_type, - "action_scale": "short" if action_id.endswith(".ruminate") else "standard", - "base_recovery": base_recovery, - "initiative_cost": initiative_cost, - "interruptibility": interruptibility, - "commitment": 0.25 if action_id.endswith(".ruminate") else 0.65, - "local_affordance_basis": [ - action_reason, - "Heartbeat slots control opportunity, not project authority.", - "Cooldown starts only after the heartbeat turn completes, so an unfinished sub-agent thread cannot be heartbeaten again.", - ], - } - ], - "reaction_windows": [ - { - "window_id": f"{schedule_id}.pending-work", - "trigger_event_ref": source_scene_ref, - "urgency": urgency, - "eligible_actor_ids": [agent_id_for_role(work_role)] if work_role else [], - "allowed_action_scales": ["short", "standard"], - "expires_at": round(state["scene_clock"] + 1.0, 6), - "notes": "Pending coordinator work can pull its owning lane forward only if readiness clears threshold.", - } - ] - if work_role - else [], - "selection_policy": state["selection_policy"], - "next_actor_selection": { - "selection_kind": selection_kind, - "selected_actor_id": selected["agent_id"], - "selected_action_ids": [action_id], - "scene_clock_after_selection": state["scene_clock"], - "selection_reason": selection_reason, - "override_reason": None, - "readiness_snapshot": snapshot, - }, - "review_notes": [ - "Epiphany heartbeat uses Ghostlight initiative timing as a harness scheduling receipt.", - "A selected idle lane may ruminate and request bounded self-memory mutation; it may not invent project work.", - "When no coordinator work is active, idle rumination uses the sleep heartbeat multiplier so the swarm dreams slowly instead of thrashing.", - ], - } - - rumination = None - if action_id.endswith(".ruminate"): - patch = rumination_patch(selected["role_id"], action_id) - rumination = { - "roleId": selected["role_id"], - "selfPatch": patch, - "result": apply_self_patch(selected["role_id"], patch, agent_dir=agent_dir) - if apply_rumination - else None, - "applied": apply_rumination, - } - - event = { - "ts": now_iso(), - "scheduleId": schedule_id, - "selectedRole": selected["role_id"], - "selectedAgentId": selected["agent_id"], - "actionId": action_id, - "actionType": "ruminate_memory" if action_id.endswith(".ruminate") else "role_work", - "coordinatorAction": coordinator_action, - "targetRole": target_role, - "workRole": work_role, - "sceneClock": state["scene_clock"], - "nextReadyAt": selected["next_ready_at"], - "turnStatus": "running" if defer_completion else "completed", - "cooldownStartedAfterCompletion": True, - } - state.setdefault("history", []).append(event) - state["history"] = state["history"][-128:] - return {"event": event, "schedule": schedule, "rumination": rumination} - - -def complete_pending_turn(state: dict[str, Any], participant: dict[str, Any]) -> dict[str, Any]: - pending = participant.get("pending_turn") - if not isinstance(pending, dict) or pending.get("status") != "running": - raise ValueError(f"{participant.get('role_id')} has no running heartbeat turn") - scene_clock = max(float(state.get("scene_clock", 0.0)), float(pending.get("startedSceneClock", 0.0))) - recovery = float(pending.get("recovery", 0.0)) - participant["next_ready_at"] = round(scene_clock + recovery, 6) - participant["last_finished_at"] = now_iso() - completed = { - **pending, - "status": "completed", - "completedAt": participant["last_finished_at"], - "completedSceneClock": round(scene_clock, 6), - "nextReadyAt": participant["next_ready_at"], - } - participant["pending_turn"] = None - return completed def run_tick(args: argparse.Namespace) -> dict[str, Any]: - state = load_state(args.state_file, target_heartbeat_rate=args.target_heartbeat_rate) errors = validate_all(args.agent_dir) if errors: raise ValueError("agent memory validation failed: " + "; ".join(errors)) - result = tick_once( - state, - coordinator_action=args.coordinator_action, - target_role=args.target_role, - urgency=args.urgency, - apply_rumination=args.apply_rumination, - agent_dir=args.agent_dir, - schedule_id=args.schedule_id, - source_scene_ref=args.source_scene_ref, - defer_completion=getattr(args, "defer_completion", False), - ) - write_json(args.state_file, state) - args.artifact_dir.mkdir(parents=True, exist_ok=True) - write_json(args.artifact_dir / f"{args.schedule_id}.initiative.json", result["schedule"]) - write_json(args.artifact_dir / f"{args.schedule_id}.event.json", result["event"]) - if result["rumination"] is not None: - write_json(args.artifact_dir / f"{args.schedule_id}.rumination.json", result["rumination"]) - return { - "ok": True, - "stateFile": str(args.state_file), - "artifactDir": str(args.artifact_dir), - **result, - } + store_file = getattr(args, "store_file", DEFAULT_HEARTBEAT_STORE) + command = [ + "tick", + "--store", + str(store_file), + "--artifact-dir", + str(args.artifact_dir), + "--target-heartbeat-rate", + str(args.target_heartbeat_rate), + "--urgency", + str(args.urgency), + "--schedule-id", + args.schedule_id, + "--source-scene-ref", + args.source_scene_ref, + ] + if args.coordinator_action: + command.extend(["--coordinator-action", args.coordinator_action]) + if args.target_role: + command.extend(["--target-role", args.target_role]) + if getattr(args, "defer_completion", False): + command.append("--defer-completion") + result = native_heartbeat_command(*command) + rumination = result.get("rumination") + if isinstance(rumination, dict) and rumination.get("selfPatch") is not None: + rumination["result"] = ( + apply_self_patch(rumination.get("roleId"), rumination["selfPatch"], agent_dir=args.agent_dir) + if args.apply_rumination + else None + ) + rumination["applied"] = bool(args.apply_rumination) + write_json(args.artifact_dir / f"{args.schedule_id}.rumination.json", rumination) + result["rumination"] = rumination + result.setdefault("stateFile", None) + result["storeFile"] = str(store_file) + result["artifactDir"] = str(args.artifact_dir) + return result def run_complete(args: argparse.Namespace) -> dict[str, Any]: - state = load_state(args.state_file, target_heartbeat_rate=0.0) - participant = participant_by_role(state, args.role) - pending = participant.get("pending_turn") - if not isinstance(pending, dict) or pending.get("status") != "running": - raise ValueError(f"{args.role} has no running heartbeat turn") - if args.action_id and pending.get("actionId") != args.action_id: - raise ValueError( - f"{args.role} pending heartbeat action is {pending.get('actionId')}, not {args.action_id}" - ) - completed = complete_pending_turn(state, participant) - event = { - "ts": now_iso(), - "scheduleId": completed.get("scheduleId"), - "selectedRole": args.role, - "selectedAgentId": participant.get("agent_id"), - "actionId": completed.get("actionId"), - "actionType": completed.get("actionType"), - "turnStatus": "completed", - "sceneClock": state.get("scene_clock"), - "nextReadyAt": participant.get("next_ready_at"), - } - state.setdefault("history", []).append(event) - state["history"] = state["history"][-128:] - write_json(args.state_file, state) - args.artifact_dir.mkdir(parents=True, exist_ok=True) - if completed.get("scheduleId"): - write_json(args.artifact_dir / f"{completed['scheduleId']}.completion.json", {"event": event, "turn": completed}) - return {"ok": True, "event": event, "completedTurn": completed} + store_file = getattr(args, "store_file", DEFAULT_HEARTBEAT_STORE) + command = [ + "complete", + "--store", + str(store_file), + "--artifact-dir", + str(args.artifact_dir), + "--role", + args.role, + ] + if args.action_id: + command.extend(["--action-id", args.action_id]) + return native_heartbeat_command(*command) def run_status(args: argparse.Namespace) -> dict[str, Any]: return heartbeat_status( - state_file=args.state_file, store_file=args.store_file, artifact_dir=args.artifact_dir, target_heartbeat_rate=args.target_heartbeat_rate, @@ -767,13 +192,15 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]: with TemporaryDirectory() as tmp: tmp_dir = Path(tmp) agent_dir = tmp_dir / "agents" - state_file = tmp_dir / "heartbeats.json" + store_file = tmp_dir / "heartbeats.msgpack" artifact_dir = tmp_dir / "artifacts" import shutil shutil.copytree(args.agent_dir, agent_dir) + native_heartbeat_command("init", "--store", str(store_file), "--target-heartbeat-rate", "1.0") first_args = argparse.Namespace( - state_file=state_file, + state_file=None, + store_file=store_file, artifact_dir=artifact_dir, agent_dir=agent_dir, target_heartbeat_rate=1.0, @@ -792,14 +219,16 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]: except ValueError as exc: blocked_repeat = str(exc) complete_args = argparse.Namespace( - state_file=state_file, + state_file=None, + store_file=store_file, artifact_dir=artifact_dir, role="implementation", action_id=work["event"]["actionId"], ) completed = run_complete(complete_args) second_args = argparse.Namespace( - state_file=state_file, + state_file=None, + store_file=store_file, artifact_dir=artifact_dir, agent_dir=agent_dir, target_heartbeat_rate=1.0, @@ -817,7 +246,7 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]: *validate_initiative_schedule_shape(work["schedule"]), *validate_initiative_schedule_shape(idle["schedule"]), ] - state = load_json(state_file) + status = heartbeat_status(store_file=store_file, artifact_dir=artifact_dir) ok = ( work["event"]["selectedRole"] == "implementation" and work["event"]["turnStatus"] == "running" @@ -833,7 +262,7 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]: and (artifact_dir / "smoke-work.initiative.json").exists() and (artifact_dir / "smoke-work.completion.json").exists() and (artifact_dir / "smoke-idle.rumination.json").exists() - and len(state.get("participants", [])) == len(ROLE_ORDER) + and len(status.get("participants", [])) == len(ROLE_ORDER) ) return { "ok": ok, @@ -900,6 +329,7 @@ def build_parser() -> argparse.ArgumentParser: tick = subparsers.add_parser("tick") tick.add_argument("--state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE) + tick.add_argument("--store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE) tick.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR) tick.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_DIR) tick.add_argument("--target-heartbeat-rate", type=float, default=1.0) @@ -917,12 +347,14 @@ def build_parser() -> argparse.ArgumentParser: complete = subparsers.add_parser("complete") complete.add_argument("--state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE) + complete.add_argument("--store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE) complete.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR) complete.add_argument("--role", choices=sorted(ROLE_TARGETS), required=True) complete.add_argument("--action-id") init = subparsers.add_parser("init") init.add_argument("--state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE) + init.add_argument("--store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE) init.add_argument("--target-heartbeat-rate", type=float, default=1.0) status = subparsers.add_parser("status") @@ -943,9 +375,14 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) try: if args.command == "init": - state = default_state(target_heartbeat_rate=args.target_heartbeat_rate) - write_json(args.state_file, state) - print(json.dumps({"ok": True, "stateFile": str(args.state_file)}, indent=2)) + result = native_heartbeat_command( + "init", + "--store", + str(args.store_file), + "--target-heartbeat-rate", + str(args.target_heartbeat_rate), + ) + print(json.dumps(result, indent=2)) return 0 if args.command == "tick": print(json.dumps(run_tick(args), indent=2))