Type heartbeat memory resonance

This commit is contained in:
Meta Vens 2026-05-18 08:00:52 +01:00
commit 3d2de911f8
8 changed files with 99 additions and 89 deletions

View file

@ -72,6 +72,8 @@ pub fn run_void_routine_store(
let appraisal_profiles = collect_role_appraisal_profiles(options.agent_store.as_deref())?;
apply_personality_timing_profiles(&mut state, &appraisal_profiles);
let resonance = build_memory_resonance(&memory_records);
let resonance_view = serde_json::to_value(&resonance)
.context("failed to project typed heartbeat memory resonance")?;
let incubation = build_incubation(
&previous_cognition
.as_ref()
@ -85,13 +87,13 @@ pub fn run_void_routine_store(
&resonance,
&memory_records,
);
let thought_lanes = build_thought_lanes(&resonance, &incubation, &memory_records);
let thought_lanes = build_thought_lanes(&resonance_view, &incubation, &memory_records);
let bridge = build_thought_bridge(
&previous_cognition
.as_ref()
.and_then(|entry| entry.bridge.clone()),
&thought_lanes,
&resonance,
&resonance_view,
&incubation,
);
let candidate_interventions = build_candidate_interventions(&bridge, &incubation);
@ -1305,7 +1307,7 @@ fn apply_mood_timing_from_appraisals(
}
}
fn build_memory_resonance(records: &[RoleMemoryRecord]) -> Value {
fn build_memory_resonance(records: &[RoleMemoryRecord]) -> HeartbeatMemoryResonance {
let mut pairs = Vec::new();
for (left_index, left) in records.iter().enumerate() {
for right in records.iter().skip(left_index + 1) {
@ -1323,44 +1325,39 @@ fn build_memory_resonance(records: &[RoleMemoryRecord]) -> Value {
if strength < 0.08 {
continue;
}
pairs.push(serde_json::json!({
"leftRole": left.role_id,
"leftMemoryId": left.memory_id,
"leftMemoryKind": left.memory_kind,
"leftSummary": left.summary,
"rightRole": right.role_id,
"rightMemoryId": right.memory_id,
"rightMemoryKind": right.memory_kind,
"rightSummary": right.summary,
"strength": strength,
"sharedTokens": shared_tokens(&left.tokens, &right.tokens),
"sourceRoles": [left.role_id, right.role_id],
"sourceKinds": [left.memory_kind, right.memory_kind],
"evidenceRefs": [left.memory_id, right.memory_id],
}));
pairs.push(HeartbeatMemoryResonancePair {
left_role: left.role_id.clone(),
left_memory_id: left.memory_id.clone(),
left_memory_kind: left.memory_kind.clone(),
left_summary: left.summary.clone(),
right_role: right.role_id.clone(),
right_memory_id: right.memory_id.clone(),
right_memory_kind: right.memory_kind.clone(),
right_summary: right.summary.clone(),
strength,
shared_tokens: shared_tokens(&left.tokens, &right.tokens),
source_roles: vec![left.role_id.clone(), right.role_id.clone()],
source_kinds: vec![left.memory_kind.clone(), right.memory_kind.clone()],
evidence_refs: vec![left.memory_id.clone(), right.memory_id.clone()],
});
}
}
pairs.sort_by(|left, right| {
right["strength"]
.as_f64()
.unwrap_or_default()
.total_cmp(&left["strength"].as_f64().unwrap_or_default())
});
pairs.sort_by(|left, right| right.strength.total_cmp(&left.strength));
pairs.truncate(8);
serde_json::json!({
"schema_version": "epiphany.memory_resonance.v0",
"updatedAt": now_iso(),
"source": "epiphany-native-void-routine",
"recordCount": records.len(),
"pairs": pairs,
})
HeartbeatMemoryResonance {
schema_version: "epiphany.memory_resonance.v0".to_string(),
updated_at: now_iso(),
source: "epiphany-native-void-routine".to_string(),
record_count: records.len(),
pairs,
}
}
fn build_incubation(
previous: &Option<Value>,
bridge: &Option<Value>,
candidate_interventions: &Option<HeartbeatCandidateInterventions>,
resonance: &Value,
resonance: &HeartbeatMemoryResonance,
records: &[RoleMemoryRecord],
) -> Value {
let previous_themes = previous
@ -1371,36 +1368,19 @@ fn build_incubation(
.unwrap_or_default();
let source_coverage = build_source_coverage(records);
let mut themes = Vec::new();
for pair in resonance
.get("pairs")
.and_then(Value::as_array)
.into_iter()
.flatten()
.take(6)
{
let left_role = pair
.get("leftRole")
.and_then(Value::as_str)
.unwrap_or("left");
let right_role = pair
.get("rightRole")
.and_then(Value::as_str)
.unwrap_or("right");
for pair in resonance.pairs.iter().take(6) {
let left_role = pair.left_role.as_str();
let right_role = pair.right_role.as_str();
let tokens = pair
.get("sharedTokens")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.take(3)
.collect::<Vec<_>>()
.join("/")
})
.unwrap_or_default();
let source_roles = unique_strings_from_value(pair.get("sourceRoles"));
let source_kinds = unique_strings_from_value(pair.get("sourceKinds"));
let source_memory_ids = unique_strings_from_value(pair.get("evidenceRefs"));
.shared_tokens
.iter()
.take(3)
.cloned()
.collect::<Vec<_>>()
.join("/");
let source_roles = pair.source_roles.clone();
let source_kinds = pair.source_kinds.clone();
let source_memory_ids = pair.evidence_refs.clone();
let summary = format!(
"{} and {} keep touching {}; let the swarm decide whether that is signal, stale echo, or a branch worth following.",
display_name_for_role(left_role),
@ -1447,7 +1427,7 @@ fn build_incubation(
.and_then(|theme| theme.get("maturation"))
.and_then(Value::as_f64)
.unwrap_or(0.32);
let strength = pair.get("strength").and_then(Value::as_f64).unwrap_or(0.0);
let strength = pair.strength;
let maturation = round3(
(prior_maturation * 0.44
+ strength * 0.24

View file

@ -59,7 +59,7 @@ pub struct EpiphanyHeartbeatCognitionEntry {
#[cultcache(key = 5, default)]
pub sleep_cycle: Option<Value>,
#[cultcache(key = 6, default)]
pub memory_resonance: Option<Value>,
pub memory_resonance: Option<HeartbeatMemoryResonance>,
#[cultcache(key = 7, default)]
pub incubation: Option<Value>,
#[cultcache(key = 8, default)]
@ -135,6 +135,35 @@ pub struct HeartbeatCandidateInterventions {
pub items: Vec<HeartbeatCandidateIntervention>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HeartbeatMemoryResonance {
#[serde(rename = "schema_version")]
pub schema_version: String,
pub updated_at: String,
pub source: String,
pub record_count: usize,
pub pairs: Vec<HeartbeatMemoryResonancePair>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HeartbeatMemoryResonancePair {
pub left_role: String,
pub left_memory_id: String,
pub left_memory_kind: String,
pub left_summary: String,
pub right_role: String,
pub right_memory_id: String,
pub right_memory_kind: String,
pub right_summary: String,
pub strength: f64,
pub shared_tokens: Vec<String>,
pub source_roles: Vec<String>,
pub source_kinds: Vec<String>,
pub evidence_refs: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HeartbeatCandidateIntervention {

View file

@ -79,7 +79,7 @@ pub fn heartbeat_status_projection(
"latestArtifacts": latest_json_artifacts(artifact_dir, artifact_limit),
"cognitionQuarantine": cognition.as_ref().map(heartbeat_cognition_status_json),
"sleepCycle": cognition.as_ref().and_then(|entry| entry.sleep_cycle.clone()),
"memoryResonance": cognition.as_ref().and_then(|entry| entry.memory_resonance.clone()),
"memoryResonance": cognition.as_ref().and_then(|entry| entry.memory_resonance.as_ref()).and_then(typed_json),
"incubation": cognition.as_ref().and_then(|entry| entry.incubation.clone()),
"thoughtLanes": cognition.as_ref().and_then(|entry| entry.thought_lanes.clone()),
"bridge": cognition.as_ref().and_then(|entry| entry.bridge.clone()),

View file

@ -128,7 +128,9 @@ fn legacy_heartbeat_cognition_entry(
latest_artifact_ref: None,
source,
sleep_cycle: legacy.sleep_cycle,
memory_resonance: legacy.memory_resonance,
memory_resonance: legacy
.memory_resonance
.and_then(|value| serde_json::from_value(value).ok()),
incubation: legacy.incubation,
thought_lanes: legacy.thought_lanes,
bridge: legacy.bridge,

View file

@ -49,33 +49,24 @@ fn import_resonance(
let Some(resonance) = cognition.memory_resonance.as_ref() else {
return;
};
let Some(pairs) = resonance.get("pairs").and_then(Value::as_array) else {
return;
};
let domain_id = push_domain(
domains,
EpiphanyMemoryProfile::ShortTerm,
"heartbeat resonance",
);
let before = nodes.len();
for pair in pairs.iter().take(8) {
let left = string_at(pair, "leftSummary");
let right = string_at(pair, "rightSummary");
let left_role = string_at(pair, "leftRole");
let right_role = string_at(pair, "rightRole");
for pair in resonance.pairs.iter().take(8) {
let id_seed = format!(
"{}:{}:{}",
left_role,
right_role,
string_at(pair, "leftMemoryId")
pair.left_role, pair.right_role, pair.left_memory_id
);
nodes.push(EpiphanyMemoryNode {
id: memory_graph_node_id(&domain_id, "resonance", id_seed, None),
domain_id: domain_id.clone(),
profile: EpiphanyMemoryProfile::ShortTerm,
kind: EpiphanyMemoryNodeKind::ShortTermThought,
title: format!("{left_role}/{right_role} resonance"),
claim: format!("{left} / {right}"),
title: format!("{}/{} resonance", pair.left_role, pair.right_role),
claim: format!("{} / {}", pair.left_summary, pair.right_summary),
question: "Is this resonance signal, stale echo, or a branch worth following?"
.to_string(),
tension: "Shared vocabulary is not proof of shared truth.".to_string(),
@ -84,7 +75,7 @@ fn import_resonance(
.to_string(),
source_hashes: vec!["anchor:missing".to_string()],
lifecycle: EpiphanyMemoryLifecycle::Active,
salience: score_to_u32(number_at(pair, "strength")),
salience: score_to_u32(pair.strength),
confidence: 55,
..Default::default()
});
@ -370,6 +361,8 @@ mod tests {
use crate::heartbeat_state::HEARTBEAT_COGNITION_SCHEMA_VERSION;
use crate::heartbeat_state::HeartbeatCandidateIntervention;
use crate::heartbeat_state::HeartbeatCandidateInterventions;
use crate::heartbeat_state::HeartbeatMemoryResonance;
use crate::heartbeat_state::HeartbeatMemoryResonancePair;
use crate::memory_graph::validate_memory_graph_snapshot;
#[test]
@ -381,16 +374,18 @@ mod tests {
latest_artifact_ref: None,
source: Some("unit-test".to_string()),
sleep_cycle: None,
memory_resonance: Some(serde_json::json!({
"pairs": [{
"leftRole": "body",
"rightRole": "soul",
"leftMemoryId": "mem-a",
"leftSummary": "Architecture needs anchors.",
"rightSummary": "Verification needs receipts.",
"strength": 0.8
}]
})),
memory_resonance: Some(HeartbeatMemoryResonance {
pairs: vec![HeartbeatMemoryResonancePair {
left_role: "body".to_string(),
right_role: "soul".to_string(),
left_memory_id: "mem-a".to_string(),
left_summary: "Architecture needs anchors.".to_string(),
right_summary: "Verification needs receipts.".to_string(),
strength: 0.8,
..Default::default()
}],
..Default::default()
}),
incubation: Some(serde_json::json!({
"themes": [{
"themeId": "theme-body-soul",

View file

@ -69,6 +69,7 @@ remembers doctrine; the branch remembers the blade.
- Heartbeat participant scene id, personality timing, mood timing, and pending-turn cooldown multipliers now live as typed fields instead of durable `participant.extra` / `pendingTurn.extra` JSON pockets. Scheduler pacing and status projection read the typed fields first and keep legacy extra fallbacks only as sealed compatibility scars.
- Heartbeat cognition appraisals and reactions now live as typed CultCache fields instead of `Option<Value>` blobs. The mood-timing scheduler consumes typed appraisals directly; legacy cognition migration parses old appraisal/reaction JSON only when loading prior stores.
- Heartbeat cognition candidate interventions now live as typed review-gated speech candidates instead of `Option<Value>` item lists. The memory graph heartbeat profile reads typed candidate items directly; legacy cognition migration parses old candidate JSON only when loading prior stores.
- Heartbeat cognition memory resonance now lives as typed resonance pairs instead of an `Option<Value>` blob. Incubation and memory graph import read typed pairs directly; temporary JSON projection remains only for still-untyped thought-lane/bridge builders and status/artifact output.
- Heartbeat durable document/schema types now live in `epiphany-core/src/heartbeat_state/heartbeat_documents.rs`, role/default construction lives in `epiphany-core/src/heartbeat_state/heartbeat_roles.rs`, persistence/validation lives in `epiphany-core/src/heartbeat_state/heartbeat_store.rs`, and status/artifact JSON projection lives in `epiphany-core/src/heartbeat_state/heartbeat_projection.rs`. The root `heartbeat_state.rs` keeps scheduling and Void cognition orchestration for the next cuts. Focused heartbeat tests and `epiphany-core` check pass after the splits.
- Heartbeat role/default and store seams now have module-local unit tests: fixed lane catalog, Ghostlight scene role projection, and typed state/cognition CultCache round-trip. Keep future heartbeat cuts aligned to those seam tests instead of growing root integration-only coverage.
- Heartbeat adaptive pacing now lives in `epiphany-core/src/heartbeat_state/heartbeat_pacing.rs`, including running-turn count and effective cooldown multipliers. It has a module-local unit test for pending-turn counting; root scheduling calls the pacing seam instead of owning pressure/concurrency math directly.

Binary file not shown.

View file

@ -56,6 +56,9 @@ objective:
Heartbeat cognition candidate interventions are typed review-gated speech
candidates; Face/Aquarium pressure no longer reads that surface as an
arbitrary JSON item list except when migrating legacy stores.
Heartbeat cognition memory resonance is a typed pair list consumed by
incubation and memory-graph import; JSON resonance exists only as a local
projection for still-untyped thought-lane/bridge builders and status output.
constraints:
- No frontier-scale training tithe.