From 90a362a6ed39782f0de58e58c5904a462b8fba72 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 01:57:42 +0100 Subject: [PATCH] Add memory graph compose law --- epiphany-core/src/lib.rs | 1 + epiphany-core/src/memory_graph/compose.rs | 93 +++++++++++++++++ epiphany-core/src/memory_graph/mod.rs | 2 + epiphany-core/src/memory_graph/tests.rs | 100 +++++++++++++++++++ epiphany-core/src/memory_graph/validation.rs | 5 + notes/fresh-workspace-handoff.md | 2 +- state/ledgers.msgpack | Bin 131012 -> 131384 bytes state/map.yaml | 2 +- 8 files changed, 203 insertions(+), 2 deletions(-) create mode 100644 epiphany-core/src/memory_graph/compose.rs diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 02efd720..90ecca5f 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -95,6 +95,7 @@ pub use memory_graph::EpiphanyMemoryPatchCandidate; pub use memory_graph::MEMORY_GRAPH_KEY; pub use memory_graph::MEMORY_GRAPH_SCHEMA_VERSION; pub use memory_graph::MEMORY_GRAPH_TYPE; +pub use memory_graph::compose_memory_graph_snapshots; pub use memory_graph::derive_memory_graph_freshness; pub use memory_graph::lifecycle_allowed_for_profile; pub use memory_graph::load_memory_graph_entry; diff --git a/epiphany-core/src/memory_graph/compose.rs b/epiphany-core/src/memory_graph/compose.rs new file mode 100644 index 00000000..745ef1b9 --- /dev/null +++ b/epiphany-core/src/memory_graph/compose.rs @@ -0,0 +1,93 @@ +use super::EpiphanyMemoryFreshness; +use super::EpiphanyMemoryFreshnessStatus; +use super::EpiphanyMemoryGraphSnapshot; +use super::EpiphanyMemoryGraphValidationError; +use super::validate_memory_graph_snapshot; +use crate::memory_graph::store::MEMORY_GRAPH_SCHEMA_VERSION; + +pub fn compose_memory_graph_snapshots( + graph_id: impl Into, + snapshots: impl IntoIterator, +) -> Result> { + let mut composed = EpiphanyMemoryGraphSnapshot { + schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()), + graph_id: graph_id.into(), + ..Default::default() + }; + + let mut freshness_notes = Vec::new(); + for snapshot in snapshots { + composed.domains.extend(snapshot.domains); + composed.nodes.extend(snapshot.nodes); + composed.edges.extend(snapshot.edges); + composed.summaries.extend(snapshot.summaries); + composed + .lifecycle_receipts + .extend(snapshot.lifecycle_receipts); + if let Some(freshness) = snapshot.freshness { + merge_freshness(&mut composed, freshness, &mut freshness_notes); + } + } + + if let Some(freshness) = composed.freshness.as_mut() { + if freshness.note.is_none() && !freshness_notes.is_empty() { + freshness.note = Some(freshness_notes.join(" ")); + } + } + + let errors = validate_memory_graph_snapshot(&composed); + if errors.is_empty() { + Ok(composed) + } else { + Err(errors) + } +} + +fn merge_freshness( + composed: &mut EpiphanyMemoryGraphSnapshot, + freshness: EpiphanyMemoryFreshness, + notes: &mut Vec, +) { + let aggregate = composed + .freshness + .get_or_insert_with(|| EpiphanyMemoryFreshness { + status: EpiphanyMemoryFreshnessStatus::Ready, + note: None, + ..Default::default() + }); + + if freshness_rank(freshness.status) > freshness_rank(aggregate.status) { + aggregate.status = freshness.status; + } + merge_unique(&mut aggregate.stale_node_ids, freshness.stale_node_ids); + merge_unique(&mut aggregate.stale_edge_ids, freshness.stale_edge_ids); + merge_unique( + &mut aggregate.stale_summary_ids, + freshness.stale_summary_ids, + ); + merge_unique( + &mut aggregate.dirty_source_hashes, + freshness.dirty_source_hashes, + ); + if let Some(note) = freshness.note { + if !note.trim().is_empty() { + notes.push(note); + } + } +} + +fn freshness_rank(status: EpiphanyMemoryFreshnessStatus) -> u8 { + match status { + EpiphanyMemoryFreshnessStatus::Stale => 2, + EpiphanyMemoryFreshnessStatus::Ready => 1, + _ => 0, + } +} + +fn merge_unique(target: &mut Vec, values: impl IntoIterator) { + for value in values { + if !target.iter().any(|existing| existing == &value) { + target.push(value); + } + } +} diff --git a/epiphany-core/src/memory_graph/mod.rs b/epiphany-core/src/memory_graph/mod.rs index 58e3e3fc..c7bc937d 100644 --- a/epiphany-core/src/memory_graph/mod.rs +++ b/epiphany-core/src/memory_graph/mod.rs @@ -1,3 +1,4 @@ +pub mod compose; pub mod context_cut; pub mod freshness; pub mod ids; @@ -23,6 +24,7 @@ pub use epiphany_state_model::EpiphanyMemoryPatchCandidate; pub use epiphany_state_model::EpiphanyMemoryProfile; pub use epiphany_state_model::EpiphanyMemorySummary; +pub use compose::compose_memory_graph_snapshots; pub use context_cut::plan_memory_graph_context_cut; pub use freshness::derive_memory_graph_freshness; pub use ids::memory_graph_domain_id; diff --git a/epiphany-core/src/memory_graph/tests.rs b/epiphany-core/src/memory_graph/tests.rs index e8989f91..f0a74d76 100644 --- a/epiphany-core/src/memory_graph/tests.rs +++ b/epiphany-core/src/memory_graph/tests.rs @@ -96,6 +96,58 @@ fn fixture_snapshot() -> EpiphanyMemoryGraphSnapshot { } } +fn role_snapshot() -> EpiphanyMemoryGraphSnapshot { + let domain_id = memory_graph_domain_id(EpiphanyMemoryProfile::RoleSelf, "role", "body"); + let node_id = memory_graph_node_id(&domain_id, "memory", "keeps boundaries typed", None); + EpiphanyMemoryGraphSnapshot { + graph_id: "role-graph".to_string(), + domains: vec![EpiphanyMemoryDomain { + id: domain_id.clone(), + profile: EpiphanyMemoryProfile::RoleSelf, + title: "Body".to_string(), + lifecycle: EpiphanyMemoryLifecycle::Accepted, + ..Default::default() + }], + nodes: vec![EpiphanyMemoryNode { + id: node_id.clone(), + domain_id: domain_id.clone(), + profile: EpiphanyMemoryProfile::RoleSelf, + kind: EpiphanyMemoryNodeKind::RoleMemory, + title: "Typed boundaries".to_string(), + claim: "Body remembers that typed boundaries keep the machine legible.".to_string(), + question: "Which boundary is currently lying?".to_string(), + tension: String::new(), + action_implication: "Prefer one owned graph store over profile-local stores." + .to_string(), + source_hashes: vec!["anchor:missing".to_string()], + lifecycle: EpiphanyMemoryLifecycle::Accepted, + confidence: 88, + ..Default::default() + }], + summaries: vec![EpiphanyMemorySummary { + id: "summary-role-body".to_string(), + domain_id, + covers_node_ids: vec![node_id], + target: "body role memory".to_string(), + claim: "Body role memory enters the shared graph as typed state.".to_string(), + question: "How should role memory shape context cuts?".to_string(), + tension: String::new(), + action_implication: "Compose role memory with repo graph truth before retrieval." + .to_string(), + anchor_count: 0, + freshness: EpiphanyMemoryFreshnessStatus::Ready, + confidence: 80, + ..Default::default() + }], + freshness: Some(EpiphanyMemoryFreshness { + status: EpiphanyMemoryFreshnessStatus::Ready, + note: Some("Role memory is ready.".to_string()), + ..Default::default() + }), + ..Default::default() + } +} + #[test] fn memory_graph_ids_are_stable_and_normalized() { let a = memory_graph_node_id("domain", "module", ".\\Src\\Lib.rs", Some("Thing")); @@ -203,6 +255,54 @@ fn memory_graph_validation_requires_conservative_summary_anatomy() { ); } +#[test] +fn memory_graph_compose_merges_profiles_into_one_validated_snapshot() { + let mut repo = fixture_snapshot(); + repo.freshness = Some(derive_memory_graph_freshness( + &repo, + &["hash-a".to_string()], + )); + + let composed = compose_memory_graph_snapshots("composed-memory", vec![repo, role_snapshot()]) + .expect("profile snapshots should compose"); + + assert_eq!(composed.graph_id, "composed-memory"); + assert!(composed.embedding_manifest.is_none()); + assert!( + composed + .domains + .iter() + .any(|domain| domain.profile == EpiphanyMemoryProfile::RepoArchitecture) + ); + assert!( + composed + .domains + .iter() + .any(|domain| domain.profile == EpiphanyMemoryProfile::RoleSelf) + ); + assert_eq!( + composed + .freshness + .as_ref() + .map(|freshness| freshness.status), + Some(EpiphanyMemoryFreshnessStatus::Stale) + ); +} + +#[test] +fn memory_graph_compose_rejects_duplicate_profile_authority() { + let snapshot = fixture_snapshot(); + + let errors = + compose_memory_graph_snapshots("duplicate-memory", vec![snapshot.clone(), snapshot]) + .expect_err("duplicate ids must not be laundered by compose"); + + assert!(errors.iter().any(|error| error.path == "domains")); + assert!(errors.iter().any(|error| error.path == "nodes")); + assert!(errors.iter().any(|error| error.path == "edges")); + assert!(errors.iter().any(|error| error.path == "summaries")); +} + #[test] fn memory_graph_freshness_propagates_dirty_source_hash_to_summary() { let snapshot = fixture_snapshot(); diff --git a/epiphany-core/src/memory_graph/validation.rs b/epiphany-core/src/memory_graph/validation.rs index d5b6c442..34fffcae 100644 --- a/epiphany-core/src/memory_graph/validation.rs +++ b/epiphany-core/src/memory_graph/validation.rs @@ -60,6 +60,11 @@ pub fn validate_memory_graph_snapshot( validate_edge(edge, index, &node_ids, &mut errors); } + collect_unique( + snapshot.summaries.iter().map(|summary| summary.id.as_str()), + "summaries", + &mut errors, + ); for (index, summary) in snapshot.summaries.iter().enumerate() { validate_summary( summary, diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 83f69a6d..17218801 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -96,7 +96,7 @@ remembers doctrine; the branch remembers the blade. - 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 arena, participant kind, speed, next-ready time, reaction bias, interrupt threshold, load, status, constraints, personality cooldown, mood cooldown, effective cooldown, adaptive pacing, history, and pending turns through `epiphany-core::EpiphanyHeartbeatStateEntry` and the native `epiphany-heartbeat-store` binary. Role dossiers set baseline timing; appraisal mood/anxiety bends it through urgency, arousal, thought pressure, guardedness, and reaction intensity, so Hands-like work pressure and high-need anxious lanes recover sooner without being heartbeaten while a prior turn is running. `epiphany-heartbeat-store pump` computes pressure from external urgency, mood/anxiety, reaction intensity, thought pressure, and current pending load, then chooses tempo plus target concurrency: calm can launch zero and sleep slow; alarm can fill most active lanes. Idle turns are for rumination: light thought shuffling, role-quality attention, and candidate selfPatch pressure. Sleep/dream cycle passes are the intended distillation window for durable self-memory and doctrine. JSON heartbeat state and Python wrapper state are 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; a heart valve, not a whole circulatory god. - The first Ghostlight-derived timing slice is landed in Epiphany, but Ghostlight is reference lineage rather than a sibling runtime to preserve. `epiphany-heartbeat-store init --profile ghostlight-scene --scene-id --scene-participant ` creates a typed CultCache MessagePack scene heartbeat store whose participants are `arena=scene`, `participantKind=character`; `tick` emits `ghostlight.initiative_schedule.v0` receipts with `scene_turn` actions and local-affordance basis. The generic Epiphany maintenance lanes are not auto-patched into scene stores. - The first Void-derived routine slice is landed in Epiphany, but VoidBot is reference lineage rather than a runtime dependency. `epiphany-heartbeat-store routine --store .\state\agent-heartbeats.msgpack --artifact-dir .\.epiphany-heartbeats --agent-store .\state\agents.msgpack` reads typed role dossiers, computes bounded memory resonance, maintains incubation themes, runs analytic and associative cognition lanes, writes bridge syntheses/saturation/tension, projects the active thought cluster through each role's Ghostlight-shaped personality vectors, derives participant-local reactions, applies personality/mood timing, advances the sleep/dream cycle, updates the typed heartbeat store, and emits an auditable `epiphany.void_routine.v0` receipt. The routine now also carries anti-loop physiology imported from Void's calmer brain: `noveltyToSelf`, `noveltyToRoom`, source coverage, saturation pressure, refractory cooling, and explicit permission to let a live unsaturated thought deepen without forcing novelty theater every pass. This mutates only heartbeat physiology fields: project truth and role memory mutation remain on their reviewed surfaces. -- The next memory foundation must not build separate engines for repo graph and agent mind. Heartbeat cognition, role self-memory, repo architecture/dataflow, evidence scars, incubation, agency pressure, and context packets should converge through `EpiphanyMemoryGraph` profiles so one typed graph owns anchors, lifecycle, summaries, freshness, context cuts, and Qdrant embedding manifests. Repo, agent, and heartbeat profile producers now map accepted graph truth, reviewed role dossier memories/goals/values, and provisional heartbeat short-term/incubation/agency/candidate pressure into memory graph documents without scanner/Qdrant/model work. Heartbeat import deliberately does not mark durable promotion. The next clean slice is a merge/compose law plus store command so the profile producers converge into one validated memory graph snapshot instead of becoming rival truth stores. +- The next memory foundation must not build separate engines for repo graph and agent mind. Heartbeat cognition, role self-memory, repo architecture/dataflow, evidence scars, incubation, agency pressure, and context packets should converge through `EpiphanyMemoryGraph` profiles so one typed graph owns anchors, lifecycle, summaries, freshness, context cuts, and Qdrant embedding manifests. Repo, agent, and heartbeat profile producers now map accepted graph truth, reviewed role dossier memories/goals/values, and provisional heartbeat short-term/incubation/agency/candidate pressure into memory graph documents without scanner/Qdrant/model work. Heartbeat import deliberately does not mark durable promotion. Compose now merges profile snapshots into one validated graph and rejects duplicate authority; the next clean slice is a native store command that writes the composed snapshot, still before Qdrant, CultNet, prompt integration, or sleep promotion. - Manual Codex-run rumination still has an explicit aftercare rule until Epiphany owns the full sleep consolidator. In the intended Epiphany cycle, sub-agents ruminate when idle and distill when they sleep; in this supervising Codex thread, a heartbeat/routine vigil is only physiology until a separate closing pass reviews the receipts and decides whether map, handoff, evidence, or role self-memory should change. - The Face public-surface pass is landed as a bounded lane. Face's role dossier lives in `state/agents.msgpack`; `epiphany_specialists.toml` gives it a VoidBot-heartbeat-derived prompt stripped of moderation authority; `state/face-discord.toml` and the native `epiphany-face-discord` binary enforce that Face may interact only through #aquarium. Missing channel id or token writes candidate chat artifacts instead of posting elsewhere. If a Face has a persona name/avatar, `post` uses the shared Discord webhook pipe so each Epiphany can speak with its own nickname and avatar without a separate bot identity. - The Void memory bridge is now native enough to keep the useful organs attached. `state/void-memory.toml` and `epiphany-void-memory` can check Void's Docker Postgres state spine, query Qdrant Discord-history and source/lore collections with the configured Ollama embedding model, and fetch raw archive context windows from Void's file-backed Discord archive. Native `epiphany-mvp-status` includes a `voidMemory` block so Aquarium/backend clients can inspect whether the mouth and memory are actually wired. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 9a8e8d9c1503a4a9d104cbd1918642e9436c6516..22607ead9decf5f70c11709fdad7ff814650123a 100644 GIT binary patch delta 299 zcmWm8u}TCn5C&l5A!j9AYc&Xh#lo!|a`XEkqgU1mLc15wo!}mZL4Mn%Vtqu{{xKT BZb1M5 delta 50 zcmdnd#Bt<5`vfIs#{XR#Ri`mBCN=M2+`fmA@zY