continuity: bound heartbeat artifact retention

This commit is contained in:
Meta Vens 2026-08-08 22:38:42 +01:00
commit 100d8854fb
12 changed files with 839 additions and 23 deletions

View file

@ -23,6 +23,7 @@ use epiphany_core::pulse_resident_self_heartbeat;
use epiphany_core::pump_heartbeat_store;
use epiphany_core::queue_heartbeat_pending_mention_store;
use epiphany_core::recover_stale_heartbeat_store;
use epiphany_core::retain_heartbeat_pulse_artifacts;
use epiphany_core::run_void_routine_store;
use epiphany_core::tick_heartbeat_store;
use epiphany_core::update_heartbeat_heat_store;
@ -96,6 +97,8 @@ fn main() -> Result<()> {
let mut now_utc: Option<String> = None;
let mut interval_seconds = 120_u64;
let mut max_iterations = 0_u64;
let mut retain_pulse_artifacts = 256_usize;
let mut retention_batch_size = 64_usize;
let mut release_store: Option<PathBuf> = None;
let mut release_runtime_id: Option<String> = None;
let mut release_id: Option<String> = None;
@ -190,6 +193,13 @@ fn main() -> Result<()> {
"--max-iterations" => {
max_iterations = next_value(&mut args, "--max-iterations")?.parse()?
}
"--retain-pulse-artifacts" => {
retain_pulse_artifacts =
next_value(&mut args, "--retain-pulse-artifacts")?.parse()?
}
"--retention-batch-size" => {
retention_batch_size = next_value(&mut args, "--retention-batch-size")?.parse()?
}
"--release-store" => release_store = Some(next_path(&mut args, "--release-store")?),
"--release-runtime-id" => {
release_runtime_id = Some(next_value(&mut args, "--release-runtime-id")?)
@ -299,6 +309,28 @@ fn main() -> Result<()> {
)?;
println!("{}", result);
}
"retain-artifacts" => {
let store_path =
store_path.ok_or_else(|| anyhow!("retain-artifacts requires --store"))?;
let artifact_dir =
artifact_dir.ok_or_else(|| anyhow!("retain-artifacts requires --artifact-dir"))?;
let receipt = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
"schemaVersion": "epiphany.heartbeat.artifact_retention_command.v0",
"status": if receipt.is_some() { "completed" } else { "within-bound" },
"receipt": receipt,
"privateStateExposed": false
})
);
}
"pump" => {
assert_swarm_brake_allows_heartbeat(
&local_verse_store,
@ -559,13 +591,21 @@ fn main() -> Result<()> {
if pulse.status != "idle" {
completed_iterations = iteration;
refused_pulses += u64::from(brake.is_some());
let retention = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
"schemaVersion":"epiphany.heartbeat.serve_pulse.v0", "status":pulse.status,
"owner":"heartbeat", "iteration":iteration, "artifactDir":iteration_dir,
"acknowledgedTerminalId":pulse.acknowledged_terminal_id, "grantId":pulse.grant_id,
"brakeId":brake.as_ref().map(|value| &value.brake_id), "privateStateExposed":false
"brakeId":brake.as_ref().map(|value| &value.brake_id), "retention":retention,
"privateStateExposed":false
})
);
if max_iterations > 0 && completed_iterations >= max_iterations {
@ -578,6 +618,13 @@ fn main() -> Result<()> {
if let Some(brake) = brake {
completed_iterations = iteration;
refused_pulses += 1;
let retention = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
@ -589,7 +636,7 @@ fn main() -> Result<()> {
"artifactDir": iteration_dir,
"brakeId": brake.brake_id,
"brakeScope": brake.scope,
"reason": brake.reason,
"reason": brake.reason, "retention": retention,
"privateStateExposed": false
})
);
@ -609,7 +656,20 @@ fn main() -> Result<()> {
)?;
if persona_pulse["status"] != "idle" {
completed_iterations = iteration;
println!("{}", persona_pulse);
let retention = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
"pulse": persona_pulse, "retention": retention,
"privateStateExposed": false
})
);
if max_iterations > 0 && completed_iterations >= max_iterations {
break;
}
@ -627,6 +687,13 @@ fn main() -> Result<()> {
)?;
completed_iterations = iteration;
completed_routines += 1;
let retention = retain_heartbeat_pulse_artifacts(
&store_path,
&artifact_dir,
retain_pulse_artifacts,
retention_batch_size,
&chrono::Utc::now().to_rfc3339(),
)?;
println!(
"{}",
serde_json::json!({
@ -637,7 +704,7 @@ fn main() -> Result<()> {
"iteration": iteration,
"artifactDir": iteration_dir,
"routineOk": result["ok"],
"routineArtifact": result["artifactPath"],
"routineArtifact": result["artifactPath"], "retention": retention,
"privateStateExposed": false
})
);
@ -696,6 +763,7 @@ fn usage() -> Result<()> {
" epiphany-heartbeat-store heat --store <path> [options]\n",
" epiphany-heartbeat-store complete --store <path> --artifact-dir <path> --role <role> [--action-id <id>]\n",
" epiphany-heartbeat-store repair-stale --store <path> --artifact-dir <path> [options]\n",
" epiphany-heartbeat-store retain-artifacts --store <path> --artifact-dir <path> [--retain-pulse-artifacts <n>] [--retention-batch-size <n>]\n",
" epiphany-heartbeat-store queue-mention --store <path> [options]\n",
" epiphany-heartbeat-store status --store <path> [--artifact-dir <path>]\n",
" epiphany-heartbeat-store routine --store <path> --artifact-dir <path> [options]\n",

View file

@ -15,6 +15,7 @@ use std::path::Path;
mod heartbeat_documents;
mod heartbeat_pacing;
mod heartbeat_projection;
mod heartbeat_retention;
mod heartbeat_roles;
mod heartbeat_store;
pub use heartbeat_documents::*;
@ -30,6 +31,7 @@ use heartbeat_projection::history_event_json;
use heartbeat_projection::pending_turn_json;
use heartbeat_projection::schedule_participant_json;
use heartbeat_projection::selection_policy_json;
pub use heartbeat_retention::retain_heartbeat_pulse_artifacts;
use heartbeat_roles::ROLE_ORDER;
use heartbeat_roles::agent_id_for_role;
pub use heartbeat_roles::default_heartbeat_state;

View file

@ -17,6 +17,18 @@ pub const HEARTBEAT_STALE_TURN_REPAIR_TYPE: &str = "epiphany.heartbeat.stale_tur
pub const HEARTBEAT_STALE_TURN_REPAIR_SCHEMA_VERSION: &str =
"epiphany.heartbeat.stale_turn_repair.v0";
pub const HEARTBEAT_STALE_TURN_REPAIR_LATEST_KEY: &str = "heartbeat/stale-turn-repair/latest";
pub const HEARTBEAT_ARTIFACT_RETENTION_PLAN_TYPE: &str =
"epiphany.heartbeat.artifact_retention_plan";
pub const HEARTBEAT_ARTIFACT_RETENTION_PLAN_SCHEMA_VERSION: &str =
"epiphany.heartbeat.artifact_retention_plan.v0";
pub const HEARTBEAT_ARTIFACT_RETENTION_PLAN_LATEST_KEY: &str =
"heartbeat/artifact-retention-plan/latest";
pub const HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_TYPE: &str =
"epiphany.heartbeat.artifact_retention_receipt";
pub const HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_SCHEMA_VERSION: &str =
"epiphany.heartbeat.artifact_retention_receipt.v0";
pub const HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_LATEST_KEY: &str =
"heartbeat/artifact-retention-receipt/latest";
pub const PERSONA_TURN_REQUEST_SCHEMA_VERSION: &str = "epiphany.persona_turn_request.v0";
pub const PERSONA_TURN_TERMINAL_RECEIPT_SCHEMA_VERSION: &str =
"epiphany.persona_turn_terminal_receipt.v0";
@ -125,6 +137,64 @@ pub struct EpiphanyHeartbeatStaleTurnRepairReceipt {
pub notes: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeartbeatArtifactRetentionMember {
pub directory_name: String,
pub manifest_sha256: String,
pub file_count: u64,
pub byte_count: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "epiphany.heartbeat.artifact_retention_plan",
schema = "EpiphanyHeartbeatArtifactRetentionPlan"
)]
pub struct EpiphanyHeartbeatArtifactRetentionPlan {
#[cultcache(key = 0)]
pub schema_version: String,
#[cultcache(key = 1)]
pub plan_id: String,
#[cultcache(key = 2)]
pub artifact_root: String,
#[cultcache(key = 3)]
pub retain_pulse_count: u64,
#[cultcache(key = 4)]
pub batch_size: u64,
#[cultcache(key = 5)]
pub members: Vec<HeartbeatArtifactRetentionMember>,
#[cultcache(key = 6)]
pub planned_at_utc: String,
#[cultcache(key = 7)]
pub private_state_exposed: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "epiphany.heartbeat.artifact_retention_receipt",
schema = "EpiphanyHeartbeatArtifactRetentionReceipt"
)]
pub struct EpiphanyHeartbeatArtifactRetentionReceipt {
#[cultcache(key = 0)]
pub schema_version: String,
#[cultcache(key = 1)]
pub receipt_id: String,
#[cultcache(key = 2)]
pub plan_id: String,
#[cultcache(key = 3)]
pub status: String,
#[cultcache(key = 4)]
pub deleted_directories: Vec<String>,
#[cultcache(key = 5)]
pub deleted_file_count: u64,
#[cultcache(key = 6)]
pub deleted_byte_count: u64,
#[cultcache(key = 7)]
pub completed_at_utc: String,
#[cultcache(key = 8)]
pub private_state_exposed: bool,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "epiphany.agent_heartbeat",

View file

@ -0,0 +1,550 @@
use super::{
EpiphanyHeartbeatArtifactRetentionPlan, EpiphanyHeartbeatArtifactRetentionReceipt,
HEARTBEAT_ARTIFACT_RETENTION_PLAN_LATEST_KEY, HEARTBEAT_ARTIFACT_RETENTION_PLAN_SCHEMA_VERSION,
HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_LATEST_KEY,
HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_SCHEMA_VERSION, HeartbeatArtifactRetentionMember,
heartbeat_state_cache, load_heartbeat_cognition_entry,
};
use anyhow::{Context, Result, anyhow, bail};
use cultcache_rs::{DatabaseEntry, SingleFileMessagePackBackingStore};
use sha2::{Digest, Sha256};
use std::fs;
use std::path::{Path, PathBuf};
pub fn retain_heartbeat_pulse_artifacts(
store_path: impl AsRef<Path>,
artifact_root: impl AsRef<Path>,
retain_pulse_count: usize,
batch_size: usize,
completed_at_utc: &str,
) -> Result<Option<EpiphanyHeartbeatArtifactRetentionReceipt>> {
if retain_pulse_count == 0 || batch_size == 0 {
bail!("heartbeat artifact retention requires non-zero retain and batch counts");
}
if completed_at_utc.trim().is_empty() {
bail!("heartbeat artifact retention requires completion time");
}
let artifact_root = artifact_root
.as_ref()
.canonicalize()
.with_context(|| format!("failed to resolve {}", artifact_root.as_ref().display()))?;
if !artifact_root.is_dir() {
bail!("heartbeat artifact root is not a directory");
}
if let Some(pending) = pending_retention_plan(store_path.as_ref())? {
if PathBuf::from(&pending.artifact_root) != artifact_root {
bail!("pending heartbeat retention plan belongs to another artifact root");
}
return reconcile_retention_plan(
store_path.as_ref(),
&artifact_root,
&pending,
completed_at_utc,
)
.map(Some);
}
let pulses = pulse_directories(&artifact_root)?;
let threshold = retain_pulse_count
.checked_add(batch_size)
.ok_or_else(|| anyhow!("heartbeat artifact retention threshold overflow"))?;
if pulses.len() <= threshold {
return Ok(None);
}
let retire_count = batch_size.min(pulses.len() - retain_pulse_count);
let members = pulses
.iter()
.take(retire_count)
.map(|(_, path)| artifact_member(&artifact_root, path))
.collect::<Result<Vec<_>>>()?;
if let Some(protected) = protected_latest_cognition_pulse(store_path.as_ref(), &artifact_root)?
&& members
.iter()
.any(|member| member.directory_name == protected)
{
bail!("heartbeat artifact retention refuses the latest cognition artifact pulse");
}
let plan_id = retention_plan_id(&artifact_root, retain_pulse_count, batch_size, &members);
let plan = EpiphanyHeartbeatArtifactRetentionPlan {
schema_version: HEARTBEAT_ARTIFACT_RETENTION_PLAN_SCHEMA_VERSION.to_string(),
plan_id,
artifact_root: artifact_root.display().to_string(),
retain_pulse_count: retain_pulse_count as u64,
batch_size: batch_size as u64,
members,
planned_at_utc: completed_at_utc.to_string(),
private_state_exposed: false,
};
validate_retention_plan(&plan)?;
write_retention_plan(store_path.as_ref(), &plan)?;
reconcile_retention_plan(store_path.as_ref(), &artifact_root, &plan, completed_at_utc).map(Some)
}
fn protected_latest_cognition_pulse(
store_path: &Path,
artifact_root: &Path,
) -> Result<Option<String>> {
let Some(reference) =
load_heartbeat_cognition_entry(store_path)?.and_then(|entry| entry.latest_artifact_ref)
else {
return Ok(None);
};
let path = PathBuf::from(reference);
if !path.exists() {
return Ok(None);
}
let canonical = path.canonicalize()?;
let Ok(relative) = canonical.strip_prefix(artifact_root) else {
return Ok(None);
};
let Some(first) = relative.components().next() else {
return Ok(None);
};
let name = first.as_os_str().to_string_lossy().to_string();
Ok(pulse_sequence(&name).is_some().then_some(name))
}
fn pending_retention_plan(
store_path: &Path,
) -> Result<Option<EpiphanyHeartbeatArtifactRetentionPlan>> {
let cache = heartbeat_state_cache(store_path)?;
let plan = cache.get::<EpiphanyHeartbeatArtifactRetentionPlan>(
HEARTBEAT_ARTIFACT_RETENTION_PLAN_LATEST_KEY,
)?;
let receipt = cache.get::<EpiphanyHeartbeatArtifactRetentionReceipt>(
HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_LATEST_KEY,
)?;
Ok(plan.filter(|plan| {
receipt
.as_ref()
.is_none_or(|receipt| receipt.plan_id != plan.plan_id)
}))
}
fn reconcile_retention_plan(
store_path: &Path,
artifact_root: &Path,
plan: &EpiphanyHeartbeatArtifactRetentionPlan,
completed_at_utc: &str,
) -> Result<EpiphanyHeartbeatArtifactRetentionReceipt> {
validate_retention_plan(plan)?;
for member in &plan.members {
let path = artifact_root.join(&member.directory_name);
if !path.exists() {
continue;
}
let observed = artifact_member(artifact_root, &path)?;
if observed != *member {
bail!(
"heartbeat artifact {:?} changed after retention planning",
member.directory_name
);
}
fs::remove_dir_all(&path)
.with_context(|| format!("failed to retire heartbeat artifact {}", path.display()))?;
}
for member in &plan.members {
if artifact_root.join(&member.directory_name).exists() {
bail!("heartbeat artifact retirement did not remove planned directory");
}
}
let receipt = EpiphanyHeartbeatArtifactRetentionReceipt {
schema_version: HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_SCHEMA_VERSION.to_string(),
receipt_id: format!("artifact-retention-receipt-{}", plan.plan_id),
plan_id: plan.plan_id.clone(),
status: "completed".to_string(),
deleted_directories: plan
.members
.iter()
.map(|member| member.directory_name.clone())
.collect(),
deleted_file_count: plan.members.iter().map(|member| member.file_count).sum(),
deleted_byte_count: plan.members.iter().map(|member| member.byte_count).sum(),
completed_at_utc: completed_at_utc.to_string(),
private_state_exposed: false,
};
validate_retention_receipt(&receipt, plan)?;
write_retention_receipt(store_path, &receipt)?;
Ok(receipt)
}
fn pulse_directories(root: &Path) -> Result<Vec<(u64, PathBuf)>> {
let mut pulses = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
let file_type = entry.file_type()?;
if !file_type.is_dir() {
continue;
}
if file_type.is_symlink() {
bail!("heartbeat artifact retention refuses symlink directories");
}
let name = entry
.file_name()
.into_string()
.map_err(|_| anyhow!("heartbeat artifact directory name is not UTF-8"))?;
let sequence = pulse_sequence(&name)
.ok_or_else(|| anyhow!("heartbeat artifact retention refuses directory {name:?}"))?;
pulses.push((sequence, entry.path()));
}
pulses.sort_by_key(|(sequence, _)| *sequence);
if pulses.windows(2).any(|pair| pair[0].0 == pair[1].0) {
bail!("heartbeat artifact root contains duplicate pulse sequences");
}
Ok(pulses)
}
fn pulse_sequence(name: &str) -> Option<u64> {
let digits = name.strip_prefix("pulse-")?;
(digits.len() == 6 && digits.bytes().all(|byte| byte.is_ascii_digit()))
.then(|| digits.parse().ok())
.flatten()
}
fn artifact_member(root: &Path, directory: &Path) -> Result<HeartbeatArtifactRetentionMember> {
let name = directory
.file_name()
.and_then(|value| value.to_str())
.ok_or_else(|| anyhow!("heartbeat artifact directory has no UTF-8 name"))?;
pulse_sequence(name).ok_or_else(|| anyhow!("invalid heartbeat pulse directory {name:?}"))?;
let canonical = directory.canonicalize()?;
if canonical.parent() != Some(root) {
bail!("heartbeat artifact directory escapes its canonical root");
}
let mut rows = Vec::new();
collect_manifest_rows(&canonical, &canonical, &mut rows)?;
rows.sort();
let mut digest = Sha256::new();
let mut file_count = 0_u64;
let mut byte_count = 0_u64;
for row in rows {
if row.kind == b'F' {
file_count += 1;
byte_count = byte_count
.checked_add(row.byte_count)
.ok_or_else(|| anyhow!("heartbeat artifact byte count overflow"))?;
}
digest.update([row.kind]);
digest.update((row.relative_path.len() as u64).to_be_bytes());
digest.update(row.relative_path.as_bytes());
digest.update(row.byte_count.to_be_bytes());
digest.update(row.sha256.as_bytes());
}
Ok(HeartbeatArtifactRetentionMember {
directory_name: name.to_string(),
manifest_sha256: format!("sha256-{:x}", digest.finalize()),
file_count,
byte_count,
})
}
#[derive(Eq, Ord, PartialEq, PartialOrd)]
struct ManifestRow {
kind: u8,
relative_path: String,
byte_count: u64,
sha256: String,
}
fn collect_manifest_rows(root: &Path, directory: &Path, rows: &mut Vec<ManifestRow>) -> Result<()> {
for entry in fs::read_dir(directory)? {
let entry = entry?;
let file_type = entry.file_type()?;
if file_type.is_symlink() {
bail!("heartbeat artifact retention refuses symlinks");
}
let path = entry.path();
let relative = path
.strip_prefix(root)?
.to_string_lossy()
.replace('\\', "/");
if file_type.is_dir() {
rows.push(ManifestRow {
kind: b'D',
relative_path: relative,
byte_count: 0,
sha256: String::new(),
});
collect_manifest_rows(root, &path, rows)?;
} else if file_type.is_file() {
let bytes = fs::read(&path)?;
rows.push(ManifestRow {
kind: b'F',
relative_path: relative,
byte_count: bytes.len() as u64,
sha256: format!("sha256-{:x}", Sha256::digest(bytes)),
});
} else {
bail!("heartbeat artifact retention refuses non-file artifacts");
}
}
Ok(())
}
fn retention_plan_id(
root: &Path,
retain_pulse_count: usize,
batch_size: usize,
members: &[HeartbeatArtifactRetentionMember],
) -> String {
let mut digest = Sha256::new();
digest.update(b"epiphany.heartbeat.artifact-retention-plan.v0\0");
digest.update(root.to_string_lossy().as_bytes());
digest.update((retain_pulse_count as u64).to_be_bytes());
digest.update((batch_size as u64).to_be_bytes());
for member in members {
digest.update(member.directory_name.as_bytes());
digest.update(member.manifest_sha256.as_bytes());
digest.update(member.file_count.to_be_bytes());
digest.update(member.byte_count.to_be_bytes());
}
format!("sha256-{:x}", digest.finalize())
}
fn validate_retention_plan(plan: &EpiphanyHeartbeatArtifactRetentionPlan) -> Result<()> {
if plan.schema_version != HEARTBEAT_ARTIFACT_RETENTION_PLAN_SCHEMA_VERSION
|| plan.private_state_exposed
|| plan.plan_id.trim().is_empty()
|| plan.artifact_root.trim().is_empty()
|| plan.retain_pulse_count == 0
|| plan.batch_size == 0
|| plan.members.is_empty()
|| plan.planned_at_utc.trim().is_empty()
{
bail!("invalid heartbeat artifact retention plan");
}
if plan.members.len() as u64 > plan.batch_size {
bail!("heartbeat artifact retention plan exceeds its batch size");
}
let mut names = std::collections::BTreeSet::new();
for member in &plan.members {
if pulse_sequence(&member.directory_name).is_none()
|| !member.manifest_sha256.starts_with("sha256-")
|| !names.insert(member.directory_name.as_str())
{
bail!("invalid heartbeat artifact retention member");
}
}
Ok(())
}
fn validate_retention_receipt(
receipt: &EpiphanyHeartbeatArtifactRetentionReceipt,
plan: &EpiphanyHeartbeatArtifactRetentionPlan,
) -> Result<()> {
if receipt.schema_version != HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_SCHEMA_VERSION
|| receipt.private_state_exposed
|| receipt.status != "completed"
|| receipt.plan_id != plan.plan_id
|| receipt.deleted_directories
!= plan
.members
.iter()
.map(|member| member.directory_name.clone())
.collect::<Vec<_>>()
|| receipt.completed_at_utc.trim().is_empty()
{
bail!("invalid heartbeat artifact retention receipt");
}
Ok(())
}
fn write_retention_plan(
store_path: &Path,
plan: &EpiphanyHeartbeatArtifactRetentionPlan,
) -> Result<()> {
let cache = heartbeat_state_cache(store_path)?;
let (plan_entry, _) = cache.prepare_entry(&plan.plan_id, plan)?;
let (latest_entry, _) =
cache.prepare_entry(HEARTBEAT_ARTIFACT_RETENTION_PLAN_LATEST_KEY, plan)?;
let expected = cache
.snapshot_envelopes()
.into_iter()
.filter(|entry| {
entry.r#type == <EpiphanyHeartbeatArtifactRetentionPlan as DatabaseEntry>::TYPE
&& (entry.key == plan.plan_id
|| entry.key == HEARTBEAT_ARTIFACT_RETENTION_PLAN_LATEST_KEY)
})
.collect::<Vec<_>>();
if !SingleFileMessagePackBackingStore::new(store_path)
.compare_and_swap_batch(&expected, vec![plan_entry, latest_entry])?
{
bail!("heartbeat artifact retention plan lost exact compare-and-swap");
}
Ok(())
}
fn write_retention_receipt(
store_path: &Path,
receipt: &EpiphanyHeartbeatArtifactRetentionReceipt,
) -> Result<()> {
let cache = heartbeat_state_cache(store_path)?;
if let Some(existing) =
cache.get::<EpiphanyHeartbeatArtifactRetentionReceipt>(&receipt.receipt_id)?
{
if existing == *receipt {
return Ok(());
}
bail!("heartbeat artifact retention receipt identity collision");
}
let (receipt_entry, _) = cache.prepare_entry(&receipt.receipt_id, receipt)?;
let (latest_entry, _) =
cache.prepare_entry(HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_LATEST_KEY, receipt)?;
let expected = cache
.snapshot_envelopes()
.into_iter()
.filter(|entry| {
entry.r#type == <EpiphanyHeartbeatArtifactRetentionReceipt as DatabaseEntry>::TYPE
&& (entry.key == receipt.receipt_id
|| entry.key == HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_LATEST_KEY)
})
.collect::<Vec<_>>();
if !SingleFileMessagePackBackingStore::new(store_path)
.compare_and_swap_batch(&expected, vec![receipt_entry, latest_entry])?
{
bail!("heartbeat artifact retention receipt lost exact compare-and-swap");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
EpiphanyHeartbeatCognitionEntry, HEARTBEAT_COGNITION_SCHEMA_VERSION,
initialize_heartbeat_store, write_heartbeat_cognition_entry,
};
fn pulse(root: &Path, sequence: u64, content: &str) -> Result<PathBuf> {
let path = root.join(format!("pulse-{sequence:06}"));
fs::create_dir_all(path.join("nested"))?;
fs::write(path.join("nested").join("artifact.json"), content)?;
Ok(path)
}
#[test]
fn retention_is_receipted_bounded_and_idempotent() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("heartbeat.cc");
let artifacts = temp.path().join("artifacts");
fs::create_dir(&artifacts)?;
initialize_heartbeat_store(&store, 1.0)?;
for sequence in 1..=5 {
pulse(&artifacts, sequence, &format!("artifact-{sequence}"))?;
}
let receipt =
retain_heartbeat_pulse_artifacts(&store, &artifacts, 2, 2, "2026-08-08T21:00:00Z")?
.expect("retention should run above hysteresis threshold");
assert_eq!(
receipt.deleted_directories,
vec!["pulse-000001", "pulse-000002"]
);
assert_eq!(receipt.deleted_file_count, 2);
assert_eq!(pulse_directories(&artifacts)?.len(), 3);
assert!(
retain_heartbeat_pulse_artifacts(&store, &artifacts, 2, 2, "2026-08-08T21:00:01Z",)?
.is_none()
);
Ok(())
}
#[test]
fn pending_plan_refuses_changed_artifact_and_preserves_it() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("heartbeat.cc");
let artifacts = temp.path().join("artifacts");
fs::create_dir(&artifacts)?;
initialize_heartbeat_store(&store, 1.0)?;
let first = pulse(&artifacts, 1, "before")?;
for sequence in 2..=5 {
pulse(&artifacts, sequence, "stable")?;
}
let members = vec![artifact_member(&artifacts.canonicalize()?, &first)?];
let root = artifacts.canonicalize()?;
let plan = EpiphanyHeartbeatArtifactRetentionPlan {
schema_version: HEARTBEAT_ARTIFACT_RETENTION_PLAN_SCHEMA_VERSION.to_string(),
plan_id: retention_plan_id(&root, 2, 2, &members),
artifact_root: root.display().to_string(),
retain_pulse_count: 2,
batch_size: 2,
members,
planned_at_utc: "2026-08-08T21:01:00Z".to_string(),
private_state_exposed: false,
};
write_retention_plan(&store, &plan)?;
fs::write(first.join("nested").join("artifact.json"), "after")?;
assert!(
retain_heartbeat_pulse_artifacts(&store, &artifacts, 2, 2, "2026-08-08T21:01:01Z",)
.is_err()
);
assert!(first.exists());
Ok(())
}
#[test]
fn unknown_directory_fails_closed_before_deletion() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("heartbeat.cc");
let artifacts = temp.path().join("artifacts");
fs::create_dir(&artifacts)?;
initialize_heartbeat_store(&store, 1.0)?;
for sequence in 1..=5 {
pulse(&artifacts, sequence, "stable")?;
}
fs::create_dir(artifacts.join("operator-evidence"))?;
assert!(
retain_heartbeat_pulse_artifacts(&store, &artifacts, 2, 2, "2026-08-08T21:02:00Z",)
.is_err()
);
assert!(artifacts.join("pulse-000001").exists());
Ok(())
}
#[test]
fn latest_cognition_artifact_is_never_retired() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("heartbeat.cc");
let artifacts = temp.path().join("artifacts");
fs::create_dir(&artifacts)?;
initialize_heartbeat_store(&store, 1.0)?;
let protected = pulse(&artifacts, 1, "protected")?;
for sequence in 2..=5 {
pulse(&artifacts, sequence, "stable")?;
}
write_heartbeat_cognition_entry(
&store,
&EpiphanyHeartbeatCognitionEntry {
schema_version: HEARTBEAT_COGNITION_SCHEMA_VERSION.to_string(),
updated_at: "2026-08-08T21:03:00Z".to_string(),
latest_run_id: Some("protected-run".to_string()),
latest_artifact_ref: Some(
protected
.join("nested")
.join("artifact.json")
.display()
.to_string(),
),
source: Some("test".to_string()),
sleep_cycle: None,
memory_resonance: None,
incubation: None,
thought_lanes: None,
bridge: None,
candidate_interventions: None,
appraisals: None,
reactions: None,
},
)?;
assert!(
retain_heartbeat_pulse_artifacts(&store, &artifacts, 2, 2, "2026-08-08T21:03:01Z",)
.is_err()
);
assert!(protected.exists());
Ok(())
}
}

