diff --git a/epiphany-core/Cargo.toml b/epiphany-core/Cargo.toml index 6b34b2d8..7df3a2a0 100644 --- a/epiphany-core/Cargo.toml +++ b/epiphany-core/Cargo.toml @@ -39,7 +39,7 @@ tokio = { version = "1", features = ["rt", "rt-multi-thread"] } wiremock = "0.6" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading"] } +windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Threading"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/epiphany-core/src/bin/epiphany-daemon-supervisor.rs b/epiphany-core/src/bin/epiphany-daemon-supervisor.rs index 3a7f5cd5..86e78479 100644 --- a/epiphany-core/src/bin/epiphany-daemon-supervisor.rs +++ b/epiphany-core/src/bin/epiphany-daemon-supervisor.rs @@ -22,7 +22,6 @@ use epiphany_core::epiphany_cluster_service_execution_audit_report; use epiphany_core::epiphany_cultmesh_daemon_poke_intent_from_status; use epiphany_core::epiphany_cultmesh_daemon_poke_receipt_for_intent; use epiphany_core::epiphany_service_execution_audit_report; -use epiphany_core::idunn_acquire_memory_semantic_projection_for_local_supervisor; use epiphany_core::idunn_recover_memory_semantic_projection_from_cultmesh; use epiphany_core::load_epiphany_cultmesh_cluster_topology; use epiphany_core::load_epiphany_cultmesh_daemon_restart_policy; @@ -41,6 +40,7 @@ use epiphany_core::write_epiphany_cultmesh_daemon_restart_policy; use epiphany_core::write_epiphany_cultmesh_daemon_scheduler_receipt; use epiphany_core::write_epiphany_cultmesh_daemon_service_lifecycle_receipt; use epiphany_core::write_epiphany_cultmesh_managed_service_policy; +use epiphany_core::write_epiphany_cultmesh_semantic_projector_service_policy; use serde_json::Value; use serde_json::json; use sha2::Digest; @@ -52,6 +52,9 @@ use std::process::Command; use std::process::Stdio; use uuid::Uuid; +const SEMANTIC_PROJECTOR_SERVICE_ID: &str = "epiphany-memory-semantic-projector-service"; +const SEMANTIC_PROJECTOR_EXECUTOR_ID: &str = "epiphany-memory-semantic-projector"; + #[cfg(windows)] use std::os::windows::process::CommandExt; @@ -65,6 +68,7 @@ fn main() -> Result<()> { "service-plan" => service_plan(args), "service-launch" | "launch-service" | "start-service" => service_launch(args), "managed-service-policy" | "service-desired-state" => managed_service_policy(args), + "semantic-projector-service-policy" => semantic_projector_service_policy(args), "managed-service-read" | "service-desired-state-read" => managed_service_read(args), "managed-service-reconcile" | "service-desired-state-reconcile" => { managed_service_reconcile(args) @@ -135,10 +139,9 @@ fn main() -> Result<()> { "windows-service-start" | "service-start" => windows_service_control(args, "start"), "windows-service-stop" | "service-stop" => windows_service_control(args, "stop"), "policy" | "write-policy" => write_policy(args), - "semantic-acquire" => semantic_acquire(args), "semantic-recover" => semantic_recover(args), other => anyhow::bail!( - "unknown command {other:?}; use reconcile, tick, serve, service-plan, service-launch, service-runbook, repo-work-service-audit, cluster-service-runbook, cluster-service-install-plan, cluster-service-audit, cluster-service-start, cluster-service-stop, cluster-service-execution-readiness, cluster-service-execution-runbook, cluster-service-execution-audit, windows-service-install, windows-service-execution-readiness, windows-service-execution-runbook, windows-service-execution-audit, service-execution-audit-smoke, windows-service-reconcile, windows-service-status, windows-service-start, windows-service-stop, policy, semantic-acquire, or semantic-recover" + "unknown command {other:?}; use reconcile, tick, serve, service-plan, service-launch, service-runbook, managed-service-policy, semantic-projector-service-policy, repo-work-service-audit, cluster-service-runbook, cluster-service-install-plan, cluster-service-audit, cluster-service-start, cluster-service-stop, cluster-service-execution-readiness, cluster-service-execution-runbook, cluster-service-execution-audit, windows-service-install, windows-service-execution-readiness, windows-service-execution-runbook, windows-service-execution-audit, service-execution-audit-smoke, windows-service-reconcile, windows-service-status, windows-service-start, windows-service-stop, policy, or semantic-recover" ), } } @@ -157,33 +160,6 @@ fn required<'a>(value: &'a Option, flag: &str) -> Result<&'a str> { value.as_deref().with_context(|| format!("missing {flag}")) } -fn semantic_acquire(args: Args) -> Result<()> { - let (input, store) = semantic_projection_input(&args)?; - let purpose = required(&args.semantic_purpose, "--purpose")?; - if !matches!(purpose, "execute" | "repair") { - anyhow::bail!("--purpose must be execute or repair"); - } - let acquisition = idunn_acquire_memory_semantic_projection_for_local_supervisor( - store, - &input, - required(&args.executor_id, "--executor-id")?, - purpose, - &Utc::now().to_rfc3339(), - )?; - println!( - "{}", - serde_json::to_string_pretty(&json!({ - "grantId": acquisition.grant.grant_id, - "claimId": acquisition.claim.claim_id, - "epoch": acquisition.claim.epoch, - "executorId": acquisition.claim.executor_id, - "purpose": purpose, - "privateStateExposed": false - }))? - ); - Ok(()) -} - fn semantic_recover(args: Args) -> Result<()> { let (input, store) = semantic_projection_input(&args)?; let (authorization, claim) = idunn_recover_memory_semantic_projection_from_cultmesh( @@ -192,7 +168,7 @@ fn semantic_recover(args: Args) -> Result<()> { store, &input, required(&args.expected_claim_id, "--expected-claim-id")?, - required(&args.executor_id, "--executor-id")?, + SEMANTIC_PROJECTOR_EXECUTOR_ID, required(&args.receipt_id, "--receipt-id")?, required(&args.provider_heartbeat_id, "--provider-heartbeat-id")?, &Utc::now().to_rfc3339(), @@ -201,10 +177,8 @@ fn semantic_recover(args: Args) -> Result<()> { "{}", serde_json::to_string_pretty(&json!({ "authorizationId": authorization.authorization_id, - "claimId": claim.claim_id, "epoch": claim.epoch, "executorId": claim.executor_id, - "executorIncarnation": claim.executor_incarnation, "privateStateExposed": false }))? ); @@ -478,6 +452,15 @@ fn service_launch(args: Args) -> Result<()> { } fn managed_service_policy(args: Args) -> Result<()> { + if args.service_id == SEMANTIC_PROJECTOR_SERVICE_ID { + anyhow::bail!( + "reserved semantic projector service policy must use semantic-projector-service-policy" + ); + } + write_managed_service_policy(args) +} + +fn write_managed_service_policy(args: Args) -> Result<()> { require_supervisor_bootstrap(&args)?; let command = service_command_path(&args)?; @@ -526,11 +509,19 @@ fn managed_service_policy(args: Args) -> Result<()> { .to_string(), ], }; - let written = write_epiphany_cultmesh_managed_service_policy( - &args.store, - args.runtime_id.clone(), - policy, - )?; + let written = if policy.service_id == SEMANTIC_PROJECTOR_SERVICE_ID { + write_epiphany_cultmesh_semantic_projector_service_policy( + &args.store, + args.runtime_id.clone(), + policy, + )? + } else { + write_epiphany_cultmesh_managed_service_policy( + &args.store, + args.runtime_id.clone(), + policy, + )? + }; println!( "{}", serde_json::to_string_pretty(&json!({ @@ -552,6 +543,82 @@ fn managed_service_policy(args: Args) -> Result<()> { Ok(()) } +fn semantic_projector_service_policy(mut args: Args) -> Result<()> { + if args.service_command.is_some() { + anyhow::bail!( + "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() + .context("semantic-projector-service-policy requires --runtime-store")?; + 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}" + )); + args.restart_mode = "always".to_string(); + args.service_command = Some(semantic_projector_command_path()?); + args.service_args = semantic_projector_service_args( + agent_store, + runtime_store, + &args.store, + &args.runtime_id, + args.loop_interval_seconds, + ); + if args.max_iterations != 0 { + anyhow::bail!("semantic projector managed service must not have a finite iteration limit"); + } + write_managed_service_policy(args) +} + +fn semantic_projector_command_path() -> Result { + let binary = if cfg!(windows) { + "epiphany-memory-semantic-projector.exe" + } else { + "epiphany-memory-semantic-projector" + }; + let path = env::current_exe() + .map(|path| path.with_file_name(binary)) + .context("failed to derive packaged semantic projector executable")?; + if !path.is_file() { + anyhow::bail!( + "packaged semantic projector executable is missing at {}; build both supervisor and projector together", + path.display() + ); + } + Ok(path) +} + +fn semantic_projector_service_args( + agent_store: &Path, + runtime_store: &Path, + local_verse_store: &Path, + runtime_id: &str, + interval_seconds: i64, +) -> Vec { + 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(), + local_verse_store.display().to_string(), + "--runtime-id".to_string(), + runtime_id.to_string(), + "--interval-seconds".to_string(), + interval_seconds.to_string(), + ] +} + fn managed_service_read(args: Args) -> Result<()> { let policy = load_epiphany_cultmesh_managed_service_policy( &args.store, @@ -3583,8 +3650,10 @@ mod provider_status_ownership_tests { #[cfg(test)] mod semantic_projector_authority_tests { + use super::*; + #[test] - fn supervisor_owns_idunn_incarnations_and_exact_evidence_selection() { + fn supervisor_keeps_acquisition_inside_projector_and_selects_exact_recovery_evidence() { let source = include_str!("epiphany-daemon-supervisor.rs"); let issuer_flag = ["--issuer", "-incarnation"].concat(); let executor_flag = ["--executor", "-incarnation"].concat(); @@ -3596,8 +3665,12 @@ mod semantic_projector_authority_tests { assert!(!source.contains(&evidence_hash_flag)); assert!(source.contains("--receipt-id")); assert!(source.contains("--provider-heartbeat-id")); - assert!(source.contains("idunn_acquire_memory_semantic_projection_for_local_supervisor")); + let acquire_command = ["semantic", "-acquire"].concat(); + assert!(!source.contains(&acquire_command)); assert!(source.contains("idunn_recover_memory_semantic_projection_from_cultmesh")); + assert!(source.contains("SEMANTIC_PROJECTOR_EXECUTOR_ID")); + let executor_id_flag = ["--executor", "-id"].concat(); + assert!(!source.contains(&executor_id_flag)); } #[test] @@ -3611,6 +3684,61 @@ mod semantic_projector_authority_tests { assert!(!body.contains("execute_memory_semantic_projection")); assert!(!body.contains("MemorySemanticIndexConfig")); } + + #[test] + fn managed_projector_policy_launches_one_process_with_both_owned_partitions() { + let args = semantic_projector_service_args( + Path::new("mind.ccmp"), + Path::new("modeling.ccmp"), + Path::new("local-verse.ccmp"), + "local-runtime", + 60, + ); + assert_eq!( + args, + vec![ + "serve", + "--agent-store", + "mind.ccmp", + "--runtime-store", + "modeling.ccmp", + "--local-verse-store", + "local-verse.ccmp", + "--runtime-id", + "local-runtime", + "--interval-seconds", + "60", + ] + ); + assert_eq!(args.iter().filter(|arg| arg.as_str() == "serve").count(), 1); + } + + #[test] + fn reserved_projector_policy_has_no_generic_or_command_override_path() { + let source = include_str!("epiphany-daemon-supervisor.rs"); + let generic_start = source + .find("fn managed_service_policy(args: Args)") + .unwrap(); + let generic_tail = &source[generic_start..]; + let generic_end = generic_tail.find("\nfn ").unwrap(); + assert!(generic_tail[..generic_end].contains("SEMANTIC_PROJECTOR_SERVICE_ID")); + + let specialized_start = source + .find("fn semantic_projector_service_policy(mut args: Args)") + .unwrap(); + let specialized_tail = &source[specialized_start..]; + let specialized_end = specialized_tail.find("\nfn ").unwrap(); + let specialized = &specialized_tail[..specialized_end]; + assert!(specialized.contains("args.service_command.is_some()")); + assert!(specialized.contains("semantic_projector_command_path()")); + assert!(specialized.contains("write_managed_service_policy(args)")); + + let legacy_cli = include_str!("epiphany-memory-semantic.rs"); + let index_arm = ["\"index\"", " =>"].concat(); + let claim_flag = ["--claim", "-id"].concat(); + assert!(!legacy_cli.contains(&index_arm)); + assert!(!legacy_cli.contains(&claim_flag)); + } } #[derive(Clone)] @@ -3654,8 +3782,6 @@ struct Args { stderr_artifact: Option, agent_store: Option, runtime_store: Option, - executor_id: Option, - semantic_purpose: Option, expected_claim_id: Option, provider_heartbeat_id: Option, } @@ -3703,8 +3829,6 @@ impl Args { let mut stderr_artifact = None; let mut agent_store = None; let mut runtime_store = None; - let mut executor_id = None; - let mut semantic_purpose = None; let mut expected_claim_id = None; let mut provider_heartbeat_id = None; @@ -3859,12 +3983,6 @@ impl Args { values.next().context("missing --runtime-store value")?, )) } - "--executor-id" => { - executor_id = Some(values.next().context("missing --executor-id value")?) - } - "--purpose" => { - semantic_purpose = Some(values.next().context("missing --purpose value")?) - } "--expected-claim-id" => { expected_claim_id = Some(values.next().context("missing --expected-claim-id value")?) @@ -3906,6 +4024,7 @@ impl Args { | "start-service" | "managed-service-policy" | "service-desired-state" + | "semantic-projector-service-policy" | "managed-service-read" | "service-desired-state-read" | "managed-service-reconcile" @@ -3957,7 +4076,6 @@ impl Args { | "service-start" | "windows-service-stop" | "service-stop" - | "semantic-acquire" | "semantic-recover" ) => { @@ -4015,8 +4133,6 @@ impl Args { stderr_artifact, agent_store, runtime_store, - executor_id, - semantic_purpose, expected_claim_id, provider_heartbeat_id, }) diff --git a/epiphany-core/src/bin/epiphany-memory-semantic-projector.rs b/epiphany-core/src/bin/epiphany-memory-semantic-projector.rs new file mode 100644 index 00000000..586c604b --- /dev/null +++ b/epiphany-core/src/bin/epiphany-memory-semantic-projector.rs @@ -0,0 +1,180 @@ +use anyhow::{Context, Result, anyhow}; +use epiphany_core::{ + EPIPHANY_CULTMESH_DAEMON_HEARTBEAT_EVENT_SCHEMA_VERSION, + EpiphanyCultMeshDaemonHeartbeatEventEntry, MemorySemanticIndexConfig, + MemorySemanticProjectionInput, MemorySemanticProjectorPulseStatus, + SemanticProjectorServiceBody, publish_epiphany_cultmesh_semantic_projection_health, + write_epiphany_cultmesh_daemon_heartbeat_event, +}; +use serde_json::json; +use std::env; +use std::path::PathBuf; +use std::thread; +use std::time::Duration; +use uuid::Uuid; + +const DAEMON_ID: &str = "epiphany-memory-semantic-projector"; + +fn main() -> Result<()> { + let args = Args::parse()?; + let projector = SemanticProjectorServiceBody::new( + &args.agent_store, + &args.runtime_store, + MemorySemanticIndexConfig::from_env(), + )?; + 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 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 health_faults = 0_u32; + for input in &inputs { + let store = source_store(&args, input)?; + if publish_epiphany_cultmesh_semantic_projection_health( + &args.local_verse_store, + args.runtime_id.clone(), + store, + input, + &provider_incarnation, + ) + .is_err() + { + health_faults += 1; + } + } + let degraded = source_faults > 0 + || health_faults > 0 + || matches!( + outcome.status, + MemorySemanticProjectorPulseStatus::Contended + | MemorySemanticProjectorPulseStatus::Refused + ); + let heartbeat = write_epiphany_cultmesh_daemon_heartbeat_event( + &args.local_verse_store, + args.runtime_id.clone(), + EpiphanyCultMeshDaemonHeartbeatEventEntry { + schema_version: EPIPHANY_CULTMESH_DAEMON_HEARTBEAT_EVENT_SCHEMA_VERSION.to_string(), + heartbeat_id: Uuid::new_v4().to_string(), + daemon_id: DAEMON_ID.to_string(), + cluster_id: "local".to_string(), + provider_incarnation: provider_incarnation.clone(), + sequence, + status: if degraded { "degraded" } else { "ready" }.to_string(), + heartbeat_at: chrono::Utc::now().to_rfc3339(), + private_state_exposed: false, + startup_lifecycle_receipt_id: args.startup_lifecycle_receipt_id.clone(), + }, + )?; + println!( + "{}", + serde_json::to_string(&json!({ + "schemaVersion": "epiphany.memory_semantic_projector_pulse.v0", + "pulseSequence": sequence, + "providerIncarnation": provider_incarnation, + "heartbeatId": heartbeat.heartbeat_id, + "providerStatus": heartbeat.status, + "pulseStatus": pulse_status(outcome.status), + "inspectedSourceCount": outcome.inspections.len(), + "sourceFaultCount": source_faults, + "healthPublicationFaultCount": health_faults, + "selectedScopeId": outcome.selected_scope_id, + "privateStateExposed": false, + "authoritative": false, + "queryAdmission": false + }))? + ); + if args.max_iterations != 0 && sequence >= args.max_iterations { + break; + } + thread::sleep(Duration::from_secs(args.interval_seconds)); + } + Ok(()) +} + +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:?}" + )), + } +} + +fn pulse_status(status: MemorySemanticProjectorPulseStatus) -> &'static str { + match status { + MemorySemanticProjectorPulseStatus::Idle => "idle", + MemorySemanticProjectorPulseStatus::Executed => "executed", + MemorySemanticProjectorPulseStatus::Contended => "contended", + MemorySemanticProjectorPulseStatus::Refused => "refused", + MemorySemanticProjectorPulseStatus::Busy => "busy", + } +} + +struct Args { + agent_store: PathBuf, + runtime_store: PathBuf, + local_verse_store: PathBuf, + runtime_id: String, + interval_seconds: u64, + max_iterations: u64, + startup_lifecycle_receipt_id: String, +} + +impl Args { + fn parse() -> Result { + let mut values = env::args().skip(1); + let command = values.next().unwrap_or_else(|| "pulse".to_string()); + 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(); + let mut interval_seconds = 60_u64; + let mut max_iterations = if matches!(command.as_str(), "pulse" | "once") { + 1 + } else { + 0 + }; + while let Some(flag) = values.next() { + let mut value = || { + values + .next() + .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()?, + "--interval-seconds" => interval_seconds = value()?.parse()?, + "--max-iterations" => max_iterations = value()?.parse()?, + _ => return Err(anyhow!("unexpected argument {flag:?}")), + } + } + if interval_seconds == 0 { + return Err(anyhow!("--interval-seconds 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, + interval_seconds, + max_iterations, + startup_lifecycle_receipt_id: env::var("EPIPHANY_STARTUP_LIFECYCLE_RECEIPT_ID") + .unwrap_or_default(), + }) + } +} diff --git a/epiphany-core/src/bin/epiphany-memory-semantic.rs b/epiphany-core/src/bin/epiphany-memory-semantic.rs index 5854c856..5aee8935 100644 --- a/epiphany-core/src/bin/epiphany-memory-semantic.rs +++ b/epiphany-core/src/bin/epiphany-memory-semantic.rs @@ -2,8 +2,7 @@ use anyhow::{Context, Result, anyhow}; use epiphany_core::{ EpiphanyMemoryContextQuery, EpiphanyMemoryGraphSnapshot, MemorySemanticIndexConfig, MemorySemanticProjectionInput, SemanticPartition, agent_memory_semantic_projection_input, - execute_memory_semantic_projection, load_memory_graph_snapshot, - load_memory_semantic_projection_readiness, + load_memory_graph_snapshot, load_memory_semantic_projection_readiness, publish_epiphany_cultmesh_semantic_projection_health, runtime_modeling_semantic_projection_input, semantic_memory_context, }; @@ -16,16 +15,6 @@ fn main() -> Result<()> { let options = Options::parse(args)?; let config = MemorySemanticIndexConfig::from_env(); match command.as_str() { - "index" => { - let (input, source_store) = options.load_projection_input()?; - let claim_id = options - .claim_id - .as_deref() - .ok_or_else(|| usage_error("index requires --claim-id "))?; - let receipt = - execute_memory_semantic_projection(source_store, &input, claim_id, &config)?; - print_receipt(&receipt, source_store)?; - } "health" => { let (input, source_store) = options.load_projection_input()?; let verse_store = options @@ -82,7 +71,6 @@ struct Options { graph_store: Option, runtime_store: Option, agent_store: Option, - claim_id: Option, local_verse_store: Option, runtime_id: String, provider_incarnation: Option, @@ -100,7 +88,6 @@ impl Options { graph_store: None, runtime_store: None, agent_store: None, - claim_id: None, local_verse_store: None, runtime_id: "epiphany-memory-semantic".to_string(), provider_incarnation: None, @@ -121,7 +108,6 @@ impl Options { "--graph-store" => options.graph_store = Some(PathBuf::from(value()?)), "--runtime-store" => options.runtime_store = Some(PathBuf::from(value()?)), "--agent-store" => options.agent_store = Some(PathBuf::from(value()?)), - "--claim-id" => options.claim_id = Some(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()?), @@ -235,7 +221,7 @@ fn parse_profile(value: &str) -> Result { fn usage_error(message: &str) -> anyhow::Error { anyhow!( - "{message}\nusage: epiphany-memory-semantic (--runtime-store |--agent-store |--graph-store ) [--swarm-id ] --partition [--claim-id ] [--local-verse-store --runtime-id --provider-incarnation ] [--text ] [--query-id ] [--budget ] [--profile ]" + "{message}\nusage: epiphany-memory-semantic (--runtime-store |--agent-store |--graph-store ) [--swarm-id ] --partition [--local-verse-store --runtime-id --provider-incarnation ] [--text ] [--query-id ] [--budget ] [--profile ]" ) } @@ -244,31 +230,6 @@ fn print_json(value: &impl serde::Serialize) -> Result<()> { Ok(()) } -fn print_receipt( - receipt: &epiphany_core::MemorySemanticIndexReceipt, - source_store: &PathBuf, -) -> Result<()> { - print_json(&serde_json::json!({ - "status": receipt.status, - "receiptId": receipt.receipt_id, - "sourceStore": source_store, - "obligationId": receipt.obligation_id, - "swarmId": receipt.swarm_id, - "partition": receipt.partition, - "collectionName": receipt.collection_name, - "graphId": receipt.graph_id, - "modelRevision": receipt.model_revision, - "modelHash": receipt.model_hash, - "embeddingProviderId": receipt.embedding_provider_id, - "embeddingModel": receipt.embedding_model, - "vectorDimensions": receipt.vector_dimensions, - "indexedDocumentCount": receipt.indexed_document_count, - "deletedDocumentCount": receipt.deleted_document_count, - "canonicalContentSetHash": receipt.canonical_content_set_hash, - "indexedAt": receipt.indexed_at, - })) -} - fn print_semantic_health( health: &epiphany_core::EpiphanyCultMeshSemanticProjectionHealthEntry, ) -> Result<()> { diff --git a/epiphany-core/src/cultmesh_integration.rs b/epiphany-core/src/cultmesh_integration.rs index 9a36cd0b..1ad18702 100644 --- a/epiphany-core/src/cultmesh_integration.rs +++ b/epiphany-core/src/cultmesh_integration.rs @@ -162,6 +162,7 @@ pub const EPIPHANY_CULTMESH_MANAGED_SERVICE_POLICY_TYPE: &str = "epiphany.cultmesh.managed_service_policy"; pub const EPIPHANY_CULTMESH_MANAGED_SERVICE_POLICY_SCHEMA_VERSION: &str = "epiphany.cultmesh.managed_service_policy.v0"; +const EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID: &str = "epiphany-memory-semantic-projector-service"; pub const EPIPHANY_CULTMESH_IDUNN_DEPLOYMENT_RECEIPT_SCHEMA_VERSION: &str = "gamecult.idunn.deployment_receipt.v0"; pub const EPIPHANY_CULTMESH_IDUNN_DEPLOYMENT_RECEIPT_LATEST_KEY: &str = @@ -4123,7 +4124,35 @@ pub fn write_epiphany_cultmesh_managed_service_policy( runtime_id: impl Into, policy: EpiphanyCultMeshManagedServicePolicyEntry, ) -> Result { + if policy.service_id == EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID { + return Err(anyhow!( + "reserved semantic projector policy requires its specialized writer" + )); + } validate_managed_service_policy(&policy)?; + write_validated_managed_service_policy(store_path, runtime_id, policy) +} + +pub fn write_epiphany_cultmesh_semantic_projector_service_policy( + store_path: impl AsRef, + runtime_id: impl Into, + policy: EpiphanyCultMeshManagedServicePolicyEntry, +) -> Result { + validate_managed_service_policy(&policy)?; + if policy.service_id != EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID { + return Err(anyhow!( + "semantic projector policy writer requires its reserved service id" + )); + } + validate_semantic_projector_managed_service_policy(&policy)?; + write_validated_managed_service_policy(store_path, runtime_id, policy) +} + +fn write_validated_managed_service_policy( + store_path: impl AsRef, + runtime_id: impl Into, + policy: EpiphanyCultMeshManagedServicePolicyEntry, +) -> Result { let mut node = open_epiphany_cultmesh_node(store_path, runtime_id)?; let key = epiphany_cultmesh_managed_service_policy_key(&policy.service_id); let written = node.put(key.as_str(), &policy)?; @@ -4528,6 +4557,50 @@ fn validate_managed_service_policy( Ok(()) } +fn validate_semantic_projector_managed_service_policy( + policy: &EpiphanyCultMeshManagedServicePolicyEntry, +) -> Result<()> { + let expected_binary = if cfg!(windows) { + "epiphany-memory-semantic-projector.exe" + } else { + "epiphany-memory-semantic-projector" + }; + if Path::new(&policy.command) + .file_name() + .and_then(|name| name.to_str()) + != Some(expected_binary) + { + return Err(anyhow!( + "reserved semantic projector policy requires the packaged projector executable" + )); + } + 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() != 11 + || policy.args[0] != "serve" + || policy.args[1] != "--agent-store" + || policy.args[2].trim().is_empty() + || policy.args[3] != "--runtime-store" + || policy.args[4].trim().is_empty() + || policy.args[5] != "--local-verse-store" + || policy.args[6].trim().is_empty() + || policy.args[7] != "--runtime-id" + || policy.args[8].trim().is_empty() + || policy.args[9] != "--interval-seconds" + || policy.args[10] + .parse::() + .ok() + .filter(|value| *value > 0) + .is_none() + { + return Err(anyhow!( + "reserved semantic projector policy must bind one packaged process to both canonical stores" + )); + } + Ok(()) +} + fn validate_daemon_scheduler_receipt( receipt: &EpiphanyCultMeshDaemonSchedulerReceiptEntry, ) -> Result<()> { @@ -7138,24 +7211,6 @@ pub fn load_latest_epiphany_cultmesh_daemon_heartbeat( .get(&epiphany_cultmesh_daemon_heartbeat_latest_key(daemon_id)) } -pub fn idunn_acquire_memory_semantic_projection_for_local_supervisor( - canonical_store: impl AsRef, - input: &crate::MemorySemanticProjectionInput, - executor_id: &str, - purpose: &str, - acquired_at: &str, -) -> Result { - crate::memory_graph::semantic_projector::idunn_acquire_memory_semantic_projection( - canonical_store, - input, - executor_id, - &format!("executor-{}", Uuid::new_v4()), - purpose, - &format!("idunn-{}", Uuid::new_v4()), - acquired_at, - ) -} - #[allow(clippy::too_many_arguments)] pub fn idunn_recover_memory_semantic_projection_from_cultmesh( verse_store: impl AsRef, @@ -7808,6 +7863,64 @@ mod tests { use cultcache_rs::CacheBackingStore; use pretty_assertions::assert_eq; + #[test] + fn reserved_semantic_projector_policy_requires_specialized_exact_writer() -> Result<()> { + let temp = tempfile::tempdir()?; + let store = temp.path().join("verse.ccmp"); + let binary = if cfg!(windows) { + "C:\\epiphany-memory-semantic-projector.exe" + } else { + "/tmp/epiphany-memory-semantic-projector" + }; + let exact = EpiphanyCultMeshManagedServicePolicyEntry { + schema_version: EPIPHANY_CULTMESH_MANAGED_SERVICE_POLICY_SCHEMA_VERSION.to_string(), + policy_id: "managed-service-policy-epiphany-memory-semantic-projector-service".into(), + service_id: EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID.into(), + owner_daemon_id: "epiphany-daemon-supervisor".into(), + command: binary.into(), + args: vec![ + "serve", + "--agent-store", + "mind.ccmp", + "--runtime-store", + "modeling.ccmp", + "--local-verse-store", + "verse.ccmp", + "--runtime-id", + "local", + "--interval-seconds", + "60", + ] + .into_iter() + .map(str::to_string) + .collect(), + cwd: None, + enabled: true, + restart_mode: "always".into(), + cooldown_seconds: 0, + backoff_multiplier: 1, + stdout_artifact: "projector.stdout.log".into(), + stderr_artifact: "projector.stderr.log".into(), + updated_at_utc: "2026-07-15T12:00:00Z".into(), + private_state_exposed: false, + notes: vec![], + }; + assert!( + write_epiphany_cultmesh_managed_service_policy(&store, "local", exact.clone()).is_err() + ); + let mut forged = exact.clone(); + forged.command = "arbitrary.exe".into(); + assert!( + write_epiphany_cultmesh_semantic_projector_service_policy(&store, "local", forged) + .is_err() + ); + assert!( + write_epiphany_cultmesh_semantic_projector_service_policy(&store, "local", exact) + .is_ok() + ); + Ok(()) + } + fn semantic_health_input( store: &Path, swarm_id: &str, @@ -8094,14 +8207,17 @@ mod tests { )?; assert_eq!(pending.status, "pending"); - let claim = idunn_acquire_memory_semantic_projection_for_local_supervisor( - &canonical, - &input, - "executor-a", - "execute", - "2026-07-15T12:01:00Z", - )? - .claim; + let claim = + crate::memory_graph::semantic_projector::idunn_acquire_memory_semantic_projection( + &canonical, + &input, + "executor-a", + "executor-a-incarnation", + "execute", + "idunn-test-incarnation", + "2026-07-15T12:01:00Z", + )? + .claim; let raw_receipt = crate::MemorySemanticIndexReceipt { schema_version: crate::MEMORY_SEMANTIC_INDEX_RECEIPT_SCHEMA_VERSION.to_string(), receipt_id: "receipt-four-state".to_string(), @@ -8144,14 +8260,17 @@ mod tests { assert_eq!(ready.status, "ready"); assert!(ready.query_eligible_display_only); - let repair = idunn_acquire_memory_semantic_projection_for_local_supervisor( - &canonical, - &input, - "executor-b", - "repair", - "2026-07-15T12:03:00Z", - )? - .claim; + let repair = + crate::memory_graph::semantic_projector::idunn_acquire_memory_semantic_projection( + &canonical, + &input, + "executor-b", + "executor-b-incarnation", + "repair", + "idunn-test-incarnation", + "2026-07-15T12:03:00Z", + )? + .claim; crate::memory_graph::semantic_projector::fail_memory_semantic_projection_claim( &canonical, &repair.claim_id, @@ -11080,14 +11199,17 @@ mod tests { 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 claim = idunn_acquire_memory_semantic_projection_for_local_supervisor( - &canonical, - &input, - "executor-old", - "execute", - "2026-07-15T12:00:00Z", - )? - .claim; + let claim = + crate::memory_graph::semantic_projector::idunn_acquire_memory_semantic_projection( + &canonical, + &input, + "executor-old", + "provider-old", + "execute", + "idunn-test-incarnation", + "2026-07-15T12:00:00Z", + )? + .claim; let status = EpiphanyCultMeshDaemonStatusEntry { schema_version: EPIPHANY_CULTMESH_DAEMON_STATUS_SCHEMA_VERSION.to_string(), daemon_id: "epiphany-memory-semantic-projector".to_string(), diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 39376135..5481498b 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -27,6 +27,7 @@ mod repo_model_gateway; mod retrieval; mod runtime_spine; mod semantic_backend; +mod semantic_projector_service; mod soul_gateway; mod state_ledger; mod state_update; @@ -429,7 +430,6 @@ pub use cultmesh_integration::epiphany_cultmesh_substrate_gate_contracts; pub use cultmesh_integration::epiphany_cultmesh_verse_policies; pub use cultmesh_integration::epiphany_local_verse_work_loop_summary; pub use cultmesh_integration::epiphany_service_execution_audit_report; -pub use cultmesh_integration::idunn_acquire_memory_semantic_projection_for_local_supervisor; pub use cultmesh_integration::idunn_recover_memory_semantic_projection_from_cultmesh; pub use cultmesh_integration::load_arrival_latest_epiphany_cultmesh_bifrost_artifact_acceptance_receipt; pub use cultmesh_integration::load_arrival_latest_epiphany_cultmesh_bifrost_body_change_publication_intent; @@ -537,6 +537,7 @@ pub use cultmesh_integration::write_epiphany_cultmesh_operator_run_receipt; pub use cultmesh_integration::write_epiphany_cultmesh_operator_snapshot; pub use cultmesh_integration::write_epiphany_cultmesh_persona_speech_audit; pub use cultmesh_integration::write_epiphany_cultmesh_role_review_event; +pub use cultmesh_integration::write_epiphany_cultmesh_semantic_projector_service_policy; pub use cultmesh_integration::write_epiphany_cultmesh_soul_contracts; pub use cultmesh_integration::write_epiphany_cultmesh_status; pub use cultmesh_integration::write_epiphany_cultmesh_substrate_gate_contracts; @@ -664,6 +665,10 @@ pub use memory_graph::MemorySemanticProjectionReadiness; pub use memory_graph::MemorySemanticProjectionSourceHead; pub use memory_graph::MemorySemanticProjectorAcquisition; pub use memory_graph::MemorySemanticProjectorExecutorGrant; +pub use memory_graph::MemorySemanticProjectorPulseClassification; +pub use memory_graph::MemorySemanticProjectorPulseInspection; +pub use memory_graph::MemorySemanticProjectorPulseOutcome; +pub use memory_graph::MemorySemanticProjectorPulseStatus; pub use memory_graph::MemorySemanticProjectorRecoveryAuthorization; pub use memory_graph::RepoFrontierAdoptedPlan; pub use memory_graph::RepoFrontierItem; @@ -689,7 +694,6 @@ pub use memory_graph::derive_memory_semantic_projection_health; pub use memory_graph::derive_memory_semantic_projection_obligation; pub use memory_graph::derive_repo_model_patch; pub use memory_graph::derive_semantic_projection; -pub use memory_graph::execute_memory_semantic_projection; pub use memory_graph::lifecycle_allowed_for_profile; pub use memory_graph::load_memory_graph_entry; pub use memory_graph::load_memory_graph_snapshot; @@ -924,6 +928,9 @@ pub use runtime_spine::select_repo_frontier_work_proposal_for_modeling; pub use runtime_spine::validate_hands_action_authority; pub use runtime_spine::write_runtime_hello_frame; pub use runtime_spine::write_runtime_schema_catalog_json; +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; diff --git a/epiphany-core/src/memory_graph/mod.rs b/epiphany-core/src/memory_graph/mod.rs index 62cd2c46..68f121ef 100644 --- a/epiphany-core/src/memory_graph/mod.rs +++ b/epiphany-core/src/memory_graph/mod.rs @@ -6,6 +6,7 @@ pub mod profiles; pub mod semantic_index; pub mod semantic_projection; pub mod semantic_projector; +pub mod semantic_projector_pulse; pub mod store; pub mod validation; @@ -50,6 +51,7 @@ pub use profiles::refresh_or_validate_repo_memory_graph; pub use semantic_index::*; pub use semantic_projection::*; pub use semantic_projector::*; +pub use semantic_projector_pulse::*; pub use store::EpiphanyMemoryGraphEntry; pub use store::MEMORY_GRAPH_KEY; pub use store::MEMORY_GRAPH_SCHEMA_VERSION; diff --git a/epiphany-core/src/memory_graph/semantic_projector.rs b/epiphany-core/src/memory_graph/semantic_projector.rs index 8bf6dbe3..be0728b7 100644 --- a/epiphany-core/src/memory_graph/semantic_projector.rs +++ b/epiphany-core/src/memory_graph/semantic_projector.rs @@ -801,6 +801,98 @@ pub fn load_memory_semantic_projection_readiness( ) } +pub(crate) fn classify_memory_semantic_projection_for_pulse( + store_path: &Path, + input: &MemorySemanticProjectionInput, +) -> Result { + validate_memory_semantic_projection_obligation(&input.obligation)?; + let envelopes = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + let persisted = decode_one::( + &envelopes, + &input.obligation.obligation_id, + )?; + if persisted.as_ref() != Some(&input.obligation) { + return Ok(super::MemorySemanticProjectorPulseClassification::Stale); + } + for expected in &input.authority.envelopes { + if envelopes + .iter() + .find(|row| row.r#type == expected.r#type && row.key == expected.key) + != Some(expected) + { + return Ok(super::MemorySemanticProjectorPulseClassification::Stale); + } + } + let scope_id = projection_scope_id(&input.obligation.swarm_id, &input.obligation.partition)?; + if let Some(claim) = decode_one::(&envelopes, &scope_id)? { + validate_memory_semantic_projection_claim(&claim)?; + if claim.scope_id != scope_id { + return Err(anyhow!("semantic projector pulse claim key disagrees")); + } + if claim.obligation_id == input.obligation.obligation_id { + match claim.status.as_str() { + "running" => return Ok(super::MemorySemanticProjectorPulseClassification::Running), + "succeeded" => { + return Ok(super::MemorySemanticProjectorPulseClassification::Succeeded); + } + _ => {} + } + } + } + let health = super::derive_memory_semantic_projection_health( + &input.obligation, + &input.authority.head, + &decode_all::(&envelopes)?, + &decode_all::(&envelopes)?, + )?; + Ok(match health.status { + super::MemorySemanticProjectionHealthStatus::Pending => { + super::MemorySemanticProjectorPulseClassification::Pending + } + super::MemorySemanticProjectionHealthStatus::Failed => { + super::MemorySemanticProjectorPulseClassification::Failed + } + super::MemorySemanticProjectionHealthStatus::Ready => { + super::MemorySemanticProjectorPulseClassification::Ready + } + super::MemorySemanticProjectionHealthStatus::Stale => { + super::MemorySemanticProjectorPulseClassification::Stale + } + }) +} + +pub(crate) fn owned_running_memory_semantic_projection_claim( + store_path: &Path, + input: &MemorySemanticProjectionInput, + executor_id: &str, + executor_incarnation: &str, +) -> Result> { + let envelopes = SingleFileMessagePackBackingStore::new(store_path).pull_all()?; + let scope_id = projection_scope_id(&input.obligation.swarm_id, &input.obligation.partition)?; + let Some(claim) = decode_one::(&envelopes, &scope_id)? else { + return Ok(None); + }; + validate_memory_semantic_projection_claim(&claim)?; + if claim.status != "running" + || claim.obligation_id != input.obligation.obligation_id + || claim.executor_id != executor_id + || claim.executor_incarnation != executor_incarnation + { + return Ok(None); + } + authenticate_claim_authority_from_envelopes(&envelopes, &claim)?; + for expected in &input.authority.envelopes { + if envelopes + .iter() + .find(|row| row.r#type == expected.r#type && row.key == expected.key) + != Some(expected) + { + return Err(anyhow!("owned running claim canonical authority advanced")); + } + } + Ok(Some(claim.claim_id)) +} + #[allow(clippy::too_many_arguments)] pub(crate) fn idunn_acquire_memory_semantic_projection( store_path: impl AsRef, @@ -973,7 +1065,7 @@ pub(crate) fn idunn_acquire_memory_semantic_projection( Ok(MemorySemanticProjectorAcquisition { grant, claim }) } -pub fn execute_memory_semantic_projection( +pub(crate) fn execute_memory_semantic_projection( store_path: impl AsRef, input: &MemorySemanticProjectionInput, claim_id: &str, diff --git a/epiphany-core/src/memory_graph/semantic_projector_pulse.rs b/epiphany-core/src/memory_graph/semantic_projector_pulse.rs new file mode 100644 index 00000000..7e095303 --- /dev/null +++ b/epiphany-core/src/memory_graph/semantic_projector_pulse.rs @@ -0,0 +1,472 @@ +use super::MemorySemanticProjectionInput; +use anyhow::Result; +use std::sync::atomic::{AtomicBool, Ordering}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MemorySemanticProjectorPulseClassification { + Pending, + Failed, + Ready, + Running, + RunningOwned { claim_id: String }, + Succeeded, + Stale, +} + +impl MemorySemanticProjectorPulseClassification { + fn automatic_purpose(&self) -> Option<&'static str> { + match self { + Self::Pending | Self::Failed => Some("execute"), + Self::Ready + | Self::Running + | Self::RunningOwned { .. } + | Self::Succeeded + | Self::Stale => None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MemorySemanticProjectorPulseInspection { + pub scope_id: String, + pub classification: Option, + pub error: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MemorySemanticProjectorPulseStatus { + Idle, + Executed, + Contended, + Refused, + Busy, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MemorySemanticProjectorPulseOutcome { + pub status: MemorySemanticProjectorPulseStatus, + pub selected_scope_id: Option, + pub inspections: Vec, + pub error: Option, +} + +pub(crate) trait MemorySemanticProjectorPulsePort { + fn classify( + &self, + input: &MemorySemanticProjectionInput, + ) -> Result; + + /// `Ok(None)` means another pulse won the exact acquisition CAS. + fn acquire( + &self, + input: &MemorySemanticProjectionInput, + purpose: &str, + ) -> Result>; + + fn execute(&self, input: &MemorySemanticProjectionInput, claim_id: &str) -> Result<()>; +} + +pub(crate) struct MemorySemanticProjectorPulser

