Collapse semantic projection to Modeling

This commit is contained in:
Meta Vens 2026-08-23 02:57:01 +02:00
commit 360073a3bf
17 changed files with 274 additions and 2000 deletions

View file

@ -584,89 +584,6 @@ pub fn validate_agent_memory_store(store_path: impl AsRef<Path>) -> Result<Vec<S
Ok(errors)
}
pub fn agent_memory_semantic_projection_input(
store_path: impl AsRef<Path>,
) -> Result<crate::MemorySemanticProjectionInput> {
let store_path = store_path.as_ref();
let mut cache = agent_memory_cache(store_path)?;
cache.pull_all_backing_stores()?;
let identity = cache
.get::<AgentMemorySwarmIdentity>(AGENT_MEMORY_SWARM_IDENTITY_KEY)?
.ok_or_else(|| anyhow!("Mind projection requires immutable swarm identity"))?;
let witness = cache
.get::<AgentMemoryGenerationWitness>(AGENT_MEMORY_GENERATION_WITNESS_LATEST_KEY)?
.ok_or_else(|| anyhow!("Mind projection requires admitted generation witness"))?;
let (generation, source_hash) = agent_memory_source_head(&mut cache)?;
if generation != witness.generation || source_hash != witness.source_hash {
return Err(anyhow!("Mind projection generation witness is not current"));
}
let mut entries = Vec::with_capacity(ROLE_TARGETS.len());
for (role_id, _, _) in ROLE_TARGETS {
entries.push(cache.get_required::<EpiphanyAgentMemoryEntry>(role_id)?);
}
let mut snapshot =
crate::memory_graph_from_agent_memories(format!("{}-mind", identity.swarm_id), &entries);
snapshot.model_revision = witness.generation;
let matches = cache
.get_all::<crate::MemorySemanticProjectionObligation>()?
.into_iter()
.filter(|obligation| obligation.source_commit_id == witness.witness_id)
.collect::<Vec<_>>();
if matches.len() != 1 {
return Err(anyhow!(
"Mind projection requires exactly one obligation for current generation"
));
}
let obligation = matches.into_iter().next().expect("one obligation");
let expected = crate::derive_memory_semantic_projection_obligation(
&snapshot,
&identity.swarm_id,
crate::SemanticPartition::Mind,
&format!("epiphany.agent-memory/{}/mind", identity.swarm_id),
&witness.witness_id,
&witness.committed_at,
)?;
if obligation != expected {
return Err(anyhow!(
"Mind projection obligation does not match canonical head"
));
}
let opening = cache.snapshot_envelopes();
let authority_envelopes = opening
.into_iter()
.filter(|envelope| {
(envelope.r#type == AGENT_MEMORY_SWARM_IDENTITY_TYPE
&& envelope.key == AGENT_MEMORY_SWARM_IDENTITY_KEY)
|| (envelope.r#type == AGENT_MEMORY_GENERATION_WITNESS_TYPE
&& envelope.key == AGENT_MEMORY_GENERATION_WITNESS_LATEST_KEY)
|| (envelope.r#type == AGENT_MEMORY_TYPE
&& ROLE_TARGETS
.iter()
.any(|(role_id, _, _)| envelope.key == *role_id))
})
.collect::<Vec<_>>();
if authority_envelopes.len() != ROLE_TARGETS.len() + 2 {
return Err(anyhow!("Mind projection authority snapshot is incomplete"));
}
Ok(crate::MemorySemanticProjectionInput {
snapshot,
authority: crate::memory_graph::MemorySemanticProjectionAuthoritySnapshot {
head: crate::MemorySemanticProjectionSourceHead {
swarm_id: obligation.swarm_id.clone(),
partition: obligation.partition.clone(),
canonical_source_id: obligation.canonical_source_id.clone(),
source_commit_id: obligation.source_commit_id.clone(),
graph_id: obligation.graph_id.clone(),
source_generation: obligation.source_generation,
source_model_hash: obligation.source_model_hash.clone(),
canonical_content_set_hash: obligation.canonical_content_set_hash.clone(),
},
envelopes: authority_envelopes,
},
obligation,
})
}
fn canonical_agent_memory_source_hash(
cache: &mut CultCache,
identity: &AgentMemorySwarmIdentity,
@ -782,35 +699,6 @@ fn commit_agent_memory_generation(
changed_role_ids: vec![role_id.to_string()],
committed_at: committed_at.clone(),
};
let mut projected_entries = Vec::with_capacity(ROLE_TARGETS.len());
for (canonical_role, _, _) in ROLE_TARGETS {
projected_entries.push(
replacements
.get(*canonical_role)
.cloned()
.or_else(|| {
cache
.get::<EpiphanyAgentMemoryEntry>(canonical_role)
.ok()
.flatten()
})
.ok_or_else(|| anyhow!("canonical Mind generation lost role {canonical_role:?}"))?,
);
}
let mut projection_snapshot = crate::memory_graph_from_agent_memories(
format!("{}-mind", identity.swarm_id),
&projected_entries,
);
projection_snapshot.model_revision = generation;
let obligation = crate::derive_memory_semantic_projection_obligation(
&projection_snapshot,
&identity.swarm_id,
crate::SemanticPartition::Mind,
&format!("epiphany.agent-memory/{}/mind", identity.swarm_id),
&witness_id,
&committed_at,
)?;
let opening = cache.snapshot_envelopes();
let mut expected = Vec::new();
let mut batch = Vec::new();
@ -845,11 +733,6 @@ fn commit_agent_memory_generation(
);
batch.push(cache.prepare_entry(&witness_id, &witness)?.0);
batch.push(cache.prepare_entry(&receipt_id, &receipt)?.0);
batch.push(
cache
.prepare_entry(&obligation.obligation_id, &obligation)?
.0,
);
let backing = SingleFileMessagePackBackingStore::new(store_path);
if !backing.compare_and_swap_batch(&expected, batch)? {
return Err(anyhow!(
@ -885,20 +768,9 @@ fn admit_initial_agent_memory_generation(
"initial Mind admission collides with live generation"
));
}
let obligations = cache
.get_all::<crate::MemorySemanticProjectionObligation>()?
.into_iter()
.filter(|obligation| obligation.source_commit_id == existing.witness_id)
.collect::<Vec<_>>();
if obligations.len() != 1 {
return Err(anyhow!(
"initial Mind admission lost its exact semantic projection obligation"
));
}
return Ok(existing);
}
let mut entries = Vec::with_capacity(ROLE_TARGETS.len());
for (role_id, expected_agent_id, _) in ROLE_TARGETS {
let entry = cache
.get::<EpiphanyAgentMemoryEntry>(role_id)?
@ -910,7 +782,6 @@ fn admit_initial_agent_memory_generation(
errors.join("; ")
));
}
entries.push(entry);
}
let committed_at = now_rfc3339();
let fingerprint = format!("{}|{}|{}", identity.swarm_id, mutation_kind, source_hash);
@ -948,18 +819,6 @@ fn admit_initial_agent_memory_generation(
changed_role_ids,
committed_at: committed_at.clone(),
};
let mut snapshot =
crate::memory_graph_from_agent_memories(format!("{}-mind", identity.swarm_id), &entries);
snapshot.model_revision = witness.generation;
let obligation = crate::derive_memory_semantic_projection_obligation(
&snapshot,
&identity.swarm_id,
crate::SemanticPartition::Mind,
&format!("epiphany.agent-memory/{}/mind", identity.swarm_id),
&witness_id,
&committed_at,
)?;
let opening = cache.snapshot_envelopes();
let mut expected = Vec::new();
let mut replacements = Vec::new();
@ -986,11 +845,6 @@ fn admit_initial_agent_memory_generation(
);
replacements.push(cache.prepare_entry(&witness_id, &witness)?.0);
replacements.push(cache.prepare_entry(&receipt_id, &receipt)?.0);
replacements.push(
cache
.prepare_entry(&obligation.obligation_id, &obligation)?
.0,
);
let backing = SingleFileMessagePackBackingStore::new(store_path);
if !backing.compare_and_swap_batch(&expected, replacements)? {
return Err(anyhow!(
@ -1360,15 +1214,6 @@ fn agent_memory_cache(store_path: &Path) -> Result<CultCache> {
cache.register_entry_type::<AgentMemorySwarmIdentity>()?;
cache.register_entry_type::<AgentMemoryGenerationWitness>()?;
cache.register_entry_type::<AgentMemoryMindAdmissionReceipt>()?;
cache.register_entry_type::<crate::MemorySemanticProjectionObligation>()?;
cache.register_entry_type::<crate::MemorySemanticProjectionClaim>()?;
cache.register_entry_type::<crate::MemorySemanticProjectionAttempt>()?;
cache.register_entry_type::<crate::MemorySemanticIndexReceipt>()?;
cache.register_entry_type::<crate::MemorySemanticProjectorExecutorGrant>()?;
cache.register_entry_type::<crate::MemorySemanticProjectorRecoveryAuthorization>()?;
cache.register_entry_type::<crate::MemorySemanticProjectionRetentionHead>()?;
cache.register_entry_type::<crate::MemorySemanticPhysicalRetirementObligation>()?;
cache.register_entry_type::<crate::MemorySemanticPhysicalRetirementReceipt>()?;
cache.register_entry_type::<EpiphanyAgentMemoryEntry>()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(store_path));
Ok(cache)
@ -1981,21 +1826,6 @@ fn immutable_swarm_identity_separates_stores_and_refuses_collision() -> Result<(
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"
)
);
assert_ne!(first.swarm_id, second.swarm_id);
Ok(())
}

View file

@ -20,8 +20,6 @@ use epiphany_core::EpiphanyCultMeshManagedServicePolicyEntry;
use epiphany_core::EpiphanyCultMeshSwarmBrakeEntry;
use epiphany_core::EpiphanyLocalVerseContext;
use epiphany_core::EpiphanyProcessObservation as ProcessObservation;
use epiphany_core::MemorySemanticProjectionInput;
use epiphany_core::agent_memory_semantic_projection_input;
use epiphany_core::authenticate_epiphany_cultmesh_semantic_projector_launch;
use epiphany_core::authenticate_resident_provider_pair;
use epiphany_core::epiphany_cultmesh_daemon_poke_intent_from_status;
@ -39,13 +37,9 @@ use epiphany_core::load_epiphany_cultmesh_swarm_brake;
use epiphany_core::load_epiphany_packaged_release;
use epiphany_core::load_latest_epiphany_cultmesh_daemon_heartbeat;
use epiphany_core::load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt_for_service;
use epiphany_core::migrate_memory_semantic_projection_attempts_v0;
use epiphany_core::observe_native_process as observe_process;
use epiphany_core::query_epiphany_local_verse_context;
use epiphany_core::retire_epiphany_cultmesh_operator_status_documents;
use epiphany_core::retire_memory_semantic_projection_claims_v0;
use epiphany_core::retire_orphaned_memory_semantic_projection_attempts_v0;
use epiphany_core::retire_unowned_memory_semantic_index_receipts;
use epiphany_core::runtime_modeling_semantic_projection_input;
use epiphany_core::write_epiphany_cultmesh_daemon_poke_intent;
use epiphany_core::write_epiphany_cultmesh_daemon_poke_receipt;
@ -193,7 +187,6 @@ fn dispatch(args: Args) -> Result<()> {
"managed-service-task-stop" => managed_service_task_control(args, "stop"),
"managed-service-task-uninstall" => managed_service_task_control(args, "uninstall"),
"migrate-retired-operator-status" => migrate_retired_operator_status(args),
"migrate-semantic-attempts-v0" => migrate_semantic_attempts_v0(args),
"provider-health-identity-enroll" => provider_health_identity_enroll(args),
"provider-health-identity-export" => provider_health_identity_export(args),
"semantic-projector-service-status" => semantic_projector_service_status(args),
@ -678,48 +671,6 @@ fn migrate_retired_operator_status(args: Args) -> Result<()> {
Ok(())
}
fn migrate_semantic_attempts_v0(args: Args) -> Result<()> {
let agent_store = args
.agent_store
.as_ref()
.context("migrate-semantic-attempts-v0 requires --agent-store")?;
let runtime_store = args
.runtime_store
.as_ref()
.context("migrate-semantic-attempts-v0 requires --runtime-store")?;
if agent_store == runtime_store {
anyhow::bail!("semantic Mind and Modeling stores must remain distinct");
}
let retired_mind_claim_ids = retire_memory_semantic_projection_claims_v0(agent_store)?;
let retired_modeling_claim_ids = retire_memory_semantic_projection_claims_v0(runtime_store)?;
let retired_mind_attempt_ids =
retire_orphaned_memory_semantic_projection_attempts_v0(agent_store)?;
let retired_modeling_attempt_ids =
retire_orphaned_memory_semantic_projection_attempts_v0(runtime_store)?;
let retired_mind_receipt_ids = retire_unowned_memory_semantic_index_receipts(agent_store)?;
let retired_modeling_receipt_ids =
retire_unowned_memory_semantic_index_receipts(runtime_store)?;
let mind_attempt_ids = migrate_memory_semantic_projection_attempts_v0(agent_store)?;
let modeling_attempt_ids = migrate_memory_semantic_projection_attempts_v0(runtime_store)?;
println!(
"{}",
serde_json::to_string_pretty(&json!({
"schemaVersion": "epiphany.memory_semantic_projection_attempt_migration.v0",
"status": "completed",
"retiredMindClaimIds": retired_mind_claim_ids,
"retiredModelingClaimIds": retired_modeling_claim_ids,
"retiredMindAttemptIds": retired_mind_attempt_ids,
"retiredModelingAttemptIds": retired_modeling_attempt_ids,
"retiredMindReceiptIds": retired_mind_receipt_ids,
"retiredModelingReceiptIds": retired_modeling_receipt_ids,
"mindAttemptIds": mind_attempt_ids,
"modelingAttemptIds": modeling_attempt_ids,
"privateStateExposed": false,
}))?
);
Ok(())
}
fn semantic_projector_service_status(args: Args) -> Result<()> {
let receipt = load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt_for_service(
&args.store,
@ -766,22 +717,16 @@ fn semantic_projector_observation_status(
}
}
fn semantic_projection_input(args: &Args) -> Result<(MemorySemanticProjectionInput, &Path)> {
match (&args.agent_store, &args.runtime_store) {
(Some(path), None) => Ok((agent_memory_semantic_projection_input(path)?, path)),
(None, Some(path)) => Ok((runtime_modeling_semantic_projection_input(path)?, path)),
_ => anyhow::bail!(
"semantic projector commands require exactly one of --agent-store or --runtime-store"
),
}
}
fn required<'a>(value: &'a Option<String>, flag: &str) -> Result<&'a str> {
value.as_deref().with_context(|| format!("missing {flag}"))
}
fn semantic_recover(args: Args) -> Result<()> {
let (input, store) = semantic_projection_input(&args)?;
let store = args
.runtime_store
.as_ref()
.context("semantic-recover requires --runtime-store")?;
let input = runtime_modeling_semantic_projection_input(store)?;
let (authorization, claim) = idunn_recover_memory_semantic_projection_from_cultmesh(
&args.store,
args.runtime_id.clone(),
@ -1906,10 +1851,6 @@ fn semantic_projector_service_policy(mut args: Args) -> Result<()> {
"semantic-projector-service-policy derives its packaged executable; --service-command is forbidden"
);
}
let agent_store = args
.agent_store
.as_ref()
.context("semantic-projector-service-policy requires --agent-store")?;
let runtime_store = args
.runtime_store
.as_ref()
@ -1922,9 +1863,6 @@ fn semantic_projector_service_policy(mut args: Args) -> Result<()> {
.ollama_base_url
.as_deref()
.context("semantic-projector-service-policy requires --ollama-base-url")?;
if agent_store == runtime_store {
anyhow::bail!("semantic projector Mind and Modeling stores must be distinct");
}
args.service_id = SEMANTIC_PROJECTOR_SERVICE_ID.to_string();
args.policy_id = Some(format!(
"managed-service-policy-{SEMANTIC_PROJECTOR_SERVICE_ID}"
@ -1932,7 +1870,6 @@ fn semantic_projector_service_policy(mut args: Args) -> Result<()> {
args.restart_mode = "always".to_string();
args.service_command = Some(packaged_role_command_path(&args, "semantic-projector")?);
args.service_args = semantic_projector_service_args(
agent_store,
runtime_store,
&args.store,
&args.runtime_id,
@ -2027,7 +1964,6 @@ fn workspace_coverage_projector_service_args(
}
fn semantic_projector_service_args(
agent_store: &Path,
runtime_store: &Path,
local_verse_store: &Path,
runtime_id: &str,
@ -2038,8 +1974,6 @@ fn semantic_projector_service_args(
) -> Vec<String> {
vec![
"serve".to_string(),
"--agent-store".to_string(),
agent_store.display().to_string(),
"--runtime-store".to_string(),
runtime_store.display().to_string(),
"--local-verse-store".to_string(),
@ -4120,9 +4054,8 @@ mod semantic_projector_authority_tests {
}
#[test]
fn managed_projector_policy_launches_one_process_with_both_owned_partitions() {
fn managed_projector_policy_launches_one_modeling_process() {
let args = semantic_projector_service_args(
Path::new("mind.ccmp"),
Path::new("modeling.ccmp"),
Path::new("local-verse.ccmp"),
"local-runtime",
@ -4135,8 +4068,6 @@ mod semantic_projector_authority_tests {
args,
vec![
"serve",
"--agent-store",
"mind.ccmp",
"--runtime-store",
"modeling.ccmp",
"--local-verse-store",
@ -4858,7 +4789,6 @@ struct Args {
artifact_ref: Option<String>,
stdout_artifact: Option<PathBuf>,
stderr_artifact: Option<PathBuf>,
agent_store: Option<PathBuf>,
runtime_store: Option<PathBuf>,
expected_claim_id: Option<String>,
provider_heartbeat_id: Option<String>,
@ -4917,7 +4847,6 @@ impl Args {
let mut artifact_ref = None;
let mut stdout_artifact = None;
let mut stderr_artifact = None;
let mut agent_store = None;
let mut runtime_store = None;
let mut expected_claim_id = None;
let mut provider_heartbeat_id = None;
@ -5053,11 +4982,6 @@ impl Args {
values.next().context("missing --stderr-artifact value")?,
));
}
"--agent-store" => {
agent_store = Some(PathBuf::from(
values.next().context("missing --agent-store value")?,
))
}
"--runtime-store" => {
runtime_store = Some(PathBuf::from(
values.next().context("missing --runtime-store value")?,
@ -5207,7 +5131,6 @@ impl Args {
| "managed-service-task-stop"
| "managed-service-task-uninstall"
| "migrate-retired-operator-status"
| "migrate-semantic-attempts-v0"
| "provider-health-identity-enroll"
| "provider-health-identity-export"
| "semantic-projector-service-status"
@ -5332,7 +5255,6 @@ impl Args {
artifact_ref,
stdout_artifact,
stderr_artifact,
agent_store,
runtime_store,
expected_claim_id,
provider_heartbeat_id,

View file

@ -55,25 +55,16 @@ fn main() -> Result<()> {
semantic_config.qdrant_url = args.qdrant_url.clone();
semantic_config.ollama_base_url = args.ollama_base_url.clone();
semantic_config.ollama_model = args.ollama_model.clone();
let projector = SemanticProjectorServiceBody::new(
&args.agent_store,
&args.runtime_store,
semantic_config.clone(),
)?;
let projector =
SemanticProjectorServiceBody::new(&args.runtime_store, semantic_config.clone())?;
let provider_incarnation = projector.provider_incarnation().to_string();
let mut cursor = None;
let mut sequence = 0_u64;
loop {
sequence = sequence.saturating_add(1);
let pulse = projector.pulse(cursor.as_deref());
let pulse = projector.pulse();
let outcome = pulse.outcome;
let inputs = pulse.inputs;
let source_faults = pulse.source_fault_count;
cursor = outcome
.selected_scope_id
.clone()
.or_else(|| outcome.inspections.last().map(|row| row.scope_id.clone()));
let mut retention_faults = Vec::new();
let mut retention_mutation_count = 0_u32;
for input in &inputs {
@ -216,7 +207,6 @@ fn authenticate_managed_launch(
fn source_store<'a>(args: &'a Args, input: &MemorySemanticProjectionInput) -> Result<&'a PathBuf> {
match input.obligation().partition.as_str() {
"mind" => Ok(&args.agent_store),
"modeling" => Ok(&args.runtime_store),
other => Err(anyhow!(
"unsupported semantic projection partition {other:?}"
@ -235,7 +225,6 @@ fn pulse_status(status: MemorySemanticProjectorPulseStatus) -> &'static str {
}
struct Args {
agent_store: PathBuf,
runtime_store: PathBuf,
local_verse_store: PathBuf,
runtime_id: String,
@ -256,7 +245,6 @@ impl Args {
if !matches!(command.as_str(), "pulse" | "once" | "serve" | "daemon") {
return Err(anyhow!("unknown command {command:?}; use pulse or serve"));
}
let mut agent_store = None;
let mut runtime_store = None;
let mut local_verse_store = None;
let mut runtime_id = "epiphany-local".to_string();
@ -277,7 +265,6 @@ impl Args {
.with_context(|| format!("missing value for {flag}"))
};
match flag.as_str() {
"--agent-store" => agent_store = Some(PathBuf::from(value()?)),
"--runtime-store" => runtime_store = Some(PathBuf::from(value()?)),
"--local-verse-store" => local_verse_store = Some(PathBuf::from(value()?)),
"--runtime-id" => runtime_id = value()?,
@ -297,7 +284,6 @@ impl Args {
return Err(anyhow!("--retained-generations must be positive"));
}
Ok(Self {
agent_store: agent_store.context("missing --agent-store")?,
runtime_store: runtime_store.context("missing --runtime-store")?,
local_verse_store: local_verse_store.context("missing --local-verse-store")?,
runtime_id,

View file

@ -1,8 +1,8 @@
use anyhow::{Context, Result, anyhow};
use epiphany_core::{
EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot, MemorySemanticIndexConfig,
MemorySemanticProjectionInput, SemanticPartition, WORKSPACE_COVERAGE_MAXIMUM_FILE_BYTES,
WorkspaceCoveragePolicy, WorkspaceProjectionIdentity, agent_memory_semantic_projection_input,
MemorySemanticProjectionInput, WORKSPACE_COVERAGE_MAXIMUM_FILE_BYTES,
WorkspaceCoveragePolicy, WorkspaceProjectionIdentity,
load_memory_semantic_projection_readiness, observe_repository_readiness,
publish_epiphany_cultmesh_semantic_projection_health,
runtime_modeling_semantic_projection_input, semantic_memory_context,
@ -47,7 +47,6 @@ fn main() -> Result<()> {
let packet = semantic_memory_context(
&snapshot,
&swarm_id,
options.partition,
&EpiphanyMemoryContextQuery {
id: options
.query_id
@ -67,11 +66,6 @@ fn main() -> Result<()> {
let runtime_store = options.runtime_store.as_ref().ok_or_else(|| {
usage_error("repository-readiness requires --runtime-store <path>")
})?;
if options.agent_store.is_some() {
return Err(usage_error(
"repository-readiness accepts only --runtime-store <path>",
));
}
let workspace_identity = WorkspaceProjectionIdentity {
policy: WorkspaceCoveragePolicy::bounded_regular_files_v0(
WORKSPACE_COVERAGE_MAXIMUM_FILE_BYTES,
@ -106,12 +100,10 @@ fn main() -> Result<()> {
struct Options {
runtime_store: Option<PathBuf>,
agent_store: Option<PathBuf>,
local_verse_store: Option<PathBuf>,
runtime_id: String,
provider_incarnation: Option<String>,
swarm_id: Option<String>,
partition: SemanticPartition,
text: Option<String>,
query_id: Option<String>,
budget: Option<u32>,
@ -125,12 +117,10 @@ impl Options {
fn parse(args: impl Iterator<Item = String>) -> Result<Self> {
let mut options = Self {
runtime_store: None,
agent_store: None,
local_verse_store: None,
runtime_id: "epiphany-memory-semantic".to_string(),
provider_incarnation: None,
swarm_id: None,
partition: SemanticPartition::Modeling,
text: None,
query_id: None,
budget: None,
@ -147,12 +137,10 @@ impl Options {
};
match flag.as_str() {
"--runtime-store" => options.runtime_store = Some(PathBuf::from(value()?)),
"--agent-store" => options.agent_store = Some(PathBuf::from(value()?)),
"--local-verse-store" => options.local_verse_store = Some(PathBuf::from(value()?)),
"--runtime-id" => options.runtime_id = value()?,
"--provider-incarnation" => options.provider_incarnation = Some(value()?),
"--swarm-id" => options.swarm_id = Some(value()?),
"--partition" => options.partition = parse_partition(&value()?)?,
"--text" => options.text = Some(value()?),
"--query-id" => options.query_id = Some(value()?),
"--budget" => options.budget = Some(value()?.parse().context("invalid budget")?),
@ -178,23 +166,8 @@ impl Options {
{
return Err(usage_error("--swarm-id must not be empty"));
}
let sources = [
options.runtime_store.is_some(),
options.agent_store.is_some(),
]
.into_iter()
.filter(|present| *present)
.count();
if sources != 1 {
return Err(usage_error(
"provide exactly one --runtime-store or --agent-store",
));
}
if options.partition == SemanticPartition::Mind && options.runtime_store.is_some() {
return Err(usage_error("Mind projection requires --agent-store"));
}
if options.partition == SemanticPartition::Modeling && options.agent_store.is_some() {
return Err(usage_error("Modeling projection requires --runtime-store"));
if options.runtime_store.is_none() {
return Err(usage_error("provide --runtime-store"));
}
Ok(options)
}
@ -208,13 +181,11 @@ impl Options {
}
fn load_projection_input(&self) -> Result<(MemorySemanticProjectionInput, &PathBuf)> {
let (input, store) = if let Some(path) = &self.runtime_store {
(runtime_modeling_semantic_projection_input(path)?, path)
} else if let Some(path) = &self.agent_store {
(agent_memory_semantic_projection_input(path)?, path)
} else {
return Err(anyhow!("semantic projection requires a typed source store"));
};
let store = self
.runtime_store
.as_ref()
.ok_or_else(|| anyhow!("semantic projection requires the runtime store"))?;
let input = runtime_modeling_semantic_projection_input(store)?;
if self
.swarm_id
.as_ref()
@ -228,7 +199,7 @@ impl Options {
}
fn source_store(&self) -> Option<&PathBuf> {
self.runtime_store.as_ref().or(self.agent_store.as_ref())
self.runtime_store.as_ref()
}
fn provider_incarnation(&self) -> Result<&str> {
@ -241,14 +212,6 @@ impl Options {
}
}
fn parse_partition(value: &str) -> Result<SemanticPartition> {
match value {
"mind" => Ok(SemanticPartition::Mind),
"modeling" => Ok(SemanticPartition::Modeling),
_ => Err(usage_error("partition must be mind or modeling")),
}
}
fn parse_profile(value: &str) -> Result<epiphany_core::EpiphanyMemoryProfile> {
serde_json::from_str(&format!("\"{value}\""))
.with_context(|| format!("unknown memory profile {value:?}"))
@ -256,7 +219,7 @@ fn parse_profile(value: &str) -> Result<epiphany_core::EpiphanyMemoryProfile> {
fn usage_error(message: &str) -> anyhow::Error {
anyhow!(
"{message}\nusage: epiphany-memory-semantic <context|health|repository-readiness> (--runtime-store <path>|--agent-store <path>|--graph-store <path>) [--swarm-id <id>] --partition <mind|modeling> [--local-verse-store <path> --runtime-id <id> --provider-incarnation <id>] [--text <query>] [--query-id <id>] [--budget <n>] [--profile <profile>] [--workspace-embedding-provider-id <id> --workspace-embedding-model <model> --workspace-vector-dimensions <n>]"
"{message}\nusage: epiphany-memory-semantic <context|health|repository-readiness> --runtime-store <path> [--swarm-id <id>] [--local-verse-store <path> --runtime-id <id> --provider-incarnation <id>] [--text <query>] [--query-id <id>] [--budget <n>] [--profile <profile>] [--workspace-embedding-provider-id <id> --workspace-embedding-model <model> --workspace-vector-dimensions <n>]"
)
}

View file

@ -2647,7 +2647,7 @@ fn validate_semantic_projection_health(
|| row.verse_id != EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID
|| row.verse_tier != EPIPHANY_CULTMESH_LOCAL_AREA_TIER
|| row.swarm_id.trim().is_empty()
|| !matches!(row.partition.as_str(), "mind" | "modeling")
|| row.partition != "modeling"
|| row.obligation_id.trim().is_empty()
|| row.canonical_model_hash.trim().is_empty()
|| row.canonical_content_set_hash.trim().is_empty()
@ -4572,31 +4572,30 @@ fn validate_semantic_projector_managed_service_policy(
if policy.policy_id != "managed-service-policy-epiphany-memory-semantic-projector-service"
|| policy.owner_daemon_id != "epiphany-daemon-supervisor"
|| policy.restart_mode != "always"
|| policy.args.len() != 17
|| policy.args.len() != 15
|| policy.args[0] != "serve"
|| policy.args[1] != "--agent-store"
|| policy.args[1] != "--runtime-store"
|| policy.args[2].trim().is_empty()
|| policy.args[3] != "--runtime-store"
|| policy.args[3] != "--local-verse-store"
|| policy.args[4].trim().is_empty()
|| policy.args[5] != "--local-verse-store"
|| policy.args[5] != "--runtime-id"
|| policy.args[6].trim().is_empty()
|| policy.args[7] != "--runtime-id"
|| policy.args[7] != "--interval-seconds"
|| policy.args[8].trim().is_empty()
|| policy.args[9] != "--interval-seconds"
|| policy.args[10]
|| policy.args[8]
.parse::<u64>()
.ok()
.filter(|value| *value > 0)
.is_none()
|| policy.args[11] != "--qdrant-url"
|| policy.args[9] != "--qdrant-url"
|| policy.args[10].trim().is_empty()
|| policy.args[11] != "--ollama-base-url"
|| policy.args[12].trim().is_empty()
|| policy.args[13] != "--ollama-base-url"
|| policy.args[13] != "--ollama-model"
|| policy.args[14].trim().is_empty()
|| policy.args[15] != "--ollama-model"
|| policy.args[16].trim().is_empty()
{
return Err(anyhow!(
"reserved semantic projector policy must bind one packaged process to both canonical stores"
"reserved semantic projector policy must bind one packaged process to the canonical Modeling store"
));
}
Ok(())
@ -7558,8 +7557,6 @@ mod tests {
command: binary.into(),
args: vec![
"serve",
"--agent-store",
"mind.ccmp",
"--runtime-store",
"modeling.ccmp",
"--local-verse-store",
@ -7908,13 +7905,12 @@ mod tests {
}
#[test]
fn semantic_health_publication_is_monotonic_partitioned_sight_only() -> Result<()> {
fn semantic_health_publication_is_monotonic_sight_only() -> Result<()> {
let temp = tempfile::tempdir()?;
let canonical = temp.path().join("canonical.msgpack");
let verse = temp.path().join("verse.ccmp");
let modeling_1 = semantic_health_input(&canonical, "swarm-a", "modeling", 1)?;
let modeling_2 = semantic_health_input(&canonical, "swarm-a", "modeling", 2)?;
let mind_1 = semantic_health_input(&canonical, "swarm-a", "mind", 1)?;
let before = SingleFileMessagePackBackingStore::new(&canonical).pull_all()?;
publish_epiphany_cultmesh_semantic_projection_health(
@ -7938,20 +7934,11 @@ mod tests {
&modeling_1,
"incarnation-a",
)?;
publish_epiphany_cultmesh_semantic_projection_health(
&verse,
"runtime",
&canonical,
&mind_1,
"incarnation-a",
)?;
assert_eq!(delayed.source_generation, 2);
let rows = load_epiphany_cultmesh_semantic_projection_health(&verse, "runtime")?;
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].partition, "mind");
assert_eq!(rows[1].partition, "modeling");
assert_eq!(rows[1].source_generation, 2);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].partition, "modeling");
assert_eq!(rows[0].source_generation, 2);
assert!(rows.iter().all(|row| !row.private_state_exposed));
assert_eq!(
SingleFileMessagePackBackingStore::new(&canonical).pull_all()?,
@ -8024,7 +8011,7 @@ mod tests {
let temp = tempfile::tempdir()?;
let canonical = temp.path().join("canonical.msgpack");
let verse = temp.path().join("verse.ccmp");
let input = semantic_health_input(&canonical, "swarm-a", "mind", 1)?;
let input = semantic_health_input(&canonical, "swarm-a", "modeling", 1)?;
let row = publish_epiphany_cultmesh_semantic_projection_health(
&verse,
"runtime",
@ -8034,7 +8021,7 @@ mod tests {
)?;
let hostile_key = format!(
"{}/latest",
semantic_projection_health_scope_key("other-swarm", "mind")
semantic_projection_health_scope_key("other-swarm", "modeling")
);
let mut node = open_epiphany_cultmesh_node(&verse, "hostile")?;
node.put(hostile_key, &row)?;
@ -8055,7 +8042,7 @@ mod tests {
let temp = tempfile::tempdir()?;
let canonical = temp.path().join("canonical.msgpack");
let verse = temp.path().join("verse.ccmp");
let input = semantic_health_input(&canonical, "swarm-a", "mind", 1)?;
let input = semantic_health_input(&canonical, "swarm-a", "modeling", 1)?;
let mut empty_authority = input.clone();
empty_authority.authority.envelopes.clear();
assert!(
@ -8103,7 +8090,6 @@ mod tests {
let packet = crate::semantic_memory_context(
input.snapshot(),
"swarm-a",
crate::SemanticPartition::Mind,
&crate::EpiphanyMemoryContextQuery {
id: "hostile-query".to_string(),
text: Some("test".to_string()),
@ -10929,7 +10915,7 @@ mod tests {
let temp = tempfile::tempdir()?;
let canonical = temp.path().join("canonical.msgpack");
let verse = temp.path().join("verse.ccmp");
let input = semantic_health_input(&canonical, "swarm-recovery", "mind", 1)?;
let input = semantic_health_input(&canonical, "swarm-recovery", "modeling", 1)?;
let claim =
crate::memory_graph::semantic_projector::idunn_acquire_memory_semantic_projection(
&canonical,
@ -10954,8 +10940,6 @@ mod tests {
command: binary.into(),
args: vec![
"serve",
"--agent-store",
"mind.ccmp",
"--runtime-store",
"modeling.ccmp",
"--local-verse-store",

View file

@ -4,7 +4,6 @@ use anyhow::anyhow;
use chrono::DateTime;
use chrono::Duration;
use chrono::Utc;
use epiphany_state_model::EpiphanyMemoryContextQuery;
use serde_json::Value;
use sha2::Digest;
use std::collections::BTreeMap;
@ -1212,12 +1211,7 @@ fn tick_once(
&pending,
&selected_after_identity(&selected),
selected_pending_mentions.clone(),
persona_memory_recall_for_scheduled_turn(
options.agent_store.as_deref(),
&selected,
&action,
&selected_pending_mentions,
),
Value::Null,
)?;
}
if !options.defer_completion && action.action_type != "persona_turn" {
@ -1225,12 +1219,6 @@ fn tick_once(
}
let selected_after = state.participants[selected_index].clone();
let persona_memory_recall = persona_memory_recall_for_scheduled_turn(
options.agent_store.as_deref(),
&selected_after,
&action,
&selected_pending_mentions,
);
let event = HeartbeatHistoryEvent {
ts: now_iso(),
schedule_id: options.schedule_id.clone(),
@ -1280,7 +1268,6 @@ fn tick_once(
"commitment": action.commitment,
"local_affordance_basis": action.local_affordance_basis,
"pending_mentions": selected_pending_mentions,
"persona_memory_recall": persona_memory_recall,
}],
"reaction_windows": if let Some(work_role) = &work_role {
serde_json::json!([{
@ -1774,171 +1761,6 @@ fn action_for_selection(
}
}
fn persona_memory_recall_for_scheduled_turn(
agent_store: Option<&Path>,
selected: &HeartbeatParticipant,
action: &HeartbeatAction,
pending_mentions: &[HeartbeatPendingMention],
) -> Value {
if action.action_type != "persona_turn" || selected.role_id != "Persona" {
return Value::Null;
}
let Some(agent_store) = agent_store else {
return serde_json::json!({
"schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION,
"status": "unavailable",
"cacheStatus": "agent-store-missing",
"renderedRecall": "- semantic Persona memory recall unavailable: no agent store was provided for this heartbeat tick",
"privateStateExposed": false,
});
};
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,
Ok(None) => {
return serde_json::json!({
"schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION,
"status": "unavailable",
"cacheStatus": "persona-memory-missing",
"renderedRecall": "- semantic Persona memory recall unavailable: Persona memory entry is missing",
"privateStateExposed": false,
});
}
Err(error) => {
return serde_json::json!({
"schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION,
"status": "unavailable",
"cacheStatus": "persona-memory-load-failed",
"renderedRecall": format!("- semantic Persona memory recall unavailable: {}", compact_heartbeat_line(&format!("{error:#}"), 320)),
"privateStateExposed": false,
});
}
};
let query = persona_memory_recall_query(selected, pending_mentions);
let mut entries = Vec::new();
for role in crate::agent_memory_role_ids() {
if let Ok(Some(role_entry)) = crate::load_agent_memory_entry_for_role(agent_store, role) {
entries.push(role_entry);
}
}
let swarm_id = swarm_identity.swarm_id;
let projection_input = crate::agent_memory_semantic_projection_input(agent_store).ok();
let graph = projection_input.as_ref().map_or_else(
|| crate::memory_graph_from_agent_memories(&format!("{swarm_id}-mind"), &entries),
|input| input.snapshot.clone(),
);
let persona_domain_id =
crate::memory_graph_domain_id(crate::EpiphanyMemoryProfile::RoleSelf, "role", "Persona");
let query_document = EpiphanyMemoryContextQuery {
id: "heartbeat-persona-turn".to_string(),
profile: Some(crate::EpiphanyMemoryProfile::RoleSelf),
domain_ids: vec![persona_domain_id],
node_ids: Vec::new(),
edge_ids: Vec::new(),
text: Some(query.clone()),
budget: Some(8),
};
let config = memory_semantic_config_for_heartbeat();
let readiness = projection_input.as_ref().and_then(|input| {
crate::load_memory_semantic_projection_readiness(agent_store, input)
.ok()
.flatten()
});
let packet = crate::semantic_memory_context(
&graph,
&swarm_id,
crate::SemanticPartition::Mind,
&query_document,
readiness.as_ref(),
&config,
);
let fallback = packet
.warnings
.iter()
.any(|warning| warning.contains("canonical BM25 fallback"));
let rendered_recall = crate::render_persona_semantic_memory_recall(&packet);
serde_json::json!({
"schemaVersion": crate::SEMANTIC_PROJECTION_SCHEMA_VERSION,
"status": if fallback { "fallback" } else { "ready" },
"cacheStatus": if fallback { "canonical-bm25" } else { "shared-mind-qdrant" },
"identityId": entry.agent.agent_id,
"roleId": entry.role_id,
"chunkCount": graph.nodes.len() + graph.summaries.len(),
"hitCount": packet.nodes.len() + packet.summaries.len(),
"renderedRecall": rendered_recall,
"warnings": packet.warnings,
"privateStateExposed": false,
})
}
fn persona_memory_recall_query(
selected: &HeartbeatParticipant,
pending_mentions: &[HeartbeatPendingMention],
) -> String {
let mention_text = pending_mentions
.iter()
.map(|mention| {
format!(
"{}: {}",
mention.author_name.as_deref().unwrap_or(&mention.author_id),
mention.visible_prompt
)
})
.collect::<Vec<_>>()
.join("\n");
format!(
"{} current Persona turn\nPending addressed pressure:\n{}",
selected.display_name,
if mention_text.trim().is_empty() {
"(none)"
} else {
mention_text.as_str()
}
)
}
fn memory_semantic_config_for_heartbeat() -> crate::MemorySemanticIndexConfig {
let mut config = crate::MemorySemanticIndexConfig::from_env();
config.qdrant_timeout_ms = config.qdrant_timeout_ms.min(1_000);
config.ollama_timeout_ms = config.ollama_timeout_ms.min(1_000);
config
}
fn compact_heartbeat_line(value: &str, max_len: usize) -> String {
let mut compacted = value.split_whitespace().collect::<Vec<_>>().join(" ");
if compacted.len() > max_len {
let keep = max_len.saturating_sub(3);
compacted.truncate(keep);
compacted.push_str("...");
}
compacted
}
fn work_role_for_action(action: Option<&str>, target_role: Option<&str>) -> Option<String> {
if let Some(target_role) = target_role
&& (ROLE_ORDER.contains(&target_role) || target_role.starts_with("ghostlight.character."))
@ -4201,14 +4023,6 @@ const STOP_WORDS: &[&str] = &[
#[cfg(test)]
mod tests {
use super::*;
use crate::EpiphanyAgentMemoryEntry;
use crate::GhostlightAgent;
use crate::GhostlightCanonicalState;
use crate::GhostlightIdentity;
use crate::GhostlightMemories;
use crate::GhostlightMemory;
use crate::GhostlightValue;
use crate::GhostlightWorld;
use pretty_assertions::assert_eq;
#[test]
@ -4882,129 +4696,6 @@ mod tests {
Ok(())
}
#[test]
fn persona_turn_action_catalog_carries_memory_recall_from_agent_store() -> Result<()> {
let temp = tempfile::tempdir()?;
let store_path = temp.path().join("Persona-heartbeats.msgpack");
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, "heartbeat-test-swarm")?;
crate::write_agent_memory_entry_for_role_migration(&agent_store, &persona_memory_entry())?;
queue_heartbeat_pending_mention_store(
&store_path,
HeartbeatQueueMentionOptions {
target_role_id: "Persona".to_string(),
source_surface: "discord".to_string(),
channel_id: "aquarium".to_string(),
message_id: "m1".to_string(),
author_id: "human".to_string(),
author_name: Some("Metacrat".to_string()),
content: "Epiphany, remember the typed contracts before speaking.".to_string(),
visible_prompt: "remember the typed contracts before speaking".to_string(),
reply_to_message_id: None,
queued_at: Some("2026-05-24T00:00:00+00:00".to_string()),
mention_id: Some("mention-Persona-memory-test".to_string()),
source_visibility: "public".to_string(),
data_classification: "public_feedback".to_string(),
model_provider_id: "openai-codex".to_string(),
model_provider_disclosure_allowed: true,
},
)?;
let tick = tick_heartbeat_store(
&store_path,
&artifact_dir,
HeartbeatTickOptions {
target_heartbeat_rate: 1.0,
coordinator_action: None,
target_role: None,
urgency: 0.0,
schedule_id: "Persona-mentioned-memory".to_string(),
source_scene_ref: "test/Persona-mentioned-memory".to_string(),
defer_completion: true,
agent_store: Some(agent_store),
resident_self_store: None,
},
)?;
let recall = &tick["schedule"]["action_catalog"][0]["persona_memory_recall"];
assert_eq!(
recall["schemaVersion"],
crate::SEMANTIC_PROJECTION_SCHEMA_VERSION
);
assert_eq!(recall["roleId"], "Persona");
assert_eq!(recall["privateStateExposed"], false);
assert!(
!recall["status"].as_str().unwrap_or_default().is_empty(),
"Persona recall should report whether it came from Qdrant or fallback"
);
assert!(
!recall["cacheStatus"]
.as_str()
.unwrap_or_default()
.is_empty(),
"Persona recall should report cache status"
);
assert!(
!recall["renderedRecall"]
.as_str()
.unwrap_or_default()
.trim()
.is_empty(),
"Persona recall should carry a rendered prompt surface"
);
assert!(recall["chunkCount"].as_u64().unwrap_or_default() > 0);
assert!(
!recall["renderedRecall"]
.as_str()
.unwrap_or_default()
.contains("sealed private note")
);
Ok(())
}
fn persona_memory_entry() -> EpiphanyAgentMemoryEntry {
EpiphanyAgentMemoryEntry {
schema_version: "ghostlight.agent_state.v0".to_string(),
role_id: "Persona".to_string(),
world: GhostlightWorld::default(),
agent: GhostlightAgent {
agent_id: "epiphany.Persona".to_string(),
identity: GhostlightIdentity {
name: "Epiphany".to_string(),
roles: vec!["Persona".to_string()],
origin: "EpiphanyAgent".to_string(),
public_description: "Public typed-contract voice.".to_string(),
private_notes: vec!["sealed private note".to_string()],
},
memories: GhostlightMemories {
semantic: vec![GhostlightMemory {
memory_id: "semantic-1".to_string(),
summary: "Clean typed contracts must shape Persona speech.".to_string(),
salience: 0.9,
confidence: 0.9,
..Default::default()
}],
..Default::default()
},
canonical_state: GhostlightCanonicalState {
values: vec![GhostlightValue {
value_id: "value-1".to_string(),
label: "Clean typed contracts".to_string(),
priority: 0.9,
unforgivable_if_betrayed: true,
}],
..Default::default()
},
..Default::default()
},
relationships: Vec::new(),
events: Vec::new(),
scenes: Vec::new(),
}
}
#[test]
fn appraisal_mood_timing_carries_affect_vector() {
let mut state = default_heartbeat_state(1.0);

View file

@ -137,7 +137,6 @@ pub use agent_memory::GhostlightValue;
pub use agent_memory::GhostlightWorld;
pub use agent_memory::PERSONA_STATE_SCHEMA_VERSION;
pub use agent_memory::agent_memory_role_ids;
pub use agent_memory::agent_memory_semantic_projection_input;
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;
@ -702,12 +701,9 @@ pub use memory_graph::RepoFrontierStatus;
pub use memory_graph::SEMANTIC_PROJECTION_SCHEMA_VERSION;
pub use memory_graph::SemanticCanonicalLocator;
pub use memory_graph::SemanticDocumentKind;
pub use memory_graph::SemanticEmbedder;
pub use memory_graph::SemanticLifecycle;
pub use memory_graph::SemanticPartition;
pub use memory_graph::SemanticProjectionCandidate;
pub use memory_graph::SemanticProjectionDocument;
pub use memory_graph::SemanticVectorIndex;
pub use memory_graph::SemanticVisibility;
pub use memory_graph::authorize_memory_semantic_physical_retirements;
pub use memory_graph::bind_memory_semantic_index_receipt;
@ -722,20 +718,15 @@ pub use memory_graph::load_memory_semantic_projection_readiness;
pub use memory_graph::load_memory_semantic_projection_success;
pub use memory_graph::memory_graph_domain_id;
pub use memory_graph::memory_graph_edge_id;
pub use memory_graph::memory_graph_from_agent_memories;
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::memory_semantic_projection_query_eligible;
pub use memory_graph::migrate_memory_semantic_projection_attempts_v0;
pub use memory_graph::observe_memory_semantic_projection;
pub use memory_graph::plan_memory_graph_context_cut;
pub use memory_graph::plan_memory_graph_context_cut_with_ranked_ids;
pub use memory_graph::resolve_semantic_candidate;
pub use memory_graph::retain_memory_semantic_projection_lifecycles;
pub use memory_graph::retire_memory_semantic_projection_claims_v0;
pub use memory_graph::retire_orphaned_memory_semantic_projection_attempts_v0;
pub use memory_graph::retire_unowned_memory_semantic_index_receipts;
pub use memory_graph::semantic_memory_context;
pub use memory_graph::semantic_point_id;
pub use memory_graph::validate_memory_graph_snapshot;
@ -1024,7 +1015,6 @@ pub use runtime_spine::write_runtime_schema_catalog_json;
pub use runtime_worker_attempt::{RuntimeTypedRequestRef, WorkerProcessStatus};
pub use semantic_projector_service::SemanticProjectorServiceBody;
pub use semantic_projector_service::SemanticProjectorServicePulse;
pub use semantic_projector_service::validate_semantic_projector_source_pair;
pub use soul_gateway::*;
pub use state_ledger::EpiphanyBranchRecord;
pub use state_ledger::EpiphanyLedgerEvidenceRecord;

View file

@ -9,7 +9,6 @@ use super::EpiphanyMemoryProfile;
use super::EpiphanyMemorySummary;
use super::RepoFrontierItem;
use super::RepoFrontierStatus;
use super::SemanticPartition;
use super::derive_memory_graph_freshness;
use super::ids::normalized_key;
use super::ids::stable_memory_graph_id;
@ -24,7 +23,7 @@ pub fn plan_memory_graph_context_cut(
snapshot: &EpiphanyMemoryGraphSnapshot,
query: &EpiphanyMemoryContextQuery,
) -> EpiphanyMemoryContextPacket {
plan_memory_graph_context_cut_constrained(snapshot, query, &[], None)
plan_memory_graph_context_cut_constrained(snapshot, query, &[], false)
}
pub fn plan_memory_graph_context_cut_with_ranked_ids(
@ -32,23 +31,22 @@ pub fn plan_memory_graph_context_cut_with_ranked_ids(
query: &EpiphanyMemoryContextQuery,
ranked_document_ids: &[String],
) -> EpiphanyMemoryContextPacket {
plan_memory_graph_context_cut_constrained(snapshot, query, ranked_document_ids, None)
plan_memory_graph_context_cut_constrained(snapshot, query, ranked_document_ids, false)
}
pub(crate) fn plan_memory_graph_context_cut_for_partition(
pub(crate) fn plan_modeling_context_cut(
snapshot: &EpiphanyMemoryGraphSnapshot,
query: &EpiphanyMemoryContextQuery,
ranked_document_ids: &[String],
partition: SemanticPartition,
) -> EpiphanyMemoryContextPacket {
plan_memory_graph_context_cut_constrained(snapshot, query, ranked_document_ids, Some(partition))
plan_memory_graph_context_cut_constrained(snapshot, query, ranked_document_ids, true)
}
fn plan_memory_graph_context_cut_constrained(
snapshot: &EpiphanyMemoryGraphSnapshot,
query: &EpiphanyMemoryContextQuery,
ranked_document_ids: &[String],
partition: Option<SemanticPartition>,
modeling_only: bool,
) -> EpiphanyMemoryContextPacket {
let budget = query.budget.unwrap_or(12).clamp(1, 64) as usize;
let dirty_source_hashes = snapshot
@ -112,7 +110,7 @@ fn plan_memory_graph_context_cut_constrained(
let (frontier, rejected_frontier_ids) = dependency_ordered_frontier(
snapshot,
query,
partition,
modeling_only,
budget,
&node_by_id,
&stale_nodes,
@ -138,7 +136,7 @@ fn plan_memory_graph_context_cut_constrained(
for document_id in ranked_document_ids {
if let Some(node) = node_by_id.get(document_id.as_str()) {
if !stale_nodes.contains(node.id.as_str())
&& node_matches(node, query.profile, partition, &domains, &[])
&& node_matches(node, query.profile, modeling_only, &domains, &[])
{
push_unique_node(&mut nodes, (*node).clone(), budget);
}
@ -150,19 +148,19 @@ fn plan_memory_graph_context_cut_constrained(
.all(|id| !stale_nodes.contains(id));
if !stale_edges.contains(edge.id.as_str())
&& endpoints_live
&& edge_matches(edge, query.profile, partition, &domains, &node_by_id)
&& edge_matches(edge, query.profile, modeling_only, &domains, &node_by_id)
{
push_unique_edge(&mut edges, (*edge).clone(), budget);
if let Some(node) = node_by_id.get(edge.source_id.as_str()) {
if !stale_nodes.contains(node.id.as_str())
&& node_matches(node, query.profile, partition, &domains, &[])
&& node_matches(node, query.profile, modeling_only, &domains, &[])
{
push_unique_node(&mut nodes, (*node).clone(), budget);
}
}
if let Some(node) = node_by_id.get(edge.target_id.as_str()) {
if !stale_nodes.contains(node.id.as_str())
&& node_matches(node, query.profile, partition, &domains, &[])
&& node_matches(node, query.profile, modeling_only, &domains, &[])
{
push_unique_node(&mut nodes, (*node).clone(), budget);
}
@ -177,7 +175,7 @@ fn plan_memory_graph_context_cut_constrained(
&& summary_matches(
summary,
query.profile,
partition,
modeling_only,
&domains,
&[],
&node_by_id,
@ -190,14 +188,21 @@ fn plan_memory_graph_context_cut_constrained(
}
}
for summary in ranked_summaries(snapshot, query, partition, &domains, &terms, &node_by_id) {
for summary in ranked_summaries(
snapshot,
query,
modeling_only,
&domains,
&terms,
&node_by_id,
) {
if summaries.len() >= budget {
break;
}
if !summary_matches(
summary,
query.profile,
partition,
modeling_only,
&domains,
&terms,
&node_by_id,
@ -221,7 +226,7 @@ fn plan_memory_graph_context_cut_constrained(
&stale_nodes,
&stale_edges,
query.profile,
partition,
modeling_only,
&domains,
budget,
&mut nodes,
@ -232,7 +237,7 @@ fn plan_memory_graph_context_cut_constrained(
for node_id in &query.node_ids {
if let Some(node) = node_by_id.get(node_id.as_str()) {
if !stale_nodes.contains(node.id.as_str())
&& node_matches(node, query.profile, partition, &domains, &[])
&& node_matches(node, query.profile, modeling_only, &domains, &[])
{
push_unique_node(&mut nodes, (*node).clone(), budget);
}
@ -241,13 +246,13 @@ fn plan_memory_graph_context_cut_constrained(
for edge_id in &query.edge_ids {
if let Some(edge) = edge_by_id.get(edge_id.as_str()) {
if !stale_edges.contains(edge.id.as_str())
&& edge_matches(edge, query.profile, partition, &domains, &node_by_id)
&& edge_matches(edge, query.profile, modeling_only, &domains, &node_by_id)
{
push_unique_edge(&mut edges, (*edge).clone(), budget);
for node_id in [&edge.source_id, &edge.target_id] {
if let Some(node) = node_by_id.get(node_id.as_str())
&& !stale_nodes.contains(node.id.as_str())
&& node_matches(node, query.profile, partition, &domains, &[])
&& node_matches(node, query.profile, modeling_only, &domains, &[])
{
push_unique_node(&mut nodes, (*node).clone(), budget);
}
@ -257,11 +262,18 @@ fn plan_memory_graph_context_cut_constrained(
}
if summaries.is_empty() && nodes.is_empty() {
for node in ranked_nodes(snapshot, query, partition, &domains, &terms, &stale_nodes) {
for node in ranked_nodes(
snapshot,
query,
modeling_only,
&domains,
&terms,
&stale_nodes,
) {
if nodes.len() >= budget {
break;
}
if node_matches(node, query.profile, partition, &domains, &terms) {
if node_matches(node, query.profile, modeling_only, &domains, &terms) {
push_unique_node(&mut nodes, node.clone(), budget);
}
}
@ -303,15 +315,12 @@ fn plan_memory_graph_context_cut_constrained(
fn dependency_ordered_frontier(
snapshot: &EpiphanyMemoryGraphSnapshot,
query: &EpiphanyMemoryContextQuery,
partition: Option<SemanticPartition>,
modeling_only: bool,
budget: usize,
node_by_id: &HashMap<&str, &EpiphanyMemoryNode>,
stale_nodes: &HashSet<&str>,
domains: &HashSet<&str>,
) -> (Vec<RepoFrontierItem>, Vec<String>) {
if partition == Some(SemanticPartition::Mind) {
return (Vec::new(), Vec::new());
}
let unresolved = snapshot
.frontier
.iter()
@ -339,7 +348,7 @@ fn dependency_ordered_frontier(
super::EpiphanyMemoryLifecycle::Retired
| super::EpiphanyMemoryLifecycle::Stale
) && !stale_nodes.contains(id.as_str())
&& node_matches(node, query.profile, partition, domains, &[])
&& node_matches(node, query.profile, modeling_only, domains, &[])
})
})
})
@ -417,7 +426,7 @@ fn append_frontier_prerequisites<'a>(
fn ranked_nodes<'a>(
snapshot: &'a EpiphanyMemoryGraphSnapshot,
query: &EpiphanyMemoryContextQuery,
partition: Option<SemanticPartition>,
modeling_only: bool,
domain_ids: &HashSet<&str>,
terms: &[String],
stale_nodes: &HashSet<&str>,
@ -426,7 +435,7 @@ fn ranked_nodes<'a>(
.nodes
.iter()
.filter(|node| {
node_matches(node, query.profile, partition, domain_ids, &[])
node_matches(node, query.profile, modeling_only, domain_ids, &[])
&& !stale_nodes.contains(node.id.as_str())
})
.collect::<Vec<_>>();
@ -445,7 +454,7 @@ fn ranked_nodes<'a>(
fn ranked_summaries<'a>(
snapshot: &'a EpiphanyMemoryGraphSnapshot,
query: &EpiphanyMemoryContextQuery,
partition: Option<SemanticPartition>,
modeling_only: bool,
domain_ids: &HashSet<&str>,
terms: &[String],
node_by_id: &HashMap<&str, &EpiphanyMemoryNode>,
@ -457,7 +466,7 @@ fn ranked_summaries<'a>(
summary_matches(
summary,
query.profile,
partition,
modeling_only,
domain_ids,
&[],
node_by_id,
@ -512,7 +521,7 @@ fn query_terms(query: &EpiphanyMemoryContextQuery) -> Vec<String> {
fn summary_matches(
summary: &EpiphanyMemorySummary,
profile: Option<EpiphanyMemoryProfile>,
partition: Option<SemanticPartition>,
modeling_only: bool,
domain_ids: &HashSet<&str>,
terms: &[String],
node_by_id: &HashMap<&str, &EpiphanyMemoryNode>,
@ -524,8 +533,8 @@ fn summary_matches(
.covers_node_ids
.iter()
.filter_map(|id| node_by_id.get(id.as_str()))
.any(|node| partition_matches(node.profile, partition));
if partition.is_some() && !covers_partition {
.any(|node| modeling_scope_matches(node.profile, modeling_only));
if modeling_only && !covers_partition {
return false;
}
if let Some(profile) = profile {
@ -553,14 +562,14 @@ fn summary_matches(
fn node_matches(
node: &EpiphanyMemoryNode,
profile: Option<EpiphanyMemoryProfile>,
partition: Option<SemanticPartition>,
modeling_only: bool,
domain_ids: &HashSet<&str>,
terms: &[String],
) -> bool {
if profile.is_some_and(|profile| node.profile != profile) {
return false;
}
if !partition_matches(node.profile, partition) {
if !modeling_scope_matches(node.profile, modeling_only) {
return false;
}
if !domain_ids.is_empty() && !domain_ids.contains(node.domain_id.as_str()) {
@ -582,30 +591,29 @@ fn node_matches(
fn edge_matches(
edge: &EpiphanyMemoryEdge,
profile: Option<EpiphanyMemoryProfile>,
partition: Option<SemanticPartition>,
modeling_only: bool,
domain_ids: &HashSet<&str>,
node_by_id: &HashMap<&str, &EpiphanyMemoryNode>,
) -> bool {
if profile.is_some_and(|profile| edge.profile != profile)
|| !partition_matches(edge.profile, partition)
|| !modeling_scope_matches(edge.profile, modeling_only)
{
return false;
}
[&edge.source_id, &edge.target_id].into_iter().all(|id| {
node_by_id.get(id.as_str()).is_some_and(|node| {
partition_matches(node.profile, partition)
modeling_scope_matches(node.profile, modeling_only)
&& (domain_ids.is_empty() || domain_ids.contains(node.domain_id.as_str()))
})
})
}
fn partition_matches(profile: EpiphanyMemoryProfile, partition: Option<SemanticPartition>) -> bool {
partition.is_none_or(|partition| {
matches!(
fn modeling_scope_matches(profile: EpiphanyMemoryProfile, modeling_only: bool) -> bool {
!modeling_only
|| matches!(
profile,
EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow
) == (partition == SemanticPartition::Modeling)
})
)
}
fn text_matches_terms<'a>(values: impl IntoIterator<Item = &'a String>, terms: &[String]) -> bool {
@ -631,7 +639,7 @@ fn include_summary_children(
stale_nodes: &HashSet<&str>,
stale_edges: &HashSet<&str>,
profile: Option<EpiphanyMemoryProfile>,
partition: Option<SemanticPartition>,
modeling_only: bool,
domain_ids: &HashSet<&str>,
budget: usize,
nodes: &mut Vec<EpiphanyMemoryNode>,
@ -640,7 +648,7 @@ fn include_summary_children(
for node_id in &summary.covers_node_ids {
if let Some(node) = node_by_id.get(node_id.as_str()) {
if stale_nodes.contains(node.id.as_str())
|| !node_matches(node, profile, partition, domain_ids, &[])
|| !node_matches(node, profile, modeling_only, domain_ids, &[])
{
continue;
}
@ -650,7 +658,7 @@ fn include_summary_children(
for edge_id in &summary.covers_edge_ids {
if let Some(edge) = edge_by_id.get(edge_id.as_str()) {
if stale_edges.contains(edge.id.as_str())
|| !edge_matches(edge, profile, partition, domain_ids, node_by_id)
|| !edge_matches(edge, profile, modeling_only, domain_ids, node_by_id)
{
continue;
}

View file

@ -32,13 +32,12 @@ pub use epiphany_state_model::RepoFrontierStatus;
pub use compose::compose_memory_graph_snapshots;
pub use context_cut::plan_memory_graph_context_cut;
pub(crate) use context_cut::plan_memory_graph_context_cut_for_partition;
pub use context_cut::plan_memory_graph_context_cut_with_ranked_ids;
pub(crate) use context_cut::plan_modeling_context_cut;
pub use freshness::derive_memory_graph_freshness;
pub use ids::memory_graph_domain_id;
pub use ids::memory_graph_edge_id;
pub use ids::memory_graph_node_id;
pub use profiles::memory_graph_from_agent_memories;
pub use profiles::memory_graph_from_heartbeat_cognition;
pub use semantic_index::*;
pub use semantic_projection::*;

View file

@ -1,270 +0,0 @@
use crate::agent_memory::EpiphanyAgentMemoryEntry;
use crate::agent_memory::GhostlightGoal;
use crate::agent_memory::GhostlightMemory;
use crate::agent_memory::GhostlightValue;
use crate::memory_graph::EpiphanyMemoryDomain;
use crate::memory_graph::EpiphanyMemoryGraphSnapshot;
use crate::memory_graph::EpiphanyMemoryLifecycle;
use crate::memory_graph::EpiphanyMemoryNode;
use crate::memory_graph::EpiphanyMemoryNodeKind;
use crate::memory_graph::EpiphanyMemoryProfile;
use crate::memory_graph::EpiphanyMemorySummary;
use crate::memory_graph::memory_graph_domain_id;
use crate::memory_graph::memory_graph_node_id;
pub fn memory_graph_from_agent_memories(
graph_id: impl Into<String>,
entries: &[EpiphanyAgentMemoryEntry],
) -> EpiphanyMemoryGraphSnapshot {
let mut domains = Vec::new();
let mut nodes = Vec::new();
let mut summaries = Vec::new();
for entry in entries {
let domain_id = memory_graph_domain_id(
EpiphanyMemoryProfile::RoleSelf,
"role",
entry.role_id.as_str(),
);
domains.push(EpiphanyMemoryDomain {
id: domain_id.clone(),
profile: EpiphanyMemoryProfile::RoleSelf,
title: format!("{} role self-memory", entry.role_id),
description: Some(
"Reviewed organ-state memory imported into the shared memory graph.".to_string(),
),
lifecycle: EpiphanyMemoryLifecycle::Accepted,
});
let before = nodes.len();
import_memories(
&domain_id,
&entry.role_id,
"semantic",
&entry.agent.memories.semantic,
&mut nodes,
);
import_memories(
&domain_id,
&entry.role_id,
"episodic",
&entry.agent.memories.episodic,
&mut nodes,
);
import_memories(
&domain_id,
&entry.role_id,
"relationship",
&entry.agent.memories.relationship_summaries,
&mut nodes,
);
import_goals(&domain_id, &entry.role_id, &entry.agent.goals, &mut nodes);
import_values(
&domain_id,
&entry.role_id,
&entry.agent.canonical_state.values,
&mut nodes,
);
let role_node_ids = nodes[before..]
.iter()
.map(|node| node.id.clone())
.collect::<Vec<_>>();
if !role_node_ids.is_empty() {
summaries.push(EpiphanyMemorySummary {
id: format!("summary-role-self-{}", entry.role_id),
domain_id: domain_id.clone(),
covers_node_ids: role_node_ids,
target: format!("role:{}", entry.role_id),
claim: format!(
"{} reviewed role self-memory records are available in the shared memory graph.",
entry.role_id
),
question: "Which memory should shape this role's next context packet?".to_string(),
tension: "Role memory is self truth, not project truth.".to_string(),
action_implication: "Use this summary for role-local context; keep project architecture in repo profiles.".to_string(),
anchor_count: 0,
freshness: crate::memory_graph::EpiphanyMemoryFreshnessStatus::Ready,
confidence: 80,
..Default::default()
});
}
}
EpiphanyMemoryGraphSnapshot {
schema_version: Some("epiphany.memory_graph.v1".to_string()),
graph_id: graph_id.into(),
domains,
nodes,
summaries,
freshness: Some(crate::memory_graph::EpiphanyMemoryFreshness {
status: crate::memory_graph::EpiphanyMemoryFreshnessStatus::Ready,
note: Some("Imported from reviewed organ-state memory.".to_string()),
..Default::default()
}),
..Default::default()
}
}
fn import_memories(
domain_id: &str,
role_id: &str,
memory_kind: &str,
memories: &[GhostlightMemory],
nodes: &mut Vec<EpiphanyMemoryNode>,
) {
for memory in memories {
nodes.push(EpiphanyMemoryNode {
id: memory_graph_node_id(domain_id, memory_kind, memory.memory_id.as_str(), None),
domain_id: domain_id.to_string(),
profile: EpiphanyMemoryProfile::RoleSelf,
kind: EpiphanyMemoryNodeKind::RoleMemory,
title: format!("{role_id} {memory_kind} memory"),
claim: memory.summary.clone(),
question: "How should this memory shape future role judgment?".to_string(),
tension: String::new(),
action_implication: format!("Use as {role_id} role-local memory, not project truth."),
source_hashes: vec!["anchor:missing".to_string()],
lifecycle: EpiphanyMemoryLifecycle::Accepted,
salience: score_to_u32(memory.salience),
confidence: score_to_u32(memory.confidence),
..Default::default()
});
}
}
fn import_goals(
domain_id: &str,
role_id: &str,
goals: &[GhostlightGoal],
nodes: &mut Vec<EpiphanyMemoryNode>,
) {
for goal in goals {
nodes.push(EpiphanyMemoryNode {
id: memory_graph_node_id(domain_id, "goal", goal.goal_id.as_str(), None),
domain_id: domain_id.to_string(),
profile: EpiphanyMemoryProfile::RoleSelf,
kind: EpiphanyMemoryNodeKind::RoleMemory,
title: format!("{role_id} goal"),
claim: goal.description.clone(),
question: "Does this goal still serve the current role?".to_string(),
tension: goal.blockers.join("; "),
action_implication: format!(
"Goal status is {} with scope {}.",
goal.status, goal.scope
),
source_hashes: vec!["anchor:missing".to_string()],
lifecycle: EpiphanyMemoryLifecycle::Accepted,
salience: score_to_u32(goal.priority),
confidence: 80,
..Default::default()
});
}
}
fn import_values(
domain_id: &str,
role_id: &str,
values: &[GhostlightValue],
nodes: &mut Vec<EpiphanyMemoryNode>,
) {
for value in values {
nodes.push(EpiphanyMemoryNode {
id: memory_graph_node_id(domain_id, "value", value.value_id.as_str(), None),
domain_id: domain_id.to_string(),
profile: EpiphanyMemoryProfile::Identity,
kind: EpiphanyMemoryNodeKind::Identity,
title: format!("{role_id} value: {}", value.label),
claim: value.label.clone(),
question: "How should this value constrain future role behavior?".to_string(),
tension: if value.unforgivable_if_betrayed {
"Marked unforgivable if betrayed.".to_string()
} else {
String::new()
},
action_implication: format!("Respect this value when selecting {role_id} context."),
source_hashes: vec!["anchor:missing".to_string()],
lifecycle: EpiphanyMemoryLifecycle::Accepted,
salience: score_to_u32(value.priority),
confidence: 80,
..Default::default()
});
}
}
fn score_to_u32(value: f64) -> u32 {
if value.is_finite() {
(value.clamp(0.0, 1.0) * 100.0).round() as u32
} else {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::agent_memory::GhostlightAgent;
use crate::agent_memory::GhostlightCanonicalState;
use crate::agent_memory::GhostlightMemories;
use crate::agent_memory::GhostlightWorld;
use crate::memory_graph::validate_memory_graph_snapshot;
#[test]
fn agent_profile_imports_reviewed_role_memory_into_valid_graph() {
let entry = EpiphanyAgentMemoryEntry {
schema_version: "ghostlight.agent_state.v0".to_string(),
role_id: "modeling".to_string(),
world: GhostlightWorld::default(),
agent: GhostlightAgent {
memories: GhostlightMemories {
semantic: vec![GhostlightMemory {
memory_id: "mem-1".to_string(),
summary: "Modeling should reject graph updates without source anchors."
.to_string(),
salience: 0.8,
confidence: 0.9,
..Default::default()
}],
..Default::default()
},
goals: vec![GhostlightGoal {
goal_id: "goal-1".to_string(),
description: "Keep architecture maps source-grounded.".to_string(),
scope: "role".to_string(),
priority: 0.7,
emotional_stake: "coherence".to_string(),
status: "active".to_string(),
..Default::default()
}],
canonical_state: GhostlightCanonicalState {
values: vec![GhostlightValue {
value_id: "value-1".to_string(),
label: "Coherence over velocity".to_string(),
priority: 1.0,
unforgivable_if_betrayed: true,
..Default::default()
}],
..Default::default()
},
..Default::default()
},
relationships: Vec::new(),
events: Vec::new(),
scenes: Vec::new(),
};
let snapshot = memory_graph_from_agent_memories("agent-profile", &[entry]);
let errors = validate_memory_graph_snapshot(&snapshot);
assert!(errors.is_empty(), "{errors:?}");
assert_eq!(snapshot.domains.len(), 1);
assert_eq!(snapshot.nodes.len(), 3);
assert_eq!(snapshot.summaries.len(), 1);
assert!(
snapshot
.nodes
.iter()
.any(|node| node.profile == EpiphanyMemoryProfile::Identity)
);
}
}

View file

@ -1,5 +1,3 @@
pub mod agent;
pub mod heartbeat;
pub use agent::memory_graph_from_agent_memories;
pub use heartbeat::memory_graph_from_heartbeat_cognition;

View file

@ -1,8 +1,7 @@
use super::{
EpiphanyMemoryContextPacket, EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot,
SEMANTIC_PROJECTION_SCHEMA_VERSION, SemanticPartition, SemanticProjectionCandidate,
SemanticProjectionDocument, derive_semantic_projection,
plan_memory_graph_context_cut_for_partition, resolve_semantic_candidate,
SEMANTIC_PROJECTION_SCHEMA_VERSION, SemanticProjectionCandidate, SemanticProjectionDocument,
derive_semantic_projection, plan_modeling_context_cut, resolve_semantic_candidate,
};
use crate::semantic_backend::{
CollectionCompatibility, OllamaConfig, OllamaEmbedder, QdrantBackend, QdrantConfig,
@ -24,7 +23,7 @@ pub const MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION: &str =
pub const MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION: &str =
"gamecult.epiphany.memory_semantic_projection_attempt.v1";
const MODELING_COLLECTION_DEFAULT: &str = "epiphany_modeling_v1";
const MIND_COLLECTION_DEFAULT: &str = "epiphany_mind_v1";
const MODELING_PARTITION: &str = "modeling";
const QUERY_LIMIT_MAX: usize = 64;
#[derive(Clone, Debug, PartialEq, Eq)]
@ -37,9 +36,7 @@ pub struct MemorySemanticIndexConfig {
pub ollama_timeout_ms: u64,
pub embedding_provider_id: String,
pub modeling_collection: String,
pub mind_collection: String,
pub modeling_query_instruction: String,
pub mind_query_instruction: String,
}
impl MemorySemanticIndexConfig {
@ -61,27 +58,16 @@ impl MemorySemanticIndexConfig {
"EPIPHANY_MODELING_QDRANT_COLLECTION",
MODELING_COLLECTION_DEFAULT,
),
mind_collection: env_value(
"EPIPHANY_MIND_QDRANT_COLLECTION",
MIND_COLLECTION_DEFAULT,
),
modeling_query_instruction: "Given a repository architecture, dataflow, ownership, invariant, or frontier question, rank the canonical Modeling documents that answer it.".to_string(),
mind_query_instruction: "Given a swarm memory, doctrine, evidence, decision, relationship, or rehydration question, rank the canonical Mind documents that answer it.".to_string(),
}
}
pub(crate) fn collection(&self, partition: SemanticPartition) -> &str {
match partition {
SemanticPartition::Mind => &self.mind_collection,
SemanticPartition::Modeling => &self.modeling_collection,
}
pub(crate) fn collection(&self) -> &str {
&self.modeling_collection
}
fn query_instruction(&self, partition: SemanticPartition) -> &str {
match partition {
SemanticPartition::Mind => &self.mind_query_instruction,
SemanticPartition::Modeling => &self.modeling_query_instruction,
}
fn query_instruction(&self) -> &str {
&self.modeling_query_instruction
}
}
@ -90,7 +76,6 @@ impl MemorySemanticIndexConfig {
pub(super) struct MemorySemanticPointPayload {
point_id: String,
swarm_id: String,
partition: SemanticPartition,
obligation_id: String,
claim_id: String,
claim_epoch: String,
@ -339,7 +324,7 @@ pub fn validate_memory_semantic_projection_obligation(
return Err(anyhow!("semantic projection obligation missing {label}"));
}
}
if !matches!(obligation.partition.as_str(), "mind" | "modeling") {
if obligation.partition != "modeling" {
return Err(anyhow!(
"semantic projection obligation has invalid partition"
));
@ -353,7 +338,6 @@ pub fn validate_memory_semantic_projection_obligation(
pub fn derive_memory_semantic_projection_obligation(
snapshot: &EpiphanyMemoryGraphSnapshot,
swarm_id: &str,
partition: SemanticPartition,
canonical_source_id: &str,
source_commit_id: &str,
created_at: &str,
@ -370,12 +354,9 @@ pub fn derive_memory_semantic_projection_obligation(
}
chrono::DateTime::parse_from_rfc3339(created_at)
.map_err(|_| anyhow!("semantic projection obligation timestamp must be RFC3339"))?;
let documents = derive_semantic_projection(swarm_id, snapshot)?
.into_iter()
.filter(|document| document.partition == partition)
.collect::<Vec<_>>();
let documents = derive_semantic_projection(swarm_id, snapshot)?;
let canonical_content_set_hash = canonical_content_set_hash(&documents);
let partition = partition_name(partition).to_string();
let partition = MODELING_PARTITION.to_string();
let identity = format!("{swarm_id}|{partition}|{canonical_source_id}|{source_commit_id}");
let obligation = MemorySemanticProjectionObligation {
schema_version: MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION.to_string(),
@ -681,17 +662,13 @@ fn authenticate_observed_projection(
pub(super) fn index_memory_semantic_partition(
snapshot: &EpiphanyMemoryGraphSnapshot,
swarm_id: &str,
partition: SemanticPartition,
namespace: &MemorySemanticProjectionNamespace,
indexed_at: &str,
config: &MemorySemanticIndexConfig,
) -> Result<MemorySemanticIndexReceipt> {
let documents = derive_semantic_projection(swarm_id, snapshot)?
.into_iter()
.filter(|document| document.partition == partition)
.collect::<Vec<_>>();
let documents = derive_semantic_projection(swarm_id, snapshot)?;
let backend = qdrant(config)?;
let collection = config.collection(partition);
let collection = config.collection();
if namespace.obligation_id.trim().is_empty()
|| namespace.claim_id.trim().is_empty()
|| namespace.claim_epoch == 0
@ -701,7 +678,7 @@ pub(super) fn index_memory_semantic_partition(
let claim_epoch = namespace.claim_epoch.to_string();
let scope = [
("swarmId", swarm_id),
("partition", partition_name(partition)),
("partition", MODELING_PARTITION),
("obligationId", namespace.obligation_id.as_str()),
("claimId", namespace.claim_id.as_str()),
("claimEpoch", claim_epoch.as_str()),
@ -712,7 +689,7 @@ pub(super) fn index_memory_semantic_partition(
if documents.is_empty() {
let (vector_size, deleted_document_count) = if backend.collection_exists(collection)? {
let actual = backend.collection_compatibility(collection)?;
let expected = compatibility(config, partition, actual.vector_size);
let expected = compatibility(config, actual.vector_size);
if actual != expected {
return Err(anyhow!(
"Qdrant collection {collection} is incompatible: actual {actual:?}, expected {expected:?}"
@ -735,7 +712,6 @@ pub(super) fn index_memory_semantic_partition(
return Ok(memory_semantic_index_receipt(
snapshot,
swarm_id,
partition,
indexed_at,
config,
collection,
@ -749,7 +725,7 @@ pub(super) fn index_memory_semantic_partition(
));
}
let embedder = embedder(config, partition)?;
let embedder = embedder(config)?;
let texts = documents
.iter()
.map(|document| document.projection_text.clone())
@ -759,7 +735,7 @@ pub(super) fn index_memory_semantic_partition(
.first()
.map(Vec::len)
.ok_or_else(|| anyhow!("semantic projection produced no embeddings"))?;
let compatibility = compatibility(config, partition, vector_size);
let compatibility = compatibility(config, vector_size);
if backend.collection_exists(collection)? {
let actual = backend.collection_compatibility(collection)?;
if actual != compatibility {
@ -818,7 +794,6 @@ pub(super) fn index_memory_semantic_partition(
Ok(memory_semantic_index_receipt(
snapshot,
swarm_id,
partition,
indexed_at,
config,
collection,
@ -836,7 +811,6 @@ pub(super) fn index_memory_semantic_partition(
fn memory_semantic_index_receipt(
snapshot: &EpiphanyMemoryGraphSnapshot,
swarm_id: &str,
partition: SemanticPartition,
indexed_at: &str,
config: &MemorySemanticIndexConfig,
collection: &str,
@ -850,7 +824,7 @@ fn memory_semantic_index_receipt(
) -> MemorySemanticIndexReceipt {
let receipt_id = format!(
"memory-semantic-index-{}-{}-{}-{}",
partition_name(partition),
MODELING_PARTITION,
snapshot.model_revision,
&content_set_hash[..16],
&format!(
@ -868,7 +842,7 @@ fn memory_semantic_index_receipt(
schema_version: MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION.to_string(),
receipt_id,
swarm_id: swarm_id.to_string(),
partition: partition_name(partition).to_string(),
partition: MODELING_PARTITION.to_string(),
collection_name: collection.to_string(),
graph_id: snapshot.graph_id.clone(),
model_revision: snapshot.model_revision,
@ -895,19 +869,15 @@ fn memory_semantic_index_receipt(
pub fn semantic_memory_context(
snapshot: &EpiphanyMemoryGraphSnapshot,
swarm_id: &str,
partition: SemanticPartition,
query: &EpiphanyMemoryContextQuery,
readiness: Option<&MemorySemanticProjectionReadiness>,
config: &MemorySemanticIndexConfig,
) -> EpiphanyMemoryContextPacket {
let eligible = readiness.is_some_and(|readiness| {
let source_matches_query = (|| -> Result<bool> {
let documents = derive_semantic_projection(swarm_id, snapshot)?
.into_iter()
.filter(|document| document.partition == partition)
.collect::<Vec<_>>();
let documents = derive_semantic_projection(swarm_id, snapshot)?;
Ok(readiness.obligation.swarm_id == swarm_id
&& readiness.obligation.partition == partition_name(partition)
&& readiness.obligation.partition == MODELING_PARTITION
&& readiness.obligation.graph_id == snapshot.graph_id
&& readiness.obligation.source_generation == snapshot.model_revision
&& readiness.obligation.source_model_hash
@ -924,8 +894,7 @@ pub fn semantic_memory_context(
)
});
if !eligible {
let mut packet =
plan_memory_graph_context_cut_for_partition(snapshot, query, &[], partition);
let mut packet = plan_modeling_context_cut(snapshot, query, &[]);
packet.warnings.push(
"semantic projection unavailable; used canonical BM25 fallback: newest canonical obligation has no exact success receipt"
.to_string(),
@ -933,11 +902,10 @@ pub fn semantic_memory_context(
return packet;
}
let readiness = readiness.expect("eligible semantic readiness disappeared");
match try_semantic_memory_context(snapshot, swarm_id, partition, query, readiness, config) {
match try_semantic_memory_context(snapshot, swarm_id, query, readiness, config) {
Ok(packet) => packet,
Err(error) => {
let mut packet =
plan_memory_graph_context_cut_for_partition(snapshot, query, &[], partition);
let mut packet = plan_modeling_context_cut(snapshot, query, &[]);
packet.warnings.push(format!(
"semantic projection unavailable; used canonical BM25 fallback: {error}"
));
@ -949,7 +917,6 @@ pub fn semantic_memory_context(
fn try_semantic_memory_context(
snapshot: &EpiphanyMemoryGraphSnapshot,
swarm_id: &str,
partition: SemanticPartition,
query: &EpiphanyMemoryContextQuery,
readiness: &MemorySemanticProjectionReadiness,
config: &MemorySemanticIndexConfig,
@ -961,13 +928,13 @@ fn try_semantic_memory_context(
.ok_or_else(|| anyhow!("semantic context requires query text"))?;
let documents = derive_semantic_projection(swarm_id, snapshot)?;
let backend = qdrant(config)?;
let collection = config.collection(partition);
let collection = config.collection();
if !backend.collection_exists(collection)? {
return Err(anyhow!("semantic collection {collection} is missing"));
}
let embedder = embedder(config, partition)?;
let embedder = embedder(config)?;
let vector = embedder.embed_query(text)?;
let expected = compatibility(config, partition, vector.len());
let expected = compatibility(config, vector.len());
let actual = backend.collection_compatibility(collection)?;
if actual != expected {
return Err(anyhow!("semantic collection compatibility mismatch"));
@ -980,7 +947,7 @@ fn try_semantic_memory_context(
limit,
&[
("swarmId", swarm_id),
("partition", partition_name(partition)),
("partition", MODELING_PARTITION),
("obligationId", readiness.receipt.obligation_id.as_str()),
("claimId", readiness.receipt.claim_id.as_str()),
("claimEpoch", query_claim_epoch.as_str()),
@ -992,7 +959,6 @@ fn try_semantic_memory_context(
.payload
.ok_or_else(|| anyhow!("semantic candidate omitted its typed locator payload"))?;
if payload.swarm_id != swarm_id
|| payload.partition != partition
|| payload.obligation_id != readiness.receipt.obligation_id
|| payload.claim_id != readiness.receipt.claim_id
|| payload.claim_epoch != readiness.receipt.claim_epoch.to_string()
@ -1010,22 +976,20 @@ fn try_semantic_memory_context(
canonical_key: payload.canonical_key,
canonical_document_id: payload.canonical_document_id,
},
partition: payload.partition,
score: hit.score,
indexed_model_revision: payload.indexed_model_revision,
indexed_model_hash: payload.indexed_model_hash,
indexed_canonical_content_hash: payload.indexed_canonical_content_hash,
};
if let Ok(document) = resolve_semantic_candidate(partition, &candidate, &documents) {
if let Ok(document) = resolve_semantic_candidate(&candidate, &documents) {
ranked_ids.push(document.canonical.canonical_document_id.clone());
}
}
let mut packet =
plan_memory_graph_context_cut_for_partition(snapshot, query, &ranked_ids, partition);
let mut packet = plan_modeling_context_cut(snapshot, query, &ranked_ids);
packet.warnings.push(format!(
"semantic projection ranked {} canonical {} candidates; all payload text was ignored",
ranked_ids.len(),
partition_name(partition)
MODELING_PARTITION
));
Ok(packet)
}
@ -1038,7 +1002,6 @@ pub(super) fn point_payload(
MemorySemanticPointPayload {
point_id: document.point_id.clone(),
swarm_id: document.swarm_id.clone(),
partition: document.partition,
obligation_id: namespace.obligation_id.clone(),
claim_id: namespace.claim_id.clone(),
claim_epoch: namespace.claim_epoch.to_string(),
@ -1123,18 +1086,12 @@ fn observe_memory_semantic_live_evidence_with(
{
return Ok(None);
}
let partition = match input.obligation.partition.as_str() {
"mind" => SemanticPartition::Mind,
"modeling" => SemanticPartition::Modeling,
_ => return Ok(None),
};
if readiness.receipt.collection_name != config.collection(partition) {
if input.obligation.partition != MODELING_PARTITION
|| readiness.receipt.collection_name != config.collection()
{
return Ok(None);
}
let documents = derive_semantic_projection(&input.obligation.swarm_id, &input.snapshot)?
.into_iter()
.filter(|document| document.partition == partition)
.collect::<Vec<_>>();
let documents = derive_semantic_projection(&input.obligation.swarm_id, &input.snapshot)?;
if documents.len() as u32 != readiness.receipt.indexed_document_count
|| canonical_content_set_hash(&documents) != readiness.receipt.canonical_content_set_hash
|| readiness.receipt.embedding_provider_id != config.embedding_provider_id
@ -1149,11 +1106,7 @@ fn observe_memory_semantic_live_evidence_with(
let collection = readiness.receipt.collection_name.as_str();
if !port.collection_exists(collection)?
|| port.collection_compatibility(collection)?
!= compatibility(
config,
partition,
readiness.receipt.vector_dimensions as usize,
)
!= compatibility(config, readiness.receipt.vector_dimensions as usize)
{
return Ok(None);
}
@ -1221,26 +1174,22 @@ fn semantic_authority_still_exact(
}))
}
fn embedder(
config: &MemorySemanticIndexConfig,
partition: SemanticPartition,
) -> Result<OllamaEmbedder> {
fn embedder(config: &MemorySemanticIndexConfig) -> Result<OllamaEmbedder> {
OllamaEmbedder::new(OllamaConfig {
base_url: config.ollama_base_url.clone(),
model: config.ollama_model.clone(),
timeout_ms: config.ollama_timeout_ms,
query_instruction: config.query_instruction(partition).to_string(),
query_instruction: config.query_instruction().to_string(),
})
}
fn compatibility(
config: &MemorySemanticIndexConfig,
partition: SemanticPartition,
vector_size: usize,
) -> CollectionCompatibility {
CollectionCompatibility {
managed_by: "epiphany".to_string(),
corpus_kind: partition_name(partition).to_string(),
corpus_kind: MODELING_PARTITION.to_string(),
schema_version: 1,
projection_version: SEMANTIC_PROJECTION_SCHEMA_VERSION.to_string(),
embedding_provider_id: config.embedding_provider_id.clone(),
@ -1249,13 +1198,6 @@ fn compatibility(
}
}
fn partition_name(partition: SemanticPartition) -> &'static str {
match partition {
SemanticPartition::Mind => "mind",
SemanticPartition::Modeling => "modeling",
}
}
fn canonical_content_set_hash(documents: &[SemanticProjectionDocument]) -> String {
let mut values = documents
.iter()
@ -1353,7 +1295,6 @@ mod tests {
let obligation = derive_memory_semantic_projection_obligation(
&empty,
"swarm-empty",
SemanticPartition::Modeling,
"source-empty",
"commit-empty",
"2026-07-15T11:59:00Z",
@ -1362,7 +1303,6 @@ mod tests {
let receipt = index_memory_semantic_partition(
&empty,
"swarm-empty",
SemanticPartition::Modeling,
&MemorySemanticProjectionNamespace {
obligation_id: obligation.obligation_id.clone(),
claim_id: "claim-empty".to_string(),
@ -1406,7 +1346,6 @@ mod tests {
let first = derive_memory_semantic_projection_obligation(
&snapshot,
"swarm-a",
SemanticPartition::Modeling,
"epiphany.runtime/runtime-a/repo-model",
"repo-model-admission-1",
"2026-07-15T00:00:00Z",
@ -1415,7 +1354,6 @@ mod tests {
derive_memory_semantic_projection_obligation(
&snapshot,
"swarm-a",
SemanticPartition::Modeling,
"epiphany.runtime/runtime-a/repo-model",
"repo-model-admission-1",
"2026-07-15T00:00:00Z",
@ -1425,7 +1363,6 @@ mod tests {
let second = derive_memory_semantic_projection_obligation(
&snapshot,
"swarm-a",
SemanticPartition::Modeling,
"epiphany.runtime/runtime-a/repo-model",
"repo-model-admission-2",
"2026-07-15T00:00:01Z",
@ -1443,23 +1380,11 @@ mod tests {
text: Some("canonical qdrant semantic".to_string()),
..Default::default()
};
let expected = plan_memory_graph_context_cut_for_partition(
&snapshot,
&query,
&[],
SemanticPartition::Modeling,
);
let expected = plan_modeling_context_cut(&snapshot, &query, &[]);
let mut config = MemorySemanticIndexConfig::from_env();
config.qdrant_url = "http://127.0.0.1:1".to_string();
config.qdrant_timeout_ms = 25;
let actual = semantic_memory_context(
&snapshot,
"swarm",
SemanticPartition::Modeling,
&query,
None,
&config,
);
let actual = semantic_memory_context(&snapshot, "swarm", &query, None, &config);
assert_eq!(actual.nodes, expected.nodes);
assert_eq!(actual.edges, expected.edges);
assert_eq!(actual.summaries, expected.summaries);
@ -1477,7 +1402,6 @@ mod tests {
let obligation = derive_memory_semantic_projection_obligation(
&snapshot,
"swarm-a",
SemanticPartition::Modeling,
"runtime/repo-model",
"admission-current",
"2026-07-15T10:00:00Z",
@ -1531,33 +1455,14 @@ mod tests {
current: current.clone(),
receipt: receipt.clone(),
};
let packet = semantic_memory_context(
&snapshot,
"swarm-b",
SemanticPartition::Modeling,
&query,
Some(&readiness),
&config,
);
let packet =
semantic_memory_context(&snapshot, "swarm-b", &query, Some(&readiness), &config);
assert!(packet.warnings.iter().any(|warning| {
warning.contains("newest canonical obligation has no exact success receipt")
}));
Ok(())
}
#[test]
fn mind_and_modeling_have_distinct_physical_collections_and_query_profiles() {
let config = MemorySemanticIndexConfig::from_env();
assert_ne!(
config.collection(SemanticPartition::Mind),
config.collection(SemanticPartition::Modeling)
);
assert_ne!(
config.query_instruction(SemanticPartition::Mind),
config.query_instruction(SemanticPartition::Modeling)
);
}
#[test]
fn physical_point_identity_is_claim_epoch_isolated_while_locator_stays_canonical() {
let document = derive_semantic_projection("swarm-a", &snapshot())
@ -1856,7 +1761,6 @@ mod tests {
MemorySemanticPointPayload {
point_id: id.to_string(),
swarm_id: "swarm-a".to_string(),
partition: SemanticPartition::Modeling,
obligation_id: "obligation-a".to_string(),
claim_id: "claim-a".to_string(),
claim_epoch: "1".to_string(),

View file

@ -11,13 +11,6 @@ use uuid::Uuid;
pub const SEMANTIC_PROJECTION_SCHEMA_VERSION: &str = "gamecult.epiphany.semantic_projection.v0";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticPartition {
Mind,
Modeling,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticDocumentKind {
@ -53,7 +46,6 @@ pub struct SemanticCanonicalLocator {
pub struct SemanticProjectionDocument {
pub point_id: String,
pub swarm_id: String,
pub partition: SemanticPartition,
pub kind: SemanticDocumentKind,
pub canonical: SemanticCanonicalLocator,
pub graph_id: String,
@ -75,48 +67,21 @@ pub struct SemanticProjectionDocument {
pub struct SemanticProjectionCandidate {
pub point_id: String,
pub canonical: SemanticCanonicalLocator,
pub partition: SemanticPartition,
pub score: f32,
pub indexed_model_revision: u64,
pub indexed_model_hash: String,
pub indexed_canonical_content_hash: String,
}
pub trait SemanticEmbedder {
fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>>;
}
pub trait SemanticVectorIndex {
fn replace_partition(
&self,
swarm_id: &str,
partition: SemanticPartition,
documents: &[(SemanticProjectionDocument, Vec<f32>)],
) -> Result<()>;
fn search(
&self,
swarm_id: &str,
partition: SemanticPartition,
vector: &[f32],
limit: usize,
) -> Result<Vec<SemanticProjectionCandidate>>;
}
pub fn semantic_point_id(
swarm_id: &str,
partition: SemanticPartition,
canonical_type: &str,
canonical_key: &str,
canonical_document_id: &str,
) -> String {
let partition = match partition {
SemanticPartition::Mind => "mind",
SemanticPartition::Modeling => "modeling",
};
Uuid::new_v5(
&Uuid::NAMESPACE_URL,
format!("{swarm_id}|{partition}|{canonical_type}|{canonical_key}|{canonical_document_id}")
format!("{swarm_id}|modeling|{canonical_type}|{canonical_key}|{canonical_document_id}")
.as_bytes(),
)
.to_string()
@ -189,14 +154,16 @@ pub fn derive_semantic_projection(
let mut out = Vec::new();
for node in &snapshot.nodes {
if excluded_lifecycle(node.lifecycle) || stale_nodes.contains(node.id.as_str()) {
if !is_modeling_profile(node.profile)
|| excluded_lifecycle(node.lifecycle)
|| stale_nodes.contains(node.id.as_str())
{
continue;
}
let domain = required_domain(&domains, &node.domain_id)?;
out.push(document(
swarm_id,
snapshot,
partition(node.profile),
SemanticDocumentKind::Node,
&node.id,
domain,
@ -219,7 +186,10 @@ pub fn derive_semantic_projection(
}
for edge in &snapshot.edges {
if excluded_lifecycle(edge.lifecycle) || stale_edges.contains(edge.id.as_str()) {
if !is_modeling_profile(edge.profile)
|| excluded_lifecycle(edge.lifecycle)
|| stale_edges.contains(edge.id.as_str())
{
continue;
}
let source = nodes
@ -230,6 +200,8 @@ pub fn derive_semantic_projection(
.ok_or_else(|| anyhow!("validated edge lost target"))?;
if excluded_lifecycle(source.lifecycle)
|| excluded_lifecycle(target.lifecycle)
|| !is_modeling_profile(source.profile)
|| !is_modeling_profile(target.profile)
|| stale_nodes.contains(source.id.as_str())
|| stale_nodes.contains(target.id.as_str())
{
@ -244,7 +216,6 @@ pub fn derive_semantic_projection(
out.push(document(
swarm_id,
snapshot,
partition(edge.profile),
SemanticDocumentKind::Edge,
&edge.id,
domain,
@ -261,18 +232,18 @@ pub fn derive_semantic_projection(
}
for summary in &snapshot.summaries {
if summary.freshness != EpiphanyMemoryFreshnessStatus::Ready
let domain = required_domain(&domains, &summary.domain_id)?;
if !is_modeling_profile(domain.profile)
|| summary.freshness != EpiphanyMemoryFreshnessStatus::Ready
|| summary.confidence < 70
|| !summary.known_omissions.is_empty()
|| stale_summaries.contains(summary.id.as_str())
{
continue;
}
let domain = required_domain(&domains, &summary.domain_id)?;
out.push(document(
swarm_id,
snapshot,
partition(domain.profile),
SemanticDocumentKind::Summary,
&summary.id,
domain,
@ -313,7 +284,6 @@ pub fn derive_semantic_projection(
out.push(document(
swarm_id,
snapshot,
SemanticPartition::Modeling,
SemanticDocumentKind::Frontier,
&item.id,
domain,
@ -340,19 +310,14 @@ pub fn derive_semantic_projection(
}
pub fn resolve_semantic_candidate<'a>(
expected_partition: SemanticPartition,
candidate: &SemanticProjectionCandidate,
current_documents: &'a [SemanticProjectionDocument],
) -> Result<&'a SemanticProjectionDocument> {
if candidate.partition != expected_partition {
return Err(anyhow!("semantic candidate partition mismatch"));
}
let document = current_documents
.iter()
.find(|document| document.point_id == candidate.point_id)
.ok_or_else(|| anyhow!("semantic candidate is missing or no longer live"))?;
if document.partition != candidate.partition
|| document.canonical != candidate.canonical
if document.canonical != candidate.canonical
|| document.model_revision != candidate.indexed_model_revision
|| document.model_hash != candidate.indexed_model_hash
|| document.canonical_content_hash != candidate.indexed_canonical_content_hash
@ -367,7 +332,6 @@ pub fn resolve_semantic_candidate<'a>(
fn document<T: Serialize>(
swarm_id: &str,
snapshot: &EpiphanyMemoryGraphSnapshot,
partition: SemanticPartition,
kind: SemanticDocumentKind,
document_id: &str,
domain: &EpiphanyMemoryDomain,
@ -395,15 +359,8 @@ fn document<T: Serialize>(
canonical_document_id: document_id.to_string(),
};
Ok(SemanticProjectionDocument {
point_id: semantic_point_id(
swarm_id,
partition,
canonical_type,
document_id,
document_id,
),
point_id: semantic_point_id(swarm_id, canonical_type, document_id, document_id),
swarm_id: swarm_id.to_string(),
partition,
kind,
canonical,
graph_id: snapshot.graph_id.clone(),
@ -428,13 +385,11 @@ fn document<T: Serialize>(
})
}
fn partition(profile: EpiphanyMemoryProfile) -> SemanticPartition {
match profile {
EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow => {
SemanticPartition::Modeling
}
_ => SemanticPartition::Mind,
}
fn is_modeling_profile(profile: EpiphanyMemoryProfile) -> bool {
matches!(
profile,
EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow
)
}
fn excluded_lifecycle(lifecycle: EpiphanyMemoryLifecycle) -> bool {
@ -575,22 +530,13 @@ mod tests {
}
#[test]
fn derives_typed_partitions_and_filters_non_live_documents() {
fn derives_only_live_modeling_documents() {
let documents = derive_semantic_projection("swarm-a", &snapshot()).unwrap();
assert_eq!(documents.len(), 5);
assert_eq!(documents.len(), 2);
assert!(
documents
.iter()
.any(
|document| document.canonical.canonical_document_id == "mind-node"
&& document.partition == SemanticPartition::Mind
)
);
assert!(
documents
.iter()
.any(|document| document.kind == SemanticDocumentKind::Frontier
&& document.partition == SemanticPartition::Modeling)
.any(|document| document.kind == SemanticDocumentKind::Frontier)
);
assert!(
!documents
@ -615,45 +561,30 @@ mod tests {
let candidate = SemanticProjectionCandidate {
point_id: document.point_id.clone(),
canonical: document.canonical.clone(),
partition: document.partition,
score: 0.9,
indexed_model_revision: document.model_revision,
indexed_model_hash: document.model_hash.clone(),
indexed_canonical_content_hash: document.canonical_content_hash.clone(),
};
assert_eq!(
resolve_semantic_candidate(SemanticPartition::Modeling, &candidate, &documents)
resolve_semantic_candidate(&candidate, &documents)
.unwrap()
.point_id,
document.point_id
);
let mut stale = candidate.clone();
stale.indexed_canonical_content_hash = "stale".into();
assert!(
resolve_semantic_candidate(SemanticPartition::Modeling, &stale, &documents).is_err()
);
assert!(
resolve_semantic_candidate(SemanticPartition::Mind, &candidate, &documents).is_err()
);
assert!(resolve_semantic_candidate(&stale, &documents).is_err());
let mut stale_revision = candidate.clone();
stale_revision.indexed_model_revision -= 1;
assert!(
resolve_semantic_candidate(SemanticPartition::Modeling, &stale_revision, &documents)
.is_err()
);
assert!(resolve_semantic_candidate(&stale_revision, &documents).is_err());
let mut stale_model = candidate.clone();
stale_model.indexed_model_hash = "old-model".into();
assert!(
resolve_semantic_candidate(SemanticPartition::Modeling, &stale_model, &documents)
.is_err()
);
assert!(resolve_semantic_candidate(&stale_model, &documents).is_err());
let mut wrong_locator = candidate.clone();
wrong_locator.canonical.canonical_document_id = "other".into();
assert!(
resolve_semantic_candidate(SemanticPartition::Modeling, &wrong_locator, &documents)
.is_err()
);
assert!(resolve_semantic_candidate(SemanticPartition::Modeling, &candidate, &[]).is_err());
assert!(resolve_semantic_candidate(&wrong_locator, &documents).is_err());
assert!(resolve_semantic_candidate(&candidate, &[]).is_err());
}
#[test]
@ -710,7 +641,7 @@ mod tests {
}
#[test]
fn hostile_composed_graph_cannot_cross_partition_or_domain_through_any_cut_path() {
fn modeling_cut_cannot_cross_domain_through_ranked_ids() {
let mut snapshot = snapshot();
snapshot.frontier.push(RepoFrontierItem {
id: "mind-frontier".into(),
@ -721,7 +652,7 @@ mod tests {
status: RepoFrontierStatus::Active,
..Default::default()
});
let modeling = crate::memory_graph::plan_memory_graph_context_cut_for_partition(
let modeling = crate::memory_graph::plan_modeling_context_cut(
&snapshot,
&crate::memory_graph::EpiphanyMemoryContextQuery {
id: "hostile-modeling".into(),
@ -733,7 +664,6 @@ mod tests {
..Default::default()
},
&["mind-node".into(), "edge".into(), "summary".into()],
SemanticPartition::Modeling,
);
assert!(modeling.nodes.iter().all(|node| {
node.domain_id == "repo"
@ -752,29 +682,5 @@ mod tests {
.collect::<Vec<_>>(),
vec!["frontier"]
);
let mind = crate::memory_graph::plan_memory_graph_context_cut_for_partition(
&snapshot,
&crate::memory_graph::EpiphanyMemoryContextQuery {
id: "hostile-mind".into(),
domain_ids: vec!["mind".into()],
node_ids: vec!["repo-node".into()],
edge_ids: vec!["edge".into()],
text: Some("owns map".into()),
budget: Some(64),
..Default::default()
},
&["repo-node".into(), "edge".into(), "frontier".into()],
SemanticPartition::Mind,
);
assert!(mind.nodes.iter().all(|node| {
node.domain_id == "mind"
&& !matches!(
node.profile,
EpiphanyMemoryProfile::RepoArchitecture | EpiphanyMemoryProfile::RepoDataflow
)
}));
assert!(mind.edges.is_empty());
assert!(mind.frontier.is_empty());
}
}

View file

@ -11,7 +11,6 @@ use cultcache_rs::{
SingleFileMessagePackBackingStore,
};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
@ -138,233 +137,6 @@ pub struct MemorySemanticPhysicalRetirementReceipt {
pub private_state_exposed: bool,
}
#[derive(Deserialize, Serialize)]
struct LegacyMemorySemanticProjectionAttemptV0 {
schema_version: String,
attempt_id: String,
obligation_id: String,
started_at: String,
completed_at: Option<String>,
status: String,
error: Option<String>,
}
#[derive(Deserialize, Serialize)]
struct LegacyMemorySemanticProjectionClaimV0 {
schema_version: String,
scope_id: String,
claim_id: String,
obligation_id: String,
attempt_id: String,
executor_id: String,
epoch: u64,
status: String,
claimed_at: String,
completed_at: Option<String>,
}
/// Retires pre-Idunn claim/attempt pairs from active authority. Their old
/// receipts remain historical and query-ineligible; current obligations can
/// then receive fresh fenced work.
pub fn retire_memory_semantic_projection_claims_v0(
store_path: impl AsRef<Path>,
) -> Result<Vec<String>> {
const ATTEMPT_TYPE: &str = "gamecult.epiphany.memory_semantic_projection_attempt";
const CLAIM_TYPE: &str = "gamecult.epiphany.memory_semantic_projection_claim";
let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref());
let opening = backing.pull_all()?;
let mut retired = Vec::new();
for claim_envelope in opening.iter().filter(|entry| entry.r#type == CLAIM_TYPE) {
if rmp_serde::from_slice::<MemorySemanticProjectionClaim>(&claim_envelope.payload).is_ok() {
continue;
}
let claim = rmp_serde::from_slice::<LegacyMemorySemanticProjectionClaimV0>(
&claim_envelope.payload,
)?;
if claim.schema_version != "gamecult.epiphany.memory_semantic_projection_claim.v0" {
return Err(anyhow!(
"unsupported legacy semantic claim schema for {:?}",
claim.claim_id
));
}
let attempt_envelope = opening
.iter()
.find(|entry| entry.r#type == ATTEMPT_TYPE && entry.key == claim.attempt_id)
.ok_or_else(|| {
anyhow!(
"legacy semantic claim {:?} has no exact attempt",
claim.claim_id
)
})?;
let attempt = rmp_serde::from_slice::<LegacyMemorySemanticProjectionAttemptV0>(
&attempt_envelope.payload,
)?;
if attempt.attempt_id != claim.attempt_id || attempt.obligation_id != claim.obligation_id {
return Err(anyhow!("legacy semantic claim/attempt pair disagrees"));
}
if !backing
.delete_batch_if_unchanged(&[claim_envelope.clone(), attempt_envelope.clone()])?
{
return Err(anyhow!(
"legacy semantic authority changed during explicit retirement"
));
}
retired.push(claim.claim_id);
}
Ok(retired)
}
/// Retires historical v0 attempts whose scope claim was already superseded or
/// overwritten before fenced claim history existed.
pub fn retire_orphaned_memory_semantic_projection_attempts_v0(
store_path: impl AsRef<Path>,
) -> Result<Vec<String>> {
const ATTEMPT_TYPE: &str = "gamecult.epiphany.memory_semantic_projection_attempt";
const CLAIM_TYPE: &str = "gamecult.epiphany.memory_semantic_projection_claim";
let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref());
let opening = backing.pull_all()?;
let current_claim_attempt_ids = opening
.iter()
.filter(|entry| entry.r#type == CLAIM_TYPE)
.filter_map(|entry| {
rmp_serde::from_slice::<MemorySemanticProjectionClaim>(&entry.payload)
.ok()
.map(|claim| claim.attempt_id)
})
.collect::<std::collections::BTreeSet<_>>();
let mut retired = Vec::new();
for attempt_envelope in opening.iter().filter(|entry| entry.r#type == ATTEMPT_TYPE) {
if rmp_serde::from_slice::<MemorySemanticProjectionAttempt>(&attempt_envelope.payload)
.is_ok()
{
continue;
}
let attempt = rmp_serde::from_slice::<LegacyMemorySemanticProjectionAttemptV0>(
&attempt_envelope.payload,
)?;
if attempt.schema_version != "gamecult.epiphany.memory_semantic_projection_attempt.v0" {
return Err(anyhow!(
"unsupported orphaned semantic attempt schema for {:?}",
attempt.attempt_id
));
}
if current_claim_attempt_ids.contains(&attempt.attempt_id) {
continue;
}
if !backing.delete_batch_if_unchanged(std::slice::from_ref(attempt_envelope))? {
return Err(anyhow!(
"orphaned semantic attempt changed during explicit retirement"
));
}
retired.push(attempt.attempt_id);
}
Ok(retired)
}
/// Retires index receipts whose physical claim namespace is absent from the
/// canonical store. Their Qdrant points are rebuildable cache residue.
pub fn retire_unowned_memory_semantic_index_receipts(
store_path: impl AsRef<Path>,
) -> Result<Vec<String>> {
const RECEIPT_TYPE: &str = "gamecult.epiphany.memory_semantic_index_receipt";
const CLAIM_TYPE: &str = "gamecult.epiphany.memory_semantic_projection_claim";
let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref());
let opening = backing.pull_all()?;
let claim_ids = opening
.iter()
.filter(|entry| entry.r#type == CLAIM_TYPE)
.filter_map(|entry| {
rmp_serde::from_slice::<MemorySemanticProjectionClaim>(&entry.payload)
.ok()
.map(|claim| claim.claim_id)
})
.collect::<std::collections::BTreeSet<_>>();
let mut retired = Vec::new();
for envelope in opening.iter().filter(|entry| entry.r#type == RECEIPT_TYPE) {
let receipt = rmp_serde::from_slice::<MemorySemanticIndexReceipt>(&envelope.payload)?;
if !receipt.claim_id.trim().is_empty()
&& receipt.claim_epoch > 0
&& claim_ids.contains(&receipt.claim_id)
{
continue;
}
if !backing.delete_batch_if_unchanged(std::slice::from_ref(envelope))? {
return Err(anyhow!(
"unowned semantic index receipt changed during explicit retirement"
));
}
retired.push(receipt.receipt_id);
}
Ok(retired)
}
/// Upgrades v0 attempt rows by binding them to the exact persisted claim that
/// already owns their attempt identity. No claim means no migration.
pub fn migrate_memory_semantic_projection_attempts_v0(
store_path: impl AsRef<Path>,
) -> Result<Vec<String>> {
const ATTEMPT_TYPE: &str = "gamecult.epiphany.memory_semantic_projection_attempt";
const CLAIM_TYPE: &str = "gamecult.epiphany.memory_semantic_projection_claim";
let backing = SingleFileMessagePackBackingStore::new(store_path.as_ref());
let opening = backing.pull_all()?;
let claims = opening
.iter()
.filter(|entry| entry.r#type == CLAIM_TYPE)
.map(|entry| rmp_serde::from_slice::<MemorySemanticProjectionClaim>(&entry.payload))
.collect::<std::result::Result<Vec<_>, _>>()?;
let mut migrated = Vec::new();
for envelope in opening.iter().filter(|entry| entry.r#type == ATTEMPT_TYPE) {
if rmp_serde::from_slice::<MemorySemanticProjectionAttempt>(&envelope.payload).is_ok() {
continue;
}
let legacy =
rmp_serde::from_slice::<LegacyMemorySemanticProjectionAttemptV0>(&envelope.payload)?;
if legacy.schema_version != "gamecult.epiphany.memory_semantic_projection_attempt.v0" {
return Err(anyhow!(
"unsupported legacy semantic attempt schema for {:?}",
legacy.attempt_id
));
}
let claim = claims
.iter()
.find(|claim| {
claim.attempt_id == legacy.attempt_id && claim.obligation_id == legacy.obligation_id
})
.ok_or_else(|| {
anyhow!(
"legacy semantic attempt {:?} has no exact owning claim",
legacy.attempt_id
)
})?;
let upgraded = MemorySemanticProjectionAttempt {
schema_version: MEMORY_SEMANTIC_PROJECTION_ATTEMPT_SCHEMA_VERSION.to_string(),
attempt_id: legacy.attempt_id,
obligation_id: legacy.obligation_id,
started_at: legacy.started_at,
completed_at: legacy.completed_at,
status: legacy.status,
error: legacy.error,
claim_id: claim.claim_id.clone(),
claim_epoch: claim.epoch,
executor_id: claim.executor_id.clone(),
executor_incarnation: claim.executor_incarnation.clone(),
authority_id: claim.authority_id.clone(),
physical_backend_url: String::new(),
collection_name: String::new(),
};
validate_memory_semantic_projection_attempt(&upgraded)?;
let mut replacement: CultCacheEnvelope = envelope.clone();
replacement.payload = rmp_serde::to_vec_named(&upgraded)?;
if !backing.compare_and_swap_entry(envelope, replacement)? {
return Err(anyhow!(
"semantic attempt changed during explicit migration"
));
}
migrated.push(upgraded.attempt_id);
}
Ok(migrated)
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(
type = "gamecult.epiphany.memory_semantic_projector_executor_grant",
@ -700,164 +472,6 @@ mod authority_tests {
Ok(())
}
#[test]
fn legacy_attempt_migration_binds_exact_owning_claim() -> Result<()> {
let temp = tempdir()?;
let store = temp.path().join("legacy-attempt.msgpack");
let obligation = obligation();
let mut cache = semantic_projector_cache(&store)?;
cache.put(&obligation.obligation_id, &obligation)?;
let projection_input = input(&store, &obligation)?;
let acquisition = idunn_acquire_memory_semantic_projection(
&store,
&projection_input,
"executor-a",
"executor-a-incarnation",
"execute",
"idunn-incarnation-a",
"2026-07-15T04:01:00Z",
)?;
let backing = SingleFileMessagePackBackingStore::new(&store);
let opening = backing.pull_all()?;
let attempt_envelope = opening
.iter()
.find(|entry| {
entry.r#type == MemorySemanticProjectionAttempt::TYPE
&& entry.key == acquisition.claim.attempt_id
})
.context("attempt missing")?;
let attempt: MemorySemanticProjectionAttempt =
rmp_serde::from_slice(&attempt_envelope.payload)?;
let legacy = LegacyMemorySemanticProjectionAttemptV0 {
schema_version: "gamecult.epiphany.memory_semantic_projection_attempt.v0".into(),
attempt_id: attempt.attempt_id.clone(),
obligation_id: attempt.obligation_id.clone(),
started_at: attempt.started_at,
completed_at: attempt.completed_at,
status: attempt.status,
error: attempt.error,
};
let mut legacy_envelope = attempt_envelope.clone();
legacy_envelope.payload = rmp_serde::to_vec_named(&legacy)?;
assert!(backing.compare_and_swap_entry(attempt_envelope, legacy_envelope)?);
assert_eq!(
migrate_memory_semantic_projection_attempts_v0(&store)?,
vec![attempt.attempt_id.clone()]
);
let (_, _, _, upgraded) = load_running_claim(&store, &acquisition.claim.claim_id)?;
assert_eq!(upgraded.claim_id, acquisition.claim.claim_id);
assert_eq!(upgraded.claim_epoch, acquisition.claim.epoch);
assert_eq!(upgraded.executor_id, acquisition.claim.executor_id);
assert_eq!(
upgraded.executor_incarnation,
acquisition.claim.executor_incarnation
);
assert_eq!(upgraded.authority_id, acquisition.claim.authority_id);
assert!(migrate_memory_semantic_projection_attempts_v0(&store)?.is_empty());
Ok(())
}
#[test]
fn legacy_unfenced_claim_and_attempt_retire_atomically() -> Result<()> {
let temp = tempdir()?;
let store = temp.path().join("legacy-claim.msgpack");
let obligation = obligation();
let mut cache = semantic_projector_cache(&store)?;
cache.put(&obligation.obligation_id, &obligation)?;
let projection_input = input(&store, &obligation)?;
let acquisition = idunn_acquire_memory_semantic_projection(
&store,
&projection_input,
"executor-a",
"executor-a-incarnation",
"execute",
"idunn-incarnation-a",
"2026-07-15T04:01:00Z",
)?;
let backing = SingleFileMessagePackBackingStore::new(&store);
let opening = backing.pull_all()?;
let claim_envelope = exact_envelope(
&opening,
MemorySemanticProjectionClaim::TYPE,
&acquisition.claim.scope_id,
)?;
let attempt_envelope = exact_envelope(
&opening,
MemorySemanticProjectionAttempt::TYPE,
&acquisition.claim.attempt_id,
)?;
let legacy_claim = LegacyMemorySemanticProjectionClaimV0 {
schema_version: "gamecult.epiphany.memory_semantic_projection_claim.v0".into(),
scope_id: acquisition.claim.scope_id.clone(),
claim_id: acquisition.claim.claim_id.clone(),
obligation_id: acquisition.claim.obligation_id.clone(),
attempt_id: acquisition.claim.attempt_id.clone(),
executor_id: acquisition.claim.executor_id.clone(),
epoch: acquisition.claim.epoch,
status: acquisition.claim.status.clone(),
claimed_at: acquisition.claim.claimed_at.clone(),
completed_at: acquisition.claim.completed_at.clone(),
};
let attempt: MemorySemanticProjectionAttempt =
rmp_serde::from_slice(&attempt_envelope.payload)?;
let legacy_attempt = LegacyMemorySemanticProjectionAttemptV0 {
schema_version: "gamecult.epiphany.memory_semantic_projection_attempt.v0".into(),
attempt_id: attempt.attempt_id,
obligation_id: attempt.obligation_id,
started_at: attempt.started_at,
completed_at: attempt.completed_at,
status: attempt.status,
error: attempt.error,
};
let mut legacy_claim_envelope = claim_envelope.clone();
legacy_claim_envelope.payload = rmp_serde::to_vec_named(&legacy_claim)?;
let mut legacy_attempt_envelope = attempt_envelope.clone();
legacy_attempt_envelope.payload = rmp_serde::to_vec_named(&legacy_attempt)?;
assert!(backing.compare_and_swap_batch(
&[claim_envelope, attempt_envelope],
vec![legacy_claim_envelope, legacy_attempt_envelope],
)?);
assert_eq!(
retire_memory_semantic_projection_claims_v0(&store)?,
vec![acquisition.claim.claim_id]
);
let observation = observe_memory_semantic_projection(&store, &projection_input)?;
assert_eq!(observation.status, "pending");
assert!(retire_memory_semantic_projection_claims_v0(&store)?.is_empty());
Ok(())
}
#[test]
fn orphaned_legacy_attempt_retires_without_fabricated_claim() -> Result<()> {
let temp = tempdir()?;
let store = temp.path().join("orphaned-attempt.msgpack");
let legacy = LegacyMemorySemanticProjectionAttemptV0 {
schema_version: "gamecult.epiphany.memory_semantic_projection_attempt.v0".into(),
attempt_id: "orphaned-attempt-1".into(),
obligation_id: "obligation-modeling-7".into(),
started_at: "2026-07-15T04:01:00Z".into(),
completed_at: Some("2026-07-15T04:02:00Z".into()),
status: "succeeded".into(),
error: None,
};
let mut backing = SingleFileMessagePackBackingStore::new(&store);
backing.push(&CultCacheEnvelope {
key: legacy.attempt_id.clone(),
r#type: MemorySemanticProjectionAttempt::TYPE.into(),
payload: rmp_serde::to_vec_named(&legacy)?,
stored_at: "2026-07-15T04:02:00Z".into(),
schema_id: Some(MemorySemanticProjectionAttempt::TYPE.into()),
})?;
assert_eq!(
retire_orphaned_memory_semantic_projection_attempts_v0(&store)?,
vec![legacy.attempt_id]
);
assert!(backing.pull_all()?.is_empty());
Ok(())
}
#[test]
fn concurrent_idunn_acquisition_has_one_winner_and_no_issued_litter() -> Result<()> {
let temp = tempdir()?;
@ -1454,7 +1068,7 @@ pub fn observe_memory_semantic_projection(
}
pub(crate) fn projection_scope_id(swarm_id: &str, partition: &str) -> Result<String> {
if swarm_id.trim().is_empty() || !matches!(partition, "mind" | "modeling") {
if swarm_id.trim().is_empty() || partition != "modeling" {
return Err(anyhow!("semantic projection scope identity is invalid"));
}
Ok(format!(
@ -1763,19 +1377,13 @@ pub(crate) fn idunn_acquire_memory_semantic_projection_with_config(
epoch,
acquired_at,
);
let partition = match obligation.partition.as_str() {
"mind" => super::SemanticPartition::Mind,
"modeling" => super::SemanticPartition::Modeling,
_ => {
return Err(anyhow!(
"semantic projection obligation partition is invalid"
));
}
};
if config.qdrant_url.trim().is_empty() || config.collection(partition).trim().is_empty() {
if obligation.partition != "modeling"
|| config.qdrant_url.trim().is_empty()
|| config.collection().trim().is_empty()
{
return Err(anyhow!("semantic projection physical namespace is invalid"));
}
let attempt = running_attempt(&claim, &config.qdrant_url, config.collection(partition));
let attempt = running_attempt(&claim, &config.qdrant_url, config.collection());
let grant = MemorySemanticProjectorExecutorGrant {
schema_version: MEMORY_SEMANTIC_PROJECTOR_EXECUTOR_GRANT_SCHEMA_VERSION.to_string(),
grant_id: grant_id.clone(),
@ -1878,15 +1486,11 @@ pub(crate) fn execute_memory_semantic_projection(
claim_id: &str,
config: &super::MemorySemanticIndexConfig,
) -> Result<MemorySemanticIndexReceipt> {
let partition = match input.obligation.partition.as_str() {
"mind" => super::SemanticPartition::Mind,
"modeling" => super::SemanticPartition::Modeling,
_ => {
return Err(anyhow!(
"semantic projection obligation partition is invalid"
));
}
};
if input.obligation.partition != "modeling" {
return Err(anyhow!(
"semantic projection obligation partition is invalid"
));
}
let store_path = store_path.as_ref();
let started_at = now_rfc3339();
let (_, _, claim, attempt) = load_running_claim(store_path, claim_id)?;
@ -1897,7 +1501,7 @@ pub(crate) fn execute_memory_semantic_projection(
}
authenticate_claim_authority(store_path, &claim)?;
if attempt.physical_backend_url != config.qdrant_url
|| attempt.collection_name != config.collection(partition)
|| attempt.collection_name != config.collection()
{
let error = anyhow!(
"semantic projection execution config disagrees with acquired physical namespace"
@ -1913,7 +1517,6 @@ pub(crate) fn execute_memory_semantic_projection(
let raw_receipt = match super::semantic_index::index_memory_semantic_partition(
&input.snapshot,
&input.obligation.swarm_id,
partition,
&super::semantic_index::MemorySemanticProjectionNamespace {
obligation_id: claim.obligation_id.clone(),
claim_id: claim.claim_id.clone(),
@ -2350,7 +1953,7 @@ pub fn validate_memory_semantic_projector_executor_grant(
|| !is_opaque_identity(&grant.grant_id)
|| !is_opaque_identity(&grant.scope_id)
|| !is_opaque_identity(&grant.swarm_id)
|| !matches!(grant.partition.as_str(), "mind" | "modeling")
|| grant.partition != "modeling"
|| !is_opaque_identity(&grant.obligation_id)
|| !is_opaque_identity(&grant.executor_id)
|| !is_opaque_identity(&grant.executor_incarnation)
@ -2407,7 +2010,7 @@ pub fn validate_memory_semantic_projector_recovery_authorization(
|| !is_opaque_identity(&authorization.authorization_id)
|| !is_opaque_identity(&authorization.scope_id)
|| !is_opaque_identity(&authorization.swarm_id)
|| !matches!(authorization.partition.as_str(), "mind" | "modeling")
|| authorization.partition != "modeling"
|| !is_opaque_identity(&authorization.obligation_id)
|| !is_opaque_identity(&authorization.claim_id)
|| authorization.claim_epoch == 0
@ -2461,7 +2064,7 @@ pub fn validate_memory_semantic_physical_retirement_obligation(
|| !is_opaque_identity(&obligation.retirement_id)
|| !is_opaque_identity(&obligation.scope_id)
|| !is_opaque_identity(&obligation.swarm_id)
|| !matches!(obligation.partition.as_str(), "mind" | "modeling")
|| obligation.partition != "modeling"
|| !is_opaque_identity(&obligation.obligation_id)
|| !is_opaque_identity(&obligation.attempt_id)
|| !is_opaque_identity(&obligation.claim_id)
@ -2833,12 +2436,8 @@ where
return Ok(receipt);
}
if retirement.physical_backend_url != config.qdrant_url
|| retirement.collection_name
!= config.collection(match retirement.partition.as_str() {
"mind" => super::SemanticPartition::Mind,
"modeling" => super::SemanticPartition::Modeling,
_ => return Err(anyhow!("semantic physical-retirement partition is invalid")),
})
|| retirement.partition != "modeling"
|| retirement.collection_name != config.collection()
{
return Err(anyhow!(
"semantic physical-retirement namespace is not permitted by current projector policy"
@ -3753,7 +3352,7 @@ fn validate_idunn_semantic_recovery_evidence(
}
if !valid_rfc3339(&evidence.launch_lifecycle_receipt_completed_at)
|| !valid_rfc3339(&evidence.provider_heartbeat_at)
|| !matches!(evidence.partition.as_str(), "mind" | "modeling")
|| evidence.partition != "modeling"
|| evidence.claim_epoch == 0
|| evidence.provider_incarnation == evidence.abandoned_executor_incarnation
|| evidence.startup_correlation_id != evidence.launch_lifecycle_receipt_id
@ -3874,14 +3473,6 @@ mod retention_tests {
other_basis.obligation_id = "memory-semantic-projection-modeling-other-basis".into();
assert!(semantic_obligation_is_stale(&other_basis, &current));
assert!(!semantic_obligation_is_stale(&current, &current));
let mut mind_current = current.clone();
mind_current.partition = "mind".into();
mind_current.source_generation = 2;
let mut mind_old = mind_current.clone();
mind_old.obligation_id = "memory-semantic-projection-mind-old".into();
mind_old.source_generation = 1;
assert!(semantic_obligation_is_stale(&mind_old, &mind_current));
}
fn failed_lifecycle(
@ -4537,32 +4128,4 @@ mod retention_tests {
);
Ok(())
}
#[test]
fn semantic_lifecycle_retention_refuses_future_generation_even_inside_window() -> Result<()> {
let directory = tempdir()?;
let store = directory.path().join("semantic.cc");
let mut older = obligation("swarm-future", 1);
let mut current = obligation("swarm-future", 2);
let mut future = obligation("swarm-future", 3);
for value in [&mut older, &mut current, &mut future] {
value.partition = "mind".into();
value.obligation_id = value.obligation_id.replace("modeling", "mind");
}
let mut cache = semantic_projector_cache(&store)?;
cache.put(&older.obligation_id, &older)?;
cache.put(&current.obligation_id, &current)?;
cache.put(&future.obligation_id, &future)?;
let input = input_for(&store, &current);
let opening = SingleFileMessagePackBackingStore::new(&store).pull_all()?;
let error =
retain_memory_semantic_projection_lifecycles(&store, &input, 1, "2026-08-10T08:00:00Z")
.unwrap_err();
assert!(error.to_string().contains("non-stale generation"));
assert_eq!(
SingleFileMessagePackBackingStore::new(&store).pull_all()?,
opening
);
Ok(())
}
}

View file

@ -81,8 +81,7 @@ where
pub(crate) fn pulse(
&self,
sealed_inputs: &[MemorySemanticProjectionInput],
fairness_cursor: Option<&str>,
input: &MemorySemanticProjectionInput,
) -> MemorySemanticProjectorPulseOutcome {
if self
.active
@ -92,77 +91,30 @@ where
return outcome(MemorySemanticProjectorPulseStatus::Busy, vec![], None, None);
}
let _guard = PulseGuard(&self.active);
if sealed_inputs.is_empty() {
return outcome(MemorySemanticProjectorPulseStatus::Idle, vec![], None, None);
}
let scopes = sealed_inputs.iter().map(scope_key).collect::<Vec<_>>();
let start = fairness_cursor
.and_then(|cursor| scopes.iter().position(|scope| scope == cursor))
.map_or(0, |index| (index + 1) % sealed_inputs.len());
let mut inspections = Vec::with_capacity(sealed_inputs.len());
let mut first_source_error = None;
for offset in 0..sealed_inputs.len() {
let index = (start + offset) % sealed_inputs.len();
let input = &sealed_inputs[index];
let scope_id = scopes[index].clone();
let classification = match self.port.classify(input) {
Ok(classification) => classification,
Err(error) => {
let error = format!("{error:#}");
first_source_error.get_or_insert_with(|| error.clone());
inspections.push(MemorySemanticProjectorPulseInspection {
let scope_id = scope_key(input);
let classification = match self.port.classify(input) {
Ok(classification) => classification,
Err(error) => {
return outcome(
MemorySemanticProjectorPulseStatus::Refused,
vec![MemorySemanticProjectorPulseInspection {
scope_id,
classification: None,
error: Some(error),
});
continue;
}
};
inspections.push(MemorySemanticProjectorPulseInspection {
scope_id: scope_id.clone(),
classification: Some(classification.clone()),
error: None,
});
if let MemorySemanticProjectorPulseClassification::RunningOwned { claim_id } =
classification
{
if let Err(error) = self.port.execute(input, &claim_id) {
return outcome(
MemorySemanticProjectorPulseStatus::Refused,
inspections,
Some(scope_id),
Some(format!("{error:#}")),
);
}
return outcome(
MemorySemanticProjectorPulseStatus::Executed,
inspections,
Some(scope_id),
error: Some(format!("{error:#}")),
}],
None,
Some(format!("{error:#}")),
);
}
let Some(purpose) = classification.automatic_purpose() else {
continue;
};
let claim_id = match self.port.acquire(input, purpose) {
Ok(Some(claim_id)) => claim_id,
Ok(None) => {
return outcome(
MemorySemanticProjectorPulseStatus::Contended,
inspections,
Some(scope_id),
None,
);
}
Err(error) => {
return outcome(
MemorySemanticProjectorPulseStatus::Refused,
inspections,
Some(scope_id),
Some(format!("{error:#}")),
);
}
};
};
let inspections = vec![MemorySemanticProjectorPulseInspection {
scope_id: scope_id.clone(),
classification: Some(classification.clone()),
error: None,
}];
if let MemorySemanticProjectorPulseClassification::RunningOwned { claim_id } =
classification
{
if let Err(error) = self.port.execute(input, &claim_id) {
return outcome(
MemorySemanticProjectorPulseStatus::Refused,
@ -178,21 +130,47 @@ where
None,
);
}
if let Some(error) = first_source_error {
outcome(
MemorySemanticProjectorPulseStatus::Refused,
inspections,
None,
Some(error),
)
} else {
outcome(
let Some(purpose) = classification.automatic_purpose() else {
return outcome(
MemorySemanticProjectorPulseStatus::Idle,
inspections,
None,
None,
)
);
};
let claim_id = match self.port.acquire(input, purpose) {
Ok(Some(claim_id)) => claim_id,
Ok(None) => {
return outcome(
MemorySemanticProjectorPulseStatus::Contended,
inspections,
Some(scope_id),
None,
);
}
Err(error) => {
return outcome(
MemorySemanticProjectorPulseStatus::Refused,
inspections,
Some(scope_id),
Some(format!("{error:#}")),
);
}
};
if let Err(error) = self.port.execute(input, &claim_id) {
return outcome(
MemorySemanticProjectorPulseStatus::Refused,
inspections,
Some(scope_id),
Some(format!("{error:#}")),
);
}
outcome(
MemorySemanticProjectorPulseStatus::Executed,
inspections,
Some(scope_id),
None,
)
}
}
@ -344,7 +322,7 @@ mod tests {
MemorySemanticProjectorPulseClassification::Stale,
] {
let pulser = MemorySemanticProjectorPulser::new(MockPort::new(vec![classification]));
let outcome = pulser.pulse(&[input("mind")], None);
let outcome = pulser.pulse(&input("modeling"));
assert_eq!(outcome.status, MemorySemanticProjectorPulseStatus::Idle);
assert!(pulser.port.acquisitions.lock().unwrap().is_empty());
assert!(pulser.port.executions.lock().unwrap().is_empty());
@ -356,7 +334,7 @@ mod tests {
let pulser = MemorySemanticProjectorPulser::new(MockPort::new(vec![
MemorySemanticProjectorPulseClassification::Repair,
]));
let outcome = pulser.pulse(&[input("modeling")], None);
let outcome = pulser.pulse(&input("modeling"));
assert_eq!(outcome.status, MemorySemanticProjectorPulseStatus::Executed);
assert_eq!(
pulser.port.acquisitions.lock().unwrap().as_slice(),
@ -368,7 +346,7 @@ mod tests {
fn native_classification_refuses_an_advanced_sealed_input_as_stale() -> Result<()> {
let temp = tempdir()?;
let store = temp.path().join("classification.msgpack");
let current = input("mind");
let current = input("modeling");
let mut cache: CultCache = semantic_projector_cache(&store)?;
cache.put(&current.obligation().obligation_id, current.obligation())?;
assert_eq!(
@ -385,29 +363,17 @@ mod tests {
}
#[test]
fn pending_and_failed_select_one_global_action_with_rotating_fairness() {
fn pending_and_failed_execute_one_action() {
for classification in [
MemorySemanticProjectorPulseClassification::Pending,
MemorySemanticProjectorPulseClassification::Failed,
] {
let pulser = MemorySemanticProjectorPulser::new(MockPort::new(vec![classification]));
let outcome = pulser.pulse(&[input("modeling")], None);
let outcome = pulser.pulse(&input("modeling"));
assert_eq!(outcome.status, MemorySemanticProjectorPulseStatus::Executed);
assert_eq!(pulser.port.acquisitions.lock().unwrap().len(), 1);
assert_eq!(pulser.port.executions.lock().unwrap().len(), 1);
}
let pulser = MemorySemanticProjectorPulser::new(MockPort::new(vec![
MemorySemanticProjectorPulseClassification::Pending,
]));
let candidates = [input("mind"), input("modeling")];
let outcome = pulser.pulse(&candidates, Some("swarm-a:mind"));
assert_eq!(
outcome.selected_scope_id.as_deref(),
Some("swarm-a:modeling")
);
assert_eq!(outcome.inspections.len(), 1);
assert_eq!(pulser.port.executions.lock().unwrap().len(), 1);
}
#[test]
@ -415,7 +381,7 @@ mod tests {
let port = MockPort::new(vec![MemorySemanticProjectorPulseClassification::Pending]);
*port.acquire_result.lock().unwrap() = Some(None);
let pulser = MemorySemanticProjectorPulser::new(port);
let outcome = pulser.pulse(&[input("mind"), input("modeling")], None);
let outcome = pulser.pulse(&input("modeling"));
assert_eq!(
outcome.status,
MemorySemanticProjectorPulseStatus::Contended
@ -431,7 +397,7 @@ mod tests {
claim_id: "recovered-claim".to_string(),
},
]));
let outcome = pulser.pulse(&[input("mind")], None);
let outcome = pulser.pulse(&input("modeling"));
assert_eq!(outcome.status, MemorySemanticProjectorPulseStatus::Executed);
assert!(pulser.port.acquisitions.lock().unwrap().is_empty());
assert_eq!(
@ -440,25 +406,6 @@ mod tests {
);
}
#[test]
fn one_source_fault_does_not_hide_an_actionable_other_source() {
let port = MockPort::new(vec![]);
*port.classifications.lock().unwrap() = vec![
Err("stale sealed source"),
Ok(MemorySemanticProjectorPulseClassification::Pending),
];
let pulser = MemorySemanticProjectorPulser::new(port);
let outcome = pulser.pulse(&[input("mind"), input("modeling")], None);
assert_eq!(outcome.status, MemorySemanticProjectorPulseStatus::Executed);
assert_eq!(outcome.inspections.len(), 2);
assert!(outcome.inspections[0].classification.is_none());
assert_eq!(
outcome.selected_scope_id.as_deref(),
Some("swarm-a:modeling")
);
assert_eq!(pulser.port.executions.lock().unwrap().len(), 1);
}
#[test]
fn overlapping_pulse_is_busy_and_cannot_execute() {
let entered = Arc::new(Barrier::new(2));
@ -468,10 +415,10 @@ mod tests {
let pulser = Arc::new(MemorySemanticProjectorPulser::new(port));
let worker = {
let pulser = pulser.clone();
std::thread::spawn(move || pulser.pulse(&[input("mind")], None))
std::thread::spawn(move || pulser.pulse(&input("modeling")))
};
entered.wait();
let busy = pulser.pulse(&[input("modeling")], None);
let busy = pulser.pulse(&input("modeling"));
assert_eq!(busy.status, MemorySemanticProjectorPulseStatus::Busy);
release.wait();
assert_eq!(

View file

@ -173,7 +173,6 @@ pub(crate) fn derive_repo_model_semantic_projection_obligation(
crate::derive_memory_semantic_projection_obligation(
&projection,
&view.identity.swarm_id,
crate::SemanticPartition::Modeling,
&format!("epiphany.runtime/{}/repo-model", view.identity.runtime_id),
&view.projection_digest,
created_at,

View file

@ -9,7 +9,7 @@ use crate::memory_graph::{
};
use crate::{
MemorySemanticIndexConfig, MemorySemanticProjectionInput,
agent_memory_semantic_projection_input, runtime_modeling_semantic_projection_input,
runtime_modeling_semantic_projection_input,
};
use anyhow::{Result, anyhow};
use chrono::{SecondsFormat, Utc};
@ -36,7 +36,6 @@ use windows_sys::Win32::System::Threading::{CreateMutexW, ReleaseMutex};
const SEMANTIC_PROJECTOR_EXECUTOR_ID: &str = "epiphany-memory-semantic-projector";
struct LocalIdunnSemanticProjectorSession {
mind_store: PathBuf,
modeling_store: PathBuf,
executor_id: String,
executor_incarnation: String,
@ -66,21 +65,12 @@ impl Drop for SemanticProjectorSingletonGuard {
}
fn acquire_semantic_projector_singleton(
mind_store: impl AsRef<Path>,
modeling_store: impl AsRef<Path>,
) -> Result<SemanticProjectorSingletonGuard> {
let mind = canonical_file(&mind_store, "Mind")?;
let modeling = canonical_file(&modeling_store, "Modeling")?;
let identity = format!(
"{:x}",
Sha256::digest(
format!(
"{}|{}",
mind.to_string_lossy().to_lowercase(),
modeling.to_string_lossy().to_lowercase()
)
.as_bytes()
)
Sha256::digest(modeling.to_string_lossy().to_lowercase().as_bytes())
);
#[cfg(windows)]
{
@ -126,24 +116,16 @@ fn acquire_semantic_projector_singleton(
impl LocalIdunnSemanticProjectorSession {
fn new(
mind_store: impl AsRef<Path>,
modeling_store: impl AsRef<Path>,
executor_id: impl Into<String>,
config: MemorySemanticIndexConfig,
) -> Result<Self> {
let mind_store = canonical_file(&mind_store, "Mind")?;
let modeling_store = canonical_file(&modeling_store, "Modeling")?;
if mind_store == modeling_store {
return Err(anyhow!(
"semantic projector sources must be distinct canonical stores"
));
}
let executor_id = executor_id.into();
if executor_id.trim().is_empty() {
return Err(anyhow!("semantic projector executor id must not be empty"));
}
Ok(Self {
mind_store,
modeling_store,
executor_id,
executor_incarnation: format!("projector-{}", Uuid::new_v4()),
@ -158,7 +140,6 @@ impl LocalIdunnSemanticProjectorSession {
fn store_for(&self, input: &MemorySemanticProjectionInput) -> Result<&Path> {
match input.obligation().partition.as_str() {
"mind" => Ok(&self.mind_store),
"modeling" => Ok(&self.modeling_store),
other => Err(anyhow!(
"unsupported semantic projector partition {other:?}"
@ -184,13 +165,11 @@ pub struct SemanticProjectorServicePulse {
impl SemanticProjectorServiceBody {
pub fn new(
mind_store: impl AsRef<Path>,
modeling_store: impl AsRef<Path>,
config: MemorySemanticIndexConfig,
) -> Result<Self> {
let singleton = acquire_semantic_projector_singleton(&mind_store, &modeling_store)?;
let singleton = acquire_semantic_projector_singleton(&modeling_store)?;
let session = LocalIdunnSemanticProjectorSession::new(
mind_store,
modeling_store,
SEMANTIC_PROJECTOR_EXECUTOR_ID,
config,
@ -207,13 +186,22 @@ impl SemanticProjectorServiceBody {
&self.provider_incarnation
}
pub fn pulse(&self, fairness_cursor: Option<&str>) -> SemanticProjectorServicePulse {
pub fn pulse(&self) -> SemanticProjectorServicePulse {
let session = &self.pulser.port;
let (inputs, source_fault_count) = collect_semantic_projection_inputs(
agent_memory_semantic_projection_input(&session.mind_store),
runtime_modeling_semantic_projection_input(&session.modeling_store),
let (inputs, source_fault_count) =
match runtime_modeling_semantic_projection_input(&session.modeling_store) {
Ok(input) => (vec![input], 0),
Err(_) => (Vec::new(), 1),
};
let outcome = inputs.first().map_or_else(
|| MemorySemanticProjectorPulseOutcome {
status: crate::MemorySemanticProjectorPulseStatus::Idle,
selected_scope_id: None,
inspections: Vec::new(),
error: None,
},
|input| self.pulser.pulse(input),
);
let outcome = self.pulser.pulse(&inputs, fairness_cursor);
SemanticProjectorServicePulse {
outcome,
inputs,
@ -222,23 +210,6 @@ impl SemanticProjectorServiceBody {
}
}
fn collect_semantic_projection_inputs(
mind: Result<MemorySemanticProjectionInput>,
modeling: Result<MemorySemanticProjectionInput>,
) -> (Vec<MemorySemanticProjectionInput>, u32) {
match (mind, modeling) {
(Ok(mind), Ok(modeling))
if validate_semantic_projector_source_pair(&mind, &modeling).is_ok() =>
{
(vec![mind, modeling], 0)
}
(Ok(_), Ok(_)) => (Vec::new(), 2),
(Ok(mind), Err(_)) => (vec![mind], 1),
(Err(_), Ok(modeling)) => (vec![modeling], 1),
(Err(_), Err(_)) => (Vec::new(), 2),
}
}
impl MemorySemanticProjectorPulsePort for LocalIdunnSemanticProjectorSession {
fn classify(
&self,
@ -292,23 +263,6 @@ impl MemorySemanticProjectorPulsePort for LocalIdunnSemanticProjectorSession {
}
}
pub fn validate_semantic_projector_source_pair(
mind: &MemorySemanticProjectionInput,
modeling: &MemorySemanticProjectionInput,
) -> Result<()> {
if mind.obligation().partition != "mind" || modeling.obligation().partition != "modeling" {
return Err(anyhow!(
"semantic projector requires one Mind and one Modeling source"
));
}
if mind.obligation().swarm_id != modeling.obligation().swarm_id {
return Err(anyhow!(
"semantic projector canonical stores belong to different swarms"
));
}
Ok(())
}
fn canonical_file(path: &impl AsRef<Path>, label: &str) -> Result<PathBuf> {
let path = path.as_ref();
if !path.is_file() {
@ -324,116 +278,16 @@ fn canonical_file(path: &impl AsRef<Path>, label: &str) -> Result<PathBuf> {
#[cfg(test)]
mod tests {
use super::*;
use crate::memory_graph::semantic_projector::MemorySemanticProjectionAuthoritySnapshot;
use crate::{
MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION, MemorySemanticProjectionObligation,
MemorySemanticProjectionSourceHead, SEMANTIC_PROJECTION_SCHEMA_VERSION,
};
fn input(swarm: &str, partition: &str) -> MemorySemanticProjectionInput {
let obligation = MemorySemanticProjectionObligation {
schema_version: MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION.to_string(),
obligation_id: format!("obligation-{swarm}-{partition}"),
swarm_id: swarm.to_string(),
partition: partition.to_string(),
canonical_source_id: format!("source-{partition}"),
source_commit_id: "commit-1".to_string(),
graph_id: format!("graph-{partition}"),
source_generation: 1,
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(),
};
MemorySemanticProjectionInput {
snapshot: crate::EpiphanyMemoryGraphSnapshot {
schema_version: Some("v0".to_string()),
graph_id: obligation.graph_id.clone(),
model_revision: 1,
..Default::default()
},
authority: MemorySemanticProjectionAuthoritySnapshot {
head: MemorySemanticProjectionSourceHead {
swarm_id: obligation.swarm_id.clone(),
partition: obligation.partition.clone(),
canonical_source_id: obligation.canonical_source_id.clone(),
source_commit_id: obligation.source_commit_id.clone(),
graph_id: obligation.graph_id.clone(),
source_generation: 1,
source_model_hash: obligation.source_model_hash.clone(),
canonical_content_set_hash: obligation.canonical_content_set_hash.clone(),
},
envelopes: Vec::new(),
},
obligation,
}
}
#[test]
fn source_pair_requires_exact_partitions_and_one_swarm() {
assert!(
validate_semantic_projector_source_pair(&input("a", "mind"), &input("a", "modeling"))
.is_ok()
);
assert!(
validate_semantic_projector_source_pair(&input("a", "mind"), &input("b", "modeling"))
.is_err()
);
assert!(
validate_semantic_projector_source_pair(&input("a", "modeling"), &input("a", "mind"))
.is_err()
);
}
#[test]
fn pulse_source_collection_keeps_both_partitions_and_does_not_hide_one_survivor() {
let (both, faults) =
collect_semantic_projection_inputs(Ok(input("a", "mind")), Ok(input("a", "modeling")));
assert_eq!(both.len(), 2);
assert_eq!(faults, 0);
let (modeling, faults) = collect_semantic_projection_inputs(
Err(anyhow!("Mind source failed")),
Ok(input("a", "modeling")),
);
assert_eq!(modeling.len(), 1);
assert_eq!(modeling[0].obligation().partition, "modeling");
assert_eq!(faults, 1);
let (foreign_pair, faults) =
collect_semantic_projection_inputs(Ok(input("a", "mind")), Ok(input("b", "modeling")));
assert!(foreign_pair.is_empty());
assert_eq!(faults, 2);
}
#[test]
fn session_refuses_one_physical_store_as_two_owners() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("canonical.ccmp");
std::fs::write(&store, [])?;
assert!(
LocalIdunnSemanticProjectorSession::new(
&store,
&store,
"projector",
MemorySemanticIndexConfig::from_env(),
)
.is_err()
);
Ok(())
}
#[test]
fn singleton_refuses_a_second_process_owner_identity() -> Result<()> {
let temp = tempfile::tempdir()?;
let mind = temp.path().join("mind.ccmp");
let modeling = temp.path().join("modeling.ccmp");
std::fs::write(&mind, [])?;
std::fs::write(&modeling, [])?;
let first = acquire_semantic_projector_singleton(&mind, &modeling)?;
assert!(acquire_semantic_projector_singleton(&mind, &modeling).is_err());
let first = acquire_semantic_projector_singleton(&modeling)?;
assert!(acquire_semantic_projector_singleton(&modeling).is_err());
drop(first);
assert!(acquire_semantic_projector_singleton(&mind, &modeling).is_ok());
assert!(acquire_semantic_projector_singleton(&modeling).is_ok());
Ok(())
}