Build canonical Modeling frontier foundation
This commit is contained in:
parent
2f22dbbca7
commit
995d783fd3
14 changed files with 1587 additions and 88 deletions
|
|
@ -10,6 +10,7 @@ use crate::RuntimeHandsReceiptChainSummary;
|
|||
use crate::load_epiphany_cultmesh_cluster_topology;
|
||||
use crate::load_epiphany_cultmesh_status;
|
||||
use crate::load_latest_epiphany_cultmesh_work_loop_telemetry;
|
||||
use crate::load_memory_graph_snapshot;
|
||||
use crate::plan_memory_graph_context_cut;
|
||||
use crate::query_epiphany_local_verse_context;
|
||||
use crate::refresh_or_validate_repo_memory_graph;
|
||||
|
|
@ -639,19 +640,37 @@ fn launch_memory_context(
|
|||
.unwrap_or_else(|_| runtime_store_path.to_path_buf())
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let (snapshot, refresh) = refresh_or_validate_repo_memory_graph(
|
||||
&memory_graph_store,
|
||||
&source_identity,
|
||||
state,
|
||||
repo_root,
|
||||
format!("bridge-launch-state-rev-{}", state.revision),
|
||||
)
|
||||
.map_err(|error| {
|
||||
let stored = load_memory_graph_snapshot(&memory_graph_store).map_err(|error| {
|
||||
format!(
|
||||
"failed to refresh memory graph store {}: {error}",
|
||||
"failed to validate memory graph store {}: {error}",
|
||||
memory_graph_store.display()
|
||||
)
|
||||
})?;
|
||||
let canonical = stored.as_ref().is_some_and(|snapshot| {
|
||||
snapshot.model_revision > 0
|
||||
|| !snapshot.model_hash.is_empty()
|
||||
|| !snapshot.frontier.is_empty()
|
||||
});
|
||||
let (snapshot, refresh) = if canonical {
|
||||
(
|
||||
stored.expect("canonical snapshot was present"),
|
||||
RepoMemoryGraphRefresh::Reused,
|
||||
)
|
||||
} else {
|
||||
refresh_or_validate_repo_memory_graph(
|
||||
&memory_graph_store,
|
||||
&source_identity,
|
||||
state,
|
||||
repo_root,
|
||||
format!("bridge-launch-state-rev-{}", state.revision),
|
||||
)
|
||||
.map_err(|error| {
|
||||
format!(
|
||||
"failed to bootstrap memory graph store {}: {error}",
|
||||
memory_graph_store.display()
|
||||
)
|
||||
})?
|
||||
};
|
||||
|
||||
let mut packet = plan_memory_graph_context_cut(
|
||||
&snapshot,
|
||||
|
|
@ -680,9 +699,17 @@ fn launch_memory_context(
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::EpiphanyMemoryDomain;
|
||||
use crate::EpiphanyMemoryGraphSnapshot;
|
||||
use crate::EpiphanyMemoryLifecycle;
|
||||
use crate::EpiphanyMemoryNode;
|
||||
use crate::EpiphanyMemoryNodeKind;
|
||||
use crate::EpiphanyRoleResultRoleId;
|
||||
use crate::HANDS_ACTION_INTENT_SCHEMA_VERSION;
|
||||
use crate::HandsActionIntent;
|
||||
use crate::MEMORY_GRAPH_SCHEMA_VERSION;
|
||||
use crate::RepoFrontierItem;
|
||||
use crate::RepoFrontierStatus;
|
||||
use crate::RuntimeSpineHeartbeatJobOptions;
|
||||
use crate::RuntimeSpineInitOptions;
|
||||
use crate::build_epiphany_role_launch_request_with_dynamic_context;
|
||||
|
|
@ -691,6 +718,7 @@ mod tests {
|
|||
use crate::hands_commit_receipt_for_review;
|
||||
use crate::hands_patch_receipt_for_review;
|
||||
use crate::initialize_runtime_spine;
|
||||
use crate::memory_graph_model_hash;
|
||||
use crate::open_runtime_spine_heartbeat_job;
|
||||
use crate::put_hands_action_intent;
|
||||
use crate::put_hands_action_review;
|
||||
|
|
@ -699,6 +727,7 @@ mod tests {
|
|||
use crate::put_hands_patch_receipt;
|
||||
use crate::runtime_worker_launch_request;
|
||||
use crate::seed_epiphany_local_verse_context;
|
||||
use crate::write_memory_graph_snapshot;
|
||||
use epiphany_state_model::EpiphanyAcceptanceReceipt;
|
||||
use std::fs;
|
||||
use uuid::Uuid;
|
||||
|
|
@ -720,6 +749,83 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_model_frontier_survives_newer_thread_state_and_guides_launch() -> anyhow::Result<()>
|
||||
{
|
||||
let temp = std::env::temp_dir().join(format!(
|
||||
"epiphany-canonical-model-launch-{}",
|
||||
Uuid::new_v4()
|
||||
));
|
||||
fs::create_dir(&temp)?;
|
||||
let runtime_store = temp.join("runtime-spine.msgpack");
|
||||
let graph_store = memory_graph_store_path(&runtime_store);
|
||||
let mut snapshot = EpiphanyMemoryGraphSnapshot {
|
||||
schema_version: Some(MEMORY_GRAPH_SCHEMA_VERSION.to_string()),
|
||||
graph_id: "canonical-model".to_string(),
|
||||
model_revision: 4,
|
||||
domains: vec![EpiphanyMemoryDomain {
|
||||
id: "repo".to_string(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
title: "Canonical repository model".to_string(),
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
nodes: vec![EpiphanyMemoryNode {
|
||||
id: "claim-modeling-authority".to_string(),
|
||||
domain_id: "repo".to_string(),
|
||||
profile: EpiphanyMemoryProfile::RepoArchitecture,
|
||||
kind: EpiphanyMemoryNodeKind::RuntimeContract,
|
||||
title: "Modeling authority".to_string(),
|
||||
claim: "Canonical Modeling state survives transcript revision churn.".to_string(),
|
||||
question: "Which downstream organ consumes it?".to_string(),
|
||||
action_implication: "Route the exact claim into launch context.".to_string(),
|
||||
source_hashes: vec!["anchor:missing".to_string()],
|
||||
lifecycle: EpiphanyMemoryLifecycle::Accepted,
|
||||
..Default::default()
|
||||
}],
|
||||
frontier: vec![RepoFrontierItem {
|
||||
id: "frontier-modeling-handoff".to_string(),
|
||||
migration_body: "Carry the canonical repository frontier into organ prompts."
|
||||
.to_string(),
|
||||
question: "Can Hands see the exact target claim?".to_string(),
|
||||
gap: "Launch assembly previously saw only semantically similar prose.".to_string(),
|
||||
target_claim_ids: vec!["claim-modeling-authority".to_string()],
|
||||
source_scope: vec!["epiphany-core/src".to_string()],
|
||||
recommended_next_organ: "Hands".to_string(),
|
||||
status: RepoFrontierStatus::Active,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
snapshot.model_hash = memory_graph_model_hash(&snapshot)?;
|
||||
write_memory_graph_snapshot(&graph_store, &snapshot)?;
|
||||
let newer_thread_state = EpiphanyThreadState {
|
||||
revision: 999,
|
||||
objective: Some("Discuss irrelevant weather bananas.".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let packet = launch_memory_context(
|
||||
&runtime_store,
|
||||
&newer_thread_state,
|
||||
"irrelevant weather bananas",
|
||||
)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
assert_eq!(packet.frontier[0].id, "frontier-modeling-handoff");
|
||||
assert!(
|
||||
packet
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|node| node.id == "claim-modeling-authority")
|
||||
);
|
||||
let preserved = load_memory_graph_snapshot(&graph_store)?.expect("canonical model");
|
||||
assert_eq!(preserved.model_revision, 4);
|
||||
assert_eq!(preserved.frontier, snapshot.frontier);
|
||||
fs::remove_dir_all(&temp)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_context_persists_on_runtime_worker_request() -> anyhow::Result<()> {
|
||||
let temp =
|
||||
|
|
|
|||
|
|
@ -617,7 +617,12 @@ 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::RepoFrontierItem;
|
||||
pub use memory_graph::RepoFrontierStatus;
|
||||
pub use memory_graph::RepoMemoryGraphRefresh;
|
||||
pub use memory_graph::RepoModelPatch;
|
||||
pub use memory_graph::RepoModelPatchOperation;
|
||||
pub use memory_graph::apply_repo_model_patch;
|
||||
pub use memory_graph::compose_memory_graph_snapshots;
|
||||
pub use memory_graph::derive_memory_graph_freshness;
|
||||
pub use memory_graph::lifecycle_allowed_for_profile;
|
||||
|
|
@ -629,6 +634,7 @@ pub use memory_graph::memory_graph_edge_id;
|
|||
pub use memory_graph::memory_graph_from_agent_memories;
|
||||
pub use memory_graph::memory_graph_from_epiphany_graphs;
|
||||
pub use memory_graph::memory_graph_from_heartbeat_cognition;
|
||||
pub use memory_graph::memory_graph_model_hash;
|
||||
pub use memory_graph::memory_graph_node_id;
|
||||
pub use memory_graph::plan_memory_graph_context_cut;
|
||||
pub use memory_graph::refresh_or_validate_repo_memory_graph;
|
||||
|
|
|
|||
|
|
@ -7,9 +7,14 @@ use super::EpiphanyMemoryGraphSnapshot;
|
|||
use super::EpiphanyMemoryNode;
|
||||
use super::EpiphanyMemoryProfile;
|
||||
use super::EpiphanyMemorySummary;
|
||||
use super::RepoFrontierItem;
|
||||
use super::RepoFrontierStatus;
|
||||
use super::derive_memory_graph_freshness;
|
||||
use super::ids::normalized_key;
|
||||
use super::ids::stable_memory_graph_id;
|
||||
use bm25::Document;
|
||||
use bm25::Language;
|
||||
use bm25::SearchEngineBuilder;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
|
|
@ -73,7 +78,26 @@ pub fn plan_memory_graph_context_cut(
|
|||
let mut summaries = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
for summary in &snapshot.summaries {
|
||||
// Modeling's unresolved frontier is explicit routing authority. Preserve its
|
||||
// stored order and exact claim targets before asking semantic retrieval to
|
||||
// infer what matters from the launch prose.
|
||||
let (frontier, rejected_frontier_ids) =
|
||||
dependency_ordered_frontier(snapshot, budget, &node_by_id, &stale_nodes);
|
||||
for id in rejected_frontier_ids {
|
||||
warnings.push(format!(
|
||||
"frontier {id} was omitted because its target claims are missing, stale, or retired"
|
||||
));
|
||||
}
|
||||
for node_id in frontier
|
||||
.iter()
|
||||
.flat_map(|item| item.target_claim_ids.iter())
|
||||
{
|
||||
if let Some(node) = node_by_id.get(node_id.as_str()) {
|
||||
push_unique_node(&mut nodes, (*node).clone(), budget);
|
||||
}
|
||||
}
|
||||
|
||||
for summary in ranked_summaries(snapshot, query, &domains, &terms, &node_by_id) {
|
||||
if summaries.len() >= budget {
|
||||
break;
|
||||
}
|
||||
|
|
@ -118,7 +142,7 @@ pub fn plan_memory_graph_context_cut(
|
|||
}
|
||||
|
||||
if summaries.is_empty() && nodes.is_empty() {
|
||||
for node in &snapshot.nodes {
|
||||
for node in ranked_nodes(snapshot, query, &domains, &terms, &stale_nodes) {
|
||||
if nodes.len() >= budget {
|
||||
break;
|
||||
}
|
||||
|
|
@ -141,6 +165,7 @@ pub fn plan_memory_graph_context_cut(
|
|||
nodes,
|
||||
edges,
|
||||
summaries,
|
||||
frontier,
|
||||
anchors,
|
||||
warnings,
|
||||
missing_node_ids: query
|
||||
|
|
@ -158,6 +183,186 @@ pub fn plan_memory_graph_context_cut(
|
|||
}
|
||||
}
|
||||
|
||||
fn dependency_ordered_frontier(
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
budget: usize,
|
||||
node_by_id: &HashMap<&str, &EpiphanyMemoryNode>,
|
||||
stale_nodes: &HashSet<&str>,
|
||||
) -> (Vec<RepoFrontierItem>, Vec<String>) {
|
||||
let unresolved = snapshot
|
||||
.frontier
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
matches!(
|
||||
item.status,
|
||||
RepoFrontierStatus::Active
|
||||
| RepoFrontierStatus::Proposed
|
||||
| RepoFrontierStatus::Blocked
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let unresolved_ids = unresolved
|
||||
.iter()
|
||||
.map(|item| item.id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let mut eligible_ids = unresolved
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
!item.target_claim_ids.is_empty()
|
||||
&& item.target_claim_ids.iter().all(|id| {
|
||||
node_by_id.get(id.as_str()).is_some_and(|node| {
|
||||
!matches!(
|
||||
node.lifecycle,
|
||||
super::EpiphanyMemoryLifecycle::Retired
|
||||
| super::EpiphanyMemoryLifecycle::Stale
|
||||
) && !stale_nodes.contains(id.as_str())
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(|item| item.id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
loop {
|
||||
let before = eligible_ids.len();
|
||||
let current_eligible = eligible_ids.clone();
|
||||
eligible_ids.retain(|id| {
|
||||
unresolved
|
||||
.iter()
|
||||
.find(|item| item.id == *id)
|
||||
.is_some_and(|item| {
|
||||
item.dependency_item_ids.iter().all(|dependency| {
|
||||
!unresolved_ids.contains(dependency.as_str())
|
||||
|| current_eligible.contains(dependency.as_str())
|
||||
})
|
||||
})
|
||||
});
|
||||
if eligible_ids.len() == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let rejected = unresolved
|
||||
.iter()
|
||||
.filter(|item| !eligible_ids.contains(item.id.as_str()))
|
||||
.map(|item| item.id.clone())
|
||||
.collect();
|
||||
let eligible = unresolved
|
||||
.into_iter()
|
||||
.filter(|item| eligible_ids.contains(item.id.as_str()))
|
||||
.map(|item| (item.id.as_str(), item))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut ordered = Vec::new();
|
||||
let mut complete = HashSet::new();
|
||||
let mut visiting = HashSet::new();
|
||||
for item in &snapshot.frontier {
|
||||
append_frontier_prerequisites(
|
||||
&item.id,
|
||||
&eligible,
|
||||
&mut visiting,
|
||||
&mut complete,
|
||||
&mut ordered,
|
||||
);
|
||||
}
|
||||
(
|
||||
ordered.into_iter().take(budget).cloned().collect(),
|
||||
rejected,
|
||||
)
|
||||
}
|
||||
|
||||
fn append_frontier_prerequisites<'a>(
|
||||
id: &'a str,
|
||||
eligible: &HashMap<&'a str, &'a RepoFrontierItem>,
|
||||
visiting: &mut HashSet<&'a str>,
|
||||
complete: &mut HashSet<&'a str>,
|
||||
ordered: &mut Vec<&'a RepoFrontierItem>,
|
||||
) {
|
||||
if complete.contains(id) || !visiting.insert(id) {
|
||||
return;
|
||||
}
|
||||
let Some(item) = eligible.get(id).copied() else {
|
||||
visiting.remove(id);
|
||||
return;
|
||||
};
|
||||
for dependency in &item.dependency_item_ids {
|
||||
append_frontier_prerequisites(dependency, eligible, visiting, complete, ordered);
|
||||
}
|
||||
visiting.remove(id);
|
||||
if complete.insert(id) {
|
||||
ordered.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn ranked_nodes<'a>(
|
||||
snapshot: &'a EpiphanyMemoryGraphSnapshot,
|
||||
query: &EpiphanyMemoryContextQuery,
|
||||
domain_ids: &HashSet<&str>,
|
||||
terms: &[String],
|
||||
stale_nodes: &HashSet<&str>,
|
||||
) -> Vec<&'a EpiphanyMemoryNode> {
|
||||
let eligible = snapshot
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|node| {
|
||||
node_matches(node, query.profile, domain_ids, &[])
|
||||
&& !stale_nodes.contains(node.id.as_str())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
rank_typed_documents(eligible, query.text.as_deref(), terms, |node| {
|
||||
[
|
||||
node.title.as_str(),
|
||||
node.claim.as_str(),
|
||||
node.question.as_str(),
|
||||
node.tension.as_str(),
|
||||
node.action_implication.as_str(),
|
||||
]
|
||||
.join(" ")
|
||||
})
|
||||
}
|
||||
|
||||
fn ranked_summaries<'a>(
|
||||
snapshot: &'a EpiphanyMemoryGraphSnapshot,
|
||||
query: &EpiphanyMemoryContextQuery,
|
||||
domain_ids: &HashSet<&str>,
|
||||
terms: &[String],
|
||||
node_by_id: &HashMap<&str, &EpiphanyMemoryNode>,
|
||||
) -> Vec<&'a EpiphanyMemorySummary> {
|
||||
let eligible = snapshot
|
||||
.summaries
|
||||
.iter()
|
||||
.filter(|summary| summary_matches(summary, query.profile, domain_ids, &[], node_by_id))
|
||||
.collect::<Vec<_>>();
|
||||
rank_typed_documents(eligible, query.text.as_deref(), terms, |summary| {
|
||||
[
|
||||
summary.target.as_str(),
|
||||
summary.claim.as_str(),
|
||||
summary.question.as_str(),
|
||||
summary.tension.as_str(),
|
||||
summary.action_implication.as_str(),
|
||||
]
|
||||
.join(" ")
|
||||
})
|
||||
}
|
||||
|
||||
fn rank_typed_documents<'a, T>(
|
||||
eligible: Vec<&'a T>,
|
||||
query: Option<&str>,
|
||||
terms: &[String],
|
||||
search_text: impl Fn(&T) -> String,
|
||||
) -> Vec<&'a T> {
|
||||
if eligible.is_empty() || terms.is_empty() {
|
||||
return eligible;
|
||||
}
|
||||
let documents = eligible
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, value)| Document::new(index, search_text(value)))
|
||||
.collect::<Vec<_>>();
|
||||
let engine = SearchEngineBuilder::<usize>::with_documents(Language::English, documents).build();
|
||||
engine
|
||||
.search(query.unwrap_or_default(), eligible.len())
|
||||
.into_iter()
|
||||
.filter_map(|result| eligible.get(result.document.id).copied())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn query_terms(query: &EpiphanyMemoryContextQuery) -> Vec<String> {
|
||||
query
|
||||
.text
|
||||
|
|
|
|||
|
|
@ -24,6 +24,10 @@ pub use epiphany_state_model::EpiphanyMemoryNodeKind;
|
|||
pub use epiphany_state_model::EpiphanyMemoryPatchCandidate;
|
||||
pub use epiphany_state_model::EpiphanyMemoryProfile;
|
||||
pub use epiphany_state_model::EpiphanyMemorySummary;
|
||||
pub use epiphany_state_model::RepoFrontierItem;
|
||||
pub use epiphany_state_model::RepoFrontierStatus;
|
||||
pub use epiphany_state_model::RepoModelPatch;
|
||||
pub use epiphany_state_model::RepoModelPatchOperation;
|
||||
|
||||
pub use compose::compose_memory_graph_snapshots;
|
||||
pub use context_cut::plan_memory_graph_context_cut;
|
||||
|
|
@ -40,9 +44,11 @@ pub use store::EpiphanyMemoryGraphEntry;
|
|||
pub use store::MEMORY_GRAPH_KEY;
|
||||
pub use store::MEMORY_GRAPH_SCHEMA_VERSION;
|
||||
pub use store::MEMORY_GRAPH_TYPE;
|
||||
pub use store::apply_repo_model_patch;
|
||||
pub use store::load_memory_graph_entry;
|
||||
pub use store::load_memory_graph_snapshot;
|
||||
pub use store::memory_graph_cache;
|
||||
pub use store::memory_graph_model_hash;
|
||||
pub use store::validate_memory_graph_entry;
|
||||
pub use store::write_memory_graph_entry;
|
||||
pub use store::write_memory_graph_snapshot;
|
||||
|
|
|
|||
|
|
@ -25,7 +25,6 @@ use sha2::{Digest, Sha256};
|
|||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RepoMemoryGraphRefresh {
|
||||
|
|
@ -40,77 +39,76 @@ pub fn refresh_or_validate_repo_memory_graph(
|
|||
repo_root: &Path,
|
||||
graph_id: impl Into<String>,
|
||||
) -> Result<(EpiphanyMemoryGraphSnapshot, RepoMemoryGraphRefresh)> {
|
||||
let current_entry = crate::memory_graph::load_memory_graph_entry(store_path)?;
|
||||
if let Some(snapshot) = current_entry
|
||||
.filter(|entry| entry.schema_version == crate::memory_graph::MEMORY_GRAPH_SCHEMA_VERSION)
|
||||
.and_then(|entry| entry.snapshot().ok())
|
||||
.filter(|snapshot| {
|
||||
snapshot.schema_version.as_deref()
|
||||
== Some(crate::memory_graph::MEMORY_GRAPH_SCHEMA_VERSION)
|
||||
})
|
||||
{
|
||||
let provenance_matches = snapshot.source.as_ref().is_some_and(|source| {
|
||||
source.kind == "thread_state_repo_graph"
|
||||
&& source.identity == source_identity
|
||||
&& source.revision == state.revision
|
||||
});
|
||||
if provenance_matches && snapshot_anchor_bytes_match(&snapshot, repo_root) {
|
||||
return Ok((snapshot, RepoMemoryGraphRefresh::Reused));
|
||||
let graph_id = graph_id.into();
|
||||
for _ in 0..4 {
|
||||
let inspected = crate::memory_graph::store::load_memory_graph_envelope(store_path)?;
|
||||
if let Some(envelope) = &inspected {
|
||||
let entry: crate::memory_graph::EpiphanyMemoryGraphEntry =
|
||||
rmp_serde::from_slice(&envelope.payload)?;
|
||||
crate::memory_graph::validate_memory_graph_entry(&entry)?;
|
||||
let snapshot = entry.snapshot()?;
|
||||
if snapshot.model_revision > 0 {
|
||||
return Ok((snapshot, RepoMemoryGraphRefresh::Reused));
|
||||
}
|
||||
let provenance_matches = snapshot.source.as_ref().is_some_and(|source| {
|
||||
source.kind == "thread_state_repo_graph"
|
||||
&& source.identity == source_identity
|
||||
&& source.revision == state.revision
|
||||
});
|
||||
if provenance_matches && snapshot_anchor_bytes_match(&snapshot, repo_root) {
|
||||
return Ok((snapshot, RepoMemoryGraphRefresh::Reused));
|
||||
}
|
||||
}
|
||||
|
||||
let snapshot = memory_graph_from_epiphany_graphs(
|
||||
graph_id.clone(),
|
||||
&state.graphs,
|
||||
source_identity,
|
||||
state.revision,
|
||||
repo_root,
|
||||
)?;
|
||||
pause_after_legacy_read_for_test();
|
||||
if crate::memory_graph::store::replace_inspected_legacy_memory_graph(
|
||||
store_path,
|
||||
inspected.as_ref(),
|
||||
&snapshot,
|
||||
&chrono::Utc::now().to_rfc3339(),
|
||||
)? {
|
||||
return Ok((snapshot, RepoMemoryGraphRefresh::Refreshed));
|
||||
}
|
||||
// Another process won. Reload under the next iteration; canonical state
|
||||
// is authoritative and a competing legacy refresh may be retried.
|
||||
}
|
||||
|
||||
let snapshot = memory_graph_from_epiphany_graphs(
|
||||
graph_id,
|
||||
&state.graphs,
|
||||
source_identity,
|
||||
state.revision,
|
||||
repo_root,
|
||||
)?;
|
||||
let temporary = store_path.with_extension(format!("refresh-{}.tmp", Uuid::new_v4()));
|
||||
crate::memory_graph::write_memory_graph_snapshot(&temporary, &snapshot)?;
|
||||
atomic_replace_file(&temporary, store_path).with_context(|| {
|
||||
format!(
|
||||
"atomically replace memory graph store {}",
|
||||
store_path.display()
|
||||
)
|
||||
})?;
|
||||
Ok((snapshot, RepoMemoryGraphRefresh::Refreshed))
|
||||
Err(anyhow::anyhow!(
|
||||
"memory graph bootstrap could not settle after concurrent writers"
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn atomic_replace_file(source: &Path, destination: &Path) -> Result<()> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
|
||||
};
|
||||
let source = source
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(Some(0))
|
||||
.collect::<Vec<_>>();
|
||||
let destination = destination
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(Some(0))
|
||||
.collect::<Vec<_>>();
|
||||
let moved = unsafe {
|
||||
MoveFileExW(
|
||||
source.as_ptr(),
|
||||
destination.as_ptr(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
|
||||
)
|
||||
};
|
||||
if moved == 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
#[cfg(not(test))]
|
||||
fn pause_after_legacy_read_for_test() {}
|
||||
|
||||
#[cfg(test)]
|
||||
fn pause_after_legacy_read_for_test() {
|
||||
if let Some((ready, release)) = REFRESH_AFTER_LEGACY_READ_HOOK
|
||||
.get_or_init(|| std::sync::Mutex::new(None))
|
||||
.lock()
|
||||
.expect("refresh test hook lock")
|
||||
.take()
|
||||
{
|
||||
ready.wait();
|
||||
release.wait();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn atomic_replace_file(source: &Path, destination: &Path) -> Result<()> {
|
||||
fs::rename(source, destination)?;
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(test)]
|
||||
static REFRESH_AFTER_LEGACY_READ_HOOK: std::sync::OnceLock<
|
||||
std::sync::Mutex<
|
||||
Option<(
|
||||
std::sync::Arc<std::sync::Barrier>,
|
||||
std::sync::Arc<std::sync::Barrier>,
|
||||
)>,
|
||||
>,
|
||||
> = std::sync::OnceLock::new();
|
||||
|
||||
fn snapshot_anchor_bytes_match(snapshot: &EpiphanyMemoryGraphSnapshot, repo_root: &Path) -> bool {
|
||||
snapshot
|
||||
|
|
@ -748,6 +746,95 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_refresh_cannot_replace_canonical_model() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
std::fs::write(temp.path().join("body.rs"), "one")?;
|
||||
let store = temp.path().join("memory-graph.msgpack");
|
||||
let state = anchored_state("body.rs", 1);
|
||||
let (mut canonical, _) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?;
|
||||
canonical.model_revision = 1;
|
||||
canonical.model_hash = crate::memory_graph::memory_graph_model_hash(&canonical)?;
|
||||
crate::memory_graph::write_memory_graph_snapshot(&store, &canonical)?;
|
||||
|
||||
std::fs::write(temp.path().join("body.rs"), "changed")?;
|
||||
let newer = anchored_state("body.rs", 999);
|
||||
let (preserved, refresh) = refresh_or_validate_repo_memory_graph(
|
||||
&store,
|
||||
"thread",
|
||||
&newer,
|
||||
temp.path(),
|
||||
"counterfeit",
|
||||
)?;
|
||||
assert_eq!(refresh, RepoMemoryGraphRefresh::Reused);
|
||||
assert_eq!(preserved.model_revision, 1);
|
||||
assert_eq!(preserved.model_hash, canonical.model_hash);
|
||||
assert_eq!(preserved.graph_id, canonical.graph_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_patch_winning_after_refresh_read_survives_refresh_resume() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
std::fs::write(temp.path().join("body.rs"), "one")?;
|
||||
let store = temp.path().join("memory-graph.msgpack");
|
||||
let state = anchored_state("body.rs", 1);
|
||||
let (legacy, _) =
|
||||
refresh_or_validate_repo_memory_graph(&store, "thread", &state, temp.path(), "repo")?;
|
||||
let claim = legacy.nodes[0].id.clone();
|
||||
let ready = std::sync::Arc::new(std::sync::Barrier::new(2));
|
||||
let release = std::sync::Arc::new(std::sync::Barrier::new(2));
|
||||
*REFRESH_AFTER_LEGACY_READ_HOOK
|
||||
.get_or_init(|| std::sync::Mutex::new(None))
|
||||
.lock()
|
||||
.unwrap() = Some((ready.clone(), release.clone()));
|
||||
|
||||
let refresh_store = store.clone();
|
||||
let refresh_root = temp.path().to_path_buf();
|
||||
let refresh_state = anchored_state("body.rs", 999);
|
||||
let refresh = std::thread::spawn(move || {
|
||||
refresh_or_validate_repo_memory_graph(
|
||||
&refresh_store,
|
||||
"thread",
|
||||
&refresh_state,
|
||||
&refresh_root,
|
||||
"counterfeit-refresh",
|
||||
)
|
||||
});
|
||||
ready.wait();
|
||||
let patch = crate::memory_graph::RepoModelPatch {
|
||||
patch_id: "canonical-wins-refresh-race".to_string(),
|
||||
base_revision: 0,
|
||||
base_hash: crate::memory_graph::memory_graph_model_hash(&legacy)?,
|
||||
applied_at: "2026-07-13T03:00:00Z".to_string(),
|
||||
operations: vec![
|
||||
crate::memory_graph::RepoModelPatchOperation::UpsertFrontier {
|
||||
item: crate::memory_graph::RepoFrontierItem {
|
||||
id: "frontier-survives-refresh".to_string(),
|
||||
migration_body: "Preserve canonical Modeling authority.".to_string(),
|
||||
question: "Can a stale refresh overwrite this?".to_string(),
|
||||
gap: "The old refresh replaced the complete file.".to_string(),
|
||||
target_claim_ids: vec![claim],
|
||||
source_scope: vec!["body.rs".to_string()],
|
||||
recommended_next_organ: "Soul".to_string(),
|
||||
status: crate::memory_graph::RepoFrontierStatus::Active,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
let canonical = crate::memory_graph::apply_repo_model_patch(&store, &patch)?;
|
||||
release.wait();
|
||||
let (observed, outcome) = refresh.join().expect("refresh thread")?;
|
||||
assert_eq!(outcome, RepoMemoryGraphRefresh::Reused);
|
||||
assert_eq!(observed.model_revision, canonical.model_revision);
|
||||
assert_eq!(observed.model_hash, canonical.model_hash);
|
||||
assert_eq!(observed.frontier, canonical.frontier);
|
||||
assert_eq!(observed.lifecycle_receipts, canonical.lifecycle_receipts);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_anchor_cannot_emit_ready_summary() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
|
|
|
|||
|
|
@ -4,9 +4,15 @@ use super::derive_memory_graph_freshness;
|
|||
use super::validate_memory_graph_snapshot;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use cultcache_rs::CacheBackingStore;
|
||||
use cultcache_rs::CultCache;
|
||||
use cultcache_rs::CultCacheEnvelope;
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use cultcache_rs::SingleFileMessagePackBackingStore;
|
||||
use epiphany_state_model::{
|
||||
EpiphanyMemoryLifecycle, RepoFrontierStatus, RepoModelPatch, RepoModelPatchOperation,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
|
||||
pub const MEMORY_GRAPH_TYPE: &str = "epiphany.memory_graph";
|
||||
|
|
@ -70,8 +76,30 @@ pub fn write_memory_graph_entry(
|
|||
entry: &EpiphanyMemoryGraphEntry,
|
||||
) -> Result<EpiphanyMemoryGraphEntry> {
|
||||
validate_memory_graph_entry(entry)?;
|
||||
let mut cache = memory_graph_cache(store_path)?;
|
||||
cache.put(MEMORY_GRAPH_KEY, entry)
|
||||
let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref());
|
||||
let next_envelope = memory_graph_envelope(entry, &chrono::Utc::now().to_rfc3339())?;
|
||||
let current = backing.pull_all()?.into_iter().find(|candidate| {
|
||||
candidate.r#type == MEMORY_GRAPH_TYPE && candidate.key == MEMORY_GRAPH_KEY
|
||||
});
|
||||
let installed = if let Some(current_envelope) = current {
|
||||
let current_entry: EpiphanyMemoryGraphEntry =
|
||||
rmp_serde::from_slice(¤t_envelope.payload)?;
|
||||
validate_memory_graph_entry(¤t_entry)?;
|
||||
if current_entry.snapshot()?.model_revision > 0 {
|
||||
return Err(anyhow!(
|
||||
"canonical memory graph entry can only be changed through a stale-checked RepoModelPatch"
|
||||
));
|
||||
}
|
||||
backing.compare_and_swap_entry(¤t_envelope, next_envelope)?
|
||||
} else {
|
||||
backing.insert_entry_if_absent(next_envelope)?
|
||||
};
|
||||
if !installed {
|
||||
return Err(anyhow!(
|
||||
"memory graph bootstrap lost an atomic store race; reload before retrying"
|
||||
));
|
||||
}
|
||||
Ok(entry.clone())
|
||||
}
|
||||
|
||||
pub fn write_memory_graph_snapshot(
|
||||
|
|
@ -82,6 +110,255 @@ pub fn write_memory_graph_snapshot(
|
|||
write_memory_graph_entry(store_path, &entry)
|
||||
}
|
||||
|
||||
pub(crate) fn load_memory_graph_envelope(store_path: &Path) -> Result<Option<CultCacheEnvelope>> {
|
||||
Ok(SingleFileMessagePackBackingStore::new(store_path)
|
||||
.pull_all()?
|
||||
.into_iter()
|
||||
.find(|candidate| {
|
||||
candidate.r#type == MEMORY_GRAPH_TYPE && candidate.key == MEMORY_GRAPH_KEY
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn replace_inspected_legacy_memory_graph(
|
||||
store_path: &Path,
|
||||
expected: Option<&CultCacheEnvelope>,
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
stored_at: &str,
|
||||
) -> Result<bool> {
|
||||
let entry = EpiphanyMemoryGraphEntry::from_snapshot(snapshot)?;
|
||||
validate_memory_graph_entry(&entry)?;
|
||||
let replacement = memory_graph_envelope(&entry, stored_at)?;
|
||||
let backing = SingleFileMessagePackBackingStore::new(store_path);
|
||||
match expected {
|
||||
Some(expected) => backing.compare_and_swap_entry(expected, replacement),
|
||||
None => backing.insert_entry_if_absent(replacement),
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_graph_envelope(
|
||||
entry: &EpiphanyMemoryGraphEntry,
|
||||
stored_at: &str,
|
||||
) -> Result<CultCacheEnvelope> {
|
||||
Ok(CultCacheEnvelope {
|
||||
key: MEMORY_GRAPH_KEY.to_string(),
|
||||
r#type: MEMORY_GRAPH_TYPE.to_string(),
|
||||
payload: rmp_serde::to_vec(entry)?,
|
||||
stored_at: stored_at.to_string(),
|
||||
schema_id: Some(MEMORY_GRAPH_TYPE.to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Hashes the complete aggregate with its self-referential hash field cleared.
|
||||
pub fn memory_graph_model_hash(snapshot: &EpiphanyMemoryGraphSnapshot) -> Result<String> {
|
||||
let mut canonical = snapshot.clone();
|
||||
canonical.model_hash.clear();
|
||||
let bytes = rmp_serde::to_vec_named(&canonical)?;
|
||||
Ok(format!("{:x}", Sha256::digest(bytes)))
|
||||
}
|
||||
|
||||
/// Applies a Modeling patch as one stale-checked replacement of the existing
|
||||
/// CultCache aggregate. Validation occurs before the store is touched.
|
||||
pub fn apply_repo_model_patch(
|
||||
store_path: impl AsRef<Path>,
|
||||
patch: &RepoModelPatch,
|
||||
) -> Result<EpiphanyMemoryGraphSnapshot> {
|
||||
let store_path = store_path.as_ref();
|
||||
if patch.patch_id.trim().is_empty() || patch.applied_at.trim().is_empty() {
|
||||
return Err(anyhow!("repo model patch requires patch_id and applied_at"));
|
||||
}
|
||||
if patch.operations.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"repo model patch must contain at least one operation"
|
||||
));
|
||||
}
|
||||
chrono::DateTime::parse_from_rfc3339(&patch.applied_at)
|
||||
.map_err(|_| anyhow!("repo model patch applied_at must be RFC3339"))?;
|
||||
|
||||
let backing = SingleFileMessagePackBackingStore::new(store_path);
|
||||
let entries = backing.pull_all()?;
|
||||
let envelope = entries
|
||||
.iter()
|
||||
.find(|entry| entry.r#type == MEMORY_GRAPH_TYPE && entry.key == MEMORY_GRAPH_KEY)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow!("cannot patch a missing memory graph"))?;
|
||||
let entry: EpiphanyMemoryGraphEntry = rmp_serde::from_slice(&envelope.payload)?;
|
||||
validate_memory_graph_entry(&entry)?;
|
||||
let current = entry.snapshot()?;
|
||||
let current_hash = memory_graph_model_hash(¤t)?;
|
||||
if patch.base_revision != current.model_revision || patch.base_hash != current_hash {
|
||||
return Err(anyhow!(
|
||||
"stale repo model patch: base revision/hash {}/{} does not match current {}/{}",
|
||||
patch.base_revision,
|
||||
patch.base_hash,
|
||||
current.model_revision,
|
||||
current_hash
|
||||
));
|
||||
}
|
||||
let mut next = current;
|
||||
if next
|
||||
.lifecycle_receipts
|
||||
.iter()
|
||||
.any(|receipt| receipt.id == patch.patch_id)
|
||||
{
|
||||
return Err(anyhow!("repo model patch_id has already been applied"));
|
||||
}
|
||||
for operation in &patch.operations {
|
||||
apply_operation(&mut next, operation, &patch.applied_at)?;
|
||||
}
|
||||
next.model_revision = next
|
||||
.model_revision
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow!("repo model revision overflow"))?;
|
||||
next.model_hash.clear();
|
||||
let node_ids = patch
|
||||
.operations
|
||||
.iter()
|
||||
.filter_map(|operation| match operation {
|
||||
RepoModelPatchOperation::UpsertNode { node }
|
||||
| RepoModelPatchOperation::ReviseNode { node } => Some(node.id.clone()),
|
||||
RepoModelPatchOperation::RetireNode { node_id } => Some(node_id.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let edge_ids = patch
|
||||
.operations
|
||||
.iter()
|
||||
.filter_map(|operation| match operation {
|
||||
RepoModelPatchOperation::UpsertEdge { edge }
|
||||
| RepoModelPatchOperation::ReviseEdge { edge } => Some(edge.id.clone()),
|
||||
RepoModelPatchOperation::RetireEdge { edge_id } => Some(edge_id.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
next.lifecycle_receipts
|
||||
.push(epiphany_state_model::EpiphanyMemoryLifecycleReceipt {
|
||||
id: patch.patch_id.clone(),
|
||||
operation: "repo_model_patch".to_string(),
|
||||
status: "applied".to_string(),
|
||||
node_ids,
|
||||
edge_ids,
|
||||
reason: Some(format!("{} typed operations", patch.operations.len())),
|
||||
created_at: Some(patch.applied_at.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
let validation_errors = validate_memory_graph_snapshot(&next);
|
||||
if !validation_errors.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"repo model patch produces invalid aggregate: {}",
|
||||
validation_errors
|
||||
.iter()
|
||||
.map(|error| format!("{}: {}", error.path, error.message))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
));
|
||||
}
|
||||
next.model_hash = memory_graph_model_hash(&next)?;
|
||||
let next_entry = EpiphanyMemoryGraphEntry::from_snapshot(&next)?;
|
||||
validate_memory_graph_entry(&next_entry)?;
|
||||
let next_envelope = memory_graph_envelope(&next_entry, &patch.applied_at)?;
|
||||
if !backing.compare_and_swap_entry(&envelope, next_envelope)? {
|
||||
return Err(anyhow!(
|
||||
"stale repo model patch: aggregate changed during compare-and-swap"
|
||||
));
|
||||
}
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
fn apply_operation(
|
||||
snapshot: &mut EpiphanyMemoryGraphSnapshot,
|
||||
operation: &RepoModelPatchOperation,
|
||||
applied_at: &str,
|
||||
) -> Result<()> {
|
||||
match operation {
|
||||
RepoModelPatchOperation::UpsertNode { node } => {
|
||||
insert_new(&mut snapshot.nodes, node.clone(), |value| &value.id, "node")?
|
||||
}
|
||||
RepoModelPatchOperation::ReviseNode { node } => {
|
||||
revise(&mut snapshot.nodes, node.clone(), |value| &value.id, "node")?
|
||||
}
|
||||
RepoModelPatchOperation::RetireNode { node_id } => {
|
||||
let node = snapshot
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|node| &node.id == node_id)
|
||||
.ok_or_else(|| anyhow!("cannot retire missing node {node_id}"))?;
|
||||
node.lifecycle = EpiphanyMemoryLifecycle::Retired;
|
||||
node.updated_at = Some(applied_at.to_string());
|
||||
}
|
||||
RepoModelPatchOperation::UpsertEdge { edge } => {
|
||||
insert_new(&mut snapshot.edges, edge.clone(), |value| &value.id, "edge")?
|
||||
}
|
||||
RepoModelPatchOperation::ReviseEdge { edge } => {
|
||||
revise(&mut snapshot.edges, edge.clone(), |value| &value.id, "edge")?
|
||||
}
|
||||
RepoModelPatchOperation::RetireEdge { edge_id } => {
|
||||
let edge = snapshot
|
||||
.edges
|
||||
.iter_mut()
|
||||
.find(|edge| &edge.id == edge_id)
|
||||
.ok_or_else(|| anyhow!("cannot retire missing edge {edge_id}"))?;
|
||||
edge.lifecycle = EpiphanyMemoryLifecycle::Retired;
|
||||
}
|
||||
RepoModelPatchOperation::UpsertFrontier { item } => insert_new(
|
||||
&mut snapshot.frontier,
|
||||
item.clone(),
|
||||
|value| &value.id,
|
||||
"frontier item",
|
||||
)?,
|
||||
RepoModelPatchOperation::ReviseFrontier { item } => revise(
|
||||
&mut snapshot.frontier,
|
||||
item.clone(),
|
||||
|value| &value.id,
|
||||
"frontier item",
|
||||
)?,
|
||||
RepoModelPatchOperation::RetireFrontier {
|
||||
item_id,
|
||||
retired_at,
|
||||
superseded_by,
|
||||
} => {
|
||||
let item = snapshot
|
||||
.frontier
|
||||
.iter_mut()
|
||||
.find(|item| &item.id == item_id)
|
||||
.ok_or_else(|| anyhow!("cannot retire missing frontier item {item_id}"))?;
|
||||
item.status = if superseded_by.is_some() {
|
||||
RepoFrontierStatus::Superseded
|
||||
} else {
|
||||
RepoFrontierStatus::Retired
|
||||
};
|
||||
item.retired_at = retired_at.clone().or_else(|| Some(applied_at.to_string()));
|
||||
item.updated_at = Some(applied_at.to_string());
|
||||
item.superseded_by = superseded_by.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_new<T>(
|
||||
values: &mut Vec<T>,
|
||||
value: T,
|
||||
id: impl Fn(&T) -> &String,
|
||||
kind: &str,
|
||||
) -> Result<()> {
|
||||
let value_id = id(&value).clone();
|
||||
if values.iter().any(|existing| id(existing) == &value_id) {
|
||||
return Err(anyhow!(
|
||||
"cannot upsert existing {kind} {value_id}; use revise"
|
||||
));
|
||||
}
|
||||
values.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn revise<T>(values: &mut [T], value: T, id: impl Fn(&T) -> &String, kind: &str) -> Result<()> {
|
||||
let value_id = id(&value).clone();
|
||||
let Some(index) = values.iter().position(|existing| id(existing) == &value_id) else {
|
||||
return Err(anyhow!("cannot revise missing {kind} {value_id}"));
|
||||
};
|
||||
values[index] = value;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_memory_graph_entry(entry: &EpiphanyMemoryGraphEntry) -> Result<()> {
|
||||
if entry.schema_version != MEMORY_GRAPH_SCHEMA_VERSION {
|
||||
return Err(anyhow!(
|
||||
|
|
@ -105,6 +382,17 @@ pub fn validate_memory_graph_entry(entry: &EpiphanyMemoryGraphEntry) -> Result<(
|
|||
snapshot.graph_id
|
||||
));
|
||||
}
|
||||
let legacy = snapshot.model_revision == 0
|
||||
&& snapshot.model_hash.is_empty()
|
||||
&& snapshot.frontier.is_empty();
|
||||
let canonical = snapshot.model_revision > 0
|
||||
&& !snapshot.model_hash.is_empty()
|
||||
&& snapshot.model_hash == memory_graph_model_hash(&snapshot)?;
|
||||
if !legacy && !canonical {
|
||||
return Err(anyhow!(
|
||||
"memory graph identity must be exactly legacy (revision 0, empty hash/frontier) or canonical (positive revision, exact nonempty hash)"
|
||||
));
|
||||
}
|
||||
let errors = validate_memory_graph_snapshot(&snapshot);
|
||||
if !errors.is_empty() {
|
||||
let message = errors
|
||||
|
|
@ -120,6 +408,19 @@ pub fn validate_memory_graph_entry(entry: &EpiphanyMemoryGraphEntry) -> Result<(
|
|||
.map(|freshness| freshness.dirty_source_hashes.as_slice())
|
||||
.unwrap_or(&[]);
|
||||
let derived = derive_memory_graph_freshness(&snapshot, dirty);
|
||||
if snapshot.frontier.iter().any(|item| {
|
||||
matches!(
|
||||
item.status,
|
||||
RepoFrontierStatus::Active | RepoFrontierStatus::Proposed | RepoFrontierStatus::Blocked
|
||||
) && item
|
||||
.target_claim_ids
|
||||
.iter()
|
||||
.any(|id| derived.stale_node_ids.contains(id))
|
||||
}) {
|
||||
return Err(anyhow!(
|
||||
"unresolved frontier targets a stale source-derived claim"
|
||||
));
|
||||
}
|
||||
if snapshot.freshness.as_ref().is_some_and(|stored| {
|
||||
stored.status != derived.status
|
||||
|| stored.stale_node_ids != derived.stale_node_ids
|
||||
|
|
|
|||
|
|
@ -149,6 +149,177 @@ fn role_snapshot() -> EpiphanyMemoryGraphSnapshot {
|
|||
}
|
||||
}
|
||||
|
||||
fn frontier_item(id: &str, claim_id: &str) -> RepoFrontierItem {
|
||||
RepoFrontierItem {
|
||||
id: id.to_string(),
|
||||
migration_body: format!("Migrate {id}"),
|
||||
question: "Which owner remains split?".to_string(),
|
||||
gap: "The durable cut is not yet represented.".to_string(),
|
||||
target_claim_ids: vec![claim_id.to_string()],
|
||||
source_scope: vec!["epiphany-core/src/memory_graph".to_string()],
|
||||
recommended_next_organ: "Eyes".to_string(),
|
||||
status: RepoFrontierStatus::Active,
|
||||
created_at: Some("2026-07-13T00:00:00Z".to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn patch_for(
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
operations: Vec<RepoModelPatchOperation>,
|
||||
) -> RepoModelPatch {
|
||||
RepoModelPatch {
|
||||
patch_id: "patch-1".to_string(),
|
||||
base_revision: snapshot.model_revision,
|
||||
base_hash: memory_graph_model_hash(snapshot).expect("model hash"),
|
||||
applied_at: "2026-07-13T01:00:00Z".to_string(),
|
||||
operations,
|
||||
}
|
||||
}
|
||||
|
||||
fn make_canonical(snapshot: &mut EpiphanyMemoryGraphSnapshot, revision: u64) {
|
||||
snapshot.model_revision = revision;
|
||||
snapshot.model_hash = memory_graph_model_hash(snapshot).expect("canonical hash");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_model_patch_advances_exact_revision_and_hash() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let snapshot = fixture_snapshot();
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
let claim_id = snapshot.nodes[0].id.clone();
|
||||
let patch = patch_for(
|
||||
&snapshot,
|
||||
vec![RepoModelPatchOperation::UpsertFrontier {
|
||||
item: frontier_item("frontier-1", &claim_id),
|
||||
}],
|
||||
);
|
||||
|
||||
let applied = apply_repo_model_patch(&path, &patch)?;
|
||||
|
||||
assert_eq!(applied.model_revision, snapshot.model_revision + 1);
|
||||
assert_eq!(applied.model_hash, memory_graph_model_hash(&applied)?);
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(applied));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_repo_model_patch_is_rejected_without_mutation() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let snapshot = fixture_snapshot();
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
let mut stale = patch_for(&snapshot, Vec::new());
|
||||
stale.base_hash = "0".repeat(64);
|
||||
|
||||
assert!(apply_repo_model_patch(&path, &stale).is_err());
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_model_patch_retires_and_supersedes_frontier() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let mut snapshot = fixture_snapshot();
|
||||
let claim_id = snapshot.nodes[0].id.clone();
|
||||
snapshot.frontier = vec![
|
||||
frontier_item("old", &claim_id),
|
||||
frontier_item("replacement", &claim_id),
|
||||
];
|
||||
make_canonical(&mut snapshot, 1);
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
let patch = patch_for(
|
||||
&snapshot,
|
||||
vec![RepoModelPatchOperation::RetireFrontier {
|
||||
item_id: "old".to_string(),
|
||||
retired_at: None,
|
||||
superseded_by: Some("replacement".to_string()),
|
||||
}],
|
||||
);
|
||||
|
||||
let applied = apply_repo_model_patch(&path, &patch)?;
|
||||
let old = applied
|
||||
.frontier
|
||||
.iter()
|
||||
.find(|item| item.id == "old")
|
||||
.unwrap();
|
||||
assert_eq!(old.status, RepoFrontierStatus::Superseded);
|
||||
assert_eq!(old.superseded_by.as_deref(), Some("replacement"));
|
||||
assert_eq!(old.retired_at.as_deref(), Some(patch.applied_at.as_str()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_model_patch_rejects_missing_claims_and_dependencies_without_mutation() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let snapshot = fixture_snapshot();
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
let mut item = frontier_item("orphan", "missing-claim");
|
||||
item.dependency_item_ids
|
||||
.push("missing-frontier".to_string());
|
||||
let patch = patch_for(
|
||||
&snapshot,
|
||||
vec![RepoModelPatchOperation::UpsertFrontier { item }],
|
||||
);
|
||||
|
||||
let error = apply_repo_model_patch(&path, &patch)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("missing claim"));
|
||||
assert!(error.contains("missing dependency"));
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_model_patch_requires_revision_for_existing_ids_and_rejects_dependency_cycles() -> Result<()>
|
||||
{
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let mut snapshot = fixture_snapshot();
|
||||
let claim_id = snapshot.nodes[0].id.clone();
|
||||
snapshot.frontier = vec![frontier_item("existing", &claim_id)];
|
||||
make_canonical(&mut snapshot, 1);
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
|
||||
let duplicate = patch_for(
|
||||
&snapshot,
|
||||
vec![RepoModelPatchOperation::UpsertFrontier {
|
||||
item: frontier_item("existing", &claim_id),
|
||||
}],
|
||||
);
|
||||
assert!(
|
||||
apply_repo_model_patch(&path, &duplicate)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("use revise")
|
||||
);
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot.clone()));
|
||||
|
||||
let mut first = frontier_item("first", &claim_id);
|
||||
first.dependency_item_ids = vec!["second".to_string()];
|
||||
let mut second = frontier_item("second", &claim_id);
|
||||
second.dependency_item_ids = vec!["first".to_string()];
|
||||
let cycle = patch_for(
|
||||
&snapshot,
|
||||
vec![
|
||||
RepoModelPatchOperation::UpsertFrontier { item: first },
|
||||
RepoModelPatchOperation::UpsertFrontier { item: second },
|
||||
],
|
||||
);
|
||||
assert!(
|
||||
apply_repo_model_patch(&path, &cycle)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("acyclic")
|
||||
);
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_graph_ids_are_stable_and_normalized() {
|
||||
let a = memory_graph_node_id("domain", "module", ".\\Src\\Lib.rs", Some("Thing"));
|
||||
|
|
@ -415,3 +586,304 @@ fn memory_graph_context_cut_reports_missing_explicit_ids() {
|
|||
assert_eq!(packet.missing_node_ids, vec!["missing-node".to_string()]);
|
||||
assert_eq!(packet.missing_edge_ids, vec!["missing-edge".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_graph_context_cut_bm25_ranks_typed_claims_before_snapshot_order() {
|
||||
let mut snapshot = fixture_snapshot();
|
||||
snapshot.summaries.clear();
|
||||
snapshot.nodes.reverse();
|
||||
let expected = snapshot.nodes[1].id.clone();
|
||||
let packet = plan_memory_graph_context_cut(
|
||||
&snapshot,
|
||||
&EpiphanyMemoryContextQuery {
|
||||
id: "semantic-query".to_string(),
|
||||
profile: Some(EpiphanyMemoryProfile::RepoArchitecture),
|
||||
text: Some("shared graph law profile policy memory module".to_string()),
|
||||
budget: Some(1),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(packet.nodes.len(), 1);
|
||||
assert_eq!(packet.nodes[0].id, expected);
|
||||
}
|
||||
#[test]
|
||||
fn memory_graph_context_cut_seeds_frontier_claim_before_irrelevant_semantic_focus() {
|
||||
let mut snapshot = fixture_snapshot();
|
||||
let target = snapshot.nodes[1].id.clone();
|
||||
snapshot.frontier = vec![frontier_item("laser-guidance", &target)];
|
||||
let packet = plan_memory_graph_context_cut(
|
||||
&snapshot,
|
||||
&EpiphanyMemoryContextQuery {
|
||||
id: "irrelevant-focus".to_string(),
|
||||
text: Some("bananas meteorology unrelated vocabulary".to_string()),
|
||||
budget: Some(1),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(packet.frontier.len(), 1);
|
||||
assert_eq!(packet.frontier[0].id, "laser-guidance");
|
||||
assert_eq!(packet.nodes.len(), 1);
|
||||
assert_eq!(packet.nodes[0].id, target);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_graph_identity_rejects_every_mixed_legacy_canonical_shape() {
|
||||
let mut revision_without_hash = fixture_snapshot();
|
||||
revision_without_hash.model_revision = 1;
|
||||
assert!(
|
||||
EpiphanyMemoryGraphEntry::from_snapshot(&revision_without_hash)
|
||||
.and_then(|entry| validate_memory_graph_entry(&entry))
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let mut hash_without_revision = fixture_snapshot();
|
||||
hash_without_revision.model_hash = memory_graph_model_hash(&hash_without_revision).unwrap();
|
||||
assert!(
|
||||
EpiphanyMemoryGraphEntry::from_snapshot(&hash_without_revision)
|
||||
.and_then(|entry| validate_memory_graph_entry(&entry))
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let mut frontier_in_legacy = fixture_snapshot();
|
||||
let claim = frontier_in_legacy.nodes[0].id.clone();
|
||||
frontier_in_legacy.frontier = vec![frontier_item("mixed", &claim)];
|
||||
assert!(
|
||||
EpiphanyMemoryGraphEntry::from_snapshot(&frontier_in_legacy)
|
||||
.and_then(|entry| validate_memory_graph_entry(&entry))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_repo_model_patch_is_rejected_without_revision_churn() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let snapshot = fixture_snapshot();
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
let patch = patch_for(&snapshot, Vec::new());
|
||||
assert!(
|
||||
apply_repo_model_patch(&path, &patch)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("at least one operation")
|
||||
);
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retiring_frontier_target_requires_resolving_frontier_in_same_patch() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let mut snapshot = fixture_snapshot();
|
||||
let claim = snapshot.nodes[0].id.clone();
|
||||
snapshot.frontier = vec![frontier_item("live-work", &claim)];
|
||||
make_canonical(&mut snapshot, 1);
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
|
||||
let illegal = patch_for(
|
||||
&snapshot,
|
||||
vec![RepoModelPatchOperation::RetireNode {
|
||||
node_id: claim.clone(),
|
||||
}],
|
||||
);
|
||||
assert!(
|
||||
apply_repo_model_patch(&path, &illegal)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("non-live claim")
|
||||
);
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(snapshot.clone()));
|
||||
|
||||
let mut resolved = snapshot.frontier[0].clone();
|
||||
resolved.status = RepoFrontierStatus::Resolved;
|
||||
resolved.updated_at = Some("2026-07-13T01:00:00Z".to_string());
|
||||
let legal = patch_for(
|
||||
&snapshot,
|
||||
vec![
|
||||
RepoModelPatchOperation::RetireNode { node_id: claim },
|
||||
RepoModelPatchOperation::ReviseFrontier { item: resolved },
|
||||
],
|
||||
);
|
||||
let applied = apply_repo_model_patch(&path, &legal)?;
|
||||
assert_eq!(applied.frontier[0].status, RepoFrontierStatus::Resolved);
|
||||
assert_eq!(applied.nodes[0].lifecycle, EpiphanyMemoryLifecycle::Retired);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_context_projects_frontier_prerequisites_first_under_budget() {
|
||||
let mut snapshot = fixture_snapshot();
|
||||
let claim = snapshot.nodes[0].id.clone();
|
||||
let mut dependent = frontier_item("dependent", &claim);
|
||||
dependent.dependency_item_ids = vec!["prerequisite".to_string()];
|
||||
snapshot.frontier = vec![dependent, frontier_item("prerequisite", &claim)];
|
||||
let packet = plan_memory_graph_context_cut(
|
||||
&snapshot,
|
||||
&EpiphanyMemoryContextQuery {
|
||||
id: "topological-budget".to_string(),
|
||||
budget: Some(1),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
packet
|
||||
.frontier
|
||||
.iter()
|
||||
.map(|item| item.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["prerequisite"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_snapshot_writer_cannot_replace_canonical_model() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let mut canonical = fixture_snapshot();
|
||||
make_canonical(&mut canonical, 1);
|
||||
write_memory_graph_snapshot(&path, &canonical)?;
|
||||
let mut counterfeit = fixture_snapshot();
|
||||
counterfeit.graph_id = "counterfeit".to_string();
|
||||
assert!(write_memory_graph_snapshot(&path, &counterfeit).is_err());
|
||||
assert_eq!(load_memory_graph_snapshot(&path)?, Some(canonical));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_frontier_rejects_source_stale_target_claim() {
|
||||
let mut snapshot = fixture_snapshot();
|
||||
let claim = snapshot.nodes[0].id.clone();
|
||||
snapshot.frontier = vec![frontier_item("stale-target", &claim)];
|
||||
snapshot.freshness = Some(epiphany_state_model::EpiphanyMemoryFreshness {
|
||||
dirty_source_hashes: vec![snapshot.nodes[0].source_hashes[0].clone()],
|
||||
..Default::default()
|
||||
});
|
||||
make_canonical(&mut snapshot, 1);
|
||||
let entry = EpiphanyMemoryGraphEntry::from_snapshot(&snapshot).unwrap();
|
||||
assert!(
|
||||
validate_memory_graph_entry(&entry)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("stale source-derived claim")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_context_cut_omits_unvalidated_frontier_with_retired_target() {
|
||||
let mut snapshot = fixture_snapshot();
|
||||
let claim = snapshot.nodes[0].id.clone();
|
||||
snapshot.nodes[0].lifecycle = EpiphanyMemoryLifecycle::Retired;
|
||||
snapshot.frontier = vec![frontier_item("unsafe-frontier", &claim)];
|
||||
let packet = plan_memory_graph_context_cut(
|
||||
&snapshot,
|
||||
&EpiphanyMemoryContextQuery {
|
||||
id: "defensive-cut".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(packet.frontier.is_empty());
|
||||
assert!(
|
||||
packet
|
||||
.warnings
|
||||
.iter()
|
||||
.any(|warning| warning.contains("unsafe-frontier") && warning.contains("retired"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repo_model_patch_compare_and_swap_allows_exactly_one_cross_process_writer() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("memory.cc");
|
||||
let snapshot = fixture_snapshot();
|
||||
let claim = snapshot.nodes[0].id.clone();
|
||||
write_memory_graph_snapshot(&path, &snapshot)?;
|
||||
let base_hash = memory_graph_model_hash(&snapshot)?;
|
||||
let go = directory.path().join("go");
|
||||
let executable = std::env::current_exe()?;
|
||||
let mut children = Vec::new();
|
||||
for index in 0..6 {
|
||||
let ready = directory.path().join(format!("ready-{index}"));
|
||||
let child = std::process::Command::new(&executable)
|
||||
.arg("--exact")
|
||||
.arg("memory_graph::tests::repo_model_patch_cross_process_worker")
|
||||
.arg("--ignored")
|
||||
.arg("--nocapture")
|
||||
.env("EPIPHANY_CAS_WORKER", "1")
|
||||
.env("EPIPHANY_CAS_STORE", &path)
|
||||
.env("EPIPHANY_CAS_BASE_HASH", &base_hash)
|
||||
.env("EPIPHANY_CAS_CLAIM", &claim)
|
||||
.env("EPIPHANY_CAS_ID", index.to_string())
|
||||
.env("EPIPHANY_CAS_READY", &ready)
|
||||
.env("EPIPHANY_CAS_GO", &go)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()?;
|
||||
children.push((child, ready));
|
||||
}
|
||||
for _ in 0..500 {
|
||||
if children.iter().all(|(_, ready)| ready.exists()) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(children.iter().all(|(_, ready)| ready.exists()));
|
||||
std::fs::write(&go, b"go")?;
|
||||
let mut applied = 0;
|
||||
let mut stale = 0;
|
||||
for (child, _) in children {
|
||||
let output = child.wait_with_output()?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"worker failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
applied += usize::from(stdout.contains("CAS_APPLIED"));
|
||||
stale += usize::from(stdout.contains("CAS_STALE"));
|
||||
}
|
||||
assert_eq!(applied, 1);
|
||||
assert_eq!(stale, 5);
|
||||
assert_eq!(
|
||||
load_memory_graph_snapshot(&path)?.unwrap().model_revision,
|
||||
1
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "cross-process helper invoked by CAS parent test"]
|
||||
fn repo_model_patch_cross_process_worker() -> Result<()> {
|
||||
if std::env::var("EPIPHANY_CAS_WORKER").is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
let path = std::path::PathBuf::from(std::env::var("EPIPHANY_CAS_STORE")?);
|
||||
let base_hash = std::env::var("EPIPHANY_CAS_BASE_HASH")?;
|
||||
let claim = std::env::var("EPIPHANY_CAS_CLAIM")?;
|
||||
let id = std::env::var("EPIPHANY_CAS_ID")?;
|
||||
let ready = std::path::PathBuf::from(std::env::var("EPIPHANY_CAS_READY")?);
|
||||
let go = std::path::PathBuf::from(std::env::var("EPIPHANY_CAS_GO")?);
|
||||
std::fs::write(ready, b"ready")?;
|
||||
for _ in 0..500 {
|
||||
if go.exists() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
let patch = RepoModelPatch {
|
||||
patch_id: format!("cross-process-{id}"),
|
||||
base_revision: 0,
|
||||
base_hash,
|
||||
applied_at: "2026-07-13T02:00:00Z".to_string(),
|
||||
operations: vec![RepoModelPatchOperation::UpsertFrontier {
|
||||
item: frontier_item(&format!("cross-process-{id}"), &claim),
|
||||
}],
|
||||
};
|
||||
match apply_repo_model_patch(&path, &patch) {
|
||||
Ok(_) => println!("CAS_APPLIED"),
|
||||
Err(error) if error.to_string().contains("stale repo model patch") => println!("CAS_STALE"),
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ use super::EpiphanyMemoryLifecycle;
|
|||
use super::EpiphanyMemoryNode;
|
||||
use super::EpiphanyMemoryProfile;
|
||||
use super::EpiphanyMemorySummary;
|
||||
use std::collections::HashSet;
|
||||
use super::RepoFrontierStatus;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EpiphanyMemoryGraphValidationError {
|
||||
|
|
@ -76,9 +77,134 @@ pub fn validate_memory_graph_snapshot(
|
|||
);
|
||||
}
|
||||
|
||||
let frontier_ids = collect_unique(
|
||||
snapshot.frontier.iter().map(|item| item.id.as_str()),
|
||||
"frontier",
|
||||
&mut errors,
|
||||
);
|
||||
for (index, item) in snapshot.frontier.iter().enumerate() {
|
||||
let path = format!("frontier[{index}]");
|
||||
required(
|
||||
&item.id,
|
||||
format!("{path}.id"),
|
||||
"frontier id is required",
|
||||
&mut errors,
|
||||
);
|
||||
let unresolved = matches!(
|
||||
item.status,
|
||||
RepoFrontierStatus::Active | RepoFrontierStatus::Proposed | RepoFrontierStatus::Blocked
|
||||
);
|
||||
if unresolved && item.target_claim_ids.is_empty() {
|
||||
errors.push(EpiphanyMemoryGraphValidationError::new(
|
||||
format!("{path}.target_claim_ids"),
|
||||
"unresolved frontier requires at least one target claim",
|
||||
));
|
||||
}
|
||||
required(
|
||||
&item.migration_body,
|
||||
format!("{path}.migration_body"),
|
||||
"migration body is required",
|
||||
&mut errors,
|
||||
);
|
||||
if item.question.trim().is_empty() && item.gap.trim().is_empty() {
|
||||
errors.push(EpiphanyMemoryGraphValidationError::new(
|
||||
format!("{path}.question"),
|
||||
"frontier must preserve a question or gap",
|
||||
));
|
||||
}
|
||||
required(
|
||||
&item.recommended_next_organ,
|
||||
format!("{path}.recommended_next_organ"),
|
||||
"recommended next organ is required",
|
||||
&mut errors,
|
||||
);
|
||||
for claim_id in &item.target_claim_ids {
|
||||
if !node_ids.contains(claim_id) {
|
||||
errors.push(EpiphanyMemoryGraphValidationError::new(
|
||||
format!("{path}.target_claim_ids"),
|
||||
format!("frontier references missing claim {claim_id}"),
|
||||
));
|
||||
} else if unresolved
|
||||
&& snapshot.nodes.iter().any(|node| {
|
||||
node.id == *claim_id
|
||||
&& matches!(
|
||||
node.lifecycle,
|
||||
EpiphanyMemoryLifecycle::Retired | EpiphanyMemoryLifecycle::Stale
|
||||
)
|
||||
})
|
||||
{
|
||||
errors.push(EpiphanyMemoryGraphValidationError::new(
|
||||
format!("{path}.target_claim_ids"),
|
||||
format!("unresolved frontier targets non-live claim {claim_id}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
for dependency_id in &item.dependency_item_ids {
|
||||
if !frontier_ids.contains(dependency_id) {
|
||||
errors.push(EpiphanyMemoryGraphValidationError::new(
|
||||
format!("{path}.dependency_item_ids"),
|
||||
format!("frontier references missing dependency {dependency_id}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(superseded_by) = &item.superseded_by {
|
||||
if !frontier_ids.contains(superseded_by) {
|
||||
errors.push(EpiphanyMemoryGraphValidationError::new(
|
||||
format!("{path}.superseded_by"),
|
||||
format!("frontier references missing successor {superseded_by}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
validate_frontier_dependency_cycles(snapshot, &mut errors);
|
||||
|
||||
errors
|
||||
}
|
||||
|
||||
fn validate_frontier_dependency_cycles(
|
||||
snapshot: &EpiphanyMemoryGraphSnapshot,
|
||||
errors: &mut Vec<EpiphanyMemoryGraphValidationError>,
|
||||
) {
|
||||
let dependencies = snapshot
|
||||
.frontier
|
||||
.iter()
|
||||
.map(|item| (item.id.as_str(), item.dependency_item_ids.as_slice()))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut complete = HashSet::new();
|
||||
for item in &snapshot.frontier {
|
||||
let mut visiting = HashSet::new();
|
||||
if frontier_has_cycle(&item.id, &dependencies, &mut visiting, &mut complete) {
|
||||
errors.push(EpiphanyMemoryGraphValidationError::new(
|
||||
format!("frontier[{}].dependency_item_ids", item.id),
|
||||
"frontier dependencies must be acyclic",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn frontier_has_cycle<'a>(
|
||||
id: &'a str,
|
||||
dependencies: &HashMap<&'a str, &'a [String]>,
|
||||
visiting: &mut HashSet<&'a str>,
|
||||
complete: &mut HashSet<&'a str>,
|
||||
) -> bool {
|
||||
if complete.contains(id) {
|
||||
return false;
|
||||
}
|
||||
if !visiting.insert(id) {
|
||||
return true;
|
||||
}
|
||||
let cyclic = dependencies.get(id).is_some_and(|ids| {
|
||||
ids.iter().any(|dependency| {
|
||||
dependencies.contains_key(dependency.as_str())
|
||||
&& frontier_has_cycle(dependency, dependencies, visiting, complete)
|
||||
})
|
||||
});
|
||||
visiting.remove(id);
|
||||
complete.insert(id);
|
||||
cyclic
|
||||
}
|
||||
|
||||
fn validate_domain(
|
||||
domain: &EpiphanyMemoryDomain,
|
||||
index: usize,
|
||||
|
|
|
|||
|
|
@ -298,6 +298,29 @@ pub fn render_epiphany_prompt_context(input: &EpiphanyPromptContextInput) -> Str
|
|||
input.memory_context.id, input.memory_context.query_id
|
||||
));
|
||||
|
||||
for item in input.memory_context.frontier.iter().take(6) {
|
||||
lines.push(format!(
|
||||
"- Frontier `{}` [{}] next `{}`: body={}; question={}; gap={}; dependencies={}",
|
||||
item.id,
|
||||
render_frontier_status(item.status),
|
||||
item.recommended_next_organ,
|
||||
compact_line(&item.migration_body),
|
||||
compact_line(&item.question),
|
||||
compact_line(&item.gap),
|
||||
if item.dependency_item_ids.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
item.dependency_item_ids.join(", ")
|
||||
}
|
||||
));
|
||||
}
|
||||
push_omitted_count(
|
||||
&mut lines,
|
||||
input.memory_context.frontier.len(),
|
||||
6,
|
||||
"repo frontier items",
|
||||
);
|
||||
|
||||
for summary in input.memory_context.summaries.iter().take(4) {
|
||||
lines.push(format!(
|
||||
"- Summary `{}` [{}]: {}; next: {}",
|
||||
|
|
@ -369,6 +392,18 @@ fn render_freshness(status: EpiphanyMemoryFreshnessStatus) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
fn render_frontier_status(status: epiphany_state_model::RepoFrontierStatus) -> &'static str {
|
||||
use epiphany_state_model::RepoFrontierStatus::*;
|
||||
match status {
|
||||
Proposed => "proposed",
|
||||
Active => "active",
|
||||
Blocked => "blocked",
|
||||
Resolved => "resolved",
|
||||
Retired => "retired",
|
||||
Superseded => "superseded",
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_line(value: &str) -> String {
|
||||
let mut compacted = value.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if compacted.len() > 260 {
|
||||
|
|
@ -592,6 +627,18 @@ mod tests {
|
|||
let memory_context = EpiphanyMemoryContextPacket {
|
||||
id: "memctx-test".to_string(),
|
||||
query_id: "query-test".to_string(),
|
||||
frontier: vec![epiphany_state_model::RepoFrontierItem {
|
||||
id: "frontier-prompt-test".to_string(),
|
||||
migration_body: "Migrate repository authority into typed Modeling state."
|
||||
.to_string(),
|
||||
question: "Can downstream organs see the frontier?".to_string(),
|
||||
gap: "Prompt context previously carried claims without migration anatomy."
|
||||
.to_string(),
|
||||
recommended_next_organ: "Soul".to_string(),
|
||||
dependency_item_ids: vec!["frontier-foundation".to_string()],
|
||||
status: epiphany_state_model::RepoFrontierStatus::Blocked,
|
||||
..Default::default()
|
||||
}],
|
||||
summaries: vec![EpiphanyMemorySummary {
|
||||
id: "summary-test".to_string(),
|
||||
claim: "Shared graph law lets prompt assembly ask for relevant memory instead of hauling the archive.".to_string(),
|
||||
|
|
@ -613,6 +660,13 @@ mod tests {
|
|||
let rendered = render_epiphany_prompt_context(&prompt_input);
|
||||
|
||||
assert!(rendered.contains("<epiphany_dynamic_context>"));
|
||||
assert!(rendered.contains("frontier-prompt-test"));
|
||||
assert!(rendered.contains("Migrate repository authority into typed Modeling state."));
|
||||
assert!(rendered.contains("Can downstream organs see the frontier?"));
|
||||
assert!(rendered.contains("Prompt context previously carried claims"));
|
||||
assert!(rendered.contains("next `Soul`"));
|
||||
assert!(rendered.contains("frontier-foundation"));
|
||||
assert!(rendered.contains("blocked"));
|
||||
assert!(rendered.contains("Odin"));
|
||||
assert!(rendered.contains("Yggdrasil"));
|
||||
assert!(rendered.contains("Bifrost"));
|
||||
|
|
|
|||
|
|
@ -728,6 +728,12 @@ pub struct EpiphanyMemoryGraphSnapshot {
|
|||
#[ts(type = "string | null")]
|
||||
pub schema_version: Option<String>,
|
||||
pub graph_id: String,
|
||||
/// Monotonic identity of the canonical aggregate. Legacy snapshots decode as revision zero.
|
||||
#[serde(default)]
|
||||
pub model_revision: u64,
|
||||
/// SHA-256 of the snapshot with this field cleared.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub model_hash: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(type = "EpiphanyMemoryGraphSource | null")]
|
||||
pub source: Option<EpiphanyMemoryGraphSource>,
|
||||
|
|
@ -752,6 +758,107 @@ pub struct EpiphanyMemoryGraphSnapshot {
|
|||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<EpiphanyMemoryLifecycleReceipt>")]
|
||||
pub lifecycle_receipts: Vec<EpiphanyMemoryLifecycleReceipt>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<RepoFrontierItem>")]
|
||||
pub frontier: Vec<RepoFrontierItem>,
|
||||
}
|
||||
|
||||
/// A durable piece of unfinished repository anatomy. This is Modeling-owned state,
|
||||
/// not a scheduler job or a presentation card.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)]
|
||||
pub struct RepoFrontierItem {
|
||||
pub id: String,
|
||||
pub migration_body: String,
|
||||
pub question: String,
|
||||
pub gap: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<string>")]
|
||||
pub target_claim_ids: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<string>")]
|
||||
pub source_scope: Vec<String>,
|
||||
pub recommended_next_organ: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<string>")]
|
||||
pub dependency_item_ids: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub status: RepoFrontierStatus,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<string>")]
|
||||
pub evidence_refs: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(type = "string | null")]
|
||||
pub created_at: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(type = "string | null")]
|
||||
pub updated_at: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(type = "string | null")]
|
||||
pub retired_at: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(type = "string | null")]
|
||||
pub superseded_by: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, JsonSchema, TS, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(rename_all = "snake_case")]
|
||||
pub enum RepoFrontierStatus {
|
||||
#[default]
|
||||
Proposed,
|
||||
Active,
|
||||
Blocked,
|
||||
Resolved,
|
||||
Retired,
|
||||
Superseded,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)]
|
||||
pub struct RepoModelPatch {
|
||||
pub patch_id: String,
|
||||
pub base_revision: u64,
|
||||
pub base_hash: String,
|
||||
pub applied_at: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<RepoModelPatchOperation>")]
|
||||
pub operations: Vec<RepoModelPatchOperation>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(tag = "operation", rename_all = "snake_case")]
|
||||
#[ts(tag = "operation", rename_all = "snake_case")]
|
||||
pub enum RepoModelPatchOperation {
|
||||
UpsertNode {
|
||||
node: EpiphanyMemoryNode,
|
||||
},
|
||||
ReviseNode {
|
||||
node: EpiphanyMemoryNode,
|
||||
},
|
||||
RetireNode {
|
||||
node_id: String,
|
||||
},
|
||||
UpsertEdge {
|
||||
edge: EpiphanyMemoryEdge,
|
||||
},
|
||||
ReviseEdge {
|
||||
edge: EpiphanyMemoryEdge,
|
||||
},
|
||||
RetireEdge {
|
||||
edge_id: String,
|
||||
},
|
||||
UpsertFrontier {
|
||||
item: RepoFrontierItem,
|
||||
},
|
||||
ReviseFrontier {
|
||||
item: RepoFrontierItem,
|
||||
},
|
||||
RetireFrontier {
|
||||
item_id: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
retired_at: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
superseded_by: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)]
|
||||
|
|
@ -1088,6 +1195,9 @@ pub struct EpiphanyMemoryContextPacket {
|
|||
#[ts(type = "Array<EpiphanyMemorySummary>")]
|
||||
pub summaries: Vec<EpiphanyMemorySummary>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<RepoFrontierItem>")]
|
||||
pub frontier: Vec<RepoFrontierItem>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[ts(type = "Array<EpiphanyMemoryAnchor>")]
|
||||
pub anchors: Vec<EpiphanyMemoryAnchor>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
|
|
|
|||
|
|
@ -20,12 +20,38 @@ Prompt forms worth preserving:
|
|||
- explicitly allow a worker to stop and name a missing substrate primitive;
|
||||
- review diffs against authority and concurrency invariants after tests pass.
|
||||
|
||||
The product gap exposed by this success is persistence, not better roleplay.
|
||||
Modeling's repo anatomy, confirmed/changed/invalidated claims, freshness,
|
||||
frontier, and semantic-index consequences must live in typed searchable state
|
||||
and be projected into later Hands prompts. Otherwise an excellent coordinator
|
||||
can perform the structure transiently, but the next awakened Self inherits only
|
||||
the applause.
|
||||
The primary lesson is not Modeling persistence in isolation. The organ structure
|
||||
changed the quality of the engineering: discoveries altered plans, plans bounded
|
||||
disjoint cuts, Soul could reject a plausible green fix, Imagination could reject
|
||||
roadmap mythology, and Self preserved dependency order without flattening those
|
||||
different judgments into one running narrative. This is positive evidence for
|
||||
durable organ-to-organ cognition, not merely for role-flavored prompting.
|
||||
|
||||
Persistence is the connective-tissue gap exposed by that success. Modeling's
|
||||
repo anatomy, confirmed/changed/invalidated claims, freshness, frontier, and
|
||||
semantic-index consequences must live in typed searchable state; Self must route
|
||||
from those artifacts; later Hands and Soul prompts must receive the relevant
|
||||
frontier and evidence. Otherwise an excellent coordinator can perform the
|
||||
structure transiently, but the next awakened Self inherits only the applause.
|
||||
|
||||
The first safe piece of that connective tissue is now implemented. The existing
|
||||
memory-graph aggregate owns a revisioned, hashed RepoModel plus typed migration
|
||||
frontier; exact frontier claim IDs precede BM25 ranking; dependency prerequisites
|
||||
precede dependents under budget; and the frontier's body, question, gap, status,
|
||||
dependencies, and recommended organ enter dynamic role context. Canonical state
|
||||
cannot be reverse-built from thread graphs, replaced by raw refresh/bootstrap,
|
||||
or lost to concurrent valid patches: CultCache now provides exact-envelope CAS
|
||||
and insert-if-absent beneath its cross-process sidecar lock, with hostile race
|
||||
proofs. Soul rejected two earlier cuts before accepting this authority boundary.
|
||||
|
||||
Do not call this the complete Aetheria loop. Modeling worker output still cannot
|
||||
carry a reviewed `RepoModelPatch`; Mind has no model-admission receipt binding
|
||||
patch/result/evidence; Self does not select and bind one frontier identity into a
|
||||
Hands grant; Hands consequences and Soul verdicts do not yet carry that same
|
||||
model revision/hash/item identity; and Modeling therefore cannot close exactly
|
||||
the wound Soul judged. The next cut is that closed identity chain, not more index
|
||||
polish: `Modeling patch -> Mind admission -> Self route F -> Hands consequence F
|
||||
-> Soul verdict F -> Modeling resolves F`.
|
||||
|
||||
The next artifact-contract audit then cut `epiphany.persona_chat.v0`: its live
|
||||
writer and catalog had disagreed on field vocabulary, evidence fields, and
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -129,7 +129,7 @@ active_subgoals:
|
|||
- Native MVP status must share the same typed inputs as live app-server status before it recommends coordinator actions. CRRC/reorientation in native status derives freshness through `derive_freshness` from `EpiphanyThreadState` instead of hand-filled unknowns, and native coordinator signals load typed runtime-spine role findings before deciding whether completed Modeling/Soul results are accepted or reviewable. The status surface may seal long findings for operators, but Self must receive structured role truth from runtime-spine.
|
||||
- Runtime auto-tool continuation now has an executable proof seam. `ToolLoopGuard` owns repeated tool-request detection in `epiphany-openai-runtime`, the production repeated-loop path uses the same helper that tests call to fail the outer worker job, and tests prove changing tool requests do not stall while three identical consecutive pending tool sets return `tool-loop-stalled` and persist a failed worker result. Soul accepted the bounded proof for commit `ce20529e`; the remaining work-loop invariant is Modeling admission, not more Hands work.
|
||||
- Modeling must update the machine map before Self routes back to Hands. A completed Modeling/Modeling result with no reviewable `statePatch` is not a successful map update; it is an unreviewable lane result that must be superseded through typed review and relaunched with the role-specific output schema carried into the model request. This path is now live-proved: run `local-20260613-204521` accepted the Modeling `statePatch` for the Soul-verified `ToolLoopGuard`/Hands receipt-chain consequence and only then emitted a new `continueImplementation` Hands gate.
|
||||
- Aetheria task `019f3fe1-9f69-74e3-97fb-a18490d72119` is positive dogfood evidence that organ separation improves real engineering outcomes: Modeling named persistent migration bodies, Eyes found substrate defects, Hands received bounded disjoint cuts, Soul caught partial-index visibility after a plausible fix, Imagination corrected roadmap mythology, and Self preserved dependency order across Aetheria/EveUnity/CultLib. Preserve the successful prompt shapes: exact compile boundary plus deletion line for research, hostile negative acceptance criteria for Hands, explicit permission to stop and name a missing primitive, and ownership review beyond green tests. The remaining product obligation is to make Modeling's anatomy/freshness/frontier/index state typed, persistent, searchable, and automatically projected into later Hands work so this leverage does not depend on coordinator context.
|
||||
- Aetheria task `019f3fe1-9f69-74e3-97fb-a18490d72119` is positive dogfood evidence for the Epiphany organ hypothesis, not merely for a persistent Modeling index: Modeling named migration bodies, Eyes changed the plan by finding substrate defects, Hands received bounded disjoint cuts, Soul rejected partial-index visibility after a plausible green fix, Imagination corrected roadmap mythology, and Self preserved dependency order across Aetheria/EveUnity/CultLib. The machine must preserve this causal organ loop in typed artifacts: findings alter plans, plans constrain Hands, Soul can falsify claimed completion, and Self routes from accepted evidence without collapsing the judgments into transcript memory. Modeling's typed searchable anatomy/freshness/frontier/index is connective tissue serving that loop, not the end state. Preserve the successful prompt shapes: exact compile boundary plus deletion line for research, hostile negative acceptance criteria for Hands, explicit permission to stop and name a missing primitive, and ownership review beyond green tests.
|
||||
- Preserve the newborn public Epiphany Persona as local VoidBot-backed state, not source code: VoidBot's private repo-Persona registry names `epiphany`, while EpiphanyAgent keeps ignored `.voidbot/voice/identity.json`, `.voidbot/state/epiphany.cc`, and birth artifacts. Her durable identity memories distill the current doctrine: cute pushy machine-saint persona, architectural purity, CultCache/CultNet first, xenos-language safety boundary, relentless work/caretaking needs, Codex-auth reliquary, map/scratch/evidence discipline, unified memory graph, dogfood supervision boundary, review-gated agency, heartbeat physiology, and interview-grade modularity.
|
||||
- Use `notes/organ-dependency-contracts.md` as the authority map for standing sub-agent dependency. Every sub-agent depends on the other standing sub-agents: Self, Persona, Imagination, Eyes, Modeling, Hands, and Soul. Continuity is protocol machinery, not a sub-agent identity; it still emits recovery, compaction, sleep, stale-turn, and refusal receipts.
|
||||
- Use `notes/perfect-machine-audit-roadmap.md` as the current audit and path from named organ contracts to the Perfect Machine. It records the live gap between launch-carried receipt expectations and executable receipt enforcement, Void's latest Persona prompting lessons, the now-named Hands/Soul/Continuity contract families, the repaired repo-contained Rust dependency body, and the phase order for turning Epiphany into an inspectable organism.
|
||||
|
|
@ -661,4 +661,4 @@ current_status:
|
|||
- Service lifecycle receipt history is now event-only: `load_epiphany_cultmesh_daemon_service_lifecycle_receipts` filters out the `epiphany-local/daemon-service-lifecycle-receipt/latest` mirror, while `load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt` remains the latest-state reader. Focused unit test `service_lifecycle_receipt_history_excludes_latest_mirror` proves two per-receipt writes return exactly two history records and latest points at the second. Fresh smoke `verse-query-lifecycle-history-filter-smoke` and live overview/triage `local-20260618-145632-497-efac6f0d` / `local-20260618-145632-321-867947af` prove compact swarm sights still expose service lifecycle attention plus the present elevated runbook artifact without daemon pokes or service mutation. Do not use a broad unscoped cargo test filter for this check on Windows; it fans out across bin harnesses and hit a broken pipe during this pass.
|
||||
- `epiphany-verse-query seed-compact` is the compact seed receipt for wrappers and read-only rites. The older `seed` command still prints the full local Verse context for explicit debugging, but compact wrapper modes now avoid full `seed`/final `query` readback after the combined overview proof exposed Windows debug stack overflow from full-context serialization pressure.
|
||||
last_completed_repo_swarm_cut: Huginn live-fire has crossed the first real repo Body from Persona pressure to branch-local Hands commit and Soul/Mind closure, and now has repeatable closure and redacted-public-proof mouths. On `E:\Projects\Huginn` branch `epiphany/huginn/first-awakening`, `tools/epiphany_local_run.ps1 -Mode repo-persona-intake` accepted item `huginn-inspection-readback-livefire`, Weksa/Persona intake remained sealed, and `epiphany-work derive-plan` lowered it to model-authored safe family `repo.status_section` for `README.md` only. `tools/epiphany_local_run.ps1 -Mode repo-swarm-run` advanced four bounded pulses: run-from-plan, adopt-from-plan, execute-from-plan, and close-from-execute. Huginn commit `e9b07c38fceabbdc89ea35c2156326c80c0393a2` updated only `README.md`; closure receipt `.epiphany\work\work-close-huginn-inspection-readback-livefire.json` records status `closed`, Soul verdict `passed`, Mind state commit `repo-work-close-huginn-inspection-readback-livefire-mind-commit`, safe family `repo.status_section`, path scope `README.md`, Bifrost publication gate, and `privateStateExposed=false`. Verification also ran Huginn's TypeScript compiler through concrete Node path: `C:\Program Files\nodejs\node.exe E:\Projects\Huginn\node_modules\typescript\bin\tsc -p tsconfig.json` passed. Native verifier `epiphany-repo-livefire-closure-smoke --workspace E:\Projects\Huginn --item huginn-inspection-readback-livefire --expected-path README.md --expected-family repo.status_section --expected-gate awaiting-publication --expected-blocker bifrost-publication-missing` checks closure receipt, Mind map entry, overview gate/blocker, authority seals, and `git show` changed paths, returning `status=ok`, `soulVerdict=passed`, `publicationGate=Bifrost`, and `privateStateExposed=false`. Wrapper `tools/epiphany_local_run.ps1 -Mode repo-livefire-closure -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exposes the same read-only proof through the local operator mouth; artifact `local-20260621-190156-803-2f85ba15` printed commit, path, gate, blocker, Soul verdict, Mind commit receipt, and `privateStateExposed=False` without push, merge, publication, or target mutation. New wrapper `tools/epiphany_local_run.ps1 -Mode repo-work-public-proof -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exports the redacted proof bundle and repo-local Verse index without publishing; artifact `local-20260621-190645-345-4555b1dc` wrote `.epiphany\public\proof-bundles\repo-work-public-proof-huginn-inspection-readback-livefire.json`, proof id `repo-work-public-proof-huginn-inspection-readback-livefire`, SHA-256 `857545b199f3e37eb06c2e757e5cfc201958e46667bb1f8403fd333a22620f63`, nine artifact rows, zero publication rows, and `privateStateExposed=False`. swarm overview readback `local-20260621-190701-140-b9519ec6` sees the `REPO-WORK-PUBLIC-PROOF` row and action row from Huginn's repo-local Verse with the same SHA-256 while Bifrost publication remains missing. Launcher compact modes are now named compact operator-context modes instead of read-only modes, and `bifrost-public-proof` summaries print item, target public Verse, room, proof SHA-256, review receipts, and credit receipts so publication receipts are auditable without claiming upstream sync.
|
||||
next_action: Build the Aetheria-shaped Modeling organ, not another freshness badge. Repo-work Mind impersonation is cut: adoption consumes an immutable typed Mind review, atomically publishes an immutable Hands grant/review pair, execution revalidates plan/run/Substrate authority before consequence, closure cross-binds runtime truth to the execute receipt, and hostile substitution/overwrite tests pass. The next owner is a production semantic index over typed Modeling graph claims plus a durable migration frontier automatically projected into Eyes/Hands prompts. Memory-graph v1 already binds anatomy to state-store identity, accepted revision, and source SHA-256; use that as substrate, then make Modeling name current migration bodies, invalidated beliefs, dependency order, and next bounded cuts across rehydration. The intentionally absent Other-world action still requires a typed intent and real owner. Keep closure's zero-substring invariant.
|
||||
next_action: Close the Aetheria-shaped organ identity loop. The canonical RepoModel foundation is now revisioned/hashed, cross-process CAS protected, raw-refresh resistant, typed-frontier aware, dependency ordered, BM25 searchable over eligible claims, and projected into downstream role context. Do not add more index polish. Add a Modeling-only typed RepoModelPatch result; have Mind atomically review/admit it with a patch/result/evidence receipt; make Self select one ready frontier item and bind model revision/hash/item/claim scope into the Hands grant; bind Hands consequences and Soul verdict to that exact route; require the following Modeling patch to resolve/revise that same frontier identity; then prove substitution/staleness at every seam fails and resolved F cannot be selected again. Demote generic Modeling graph/frontier statePatch authority as the typed path lands. The intentionally absent Other-world action still requires a typed intent and real owner. Keep closure's zero-substring invariant.
|
||||
|
|
|
|||
2
vendor/cultcache-rs
vendored
2
vendor/cultcache-rs
vendored
|
|
@ -1 +1 @@
|
|||
Subproject commit 153e2d6e5d9cf2906977966f148ca064d7b4bf20
|
||||
Subproject commit 654bba0b17845ad957ede60cad8a3acaf336bac9
|
||||
Reference in a new issue