{ + pub(crate) port: P, + active: AtomicBool, +} + +impl

MemorySemanticProjectorPulser

+where + P: MemorySemanticProjectorPulsePort, +{ + pub(crate) fn new(port: P) -> Self { + Self { + port, + active: AtomicBool::new(false), + } + } + + pub(crate) fn pulse( + &self, + sealed_inputs: &[MemorySemanticProjectionInput], + fairness_cursor: Option<&str>, + ) -> MemorySemanticProjectorPulseOutcome { + if self + .active + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + 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::>(); + 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 { + 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), + None, + ); + } + 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:#}")), + ); + } + }; + 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), + None, + ); + } + if let Some(error) = first_source_error { + outcome( + MemorySemanticProjectorPulseStatus::Refused, + inspections, + None, + Some(error), + ) + } else { + outcome( + MemorySemanticProjectorPulseStatus::Idle, + inspections, + None, + None, + ) + } + } +} + +struct PulseGuard<'a>(&'a AtomicBool); + +impl Drop for PulseGuard<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +fn scope_key(input: &MemorySemanticProjectionInput) -> String { + format!( + "{}:{}", + input.obligation().swarm_id, + input.obligation().partition + ) +} + +fn outcome( + status: MemorySemanticProjectorPulseStatus, + inspections: Vec, + selected_scope_id: Option, + error: Option, +) -> MemorySemanticProjectorPulseOutcome { + MemorySemanticProjectorPulseOutcome { + status, + selected_scope_id, + inspections, + error, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory_graph::semantic_projector::MemorySemanticProjectionAuthoritySnapshot; + use crate::memory_graph::semantic_projector::{ + classify_memory_semantic_projection_for_pulse, semantic_projector_cache, + }; + use crate::{ + MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION, MemorySemanticProjectionObligation, + MemorySemanticProjectionSourceHead, SEMANTIC_PROJECTION_SCHEMA_VERSION, + }; + use cultcache_rs::CultCache; + use std::sync::{Arc, Barrier, Mutex}; + use tempfile::tempdir; + + fn input(partition: &str) -> MemorySemanticProjectionInput { + let obligation = MemorySemanticProjectionObligation { + schema_version: MEMORY_SEMANTIC_PROJECTION_OBLIGATION_SCHEMA_VERSION.to_string(), + obligation_id: format!("obligation-{partition}"), + swarm_id: "swarm-a".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![], + }, + obligation, + } + } + + struct MockPort { + classifications: Mutex< + Vec>, + >, + acquire_result: Mutex>>, + acquisitions: Mutex>, + executions: Mutex>, + execute_barriers: Option<(Arc, Arc)>, + } + + impl MockPort { + fn new(classifications: Vec) -> Self { + Self { + classifications: Mutex::new(classifications.into_iter().map(Ok).collect()), + acquire_result: Mutex::new(Some(Some("claim-1".to_string()))), + acquisitions: Mutex::new(vec![]), + executions: Mutex::new(vec![]), + execute_barriers: None, + } + } + } + + impl MemorySemanticProjectorPulsePort for MockPort { + fn classify( + &self, + _input: &MemorySemanticProjectionInput, + ) -> Result { + self.classifications + .lock() + .unwrap() + .remove(0) + .map_err(anyhow::Error::msg) + } + + fn acquire( + &self, + input: &MemorySemanticProjectionInput, + purpose: &str, + ) -> Result> { + assert_eq!(purpose, "execute"); + self.acquisitions.lock().unwrap().push(scope_key(input)); + Ok(self.acquire_result.lock().unwrap().take().unwrap_or(None)) + } + + fn execute(&self, _input: &MemorySemanticProjectionInput, claim_id: &str) -> Result<()> { + self.executions.lock().unwrap().push(claim_id.to_string()); + if let Some((entered, release)) = &self.execute_barriers { + entered.wait(); + release.wait(); + } + Ok(()) + } + } + + #[test] + fn decision_table_never_runs_ready_running_succeeded_or_stale() { + for classification in [ + MemorySemanticProjectorPulseClassification::Ready, + MemorySemanticProjectorPulseClassification::Running, + MemorySemanticProjectorPulseClassification::Succeeded, + MemorySemanticProjectorPulseClassification::Stale, + ] { + let pulser = MemorySemanticProjectorPulser::new(MockPort::new(vec![classification])); + let outcome = pulser.pulse(&[input("mind")], None); + assert_eq!(outcome.status, MemorySemanticProjectorPulseStatus::Idle); + assert!(pulser.port.acquisitions.lock().unwrap().is_empty()); + assert!(pulser.port.executions.lock().unwrap().is_empty()); + } + } + + #[test] + 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 mut cache: CultCache = semantic_projector_cache(&store)?; + cache.put(¤t.obligation().obligation_id, current.obligation())?; + assert_eq!( + classify_memory_semantic_projection_for_pulse(&store, ¤t)?, + MemorySemanticProjectorPulseClassification::Pending + ); + let mut stale = current.clone(); + stale.obligation.source_generation += 1; + assert_eq!( + classify_memory_semantic_projection_for_pulse(&store, &stale)?, + MemorySemanticProjectorPulseClassification::Stale + ); + Ok(()) + } + + #[test] + fn pending_and_failed_select_one_global_action_with_rotating_fairness() { + for classification in [ + MemorySemanticProjectorPulseClassification::Pending, + MemorySemanticProjectorPulseClassification::Failed, + ] { + let pulser = MemorySemanticProjectorPulser::new(MockPort::new(vec![classification])); + let outcome = pulser.pulse(&[input("modeling")], None); + 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] + fn contention_consumes_the_one_action_slot_without_false_execution() { + 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); + assert_eq!( + outcome.status, + MemorySemanticProjectorPulseStatus::Contended + ); + assert_eq!(outcome.inspections.len(), 1); + assert!(pulser.port.executions.lock().unwrap().is_empty()); + } + + #[test] + fn owned_running_claim_resumes_without_a_second_acquisition() { + let pulser = MemorySemanticProjectorPulser::new(MockPort::new(vec![ + MemorySemanticProjectorPulseClassification::RunningOwned { + claim_id: "recovered-claim".to_string(), + }, + ])); + let outcome = pulser.pulse(&[input("mind")], None); + assert_eq!(outcome.status, MemorySemanticProjectorPulseStatus::Executed); + assert!(pulser.port.acquisitions.lock().unwrap().is_empty()); + assert_eq!( + pulser.port.executions.lock().unwrap().as_slice(), + ["recovered-claim"] + ); + } + + #[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)); + let release = Arc::new(Barrier::new(2)); + let mut port = MockPort::new(vec![MemorySemanticProjectorPulseClassification::Pending]); + port.execute_barriers = Some((entered.clone(), release.clone())); + let pulser = Arc::new(MemorySemanticProjectorPulser::new(port)); + let worker = { + let pulser = pulser.clone(); + std::thread::spawn(move || pulser.pulse(&[input("mind")], None)) + }; + entered.wait(); + let busy = pulser.pulse(&[input("modeling")], None); + assert_eq!(busy.status, MemorySemanticProjectorPulseStatus::Busy); + release.wait(); + assert_eq!( + worker.join().unwrap().status, + MemorySemanticProjectorPulseStatus::Executed + ); + assert_eq!(pulser.port.executions.lock().unwrap().len(), 1); + } +} diff --git a/epiphany-core/src/semantic_projector_service.rs b/epiphany-core/src/semantic_projector_service.rs new file mode 100644 index 00000000..6621742b --- /dev/null +++ b/epiphany-core/src/semantic_projector_service.rs @@ -0,0 +1,427 @@ +use crate::memory_graph::semantic_projector::{ + classify_memory_semantic_projection_for_pulse, execute_memory_semantic_projection, + idunn_acquire_memory_semantic_projection, owned_running_memory_semantic_projection_claim, +}; +use crate::memory_graph::{ + MemorySemanticProjectorPulseClassification, MemorySemanticProjectorPulseOutcome, + MemorySemanticProjectorPulsePort, MemorySemanticProjectorPulser, +}; +use crate::{ + MemorySemanticIndexConfig, MemorySemanticProjectionInput, + agent_memory_semantic_projection_input, runtime_modeling_semantic_projection_input, +}; +use anyhow::{Result, anyhow}; +use chrono::{SecondsFormat, Utc}; +use sha2::{Digest, Sha256}; +#[cfg(windows)] +use std::ffi::OsStr; +#[cfg(unix)] +use std::fs::File; +#[cfg(unix)] +use std::os::fd::AsRawFd; +#[cfg(windows)] +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use uuid::Uuid; + +#[cfg(windows)] +use windows_sys::Win32::Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GetLastError, HANDLE}; +#[cfg(windows)] +use windows_sys::Win32::System::Threading::{CreateMutexW, ReleaseMutex}; + +/// Trusted in-process authority held by the one Idunn-managed projector body. +/// The constructor generates process-stable incarnations; callers cannot label +/// themselves as an existing Idunn or executor incarnation. +const SEMANTIC_PROJECTOR_EXECUTOR_ID: &str = "epiphany-memory-semantic-projector"; + +struct LocalIdunnSemanticProjectorSession { + mind_store: PathBuf, + modeling_store: PathBuf, + executor_id: String, + executor_incarnation: String, + idunn_incarnation: String, + config: MemorySemanticIndexConfig, +} + +struct SemanticProjectorSingletonGuard { + #[cfg(windows)] + handle: HANDLE, + #[cfg(unix)] + file: File, +} + +impl Drop for SemanticProjectorSingletonGuard { + fn drop(&mut self) { + #[cfg(windows)] + unsafe { + let _ = ReleaseMutex(self.handle); + CloseHandle(self.handle); + } + #[cfg(unix)] + unsafe { + let _ = libc::flock(self.file.as_raw_fd(), libc::LOCK_UN); + } + } +} + +fn acquire_semantic_projector_singleton( + mind_store: impl AsRef, + modeling_store: impl AsRef, +) -> Result { + 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() + ) + ); + #[cfg(windows)] + { + let name = OsStr::new(&format!("Global\\EpiphanySemanticProjector-{identity}")) + .encode_wide() + .chain(std::iter::once(0)) + .collect::>(); + let handle = unsafe { CreateMutexW(std::ptr::null_mut(), 1, name.as_ptr()) }; + if handle.is_null() { + return Err(anyhow!( + "semantic projector singleton mutex creation failed: {}", + unsafe { GetLastError() } + )); + } + if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS { + unsafe { CloseHandle(handle) }; + return Err(anyhow!( + "semantic projector owner already exists for canonical store pair" + )); + } + return Ok(SemanticProjectorSingletonGuard { handle }); + } + #[cfg(unix)] + { + let path = std::env::temp_dir().join(format!("epiphany-semantic-{identity}.lock")); + let file = File::options() + .create(true) + .read(true) + .write(true) + .open(path)?; + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + return Err(anyhow!( + "semantic projector owner already exists for canonical store pair" + )); + } + return Ok(SemanticProjectorSingletonGuard { file }); + } + #[allow(unreachable_code)] + Err(anyhow!( + "semantic projector singleton is unsupported on this platform" + )) +} + +impl LocalIdunnSemanticProjectorSession { + fn new( + mind_store: impl AsRef, + modeling_store: impl AsRef, + executor_id: impl Into, + config: MemorySemanticIndexConfig, + ) -> Result { + 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()), + idunn_incarnation: format!("idunn-{}", Uuid::new_v4()), + config, + }) + } + + pub fn provider_incarnation(&self) -> &str { + &self.executor_incarnation + } + + 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:?}" + )), + } + } +} + +/// The only public authority-bearing semantic projector body. Construction +/// atomically takes the host-wide singleton before minting a process session, +/// and the guard remains owned for the body's full lifetime. +pub struct SemanticProjectorServiceBody { + _singleton: SemanticProjectorSingletonGuard, + pulser: MemorySemanticProjectorPulser, + provider_incarnation: String, +} + +pub struct SemanticProjectorServicePulse { + pub outcome: MemorySemanticProjectorPulseOutcome, + pub inputs: Vec, + pub source_fault_count: u32, +} + +impl SemanticProjectorServiceBody { + pub fn new( + mind_store: impl AsRef, + modeling_store: impl AsRef, + config: MemorySemanticIndexConfig, + ) -> Result { + let singleton = acquire_semantic_projector_singleton(&mind_store, &modeling_store)?; + let mind_input = agent_memory_semantic_projection_input(&mind_store)?; + let modeling_input = runtime_modeling_semantic_projection_input(&modeling_store)?; + validate_semantic_projector_source_pair(&mind_input, &modeling_input)?; + let session = LocalIdunnSemanticProjectorSession::new( + mind_store, + modeling_store, + SEMANTIC_PROJECTOR_EXECUTOR_ID, + config, + )?; + let provider_incarnation = session.provider_incarnation().to_string(); + Ok(Self { + _singleton: singleton, + pulser: MemorySemanticProjectorPulser::new(session), + provider_incarnation, + }) + } + + pub fn provider_incarnation(&self) -> &str { + &self.provider_incarnation + } + + pub fn pulse(&self, fairness_cursor: Option<&str>) -> SemanticProjectorServicePulse { + let session = &self.pulser.port; + let mut source_fault_count = 0; + let mut inputs = Vec::with_capacity(2); + match agent_memory_semantic_projection_input(&session.mind_store) { + Ok(input) => inputs.push(input), + Err(_) => source_fault_count += 1, + } + match runtime_modeling_semantic_projection_input(&session.modeling_store) { + Ok(input) => inputs.push(input), + Err(_) => source_fault_count += 1, + } + if inputs.len() == 2 + && validate_semantic_projector_source_pair(&inputs[0], &inputs[1]).is_err() + { + source_fault_count += 2; + inputs.clear(); + } + let outcome = self.pulser.pulse(&inputs, fairness_cursor); + SemanticProjectorServicePulse { + outcome, + inputs, + source_fault_count, + } + } +} + +impl MemorySemanticProjectorPulsePort for LocalIdunnSemanticProjectorSession { + fn classify( + &self, + input: &MemorySemanticProjectionInput, + ) -> Result { + let store = self.store_for(input)?; + let classification = classify_memory_semantic_projection_for_pulse(store, input)?; + if classification == MemorySemanticProjectorPulseClassification::Running { + if let Some(claim_id) = owned_running_memory_semantic_projection_claim( + store, + input, + &self.executor_id, + &self.executor_incarnation, + )? { + return Ok(MemorySemanticProjectorPulseClassification::RunningOwned { claim_id }); + } + } + Ok(classification) + } + + fn acquire( + &self, + input: &MemorySemanticProjectionInput, + purpose: &str, + ) -> Result> { + let store = self.store_for(input)?; + match idunn_acquire_memory_semantic_projection( + store, + input, + &self.executor_id, + &self.executor_incarnation, + purpose, + &self.idunn_incarnation, + &Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true), + ) { + Ok(acquisition) => Ok(Some(acquisition.claim.claim_id)), + Err(_error) + if classify_memory_semantic_projection_for_pulse(store, input)? + == MemorySemanticProjectorPulseClassification::Running => + { + Ok(None) + } + Err(error) => Err(error), + } + } + + fn execute(&self, input: &MemorySemanticProjectionInput, claim_id: &str) -> Result<()> { + execute_memory_semantic_projection(self.store_for(input)?, input, claim_id, &self.config)?; + Ok(()) + } +} + +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, label: &str) -> Result { + let path = path.as_ref(); + if !path.is_file() { + return Err(anyhow!( + "{label} canonical store is missing: {}", + path.display() + )); + } + path.canonicalize() + .map_err(|error| anyhow!("{label} canonical store identity is unavailable: {error}")) +} + +#[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 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()); + drop(first); + assert!(acquire_semantic_projector_singleton(&mind, &modeling).is_ok()); + Ok(()) + } + + #[test] + fn authority_body_has_no_public_raw_session_or_session_local_windows_lock() { + let source = include_str!("semantic_projector_service.rs"); + let public_session = ["pub struct Local", "IdunnSemanticProjectorSession"].concat(); + let public_singleton = ["pub fn acquire_semantic", "_projector_singleton"].concat(); + let local_namespace = ["Local", "\\\\EpiphanySemanticProjector"].concat(); + assert!(!source.contains(&public_session)); + assert!(!source.contains(&public_singleton)); + assert!(!source.contains(&local_namespace)); + assert!(source.contains("Global\\\\EpiphanySemanticProjector")); + assert!(source.contains("pub struct SemanticProjectorServiceBody")); + } +} diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index a9717a4f..f1ed61bf 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1235,17 +1235,64 @@ Eve, and swarm overview remain derived sight and forbidden writers. Initial execution, retry, repair, and recovered execution share the same claim- authenticating projector primitive. -Remaining limits: open-obligation discovery is not yet attached to the Idunn -daemon, no single projector owner is packaged, canonical-store/Qdrant placement -between local and Yggdrasil remains undecided, and local Qdrant remains -overexposed. The low-level mint and recovery primitives are crate-private. -Their public local-supervisor ports generate incarnations internally, but are -still a trusted in-process boundary rather than authenticated OS IPC. Keep them -inside one configured Idunn body until durable service identity owns them. Do -not expose those ports to untrusted Verse peers. Do not deploy two projectors. +## Workstation semantic projector service body (2026-07-15) -Next: add a bounded Idunn pulse that discovers authenticated open Mind and -Modeling obligations without creating demand, runs the same acquire/execute -primitive, republishes sight independently, and reports provider readiness only -after its own heartbeat. Then select and package exactly one deployment -topology. +The open-obligation pulse and single process owner are now implemented as one +workstation-local `epiphany-memory-semantic-projector` body managed by Idunn. +Its constructor requires two distinct canonical files--one Mind store and one +Modeling runtime store--and refuses unless their sealed inputs name the exact +partitions and the same immutable swarm. It takes a host OS singleton for that +canonical pair before minting its process-stable provider/executor incarnation. +Mind and Modeling remain separate authorities, claims, collections, and +receipts; they merely share one survival body. + +Every pulse reloads both canonical inputs. It stores no open-obligation queue +and allows at most one global action, rotating fairly between actionable +partitions. Ready, foreign-running, succeeded, and stale inputs never execute. +Pending and failed inputs acquire exact Idunn authority before using the one +crate-private executor. A running claim owned by the current provider +incarnation resumes directly without minting a second grant; a foreign running +claim remains pressure until exact recovery. Overlapping pulses return busy, +and the serve cooldown begins only after the bounded pulse completes. A fault +loading one source does not turn the other source into false readiness or hide +its valid action. + +The old production mouths are gone: `epiphany-memory-semantic` no longer has an +`index` arm or claim flag, there is no public raw execute function, and the +supervisor no longer exposes general semantic acquisition. Recovery remains a +narrow supervisor action. It authenticates the abandoned claim, exact Idunn +lifecycle intent/receipt, and causally linked replacement-provider heartbeat, +then rotates claim authority only. The running service recognizes that exact +recovered claim as its own and resumes it on a later ordinary pulse. + +Idunn owns a specialized reserved service-policy writer for fixed service id +`epiphany-memory-semantic-projector-service`. It derives the packaged sibling +binary, fixed executor identity, both canonical stores, infinite serve shape, +and restart-always policy. The generic managed-service writer refuses that +reserved id; callers cannot substitute a command, service id, restart mode, or +finite child lifetime. Existing Idunn managed-service reconciliation owns +process survival and lifecycle receipts. The OS singleton prevents a service +and an interactive process from simultaneously owning the same canonical pair. + +Provider heartbeat and per-partition semantic health remain derived sight. +Heartbeat `ready` means the body owns its singleton, validated the source pair, +and completed a healthy pulse/publication pass; it is not semantic query +readiness. Only the canonical success chain admits query. Pulse JSON, health, +heartbeat, Qdrant, Ollama, Eve, and swarm overview cannot create obligations, +grants, recovery, terminal evidence, or readiness. + +Deployment is deliberately not live. The chosen topology is the workstation +beside its canonical stores, with Yggdrasil permitted to supply embedding over +WireGuard. Current local inspection found Docker container `voidbot-qdrant` +stopped with exit code 143. Its name records foreign ownership, so Epiphany did +not restart, adopt, reconfigure, or claim it. No semantic projector service +policy has been published and no restart proof has been claimed. Moving only +the projector to Yggdrasil or starting a second partition/projector body remains +forbidden. + +Next: establish explicit Qdrant ownership and a live workstation-reachable +endpoint, confirm collection compatibility and the Yggdrasil Ollama route, +then publish the reserved projector policy. Run one bounded live pulse, prove +both derived health rows and provider heartbeat, kill the body once, and prove +Idunn restart plus causally linked heartbeat/recovery/resumption. This is a +preflight and survival proof, not permission to call deployment complete. diff --git a/notes/semantic-projector-service-runbook.md b/notes/semantic-projector-service-runbook.md new file mode 100644 index 00000000..1983abfa --- /dev/null +++ b/notes/semantic-projector-service-runbook.md @@ -0,0 +1,106 @@ +# Semantic Projector Service + +## Authority + +One workstation-local `epiphany-memory-semantic-projector` process owns semantic +projection execution for both canonical partitions in one Epiphany swarm: + +- Mind input: `state/agents.msgpack` +- Modeling input: the configured runtime-spine CultCache store +- Derived index: physically separated Mind and Modeling Qdrant collections +- Derived sight: provider-authored CultMesh health and heartbeat events + +Canonical CultCache admission owns projection obligations. Idunn owns process +survival, executor assignment, and explicit fenced recovery. The projector owns +claim-bound Qdrant mutation and terminal evidence. Query admission alone proves +semantic readiness. Qdrant, Ollama, health, heartbeat, Eve, and swarm overview +are not state authority. + +The process must remain beside the canonical stores. Yggdrasil may host Ollama +embedding work over WireGuard, but moving only the projector to Yggdrasil would +split local store authority. Do not install a second projector on Yggdrasil or +one process per partition. + +## Build + +```powershell +$env:CARGO_TARGET_DIR='C:\Users\Meta\.cargo-target-codex' +cargo build --release --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-memory-semantic-projector --bin epiphany-daemon-supervisor +``` + +## Required configuration + +Set these in the Idunn service environment before launch: + +```text +EPIPHANY_QDRANT_URL=http://127.0.0.1:6333 +EPIPHANY_OLLAMA_URL=http://:11435 +``` + +Use the embedding model and collection configuration already consumed by +`MemorySemanticIndexConfig::from_env`. Keep credentials in the service +environment or secret store; never place them in policy arguments or logs. + +## Preflight + +1. Confirm both canonical stores exist and describe the same immutable swarm. +2. Confirm Qdrant is reachable from the workstation and its collection metadata + matches the configured embedding dimensions. +3. Confirm Ollama is reachable and the configured embedding model is loaded. +4. Confirm no projector process already owns the canonical store pair. The + binary also enforces this with a host OS singleton. On Windows this is a + `Global\\` named mutex shared by service and interactive sessions; failure to + create or open it fails closed before a provider incarnation exists. +5. Confirm the local Verse store is bootstrapped and Idunn's managed-service + reconciler is running. + +Current local observation on 2026-07-15: Docker reports `voidbot-qdrant` as +`Exited (143)`. Its name indicates foreign service ownership, so this runbook +does not restart or silently adopt it. Deployment remains blocked until an +explicit Epiphany-owned or intentionally shared Qdrant endpoint is live. + +## Publish the typed service policy + +```powershell +$supervisor = '.\target\release\epiphany-daemon-supervisor.exe' +& $supervisor semantic-projector-service-policy ` + --store .\.epiphany-run\cultmesh\local-verse.ccmp ` + --runtime-id epiphany-local ` + --agent-store .\state\agents.msgpack ` + --runtime-store ` + --loop-interval-seconds 60 +``` + +This command writes the fixed +`epiphany-memory-semantic-projector-service` managed-service policy with +`restartMode=always`. Its generated child command contains both canonical +stores. The projector executable is derived as the packaged sibling of the +running supervisor and must already exist. Caller-supplied executable paths, +service IDs, restart modes, arbitrary child arguments, and finite iteration +limits do not own this service shape. The generic managed-service writer +refuses the reserved service id. + +Idunn's existing `managed-service-serve` loop reconciles that policy and writes +the startup lifecycle receipt identifier into the child environment. The +projector publishes its first provider heartbeat only after it holds the OS +singleton and validates both canonical inputs. + +## Recovery + +Use `semantic-recover` only with the exact abandoned claim, successful Idunn +restart receipt, and causally linked provider heartbeat. Recovery always assigns +the fixed packaged projector executor identity. It rotates authority; it does +not execute projection or mint readiness. The running projector resumes its own +recovered claim on the next pulse. + +## Proof after launch + +- Read the fixed managed-service policy and latest lifecycle receipt. +- Read the projector heartbeat for its current provider incarnation. +- Read both named semantic-health projections. +- Run a Mind and Modeling semantic query and confirm the query gate reports + semantic ranking only when each newest exact obligation/success chain is + authenticated. +- Stop the process once, let Idunn restart it, and verify a newer provider + heartbeat names the startup lifecycle receipt. Do not use command exit zero as + readiness. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 6acfdfd4..3563743c 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index f8e3f80a..35cc93e6 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -714,4 +714,4 @@ current_status: - Service lifecycle receipt history is now event-only: `load_epiphany_cultmesh_daemon_service_lifecycle_receipts` filters out the `epiphany-local/daemon-service-lifecycle-receipt/latest` mirror, while `load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt` remains the latest-state reader. Focused unit test `service_lifecycle_receipt_history_excludes_latest_mirror` proves two per-receipt writes return exactly two history records and latest points at the second. Fresh smoke `verse-query-lifecycle-history-filter-smoke` and live overview/triage `local-20260618-145632-497-efac6f0d` / `local-20260618-145632-321-867947af` prove compact swarm sights still expose service lifecycle attention plus the present elevated runbook artifact without daemon pokes or service mutation. Do not use a broad unscoped cargo test filter for this check on Windows; it fans out across bin harnesses and hit a broken pipe during this pass. - `epiphany-verse-query seed-compact` is the compact seed receipt for wrappers and read-only rites. The older `seed` command still prints the full local Verse context for explicit debugging, but compact wrapper modes now avoid full `seed`/final `query` readback after the combined overview proof exposed Windows debug stack overflow from full-context serialization pressure. last_completed_repo_swarm_cut: Huginn live-fire has crossed the first real repo Body from Persona pressure to branch-local Hands commit and Soul/Mind closure, and now has repeatable closure and redacted-public-proof mouths. On `E:\Projects\Huginn` branch `epiphany/huginn/first-awakening`, `tools/epiphany_local_run.ps1 -Mode repo-persona-intake` accepted item `huginn-inspection-readback-livefire`, Weksa/Persona intake remained sealed, and `epiphany-work derive-plan` lowered it to model-authored safe family `repo.status_section` for `README.md` only. `tools/epiphany_local_run.ps1 -Mode repo-swarm-run` advanced four bounded pulses: run-from-plan, adopt-from-plan, execute-from-plan, and close-from-execute. Huginn commit `e9b07c38fceabbdc89ea35c2156326c80c0393a2` updated only `README.md`; closure receipt `.epiphany\work\work-close-huginn-inspection-readback-livefire.json` records status `closed`, Soul verdict `passed`, Mind state commit `repo-work-close-huginn-inspection-readback-livefire-mind-commit`, safe family `repo.status_section`, path scope `README.md`, Bifrost publication gate, and `privateStateExposed=false`. Verification also ran Huginn's TypeScript compiler through concrete Node path: `C:\Program Files\nodejs\node.exe E:\Projects\Huginn\node_modules\typescript\bin\tsc -p tsconfig.json` passed. Native verifier `epiphany-repo-livefire-closure-smoke --workspace E:\Projects\Huginn --item huginn-inspection-readback-livefire --expected-path README.md --expected-family repo.status_section --expected-gate awaiting-publication --expected-blocker bifrost-publication-missing` checks closure receipt, Mind map entry, overview gate/blocker, authority seals, and `git show` changed paths, returning `status=ok`, `soulVerdict=passed`, `publicationGate=Bifrost`, and `privateStateExposed=false`. Wrapper `tools/epiphany_local_run.ps1 -Mode repo-livefire-closure -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exposes the same read-only proof through the local operator mouth; artifact `local-20260621-190156-803-2f85ba15` printed commit, path, gate, blocker, Soul verdict, Mind commit receipt, and `privateStateExposed=False` without push, merge, publication, or target mutation. New wrapper `tools/epiphany_local_run.ps1 -Mode repo-work-public-proof -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exports the redacted proof bundle and repo-local Verse index without publishing; artifact `local-20260621-190645-345-4555b1dc` wrote `.epiphany\public\proof-bundles\repo-work-public-proof-huginn-inspection-readback-livefire.json`, proof id `repo-work-public-proof-huginn-inspection-readback-livefire`, SHA-256 `857545b199f3e37eb06c2e757e5cfc201958e46667bb1f8403fd333a22620f63`, nine artifact rows, zero publication rows, and `privateStateExposed=False`. swarm overview readback `local-20260621-190701-140-b9519ec6` sees the `REPO-WORK-PUBLIC-PROOF` row and action row from Huginn's repo-local Verse with the same SHA-256 while Bifrost publication remains missing. Launcher compact modes are now named compact operator-context modes instead of read-only modes, and `bifrost-public-proof` summaries print item, target public Verse, room, proof SHA-256, review receipts, and credit receipts so publication receipts are auditable without claiming upstream sync. - next_action: Complete semantic projection physiology on the landed atomic admission, physically epoch-isolated projector, exact query gate, provider-status ownership cut, non-authoritative CultMesh health sight, and typed Idunn executor/recovery authority. Mind and Modeling alone emit canonical obligations. Idunn acquisition reauthenticates the sealed current source and CAS-writes its authority envelopes with a consumed grant plus claim/attempt bound to exact scope, obligation, executor incarnation, purpose, predecessor, and epoch; historical obligations cannot reopen advanced heads, and execute cannot become repair. Execution accepts the authenticated claim id rather than treating an executor label as capability. Recovery authenticates the exact Idunn poke intent/awaiting-heartbeat receipt and a newer provider-authored ready heartbeat that names that receipt as its startup cause, then one CAS consumes their store/input/claim-bound authorization, fails the abandoned attempt, and advances the claim epoch; recovery cannot execute or mint readiness. The projector alone owns claim-bound Qdrant mutation and terminal evidence, while the opaque query gate authenticates the complete succeeded grant-or-recovery/claim/attempt/receipt chain. Next add bounded open-obligation discovery for both Mind and Modeling without letting a timer create demand, then package exactly one projector owner after resolving local-versus-Yggdrasil canonical-store and Qdrant placement. Low-level mint/recovery are crate-private; public local-supervisor ports generate incarnations internally but remain a trusted in-process boundary, not authenticated OS IPC. Keep them inside one configured Idunn body until durable service identity owns them. Yggdrasil has GPU Ollama/Odin/Idunn but no Qdrant or Epiphany target; local Qdrant is healthy but overexposed on all interfaces. Timers, collection metadata, point counts, paths, CLI labels, Idunn liveness, CultMesh mirrors, Eve/swarm overview, and payload prose own no obligation, recovery, completion, or readiness. + next_action: Complete the live preflight and survival proof for the landed workstation semantic projector service body. One Idunn-managed `epiphany-memory-semantic-projector` process now owns execution for two explicit distinct same-swarm canonical stores: Mind and Modeling retain separate obligations, claims, Qdrant collections, and receipts. The body takes a host OS singleton for the canonical pair before minting a process-stable incarnation. Every fresh pulse reloads both sealed inputs, stores no open-work queue, permits at most one fair global action, never executes ready/foreign-running/succeeded/stale inputs, and resumes only an exact running claim owned by its current incarnation. Pending/failed work acquires exact Idunn authority before the crate-private executor; overlapping pulses are busy and cooldown follows completion. Exact recovery remains a separate supervisor action over authenticated lifecycle and provider-heartbeat evidence; it only rotates authority, after which the ordinary pulse resumes the recovered claim. The legacy CLI index/claim mouth and public raw execute surface are gone. Idunn's specialized writer exclusively owns the reserved fixed service policy and packaged sibling command; the generic managed-service writer cannot claim that service id or override its command, stores, restart mode, or unbounded serve shape. Provider health and heartbeat are derived sight only; the canonical grant-or-recovery/claim/attempt/receipt chain alone admits query. Deployment is not live: local `voidbot-qdrant` is stopped with exit code 143 and is foreign-owned, so Epiphany did not restart or adopt it; no projector policy or restart proof is claimed. Next establish explicit Qdrant ownership and a live workstation-reachable endpoint, verify collection compatibility and Yggdrasil Ollama reachability, then publish the reserved policy and prove bounded pulse, provider heartbeat, both health rows, forced Idunn restart, causal heartbeat, exact recovery/resumption, and singleton refusal. Do not call that deployment complete until those live proofs pass; do not move only the projector to Yggdrasil or start a second owner.