Make heartbeat state native CultCache

This commit is contained in:
Meta Vens 2026-05-06 05:29:28 +01:00
commit 5c9f37ed59
12 changed files with 1254 additions and 934 deletions

1
.gitignore vendored
View file

@ -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

View file

@ -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<PathBuf> = None;
let mut store_path: Option<PathBuf> = None;
let mut projection_path: Option<PathBuf> = None;
let mut artifact_dir: Option<PathBuf> = None;
let mut target_heartbeat_rate = 1.0_f64;
let mut coordinator_action: Option<String> = None;
let mut target_role: Option<String> = 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<String> = None;
let mut action_id: Option<String> = 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<Item = String>, name: &str) -> Result<PathBuf> {
Ok(PathBuf::from(next_value(args, name)?))
}
fn next_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
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 <path> --store <path> [--projection <path>]\n epiphany-heartbeat-store project --store <path> --projection <path>\n epiphany-heartbeat-store status --store <path>"
"usage: epiphany-heartbeat-store init --store <path>\n epiphany-heartbeat-store tick --store <path> --artifact-dir <path> [--coordinator-action <action>] [--defer-completion]\n epiphany-heartbeat-store complete --store <path> --artifact-dir <path> --role <role> [--action-id <id>]\n epiphany-heartbeat-store status --store <path> [--artifact-dir <path>]\n epiphany-heartbeat-store migrate-json --json <path> --store <path> [--projection <path>]\n epiphany-heartbeat-store project --store <path> --projection <path>"
))
}

File diff suppressed because it is too large Load diff

View file

@ -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;

View file

@ -134,8 +134,8 @@ pub fn propose_map_update(input: EpiphanyMapProposalInput) -> Result<EpiphanyMap
};
for path in &code_ref_paths {
let path_code_refs = code_refs_for_path(&code_refs, &path);
let candidate_node_id = graph_node_id(&path);
let path_code_refs = code_refs_for_path(&code_refs, path);
let candidate_node_id = graph_node_id(path);
if let Some(node_match) = find_architecture_node_for_path(
&graphs,
&path_code_refs,
@ -152,7 +152,7 @@ pub fn propose_map_update(input: EpiphanyMapProposalInput) -> Result<EpiphanyMap
active_node_ids.push(node_id.clone());
graphs.architecture.nodes.push(EpiphanyGraphNode {
id: node_id,
title: title_from_path(&path),
title: title_from_path(path),
purpose: truncate_chars(
&format!(
"Candidate implementation surface from verified observation: {}",

View file

@ -549,7 +549,7 @@ fn search_threads() -> NonZero<usize> {
.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);

View file

@ -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.

View file

@ -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.

View file

@ -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
}
]
}

View file

@ -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."}

View file

@ -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.

View file

@ -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))