View file

@ -1,3 +1,5 @@
use super::EpiphanyHeartbeatArtifactRetentionPlan;
use super::EpiphanyHeartbeatArtifactRetentionReceipt;
use super::EpiphanyHeartbeatCognitionEntry;
use super::EpiphanyHeartbeatStaleTurnRepairReceipt;
use super::EpiphanyHeartbeatStateEntry;
@ -30,6 +32,8 @@ pub fn heartbeat_state_cache(store_path: impl AsRef<Path>) -> Result<CultCache>
cache.register_entry_type::<EpiphanyHeartbeatStateEntry>()?;
cache.register_entry_type::<EpiphanyHeartbeatCognitionEntry>()?;
cache.register_entry_type::<EpiphanyHeartbeatStaleTurnRepairReceipt>()?;
cache.register_entry_type::<EpiphanyHeartbeatArtifactRetentionPlan>()?;
cache.register_entry_type::<EpiphanyHeartbeatArtifactRetentionReceipt>()?;
import_owned_heartbeat_envelopes(&mut cache, store_path.as_ref(), false)?;
Ok(cache)
}
@ -39,6 +43,8 @@ fn legacy_heartbeat_state_cache(store_path: impl AsRef<Path>) -> Result<CultCach
cache.register_entry_type::<LegacyHeartbeatStateWithCognition>()?;
cache.register_entry_type::<EpiphanyHeartbeatCognitionEntry>()?;
cache.register_entry_type::<EpiphanyHeartbeatStaleTurnRepairReceipt>()?;
cache.register_entry_type::<EpiphanyHeartbeatArtifactRetentionPlan>()?;
cache.register_entry_type::<EpiphanyHeartbeatArtifactRetentionReceipt>()?;
import_owned_heartbeat_envelopes(&mut cache, store_path.as_ref(), true)?;
Ok(cache)
}
@ -59,6 +65,10 @@ fn import_owned_heartbeat_envelopes(
|| (envelope.r#type == <EpiphanyHeartbeatCognitionEntry as DatabaseEntry>::TYPE
&& envelope.key == HEARTBEAT_COGNITION_KEY)
|| envelope.r#type == <EpiphanyHeartbeatStaleTurnRepairReceipt as DatabaseEntry>::TYPE;
let owned = owned
|| envelope.r#type == <EpiphanyHeartbeatArtifactRetentionPlan as DatabaseEntry>::TYPE
|| envelope.r#type
== <EpiphanyHeartbeatArtifactRetentionReceipt as DatabaseEntry>::TYPE;
if !owned {
continue;
}
@ -79,6 +89,13 @@ fn import_owned_heartbeat_envelopes(
}
} else if envelope.r#type == <EpiphanyHeartbeatCognitionEntry as DatabaseEntry>::TYPE {
cache.load_envelope::<EpiphanyHeartbeatCognitionEntry>(envelope)?;
} else if envelope.r#type == <EpiphanyHeartbeatArtifactRetentionPlan as DatabaseEntry>::TYPE
{
cache.load_envelope::<EpiphanyHeartbeatArtifactRetentionPlan>(envelope)?;
} else if envelope.r#type
== <EpiphanyHeartbeatArtifactRetentionReceipt as DatabaseEntry>::TYPE
{
cache.load_envelope::<EpiphanyHeartbeatArtifactRetentionReceipt>(envelope)?;
} else {
cache.load_envelope::<EpiphanyHeartbeatStaleTurnRepairReceipt>(envelope)?;
}

