diff --git a/Cargo.toml b/Cargo.toml index 1d86aaf3..0bd3b471 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -137,10 +137,6 @@ path = "epiphany-core/src/bin/epiphany-host-identity.rs" name = "epiphany-swarm" path = "epiphany-core/src/bin/epiphany-swarm.rs" -[[bin]] -name = "epiphany-operator-command" -path = "epiphany-core/src/bin/epiphany-operator-command.rs" - [[bin]] name = "epiphany-heartbeat-store" path = "epiphany-core/src/bin/epiphany-heartbeat-store.rs" diff --git a/epiphany-core/Cargo.toml b/epiphany-core/Cargo.toml index 52565f25..63f78fe6 100644 --- a/epiphany-core/Cargo.toml +++ b/epiphany-core/Cargo.toml @@ -97,22 +97,10 @@ path = "src/bin/epiphany-memory-semantic.rs" name = "epiphany-memory-semantic-projector" path = "src/bin/epiphany-memory-semantic-projector.rs" -[[bin]] -name = "epiphany-frontier-execution" -path = "src/bin/epiphany-frontier-execution.rs" - [[bin]] name = "epiphany-mvp-coordinator-smoke" path = "src/bin/epiphany-mvp-coordinator-smoke.rs" -[[bin]] -name = "epiphany-operator-command" -path = "src/bin/epiphany-operator-command.rs" - -[[bin]] -name = "epiphany-operator-command-fixture" -path = "src/bin/epiphany-operator-command-fixture.rs" - [[bin]] name = "epiphany-operator-run" path = "src/bin/epiphany-operator-run.rs" diff --git a/epiphany-core/src/bin/epiphany-daemon-supervisor.rs b/epiphany-core/src/bin/epiphany-daemon-supervisor.rs index a1fc062a..9b6e603f 100644 --- a/epiphany-core/src/bin/epiphany-daemon-supervisor.rs +++ b/epiphany-core/src/bin/epiphany-daemon-supervisor.rs @@ -23,7 +23,6 @@ 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_operator_command_service_health; use epiphany_core::authenticate_resident_provider_pair; use epiphany_core::epiphany_cultmesh_daemon_poke_intent_from_status; use epiphany_core::epiphany_cultmesh_daemon_poke_receipt_for_intent; @@ -43,7 +42,6 @@ use epiphany_core::load_latest_epiphany_cultmesh_daemon_service_lifecycle_receip 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::read_operator_command_trust_anchor; 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; @@ -1000,61 +998,6 @@ fn publish_managed_service_iteration_health( contradictions .push("resident health requires both heartbeat and Self provider stores".into()); } - match ( - args.operator_service_readiness_store.as_deref(), - args.operator_executor_trust_anchor.as_deref(), - args.operator_service_bind.as_deref(), - ) { - (Some(store), Some(anchor_path), Some(bind)) => { - expected += 1; - let result = read_operator_command_trust_anchor(anchor_path).and_then(|anchor| { - authenticate_operator_command_service_health( - store, - &args.runtime_id, - &release.release_id, - authenticated_release_witness_sha256, - &release.source_commit_sha, - bind, - &anchor, - Utc::now().timestamp_millis().max(0) as u64, - 15_000, - ) - }); - match result { - Ok(health) => { - let expected_executable = - epiphany_packaged_release_binary_path(release, "operator-command") - .and_then(|path| fs::canonicalize(path).map_err(Into::into)); - let observed = capture_process_instance(health.process_id); - match (expected_executable, observed) { - (Ok(expected_executable), Ok(process)) - if process.creation_token == health.process_creation_token - && process.executable_path == expected_executable - && process.executable_path.display().to_string() - == health.process_executable_path => - { - terminal_current += 1 - } - (Ok(_), Ok(_)) => contradictions.push( - "operator service process identity is not the signed packaged sibling" - .into(), - ), - (Err(error), _) | (_, Err(error)) => contradictions.push(format!( - "operator service process cannot be authenticated: {error:#}" - )), - } - } - Err(error) => contradictions.push(format!( - "operator service signed readiness is invalid: {error:#}" - )), - } - } - (None, None, None) => {} - _ => { - expected += 1; - contradictions.push("operator service health requires readiness store, executor trust anchor, and exact bind".into()); - } - } for service_id in required { let Some(policy) = policies .iter() @@ -5297,9 +5240,6 @@ struct Args { resident_heartbeat_store: Option, resident_self_store: Option, resident_provider_stale_seconds: u64, - operator_service_readiness_store: Option, - operator_executor_trust_anchor: Option, - operator_service_bind: Option, } impl Args { @@ -5359,9 +5299,6 @@ impl Args { let mut resident_heartbeat_store = None; let mut resident_self_store = None; let mut resident_provider_stale_seconds = 180_u64; - let mut operator_service_readiness_store = None; - let mut operator_executor_trust_anchor = None; - let mut operator_service_bind = None; while let Some(arg) = values.next() { match arg.as_str() { @@ -5600,26 +5537,6 @@ impl Args { anyhow::bail!("--resident-provider-stale-seconds must be positive"); } } - "--operator-service-readiness-store" => { - operator_service_readiness_store = - Some(PathBuf::from(values.next().context( - "missing --operator-service-readiness-store value", - )?)) - } - "--operator-executor-trust-anchor" => { - operator_executor_trust_anchor = Some(PathBuf::from( - values - .next() - .context("missing --operator-executor-trust-anchor value")?, - )) - } - "--operator-service-bind" => { - operator_service_bind = Some( - values - .next() - .context("missing --operator-service-bind value")?, - ) - } other => anyhow::bail!("unknown argument {other:?}"), } } @@ -5767,19 +5684,6 @@ impl Args { ); } } - let operator_health_fields = [ - operator_service_readiness_store.is_some(), - operator_executor_trust_anchor.is_some(), - operator_service_bind.is_some(), - ]; - if operator_health_fields.into_iter().any(|value| value) - && !operator_health_fields.into_iter().all(|value| value) - { - anyhow::bail!( - "operator service health store, executor trust anchor, and bind are all-or-none" - ); - } - Ok(Self { command, store, @@ -5834,9 +5738,6 @@ impl Args { resident_heartbeat_store, resident_self_store, resident_provider_stale_seconds, - operator_service_readiness_store, - operator_executor_trust_anchor, - operator_service_bind, }) } } diff --git a/epiphany-core/src/bin/epiphany-frontier-execution.rs b/epiphany-core/src/bin/epiphany-frontier-execution.rs deleted file mode 100644 index b0086a85..00000000 --- a/epiphany-core/src/bin/epiphany-frontier-execution.rs +++ /dev/null @@ -1,124 +0,0 @@ -use anyhow::{Result, anyhow}; -use epiphany_core::{ - RepoFrontierExecutionAmendment, RepoFrontierPlanDecisionReceipt, RepoFrontierRoute, - amend_repo_frontier_execution, assemble_repo_model_view, runtime_spine_cache, - validate_frontier_plan_decision_chain, -}; -use sha2::{Digest, Sha256}; -use std::{collections::BTreeMap, env, path::PathBuf}; - -fn main() -> Result<()> { - let mut values = BTreeMap::new(); - let mut args = env::args().skip(1); - let command = args.next().ok_or_else(|| anyhow!(usage()))?; - if command != "amend-frontier-execution" && command != "inspect-frontier-execution" { - return Err(anyhow!("unknown command {command}\n{}", usage())); - } - while let Some(flag) = args.next() { - let value = args - .next() - .ok_or_else(|| anyhow!("missing value for {flag}"))?; - if values.insert(flag.clone(), value).is_some() { - return Err(anyhow!("duplicate option {flag}")); - } - } - let take = |name: &str| { - values - .get(name) - .cloned() - .ok_or_else(|| anyhow!("missing {name}")) - }; - let store = PathBuf::from(take("--store")?); - let route_id = take("--route-id")?; - if command == "inspect-frontier-execution" { - let mut cache = runtime_spine_cache(&store)?; - cache.pull_all_backing_stores()?; - let routes = cache.get_all::()?; - let available = routes - .iter() - .map(|route| route.route_id.as_str()) - .collect::>() - .join(", "); - let route = routes - .into_iter() - .find(|route| route.route_id == route_id) - .ok_or_else(|| anyhow!("route {route_id} does not exist; available: {available}"))?; - let plan = route - .adopted_plan - .as_ref() - .ok_or_else(|| anyhow!("route {route_id} has no adopted plan"))?; - let current_model = assemble_repo_model_view(&store)?; - let mut plan_decisions = cache - .get_all::()? - .into_iter() - .filter(|decision| decision.planning_request_id == plan.planning_request_id) - .collect::>(); - if plan_decisions.len() != 1 { - return Err(anyhow!( - "route {route_id} requires exactly one typed plan decision; found {}", - plan_decisions.len() - )); - } - let plan_decision = plan_decisions.pop().expect("one decision checked above"); - validate_frontier_plan_decision_chain(&plan_decision, &route, ¤t_model) - .map_err(anyhow::Error::msg)?; - println!( - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "routeId": route.route_id, - "modelProjectionDigest": route.model_projection_digest, - "modelSourceDocuments": route.model_source_documents, - "frontierPlanDecisionId": plan_decision.decision_id, - "frontierPlanDecision": plan_decision, - "frontierItemId": route.frontier_item_id, - "frontierItemHash": route.frontier_item_hash, - "originalAction": plan.action, - "originalCommand": plan.command, - "effectiveAction": plan.effective_action(), - "effectiveCommand": plan.effective_command(), - "executionAmendment": plan.execution_amendment, - }))? - ); - return Ok(()); - } - let source_actor_id = take("--source-actor-id")?; - let command_id = take("--command-id")?; - let admission_id = take("--admission-id")?; - let packet_sha256 = take("--packet-sha256")?; - let previous_action = take("--previous-action")?; - let previous_command = take("--previous-command")?; - let action = take("--action")?; - let replacement_command = take("--replacement-command")?; - let rationale = take("--rationale")?; - let amended_at = take("--amended-at")?; - let semantic = format!( - "{route_id}\0{source_actor_id}\0{command_id}\0{admission_id}\0{packet_sha256}\0{action}\0{replacement_command}\0{rationale}\0{amended_at}" - ); - let amendment_id = format!( - "repo-frontier-execution-amendment-{:x}", - Sha256::digest(semantic.as_bytes()) - ); - let receipt = amend_repo_frontier_execution( - store, - RepoFrontierExecutionAmendment { - amendment_id, - replaces_route_id: route_id, - source_actor_id, - command_id, - admission_id, - packet_sha256, - previous_action_sha256: format!("{:x}", Sha256::digest(previous_action.as_bytes())), - previous_command_sha256: format!("{:x}", Sha256::digest(previous_command.as_bytes())), - action, - command: replacement_command, - rationale, - amended_at, - }, - )?; - println!("{}", serde_json::to_string_pretty(&receipt)?); - Ok(()) -} - -fn usage() -> &'static str { - "usage: epiphany-frontier-execution inspect-frontier-execution --store PATH --route-id ID\n epiphany-frontier-execution amend-frontier-execution --store PATH --route-id ID --source-actor-id ID --command-id ID --admission-id ID --packet-sha256 SHA256 --previous-action TEXT --previous-command TEXT --action TEXT --replacement-command TEXT --rationale TEXT --amended-at RFC3339" -} diff --git a/epiphany-core/src/bin/epiphany-hands-action.rs b/epiphany-core/src/bin/epiphany-hands-action.rs index 60a1873b..29286813 100644 --- a/epiphany-core/src/bin/epiphany-hands-action.rs +++ b/epiphany-core/src/bin/epiphany-hands-action.rs @@ -930,7 +930,6 @@ mod tests { stop_conditions: vec!["A check fails.".into()], rollback_steps: vec!["Revert the fixture change.".into()], commit_message: "Exercise exact Hands authority".into(), - execution_amendment: None, }), status: RepoFrontierStatus::Active, ..Default::default() diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index 52721eaa..7b6f4832 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -1669,7 +1669,6 @@ fn record_hands_implementation_gate( "plannedCommand": route.adopted_plan.as_ref().map(|plan| plan.effective_command()), "originalPlannedAction": route.adopted_plan.as_ref().map(|plan| plan.action.as_str()), "originalPlannedCommand": route.adopted_plan.as_ref().map(|plan| plan.command.as_str()), - "executionAmendmentId": route.adopted_plan.as_ref().and_then(|plan| plan.execution_amendment.as_ref()).map(|amendment| amendment.amendment_id.as_str()), "plannedChecks": route.adopted_plan.as_ref().map(|plan| plan.checks.as_slice()), "plannedStopConditions": route.adopted_plan.as_ref().map(|plan| plan.stop_conditions.as_slice()), "plannedRollbackSteps": route.adopted_plan.as_ref().map(|plan| plan.rollback_steps.as_slice()), diff --git a/epiphany-core/src/bin/epiphany-operator-command-fixture.rs b/epiphany-core/src/bin/epiphany-operator-command-fixture.rs deleted file mode 100644 index 338aff0f..00000000 --- a/epiphany-core/src/bin/epiphany-operator-command-fixture.rs +++ /dev/null @@ -1,13 +0,0 @@ -use anyhow::{Context, Result}; -use epiphany_core::write_operator_command_interop_fixture; -use std::path::PathBuf; - -fn main() -> Result<()> { - let output = std::env::args_os() - .nth(1) - .map(PathBuf::from) - .context("usage: epiphany-operator-command-fixture ")?; - let manifest = write_operator_command_interop_fixture(&output)?; - println!("{}", serde_json::to_string_pretty(&manifest)?); - Ok(()) -} diff --git a/epiphany-core/src/bin/epiphany-operator-command.rs b/epiphany-core/src/bin/epiphany-operator-command.rs deleted file mode 100644 index 38066987..00000000 --- a/epiphany-core/src/bin/epiphany-operator-command.rs +++ /dev/null @@ -1,235 +0,0 @@ -use anyhow::{Context, Result, anyhow, bail}; -use epiphany_core::{ - OperatorCapability, OperatorCommandPolicy, OperatorCommandServiceConfig, - OperatorCommandServiceReadiness, OperatorStatusProviderHealthConfig, open_host_identity_at, - read_operator_command_trust_anchor, serve_operator_command_rudp, -}; -use std::collections::BTreeMap; -use std::net::{SocketAddr, UdpSocket}; -use std::path::PathBuf; - -fn main() -> Result<()> { - let args = Args::parse(std::env::args().skip(1))?; - let signer = open_host_identity_at(&args.executor_identity_store)?; - let config = OperatorCommandServiceConfig { - command_store: args.command_store.clone(), - local_verse_store: args.local_verse_store.clone(), - resident_self_store: args.resident_self_store.clone(), - runtime_store: args.runtime_store.clone(), - policy: OperatorCommandPolicy { - runtime_id: args.runtime_id.clone(), - discord_guild_id: args.guild_id.clone(), - allowed_channel_ids: args.channel_ids.clone(), - actor_capabilities: args.actor_capabilities.clone(), - max_ttl_seconds: args.max_ttl_seconds, - }, - trusted_bifrost_identity: read_operator_command_trust_anchor(&args.bifrost_trust_anchor)?, - provider_health: OperatorStatusProviderHealthConfig { - query_endpoint: args.idunn_provider_query, - idunn_runtime_id: args.idunn_runtime_id.clone(), - trust_anchor_store: args.idunn_projection_anchor.clone(), - admission_store: args.provider_admission_store.clone(), - max_local_age_millis: args.provider_ttl_millis, - deployment_id: args.deployment_id.clone(), - release_id: args.release_id.clone(), - release_witness_sha256: args.release_witness_sha256.clone(), - source_commit: args.source_commit.clone(), - }, - }; - if args.status_only { - print_readiness(&args, &signer, "configured")?; - return Ok(()); - } - let socket = UdpSocket::bind(args.bind).with_context(|| { - format!( - "binding Epiphany operator command RUDP service at {}", - args.bind - ) - })?; - print_readiness(&args, &signer, "serving")?; - let health = epiphany_core::OperatorCommandServiceHealthConfig { - store: args.readiness_store.clone(), - bind: args.bind.to_string(), - release_id: args.release_id.clone(), - release_witness_sha256: args.release_witness_sha256.clone(), - source_commit: args.source_commit.clone(), - }; - serve_operator_command_rudp(socket, &config, &signer, &health) -} - -fn print_readiness( - args: &Args, - signer: &epiphany_core::HostIdentitySigner, - status: &str, -) -> Result<()> { - println!( - "{}", - serde_json::to_string(&OperatorCommandServiceReadiness { - schema_version: "epiphany.operator_command.service_readiness.v0".into(), - status: status.into(), - runtime_id: args.runtime_id.clone(), - bind: args.bind.to_string(), - executor_identity_id: signer.entry().identity_id.clone(), - private_state_exposed: false, - })? - ); - Ok(()) -} - -struct Args { - bind: SocketAddr, - runtime_id: String, - bifrost_trust_anchor: PathBuf, - executor_identity_store: PathBuf, - command_store: PathBuf, - local_verse_store: PathBuf, - resident_self_store: PathBuf, - runtime_store: PathBuf, - guild_id: String, - channel_ids: Vec, - actor_capabilities: BTreeMap>, - max_ttl_seconds: i64, - readiness_store: PathBuf, - release_id: String, - release_witness_sha256: String, - source_commit: String, - deployment_id: String, - idunn_provider_query: SocketAddr, - idunn_runtime_id: String, - idunn_projection_anchor: PathBuf, - provider_admission_store: PathBuf, - provider_ttl_millis: u64, - status_only: bool, -} - -impl Args { - fn parse(values: impl Iterator) -> Result { - let mut values = values.peekable(); - let mut fields = BTreeMap::::new(); - let mut channels = Vec::new(); - let mut actors = BTreeMap::new(); - let mut status_only = false; - while let Some(flag) = values.next() { - match flag.as_str() { - "--status" => status_only = true, - "--channel-id" => channels.push(values.next().context("missing --channel-id")?), - "--actor-capabilities" => { - let value = values.next().context("missing --actor-capabilities")?; - let (actor, capabilities) = value.split_once('=').context( - "--actor-capabilities must be actor=status,sleep,wake,directive", - )?; - if actor.trim().is_empty() || actors.contains_key(actor) { - bail!("operator actor capability binding is empty or duplicated"); - } - let parsed = capabilities - .split(',') - .map(parse_capability) - .collect::>>()?; - if parsed.is_empty() { - bail!("operator actor requires at least one capability"); - } - actors.insert(actor.to_string(), parsed); - } - "--bind" - | "--runtime-id" - | "--bifrost-trust-anchor" - | "--executor-identity-store" - | "--command-store" - | "--local-verse-store" - | "--resident-self-store" - | "--runtime-store" - | "--guild-id" - | "--readiness-store" - | "--release-id" - | "--release-witness-sha256" - | "--source-commit" - | "--deployment-id" - | "--idunn-provider-query" - | "--idunn-runtime-id" - | "--idunn-projection-anchor" - | "--provider-admission-store" - | "--provider-ttl-millis" - | "--max-ttl-seconds" => { - let value = values - .next() - .ok_or_else(|| anyhow!("missing value for {flag}"))?; - if fields.insert(flag.clone(), value).is_some() { - bail!("duplicate operator service argument {flag}"); - } - } - _ => bail!("unknown operator service argument {flag}"), - } - } - let required = |name: &str| { - fields - .get(name) - .cloned() - .ok_or_else(|| anyhow!("missing {name}")) - }; - if channels.is_empty() || actors.is_empty() { - bail!("operator service requires channels and actor capabilities"); - } - let max_ttl_seconds = fields - .get("--max-ttl-seconds") - .map(String::as_str) - .unwrap_or("60") - .parse()?; - if !(1..=60).contains(&max_ttl_seconds) { - bail!("operator service max TTL must be 1..=60 seconds"); - } - let provider_ttl_millis = required("--provider-ttl-millis")?.parse()?; - if provider_ttl_millis == 0 { - bail!("provider health TTL must be nonzero"); - } - Ok(Self { - bind: required("--bind")?.parse()?, - runtime_id: required("--runtime-id")?, - bifrost_trust_anchor: required("--bifrost-trust-anchor")?.into(), - executor_identity_store: required("--executor-identity-store")?.into(), - command_store: required("--command-store")?.into(), - local_verse_store: required("--local-verse-store")?.into(), - resident_self_store: required("--resident-self-store")?.into(), - runtime_store: required("--runtime-store")?.into(), - guild_id: required("--guild-id")?, - channel_ids: channels, - actor_capabilities: actors, - max_ttl_seconds, - readiness_store: required("--readiness-store")?.into(), - release_id: required("--release-id")?, - release_witness_sha256: required("--release-witness-sha256")?, - source_commit: required("--source-commit")?, - deployment_id: required("--deployment-id")?, - idunn_provider_query: required("--idunn-provider-query")?.parse()?, - idunn_runtime_id: required("--idunn-runtime-id")?, - idunn_projection_anchor: required("--idunn-projection-anchor")?.into(), - provider_admission_store: required("--provider-admission-store")?.into(), - provider_ttl_millis, - status_only, - }) - } -} - -fn parse_capability(value: &str) -> Result { - match value { - "status" => Ok(OperatorCapability::Status), - "sleep" => Ok(OperatorCapability::Sleep), - "wake" => Ok(OperatorCapability::Wake), - "directive" => Ok(OperatorCapability::Directive), - "reviews" => Ok(OperatorCapability::Reviews), - "review" => Ok(OperatorCapability::Review), - _ => bail!("unknown operator capability {value}"), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parser_has_no_argv_or_store_selector_escape_hatch() { - assert!(Args::parse(["--argv".into(), "whoami".into()].into_iter()).is_err()); - assert!( - Args::parse(["--actor-capabilities".into(), "actor=shell".into()].into_iter()).is_err() - ); - } -} diff --git a/epiphany-core/src/cultmesh_integration.rs b/epiphany-core/src/cultmesh_integration.rs index 95bf56d5..246db509 100644 --- a/epiphany-core/src/cultmesh_integration.rs +++ b/epiphany-core/src/cultmesh_integration.rs @@ -4248,7 +4248,7 @@ pub fn default_epiphany_cultmesh_swarm_brake( } /// The single runtime brake identity shared by deployment, resident readiness, -/// and authenticated operator commands. A caller identity is provenance, not +/// and local typed control surfaces. A caller identity is provenance, not /// brake ownership, and must not be substituted into either constant. pub const EPIPHANY_CANONICAL_SWARM_BRAKE_ID: &str = "epiphany/swarm-brake"; pub const EPIPHANY_CANONICAL_SWARM_BRAKE_OWNER: &str = "epiphany.swarm-brake"; diff --git a/epiphany-core/src/frontier_plan_chain.rs b/epiphany-core/src/frontier_plan_chain.rs index ccb61994..5377046b 100644 --- a/epiphany-core/src/frontier_plan_chain.rs +++ b/epiphany-core/src/frontier_plan_chain.rs @@ -15,14 +15,6 @@ pub fn validate_frontier_plan_decision_chain( Some(crate::RepoFrontierPlanDecisionSource::MindWorker { result_id, job_id }) => { !result_id.trim().is_empty() && !job_id.trim().is_empty() } - Some(crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { - command_id, - admission_id, - packet_sha256, - source_actor_id, - }) => [command_id, admission_id, packet_sha256, source_actor_id] - .into_iter() - .all(|value| !value.trim().is_empty()), None => false, }; let decision_basis = crate::EpiphanyRepoModelBasis { diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 8b6759fb..867e173f 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -20,8 +20,6 @@ mod imagination_consideration; mod memory_graph; mod mind_contracts; mod mind_documents; -mod operator_command; -mod operator_command_service; mod organ_dependencies; mod packaged_release; mod persona_conversation; @@ -724,7 +722,6 @@ pub use memory_graph::MemorySemanticProjectorPulseOutcome; pub use memory_graph::MemorySemanticProjectorPulseStatus; pub use memory_graph::MemorySemanticProjectorRecoveryAuthorization; pub use memory_graph::RepoFrontierAdoptedPlan; -pub use memory_graph::RepoFrontierExecutionAmendment; pub use memory_graph::RepoFrontierItem; pub use memory_graph::RepoFrontierStatus; pub use memory_graph::SEMANTIC_PROJECTION_SCHEMA_VERSION; @@ -776,27 +773,6 @@ pub use memory_graph::validate_memory_semantic_projection_obligation; pub use mind_contracts::MindCultNetContract; pub use mind_contracts::default_mind_cultnet_contracts; pub use mind_documents::*; -pub use operator_command::{ - BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION, BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE, - BifrostOperatorCommandAdmission, LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION, - LocalAdmittedOperatorCommand, OPERATOR_COMMAND_RESULT_SCHEMA_VERSION, OperatorCapability, - OperatorCommand, OperatorCommandPacket, OperatorCommandPolicy, OperatorCommandResult, - OperatorCommandResultDisposition, admit_and_execute_bifrost_operator_command, - operator_command_admission_signing_payload, operator_command_admission_signing_purpose, - operator_command_packet_sha256, -}; -pub use operator_command_service::{ - EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION, - EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_TYPE, EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID, - EpiphanyOperatorCommandResultReceipt, EpiphanyOperatorCommandServiceHealth, - EpiphanyOperatorCommandWireResult, EpiphanyOperatorStatusProviderV2, EpiphanyOperatorStatusV2, - OperatorCommandInteropFixtureManifest, OperatorCommandServiceConfig, - OperatorCommandServiceHealthConfig, OperatorCommandServiceReadiness, - OperatorStatusProviderHealthConfig, authenticate_operator_command_service_health, - execute_operator_command_admission, operator_command_result_receipt_signing_payload, - operator_command_result_receipt_signing_purpose, read_operator_command_trust_anchor, - serve_operator_command_rudp, write_operator_command_interop_fixture, -}; pub use organ_dependencies::EPIPHANY_LAUNCH_ORGAN_CONTRACT_SCHEMA_VERSION; pub use organ_dependencies::EPIPHANY_ORGAN_DEPENDENCY_SCHEMA_VERSION; pub use organ_dependencies::EPIPHANY_STANDING_ORGANS; @@ -964,7 +940,6 @@ pub use runtime_spine::RuntimeSpineSessionOptions; pub use runtime_spine::RuntimeTypedFulfillmentEvidence; pub use runtime_spine::abandon_unactivated_runtime_worker_process; pub use runtime_spine::activate_runtime_worker_process; -pub use runtime_spine::amend_repo_frontier_execution; pub use runtime_spine::append_runtime_event; pub use runtime_spine::archive_completed_coordinator_session; pub use runtime_spine::archive_completed_model_session; @@ -975,7 +950,6 @@ pub use runtime_spine::bind_runtime_to_agent_memory_swarm; pub use runtime_spine::canonical_repo_frontier_plan_candidate_id; pub use runtime_spine::claim_runtime_worker_process; pub use runtime_spine::close_runtime_session; -pub use runtime_spine::commit_operator_repo_frontier_plan_review; pub use runtime_spine::commit_repo_frontier_modeling_request; pub use runtime_spine::commit_repo_frontier_plan_decision; pub use runtime_spine::commit_repo_frontier_plan_mind_request; @@ -994,8 +968,6 @@ pub use runtime_spine::model_pass_failure_for_request; pub use runtime_spine::open_coordinator_run; pub use runtime_spine::open_runtime_model_execution; pub use runtime_spine::open_runtime_spine_heartbeat_job; -pub use runtime_spine::operator_repo_frontier_plan_review_is_current; -pub use runtime_spine::pending_repo_frontier_plan_reviews; pub use runtime_spine::prepare_runtime_spine_heartbeat_job; pub use runtime_spine::promote_autonomous_direction_options_for_modeling; pub use runtime_spine::put_coordinator_run_receipt; @@ -1047,7 +1019,6 @@ pub use runtime_spine::runtime_latest_repo_frontier_relinquishment; pub use runtime_spine::runtime_modeling_semantic_projection_input; pub use runtime_spine::runtime_registered_document_types; pub use runtime_spine::runtime_reorient_worker_result; -pub use runtime_spine::runtime_repo_frontier_execution_amendment; pub use runtime_spine::runtime_repo_frontier_plan_decision; pub use runtime_spine::runtime_repo_frontier_planning_eligibility; pub use runtime_spine::runtime_repo_frontier_planning_lifecycle; diff --git a/epiphany-core/src/memory_graph/mod.rs b/epiphany-core/src/memory_graph/mod.rs index f8e7b458..d1017144 100644 --- a/epiphany-core/src/memory_graph/mod.rs +++ b/epiphany-core/src/memory_graph/mod.rs @@ -27,7 +27,6 @@ pub use epiphany_state_model::EpiphanyMemoryPatchCandidate; pub use epiphany_state_model::EpiphanyMemoryProfile; pub use epiphany_state_model::EpiphanyMemorySummary; pub use epiphany_state_model::RepoFrontierAdoptedPlan; -pub use epiphany_state_model::RepoFrontierExecutionAmendment; pub use epiphany_state_model::RepoFrontierItem; pub use epiphany_state_model::RepoFrontierStatus; diff --git a/epiphany-core/src/mind_documents.rs b/epiphany-core/src/mind_documents.rs index dd7dfa1f..3aa83c04 100644 --- a/epiphany-core/src/mind_documents.rs +++ b/epiphany-core/src/mind_documents.rs @@ -384,7 +384,6 @@ pub(crate) fn register_mind_document_types(cache: &mut CultCache) -> Result<()> crate::repo_model_documents::register_repo_model_document_types(cache)?; cache.register_entry_type::()?; cache.register_entry_type::()?; - cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -422,9 +421,6 @@ pub(crate) fn validate_mind_write_envelope(envelope: &CultCacheEnvelope) -> Resu } else if envelope.r#type == crate::RepoFrontierRelinquishmentReceipt::TYPE { rmp_serde::from_slice::(&envelope.payload)? .receipt_id - } else if envelope.r#type == crate::RepoFrontierExecutionAmendmentReceipt::TYPE { - rmp_serde::from_slice::(&envelope.payload)? - .receipt_id } else if envelope.r#type == crate::AtlasSurfaceOffer::TYPE { let value: crate::AtlasSurfaceOffer = rmp_serde::from_slice(&envelope.payload)?; value.validate()?; diff --git a/epiphany-core/src/operator_command.rs b/epiphany-core/src/operator_command.rs deleted file mode 100644 index c6446a05..00000000 --- a/epiphany-core/src/operator_command.rs +++ /dev/null @@ -1,1255 +0,0 @@ -use anyhow::{Result, anyhow, bail}; -use cultcache_rs::{ - CacheBackingStore, CultCache, DatabaseEntry, SingleFileMessagePackBackingStore, -}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; -use std::path::Path; - -use crate::{ - EPIPHANY_CANONICAL_SWARM_BRAKE_ID, EPIPHANY_CANONICAL_SWARM_BRAKE_OWNER, HostIdentitySignature, - HostIdentityTrustAnchorEntry, RepoFrontierPlanDecision, RepoFrontierPlanOperatorReview, - RepoFrontierPlanReviewSummary, ResidentSelfPressure, commit_operator_repo_frontier_plan_review, - engage_epiphany_cultmesh_swarm_brake, enqueue_resident_self_pressure, - load_epiphany_cultmesh_swarm_brake, load_latest_epiphany_cultmesh_operator_snapshot, - operator_repo_frontier_plan_review_is_current, pending_repo_frontier_plan_reviews, - release_epiphany_cultmesh_swarm_brake, resident_self_pressures, - verify_host_identity_trust_anchor_signature, -}; - -pub const BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str = - "bifrost.operator_command.delivery.v2"; -pub const BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE: &str = "bifrost.operator_command.delivery"; -pub const LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION: &str = - "epiphany.operator_command.admitted.v2"; -pub const OPERATOR_COMMAND_RESULT_SCHEMA_VERSION: &str = "epiphany.operator_command.result.v2"; -const SIGNING_PURPOSE: &str = "bifrost.operator-command.delivery.v2"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum OperatorCapability { - Status, - Sleep, - Wake, - Directive, - Reviews, - Review, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "snake_case", - rename_all_fields = "camelCase", - deny_unknown_fields -)] -pub enum OperatorCommand { - Status, - Sleep { - reason: String, - }, - Wake, - Directive { - objective: String, - }, - Reviews, - Review { - mind_request_id: String, - candidate_id: String, - candidate_sha256: String, - expected_model_projection_digest: String, - expected_model_source_documents: Vec, - decision: RepoFrontierPlanDecision, - }, -} - -impl OperatorCommand { - fn capability(&self) -> OperatorCapability { - match self { - Self::Status => OperatorCapability::Status, - Self::Sleep { .. } => OperatorCapability::Sleep, - Self::Wake => OperatorCapability::Wake, - Self::Directive { .. } => OperatorCapability::Directive, - Self::Reviews => OperatorCapability::Reviews, - Self::Review { .. } => OperatorCapability::Review, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct OperatorCommandPacket { - pub command_id: String, - pub nonce: String, - pub source_event_id: String, - pub source_actor_id: String, - pub discord_guild_id: String, - pub discord_channel_id: String, - pub discord_message_id: String, - pub target_runtime_id: String, - pub issued_at: String, - pub expires_at: String, - pub command: OperatorCommand, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct BifrostOperatorCommandAdmission { - pub schema_name: String, - pub schema_version: String, - pub admission_id: String, - pub packet: OperatorCommandPacket, - pub packet_sha256: String, - pub source_observer_id: String, - pub source_observer_runtime_id: String, - pub provider: String, - pub bifrost_admission_receipt_id: String, - pub authority: String, - pub provider_identity_id: String, - pub provider_signature: Vec, -} - -impl DatabaseEntry for BifrostOperatorCommandAdmission { - const TYPE: &'static str = BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE; - const SCHEMA_NAME: &'static str = "BifrostOperatorCommandAdmission"; -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.operator_command.admitted", - schema = "LocalAdmittedOperatorCommand" -)] -pub struct LocalAdmittedOperatorCommand { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub command_id: String, - #[cultcache(key = 2)] - pub admission_id: String, - #[cultcache(key = 3)] - pub nonce: String, - #[cultcache(key = 4)] - pub packet_sha256: String, - #[cultcache(key = 5)] - pub source_actor_id: String, - #[cultcache(key = 6)] - pub capability: String, - #[cultcache(key = 7)] - pub target_runtime_id: String, - #[cultcache(key = 8)] - pub admitted_at: String, - #[cultcache(key = 9)] - pub expires_at: String, - #[cultcache(key = 10)] - pub authority: String, - #[cultcache(key = 11)] - pub private_state_exposed: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum OperatorCommandResultDisposition { - Observed, - Applied, - Refused, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.operator_command.result", - schema = "OperatorCommandResult" -)] -pub struct OperatorCommandResult { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub result_id: String, - #[cultcache(key = 2)] - pub command_id: String, - #[cultcache(key = 3)] - pub packet_sha256: String, - #[cultcache(key = 4)] - pub target_runtime_id: String, - #[cultcache(key = 5)] - pub disposition: String, - #[cultcache(key = 6)] - pub consequence_kind: String, - #[cultcache(key = 7)] - pub consequence_ref: String, - #[cultcache(key = 8)] - pub completed_at: String, - #[cultcache(key = 9)] - pub private_state_exposed: bool, - #[cultcache(key = 10)] - pub operator_status: String, - #[cultcache(key = 11)] - pub state_status: String, - #[cultcache(key = 12)] - pub coordinator_action: String, - #[cultcache(key = 13)] - pub brake_status: String, - #[cultcache(key = 14)] - pub detail: String, - #[cultcache(key = 15, default)] - pub reviews: Vec, - #[cultcache(key = 16, default)] - pub review_candidate_id: String, - #[cultcache(key = 17, default)] - pub review_decision: String, -} - -#[derive(Clone, Debug)] -pub struct OperatorCommandPolicy { - pub runtime_id: String, - pub discord_guild_id: String, - pub allowed_channel_ids: Vec, - pub actor_capabilities: BTreeMap>, - pub max_ttl_seconds: i64, -} - -pub fn operator_command_packet_sha256(packet: &OperatorCommandPacket) -> Result { - Ok(format!( - "sha256-{:x}", - Sha256::digest(rmp_serde::to_vec(packet)?) - )) -} - -pub fn operator_command_admission_signing_payload( - admission: &BifrostOperatorCommandAdmission, -) -> Result> { - rmp_serde::to_vec(&( - admission.schema_version.as_str(), - admission.admission_id.as_str(), - &admission.packet, - admission.packet_sha256.as_str(), - admission.source_observer_id.as_str(), - admission.source_observer_runtime_id.as_str(), - admission.provider.as_str(), - admission.bifrost_admission_receipt_id.as_str(), - admission.authority.as_str(), - admission.provider_identity_id.as_str(), - )) - .map_err(Into::into) -} - -pub fn operator_command_admission_signing_purpose() -> &'static str { - SIGNING_PURPOSE -} - -fn command_cache(path: &Path) -> Result { - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - cache.register_entry_type::()?; - if path.exists() { - for envelope in SingleFileMessagePackBackingStore::new(path).pull_all()? { - match envelope.r#type.as_str() { - LocalAdmittedOperatorCommand::TYPE => { - cache.load_envelope::(envelope)?; - } - OperatorCommandResult::TYPE => { - cache.load_envelope::(envelope)?; - } - _ => bail!("operator command store contains foreign authority"), - }; - } - } - if cache - .get_all::()? - .iter() - .any(|entry| entry.schema_version != LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION) - || cache - .get_all::()? - .iter() - .any(|entry| entry.schema_version != OPERATOR_COMMAND_RESULT_SCHEMA_VERSION) - { - bail!("operator command store contains an unsupported schema"); - } - Ok(cache) -} - -fn validate_admission( - admission: &BifrostOperatorCommandAdmission, - anchor: &HostIdentityTrustAnchorEntry, - policy: &OperatorCommandPolicy, - now: chrono::DateTime, - enforce_time: bool, -) -> Result { - let packet = &admission.packet; - let issued = - chrono::DateTime::parse_from_rfc3339(&packet.issued_at)?.with_timezone(&chrono::Utc); - let expires = - chrono::DateTime::parse_from_rfc3339(&packet.expires_at)?.with_timezone(&chrono::Utc); - let capability = packet.command.capability(); - let command_text_valid = match &packet.command { - OperatorCommand::Sleep { reason } => !reason.trim().is_empty() && reason.len() <= 512, - OperatorCommand::Directive { objective } => { - !objective.trim().is_empty() && objective.len() <= 4096 - } - OperatorCommand::Review { - mind_request_id, - candidate_id, - candidate_sha256, - expected_model_projection_digest, - expected_model_source_documents, - .. - } => { - let model_basis = crate::EpiphanyRepoModelBasis { - projection_digest: expected_model_projection_digest.clone(), - source_documents: expected_model_source_documents.clone(), - }; - !mind_request_id.trim().is_empty() - && mind_request_id.len() <= 256 - && !candidate_id.trim().is_empty() - && candidate_id.len() <= 256 - && candidate_sha256.len() == 64 - && candidate_sha256 - .bytes() - .all(|byte| byte.is_ascii_hexdigit()) - && model_basis.validate().is_ok() - } - _ => true, - }; - if admission.schema_name != BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE - || admission.schema_version != BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION - || admission.admission_id.trim().is_empty() - || packet.command_id.trim().is_empty() - || packet.nonce.trim().is_empty() - || packet.source_event_id.trim().is_empty() - || packet.source_actor_id.trim().is_empty() - || packet.discord_message_id.trim().is_empty() - || admission.source_observer_id != "voidbot" - || admission.source_observer_runtime_id.trim().is_empty() - || admission.provider != "bifrost" - || admission.bifrost_admission_receipt_id.trim().is_empty() - || admission.authority != "exact_operator_command_only" - || !command_text_valid - || packet.target_runtime_id != policy.runtime_id - || packet.discord_guild_id != policy.discord_guild_id - || !policy - .allowed_channel_ids - .contains(&packet.discord_channel_id) - || (enforce_time && issued > now) - || (enforce_time && expires < now) - || expires <= issued - || (expires - issued).num_seconds() > policy.max_ttl_seconds - || policy.max_ttl_seconds <= 0 - || !policy - .actor_capabilities - .get(&packet.source_actor_id) - .is_some_and(|caps| caps.contains(&capability)) - { - bail!("Bifrost operator command violates local command policy"); - } - if admission.provider_identity_id != anchor.identity_id - || admission.packet_sha256 != operator_command_packet_sha256(packet)? - { - bail!("Bifrost operator command identity or payload binding is invalid"); - } - verify_host_identity_trust_anchor_signature( - anchor, - SIGNING_PURPOSE, - &operator_command_admission_signing_payload(admission)?, - &HostIdentitySignature { - identity_id: admission.provider_identity_id.clone(), - signature: admission.provider_signature.clone(), - }, - )?; - Ok(capability) -} - -pub fn admit_and_execute_bifrost_operator_command( - command_store: &Path, - local_verse_store: &Path, - resident_self_store: &Path, - runtime_store: &Path, - admission: &BifrostOperatorCommandAdmission, - trusted_bifrost_identity: &HostIdentityTrustAnchorEntry, - policy: &OperatorCommandPolicy, - now: &str, -) -> Result { - let now_dt = chrono::DateTime::parse_from_rfc3339(now)?.with_timezone(&chrono::Utc); - let capability = - validate_admission(admission, trusted_bifrost_identity, policy, now_dt, false)?; - let packet = &admission.packet; - let mut admitted = LocalAdmittedOperatorCommand { - schema_version: LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(), - command_id: packet.command_id.clone(), - admission_id: admission.admission_id.clone(), - nonce: packet.nonce.clone(), - packet_sha256: admission.packet_sha256.clone(), - source_actor_id: packet.source_actor_id.clone(), - capability: format!("{capability:?}").to_lowercase(), - target_runtime_id: packet.target_runtime_id.clone(), - admitted_at: now.into(), - expires_at: packet.expires_at.clone(), - authority: "exact-command-only".into(), - private_state_exposed: false, - }; - let cache = command_cache(command_store)?; - let prior_admission = cache.get::(&packet.command_id)?; - let was_admitted = prior_admission.is_some(); - for prior in cache.get_all::()? { - if prior.source_actor_id == admitted.source_actor_id - && prior.nonce == admitted.nonce - && prior.command_id != admitted.command_id - { - bail!("operator command actor nonce collision"); - } - } - if let Some(prior) = prior_admission.as_ref() { - let mut replay = admitted.clone(); - replay.admitted_at = prior.admitted_at.clone(); - if &replay != prior { - bail!("operator command identity collision"); - } - admitted = prior.clone(); - } - let result_id = format!( - "operator-command-result-{:x}", - Sha256::digest(format!("{}:{}", packet.command_id, admission.packet_sha256).as_bytes()) - ); - if let Some(existing) = cache.get::(&result_id)? { - return Ok(existing); - } - if !was_admitted { - validate_admission(admission, trusted_bifrost_identity, policy, now_dt, true)?; - } - if cache - .get::(&packet.command_id)? - .as_ref() - != Some(&admitted) - { - let (entry, _) = cache.prepare_entry(&packet.command_id, &admitted)?; - if !SingleFileMessagePackBackingStore::new(command_store).insert_entry_if_absent(entry)? { - bail!("operator command admission collision"); - } - } - let ( - disposition, - consequence_kind, - consequence_ref, - operator_status, - state_status, - coordinator_action, - brake_status, - detail, - reviews, - review_candidate_id, - review_decision, - ) = match &packet.command { - OperatorCommand::Status => { - let snapshot = load_latest_epiphany_cultmesh_operator_snapshot( - local_verse_store, - policy.runtime_id.clone(), - )?; - let Some(snapshot) = snapshot else { - return persist_result( - command_store, - packet, - admission, - policy, - now, - result_id, - OperatorCommandResultDisposition::Refused, - "operator-snapshot", - "", - "", - "", - "", - "", - "operator status snapshot is unavailable", - Vec::new(), - "", - "", - ); - }; - let brake_status = - load_epiphany_cultmesh_swarm_brake(local_verse_store, policy.runtime_id.clone())? - .map(|brake| brake.status) - .unwrap_or_else(|| "absent".into()); - ( - OperatorCommandResultDisposition::Observed, - "operator-snapshot", - snapshot.snapshot_id, - format!("coordinator-snapshot/{}", snapshot.status), - format!("coordinator-state/{}", snapshot.state_status), - format!("coordinator-action/{}", snapshot.coordinator_action), - brake_status, - String::from( - "bounded coordinator snapshot plus independently owned swarm-brake observation; this is not deployment or provider readiness", - ), - Vec::new(), - String::new(), - String::new(), - ) - } - OperatorCommand::Sleep { reason } => { - let brake_actor = format!( - "operator-command:{};source:{}", - packet.command_id, packet.source_actor_id - ); - if let Some(current) = - load_epiphany_cultmesh_swarm_brake(local_verse_store, policy.runtime_id.clone())? - { - let exact_retry = current.brake_id == EPIPHANY_CANONICAL_SWARM_BRAKE_ID - && current.operator_agent_id == EPIPHANY_CANONICAL_SWARM_BRAKE_OWNER - && current.notes.iter().any(|note| { - note == &format!("Explicit brake engagement by {brake_actor}.") - }); - let current_is_not_older = - chrono::DateTime::parse_from_rfc3339(¤t.created_at_utc)? - >= chrono::DateTime::parse_from_rfc3339(&packet.issued_at)?; - let foreign = current.brake_id != EPIPHANY_CANONICAL_SWARM_BRAKE_ID - || current.operator_agent_id != EPIPHANY_CANONICAL_SWARM_BRAKE_OWNER; - if (current.status == "engaged" && foreign) - || (!exact_retry && current_is_not_older) - { - return persist_result( - command_store, - packet, - admission, - policy, - now, - result_id, - OperatorCommandResultDisposition::Refused, - "swarm-brake", - "", - "", - "", - "", - ¤t.status, - "operator sleep cannot replace a foreign or newer brake generation", - Vec::new(), - "", - "", - ); - } - } - let brake = engage_epiphany_cultmesh_swarm_brake( - local_verse_store, - policy.runtime_id.clone(), - reason.trim(), - brake_actor, - packet.issued_at.clone(), - false, - )?; - ( - OperatorCommandResultDisposition::Applied, - "swarm-brake", - brake.brake_id, - String::new(), - String::new(), - String::new(), - "engaged".into(), - String::from("Discord operator brake engaged"), - Vec::new(), - String::new(), - String::new(), - ) - } - OperatorCommand::Wake => { - let brake = - load_epiphany_cultmesh_swarm_brake(local_verse_store, policy.runtime_id.clone())?; - let Some(_) = brake.filter(|brake| { - brake.brake_id == EPIPHANY_CANONICAL_SWARM_BRAKE_ID - && brake.operator_agent_id == EPIPHANY_CANONICAL_SWARM_BRAKE_OWNER - }) else { - return persist_result( - command_store, - packet, - admission, - policy, - now, - result_id, - OperatorCommandResultDisposition::Refused, - "swarm-brake", - "", - "", - "", - "", - "engaged", - "operator wake cannot release a brake owned by another authority", - Vec::new(), - "", - "", - ); - }; - let brake = release_epiphany_cultmesh_swarm_brake( - local_verse_store, - policy.runtime_id.clone(), - "Authenticated operator wake; release brake only.", - format!( - "operator-command:{};source:{}", - packet.command_id, packet.source_actor_id - ), - packet.issued_at.clone(), - )?; - ( - OperatorCommandResultDisposition::Applied, - "swarm-brake", - brake.brake_id, - String::new(), - String::new(), - String::new(), - "released".into(), - String::from("Discord operator brake released; no work scheduled"), - Vec::new(), - String::new(), - String::new(), - ) - } - OperatorCommand::Directive { objective } => { - let pressure_id = format!("operator-command-{}", packet.command_id); - let pressure = ResidentSelfPressure { - schema_version: crate::RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: pressure_id.clone(), - kind: "operator-objective".into(), - provenance_ref: format!("cultcache://operator-command/{}", packet.command_id), - objective: objective.trim().into(), - created_at_millis: issued_millis(&packet.issued_at)?, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }; - match resident_self_pressures(resident_self_store)? - .into_iter() - .find(|p| p.pressure_id == pressure_id) - { - Some(existing) if existing == pressure => {} - Some(_) => { - return persist_result( - command_store, - packet, - admission, - policy, - now, - result_id, - OperatorCommandResultDisposition::Refused, - "resident-self-pressure", - &pressure_id, - "", - "", - "", - "", - "operator directive pressure identity collision", - Vec::new(), - "", - "", - ); - } - None => enqueue_resident_self_pressure(resident_self_store, &pressure)?, - } - ( - OperatorCommandResultDisposition::Applied, - "resident-self-pressure", - pressure_id, - String::new(), - String::new(), - String::new(), - String::new(), - String::from("directive admitted as pressure only"), - Vec::new(), - String::new(), - String::new(), - ) - } - OperatorCommand::Reviews => { - let reviews = pending_repo_frontier_plan_reviews(runtime_store, 10)?; - ( - OperatorCommandResultDisposition::Observed, - "mind-review-candidates", - String::new(), - String::new(), - String::new(), - String::new(), - String::new(), - format!("{} pending Mind review candidate(s)", reviews.len()), - reviews, - String::new(), - String::new(), - ) - } - OperatorCommand::Review { - mind_request_id, - candidate_id, - candidate_sha256, - expected_model_projection_digest, - expected_model_source_documents, - decision, - } => { - let review = RepoFrontierPlanOperatorReview { - command_id: packet.command_id.clone(), - admission_id: admission.admission_id.clone(), - packet_sha256: admission.packet_sha256.clone(), - source_actor_id: packet.source_actor_id.clone(), - mind_request_id: mind_request_id.clone(), - candidate_id: candidate_id.clone(), - candidate_sha256: candidate_sha256.clone(), - expected_model_projection_digest: expected_model_projection_digest.clone(), - expected_model_source_documents: expected_model_source_documents.clone(), - decision: *decision, - decided_at: packet.issued_at.clone(), - }; - if !operator_repo_frontier_plan_review_is_current(runtime_store, &review)? { - return persist_result( - command_store, - packet, - admission, - policy, - now, - result_id, - OperatorCommandResultDisposition::Refused, - "mind-review-decision", - "", - "", - "", - "", - "", - "Mind refused stale, terminal, or mismatched review candidate", - Vec::new(), - candidate_id, - &format!("{decision:?}").to_lowercase(), - ); - } - let receipt = commit_operator_repo_frontier_plan_review(runtime_store, &review)?; - ( - OperatorCommandResultDisposition::Applied, - "mind-review-decision", - receipt.decision_id, - String::new(), - String::new(), - String::new(), - String::new(), - String::from("Mind committed exact current-candidate disposition"), - Vec::new(), - candidate_id.clone(), - format!("{decision:?}").to_lowercase(), - ) - } - }; - persist_result( - command_store, - packet, - admission, - policy, - now, - result_id, - disposition, - consequence_kind, - &consequence_ref, - &operator_status, - &state_status, - &coordinator_action, - &brake_status, - &detail, - reviews, - &review_candidate_id, - &review_decision, - ) -} - -#[allow(clippy::too_many_arguments)] -fn persist_result( - command_store: &Path, - packet: &OperatorCommandPacket, - admission: &BifrostOperatorCommandAdmission, - policy: &OperatorCommandPolicy, - now: &str, - result_id: String, - disposition: OperatorCommandResultDisposition, - consequence_kind: &str, - consequence_ref: &str, - operator_status: &str, - state_status: &str, - coordinator_action: &str, - brake_status: &str, - detail: &str, - reviews: Vec, - review_candidate_id: &str, - review_decision: &str, -) -> Result { - let result = OperatorCommandResult { - schema_version: OPERATOR_COMMAND_RESULT_SCHEMA_VERSION.into(), - result_id: result_id.clone(), - command_id: packet.command_id.clone(), - packet_sha256: admission.packet_sha256.clone(), - target_runtime_id: policy.runtime_id.clone(), - disposition: format!("{disposition:?}").to_lowercase(), - consequence_kind: consequence_kind.into(), - consequence_ref: consequence_ref.into(), - completed_at: now.into(), - private_state_exposed: false, - operator_status: operator_status.into(), - state_status: state_status.into(), - coordinator_action: coordinator_action.into(), - brake_status: brake_status.into(), - detail: detail.into(), - reviews, - review_candidate_id: review_candidate_id.into(), - review_decision: review_decision.into(), - }; - let refreshed = command_cache(command_store)?; - let (entry, _) = refreshed.prepare_entry(&result_id, &result)?; - if !SingleFileMessagePackBackingStore::new(command_store).insert_entry_if_absent(entry)? { - let existing = command_cache(command_store)?.get::(&result_id)?; - if existing.as_ref() != Some(&result) { - bail!("operator command result collision"); - } - } - Ok(result) -} - -fn issued_millis(value: &str) -> Result { - let millis = chrono::DateTime::parse_from_rfc3339(value)?.timestamp_millis(); - u64::try_from(millis).map_err(|_| anyhow!("operator command timestamp predates epoch")) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn policy() -> OperatorCommandPolicy { - OperatorCommandPolicy { - runtime_id: "epiphany-yggdrasil".into(), - discord_guild_id: "guild-1".into(), - allowed_channel_ids: vec!["ops-1".into()], - actor_capabilities: BTreeMap::from([( - "operator-1".into(), - vec![ - OperatorCapability::Status, - OperatorCapability::Sleep, - OperatorCapability::Wake, - OperatorCapability::Directive, - OperatorCapability::Reviews, - OperatorCapability::Review, - ], - )]), - max_ttl_seconds: 600, - } - } - - fn signed( - signer: &crate::HostIdentitySigner, - id: &str, - command: OperatorCommand, - ) -> Result { - let packet = OperatorCommandPacket { - command_id: id.into(), - nonce: format!("nonce-{id}"), - source_event_id: format!("event-{id}"), - source_actor_id: "operator-1".into(), - discord_guild_id: "guild-1".into(), - discord_channel_id: "ops-1".into(), - discord_message_id: format!("message-{id}"), - target_runtime_id: "epiphany-yggdrasil".into(), - issued_at: "2026-07-19T11:59:00Z".into(), - expires_at: "2026-07-19T12:05:00Z".into(), - command, - }; - let mut admission = BifrostOperatorCommandAdmission { - schema_name: BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE.into(), - schema_version: BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(), - admission_id: format!("admission-{id}"), - packet_sha256: operator_command_packet_sha256(&packet)?, - packet, - source_observer_id: "voidbot".into(), - source_observer_runtime_id: "voidbot-yggdrasil".into(), - provider: "bifrost".into(), - bifrost_admission_receipt_id: format!("receipt-{id}"), - authority: "exact_operator_command_only".into(), - provider_identity_id: signer.entry().identity_id.clone(), - provider_signature: Vec::new(), - }; - admission.provider_signature = signer - .sign( - SIGNING_PURPOSE, - &operator_command_admission_signing_payload(&admission)?, - )? - .signature; - Ok(admission) - } - - fn snapshot() -> crate::EpiphanyCultMeshOperatorSnapshotEntry { - crate::EpiphanyCultMeshOperatorSnapshotEntry { - schema_version: crate::EPIPHANY_CULTMESH_OPERATOR_SNAPSHOT_SCHEMA_VERSION.into(), - runtime_id: "epiphany-yggdrasil".into(), - verse_id: crate::EPIPHANY_CULTMESH_INTERNAL_VERSE_ID.into(), - snapshot_id: "snapshot-1".into(), - generated_at_utc: "2026-07-19T11:58:00Z".into(), - source_mode: "native".into(), - source_path: "cultcache://operator-safe/status".into(), - thread_id: "thread-1".into(), - status: "sleeping".into(), - state_status: "ready".into(), - coordinator_action: "none".into(), - crrc_action: "none".into(), - pressure_level: "low".into(), - reorient_action: "none".into(), - next_action: "await pressure".into(), - artifact_refs: Vec::new(), - available_actions: vec!["status".into()], - notes: Vec::new(), - } - } - - #[test] - fn hostile_commands_refuse_without_local_writes() -> Result<()> { - let temp = tempfile::tempdir()?; - let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; - let anchor = - crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?; - for case in ["signature", "runtime", "channel", "actor", "expired"] { - let root = temp.path().join(case); - std::fs::create_dir_all(&root)?; - let (commands, verse, resident) = ( - root.join("commands.cc"), - root.join("verse.cc"), - root.join("resident.cc"), - ); - let mut admission = signed( - &signer, - case, - OperatorCommand::Directive { - objective: "Map this domain.".into(), - }, - )?; - match case { - "signature" => admission.provider_signature[0] ^= 1, - "runtime" => admission.packet.target_runtime_id = "alien".into(), - "channel" => admission.packet.discord_channel_id = "alien".into(), - "actor" => admission.packet.source_actor_id = "alien".into(), - "expired" => admission.packet.expires_at = "2026-07-19T11:59:30Z".into(), - _ => unreachable!(), - } - assert!( - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &admission, - &anchor, - &policy(), - "2026-07-19T12:00:00Z" - ) - .is_err() - ); - assert!(!commands.exists() && !verse.exists() && !resident.exists()); - } - Ok(()) - } - - #[test] - fn superseded_delivery_schema_is_rejected_without_local_writes() -> Result<()> { - let temp = tempfile::tempdir()?; - let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; - let anchor = - crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?; - let (commands, verse, resident, runtime) = ( - temp.path().join("commands.cc"), - temp.path().join("verse.cc"), - temp.path().join("resident.cc"), - temp.path().join("runtime.cc"), - ); - let mut superseded = signed( - &signer, - "superseded-sleep", - OperatorCommand::Sleep { - reason: "This packet uses the superseded delivery contract.".into(), - }, - )?; - superseded.schema_version = "bifrost.operator_command.delivery.v1".into(); - assert!( - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &runtime, - &superseded, - &anchor, - &policy(), - "2026-07-19T12:00:00Z", - ) - .is_err() - ); - assert!(!commands.exists() && !verse.exists() && !resident.exists() && !runtime.exists()); - Ok(()) - } - - #[test] - fn commands_delegate_without_wake_or_directive_authority_leak() -> Result<()> { - let temp = tempfile::tempdir()?; - let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; - let anchor = - crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?; - let (commands, verse, resident) = ( - temp.path().join("commands.cc"), - temp.path().join("verse.cc"), - temp.path().join("resident.cc"), - ); - crate::write_epiphany_cultmesh_operator_snapshot(&verse, snapshot())?; - let p = policy(); - let status = signed(&signer, "status", OperatorCommand::Status)?; - let status_result = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &status, - &anchor, - &p, - "2026-07-19T12:00:00Z", - )?; - assert_eq!(status_result.consequence_ref, "snapshot-1"); - assert_eq!( - status_result.operator_status, - "coordinator-snapshot/sleeping" - ); - assert_eq!(status_result.state_status, "coordinator-state/ready"); - assert_eq!(status_result.coordinator_action, "coordinator-action/none"); - assert!( - [ - status_result.operator_status.as_str(), - status_result.state_status.as_str(), - status_result.coordinator_action.as_str(), - ] - .into_iter() - .all(|value| value != "ready" && value != "none") - ); - assert!( - status_result - .detail - .contains("not deployment or provider readiness") - ); - assert!(!resident.exists()); - let sleep = signed( - &signer, - "sleep", - OperatorCommand::Sleep { - reason: "Move preparation.".into(), - }, - )?; - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &sleep, - &anchor, - &p, - "2026-07-19T12:00:00Z", - )?; - let written_brake = - load_epiphany_cultmesh_swarm_brake(&verse, p.runtime_id.clone())?.unwrap(); - assert_eq!(written_brake.status, "engaged"); - assert_eq!(written_brake.brake_id, EPIPHANY_CANONICAL_SWARM_BRAKE_ID); - assert_eq!( - written_brake.operator_agent_id, - EPIPHANY_CANONICAL_SWARM_BRAKE_OWNER - ); - assert_eq!(written_brake.scope, "all"); - assert_eq!( - written_brake.protected_surfaces, - vec![ - "heartbeat.scheduler", - "coordinator.run", - "persona.public_speech", - "daemon.tool_invocation", - "daemon.lifecycle_poke", - "atlas.publish", - "atlas.project", - "atlas.impact_ingress" - ] - ); - assert!( - !written_brake - .protected_surfaces - .iter() - .any(|surface| matches!( - surface.as_str(), - "scheduling" | "daemon-pokes" | "operator-runs" - )) - ); - let wake = signed(&signer, "wake", OperatorCommand::Wake)?; - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &wake, - &anchor, - &p, - "2026-07-19T12:00:01Z", - )?; - assert_eq!( - load_epiphany_cultmesh_swarm_brake(&verse, p.runtime_id.clone())? - .unwrap() - .status, - "released" - ); - assert!( - !resident.exists(), - "wake created pressure, grant, or job authority" - ); - let directive = signed( - &signer, - "directive", - OperatorCommand::Directive { - objective: "Map the operator nerve.".into(), - }, - )?; - let first = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &directive, - &anchor, - &p, - "2026-07-19T12:00:02Z", - )?; - let pressures = resident_self_pressures(&resident)?; - assert_eq!(pressures.len(), 1); - assert_eq!(pressures[0].kind, "operator-objective"); - assert!(pressures[0].consumed_by_grant_id.is_none()); - assert_eq!( - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &directive, - &anchor, - &p, - "2026-07-19T12:00:03Z" - )?, - first - ); - assert_eq!(resident_self_pressures(&resident)?.len(), 1); - Ok(()) - } - - #[test] - fn wake_cannot_release_the_deployment_brake() -> Result<()> { - let temp = tempfile::tempdir()?; - let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; - let anchor = - crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?; - let (commands, verse, resident) = ( - temp.path().join("commands.cc"), - temp.path().join("verse.cc"), - temp.path().join("resident.cc"), - ); - let mut deployment = crate::default_epiphany_cultmesh_swarm_brake("2026-07-19T11:00:00Z"); - deployment.brake_id = "epiphany-yggdrasil/deployment-brake".into(); - deployment.runtime_id = "epiphany-yggdrasil".into(); - crate::write_epiphany_cultmesh_swarm_brake(&verse, "epiphany-yggdrasil", deployment)?; - let before = std::fs::read(&verse)?; - let wake = signed(&signer, "foreign-wake", OperatorCommand::Wake)?; - let refused = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &wake, - &anchor, - &policy(), - "2026-07-19T12:00:00Z", - )?; - assert_eq!(refused.disposition, "refused"); - assert_eq!(std::fs::read(&verse)?, before); - assert!(!resident.exists()); - assert_eq!( - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &wake, - &anchor, - &policy(), - "2026-07-19T12:00:01Z" - )?, - refused - ); - assert_eq!(std::fs::read(&verse)?, before); - Ok(()) - } - - #[test] - fn replay_recovers_after_admission_and_consequence_without_result() -> Result<()> { - let temp = tempfile::tempdir()?; - let signer = crate::enroll_host_identity_at(&temp.path().join("identity.cc"))?; - let anchor = - crate::export_host_identity_trust_anchor(&signer, &temp.path().join("anchor.cc"))?; - let (commands, verse, resident) = ( - temp.path().join("commands.cc"), - temp.path().join("verse.cc"), - temp.path().join("resident.cc"), - ); - let admission = signed( - &signer, - "crash-recovery", - OperatorCommand::Directive { - objective: "Recover the exact pressure.".into(), - }, - )?; - let packet = &admission.packet; - let admitted = LocalAdmittedOperatorCommand { - schema_version: LOCAL_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(), - command_id: packet.command_id.clone(), - admission_id: admission.admission_id.clone(), - nonce: packet.nonce.clone(), - packet_sha256: admission.packet_sha256.clone(), - source_actor_id: packet.source_actor_id.clone(), - capability: "directive".into(), - target_runtime_id: packet.target_runtime_id.clone(), - admitted_at: "2026-07-19T12:00:00Z".into(), - expires_at: packet.expires_at.clone(), - authority: "exact-command-only".into(), - private_state_exposed: false, - }; - let cache = command_cache(&commands)?; - let (entry, _) = cache.prepare_entry(&packet.command_id, &admitted)?; - assert!(SingleFileMessagePackBackingStore::new(&commands).insert_entry_if_absent(entry)?); - let pressure = ResidentSelfPressure { - schema_version: crate::RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(), - pressure_id: format!("operator-command-{}", packet.command_id), - kind: "operator-objective".into(), - provenance_ref: format!("cultcache://operator-command/{}", packet.command_id), - objective: "Recover the exact pressure.".into(), - created_at_millis: issued_millis(&packet.issued_at)?, - status: "pending".into(), - consumed_by_grant_id: None, - private_state_exposed: false, - }; - enqueue_resident_self_pressure(&resident, &pressure)?; - let result = admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &admission, - &anchor, - &policy(), - "2026-07-19T12:06:00Z", - )?; - assert_eq!(result.disposition, "applied"); - assert_eq!(resident_self_pressures(&resident)?, vec![pressure]); - assert_eq!( - admit_and_execute_bifrost_operator_command( - &commands, - &verse, - &resident, - &resident, - &admission, - &anchor, - &policy(), - "2026-07-19T12:00:04Z" - )?, - result - ); - Ok(()) - } -} diff --git a/epiphany-core/src/operator_command_service.rs b/epiphany-core/src/operator_command_service.rs deleted file mode 100644 index b99b90b6..00000000 --- a/epiphany-core/src/operator_command_service.rs +++ /dev/null @@ -1,1564 +0,0 @@ -use anyhow::{Context, Result, anyhow, bail}; -use chrono::Utc; -use cultcache_rs::{ - CacheBackingStore, CultCache, DatabaseEntry, SingleFileMessagePackBackingStore, -}; -use cultnet_rs::{ - CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, - CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, CultNetWireContract, - GameCultServiceTrustAnchorRecord, decode_cultnet_message_from_slice, - encode_cultnet_message_to_vec, query_read_only_raw_snapshot, -}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::net::{SocketAddr, UdpSocket}; -use std::path::{Path, PathBuf}; -use std::time::Duration; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; - -use crate::{ - BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE, BifrostOperatorCommandAdmission, HostIdentitySigner, - HostIdentityTrustAnchorEntry, IdunnProviderHealthAdmission, OperatorCommand, - OperatorCommandPolicy, OperatorCommandResult, ProviderReleaseBinding, RequiredProviderHealth, - admit_and_execute_bifrost_operator_command, admit_required_idunn_provider_health, - load_resident_self_state, pending_repo_frontier_plan_reviews, - read_idunn_provider_health_trust_anchor, required_idunn_provider_health_query, - resident_self_pressures, verify_idunn_provider_health_candidate, -}; - -pub const EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_TYPE: &str = - "epiphany.operator_command.sealed_result"; -pub const EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.operator_command.sealed_result.v2"; -const RESULT_SIGNING_PURPOSE: &str = "epiphany.operator-command.sealed-result.v2"; -pub const EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID: u32 = 0xe91f_0001; -pub const EPIPHANY_OPERATOR_COMMAND_SERVICE_HEALTH_SCHEMA_VERSION: &str = - "epiphany.operator_command.service_health.v0"; -const SERVICE_HEALTH_KEY: &str = "operator-command-service"; -const SERVICE_HEALTH_SIGNING_PURPOSE: &str = "epiphany.operator-command.service-health.v0"; -const IDUNN_PUBLIC_HEALTH_QUERY_CONNECTION_ID: u32 = 0x1d0d_0002; - -#[derive(Clone, Debug)] -pub struct OperatorCommandServiceConfig { - pub command_store: PathBuf, - pub local_verse_store: PathBuf, - pub resident_self_store: PathBuf, - pub runtime_store: PathBuf, - pub policy: OperatorCommandPolicy, - pub trusted_bifrost_identity: HostIdentityTrustAnchorEntry, - pub provider_health: OperatorStatusProviderHealthConfig, -} - -#[derive(Clone, Debug)] -pub struct OperatorStatusProviderHealthConfig { - pub query_endpoint: SocketAddr, - pub idunn_runtime_id: String, - pub trust_anchor_store: PathBuf, - pub admission_store: PathBuf, - pub max_local_age_millis: u64, - pub deployment_id: String, - pub release_id: String, - pub release_witness_sha256: String, - pub source_commit: String, -} - -#[derive(Clone, Debug)] -pub struct OperatorCommandServiceHealthConfig { - pub store: PathBuf, - pub bind: String, - pub release_id: String, - pub release_witness_sha256: String, - pub source_commit: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.operator_command.service_health", - schema = "EpiphanyOperatorCommandServiceHealth" -)] -pub struct EpiphanyOperatorCommandServiceHealth { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub runtime_id: String, - #[cultcache(key = 2)] - pub release_id: String, - #[cultcache(key = 3)] - pub release_witness_sha256: String, - #[cultcache(key = 4)] - pub source_commit: String, - #[cultcache(key = 5)] - pub bind: String, - #[cultcache(key = 6)] - pub config_sha256: String, - #[cultcache(key = 7)] - pub bifrost_identity_id: String, - #[cultcache(key = 8)] - pub executor_identity_id: String, - #[cultcache(key = 9)] - pub observed_at: String, - #[cultcache(key = 10)] - pub observed_at_millis: u64, - #[cultcache(key = 11)] - pub process_id: u32, - #[cultcache(key = 12)] - pub process_creation_token: u64, - #[cultcache(key = 13)] - pub process_executable_path: String, - #[cultcache(key = 14)] - pub private_state_exposed: bool, - #[cultcache(key = 15)] - pub executor_signature: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct EpiphanyOperatorCommandResultReceipt { - pub schema_version: String, - pub result: EpiphanyOperatorCommandWireResult, - pub result_payload_sha256: String, - pub command_id: String, - pub packet_sha256: String, - pub target_runtime_id: String, - pub completed_at: String, - pub provider_identity_id: String, - pub private_state_exposed: bool, - pub executor_signature: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct EpiphanyOperatorCommandWireResult { - pub schema_version: String, - pub result_id: String, - pub command_id: String, - pub packet_sha256: String, - pub target_runtime_id: String, - pub disposition: String, - pub consequence_kind: String, - pub consequence_ref: String, - pub completed_at: String, - pub private_state_exposed: bool, - pub operator_status: String, - pub state_status: String, - pub coordinator_action: String, - pub brake_status: String, - pub detail: String, - pub reviews: Vec, - pub review_candidate_id: String, - pub review_decision: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub status_v2: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct EpiphanyOperatorStatusProviderV2 { - pub daemon_id: String, - pub health_contract: String, - pub availability: String, - pub unavailable_reason: String, - pub state: Option, - pub reason_code: Option, - pub provider_observed_at_unix_millis: Option, - pub evaluated_at_unix_millis: Option, - pub expires_at_unix_millis: Option, - pub release_id: Option, - pub release_witness_sha256: Option, - pub source_commit: Option, - pub deployment_id: Option, - pub projection_sha256: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct EpiphanyOperatorStatusV2 { - pub schema_version: String, - pub release_id: String, - pub release_witness_sha256: String, - pub source_commit: String, - pub deployment_id: String, - pub coordinator_snapshot: String, - pub coordinator_state: String, - pub coordinator_action: String, - pub brake_status: String, - pub resident_status: String, - pub pressure_count: usize, - pub pending_review_count: usize, - pub provider_set_status: String, - pub providers: Vec, - pub private_state_exposed: bool, -} - -impl From<&OperatorCommandResult> for EpiphanyOperatorCommandWireResult { - fn from(value: &OperatorCommandResult) -> Self { - Self { - schema_version: value.schema_version.clone(), - result_id: value.result_id.clone(), - command_id: value.command_id.clone(), - packet_sha256: value.packet_sha256.clone(), - target_runtime_id: value.target_runtime_id.clone(), - disposition: value.disposition.clone(), - consequence_kind: value.consequence_kind.clone(), - consequence_ref: value.consequence_ref.clone(), - completed_at: value.completed_at.clone(), - private_state_exposed: value.private_state_exposed, - operator_status: value.operator_status.clone(), - state_status: value.state_status.clone(), - coordinator_action: value.coordinator_action.clone(), - brake_status: value.brake_status.clone(), - detail: value.detail.clone(), - reviews: value.reviews.clone(), - review_candidate_id: value.review_candidate_id.clone(), - review_decision: value.review_decision.clone(), - status_v2: None, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct OperatorCommandServiceReadiness { - pub schema_version: String, - pub status: String, - pub runtime_id: String, - pub bind: String, - pub executor_identity_id: String, - pub private_state_exposed: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct OperatorCommandInteropFixtureManifest { - pub schema_version: String, - pub admission_file: String, - pub bifrost_raw_trust_anchor_file: String, - pub executor_raw_trust_anchor_file: String, - pub executor_cultcache_trust_anchor_file: String, - pub sealed_result_file: String, - pub protocol_file: String, - pub admission_sha256: String, - pub sealed_result_sha256: String, - pub protocol_sha256: String, - pub admission_signing_purpose: String, - pub result_signing_purpose: String, - pub rudp_connection_id: u32, - pub private_state_exposed: bool, -} - -pub fn operator_command_result_receipt_signing_purpose() -> &'static str { - RESULT_SIGNING_PURPOSE -} - -pub fn operator_command_result_receipt_signing_payload( - receipt: &EpiphanyOperatorCommandResultReceipt, -) -> Result> { - rmp_serde::to_vec(&( - receipt.schema_version.as_str(), - &receipt.result, - receipt.result_payload_sha256.as_str(), - receipt.command_id.as_str(), - receipt.packet_sha256.as_str(), - receipt.target_runtime_id.as_str(), - receipt.completed_at.as_str(), - receipt.provider_identity_id.as_str(), - receipt.private_state_exposed, - )) - .map_err(Into::into) -} - -pub fn execute_operator_command_admission( - config: &OperatorCommandServiceConfig, - signer: &HostIdentitySigner, - admission_payload: &[u8], - now: &str, -) -> Result { - let admission: BifrostOperatorCommandAdmission = rmp_serde::from_slice(admission_payload) - .context("operator service rejected malformed or non-strict Bifrost admission")?; - let result = admit_and_execute_bifrost_operator_command( - &config.command_store, - &config.local_verse_store, - &config.resident_self_store, - &config.runtime_store, - &admission, - &config.trusted_bifrost_identity, - &config.policy, - now, - )?; - let mut wire_result = EpiphanyOperatorCommandWireResult::from(&result); - if matches!(admission.packet.command, OperatorCommand::Status) { - wire_result.schema_version = "epiphany.operator_command.status_result.v2".into(); - wire_result.status_v2 = Some(build_operator_status_v2(config, &result)?); - } - let result_payload = rmp_serde::to_vec_named(&wire_result)?; - let mut receipt = EpiphanyOperatorCommandResultReceipt { - schema_version: EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION.into(), - result_payload_sha256: format!("sha256-{:x}", Sha256::digest(&result_payload)), - command_id: result.command_id.clone(), - packet_sha256: result.packet_sha256.clone(), - target_runtime_id: result.target_runtime_id.clone(), - completed_at: result.completed_at.clone(), - provider_identity_id: signer.entry().identity_id.clone(), - private_state_exposed: false, - executor_signature: Vec::new(), - result: wire_result, - }; - receipt.executor_signature = signer - .sign( - RESULT_SIGNING_PURPOSE, - &operator_command_result_receipt_signing_payload(&receipt)?, - )? - .signature; - Ok(receipt) -} - -fn required_status_providers( - config: &OperatorStatusProviderHealthConfig, -) -> Vec { - vec![ - RequiredProviderHealth { - daemon_id: "yggdrasil-epiphany".into(), - health_contract: crate::EPIPHANY_IDUNN_RUNTIME_HEALTH_CONTRACT.into(), - release_binding: ProviderReleaseBinding::Exact { - release_id: config.release_id.clone(), - release_witness_sha256: config.release_witness_sha256.clone(), - source_commit: config.source_commit.clone(), - deployment_id: config.deployment_id.clone(), - }, - }, - RequiredProviderHealth { - daemon_id: "yggdrasil-bifrost-persona-feedback".into(), - health_contract: "bifrost.cultnet-rudp-persona-feedback-health".into(), - release_binding: ProviderReleaseBinding::Forbidden, - }, - ] -} - -fn build_operator_status_v2( - config: &OperatorCommandServiceConfig, - result: &OperatorCommandResult, -) -> Result { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH)? - .as_millis() - .try_into()?; - let required = required_status_providers(&config.provider_health); - let (providers, complete) = match query_and_admit_status_providers(config, &required, now) { - Ok(value) => value, - Err(_) => ( - required - .iter() - .map(|item| { - unavailable_provider(item, "authenticated-provider-snapshot-unavailable") - }) - .collect(), - false, - ), - }; - let resident = load_resident_self_state(&config.resident_self_store)?; - Ok(EpiphanyOperatorStatusV2 { - schema_version: "epiphany.operator.status.v2".into(), - release_id: config.provider_health.release_id.clone(), - release_witness_sha256: config.provider_health.release_witness_sha256.clone(), - source_commit: config.provider_health.source_commit.clone(), - deployment_id: config.provider_health.deployment_id.clone(), - coordinator_snapshot: result.operator_status.clone(), - coordinator_state: result.state_status.clone(), - coordinator_action: result.coordinator_action.clone(), - brake_status: result.brake_status.clone(), - resident_status: if resident.active_turn.is_some() { - "resident-self/running" - } else { - "resident-self/idle" - } - .into(), - pressure_count: resident_self_pressures(&config.resident_self_store)?.len(), - pending_review_count: pending_repo_frontier_plan_reviews(&config.runtime_store, 25)?.len(), - provider_set_status: if complete { - "complete-authenticated" - } else { - "incomplete" - } - .into(), - providers, - private_state_exposed: false, - }) -} - -fn query_and_admit_status_providers( - config: &OperatorCommandServiceConfig, - required: &[RequiredProviderHealth], - now: u64, -) -> Result<(Vec, bool)> { - let anchor: GameCultServiceTrustAnchorRecord = - read_idunn_provider_health_trust_anchor(&config.provider_health.trust_anchor_store)?; - let query = required_idunn_provider_health_query( - format!("operator-status-{now}"), - required, - &config.provider_health.idunn_runtime_id, - )?; - let records = query_read_only_raw_snapshot(&query, |request| { - exchange_idunn_public_snapshot( - config.provider_health.query_endpoint, - &config.policy.runtime_id, - request, - ) - })?; - let mut projected = Vec::with_capacity(required.len()); - let mut verified_records = Vec::with_capacity(required.len()); - for requirement in required { - let Some(record) = records - .iter() - .find(|record| record.record_key == requirement.record_key()) - else { - projected.push(unavailable_provider( - requirement, - "required-provider-record-missing", - )); - continue; - }; - match verify_idunn_provider_health_candidate( - requirement, - record, - &anchor, - &config.provider_health.idunn_runtime_id, - now, - config.provider_health.max_local_age_millis, - ) { - Ok(value) => { - projected.push(available_provider(&value)); - verified_records.push(record.clone()); - } - Err(_) => projected.push(unavailable_provider( - requirement, - "required-provider-record-invalid", - )), - } - } - let complete = verified_records.len() == required.len(); - if complete { - admit_required_idunn_provider_health( - &config.provider_health.admission_store, - required, - &verified_records, - &anchor, - &config.provider_health.idunn_runtime_id, - now, - config.provider_health.max_local_age_millis, - )?; - } - Ok((projected, complete)) -} - -fn exchange_idunn_public_snapshot( - endpoint: SocketAddr, - runtime_id: &str, - request: CultNetMessage, -) -> Result { - let socket = UdpSocket::bind("0.0.0.0:0")?; - socket.set_read_timeout(Some(Duration::from_millis(100)))?; - let mut transport = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::client( - runtime_id, - socket, - endpoint, - IDUNN_PUBLIC_HEALTH_QUERY_CONNECTION_ID, - ))?; - transport.connect(Vec::new())?; - let deadline = Instant::now() + Duration::from_secs(2); - while !transport.connected() { - let _ = transport.receive_once()?; - transport.poll_resends()?; - if Instant::now() >= deadline { - bail!("Idunn public provider-health handshake unavailable"); - } - } - transport.send( - "schema", - encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?, - )?; - loop { - if let Some(frame) = transport.receive_once()? { - if frame.channel_id != "schema" { - bail!("Idunn public provider-health response channel is invalid"); - } - return decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - ); - } - transport.poll_resends()?; - if Instant::now() >= deadline { - bail!("Idunn public provider-health response unavailable"); - } - } -} - -fn available_provider(value: &IdunnProviderHealthAdmission) -> EpiphanyOperatorStatusProviderV2 { - EpiphanyOperatorStatusProviderV2 { - daemon_id: value.daemon_id.clone(), - health_contract: value.health_contract.clone(), - availability: "authenticated-current".into(), - unavailable_reason: String::new(), - state: Some(value.provider_state.clone()), - reason_code: Some(value.reason_code.clone()), - provider_observed_at_unix_millis: Some(value.provider_observed_at_unix_millis), - evaluated_at_unix_millis: Some(value.evaluated_at_unix_millis), - expires_at_unix_millis: Some(value.expires_at_unix_millis), - release_id: value.release_id.clone(), - release_witness_sha256: value.release_witness_sha256.clone(), - source_commit: value.source_commit.clone(), - deployment_id: value.deployment_id.clone(), - projection_sha256: Some(value.projection_sha256.clone()), - } -} - -fn unavailable_provider( - value: &RequiredProviderHealth, - reason: &str, -) -> EpiphanyOperatorStatusProviderV2 { - EpiphanyOperatorStatusProviderV2 { - daemon_id: value.daemon_id.clone(), - health_contract: value.health_contract.clone(), - availability: "unavailable".into(), - unavailable_reason: reason.into(), - state: None, - reason_code: None, - provider_observed_at_unix_millis: None, - evaluated_at_unix_millis: None, - expires_at_unix_millis: None, - release_id: None, - release_witness_sha256: None, - source_commit: None, - deployment_id: None, - projection_sha256: None, - } -} - -fn operator_status_v2_migration_fixture() -> EpiphanyOperatorStatusV2 { - let requirements = required_status_providers(&OperatorStatusProviderHealthConfig { - query_endpoint: "127.0.0.1:1".parse().expect("fixed fixture endpoint"), - idunn_runtime_id: "idunn-yggdrasil".into(), - trust_anchor_store: PathBuf::new(), - admission_store: PathBuf::new(), - max_local_age_millis: 30_000, - deployment_id: "deployment-fixture".into(), - release_id: "release-fixture".into(), - release_witness_sha256: format!("sha256-{}", "a".repeat(64)), - source_commit: "b".repeat(40), - }); - EpiphanyOperatorStatusV2 { - schema_version: "epiphany.operator.status.v2".into(), - release_id: "release-fixture".into(), - release_witness_sha256: format!("sha256-{}", "a".repeat(64)), - source_commit: "b".repeat(40), - deployment_id: "deployment-fixture".into(), - coordinator_snapshot: "coordinator-snapshot/sleeping".into(), - coordinator_state: "coordinator-state/ready".into(), - coordinator_action: "coordinator-action/none".into(), - brake_status: "engaged".into(), - resident_status: "resident-self/idle".into(), - pressure_count: 0, - pending_review_count: 0, - provider_set_status: "incomplete".into(), - providers: requirements - .iter() - .map(|value| unavailable_provider(value, "required-provider-record-missing")) - .collect(), - private_state_exposed: false, - } -} - -pub fn serve_operator_command_rudp( - socket: UdpSocket, - config: &OperatorCommandServiceConfig, - signer: &HostIdentitySigner, - health: &OperatorCommandServiceHealthConfig, -) -> Result<()> { - socket.set_read_timeout(Some(Duration::from_millis(100)))?; - let mut transport = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::server( - &config.policy.runtime_id, - socket, - EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID, - ))?; - serve_operator_command_rudp_loop(&mut transport, config, signer, Some(health), None, None) -} - -fn serve_operator_command_rudp_loop( - transport: &mut CultNetRudpSocketTransportConnection, - config: &OperatorCommandServiceConfig, - signer: &HostIdentitySigner, - health: Option<&OperatorCommandServiceHealthConfig>, - iteration_limit: Option, - fixed_now: Option<&str>, -) -> Result<()> { - let mut iterations = 0usize; - let mut last_health = None::; - loop { - if iteration_limit.is_some_and(|limit| iterations >= limit) { - return Ok(()); - } - iterations += 1; - if let Some(health) = health { - if last_health.is_none_or(|at| at.elapsed() >= Duration::from_secs(5)) { - publish_operator_command_service_health(&health.store, config, signer, health)?; - last_health = Some(Instant::now()); - } - } - match transport.receive_once() { - Ok(Some(frame)) => { - let response = match fixed_now { - Some(now) => process_wire_frame_at(config, signer, &frame.payload, now), - None => process_wire_frame(config, signer, &frame.payload), - }; - if let Ok(message) = response { - match encode_cultnet_message_to_vec( - &message, - CultNetWireContract::CultNetSchemaV0, - ) { - Ok(payload) => { - if let Err(error) = transport.send("schema", payload) { - eprintln!("operator service reply transport error: {error:#}"); - } - } - Err(error) => eprintln!("operator service reply encoding error: {error:#}"), - } - } - } - Ok(None) => {} - Err(error) => { - eprintln!("operator service discarded hostile transport frame: {error:#}") - } // Malformed, foreign, unsigned, expired-new, and capability-invalid - // admissions receive no signed application reply. A receipt would - // falsely turn unauthenticated material into an Epiphany statement. - // Authenticated owner precondition failures are instead returned by - // the core as sealed `refused` results. - } - if let Err(error) = transport.poll_resends() { - eprintln!("operator service resend transport error: {error:#}"); - } - } -} - -fn service_config_sha256( - config: &OperatorCommandServiceConfig, - health: &OperatorCommandServiceHealthConfig, -) -> Result { - let bytes = rmp_serde::to_vec(&( - config.policy.runtime_id.as_str(), - config.policy.discord_guild_id.as_str(), - &config.policy.allowed_channel_ids, - &config.policy.actor_capabilities, - config.policy.max_ttl_seconds, - config.trusted_bifrost_identity.identity_id.as_str(), - ( - config.provider_health.query_endpoint, - config.provider_health.idunn_runtime_id.as_str(), - &config.provider_health.trust_anchor_store, - &config.provider_health.admission_store, - config.provider_health.max_local_age_millis, - config.provider_health.deployment_id.as_str(), - config.provider_health.release_id.as_str(), - config.provider_health.release_witness_sha256.as_str(), - config.provider_health.source_commit.as_str(), - ), - health.bind.as_str(), - health.release_id.as_str(), - health.release_witness_sha256.as_str(), - health.source_commit.as_str(), - ))?; - Ok(format!("sha256-{:x}", Sha256::digest(bytes))) -} - -fn service_health_signing_payload(value: &EpiphanyOperatorCommandServiceHealth) -> Result> { - rmp_serde::to_vec(&( - value.schema_version.as_str(), - value.runtime_id.as_str(), - value.release_id.as_str(), - value.release_witness_sha256.as_str(), - value.source_commit.as_str(), - value.bind.as_str(), - value.config_sha256.as_str(), - value.bifrost_identity_id.as_str(), - value.executor_identity_id.as_str(), - value.observed_at.as_str(), - value.observed_at_millis, - value.process_id, - value.process_creation_token, - value.process_executable_path.as_str(), - value.private_state_exposed, - )) - .map_err(Into::into) -} - -pub fn publish_operator_command_service_health( - store: &Path, - config: &OperatorCommandServiceConfig, - signer: &HostIdentitySigner, - health: &OperatorCommandServiceHealthConfig, -) -> Result { - let observed_at_millis = SystemTime::now() - .duration_since(UNIX_EPOCH)? - .as_millis() - .try_into() - .context("operator health time exceeds u64")?; - let process = crate::capture_process_instance(std::process::id())?; - let mut value = EpiphanyOperatorCommandServiceHealth { - schema_version: EPIPHANY_OPERATOR_COMMAND_SERVICE_HEALTH_SCHEMA_VERSION.into(), - runtime_id: config.policy.runtime_id.clone(), - release_id: health.release_id.clone(), - release_witness_sha256: health.release_witness_sha256.clone(), - source_commit: health.source_commit.clone(), - bind: health.bind.clone(), - config_sha256: service_config_sha256(config, health)?, - bifrost_identity_id: config.trusted_bifrost_identity.identity_id.clone(), - executor_identity_id: signer.entry().identity_id.clone(), - observed_at: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), - observed_at_millis, - process_id: process.process_id, - process_creation_token: process.creation_token, - process_executable_path: process.executable_path.display().to_string(), - private_state_exposed: false, - executor_signature: Vec::new(), - }; - value.executor_signature = signer - .sign( - SERVICE_HEALTH_SIGNING_PURPOSE, - &service_health_signing_payload(&value)?, - )? - .signature; - let backing = SingleFileMessagePackBackingStore::new(store); - let existing = backing.pull_all()?.into_iter().find(|entry| { - entry.r#type == ::TYPE - && entry.key == SERVICE_HEALTH_KEY - }); - let mut cache = CultCache::new(); - cache.register_entry_type::()?; - let (replacement, _) = cache.prepare_entry(SERVICE_HEALTH_KEY, &value)?; - let committed = match existing { - Some(expected) => backing.compare_and_swap_entry(&expected, replacement)?, - None => backing.insert_entry_if_absent(replacement)?, - }; - if !committed { - bail!("operator service health lost exact CAS"); - } - Ok(value) -} - -pub fn authenticate_operator_command_service_health( - store: &Path, - runtime_id: &str, - release_id: &str, - release_witness_sha256: &str, - source_commit: &str, - bind: &str, - executor: &HostIdentityTrustAnchorEntry, - now_millis: u64, - freshness_millis: u64, -) -> Result { - let mut matches = SingleFileMessagePackBackingStore::new(store) - .pull_all()? - .into_iter() - .filter(|entry| { - entry.r#type == ::TYPE - && entry.key == SERVICE_HEALTH_KEY - }); - let envelope = matches - .next() - .context("operator service health is absent")?; - if matches.next().is_some() { - bail!("operator service health has duplicate owner state"); - } - let value: EpiphanyOperatorCommandServiceHealth = rmp_serde::from_slice(&envelope.payload)?; - if value.schema_version != EPIPHANY_OPERATOR_COMMAND_SERVICE_HEALTH_SCHEMA_VERSION - || value.private_state_exposed - || value.runtime_id != runtime_id - || value.release_id != release_id - || value.release_witness_sha256 != release_witness_sha256 - || value.source_commit != source_commit - || value.bind != bind - || !value.config_sha256.starts_with("sha256-") - || value.config_sha256.len() != 71 - || value.bifrost_identity_id.trim().is_empty() - || value.executor_identity_id != executor.identity_id - || value.process_id == 0 - || value.process_creation_token == 0 - || value.process_executable_path.trim().is_empty() - || value.observed_at_millis > now_millis - || now_millis.saturating_sub(value.observed_at_millis) > freshness_millis - { - bail!("operator service health is stale or not bound to the exact release/config/identity"); - } - crate::verify_host_identity_trust_anchor_signature( - executor, - SERVICE_HEALTH_SIGNING_PURPOSE, - &service_health_signing_payload(&value)?, - &crate::HostIdentitySignature { - identity_id: value.executor_identity_id.clone(), - signature: value.executor_signature.clone(), - }, - )?; - Ok(value) -} - -fn process_wire_frame( - config: &OperatorCommandServiceConfig, - signer: &HostIdentitySigner, - payload: &[u8], -) -> Result { - process_wire_frame_at(config, signer, payload, &chrono::Utc::now().to_rfc3339()) -} - -fn process_wire_frame_at( - config: &OperatorCommandServiceConfig, - signer: &HostIdentitySigner, - payload: &[u8], - now: &str, -) -> Result { - let message = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0) - .context("operator service rejected non-CultNet payload")?; - let CultNetMessage::DocumentPutRaw { document, .. } = message else { - bail!("operator service accepts only one raw typed admission document"); - }; - if document.schema_id != BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE - || document.payload_encoding != CultNetRawPayloadEncoding::Messagepack - || document.source_role.as_deref() != Some("bifrost-operator-admission") - { - bail!("operator service rejected foreign wire document authority"); - } - let admission: BifrostOperatorCommandAdmission = - rmp_serde::from_slice(&document.payload).context("operator wire admission is malformed")?; - if document.record_key != admission.admission_id - || document.source_runtime_id.as_deref() - != Some(admission.source_observer_runtime_id.as_str()) - { - bail!("operator wire envelope substituted admission identity"); - } - let receipt = execute_operator_command_admission(config, signer, &document.payload, now)?; - Ok(CultNetMessage::DocumentPutRaw { - message_id: format!("operator-result-{}", receipt.command_id), - document: CultNetRawDocumentRecord { - schema_id: EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_TYPE.into(), - record_key: receipt.command_id.clone(), - stored_at: receipt.completed_at.clone(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: rmp_serde::to_vec_named(&receipt)?, - source_runtime_id: Some(config.policy.runtime_id.clone()), - source_agent_id: Some(receipt.provider_identity_id.clone()), - source_role: Some("epiphany-operator-command-executor".into()), - tags: Some(vec!["cultnet.transport.rudp.v0".into()]), - }, - }) -} - -pub fn read_operator_command_trust_anchor(path: &Path) -> Result { - // This is the Bifrost-owned boundary artifact: one raw compact MessagePack - // six-tuple. Epiphany's canonical exported `.cc` anchor is a CultCache - // envelope and intentionally is not accepted by this ingress reader. - rmp_serde::from_slice(&std::fs::read(path)?) - .map_err(|error| anyhow!("operator Bifrost trust anchor is malformed: {error}")) -} - -pub fn write_operator_command_interop_fixture( - output: &Path, -) -> Result { - std::fs::create_dir_all(output)?; - let private = output.join(".fixture-private"); - if private.exists() { - bail!("operator interop fixture private workspace already exists"); - } - std::fs::create_dir(&private)?; - let generated = (|| -> Result { - let bifrost = crate::enroll_host_identity_at(&private.join("bifrost.cc"))?; - let executor = crate::enroll_host_identity_at(&private.join("executor.cc"))?; - let bifrost_anchor = - crate::export_host_identity_trust_anchor(&bifrost, &private.join("bifrost-anchor.cc"))?; - let executor_anchor = crate::export_host_identity_trust_anchor( - &executor, - &output.join("executor-anchor.cc"), - )?; - let config = OperatorCommandServiceConfig { - command_store: private.join("commands.cc"), - local_verse_store: private.join("verse.cc"), - resident_self_store: private.join("resident.cc"), - runtime_store: private.join("runtime.cc"), - policy: OperatorCommandPolicy { - runtime_id: "epiphany-interop-fixture".into(), - discord_guild_id: "fixture-guild".into(), - allowed_channel_ids: vec!["fixture-ops".into()], - actor_capabilities: std::collections::BTreeMap::from([( - "fixture-actor".into(), - vec![crate::OperatorCapability::Sleep], - )]), - max_ttl_seconds: 60, - }, - trusted_bifrost_identity: bifrost_anchor.clone(), - provider_health: OperatorStatusProviderHealthConfig { - query_endpoint: "127.0.0.1:1".parse()?, - idunn_runtime_id: "idunn-interop-fixture".into(), - trust_anchor_store: private.join("idunn-anchor.cc"), - admission_store: private.join("provider-admission.cc"), - max_local_age_millis: 30_000, - deployment_id: "deployment-fixture".into(), - release_id: "release-fixture".into(), - release_witness_sha256: format!("sha256-{}", "a".repeat(64)), - source_commit: "b".repeat(40), - }, - }; - let packet = crate::OperatorCommandPacket { - command_id: "fixture-command-1".into(), - nonce: "fixture-nonce-1".into(), - source_event_id: "fixture-event-1".into(), - source_actor_id: "fixture-actor".into(), - discord_guild_id: "fixture-guild".into(), - discord_channel_id: "fixture-ops".into(), - discord_message_id: "fixture-message-1".into(), - target_runtime_id: "epiphany-interop-fixture".into(), - issued_at: "2026-07-19T12:00:00Z".into(), - expires_at: "2026-07-19T12:01:00Z".into(), - command: crate::OperatorCommand::Sleep { - reason: "Interop fixture".into(), - }, - }; - let mut admission = BifrostOperatorCommandAdmission { - schema_name: BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE.into(), - schema_version: crate::BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(), - admission_id: "fixture-admission-1".into(), - packet_sha256: crate::operator_command_packet_sha256(&packet)?, - packet, - source_observer_id: "voidbot".into(), - source_observer_runtime_id: "fixture-bifrost".into(), - provider: "bifrost".into(), - bifrost_admission_receipt_id: "fixture-bifrost-receipt-1".into(), - authority: "exact_operator_command_only".into(), - provider_identity_id: bifrost.entry().identity_id.clone(), - provider_signature: Vec::new(), - }; - admission.provider_signature = bifrost - .sign( - crate::operator_command_admission_signing_purpose(), - &crate::operator_command_admission_signing_payload(&admission)?, - )? - .signature; - let admission_bytes = rmp_serde::to_vec_named(&admission)?; - let receipt = execute_operator_command_admission( - &config, - &executor, - &admission_bytes, - "2026-07-19T12:00:01Z", - )?; - let model_payload_msgpack = rmp_serde::to_vec_named(&( - "epiphany.repo_model.epoch.v1", - "fixture-repo-model", - "epiphany-interop-fixture", - "fixture-swarm", - "fixture-workspace", - format!("sha256:{}", "b".repeat(64)), - ))?; - let model_source_documents = vec![crate::EpiphanyMindDocumentVersion { - store_id: "epiphany-mind".into(), - document_type: "epiphany.mind.repo_model.identity.v1".into(), - document_key: "repo-model".into(), - schema_id: Some("EpiphanyRepoModelIdentityDocument".into()), - payload_sha256: format!("sha256:{:x}", Sha256::digest(&model_payload_msgpack)), - payload_msgpack: model_payload_msgpack, - }]; - let model_projection_digest = format!( - "sha256:{:x}", - Sha256::digest(rmp_serde::to_vec_named(&model_source_documents)?) - ); - let receipt_bytes = rmp_serde::to_vec_named(&receipt)?; - std::fs::write(output.join("operator-admission.msgpack"), &admission_bytes)?; - std::fs::write( - output.join("bifrost-anchor.msgpack"), - rmp_serde::to_vec(&bifrost_anchor)?, - )?; - std::fs::write( - output.join("executor-anchor.msgpack"), - rmp_serde::to_vec(&executor_anchor)?, - )?; - std::fs::write(output.join("sealed-result.msgpack"), &receipt_bytes)?; - let protocol = serde_json::json!({ - "schemaVersion": "epiphany.operator_command.protocol_fixture.v2", - "admissionSchemaVersion": crate::BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION, - "resultSchemaVersion": crate::OPERATOR_COMMAND_RESULT_SCHEMA_VERSION, - "sealedResultSchemaVersion": EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_SCHEMA_VERSION, - "admissionSigningPurpose": crate::operator_command_admission_signing_purpose(), - "resultSigningPurpose": RESULT_SIGNING_PURPOSE, - "commands": [ - serde_json::to_value(crate::OperatorCommand::Status)?, - serde_json::to_value(crate::OperatorCommand::Sleep { reason: "Bounded sleep reason".into() })?, - serde_json::to_value(crate::OperatorCommand::Wake)?, - serde_json::to_value(crate::OperatorCommand::Directive { objective: "Bounded operator objective".into() })?, - serde_json::to_value(crate::OperatorCommand::Reviews)?, - serde_json::to_value(crate::OperatorCommand::Review { - mind_request_id: "mind-request-fixture-1".into(), - candidate_id: "candidate-fixture-1".into(), - candidate_sha256: "1".repeat(64), - expected_model_projection_digest: model_projection_digest.clone(), - expected_model_source_documents: model_source_documents.clone(), - decision: crate::RepoFrontierPlanDecision::Adopt, - })?, - ], - "reviewDecisions": [ - serde_json::to_value(crate::RepoFrontierPlanDecision::Adopt)?, - serde_json::to_value(crate::RepoFrontierPlanDecision::Refuse)?, - serde_json::to_value(crate::RepoFrontierPlanDecision::Hold)?, - ], - "boundedReviewResult": serde_json::to_value(EpiphanyOperatorCommandWireResult { - schema_version: crate::OPERATOR_COMMAND_RESULT_SCHEMA_VERSION.into(), - result_id: "operator-result-fixture-reviews".into(), - command_id: "fixture-command-reviews".into(), - packet_sha256: format!("sha256-{}", "3".repeat(64)), - target_runtime_id: "epiphany-interop-fixture".into(), - disposition: "observed".into(), - consequence_kind: "mind-review-candidates".into(), - consequence_ref: String::new(), - completed_at: "2026-07-19T12:00:01Z".into(), - private_state_exposed: false, - operator_status: String::new(), - state_status: String::new(), - coordinator_action: String::new(), - brake_status: String::new(), - detail: "1 pending Mind review candidate(s)".into(), - reviews: vec![crate::RepoFrontierPlanReviewSummary { - mind_request_id: "mind-request-fixture-1".into(), - candidate_id: "candidate-fixture-1".into(), - candidate_sha256: "1".repeat(64), - model_projection_digest: model_projection_digest, - model_source_documents: model_source_documents, - frontier_item_id: "frontier-fixture-1".into(), - requested_at: "2026-07-19T11:59:00Z".into(), - }], - review_candidate_id: String::new(), - review_decision: String::new(), - status_v2: None, - })?, - "operatorStatusV2MigrationFixture": serde_json::to_value( - operator_status_v2_migration_fixture() - )?, - }); - let protocol_bytes = serde_json::to_vec_pretty(&protocol)?; - std::fs::write(output.join("protocol.json"), &protocol_bytes)?; - let manifest = OperatorCommandInteropFixtureManifest { - schema_version: "epiphany.operator_command.interop_fixture.v0".into(), - admission_file: "operator-admission.msgpack".into(), - bifrost_raw_trust_anchor_file: "bifrost-anchor.msgpack".into(), - executor_raw_trust_anchor_file: "executor-anchor.msgpack".into(), - executor_cultcache_trust_anchor_file: "executor-anchor.cc".into(), - sealed_result_file: "sealed-result.msgpack".into(), - protocol_file: "protocol.json".into(), - admission_sha256: format!("sha256-{:x}", Sha256::digest(&admission_bytes)), - sealed_result_sha256: format!("sha256-{:x}", Sha256::digest(&receipt_bytes)), - protocol_sha256: format!("sha256-{:x}", Sha256::digest(&protocol_bytes)), - admission_signing_purpose: crate::operator_command_admission_signing_purpose().into(), - result_signing_purpose: RESULT_SIGNING_PURPOSE.into(), - rudp_connection_id: EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID, - private_state_exposed: false, - }; - std::fs::write( - output.join("manifest.json"), - serde_json::to_vec_pretty(&manifest)?, - )?; - Ok(manifest) - })(); - let cleanup = std::fs::remove_dir_all(&private); - generated.and_then(|manifest| { - cleanup.context("failed to remove interop fixture private signing material")?; - Ok(manifest) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{OperatorCapability, OperatorCommand, OperatorCommandPacket}; - use cultcache_rs::{CacheBackingStore, SingleFileMessagePackBackingStore}; - use std::collections::BTreeMap; - use std::thread; - use std::time::Instant; - - #[test] - fn status_v2_golden_is_bounded_and_names_exact_provider_policies() { - let value = operator_status_v2_migration_fixture(); - assert_eq!(value.schema_version, "epiphany.operator.status.v2"); - assert_eq!(value.provider_set_status, "incomplete"); - assert_eq!(value.providers.len(), 2); - assert_eq!(value.providers[0].daemon_id, "yggdrasil-epiphany"); - assert_eq!( - value.providers[1].daemon_id, - "yggdrasil-bifrost-persona-feedback" - ); - assert!(value.providers.iter().all(|provider| { - provider.availability == "unavailable" - && provider.state.is_none() - && provider.projection_sha256.is_none() - })); - let json = serde_json::to_string(&value).unwrap(); - for forbidden in ["signature", "privateKey", "detail", "\\\\", ":\\"] { - assert!( - !json.contains(forbidden), - "leaked forbidden field {forbidden}" - ); - } - assert!(!value.private_state_exposed); - } - - fn fixture( - root: &Path, - ) -> Result<( - OperatorCommandServiceConfig, - HostIdentitySigner, - HostIdentitySigner, - )> { - let bifrost = crate::enroll_host_identity_at(&root.join("bifrost.cc"))?; - let anchor = crate::export_host_identity_trust_anchor(&bifrost, &root.join("anchor.cc"))?; - let executor = crate::enroll_host_identity_at(&root.join("executor.cc"))?; - Ok(( - OperatorCommandServiceConfig { - command_store: root.join("commands.cc"), - local_verse_store: root.join("verse.cc"), - resident_self_store: root.join("resident.cc"), - runtime_store: root.join("runtime.cc"), - policy: OperatorCommandPolicy { - runtime_id: "epiphany-yggdrasil".into(), - discord_guild_id: "guild".into(), - allowed_channel_ids: vec!["ops".into()], - actor_capabilities: BTreeMap::from([( - "actor".into(), - vec![OperatorCapability::Sleep], - )]), - max_ttl_seconds: 60, - }, - trusted_bifrost_identity: anchor, - provider_health: OperatorStatusProviderHealthConfig { - query_endpoint: "127.0.0.1:1".parse()?, - idunn_runtime_id: "idunn-yggdrasil".into(), - trust_anchor_store: root.join("idunn-anchor.cc"), - admission_store: root.join("provider-admission.cc"), - max_local_age_millis: 30_000, - deployment_id: "deployment-test".into(), - release_id: "release-test".into(), - release_witness_sha256: format!("sha256-{}", "a".repeat(64)), - source_commit: "b".repeat(40), - }, - }, - executor, - bifrost, - )) - } - - fn admission(signer: &HostIdentitySigner) -> Result { - let packet = OperatorCommandPacket { - command_id: "command-1".into(), - nonce: "nonce-1".into(), - source_event_id: "event-1".into(), - source_actor_id: "actor".into(), - discord_guild_id: "guild".into(), - discord_channel_id: "ops".into(), - discord_message_id: "message-1".into(), - target_runtime_id: "epiphany-yggdrasil".into(), - issued_at: "2026-07-19T12:00:00Z".into(), - expires_at: "2026-07-19T12:01:00Z".into(), - command: OperatorCommand::Sleep { - reason: "Supervised sleep.".into(), - }, - }; - let mut value = BifrostOperatorCommandAdmission { - schema_name: BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE.into(), - schema_version: crate::BIFROST_OPERATOR_COMMAND_ADMISSION_SCHEMA_VERSION.into(), - admission_id: "admission-1".into(), - packet_sha256: crate::operator_command_packet_sha256(&packet)?, - packet, - source_observer_id: "voidbot".into(), - source_observer_runtime_id: "voidbot-yggdrasil".into(), - provider: "bifrost".into(), - bifrost_admission_receipt_id: "receipt-1".into(), - authority: "exact_operator_command_only".into(), - provider_identity_id: signer.entry().identity_id.clone(), - provider_signature: Vec::new(), - }; - value.provider_signature = signer - .sign( - crate::operator_command_admission_signing_purpose(), - &crate::operator_command_admission_signing_payload(&value)?, - )? - .signature; - Ok(value) - } - - #[test] - fn signed_service_health_binds_release_config_identity_and_freshness() -> Result<()> { - let temp = tempfile::tempdir()?; - let (config, executor, _) = fixture(temp.path())?; - let executor_anchor = crate::export_host_identity_trust_anchor( - &executor, - &temp.path().join("executor-anchor.cc"), - )?; - let health_config = OperatorCommandServiceHealthConfig { - store: temp.path().join("operator-health.cc"), - bind: "127.0.0.1:17874".into(), - release_id: "release-1".into(), - release_witness_sha256: format!("sha256-{}", "a".repeat(64)), - source_commit: "b".repeat(40), - }; - let published = publish_operator_command_service_health( - &health_config.store, - &config, - &executor, - &health_config, - )?; - assert_eq!( - authenticate_operator_command_service_health( - &health_config.store, - &config.policy.runtime_id, - &health_config.release_id, - &health_config.release_witness_sha256, - &health_config.source_commit, - &health_config.bind, - &executor_anchor, - published.observed_at_millis, - 15_000, - )?, - published - ); - assert!( - authenticate_operator_command_service_health( - &health_config.store, - &config.policy.runtime_id, - "alien-release", - &health_config.release_witness_sha256, - &health_config.source_commit, - &health_config.bind, - &executor_anchor, - published.observed_at_millis, - 15_000, - ) - .is_err() - ); - assert!( - authenticate_operator_command_service_health( - &health_config.store, - &config.policy.runtime_id, - &health_config.release_id, - &health_config.release_witness_sha256, - &health_config.source_commit, - &health_config.bind, - &executor_anchor, - published.observed_at_millis + 15_001, - 15_000, - ) - .is_err() - ); - Ok(()) - } - - #[test] - fn seals_exact_result_and_replays_same_receipt() -> Result<()> { - let temp = tempfile::tempdir()?; - let (config, executor, bifrost) = fixture(temp.path())?; - let payload = rmp_serde::to_vec_named(&admission(&bifrost)?)?; - let first = execute_operator_command_admission( - &config, - &executor, - &payload, - "2026-07-19T12:00:01Z", - )?; - let reopened_executor = crate::open_host_identity_at(&temp.path().join("executor.cc"))?; - let replay = execute_operator_command_admission( - &config, - &reopened_executor, - &payload, - "2026-07-19T12:02:00Z", - )?; - assert_eq!(first, replay); - assert!(!first.private_state_exposed); - crate::verify_host_identity_signature( - executor.entry(), - RESULT_SIGNING_PURPOSE, - &operator_command_result_receipt_signing_payload(&first)?, - &crate::HostIdentitySignature { - identity_id: first.provider_identity_id.clone(), - signature: first.executor_signature.clone(), - }, - )?; - Ok(()) - } - - #[test] - fn strict_wire_rejects_tamper_before_command_store_write() -> Result<()> { - let temp = tempfile::tempdir()?; - let (config, executor, bifrost) = fixture(temp.path())?; - let mut value = serde_json::to_value(admission(&bifrost)?)?; - value - .as_object_mut() - .unwrap() - .insert("argv".into(), serde_json::json!(["whoami"])); - let payload = rmp_serde::to_vec_named(&value)?; - assert!( - execute_operator_command_admission( - &config, - &executor, - &payload, - "2026-07-19T12:00:01Z" - ) - .is_err() - ); - assert!(!config.command_store.exists()); - Ok(()) - } - - #[test] - fn cultnet_wire_accepts_only_exact_typed_admission_and_returns_sealed_receipt() -> Result<()> { - let temp = tempfile::tempdir()?; - let (config, executor, bifrost) = fixture(temp.path())?; - let admission = admission(&bifrost)?; - let request = CultNetMessage::DocumentPutRaw { - message_id: "request-1".into(), - document: CultNetRawDocumentRecord { - schema_id: BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE.into(), - record_key: admission.admission_id.clone(), - stored_at: admission.packet.issued_at.clone(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: rmp_serde::to_vec_named(&admission)?, - source_runtime_id: Some(admission.source_observer_runtime_id.clone()), - source_agent_id: Some(admission.provider_identity_id.clone()), - source_role: Some("bifrost-operator-admission".into()), - tags: Some(vec!["cultnet.transport.rudp.v0".into()]), - }, - }; - let encoded = - encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?; - let response = process_wire_frame_at(&config, &executor, &encoded, "2026-07-19T12:00:01Z")?; - let CultNetMessage::DocumentPutRaw { document, .. } = response else { - panic!("non-document response") - }; - assert_eq!( - document.schema_id, - EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_TYPE - ); - let receipt: EpiphanyOperatorCommandResultReceipt = - rmp_serde::from_slice(&document.payload)?; - assert_eq!(receipt.provider_identity_id, executor.entry().identity_id); - assert_eq!(receipt.command_id, admission.packet.command_id); - assert_eq!(receipt.packet_sha256, admission.packet_sha256); - assert!(!receipt.private_state_exposed); - - let mut alien = request; - let CultNetMessage::DocumentPutRaw { document, .. } = &mut alien else { - unreachable!() - }; - document.source_role = Some("persona-feedback".into()); - let before = std::fs::read(&config.command_store)?; - assert!( - process_wire_frame_at( - &config, - &executor, - &encode_cultnet_message_to_vec(&alien, CultNetWireContract::CultNetSchemaV0)?, - "2026-07-19T12:00:02Z" - ) - .is_err() - ); - assert_eq!(std::fs::read(&config.command_store)?, before); - Ok(()) - } - - #[test] - fn valid_command_succeeds_after_hostile_udp_on_same_service_instance() -> Result<()> { - let temp = tempfile::tempdir()?; - let (config, executor, bifrost) = fixture(temp.path())?; - let admission = admission(&bifrost)?; - let socket = UdpSocket::bind("127.0.0.1:0")?; - socket.set_read_timeout(Some(Duration::from_millis(20)))?; - let target = socket.local_addr()?; - let attacker = UdpSocket::bind("127.0.0.1:0")?; - attacker.send_to(b"not-cultnet-rudp", target)?; - let server = thread::spawn(move || -> Result<()> { - let mut transport = CultNetRudpSocketTransportConnection::new( - CultNetRudpSocketTransportOptions::server( - &config.policy.runtime_id, - socket, - EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID, - ), - )?; - serve_operator_command_rudp_loop( - &mut transport, - &config, - &executor, - None, - Some(100), - Some("2026-07-19T12:00:01Z"), - ) - }); - - let request = CultNetMessage::DocumentPutRaw { - message_id: "post-hostile-request".into(), - document: CultNetRawDocumentRecord { - schema_id: BIFROST_OPERATOR_COMMAND_DELIVERY_TYPE.into(), - record_key: admission.admission_id.clone(), - stored_at: admission.packet.issued_at.clone(), - payload_encoding: CultNetRawPayloadEncoding::Messagepack, - payload: rmp_serde::to_vec_named(&admission)?, - source_runtime_id: Some(admission.source_observer_runtime_id.clone()), - source_agent_id: Some(admission.provider_identity_id.clone()), - source_role: Some("bifrost-operator-admission".into()), - tags: Some(vec!["cultnet.transport.rudp.v0".into()]), - }, - }; - let client_socket = UdpSocket::bind("127.0.0.1:0")?; - client_socket.set_read_timeout(Some(Duration::from_millis(20)))?; - let mut client = - CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions::client( - "fixture-bifrost", - client_socket, - target, - EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID, - ))?; - client.connect(Vec::new())?; - let deadline = Instant::now() + Duration::from_secs(2); - while !client.connected() { - let _ = client.receive_once()?; - client.poll_resends()?; - if Instant::now() >= deadline { - bail!("post-hostile client handshake timed out"); - } - } - client.send( - "schema", - encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?, - )?; - let deadline = Instant::now() + Duration::from_secs(2); - let response = loop { - if let Some(frame) = client.receive_once()? { - break decode_cultnet_message_from_slice( - &frame.payload, - CultNetWireContract::CultNetSchemaV0, - )?; - } - client.poll_resends()?; - if Instant::now() >= deadline { - bail!("post-hostile sealed response timed out"); - } - }; - let CultNetMessage::DocumentPutRaw { document, .. } = response else { - bail!("post-hostile service returned non-document response"); - }; - assert_eq!( - document.schema_id, - EPIPHANY_OPERATOR_COMMAND_RESULT_RECEIPT_TYPE - ); - let receipt: EpiphanyOperatorCommandResultReceipt = - rmp_serde::from_slice(&document.payload)?; - assert_eq!(receipt.command_id, admission.packet.command_id); - assert_eq!(receipt.packet_sha256, admission.packet_sha256); - server - .join() - .map_err(|_| anyhow!("operator service test thread panicked"))??; - Ok(()) - } - - #[test] - fn rust_fixture_contains_verifiable_bifrost_and_executor_bytes() -> Result<()> { - let temp = tempfile::tempdir()?; - let manifest = write_operator_command_interop_fixture(temp.path())?; - assert_eq!( - manifest.rudp_connection_id, - EPIPHANY_OPERATOR_COMMAND_RUDP_CONNECTION_ID - ); - assert!(!temp.path().join(".fixture-private").exists()); - - let admission_bytes = std::fs::read(temp.path().join(&manifest.admission_file))?; - let admission: BifrostOperatorCommandAdmission = rmp_serde::from_slice(&admission_bytes)?; - let bifrost_anchor: HostIdentityTrustAnchorEntry = rmp_serde::from_slice(&std::fs::read( - temp.path().join(&manifest.bifrost_raw_trust_anchor_file), - )?)?; - crate::verify_host_identity_trust_anchor_signature( - &bifrost_anchor, - crate::operator_command_admission_signing_purpose(), - &crate::operator_command_admission_signing_payload(&admission)?, - &crate::HostIdentitySignature { - identity_id: admission.provider_identity_id.clone(), - signature: admission.provider_signature.clone(), - }, - )?; - - let receipt_bytes = std::fs::read(temp.path().join(&manifest.sealed_result_file))?; - let receipt: EpiphanyOperatorCommandResultReceipt = rmp_serde::from_slice(&receipt_bytes)?; - let executor_anchor: HostIdentityTrustAnchorEntry = rmp_serde::from_slice(&std::fs::read( - temp.path().join(&manifest.executor_raw_trust_anchor_file), - )?)?; - let envelopes = SingleFileMessagePackBackingStore::new( - &temp - .path() - .join(&manifest.executor_cultcache_trust_anchor_file), - ) - .pull_all()?; - assert_eq!(envelopes.len(), 1); - let canonical_anchor: HostIdentityTrustAnchorEntry = - rmp_serde::from_slice(&envelopes[0].payload)?; - assert_eq!(canonical_anchor, executor_anchor); - crate::verify_host_identity_trust_anchor_signature( - &executor_anchor, - RESULT_SIGNING_PURPOSE, - &operator_command_result_receipt_signing_payload(&receipt)?, - &crate::HostIdentitySignature { - identity_id: receipt.provider_identity_id.clone(), - signature: receipt.executor_signature.clone(), - }, - )?; - let wire_result = rmp_serde::to_vec_named(&receipt.result)?; - assert_eq!( - receipt.result_payload_sha256, - format!("sha256-{:x}", Sha256::digest(wire_result)) - ); - let protocol_bytes = std::fs::read(temp.path().join(&manifest.protocol_file))?; - assert_eq!( - manifest.protocol_sha256, - format!("sha256-{:x}", Sha256::digest(&protocol_bytes)) - ); - let protocol: serde_json::Value = serde_json::from_slice(&protocol_bytes)?; - assert_eq!( - protocol["commands"] - .as_array() - .expect("fixture commands") - .iter() - .map(|command| command["kind"].as_str().expect("command kind")) - .collect::>(), - vec!["status", "sleep", "wake", "directive", "reviews", "review"] - ); - let review = &protocol["commands"][5]; - assert!(review.get("mindRequestId").is_some()); - assert!(review.get("expectedModelProjectionDigest").is_some()); - assert!(review.get("expectedModelSourceDocuments").is_some()); - assert!(review.get("expectedModelRevision").is_none()); - assert!(review.get("expectedModelHash").is_none()); - assert!(review.get("mind_request_id").is_none()); - let crate::OperatorCommand::Review { - expected_model_projection_digest, - expected_model_source_documents, - .. - } = serde_json::from_value(review.clone())? - else { - unreachable!("review fixture decoded as another command") - }; - crate::EpiphanyRepoModelBasis { - projection_digest: expected_model_projection_digest, - source_documents: expected_model_source_documents, - } - .validate()?; - assert_eq!( - protocol["boundedReviewResult"]["reviews"] - .as_array() - .unwrap() - .len(), - 1 - ); - assert!( - protocol["boundedReviewResult"]["reviews"][0] - .get("proposalText") - .is_none() - ); - Ok(()) - } -} diff --git a/epiphany-core/src/repo_model_gateway.rs b/epiphany-core/src/repo_model_gateway.rs index a00bc467..71c85369 100644 --- a/epiphany-core/src/repo_model_gateway.rs +++ b/epiphany-core/src/repo_model_gateway.rs @@ -49,10 +49,6 @@ pub const REPO_FRONTIER_RELINQUISHMENT_RECEIPT_SCHEMA_VERSION: &str = "epiphany.mind.repo_frontier_relinquishment_receipt.v0"; pub const REPO_FRONTIER_RELINQUISHMENT_RECEIPT_CONTRACT: &str = "epiphany.repo_frontier_relinquishment.v0"; -pub const REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_SCHEMA_VERSION: &str = - "epiphany.mind.repo_frontier_execution_amendment_receipt.v0"; -pub const REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_CONTRACT: &str = - "epiphany.repo_frontier_execution_amendment.v0"; pub const REPO_FRONTIER_MODELING_REQUEST_TYPE: &str = "epiphany.modeling.repo_frontier_verdict_request"; pub const REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION: &str = @@ -729,47 +725,7 @@ pub struct RepoFrontierPlanDecisionReceipt { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum RepoFrontierPlanDecisionSource { - MindWorker { - result_id: String, - job_id: String, - }, - AuthenticatedOperatorReview { - command_id: String, - admission_id: String, - packet_sha256: String, - source_actor_id: String, - }, -} - -/// Operator-safe identity projection of one current Mind review candidate. -/// Proposal text, commands, paths, and private state deliberately remain in -/// the canonical runtime store owned by Mind. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct RepoFrontierPlanReviewSummary { - pub mind_request_id: String, - pub candidate_id: String, - pub candidate_sha256: String, - pub model_projection_digest: String, - pub model_source_documents: Vec, - pub frontier_item_id: String, - pub requested_at: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct RepoFrontierPlanOperatorReview { - pub command_id: String, - pub admission_id: String, - pub packet_sha256: String, - pub source_actor_id: String, - pub mind_request_id: String, - pub candidate_id: String, - pub candidate_sha256: String, - pub expected_model_projection_digest: String, - pub expected_model_source_documents: Vec, - pub decision: RepoFrontierPlanDecision, - pub decided_at: String, + MindWorker { result_id: String, job_id: String }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -946,49 +902,3 @@ pub struct RepoFrontierRelinquishmentReceipt { #[cultcache(key = 10)] pub contract: String, } - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.mind.repo_frontier_execution_amendment_receipt", - schema = "RepoFrontierExecutionAmendmentReceipt" -)] -pub struct RepoFrontierExecutionAmendmentReceipt { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub receipt_id: String, - #[cultcache(key = 2)] - pub amendment_id: String, - #[cultcache(key = 3)] - pub replaced_route_id: String, - #[cultcache(key = 4)] - pub frontier_item_id: String, - #[cultcache(key = 5)] - pub previous_frontier_item_hash: String, - #[cultcache(key = 6)] - pub previous_model_projection_digest: String, - #[cultcache(key = 7)] - pub previous_model_source_documents: Vec, - #[cultcache(key = 8)] - pub admitted_model_projection_digest: String, - #[cultcache(key = 9)] - pub admitted_model_source_documents: Vec, - #[cultcache(key = 10)] - pub source_actor_id: String, - #[cultcache(key = 11)] - pub command_id: String, - #[cultcache(key = 12)] - pub admission_id: String, - #[cultcache(key = 13)] - pub packet_sha256: String, - #[cultcache(key = 14)] - pub replacement_action: String, - #[cultcache(key = 15)] - pub replacement_command: String, - #[cultcache(key = 16)] - pub rationale: String, - #[cultcache(key = 17)] - pub amended_at: String, - #[cultcache(key = 18)] - pub contract: String, -} diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index 15ddc19b..e409f5df 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -36,8 +36,6 @@ use crate::organ_dependencies::EpiphanyLaunchOrganContract; use crate::repo_model_gateway::{ REPO_FRONTIER_AUTONOMOUS_PROPOSAL_BINDING_CONTRACT, REPO_FRONTIER_AUTONOMOUS_PROPOSAL_BINDING_SCHEMA_VERSION, - REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_CONTRACT, - REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_SCHEMA_VERSION, REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT, REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION, REPO_FRONTIER_MODELING_REQUEST_CONTRACT, REPO_FRONTIER_MODELING_REQUEST_SCHEMA_VERSION, REPO_FRONTIER_PLAN_CANDIDATE_SCHEMA_VERSION, REPO_FRONTIER_PLAN_DECISION_CONTRACT, @@ -59,10 +57,9 @@ use crate::repo_model_gateway::{ REPO_MODEL_CLAIM_CHALLENGE_CONTRACT, REPO_MODEL_CLAIM_CHALLENGE_SCHEMA_VERSION, RUNTIME_REPOSITORY_DOMAIN_BINDING_CONTRACT, RUNTIME_REPOSITORY_DOMAIN_BINDING_KEY, RUNTIME_REPOSITORY_DOMAIN_BINDING_SCHEMA_VERSION, RepoFrontierAutonomousProposalBinding, - RepoFrontierExecutionAmendmentReceipt, RepoFrontierHandsAuthority, RepoFrontierModelingRequest, - RepoFrontierNextOrgan, RepoFrontierPlanCandidate, RepoFrontierPlanDecision, - RepoFrontierPlanDecisionReceipt, RepoFrontierPlanMindDecision, - RepoFrontierPlanMindLaunchBinding, RepoFrontierPlanMindRequest, + RepoFrontierHandsAuthority, RepoFrontierModelingRequest, RepoFrontierNextOrgan, + RepoFrontierPlanCandidate, RepoFrontierPlanDecision, RepoFrontierPlanDecisionReceipt, + RepoFrontierPlanMindDecision, RepoFrontierPlanMindLaunchBinding, RepoFrontierPlanMindRequest, RepoFrontierPlanningCandidateEligibility, RepoFrontierPlanningEligibility, RepoFrontierPlanningFailureReview, RepoFrontierPlanningLaunchBinding, RepoFrontierPlanningLifecycle, RepoFrontierPlanningLifecycleStage, RepoFrontierPlanningRequest, @@ -7578,129 +7575,6 @@ pub fn commit_repo_frontier_plan_decision( enum FrontierPlanDecisionSource<'a> { MindWorker(&'a str), - Operator(&'a crate::RepoFrontierPlanOperatorReview), -} - -/// Read-only, bounded identities for candidates already routed to canonical -/// Mind review. Invalid, stale, or terminal candidates are not projected. -pub fn pending_repo_frontier_plan_reviews( - runtime_store: impl AsRef, - limit: usize, -) -> Result> { - if limit == 0 || limit > 25 { - return Err(anyhow!( - "Mind review projection limit must be within 1..=25" - )); - } - let mut cache = runtime_spine_cache(runtime_store.as_ref())?; - cache.pull_all_backing_stores()?; - let terminal = cache - .get_all::()? - .into_iter() - .map(|receipt| receipt.planning_request_id) - .collect::>(); - let mut summaries = Vec::new(); - for request in cache.get_all::()? { - let Ok((planning, candidate)) = validate_repo_frontier_plan_mind_request(&cache, &request) - else { - continue; - }; - if terminal.contains(&planning.request_id) { - continue; - } - summaries.push(crate::RepoFrontierPlanReviewSummary { - mind_request_id: request.request_id, - candidate_id: candidate.candidate_id, - candidate_sha256: request.candidate_sha256, - model_projection_digest: planning.model_projection_digest, - model_source_documents: planning.model_source_documents, - frontier_item_id: planning.frontier_item_id, - requested_at: request.requested_at, - }); - } - summaries.sort_by(|a, b| { - a.requested_at - .cmp(&b.requested_at) - .then_with(|| a.mind_request_id.cmp(&b.mind_request_id)) - }); - summaries.truncate(limit); - Ok(summaries) -} - -/// Canonical Mind commit path for an authenticated operator's exact review -/// request. The operator selects a disposition; Mind revalidates the complete -/// immutable candidate and current model before performing the same atomic -/// terminal transition used by a Mind worker. -pub fn commit_operator_repo_frontier_plan_review( - runtime_store: impl AsRef, - review: &crate::RepoFrontierPlanOperatorReview, -) -> Result { - commit_repo_frontier_plan_decision_inner( - runtime_store, - FrontierPlanDecisionSource::Operator(review), - None, - ) -} - -/// Classifies only operator-visible precondition refusal. Store corruption, -/// decoding failure, and I/O remain errors and must never be fossilized as a -/// terminal Refused command result. -pub fn operator_repo_frontier_plan_review_is_current( - runtime_store: impl AsRef, - review: &crate::RepoFrontierPlanOperatorReview, -) -> Result { - let mut cache = runtime_spine_cache(runtime_store.as_ref())?; - cache.pull_all_backing_stores()?; - let Some(request) = cache.get::(&review.mind_request_id)? else { - return Ok(false); - }; - let (planning, candidate) = - validate_repo_frontier_plan_mind_request_identity(&cache, &request)?; - if review.candidate_id != candidate.candidate_id - || review.candidate_sha256 != request.candidate_sha256 - || review.expected_model_projection_digest != planning.model_projection_digest - || review.expected_model_source_documents != planning.model_source_documents - { - return Ok(false); - } - let terminal = cache - .get_all::()? - .into_iter() - .filter(|receipt| receipt.planning_request_id == planning.request_id) - .collect::>(); - if !terminal.is_empty() { - if terminal.len() != 1 { - return Err(anyhow!( - "Mind review candidate has multiple terminal decisions" - )); - } - let receipt = &terminal[0]; - return Ok(receipt.decision == review.decision - && receipt.candidate_id == review.candidate_id - && receipt.candidate_sha256 == review.candidate_sha256 - && receipt.model_projection_digest == review.expected_model_projection_digest - && receipt.model_source_documents == review.expected_model_source_documents - && receipt.decision_source.as_ref() - == Some( - &crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { - command_id: review.command_id.clone(), - admission_id: review.admission_id.clone(), - packet_sha256: review.packet_sha256.clone(), - source_actor_id: review.source_actor_id.clone(), - }, - )); - } - if require_keyed_repo_model_basis( - &cache, - &planning.model_projection_digest, - &planning.model_source_documents, - ) - .is_err() - { - return Ok(false); - } - validate_repo_frontier_plan_candidate_against_request(&cache, &candidate, &planning)?; - Ok(true) } fn commit_repo_frontier_plan_decision_inner( @@ -7711,69 +7585,33 @@ fn commit_repo_frontier_plan_decision_inner( let runtime_store = runtime_store.as_ref(); let mut cache = runtime_spine_cache(runtime_store)?; cache.pull_all_backing_stores()?; - let ( - mind_request_id, - decision, - rationale, - decided_at, - decision_source, - decision_context_id, - operator_provenance, - ) = match source { - FrontierPlanDecisionSource::MindWorker(result_id) => { - let result = cache - .get_all::()? - .into_iter() - .find(|result| result.result_id == result_id) - .ok_or_else(|| anyhow!("frontier plan decision lost its Mind result"))?; - let typed = result - .frontier_plan_mind_decision()? - .ok_or_else(|| anyhow!("frontier plan decision requires a typed Mind decision"))?; - ( - result - .frontier_plan_mind_request_id - .clone() - .ok_or_else(|| anyhow!("Mind result lacks its plan request echo"))?, - typed.decision, - typed.rationale, - typed.decided_at, - crate::RepoFrontierPlanDecisionSource::MindWorker { - result_id: result.result_id, - job_id: result.job_id, - }, - Some(result.decision_context_id), - None, - ) - } - FrontierPlanDecisionSource::Operator(review) => { - let admitted = cache - .get::(&review.command_id)? - .ok_or_else(|| anyhow!("operator review lost its admitted command"))?; - if admitted.admission_id != review.admission_id - || admitted.packet_sha256 != review.packet_sha256 - || admitted.source_actor_id != review.source_actor_id - { - return Err(anyhow!("operator review provenance mismatch")); + let (mind_request_id, decision, rationale, decided_at, decision_source, decision_context_id) = + match source { + FrontierPlanDecisionSource::MindWorker(result_id) => { + let result = cache + .get_all::()? + .into_iter() + .find(|result| result.result_id == result_id) + .ok_or_else(|| anyhow!("frontier plan decision lost its Mind result"))?; + let typed = result.frontier_plan_mind_decision()?.ok_or_else(|| { + anyhow!("frontier plan decision requires a typed Mind decision") + })?; + ( + result + .frontier_plan_mind_request_id + .clone() + .ok_or_else(|| anyhow!("Mind result lacks its plan request echo"))?, + typed.decision, + typed.rationale, + typed.decided_at, + crate::RepoFrontierPlanDecisionSource::MindWorker { + result_id: result.result_id, + job_id: result.job_id, + }, + Some(result.decision_context_id), + ) } - let provenance = cache - .get_envelope::(&review.command_id)? - .ok_or_else(|| anyhow!("operator review provenance envelope disappeared"))?; - ( - review.mind_request_id.clone(), - review.decision, - format!("Authenticated operator requested {:?}.", review.decision).to_lowercase(), - review.decided_at.clone(), - crate::RepoFrontierPlanDecisionSource::AuthenticatedOperatorReview { - command_id: review.command_id.clone(), - admission_id: review.admission_id.clone(), - packet_sha256: review.packet_sha256.clone(), - source_actor_id: review.source_actor_id.clone(), - }, - None, - Some(provenance), - ) - } - }; + }; chrono::DateTime::parse_from_rfc3339(&decided_at) .map_err(|_| anyhow!("frontier plan decision time must be RFC3339"))?; let mind_request = cache @@ -7781,17 +7619,6 @@ fn commit_repo_frontier_plan_decision_inner( .ok_or_else(|| anyhow!("frontier plan decision requires its typed Mind request"))?; let (planning, candidate) = validate_repo_frontier_plan_mind_request_identity(&cache, &mind_request)?; - if let FrontierPlanDecisionSource::Operator(review) = source { - if review.candidate_id != candidate.candidate_id - || review.candidate_sha256 != mind_request.candidate_sha256 - || review.expected_model_projection_digest != planning.model_projection_digest - || review.expected_model_source_documents != planning.model_source_documents - { - return Err(anyhow!( - "operator review does not bind the exact keyed model" - )); - } - } let candidate_sha256 = format!("{:x}", Sha256::digest(rmp_serde::to_vec_named(&candidate)?)); let decision_id = format!( "repo-frontier-plan-decision-{:x}", @@ -7858,13 +7685,12 @@ fn commit_repo_frontier_plan_decision_inner( { strong_reads.push(envelope); } - if let crate::RepoFrontierPlanDecisionSource::MindWorker { job_id, .. } = &decision_source { - strong_reads.push( - cache - .get_envelope::(job_id)? - .ok_or_else(|| anyhow!("frontier plan decision lost its Mind result envelope"))?, - ); - } + let crate::RepoFrontierPlanDecisionSource::MindWorker { job_id, .. } = &decision_source; + strong_reads.push( + cache + .get_envelope::(job_id)? + .ok_or_else(|| anyhow!("frontier plan decision lost its Mind result envelope"))?, + ); let mut writes = Vec::new(); if decision == RepoFrontierPlanDecision::Adopt { let item = cache @@ -7887,7 +7713,6 @@ fn commit_repo_frontier_plan_decision_inner( stop_conditions: candidate.stop_conditions.clone(), rollback_steps: candidate.rollback_steps.clone(), commit_message: candidate.commit_message.clone(), - execution_amendment: None, }); writes.push( cache @@ -7908,26 +7733,16 @@ fn commit_repo_frontier_plan_decision_inner( if let Some(pre_cas) = pre_cas { pre_cas(); } - let outcome = if let Some(context_id) = decision_context_id { - crate::commit_mind_mutation( - runtime_store, - &context_id, - "Mind.repo_frontier_plan_decision", - strong_reads, - writes, - &decided_at, - )? - } else { - crate::commit_operator_mind_mutation( - runtime_store, - operator_provenance - .ok_or_else(|| anyhow!("operator plan decision lacks provenance"))?, - "Mind.repo_frontier_plan_decision", - strong_reads, - writes, - &decided_at, - )? - }; + let context_id = decision_context_id + .ok_or_else(|| anyhow!("Mind plan decision lacks its decision context"))?; + let outcome = crate::commit_mind_mutation( + runtime_store, + &context_id, + "Mind.repo_frontier_plan_decision", + strong_reads, + writes, + &decided_at, + )?; match outcome { crate::EpiphanyMindCommitOutcome::Committed(_) => Ok(receipt), crate::EpiphanyMindCommitOutcome::Conflict { .. } => { @@ -9903,124 +9718,6 @@ fn worker_result_has_keyed_mind_commit( })) } -/// Mind-owned repair for a route whose immutable adopted plan cannot bind the -/// already-observed consequence. The original plan and route remain intact; -/// only an authenticated, single-use execution amendment enters RepoModel. -pub fn amend_repo_frontier_execution( - store_path: impl AsRef, - amendment: crate::RepoFrontierExecutionAmendment, -) -> Result { - let store_path = store_path.as_ref(); - chrono::DateTime::parse_from_rfc3339(&amendment.amended_at) - .map_err(|_| anyhow!("execution amendment amended_at must be RFC3339"))?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - if let Some(existing) = - cache.get::(&amendment.amendment_id)? - { - return Ok(existing); - } - let route = cache - .get::(&amendment.replaces_route_id)? - .ok_or_else(|| anyhow!("execution amendment requires the exact route"))?; - let provenance = cache - .get_envelope::(&amendment.command_id)? - .ok_or_else(|| anyhow!("execution amendment lost its admitted operator command"))?; - let admitted = cache - .get::(&amendment.command_id)? - .ok_or_else(|| anyhow!("execution amendment lost operator provenance"))?; - if admitted.admission_id != amendment.admission_id - || admitted.packet_sha256 != amendment.packet_sha256 - || admitted.source_actor_id != amendment.source_actor_id - { - return Err(anyhow!("execution amendment operator provenance mismatch")); - } - let basis = crate::EpiphanyRepoModelBasis { - projection_digest: route.model_projection_digest.clone(), - source_documents: route.model_source_documents.clone(), - }; - let view = - require_keyed_repo_model_basis(&cache, &basis.projection_digest, &basis.source_documents)?; - let mut item = view - .frontier - .into_iter() - .find(|item| item.id == route.frontier_item_id) - .ok_or_else(|| anyhow!("execution amendment frontier disappeared"))?; - let previous_frontier_item_hash = repo_frontier_item_hash(&item)?; - if previous_frontier_item_hash != route.frontier_item_hash { - return Err(anyhow!("execution amendment route is stale")); - } - let plan = item - .adopted_plan - .as_mut() - .ok_or_else(|| anyhow!("execution amendment requires an adopted plan"))?; - if plan.execution_amendment.is_some() { - return Err(anyhow!( - "execution amendment cannot replace another amendment" - )); - } - plan.execution_amendment = Some(amendment.clone()); - let proposal = crate::EpiphanyRepoModelMutationProposal::new( - format!( - "repo-frontier-execution-amendment-{}", - amendment.amendment_id - ), - amendment.command_id.clone(), - amendment.amendment_id.clone(), - vec![ - amendment.admission_id.clone(), - amendment.packet_sha256.clone(), - ], - crate::load_current_runtime_repository_body_basis(store_path)?, - vec![crate::EpiphanyRepoModelMutationOperation::PutFrontier { item }], - )?; - let mutation = crate::plan_repo_model_mutation(store_path, &proposal)?; - let admitted_basis = keyed_repo_model_basis_after_writes(&basis, &mutation.writes)?; - let receipt = RepoFrontierExecutionAmendmentReceipt { - schema_version: REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_SCHEMA_VERSION.into(), - receipt_id: amendment.amendment_id.clone(), - amendment_id: amendment.amendment_id.clone(), - replaced_route_id: route.route_id, - frontier_item_id: route.frontier_item_id, - previous_frontier_item_hash, - previous_model_projection_digest: basis.projection_digest, - previous_model_source_documents: basis.source_documents, - admitted_model_projection_digest: admitted_basis.projection_digest, - admitted_model_source_documents: admitted_basis.source_documents, - source_actor_id: amendment.source_actor_id, - command_id: amendment.command_id, - admission_id: amendment.admission_id, - packet_sha256: amendment.packet_sha256, - replacement_action: amendment.action, - replacement_command: amendment.command, - rationale: amendment.rationale, - amended_at: amendment.amended_at.clone(), - contract: REPO_FRONTIER_EXECUTION_AMENDMENT_RECEIPT_CONTRACT.into(), - }; - let mut writes = mutation.writes; - writes.push(cache.prepare_entry(&receipt.receipt_id, &receipt)?.0); - match crate::commit_operator_mind_mutation( - store_path, - provenance, - "Mind.repo_frontier_execution_amendment", - mutation.strong_reads, - writes, - &amendment.amended_at, - )? { - crate::EpiphanyMindCommitOutcome::Committed(_) => Ok(receipt), - crate::EpiphanyMindCommitOutcome::Conflict { .. } => { - let mut reloaded = runtime_spine_cache(store_path)?; - reloaded.pull_all_backing_stores()?; - match reloaded.get::(&receipt.receipt_id)? { - Some(existing) if existing == receipt => Ok(existing), - _ => Err(anyhow!( - "execution amendment lost its exact keyed-model CAS" - )), - } - } - } -} - pub(crate) fn validate_repo_frontier_verification_request_intrinsic( request: &RepoFrontierVerificationRequest, ) -> Result { @@ -10349,15 +10046,6 @@ pub fn runtime_repo_frontier_plan_decision( .find(|receipt| receipt.decision_id == decision_id)) } -pub fn runtime_repo_frontier_execution_amendment( - store_path: impl AsRef, - receipt_id: &str, -) -> Result> { - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.get::(receipt_id) -} - pub fn runtime_latest_repo_frontier_relinquishment( store_path: impl AsRef, ) -> Result> { diff --git a/epiphany-release-construction/src/lib.rs b/epiphany-release-construction/src/lib.rs index 2dff43e8..0290a482 100644 --- a/epiphany-release-construction/src/lib.rs +++ b/epiphany-release-construction/src/lib.rs @@ -107,7 +107,6 @@ pub fn required_packaged_release_binaries(target_triple: &str) -> Vec<(&'static ("repository-body", file_name("epiphany-repository-body")), ("host-identity", file_name("epiphany-host-identity")), ("swarm", file_name("epiphany-swarm")), - ("operator-command", file_name("epiphany-operator-command")), ("heartbeat", file_name("epiphany-heartbeat-store")), ("runtime-spine", file_name("epiphany-runtime-spine")), ( @@ -635,7 +634,6 @@ fn required_release_build_target(role: &str) -> Result<(&'static str, &'static s "repository-body" => Ok(("epiphany-core", "epiphany-repository-body")), "host-identity" => Ok(("epiphany-core", "epiphany-host-identity")), "swarm" => Ok(("epiphany-core", "epiphany-swarm")), - "operator-command" => Ok(("epiphany-core", "epiphany-operator-command")), "heartbeat" => Ok(("epiphany-core", "epiphany-heartbeat-store")), "runtime-spine" => Ok(("epiphany-core", "epiphany-runtime-spine")), "persona-feedback-ingress" => Ok(("epiphany-core", "epiphany-persona-feedback-ingress")), @@ -1263,7 +1261,6 @@ mod tests { .collect::>(); for role in [ "swarm", - "operator-command", "heartbeat", "runtime-spine", "state-steward", @@ -1282,10 +1279,6 @@ mod tests { required_release_build_target("swarm").unwrap(), ("epiphany-core", "epiphany-swarm") ); - assert_eq!( - required_release_build_target("operator-command").unwrap(), - ("epiphany-core", "epiphany-operator-command") - ); assert_eq!( required_release_build_target("heartbeat").unwrap(), ("epiphany-core", "epiphany-heartbeat-store") diff --git a/epiphany-state-model/src/lib.rs b/epiphany-state-model/src/lib.rs index c504e8be..bb2eafa6 100644 --- a/epiphany-state-model/src/lib.rs +++ b/epiphany-state-model/src/lib.rs @@ -756,43 +756,18 @@ pub struct RepoFrontierAdoptedPlan { #[ts(type = "Array")] pub rollback_steps: Vec, pub commit_message: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(type = "RepoFrontierExecutionAmendment | null")] - pub execution_amendment: Option, } impl RepoFrontierAdoptedPlan { pub fn effective_action(&self) -> &str { - self.execution_amendment - .as_ref() - .map_or(self.action.as_str(), |amendment| amendment.action.as_str()) + self.action.as_str() } pub fn effective_command(&self) -> &str { - self.execution_amendment - .as_ref() - .map_or(self.command.as_str(), |amendment| { - amendment.command.as_str() - }) + self.command.as_str() } } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)] -pub struct RepoFrontierExecutionAmendment { - pub amendment_id: String, - pub replaces_route_id: String, - pub source_actor_id: String, - pub command_id: String, - pub admission_id: String, - pub packet_sha256: String, - pub previous_action_sha256: String, - pub previous_command_sha256: String, - pub action: String, - pub command: String, - pub rationale: String, - pub amended_at: String, -} - #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, JsonSchema, TS, Default)] #[serde(rename_all = "snake_case")] #[ts(rename_all = "snake_case")] diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 2ba8faae..016f9465 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -325,12 +325,11 @@ Accepted at the `bb823c54` source boundary: Open before Model Atlas Gate 1 resumes: -1. provision Yggdrasil's missing Bifrost organizational-operator substrate - through its owning infrastructure lane, then provision Epiphany's Codex - credentials through their single owner and reissue Idunn deployment of the - already tested/sealed `ebc0ffe4` package. Require runtime publication and - signed health; the current exact request refused before mutation and left - Epiphany inactive on recovery source `267a0257`; +1. provision Epiphany's Codex credentials through their single owner, then let + Idunn build and deploy the source containing the operator-bridge deletion. + Require runtime publication and signed health; the prior exact request + refused before mutation and left Epiphany inactive on recovery source + `267a0257`; 2. run the fresh exact-package capstone over a new store, including concurrent Persona/repository work, complete decision inspection without transcripts, and process restart/re-entry. The equivalent source-level ownership, @@ -341,8 +340,9 @@ Open before Model Atlas Gate 1 resumes: Historical c011 and partial Gate roots remain read-only. The pre-upgrade Yggdrasil's old capacity/topology is obsolete; the upgraded 16-vCPU host is the intended swarm and CI/CD body. Idunn owns the installed Epiphany source-change -path and sealed the package, but the absent Bifrost operator substrate still -blocks publication. The package is not capstone or service-health evidence. +path. The former Discord/Bifrost/VoidBot operator bridge and its deployment +gate are deleted; Bifrost remains Persona and governed-consequence transport. +The prior package is not capstone or service-health evidence. Operational topology registration and autonomous scheduling remain forbidden until their owning gates pass. diff --git a/notes/epiphany-discord-operator-nerve.md b/notes/epiphany-discord-operator-nerve.md deleted file mode 100644 index cd57c79f..00000000 --- a/notes/epiphany-discord-operator-nerve.md +++ /dev/null @@ -1,268 +0,0 @@ -# Epiphany Discord Operator Nerve - -## Objective - -This is Epiphany's ordinary organizational interface, not a remote-control -fixture for one deployment. A resident swarm continuously models its authorized -domain, derives bounded direction from the admitted map, and lets Imagination -suggest improvements and possible features without waiting for an instruction. -The repository Persona gives the organization a shared conversational crossing: -members can add attributed feedback, challenge the model, and discuss proposals -without becoming machine operators merely by speaking. - -Explicit operator commands form a second, narrower nerve for named consequences -such as inspection, sleep, wake, direction pressure, and Mind review. Yggdrasil -continuing while Starfire is packed is the July 22 acceptance case for that -product contract, not the reason the contract exists. VoidBot must never gain -access to Epiphany's private stores. - -Persona feedback and operator command are different nerves: - -- Persona conversation is `feedback_only` at VoidBot/Bifrost and - `resident-pressure-only` in Epiphany. It may provoke attention and an - Imagination proposal, but it is not required to ignite either Modeling or - autonomous direction. It cannot adopt Mind state or grant consequence. -- Operator commands are explicit owner-authenticated slash commands. They cross - Bifrost as signed, expiring, target-bound typed intent and invoke one named - Epiphany owner primitive. They are never inferred from prose. - -## Authority map - -### Discord / VoidBot - -Owner: Discord interaction capture and owner authentication. - -Inputs: one explicit `/epiphany` subcommand, Discord actor/guild/channel and -interaction identity, and command fields allowed by that subcommand. - -Outputs: one immutable operator-command observation for Bifrost, or an -immediate authentication/shape refusal. - -Does not own: Epiphany state, brake transitions, pressure admission, Mind -review, Bifrost signing, release, deployment, or arbitrary command execution. - -### Bifrost / Heimdall - -Owner: outside identity/capability association and governed crossing. - -Inputs: the exact Discord observation, an operator capability associated with -the actor, configured target binding, current time, and command policy. - -Outputs: one signed, expiring, nonce-bound command admission; later, one sealed -result delivery bound to the exact command admission. - -Does not own: the resulting Epiphany transition or receipt. A Bifrost signature -proves who requested what crossing; it does not prove that Epiphany applied it. - -### Epiphany operator-command ingress - -Owner: target validation and dispatch to one existing Epiphany owner primitive. - -Inputs: Bifrost trust anchor, signed command admission, exact runtime/repository, -nonce, expiry, expected prior state/revision when required, and the command's -bounded payload. - -Outputs: an Epiphany-owned typed result receipt containing applied/refused/no-op, -the exact owner receipt or snapshot reference, and no private state. - -Does not own: Discord identity, Bifrost capability, generic process execution, -release authorization, or deployment. - -### Existing Epiphany owners - -- Status: read-only operator-safe projection. The deployed v1 result currently - carries a coordinator snapshot plus the independently owned brake state. It - exposes no raw worker state or transcripts, but it also does not yet compose - authenticated release, resident-readiness, Idunn, or Bifrost health. -- Sleep: swarm-brake owner engages the named cognitive/action surfaces. -- Wake: swarm-brake owner releases the brake only. Wake does not issue a grant, - enqueue a turn, adopt a plan, invoke Hands, speak, release, or deploy. -- Directive: resident-pressure owner admits one `operator-objective` pressure - with exact actor/capability provenance and expiry. It grants attention only. -- Reviews: the owning Mind/review gate lists bounded pending requests and - applies exact `Adopt`, `Refuse`, or `Hold` through its existing commit - primitive. Discord and Bifrost cannot mint the resulting receipt. - -## Command families - -1. `status`: read-only; idempotent; returns a sealed snapshot. -2. `sleep`: engage brake; requires expected brake identity/revision; repeated - exact command is idempotent. -3. `wake`: release brake; requires expected brake identity/revision; produces - no work grant. -4. `direct`: admits one expiring operator-objective pressure; never parses the - text as a command family or consequence grant. -5. `reviews`: read-only bounded list of pending review summaries. -6. `review`: exact Mind request id, candidate id/digest, model revision/hash, - and `Adopt|Refuse|Hold`. The result contains identities and disposition only. - -Every mutating command carries a unique command id/nonce, issued-at, expires-at, -target runtime/repository, actor identity, Bifrost capability reference, -expected prior state where relevant, and exact payload digest. Replays return -the existing result only when command and payload are byte-equivalent. - -## Forbidden writers and cut line - -- No natural-language command inference, regex tribunal, or magic prefix. -- No `/queue-codex` or shell proxy. -- No arbitrary argv, executable path, environment, or store path in a command. -- No Discord bot mount or filesystem permission for Epiphany stores. -- No wake-and-run composite. -- No conversation-derived Mind, Hands, Persona speech, release, deployment, or - service-lifecycle authority. -- No status assembled from PID/process prose when a typed provider owns it. -- No result success manufactured by VoidBot or Bifrost. -- Release authorization/revocation remains Bifrost's separate release gate. -- Deployment and service recovery remain Idunn's separate lifecycle gate. - -## Shared paths - -Discord interaction -> VoidBot observation -> Bifrost admission -> Epiphany -ingress -> named owner primitive -> Epiphany result -> Bifrost delivery -> -VoidBot interaction response. - -All six commands use this route. Status/reviews stop at read-only owners. -Sleep/wake share the brake transition primitive. Directive shares resident -pressure admission. Review shares the canonical Mind/review commit primitive. - -## July 22 proof - -With Starfire disconnected and no SSH tunnel dependency: - -1. owner and non-owner Discord actors receive the correct admission/refusal; -2. status names exact deployed commit/release, brake, resident state, pressure - and review counts, and Idunn/Bifrost health without private state; this is an - open acceptance item, not a property of the current coordinator snapshot; -3. sleep engages the brake and is idempotent; -4. wake releases only the brake and creates no grant, job, Mind change, Hands - authority, speech, release, or deployment; -5. direct creates exactly one expiring operator-objective pressure and no other - authority; -6. reviews exposes only bounded summaries; -7. review applies only to the exact current gate and stale/substituted/replayed - decisions refuse without writes; -8. every accepted/refused/no-op command returns a sealed receipt bound to the - Discord interaction and Bifrost admission; -9. signer, target, nonce, expiry, actor capability, and payload tampering fail - without changing Epiphany state; -10. Ygg services survive restart and continue the route without Starfire. - -## Implemented Epiphany review owner (2026-07-19) - -`Reviews` projects at most ten current `RepoFrontierPlanMindRequest` identities. -Mind revalidates the immutable Imagination result, candidate digest, current -RepoModel revision/hash, frontier item, runtime, and thread. Plan action, -command, paths, checks, rollback, proposal text, and private state stay sealed. - -`Review` enters the existing `RepoFrontierPlanDecisionReceipt` owner. `Refuse` -and `Hold` are canonical terminal receipts without RepoModel mutation. `Adopt` -uses the existing atomic RepoModel admission CAS; it creates no route, Hands -authority, Substrate grant, Persona speech authority, release, or deployment. -Decision provenance is typed as a Mind worker result or an authenticated -operator review carrying command, admission, packet digest, and actor identity. -Downstream RepoModel provenance is independently typed as worker result or -frontier-plan decision. Absence is `None`, never an empty worker-id sentinel. - -The v1 command and sealed-result contracts derive review decision time from the -immutable packet `issuedAt`, so consequence-before-result replay is independent -of the retry clock. Candidate mismatch becomes a terminal refusal; storage, -decoding, CAS, and corruption faults propagate. CultCache v0 decision tuples -decode worker provenance into explicit legacy Options. Signed v0 operator -deliveries may drain and replay the original four families, but cannot acquire -the v1 review vocabulary. - -## Live deployment boundary - -The Ygg body runs the v1 six-command crossing through VoidBot, Bifrost, and the -loopback-only Epiphany operator service. Bifrost commit -`6491f449cf0dbfa952b409de90ccdf511669a60b` cut the surviving v0 request -identity; VoidBot is the v1 producer and Bifrost is the v1 consumer. Legacy v0 -admission/result replay remains sealed to the original four commands and is not -a second live request authority. Focused Bifrost interop tests, provider tests, -VoidBot TypeScript compilation, and the cross-runtime smoke pass. The worker is -healthy on Ygg and currently reports zero pending results. - -The remaining acceptance proof needs a real owner Discord interaction; a local -fixture must not impersonate an organization member. Run `/epiphany status` and -ordinary Persona feedback, then inspect typed receipts and negative authority -deltas only. Keep the canonical deployment brake engaged and do not exercise -Wake. Generic VoidBot `provider-status`, `queue-codex`, and job approval operate -VoidBot's own provider/job system and cannot stand in for Epiphany status, -direction, or Mind review. - -## Rust/Bifrost boundary proof (2026-07-19) - -The Epiphany-owned command service now admits the exact signed Bifrost command, -persists admission before consequence, recovers an identity-equal admitted -command after packet expiry, and seals the truthful completion time. Packet -expiry gates first admission; it is not a demand to falsify recovery time. -Malformed UDP is contained inside the daemon loop, and the hostile smoke proves -the same service instance can subsequently complete a CultNet/RUDP handshake -and return the exact sealed receipt. - -`epiphany-operator-command-fixture` emits public Rust-produced interop bytes: -the named admission and sealed receipt, raw compact Bifrost/executor trust -anchors, the canonical executor CultCache `.cc`, and a hash/purpose/connection -manifest. Private fixture signers are quarantined during generation and deleted -before return. The ignored persistent smoke output lives at -`.epiphany-smoke/operator-command-interop-rust`; regenerate it rather than -committing generated signatures or private material. - -Status now has an explicit Epiphany-owned v2 wire projection. The persisted -command result remains v1; only a Status receipt carries -`epiphany.operator_command.status_result.v2` plus typed `statusV2`. Every call -queries Idunn's public CultNet/RUDP snapshot for exactly Epiphany and Bifrost, -verifies each returned record independently against the root-pinned Idunn -projection anchor, and commits the local admission store only when the complete -set verifies. A valid record remains visible when its peer is absent, while the -set stays `incomplete`; stale admission is never reused as current sight. -Provider output contains bounded state, reason, clocks, lineage, and digest—no -signature, detail, path, key, or private state. `protocol.json` now contains the -typed `operatorStatusV2MigrationFixture` golden value for Bifrost and VoidBot -migration; neither consumer is changed by this pass. - -Bifrost's JavaScript smoke consumes those Rust bytes, verifies admission and -receipt signatures plus payload digests, compares the real compact enum/byte -shapes, and rejects mutation. That proof exposed two corrected boundary faults: -Rust compact command enums are unit strings or `[variant, sole-field]` tuples, -not named command maps, and MessagePack integer sequences must be normalized to -exact byte arrays before signature verification. - -Addressing Epiphany currently queues a local VoidBot repo-Face turn and -independently exports the visible prompt as remote feedback. There is not yet a -correlated live Epiphany Persona speech result -> Bifrost Discord receipt -> -original-message reply path. Describe current replies as the local repo Face; -do not claim they are round-trip speech from resident Epiphany. That return -path is later work and must not delay the move-period command nerve. - -## Source anchors - -- VoidBot interaction/addressing owner: - `F:\Projects\VoidBot\apps\bot\src\discord-bot.ts` -- VoidBot feedback-only document: - `F:\Projects\VoidBot\packages\core\src\persona-feedback-observation.ts` -- VoidBot slash commands and owner job controls: - `F:\Projects\VoidBot\apps\bot\src\discord-bot-handlers.ts` -- Bifrost feedback documents/provider: - `F:\Projects\Bifrost\tools\persona-feedback-documents.mjs` and - `F:\Projects\Bifrost\tools\persona-feedback.mjs` -- Bifrost outbound operator alarm seed: - `F:\Projects\Bifrost\tools\operator-notification.mjs` -- Epiphany signature/target admission pattern: - `epiphany-core/src/persona_feedback_admission.rs` -- Epiphany pressure owner: - `epiphany-core/src/resident_self.rs` (`enqueue_resident_self_pressure`) -- Epiphany brake owner: - `epiphany-core/src/cultmesh_integration.rs` - (`load_epiphany_cultmesh_swarm_brake`, - `engage_epiphany_cultmesh_swarm_brake`, - `release_epiphany_cultmesh_swarm_brake`) -- Epiphany operator-safe status owner: - `EpiphanyCultMeshOperatorSnapshotEntry` in the same CultMesh module -- Epiphany frontier Mind decision owner: - `epiphany-core/src/runtime_spine.rs` around - `commit_repo_frontier_plan_decision` -- Ygg deployment/configuration: - `F:\Projects\gamecult-ops\compose\voidbot.yggdrasil.yaml`, - `compose\bifrost.yggdrasil.yaml`, and - `runbooks\epiphany-yggdrasil-deploy.md` diff --git a/notes/epiphany-fork-implementation-plan.md b/notes/epiphany-fork-implementation-plan.md index a29a7df7..779372ad 100644 --- a/notes/epiphany-fork-implementation-plan.md +++ b/notes/epiphany-fork-implementation-plan.md @@ -408,14 +408,15 @@ Cut in this order: exact source `ebc0ffe4` passed Idunn's full Yggdrasil workspace gate, then sealed 27 binaries as release `sha256-bb76728653b8e2e872b4da47f917abe4233fd6d4ae1fd573c5971c7db3922a5c`. - Publication refused before mutation because the Bifrost organizational- - operator substrate is absent. Starfire is not a fallback. + Publication refused before mutation. The unused Discord/Bifrost/VoidBot + operator bridge that caused that gate is now deleted; Starfire is not a + fallback. 25. **Decision discovery is read-only:** exact source `5f66d6c9` adds `list-decisions` beside `audit-decision` in the existing packaged model runtime. It lists only fully validated terminal decision contexts, persists nothing, and omits nonterminal pass physiology. That surface is now inside - the accepted Idunn-built `ebc0ffe4` package; runtime publication and signed - health remain blocked by infrastructure authority outside Epiphany. + the accepted Idunn-built `ebc0ffe4` package. The next Idunn-built source + must replace it before runtime publication and signed health can be claimed. Do not preserve the aggregate for compatibility, manufacture a bootstrap thread, release autonomous scheduling, register topology in `gamecult-ops`, diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index b95491f9..b220206b 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -240,15 +240,15 @@ with witness SHA-256 `4d8350fac61f90d32a2b8067731308ec3e3672a42804db29c680b0fc68ab9adc` and `privateStateExposed=false`. -The exact Idunn request ending `2026-08-21T20:17:11.821Z` then refused before -publication because Yggdrasil lacks the Bifrost organizational-operator -runtime identity and its VoidBot, bridge-group, private-state, anchor, and -configuration substrate. The deployment brake is engaged; Epiphany units are -inactive and disabled; `app/current` still names recovery source `267a0257`; -no `deployment.env`, runtime publication, or signed-health admission exists. -Resident Self's two Codex credential files are also absent behind that first -gate. This is a clean infrastructure blocker, not package acceptance or a -license to bootstrap another organ from the Epiphany lane. +The exact Idunn request ending `2026-08-21T20:17:11.821Z` refused before +publication or mutation. The Discord/Bifrost/VoidBot operator control plane +that imposed that gate is now deleted across Epiphany, Bifrost, VoidBot, and +gamecult-ops. The deployment brake remains engaged; Epiphany units are inactive +and disabled; `app/current` still names recovery source `267a0257`; no +`deployment.env`, runtime publication, or signed-health admission exists. +Resident Self's two Codex credential files remain the legitimate deployment +input blocker. The prior package predates this cut and cannot be promoted as +current source. Fresh source tests prove the retained chain, concurrent keyed commits, old-epoch refusal, deterministic current-work re-entry, and Persona replay @@ -294,12 +294,11 @@ A stopped build container or cloned source volume owns no durable proof. ## Immediate next action -1. Have the Bifrost/VoidBot infrastructure owner install the missing - organizational-operator substrate, then provision Epiphany's Codex - credentials through their single owner. Reissue the exact Idunn deployment - for the already tested and sealed `ebc0ffe4` package and require publication, - runtime start, and signed-health receipts. Do not run a competing release - build on Starfire and do not let the Epiphany lane bootstrap another organ. +1. Provision Epiphany's Codex credentials through their single owner. Let Idunn + build and deploy the source containing the operator-bridge deletion, then + require publication, runtime start, and signed-health receipts. Do not run a + competing release build on Starfire and do not let the Epiphany lane + bootstrap another organ. 2. Run the fresh-store Decision-Auditable Concurrent Mind capstone against the Idunn-admitted package: concurrent Persona/repository work, Body -> Modeling -> Mind, explicit Eyes evidence where required, Hands -> Verification -> Mind, @@ -309,8 +308,7 @@ A stopped build container or cloned source volume owns no durable proof. consequence leg. Do not transplant the old proof anchor or ship a generic test harness. 4. Only then resume Model Atlas Gate 1 from a new external root. Idunn remains - the sole deployment owner; Bifrost/VoidBot bootstrap belongs to its own - infrastructure authority. + the sole deployment owner. ## Operational state that matters @@ -321,12 +319,12 @@ A stopped build container or cloned source volume owns no durable proof. - The old Yggdrasil capacity measurement is obsolete. The upgraded host is the intended swarm body and CI/CD machine. Idunn owns source-change compilation, testing, release construction, deployment, and daemon survival there; its - current deployment truth belongs to the separate deployment task. + current deployment truth belongs to Idunn's typed deployment receipts. - Idunn is active and independent at exact source `745e0109`; its Epiphany source-change target is installed. Exact `ebc0ffe4` passed the full workspace - gate and sealed successfully on Yggdrasil. Publication stopped safely at the - missing Bifrost operator substrate; this is not a reason to fall back to - Starfire compilation. + gate and sealed successfully on Yggdrasil. Publication stopped safely before + mutation. That package is superseded by this source cut and is not a reason + to fall back to Starfire compilation. - Bifrost public crossing remains active on Yggdrasil. A completed public Persona consequence is still unproven because the Yggdrasil Discord credential is absent. diff --git a/notes/memory-graph-semantic-projection-authority-map.md b/notes/memory-graph-semantic-projection-authority-map.md index 31d5f4a6..e5593471 100644 --- a/notes/memory-graph-semantic-projection-authority-map.md +++ b/notes/memory-graph-semantic-projection-authority-map.md @@ -474,7 +474,7 @@ does not invent that grant. liveness, timestamps, and latest error are observation/cache state only. - Idunn command exit is not provider heartbeat, semantic readiness, or proof that a restarted child initialized successfully. -- The health mirror, Self, operator commands, CultMesh, Eve, and Gjallar cannot +- The health mirror, Self, local operator projections, CultMesh, Eve, and Gjallar cannot create obligations, attempts, receipts, canonical state, or readiness. - Arbitrary peers cannot invoke recovery with free-form claim and reason strings. Production recovery requires store-authenticated typed Idunn diff --git a/notes/persona-conversation-authority-map.md b/notes/persona-conversation-authority-map.md index e5b222b3..3ba8c777 100644 --- a/notes/persona-conversation-authority-map.md +++ b/notes/persona-conversation-authority-map.md @@ -57,7 +57,6 @@ writer or scheduler in this path. - VoidBot may not write Epiphany conversation obligations or select Persona turns. - Resident Self feedback pressure may not impersonate addressed conversation. -- The operator-command path may not become ordinary chat ingress. - Heartbeat may not delete a mention merely because it selected a turn. - Model output may not mutate Mind or claim delivery directly. - The Discord mouth may not synthesize Persona speech. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index be8e1d21..19076275 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 64e3c4cc..0483801a 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -4,7 +4,7 @@ experiment: purpose: Native, inspectable agent organism with typed state and explicit organ authority. objective: - current: Provision Yggdrasil's missing Bifrost organizational-operator substrate through its owning infrastructure lane, then let Idunn publish and health-admit the already sealed Epiphany package before the positive capstone and Model Atlas Gate 1. + current: Land the Discord/Bifrost/VoidBot operator-control-plane deletion, then let Idunn build, publish, and health-admit the new Epiphany source after the canonical Codex credentials are provisioned. architecture: body: Repository, runtime, service processes, stores, interfaces, and deployment substrate. @@ -38,14 +38,14 @@ invariants: - Evidence and git retain history; this map retains only state that changes future decisions. current_status: - decision_audit_cut: Exact f8412b69 adds a read-only context-ID audit projection over the sealed basis, decoded reasoning projection, exact terminal native/provider requests, governed tool observations, structured terminal records, and exact Mind commit receipts. Exact 5f66d6c9 adds deterministic read-only discovery of fully auditable terminal context IDs through the existing packaged model runtime; sealed but nonterminal contexts remain physiology and are omitted. Worker archive v1 retains the typed role and generic result family; runtime schema v2 refuses the prior digest-only writable archive shape. Yggdrasil CI then falsified five portable-test assumptions and accepted their source repairs through exact ebc0ffe4. Idunn's full workspace gate is green and its exact Linux package is sealed; runtime publication remains blocked before mutation by the absent Bifrost organizational-operator substrate. + decision_audit_cut: Exact f8412b69 adds a read-only context-ID audit projection over the sealed basis, decoded reasoning projection, exact terminal native/provider requests, governed tool observations, structured terminal records, and exact Mind commit receipts. Exact 5f66d6c9 adds deterministic read-only discovery of fully auditable terminal context IDs through the existing packaged model runtime; sealed but nonterminal contexts remain physiology and are omitted. Worker archive v1 retains the typed role and generic result family; runtime schema v2 refuses the prior digest-only writable archive shape. Yggdrasil CI then falsified five portable-test assumptions and accepted their source repairs through exact ebc0ffe4. Its sealed Linux package predates the operator-control-plane deletion and is now historical package evidence, not a deployable current release. provider_schema_cut: Exact 553f79d9 makes one OpenAI Responses dialect compiler own every role and Persona output schema. Provider-illegal conditional and parent-relative structure is removed, literal-only schemas receive explicit types, supported standard-model constraints remain generation guidance, and UUID formats lower to exact patterns. Full native decoding and family Mind admission remain final authority. Preserved packaged falsifications at 55fb4cf8, edd664db, and 1e01c339 prove refusal before inference, typed failure without Mind writes, successful concurrent Persona cognition, and transcript-free failure audit. repo_model_body_cut: Exact a8f3c1f0 makes the authenticated runtime Body route own initial keyed RepoModel binding. Bootstrap derives the digest from the admitted RepositoryBodyObservationBasis, initialization reauthenticates runtime, swarm, workspace, and Body binding before any write, and a hostile seed refuses with the whole store byte-identical. The exact 553f79d9 package exposed this root after concurrent Persona and terminal Modeling cognition; its result is not transplanted. semantic_cache_cut: The current worktree derives Modeling semantic work from the complete exact keyed RepoModel document-version set and the Mind commit receipts that own those versions. Work items are content-addressed cache physiology generated from the freshly assembled view, so disjoint Mind commits never contend on a singleton projection head. Every operation rederives the complete current keyed basis from its opening snapshot; full-snapshot CAS fences concurrent namespace phantoms. Bootstrap work cannot suppress a later keyed basis, and Modeling retention judges staleness by exact basis identity rather than synthetic aggregate generation or timestamp order. The projector's graph-shaped revision/hash fields survive only as compatibility-shaped cache DTO fields and cannot admit Mind or route cognition. Focused keyed-concurrency and retention suites pass; core is 496/496. package_baseline: Exact clean a8f3c1f0 packaged 27 native Windows binaries as release sha256-19d40048f46355486e66c2abc766abb277122c552cb121a9161e6e95a471be46 with witness sha256-ee8bf0574b5e7d489adc47f6dca491fe5224c8b3e61b3d2fd8c2e67c36d5f903 and privateStateExposed=false. Its fresh capstone projected launchModeling directly from the Body obligation and launched Persona plus Modeling concurrently, but both provider calls failed at the denied chatgpt.com transport boundary. Modeling preserved a transcript-free typed failure audit. Persona exposed a real terminality gap: its outer job failed while the Persona session remained active. The current worktree gives every model-backed role, reorient, and Persona failure one shared terminal owner. Reorientation failure admission now also requires that canonical model-pass failure rather than accepting a generic failed worker result plus context. Provider requests are derived internally from the native request at execution opening, event recording, and context sealing; no public provider-request storage mouth remains. A native negative replay proves sealed basis/context, one typed failure, transcriptRequired=false, and byte-identical restart. The full native workspace/all-target suite passes with core 496/496, OpenAI runtime 25/25, both runtime binaries 10/10, Persona service 1/1, tool runtime 14/14 plus one explicitly live immutable-GitHub test ignored, and all release-construction tests passing. A positive provider-backed package capstone remains open. summary: The keyed RepoModel hard cut, decision-context foundation, Model Atlas code slice, complete Body, Proposal, frontier-verdict Modeling, frontier Research, frontier Verification, frontier Planning/PlanMind, Reorientation, and Persona decision-context lifecycles are landed on codex/epiphany-shakedown-live. Keyed Mind plus exact runtime receipts own coordinator presence, work discovery, deterministic launch, job-bound continuation, review, typed failure, semantic admission, and retained decision reachability. Exact 07d891ba and ec1431ff delete the persisted/global thread aggregate and its generic coordinator/prompt/revision surfaces. Exact f7948795 deletes MindGatewayReview, MindStateCommitReceipt v0, the generic interpreter prompt, runtime registration/read APIs, false thought/state-effect/adoption CultNet mouths, and stale launch proof profiles. CultMesh now projects only reasoning basis, decision context, and exact Mind commit receipt, read-only. Exact 1c9aafd8 seals the terminal decision context before model-backed frontier-Planning failure and binds the typed failure plus generic job result to it. Exact e0e75a30 deletes the residual aggregate role patch/parser/policy surface, gives Research one closed typed decision, and deletes the unowned generic Imagination planning patch. Exact 12b1b285 makes runtime model/tool binding validation the shared owner for execution and decision sealing; hostile provider, receipt, and stored-binding substitutions refuse, while retained basis/context audit survives transcript-delta deletion. Exact 01602fd3 advances Mind/runtime to v2/v1 and refuses historical or split writable identity pairs before registered writers see them. Exact 26b6a5bf proves simultaneous disjoint Modeling writes, simultaneous Verification+Modeling admission, same-identity conflict, exact replay, and reopened graph assembly; raw mutation primitives are crate-private. Exact 7c2ebd81 moves Persona state-note admission from the legacy agent-memory aggregate into keyed Mind documents and proves a concrete Hands consequence can commit simultaneously. Exact 79c0e373 seals the assembled Persona input and observed source versions in Mind before inference. Exact d3300bba authenticates that input through its one exact Mind commit, refuses naked typed documents, re-enters without external observation or model inference, and proves current-work reconstruction is identical and read-only across Launch, Wait, completed, and post-Research boundaries. No compatibility reader, bootstrap aggregate, schema migrator, or dual reader survives. The source-level Decision-Auditable Concurrent Mind migration is accepted; the fresh exact-package capstone remains open. The machine remains a supervised engineering alpha; Model Atlas operational Gate 1 stays paused. public_positioning: docs/positioning.md is the current public claim owner. Epiphany is the organizational layer above frontier AI workers; global coherence collapse is the primary failure; prompts are bounded projections of governed organizational state; humans retain purpose, judgment, authority, disagreement, exceptions, and acceptance. GameCult is the forge and longitudinal evidence program for a target federation of one locally owned Epiphany project organism per living project Body. Model Atlas carries typed offers, claims, evidence, and derived technical relationships; Bifrost is the intended external work, membership, governance, attribution, and identity-linked receipt rail. Public Persona relationships and visitor surfaces are intended social infrastructure, while private Mind and consequence authority remain local. The fleet, real three-repository Gate 1, complete Bifrost attribution, sustained autonomous production, visitor experience, and external design-partner pilots remain gated alpha targets. - latest_phase: Exact 1662a012 makes coordinator policy a pure priority projection over keyed Mind and exact current work. Exact 07d891ba removes 5,441 lines of persisted aggregate coordinator machinery; exact ec1431ff removes another 4,547 lines of thread schema, prompt, revision, freshness, and graph-context authority. Exact f7948795 removes 754 lines net around the dead generic Mind gateway and replaces its mutation-shaped contracts with three read-only decision-audit projections. Exact 1c9aafd8 repairs model-backed frontier-Planning failure ordering: context first, typed failure second, generic job closure third, with one shared context ID. Exact e0e75a30 deletes 612 lines and adds one narrow Research decision contract; runtime result/output contracts advance to v4, and generic patch source guards pass. Exact 12b1b285 replaces partial context-side binding checks with shared exact runtime model/tool validators and proves provider/tool substitution refusal plus transcript-independent retained audit. Exact 01602fd3 advances Mind epoch to v2 and runtime-spine schema to v1; a claimed runtime store must expose one exact current pair, while unrelated physiology stores remain outside Mind ownership. Exact 26b6a5bf proves actual concurrent disjoint-node merge, Verification+Modeling merge, same-key conflict, exact replay, and restart assembly while demoting raw mutation formulation to crate-internal machinery. Exact 7c2ebd81 gives Persona state-note effects one keyed Mind owner under the Interpreter decision context, deletes the aggregate agent-memory writer from that path, and proves concrete Hands+Persona concurrency. Exact 79c0e373 admits the full Persona pass input once, binds all three stages to its exact Mind version, refuses substituted plans, removes direct Git prompt inspection, and excludes Persona-private documents from generic role projections. Exact d3300bba makes one validated `EpiphanyMindCommitReceipt` the re-entry proof for that input, seals plan construction behind the authenticated loader, refuses a naked typed input, performs no external reads or model call on terminal replay, and proves current-work projection is stable without mutation after store reopen. Exact bb823c54 makes provider lowering internal-only, derives terminal transport ownership from the sealed context, and applies one failure closure path to role, reorient, and Persona cognition. Exact 5f66d6c9 adds read-only decision discovery without adding a state writer, transcript dependency, or proof-only binary. Family launches proceed directly from keyed obligations to typed launch documents; thread is pass-local provenance only, stateRevision is absent, and no generic Mind review or patch can authorize mutation. Modeling cache operations authenticate the complete keyed namespace before acting, so a disjoint insert cannot be misclassified as stale work. Yggdrasil CI exposed and exact ebc0ffe4 repairs five Windows-shaped test fixtures; Idunn's full workspace gate records 133 successful summaries with core 499/499. Idunn sealed the 27-binary Linux package with privateStateExposed=false, then refused before publication because the Bifrost organizational-operator substrate is absent. Gate 1 remains paused behind infrastructure admission and the fresh exact-package capstone. + latest_phase: Exact 1662a012 makes coordinator policy a pure priority projection over keyed Mind and exact current work. Exact 07d891ba removes 5,441 lines of persisted aggregate coordinator machinery; exact ec1431ff removes another 4,547 lines of thread schema, prompt, revision, freshness, and graph-context authority. Exact f7948795 removes 754 lines net around the dead generic Mind gateway and replaces its mutation-shaped contracts with three read-only decision-audit projections. Exact 1c9aafd8 repairs model-backed frontier-Planning failure ordering: context first, typed failure second, generic job closure third, with one shared context ID. Exact e0e75a30 deletes 612 lines and adds one narrow Research decision contract; runtime result/output contracts advance to v4, and generic patch source guards pass. Exact 12b1b285 replaces partial context-side binding checks with shared exact runtime model/tool validators and proves provider/tool substitution refusal plus transcript-independent retained audit. Exact 01602fd3 advances Mind epoch to v2 and runtime-spine schema to v1; a claimed runtime store must expose one exact current pair, while unrelated physiology stores remain outside Mind ownership. Exact 26b6a5bf proves actual concurrent disjoint-node merge, Verification+Modeling merge, same-key conflict, exact replay, and restart assembly while demoting raw mutation formulation to crate-internal machinery. Exact 7c2ebd81 gives Persona state-note effects one keyed Mind owner under the Interpreter decision context, deletes the aggregate agent-memory writer from that path, and proves concrete Hands+Persona concurrency. Exact 79c0e373 admits the full Persona pass input once, binds all three stages to its exact Mind version, refuses substituted plans, removes direct Git prompt inspection, and excludes Persona-private documents from generic role projections. Exact d3300bba makes one validated `EpiphanyMindCommitReceipt` the re-entry proof for that input, seals plan construction behind the authenticated loader, refuses a naked typed input, performs no external reads or model call on terminal replay, and proves current-work projection is stable without mutation after store reopen. Exact bb823c54 makes provider lowering internal-only, derives terminal transport ownership from the sealed context, and applies one failure closure path to role, reorient, and Persona cognition. Exact 5f66d6c9 adds read-only decision discovery without adding a state writer, transcript dependency, or proof-only binary. Family launches proceed directly from keyed obligations to typed launch documents; thread is pass-local provenance only, stateRevision is absent, and no generic Mind review or patch can authorize mutation. Modeling cache operations authenticate the complete keyed namespace before acting, so a disjoint insert cannot be misclassified as stale work. Yggdrasil CI exposed and exact ebc0ffe4 repairs five Windows-shaped test fixtures; Idunn's full workspace gate records 133 successful summaries with core 499/499. Idunn sealed the 27-binary Linux package with privateStateExposed=false, then refused before publication. The unused Discord/Bifrost/VoidBot operator control plane that manufactured that gate is now deleted across source, transport, deployment, and health. Gate 1 remains paused behind fresh Idunn admission and the exact-package capstone. operational_state: local_worktree: source_head_ebc0ffe4_pushed_yggdrasil_workspace_gate_green_package_sealed docker_engine_access: starfire_compiler_retired_12_stopped_epiphany_build_containers_and_10_compiler_volumes_removed_8_94_gib_reclaimed_no_current_source_build @@ -55,7 +55,7 @@ current_status: yggdrasil_idunn_epiphany_cicd: exact_745e0109_live_source_change_owner_workspace_tests_green_ebc0ffe4_package_sealed_publication_refused_before_mutation yggdrasil_epiphany_package: source_ebc0ffe4_release_sha256_bb76728653b8e2e872b4da47f917abe4233fd6d4ae1fd573c5971c7db3922a5c_witness_sha256_4d8350fac61f90d32a2b8067731308ec3e3672a42804db29c680b0fc68ab9adc_27_binaries_private_state_false yggdrasil_epiphany_test_receipt: sha256_38c36ebe12e662602d6eccbbdc520de19bff801fec90af0eec2a345306a567d8_133_summaries_core_499_passed - yggdrasil_epiphany_deployment: request_2026_08_21T20_17_11_821Z_failed_before_publication_absent_bifrost_operator_substrate_brake_engaged_units_inactive_recovery_267a0257 + yggdrasil_epiphany_deployment: prior_request_failed_before_publication_and_mutation_bridge_gate_deleted_new_idunn_release_required_units_inactive_recovery_267a0257 starfire: operator_workstation_and_source_checkout_not_cicd_build_body starfire_runtime_identity: epiphany-starfire starfire_swarm_brake: original_c011_quiescent_exited_255_f90_copied_proof_body_braked_and_stopped_exit_zero @@ -81,10 +81,10 @@ current_status: starfire_linux_resident_peak: 62590976_bytes_self_plus_coordinator_plus_model_worker starfire_linux_role_cognition: eyes_and_modeling_tools_results_and_acceptance_proven_zero_consequence starfire_linux_modeling_peak: 109887488_bytes_resident_body_plus_modeling_circuit - yggdrasil_epiphany_service_contract: installed_idunn_source_change_owner_publication_requires_bifrost_operator_substrate + yggdrasil_epiphany_service_contract: idunn_source_change_owner_eve_and_local_typed_operator_surfaces_no_discord_control_plane resident_physiology: historical_c011_exact_465af24d_zero_zombie_proof_accepted_current_containers_exited_255 - unresolved_authority: The source-level Decision-Auditable Concurrent Mind ownership wounds named by this migration are cut. Exact ebc0ffe4 passes Idunn's full Yggdrasil workspace gate and is sealed as a 27-binary Linux package with privateStateExposed=false. Deployment has not occurred: the exact Idunn request refused before publication because Yggdrasil lacks the Bifrost organizational-operator runtime identity and its voidbot, bridge-group, private-state, anchor, and configuration substrate. Resident Self's Codex credential files are also absent behind that first gate. No signed Epiphany service-health admission or positive provider-backed package cognition exists. Model Atlas Gate 1 remains paused. Historical c011 and partial Gate roots stay untouched/read-only. - next_action: Have the Bifrost/VoidBot infrastructure owner provision the missing organizational-operator substrate on Yggdrasil without giving Epiphany or Idunn authority to improvise it. Then provision Epiphany's Codex credentials through their single credential owner and reissue the exact Idunn deployment for sealed source ebc0ffe4. Require publication, runtime start, and signed-health receipts; Starfire must not build. After Idunn admits the release, establish a fresh canonical Persona mouth trust anchor and run the fresh-store positive Decision-Auditable Concurrent Mind capstone through Persona, Body-Modeling-Mind, optional explicit Eyes evidence, Hands-Verification-Mind, decision discovery plus exact context audit, and restart. Do not invent a generic harness, transplant historical proof authority, ship a proof-only binary, or add a compatibility aggregate, generic mutation registry, dual reader, schema migrator, transcript authority, role-specific provider exception, or synthetic semantic head. + unresolved_authority: The source-level Decision-Auditable Concurrent Mind ownership wounds are cut. The unused Discord/VoidBot/Bifrost organizational operator bridge, its Bifrost admission worker, operator review and execution-amendment writers, standalone Epiphany command daemon, and deployment/readiness gates are deleted. Bifrost remains the Persona and governed external-consequence transport; Eve/CultUI and local typed tools remain the intended human and enginseer surfaces. Resident Self's Codex credential files are still absent. The prior ebc0ffe4 package predates this cut and cannot be deployed as current source. No signed Epiphany service-health admission or positive provider-backed package cognition exists. Model Atlas Gate 1 remains paused. Historical c011 and partial Gate roots stay untouched/read-only. + next_action: Commit and push the four-repository operator-bridge cut, let Idunn build the new Epiphany source on Yggdrasil, and provision Epiphany's Codex credentials through their single credential owner. Require exact package, publication, runtime start, and signed-health receipts; Starfire must not build. After Idunn admits the release, establish a fresh canonical Persona mouth trust anchor and run the fresh-store positive Decision-Auditable Concurrent Mind capstone through Persona, Body-Modeling-Mind, optional explicit Eyes evidence, Hands-Verification-Mind, decision discovery plus exact context audit, and restart. Do not invent a generic harness, transplant historical proof authority, ship a proof-only binary, or add a compatibility aggregate, generic mutation registry, dual reader, schema migrator, transcript authority, role-specific provider exception, or synthetic semantic head. active_subgoals: - Complete the fresh exact-package Decision-Auditable Concurrent Mind capstone before any further operational Gate run.