Make semantic projection causality explicit

This commit is contained in:
Meta Vens 2026-07-15 04:15:45 +01:00
commit 3be5e5b52b
11 changed files with 740 additions and 21 deletions

View file

@ -17,20 +17,83 @@ use std::path::Path;
pub const AGENT_MEMORY_TYPE: &str = "epiphany.agent_memory";
pub const AGENT_MEMORY_SCHEMA_VERSION: &str = "ghostlight.agent_state.v0";
pub const AGENT_MEMORY_SWARM_IDENTITY_TYPE: &str = "epiphany.agent_memory_swarm_identity";
pub const AGENT_MEMORY_SWARM_IDENTITY_SCHEMA_VERSION: &str =
"epiphany.agent_memory_swarm_identity.v0";
pub const AGENT_MEMORY_SWARM_IDENTITY_KEY: &str = "swarm-identity";
pub const AGENT_STATE_SOA_TYPE: &str = "epiphany.agent_state_soa";
pub const AGENT_STATE_SOA_SCHEMA_VERSION: &str = "epiphany.agent_state_soa.v0";
pub const AGENT_STATE_SOA_KEY: &str = "swarm";
pub fn swarm_identity_from_agent_memories(entries: &[EpiphanyAgentMemoryEntry]) -> String {
let mut identities = entries
.iter()
.map(|entry| format!("{}:{}", entry.role_id, entry.agent.agent_id))
.collect::<Vec<_>>();
identities.sort();
format!(
"swarm-{}",
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, identities.join("\n").as_bytes(),)
)
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "epiphany.agent_memory_swarm_identity",
schema = "AgentMemorySwarmIdentity"
)]
pub struct AgentMemorySwarmIdentity {
#[cultcache(key = 0)]
pub schema_version: String,
#[cultcache(key = 1)]
pub swarm_id: String,
}
pub fn load_agent_memory_swarm_identity(
store_path: impl AsRef<Path>,
) -> Result<Option<AgentMemorySwarmIdentity>> {
let store_path = store_path.as_ref();
if !store_path.exists() {
return Ok(None);
}
let mut cache = agent_memory_cache(store_path)?;
cache.pull_all_backing_stores()?;
cache.get(AGENT_MEMORY_SWARM_IDENTITY_KEY)
}
pub fn ensure_agent_memory_swarm_identity(
store_path: impl AsRef<Path>,
swarm_id: &str,
) -> Result<AgentMemorySwarmIdentity> {
let swarm_id = swarm_id.trim();
if swarm_id.is_empty() {
return Err(anyhow!(
"agent memory swarm identity requires a non-empty swarm_id"
));
}
let store_path = store_path.as_ref();
let mut cache = agent_memory_cache(store_path)?;
cache.pull_all_backing_stores()?;
if let Some(existing) =
cache.get::<AgentMemorySwarmIdentity>(AGENT_MEMORY_SWARM_IDENTITY_KEY)?
{
if existing.swarm_id == swarm_id
&& existing.schema_version == AGENT_MEMORY_SWARM_IDENTITY_SCHEMA_VERSION
{
return Ok(existing);
}
return Err(anyhow!(
"agent memory swarm identity collision: store owns {:?}, refused {:?}",
existing.swarm_id,
swarm_id
));
}
let identity = AgentMemorySwarmIdentity {
schema_version: AGENT_MEMORY_SWARM_IDENTITY_SCHEMA_VERSION.to_string(),
swarm_id: swarm_id.to_string(),
};
let envelope = cache
.prepare_entry(AGENT_MEMORY_SWARM_IDENTITY_KEY, &identity)?
.0;
let backing = SingleFileMessagePackBackingStore::new(store_path);
if !backing.compare_and_swap_batch(&[], vec![envelope])? {
let raced = load_agent_memory_swarm_identity(store_path)?;
if raced.as_ref() == Some(&identity) {
return Ok(identity);
}
return Err(anyhow!(
"agent memory swarm identity lost immutable compare-and-swap"
));
}
Ok(identity)
}
const ROLE_TARGETS: &[(&str, &str, &str)] = &[
@ -1466,6 +1529,14 @@ pub fn agent_memory_status(store_path: impl AsRef<Path>) -> Result<Value> {
});
}
let errors = validate_agent_memory_store(store_path)?;
let swarm_identity = cache
.get::<AgentMemorySwarmIdentity>(AGENT_MEMORY_SWARM_IDENTITY_KEY)?
.map(|identity| {
serde_json::json!({
"schemaVersion": identity.schema_version,
"swarmId": identity.swarm_id,
})
});
let agent_state_soa = project_agent_state_soa_from_cache(store_path, &cache)?;
let persisted_agent_state_soa = cache
.get::<EpiphanyAgentStateSoaEntry>(AGENT_STATE_SOA_KEY)?
@ -1482,6 +1553,8 @@ pub fn agent_memory_status(store_path: impl AsRef<Path>) -> Result<Value> {
"store": store_path,
"present": true,
"entryType": AGENT_MEMORY_TYPE,
"swarmIdentityEntryType": AGENT_MEMORY_SWARM_IDENTITY_TYPE,
"swarmIdentity": swarm_identity,
"agentStateSoaEntryType": AGENT_STATE_SOA_TYPE,
"errors": errors,
"agentStateSoa": {
@ -1901,6 +1974,7 @@ pub fn project_agent_memory_to_json_dir(
fn agent_memory_cache(store_path: &Path) -> Result<CultCache> {
let mut cache = CultCache::new();
cache.register_entry_type::<AgentMemorySwarmIdentity>()?;
cache.register_entry_type::<EpiphanyAgentMemoryEntry>()?;
cache.register_entry_type::<EpiphanyAgentStateSoaEntry>()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path));
@ -2996,3 +3070,39 @@ mod tests {
.to_string()
}
}
#[test]
fn immutable_swarm_identity_separates_stores_and_refuses_collision() -> Result<()> {
let temp = tempfile::tempdir()?;
let first_store = temp.path().join("first.msgpack");
let second_store = temp.path().join("second.msgpack");
let first = ensure_agent_memory_swarm_identity(&first_store, "swarm-alpha")?;
let second = ensure_agent_memory_swarm_identity(&second_store, "swarm-beta")?;
assert_eq!(
load_agent_memory_swarm_identity(&first_store)?,
Some(first.clone())
);
assert_eq!(
ensure_agent_memory_swarm_identity(&first_store, "swarm-alpha")?,
first
);
let collision = ensure_agent_memory_swarm_identity(&first_store, "swarm-beta")
.expect_err("immutable store identity must refuse substitution");
assert!(collision.to_string().contains("collision"));
assert_ne!(
crate::semantic_point_id(
&first.swarm_id,
crate::SemanticPartition::Mind,
AGENT_MEMORY_TYPE,
"Persona",
"memory-1"
),
crate::semantic_point_id(
&second.swarm_id,
crate::SemanticPartition::Mind,
AGENT_MEMORY_TYPE,
"Persona",
"memory-1"
)
);
Ok(())
}

View file

@ -5,6 +5,7 @@ use epiphany_core::AgentSelfPatch;
use epiphany_core::agent_memory_status;
use epiphany_core::apply_agent_memory_lifecycle_operation;
use epiphany_core::apply_agent_self_patch_document;
use epiphany_core::ensure_agent_memory_swarm_identity;
use epiphany_core::migrate_agent_memory_json_dir_to_cultcache;
use epiphany_core::project_agent_memory_to_json_dir;
use epiphany_core::project_persona_state_for_role;
@ -47,6 +48,11 @@ fn main() -> Result<()> {
let store = require_path_arg(&mut args, "--store")?;
print_json(&agent_memory_status(store)?)?;
}
"set-swarm-identity" => {
let store = require_path_arg(&mut args, "--store")?;
let swarm_id = require_string_arg(&mut args, "--swarm-id")?;
print_json(&ensure_agent_memory_swarm_identity(store, &swarm_id)?)?;
}
"refresh-soa" => {
let store = require_path_arg(&mut args, "--store")?;
print_json(&refresh_agent_state_soa(store)?)?;
@ -192,7 +198,7 @@ fn print_json<T: serde::Serialize>(value: &T) -> Result<()> {
fn print_usage() {
eprintln!(
"usage: epiphany-agent-memory-store <migrate-json-dir|project-json-dir|project-persona|status|refresh-soa|repair|validate|review-patch|apply-patch|review-lifecycle|apply-lifecycle|smoke> ..."
"usage: epiphany-agent-memory-store <migrate-json-dir|project-json-dir|project-persona|set-swarm-identity|status|refresh-soa|repair|validate|review-patch|apply-patch|review-lifecycle|apply-lifecycle|smoke> ..."
);
}

View file

@ -167,16 +167,17 @@ impl Options {
if entries.is_empty() {
return Err(anyhow!("agent store has no admitted organ memory"));
}
let derived_swarm_id = epiphany_core::swarm_identity_from_agent_memories(&entries);
if self.swarm_id != derived_swarm_id {
let identity = epiphany_core::load_agent_memory_swarm_identity(path)?
.ok_or_else(|| anyhow!("agent store has no immutable swarm identity; run epiphany-agent-memory-store set-swarm-identity"))?;
if self.swarm_id != identity.swarm_id {
return Err(anyhow!(
"--swarm-id {:?} does not match the canonical agent-store swarm identity {:?}",
self.swarm_id,
derived_swarm_id
identity.swarm_id
));
}
return Ok(memory_graph_from_agent_memories(
format!("{derived_swarm_id}-mind"),
format!("{}-mind", identity.swarm_id),
&entries,
));
}

View file

@ -1112,6 +1112,28 @@ fn persona_memory_recall_for_scheduled_turn(
});
};
let swarm_identity = match crate::load_agent_memory_swarm_identity(agent_store) {
Ok(Some(identity)) => identity,
Ok(None) => {
return serde_json::json!({
"schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION,
"status": "unavailable",
"cacheStatus": "swarm-identity-missing",
"renderedRecall": "- semantic Persona memory recall unavailable: agent store has no immutable swarm identity",
"privateStateExposed": false,
});
}
Err(error) => {
return serde_json::json!({
"schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION,
"status": "unavailable",
"cacheStatus": "swarm-identity-load-failed",
"renderedRecall": format!("- semantic Persona memory recall unavailable: {}", compact_heartbeat_line(&format!("{error:#}"), 320)),
"privateStateExposed": false,
});
}
};
let entry = match crate::agent_memory::load_agent_memory_entry_for_role(agent_store, "Persona")
{
Ok(Some(entry)) => entry,
@ -1142,7 +1164,7 @@ fn persona_memory_recall_for_scheduled_turn(
entries.push(role_entry);
}
}
let swarm_id = crate::swarm_identity_from_agent_memories(&entries);
let swarm_id = swarm_identity.swarm_id;
let graph = crate::memory_graph_from_agent_memories(&format!("{swarm_id}-mind"), &entries);
let persona_domain_id =
crate::memory_graph_domain_id(crate::EpiphanyMemoryProfile::RoleSelf, "role", "Persona");
@ -3845,6 +3867,7 @@ mod tests {
let agent_store = temp.path().join("agents.msgpack");
let artifact_dir = temp.path().join("artifacts");
initialize_heartbeat_store(&store_path, 1.0)?;
crate::ensure_agent_memory_swarm_identity(&agent_store, "swarm-persona-memory-test")?;
crate::write_agent_memory_entry_for_role(&agent_store, &persona_memory_entry())?;
queue_heartbeat_pending_mention_store(
&store_path,

View file

@ -74,11 +74,15 @@ pub use agent_launch::epiphany_worker_prompt;
pub use agent_launch::render_epiphany_coordinator_note;
pub use agent_launch::render_epiphany_pre_compaction_checkpoint_intervention;
pub use agent_launch::unique_strings;
pub use agent_memory::AGENT_MEMORY_SWARM_IDENTITY_KEY;
pub use agent_memory::AGENT_MEMORY_SWARM_IDENTITY_SCHEMA_VERSION;
pub use agent_memory::AGENT_MEMORY_SWARM_IDENTITY_TYPE;
pub use agent_memory::AgentCanonicalTraitSeed;
pub use agent_memory::AgentMemoryBundle;
pub use agent_memory::AgentMemoryLifecycleAction;
pub use agent_memory::AgentMemoryLifecycleOperation;
pub use agent_memory::AgentMemoryReview;
pub use agent_memory::AgentMemorySwarmIdentity;
pub use agent_memory::AgentSelfPatch;
pub use agent_memory::EpiphanyAgentMemoryEntry;
pub use agent_memory::EpiphanyAgentStateSoaEntry;
@ -104,7 +108,9 @@ pub use agent_memory::apply_agent_canonical_trait_seeds;
pub use agent_memory::apply_agent_memory_lifecycle_operation;
pub use agent_memory::apply_agent_self_patch;
pub use agent_memory::apply_agent_self_patch_document;
pub use agent_memory::ensure_agent_memory_swarm_identity;
pub use agent_memory::load_agent_memory_entry_for_role;
pub use agent_memory::load_agent_memory_swarm_identity;
pub use agent_memory::load_agent_state_soa_entry;
pub use agent_memory::migrate_agent_memory_json_dir_to_cultcache;
pub use agent_memory::organ_state_profile_for_role;
@ -116,7 +122,6 @@ pub use agent_memory::repair_agent_memory_store;
pub use agent_memory::review_agent_memory_lifecycle_operation;
pub use agent_memory::review_agent_self_patch;
pub use agent_memory::review_agent_self_patch_document;
pub use agent_memory::swarm_identity_from_agent_memories;
pub use agent_memory::validate_agent_memory_store;
pub use agent_memory::write_agent_memory_entry_for_role;
pub use agent_utterance_state::AGENT_CHARACTER_STATE_VECTOR_SIZE;
@ -622,6 +627,18 @@ pub use memory_graph::MEMORY_GRAPH_TYPE;
pub use memory_graph::MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION;
pub use memory_graph::MemorySemanticIndexConfig;
pub use memory_graph::MemorySemanticIndexReceipt;
pub use memory_graph::MemorySemanticProjectionAttempt;
pub use memory_graph::MemorySemanticProjectionHealth;
pub use memory_graph::MemorySemanticProjectionHealthStatus;
pub use memory_graph::MemorySemanticProjectionObligation;
pub use memory_graph::MemorySemanticProjectionSourceHead;
pub use memory_graph::MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION;
pub use memory_graph::MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION;
pub use memory_graph::bind_memory_semantic_index_receipt;
pub use memory_graph::derive_memory_semantic_projection_health;
pub use memory_graph::memory_semantic_projection_query_eligible;
pub use memory_graph::validate_memory_semantic_projection_attempt;
pub use memory_graph::validate_memory_semantic_projection_obligation;
pub use memory_graph::RepoFrontierAdoptedPlan;
pub use memory_graph::RepoFrontierItem;
pub use memory_graph::RepoFrontierStatus;

View file

@ -1,7 +1,7 @@
use super::{
EpiphanyMemoryContextPacket, EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot,
SEMANTIC_PROJECTION_SCHEMA_VERSION, SemanticPartition, SemanticProjectionCandidate,
SemanticProjectionDocument, derive_semantic_projection, plan_memory_graph_context_cut,
SemanticProjectionDocument, derive_semantic_projection,
plan_memory_graph_context_cut_for_partition, resolve_semantic_candidate,
};
use crate::semantic_backend::{
@ -18,6 +18,10 @@ use std::path::Path;
pub const MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION: &str =
"gamecult.epiphany.memory_semantic_index_receipt.v0";
pub const MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION: &str =
"gamecult.epiphany.memory_semantic_projection_obligation.v0";
pub const MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION: &str =
"gamecult.epiphany.memory_semantic_projection_attempt.v0";
const MODELING_COLLECTION_DEFAULT: &str = "epiphany_modeling_v1";
const MIND_COLLECTION_DEFAULT: &str = "epiphany_mind_v1";
const QUERY_LIMIT_MAX: usize = 64;
@ -100,6 +104,93 @@ struct MemorySemanticPointPayload {
embedding_model: String,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.epiphany.memory_semantic_projection_obligation",
schema = "MemorySemanticProjectionObligation"
)]
pub struct MemorySemanticProjectionObligation {
#[cultcache(key = 0)]
pub schema_version: String,
#[cultcache(key = 1)]
pub obligation_id: String,
#[cultcache(key = 2)]
pub swarm_id: String,
#[cultcache(key = 3)]
pub partition: String,
#[cultcache(key = 4)]
pub canonical_source_id: String,
#[cultcache(key = 5)]
pub source_commit_id: String,
#[cultcache(key = 6)]
pub graph_id: String,
#[cultcache(key = 7)]
pub source_generation: u64,
#[cultcache(key = 8)]
pub source_model_hash: String,
#[cultcache(key = 9)]
pub canonical_content_set_hash: String,
#[cultcache(key = 10)]
pub projection_schema_version: String,
#[cultcache(key = 11)]
pub created_at: String,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.epiphany.memory_semantic_projection_attempt",
schema = "MemorySemanticProjectionAttempt"
)]
pub struct MemorySemanticProjectionAttempt {
#[cultcache(key = 0)]
pub schema_version: String,
#[cultcache(key = 1)]
pub attempt_id: String,
#[cultcache(key = 2)]
pub obligation_id: String,
#[cultcache(key = 3)]
pub started_at: String,
#[cultcache(key = 4)]
pub completed_at: Option<String>,
#[cultcache(key = 5)]
pub status: String,
#[cultcache(key = 6)]
pub error: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MemorySemanticProjectionHealthStatus {
Pending,
Failed,
Stale,
Ready,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MemorySemanticProjectionSourceHead {
pub swarm_id: String,
pub partition: String,
pub canonical_source_id: String,
pub source_commit_id: String,
pub graph_id: String,
pub source_generation: u64,
pub source_model_hash: String,
pub canonical_content_set_hash: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MemorySemanticProjectionHealth {
pub status: MemorySemanticProjectionHealthStatus,
pub obligation_id: String,
pub receipt_id: Option<String>,
pub latest_attempt_id: Option<String>,
pub latest_error: Option<String>,
pub query_eligible: bool,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.epiphany.memory_semantic_index_receipt",
@ -138,6 +229,200 @@ pub struct MemorySemanticIndexReceipt {
pub indexed_at: String,
#[cultcache(key = 15)]
pub status: String,
#[cultcache(key = 16)]
pub obligation_id: String,
#[cultcache(key = 17)]
pub canonical_source_id: String,
#[cultcache(key = 18)]
pub source_commit_id: String,
#[cultcache(key = 19)]
pub source_generation: u64,
#[cultcache(key = 20)]
pub projection_schema_version: String,
}
pub fn validate_memory_semantic_projection_obligation(
obligation: &MemorySemanticProjectionObligation,
) -> Result<()> {
if obligation.schema_version != MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION {
return Err(anyhow!("unsupported semantic projection obligation schema"));
}
for (label, value) in [
("obligation_id", obligation.obligation_id.as_str()),
("swarm_id", obligation.swarm_id.as_str()),
("partition", obligation.partition.as_str()),
(
"canonical_source_id",
obligation.canonical_source_id.as_str(),
),
("source_commit_id", obligation.source_commit_id.as_str()),
("graph_id", obligation.graph_id.as_str()),
("source_model_hash", obligation.source_model_hash.as_str()),
(
"canonical_content_set_hash",
obligation.canonical_content_set_hash.as_str(),
),
("created_at", obligation.created_at.as_str()),
] {
if value.trim().is_empty() {
return Err(anyhow!("semantic projection obligation missing {label}"));
}
}
if !matches!(obligation.partition.as_str(), "mind" | "modeling") {
return Err(anyhow!(
"semantic projection obligation has invalid partition"
));
}
if obligation.projection_schema_version != SEMANTIC_PROJECTION_SCHEMA_VERSION {
return Err(anyhow!("semantic projection obligation schema mismatch"));
}
Ok(())
}
pub fn validate_memory_semantic_projection_attempt(
attempt: &MemorySemanticProjectionAttempt,
) -> Result<()> {
if attempt.schema_version != MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION {
return Err(anyhow!("unsupported semantic projection attempt schema"));
}
if attempt.attempt_id.trim().is_empty()
|| attempt.obligation_id.trim().is_empty()
|| attempt.started_at.trim().is_empty()
{
return Err(anyhow!(
"semantic projection attempt is missing identity or time"
));
}
match attempt.status.as_str() {
"running" if attempt.completed_at.is_none() && attempt.error.is_none() => Ok(()),
"failed" if attempt.completed_at.is_some() && attempt.error.is_some() => Ok(()),
_ => Err(anyhow!(
"semantic projection attempt status does not match its terminal fields"
)),
}
}
pub fn derive_memory_semantic_projection_health(
obligation: &MemorySemanticProjectionObligation,
current: &MemorySemanticProjectionSourceHead,
attempts: &[MemorySemanticProjectionAttempt],
receipts: &[MemorySemanticIndexReceipt],
) -> Result<MemorySemanticProjectionHealth> {
validate_memory_semantic_projection_obligation(obligation)?;
for attempt in attempts
.iter()
.filter(|attempt| attempt.obligation_id == obligation.obligation_id)
{
validate_memory_semantic_projection_attempt(attempt)?;
}
let stale = !obligation_matches_source(obligation, current);
let mut matching_receipts = receipts
.iter()
.filter(|receipt| receipt_matches_obligation(receipt, obligation))
.collect::<Vec<_>>();
matching_receipts.sort_by(|left, right| left.indexed_at.cmp(&right.indexed_at));
let receipt = matching_receipts.last().copied();
let mut matching_attempts = attempts
.iter()
.filter(|attempt| attempt.obligation_id == obligation.obligation_id)
.collect::<Vec<_>>();
matching_attempts.sort_by(|left, right| {
left.completed_at
.as_deref()
.unwrap_or(left.started_at.as_str())
.cmp(
right
.completed_at
.as_deref()
.unwrap_or(right.started_at.as_str()),
)
});
let latest_attempt = matching_attempts.last().copied();
let status = if stale {
MemorySemanticProjectionHealthStatus::Stale
} else if receipt.is_some() {
MemorySemanticProjectionHealthStatus::Ready
} else if latest_attempt.is_some_and(|attempt| attempt.status == "failed") {
MemorySemanticProjectionHealthStatus::Failed
} else {
MemorySemanticProjectionHealthStatus::Pending
};
Ok(MemorySemanticProjectionHealth {
status,
obligation_id: obligation.obligation_id.clone(),
receipt_id: receipt.map(|receipt| receipt.receipt_id.clone()),
latest_attempt_id: latest_attempt.map(|attempt| attempt.attempt_id.clone()),
latest_error: latest_attempt.and_then(|attempt| attempt.error.clone()),
query_eligible: status == MemorySemanticProjectionHealthStatus::Ready,
})
}
pub fn memory_semantic_projection_query_eligible(
obligation: &MemorySemanticProjectionObligation,
current: &MemorySemanticProjectionSourceHead,
receipt: &MemorySemanticIndexReceipt,
) -> bool {
validate_memory_semantic_projection_obligation(obligation).is_ok()
&& obligation_matches_source(obligation, current)
&& receipt_matches_obligation(receipt, obligation)
}
pub fn bind_memory_semantic_index_receipt(
mut receipt: MemorySemanticIndexReceipt,
obligation: &MemorySemanticProjectionObligation,
) -> Result<MemorySemanticIndexReceipt> {
validate_memory_semantic_projection_obligation(obligation)?;
if receipt.swarm_id != obligation.swarm_id
|| receipt.partition != obligation.partition
|| receipt.graph_id != obligation.graph_id
|| receipt.model_revision != obligation.source_generation
|| receipt.model_hash != obligation.source_model_hash
|| receipt.canonical_content_set_hash != obligation.canonical_content_set_hash
|| receipt.status != "ready"
{
return Err(anyhow!(
"semantic index result does not match the exact projection obligation"
));
}
receipt.obligation_id = obligation.obligation_id.clone();
receipt.canonical_source_id = obligation.canonical_source_id.clone();
receipt.source_commit_id = obligation.source_commit_id.clone();
receipt.source_generation = obligation.source_generation;
receipt.projection_schema_version = obligation.projection_schema_version.clone();
Ok(receipt)
}
fn obligation_matches_source(
obligation: &MemorySemanticProjectionObligation,
current: &MemorySemanticProjectionSourceHead,
) -> bool {
obligation.swarm_id == current.swarm_id
&& obligation.partition == current.partition
&& obligation.canonical_source_id == current.canonical_source_id
&& obligation.source_commit_id == current.source_commit_id
&& obligation.graph_id == current.graph_id
&& obligation.source_generation == current.source_generation
&& obligation.source_model_hash == current.source_model_hash
&& obligation.canonical_content_set_hash == current.canonical_content_set_hash
}
fn receipt_matches_obligation(
receipt: &MemorySemanticIndexReceipt,
obligation: &MemorySemanticProjectionObligation,
) -> bool {
receipt.schema_version == MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION
&& receipt.status == "ready"
&& receipt.obligation_id == obligation.obligation_id
&& receipt.swarm_id == obligation.swarm_id
&& receipt.partition == obligation.partition
&& receipt.canonical_source_id == obligation.canonical_source_id
&& receipt.source_commit_id == obligation.source_commit_id
&& receipt.graph_id == obligation.graph_id
&& receipt.source_generation == obligation.source_generation
&& receipt.model_revision == obligation.source_generation
&& receipt.model_hash == obligation.source_model_hash
&& receipt.canonical_content_set_hash == obligation.canonical_content_set_hash
&& receipt.projection_schema_version == obligation.projection_schema_version
}
pub fn index_memory_semantic_partition(
@ -230,6 +515,11 @@ pub fn index_memory_semantic_partition(
canonical_content_set_hash: content_set_hash,
indexed_at: indexed_at.to_string(),
status: "ready".to_string(),
obligation_id: String::new(),
canonical_source_id: snapshot.graph_id.clone(),
source_commit_id: String::new(),
source_generation: snapshot.model_revision,
projection_schema_version: SEMANTIC_PROJECTION_SCHEMA_VERSION.to_string(),
})
}
@ -255,7 +545,8 @@ pub fn semantic_memory_context(
match try_semantic_memory_context(snapshot, swarm_id, partition, query, config) {
Ok(packet) => packet,
Err(error) => {
let mut packet = plan_memory_graph_context_cut(snapshot, query);
let mut packet =
plan_memory_graph_context_cut_for_partition(snapshot, query, &[], partition);
packet.warnings.push(format!(
"semantic projection unavailable; used canonical BM25 fallback: {error}"
));
@ -479,7 +770,12 @@ mod tests {
text: Some("canonical qdrant semantic".to_string()),
..Default::default()
};
let expected = plan_memory_graph_context_cut(&snapshot, &query);
let expected = plan_memory_graph_context_cut_for_partition(
&snapshot,
&query,
&[],
SemanticPartition::Modeling,
);
let mut config = MemorySemanticIndexConfig::from_env();
config.qdrant_url = "http://127.0.0.1:1".to_string();
config.qdrant_timeout_ms = 25;
@ -513,4 +809,182 @@ mod tests {
config.query_instruction(SemanticPartition::Modeling)
);
}
fn obligation() -> MemorySemanticProjectionObligation {
MemorySemanticProjectionObligation {
schema_version: MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION.to_string(),
obligation_id: "projection:swarm:modeling:commit-7".to_string(),
swarm_id: "swarm".to_string(),
partition: "modeling".to_string(),
canonical_source_id: "runtime-spine".to_string(),
source_commit_id: "commit-7".to_string(),
graph_id: "graph".to_string(),
source_generation: 7,
source_model_hash: "model-hash".to_string(),
canonical_content_set_hash: "content-hash".to_string(),
projection_schema_version: SEMANTIC_PROJECTION_SCHEMA_VERSION.to_string(),
created_at: "2026-07-15T10:00:00Z".to_string(),
}
}
fn source_head() -> MemorySemanticProjectionSourceHead {
let obligation = obligation();
MemorySemanticProjectionSourceHead {
swarm_id: obligation.swarm_id,
partition: obligation.partition,
canonical_source_id: obligation.canonical_source_id,
source_commit_id: obligation.source_commit_id,
graph_id: obligation.graph_id,
source_generation: obligation.source_generation,
source_model_hash: obligation.source_model_hash,
canonical_content_set_hash: obligation.canonical_content_set_hash,
}
}
fn receipt() -> MemorySemanticIndexReceipt {
let obligation = obligation();
MemorySemanticIndexReceipt {
schema_version: MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION.to_string(),
receipt_id: "receipt-7".to_string(),
swarm_id: obligation.swarm_id,
partition: obligation.partition,
collection_name: "epiphany_modeling_v1".to_string(),
graph_id: obligation.graph_id,
model_revision: obligation.source_generation,
model_hash: obligation.source_model_hash,
embedding_provider_id: "provider".to_string(),
embedding_model: "model".to_string(),
vector_dimensions: 1024,
indexed_document_count: 3,
deleted_document_count: 0,
canonical_content_set_hash: obligation.canonical_content_set_hash,
indexed_at: "2026-07-15T10:01:00Z".to_string(),
status: "ready".to_string(),
obligation_id: obligation.obligation_id,
canonical_source_id: obligation.canonical_source_id,
source_commit_id: obligation.source_commit_id,
source_generation: obligation.source_generation,
projection_schema_version: obligation.projection_schema_version,
}
}
fn failed_attempt() -> MemorySemanticProjectionAttempt {
MemorySemanticProjectionAttempt {
schema_version: MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION.to_string(),
attempt_id: "attempt-1".to_string(),
obligation_id: obligation().obligation_id,
started_at: "2026-07-15T10:00:30Z".to_string(),
completed_at: Some("2026-07-15T10:00:31Z".to_string()),
status: "failed".to_string(),
error: Some("qdrant unavailable".to_string()),
}
}
#[test]
fn projection_health_is_derived_from_exact_canonical_causality() {
let obligation = obligation();
let current = source_head();
let pending =
derive_memory_semantic_projection_health(&obligation, &current, &[], &[]).unwrap();
assert_eq!(
pending.status,
MemorySemanticProjectionHealthStatus::Pending
);
assert!(!pending.query_eligible);
let failed = derive_memory_semantic_projection_health(
&obligation,
&current,
&[failed_attempt()],
&[],
)
.unwrap();
assert_eq!(failed.status, MemorySemanticProjectionHealthStatus::Failed);
assert_eq!(failed.latest_error.as_deref(), Some("qdrant unavailable"));
let ready = derive_memory_semantic_projection_health(
&obligation,
&current,
&[failed_attempt()],
&[receipt()],
)
.unwrap();
assert_eq!(ready.status, MemorySemanticProjectionHealthStatus::Ready);
assert!(ready.query_eligible);
let mut newer = current.clone();
newer.source_generation += 1;
newer.source_commit_id = "commit-8".to_string();
let stale = derive_memory_semantic_projection_health(
&obligation,
&newer,
&[failed_attempt()],
&[receipt()],
)
.unwrap();
assert_eq!(stale.status, MemorySemanticProjectionHealthStatus::Stale);
assert!(!stale.query_eligible);
}
#[test]
fn hostile_receipt_mismatches_never_grant_query_eligibility() {
let obligation = obligation();
let current = source_head();
for field in [
"obligation",
"swarm",
"partition",
"source",
"commit",
"graph",
"generation",
"revision",
"model",
"content",
"projection-schema",
"status",
] {
let mut hostile = receipt();
match field {
"obligation" => hostile.obligation_id = "other".to_string(),
"swarm" => hostile.swarm_id = "other".to_string(),
"partition" => hostile.partition = "mind".to_string(),
"source" => hostile.canonical_source_id = "other".to_string(),
"commit" => hostile.source_commit_id = "other".to_string(),
"graph" => hostile.graph_id = "other".to_string(),
"generation" => hostile.source_generation += 1,
"revision" => hostile.model_revision += 1,
"model" => hostile.model_hash = "other".to_string(),
"content" => hostile.canonical_content_set_hash = "other".to_string(),
"projection-schema" => hostile.projection_schema_version = "other".to_string(),
"status" => hostile.status = "failed".to_string(),
_ => unreachable!(),
}
assert!(
!memory_semantic_projection_query_eligible(&obligation, &current, &hostile),
"hostile {field} substitution was accepted"
);
}
}
#[test]
fn unbound_index_result_is_not_ready_until_exact_obligation_binding() {
let obligation = obligation();
let current = source_head();
let mut result = receipt();
result.obligation_id.clear();
result.canonical_source_id.clear();
result.source_commit_id.clear();
assert!(!memory_semantic_projection_query_eligible(
&obligation,
&current,
&result
));
let bound = bind_memory_semantic_index_receipt(result, &obligation).unwrap();
assert!(memory_semantic_projection_query_eligible(
&obligation,
&current,
&bound
));
}
}