View file

@ -619,10 +619,18 @@ pub use eyes_gateway::EyesEvidencePacket;
pub use eyes_gateway::default_eyes_cultnet_contracts;
pub use eyes_gateway::eyes_evidence_packet_from_research_finding;
pub use hands_gateway::*;
pub use heartbeat_state::EpiphanyHeartbeatArtifactRetentionPlan;
pub use heartbeat_state::EpiphanyHeartbeatArtifactRetentionReceipt;
pub use heartbeat_state::EpiphanyHeartbeatCognitionEntry;
pub use heartbeat_state::EpiphanyHeartbeatStaleTurnRepairReceipt;
pub use heartbeat_state::EpiphanyHeartbeatStateEntry;
pub use heartbeat_state::GhostlightSceneParticipantSeed;
pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_PLAN_LATEST_KEY;
pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_PLAN_SCHEMA_VERSION;
pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_PLAN_TYPE;
pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_LATEST_KEY;
pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_SCHEMA_VERSION;
pub use heartbeat_state::HEARTBEAT_ARTIFACT_RETENTION_RECEIPT_TYPE;
pub use heartbeat_state::HEARTBEAT_COGNITION_KEY;
pub use heartbeat_state::HEARTBEAT_COGNITION_SCHEMA_VERSION;
pub use heartbeat_state::HEARTBEAT_COGNITION_TYPE;
@ -635,6 +643,7 @@ pub use heartbeat_state::HEARTBEAT_STATE_TYPE;
pub use heartbeat_state::HeartbeatAgentReaction;
pub use heartbeat_state::HeartbeatAgentThoughtAppraisal;
pub use heartbeat_state::HeartbeatAppraisalReview;
pub use heartbeat_state::HeartbeatArtifactRetentionMember;
pub use heartbeat_state::HeartbeatBirthPersonalitySeed;
pub use heartbeat_state::HeartbeatCandidateImplications;
pub use heartbeat_state::HeartbeatCompleteOptions;
@ -680,6 +689,7 @@ pub use heartbeat_state::pump_heartbeat_store;
pub use heartbeat_state::queue_heartbeat_pending_mention_store;
pub use heartbeat_state::reconcile_resident_self_heartbeat_ack;
pub use heartbeat_state::recover_stale_heartbeat_store;
pub use heartbeat_state::retain_heartbeat_pulse_artifacts;
pub use heartbeat_state::run_void_routine_store;
pub use heartbeat_state::tick_heartbeat_store;
pub use heartbeat_state::update_heartbeat_heat_store;
@ -1110,8 +1120,8 @@ pub use runtime_spine::validate_hands_action_authority;
pub use runtime_spine::write_runtime_hello_frame;
pub use runtime_spine::write_runtime_schema_catalog_json;
pub use runtime_store_migration::{
RuntimeStoreMigrationReceipt, RUNTIME_STORE_MIGRATION_RECEIPT_SCHEMA_VERSION,
RUNTIME_STORE_MIGRATION_RECEIPT_TYPE, migrate_runtime_store_to_redb,
RUNTIME_STORE_MIGRATION_RECEIPT_SCHEMA_VERSION, RUNTIME_STORE_MIGRATION_RECEIPT_TYPE,
RuntimeStoreMigrationReceipt, migrate_runtime_store_to_redb,
};
pub use semantic_projector_service::SemanticProjectorServiceBody;
pub use semantic_projector_service::SemanticProjectorServicePulse;

View file

@ -246,10 +246,25 @@ pub fn package_epiphany_release(
}
fn release_source_cache_identity(repo: &Path) -> Result<String> {
let canonical_repo = canonical_path(repo)?;
let common_dir = PathBuf::from(git_output(repo, &["rev-parse", "--git-common-dir"])?.trim());
let common_dir = if common_dir.is_absolute() {
canonical_path(&common_dir)?
} else {
canonical_path(&repo.join(common_dir))?
};
// Linked worktrees are views of one repository and must share one exact-source
// cache. For ordinary non-bare repositories, hashing the common `.git` parent
// also preserves the cache identity used before worktree-aware ownership.
let cache_owner = if common_dir.file_name().is_some_and(|name| name == ".git") {
common_dir
.parent()
.ok_or_else(|| anyhow!("repository common directory has no owner"))?
} else {
common_dir.as_path()
};
let mut digest = Sha256::new();
digest.update(b"epiphany.release_source_cache.v0\0");
digest.update(canonical_repo.to_string_lossy().as_bytes());
digest.update(cache_owner.to_string_lossy().as_bytes());
Ok(format!("{:x}", digest.finalize()))
}
@ -1050,13 +1065,47 @@ mod tests {
let root = TempDir::new().expect("temporary root");
let first = root.path().join("first");
let second = root.path().join("second");
fs::create_dir_all(&first).expect("first repository path");
fs::create_dir_all(&second).expect("second repository path");
let linked = root.path().join("linked");
for repo in [&first, &second] {
fs::create_dir_all(repo).expect("repository path");
run_git_checked(repo, &["init"], "initialize test repository")
.expect("initialized repository");
run_git_checked(
repo,
&[
"-c",
"user.name=Epiphany Test",
"-c",
"user.email=epiphany-test@invalid",
"commit",
"--allow-empty",
"-m",
"cache identity fixture",
],
"commit test repository",
)
.expect("committed repository");
}
run_git_checked(
&first,
&[
"worktree",
"add",
"--detach",
linked.to_str().expect("UTF-8 path"),
],
"create linked test worktree",
)
.expect("linked worktree");
assert_eq!(
release_source_cache_identity(&first).expect("first identity"),
release_source_cache_identity(&first).expect("stable first identity")
);
assert_eq!(
release_source_cache_identity(&first).expect("main identity"),
release_source_cache_identity(&linked).expect("linked identity")
);
assert_ne!(
release_source_cache_identity(&first).expect("first identity"),
release_source_cache_identity(&second).expect("second identity")
@ -1076,6 +1125,13 @@ mod tests {
#[test]
fn resident_cognition_roles_keep_their_owning_manifests() {
let root_manifest = fs::read_to_string(
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("epiphany-core has a repository parent")
.join("Cargo.toml"),
)
.expect("root release manifest");
let packaged_roles = required_packaged_release_binaries("x86_64-unknown-linux-gnu")
.into_iter()
.map(|(role, _)| role)
@ -1112,6 +1168,7 @@ mod tests {
required_release_build_target("runtime-spine").unwrap(),
("epiphany-core", "epiphany-runtime-spine")
);
assert!(root_manifest.contains("name = \"epiphany-runtime-spine\""));
assert_eq!(
required_release_build_target("coordinator").unwrap(),
(".", "epiphany-mvp-coordinator")
@ -1151,15 +1208,10 @@ mod tests {
let core = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let repo = core.parent().expect("epiphany-core repository parent");
let root_manifest = fs::read_to_string(repo.join("Cargo.toml")).expect("root manifest");
let core_manifest =
fs::read_to_string(core.join("Cargo.toml")).expect("core manifest");
let core_manifest = fs::read_to_string(core.join("Cargo.toml")).expect("core manifest");
assert!(root_manifest.contains(
"coordinator-runtime = [\"dep:epiphany-self-policy\"]"
));
assert!(root_manifest.contains(
"required-features = [\"coordinator-runtime\"]"
));
assert!(root_manifest.contains("coordinator-runtime = [\"dep:epiphany-self-policy\"]"));
assert!(root_manifest.contains("required-features = [\"coordinator-runtime\"]"));
assert!(core_manifest.contains("autobins = false"));
assert!(!core_manifest.contains("name = \"epiphany-mvp-coordinator\""));
assert!(!core_manifest.contains("name = \"epiphany-mvp-status\""));