Package resident organizational cognition
This commit is contained in:
parent
0a3c364a6c
commit
17534e6f12
15 changed files with 1580 additions and 41 deletions
|
|
@ -19,6 +19,7 @@ use epiphany_core::EpiphanyProcessObservation as ProcessObservation;
|
|||
use epiphany_core::MemorySemanticProjectionInput;
|
||||
use epiphany_core::agent_memory_semantic_projection_input;
|
||||
use epiphany_core::authenticate_epiphany_cultmesh_semantic_projector_launch;
|
||||
use epiphany_core::authenticate_resident_provider_pair;
|
||||
use epiphany_core::epiphany_cultmesh_daemon_poke_intent_from_status;
|
||||
use epiphany_core::epiphany_cultmesh_daemon_poke_receipt_for_intent;
|
||||
use epiphany_core::idunn_recover_memory_semantic_projection_from_cultmesh;
|
||||
|
|
@ -922,11 +923,32 @@ fn publish_managed_service_iteration_health(
|
|||
SEMANTIC_PROJECTOR_SERVICE_ID,
|
||||
WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID,
|
||||
];
|
||||
let expected = required.len();
|
||||
let mut expected = required.len();
|
||||
let mut terminal_current = 0_usize;
|
||||
let mut warming = 0_usize;
|
||||
let mut workspace_evidence = None;
|
||||
let mut contradictions = Vec::new();
|
||||
if let (Some(heartbeat_store), Some(resident_store)) = (
|
||||
args.resident_heartbeat_store.as_deref(),
|
||||
args.resident_self_store.as_deref(),
|
||||
) {
|
||||
expected += 2;
|
||||
let pair = authenticate_resident_provider_pair(
|
||||
release,
|
||||
authenticated_release_witness_sha256,
|
||||
heartbeat_store,
|
||||
resident_store,
|
||||
Utc::now().timestamp_millis().max(0) as u64,
|
||||
args.resident_provider_stale_seconds.saturating_mul(1000),
|
||||
);
|
||||
terminal_current += pair.terminal_current;
|
||||
warming += pair.warming;
|
||||
contradictions.extend(pair.contradictions);
|
||||
} else if args.resident_heartbeat_store.is_some() || args.resident_self_store.is_some() {
|
||||
expected += 2;
|
||||
contradictions
|
||||
.push("resident health requires both heartbeat and Self provider stores".into());
|
||||
}
|
||||
for service_id in required {
|
||||
let Some(policy) = policies
|
||||
.iter()
|
||||
|
|
@ -4757,6 +4779,9 @@ struct Args {
|
|||
idunn_daemon: Option<String>,
|
||||
idunn_health_contract: Option<String>,
|
||||
idunn_deployment_request_id: Option<String>,
|
||||
resident_heartbeat_store: Option<PathBuf>,
|
||||
resident_self_store: Option<PathBuf>,
|
||||
resident_provider_stale_seconds: u64,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
|
|
@ -4811,6 +4836,9 @@ impl Args {
|
|||
let mut idunn_daemon = None;
|
||||
let mut idunn_health_contract = None;
|
||||
let mut idunn_deployment_request_id = None;
|
||||
let mut resident_heartbeat_store = None;
|
||||
let mut resident_self_store = None;
|
||||
let mut resident_provider_stale_seconds = 180_u64;
|
||||
|
||||
while let Some(arg) = values.next() {
|
||||
match arg.as_str() {
|
||||
|
|
@ -5014,6 +5042,29 @@ impl Args {
|
|||
.context("missing --idunn-deployment-request-id value")?,
|
||||
);
|
||||
}
|
||||
"--resident-heartbeat-store" => {
|
||||
resident_heartbeat_store = Some(PathBuf::from(
|
||||
values
|
||||
.next()
|
||||
.context("missing --resident-heartbeat-store value")?,
|
||||
));
|
||||
}
|
||||
"--resident-self-store" => {
|
||||
resident_self_store = Some(PathBuf::from(
|
||||
values
|
||||
.next()
|
||||
.context("missing --resident-self-store value")?,
|
||||
));
|
||||
}
|
||||
"--resident-provider-stale-seconds" => {
|
||||
resident_provider_stale_seconds = values
|
||||
.next()
|
||||
.context("missing --resident-provider-stale-seconds value")?
|
||||
.parse()?;
|
||||
if resident_provider_stale_seconds == 0 {
|
||||
anyhow::bail!("--resident-provider-stale-seconds must be positive");
|
||||
}
|
||||
}
|
||||
other => anyhow::bail!("unknown argument {other:?}"),
|
||||
}
|
||||
}
|
||||
|
|
@ -5174,6 +5225,9 @@ impl Args {
|
|||
idunn_daemon,
|
||||
idunn_health_contract,
|
||||
idunn_deployment_request_id,
|
||||
resident_heartbeat_store,
|
||||
resident_self_store,
|
||||
resident_provider_stale_seconds,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,11 +12,13 @@ use epiphany_core::HeartbeatTickOptions;
|
|||
use epiphany_core::VoidRoutineOptions;
|
||||
use epiphany_core::apply_agent_self_patch_document;
|
||||
use epiphany_core::complete_heartbeat_store;
|
||||
use epiphany_core::heartbeat_local_provider_status;
|
||||
use epiphany_core::heartbeat_status_projection;
|
||||
use epiphany_core::initialize_ghostlight_scene_heartbeat_store;
|
||||
use epiphany_core::initialize_heartbeat_store;
|
||||
use epiphany_core::load_epiphany_cultmesh_swarm_brake;
|
||||
use epiphany_core::load_heartbeat_state_entry;
|
||||
use epiphany_core::pulse_resident_self_heartbeat;
|
||||
use epiphany_core::pump_heartbeat_store;
|
||||
use epiphany_core::queue_heartbeat_pending_mention_store;
|
||||
use epiphany_core::recover_stale_heartbeat_store;
|
||||
|
|
@ -24,6 +26,10 @@ use epiphany_core::run_void_routine_store;
|
|||
use epiphany_core::tick_heartbeat_store;
|
||||
use epiphany_core::update_heartbeat_heat_store;
|
||||
use epiphany_core::validate_agent_memory_store;
|
||||
use epiphany_core::{
|
||||
ResidentProviderReadiness, authenticate_epiphany_packaged_release, capture_process_instance,
|
||||
publish_resident_provider_readiness,
|
||||
};
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
|
@ -85,6 +91,10 @@ fn main() -> Result<()> {
|
|||
let mut now_utc: Option<String> = None;
|
||||
let mut interval_seconds = 120_u64;
|
||||
let mut max_iterations = 0_u64;
|
||||
let mut release_store: Option<PathBuf> = None;
|
||||
let mut release_runtime_id: Option<String> = None;
|
||||
let mut release_id: Option<String> = None;
|
||||
let mut release_witness_sha256: Option<String> = None;
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
|
|
@ -166,6 +176,14 @@ fn main() -> Result<()> {
|
|||
"--max-iterations" => {
|
||||
max_iterations = next_value(&mut args, "--max-iterations")?.parse()?
|
||||
}
|
||||
"--release-store" => release_store = Some(next_path(&mut args, "--release-store")?),
|
||||
"--release-runtime-id" => {
|
||||
release_runtime_id = Some(next_value(&mut args, "--release-runtime-id")?)
|
||||
}
|
||||
"--release-id" => release_id = Some(next_value(&mut args, "--release-id")?),
|
||||
"--release-witness-sha256" => {
|
||||
release_witness_sha256 = Some(next_value(&mut args, "--release-witness-sha256")?)
|
||||
}
|
||||
_ => return Err(anyhow!("unknown argument {arg:?}")),
|
||||
}
|
||||
}
|
||||
|
|
@ -197,7 +215,11 @@ fn main() -> Result<()> {
|
|||
);
|
||||
}
|
||||
"tick" => {
|
||||
assert_swarm_brake_allows_heartbeat(&local_verse_store, "tick")?;
|
||||
assert_swarm_brake_allows_heartbeat(
|
||||
&local_verse_store,
|
||||
release_runtime_id.as_deref(),
|
||||
"tick",
|
||||
)?;
|
||||
let store_path = store_path.ok_or_else(|| anyhow!("tick requires --store"))?;
|
||||
let artifact_dir =
|
||||
artifact_dir.ok_or_else(|| anyhow!("tick requires --artifact-dir"))?;
|
||||
|
|
@ -264,7 +286,11 @@ fn main() -> Result<()> {
|
|||
println!("{}", result);
|
||||
}
|
||||
"pump" => {
|
||||
assert_swarm_brake_allows_heartbeat(&local_verse_store, "pump")?;
|
||||
assert_swarm_brake_allows_heartbeat(
|
||||
&local_verse_store,
|
||||
release_runtime_id.as_deref(),
|
||||
"pump",
|
||||
)?;
|
||||
let store_path = store_path.ok_or_else(|| anyhow!("pump requires --store"))?;
|
||||
let artifact_dir =
|
||||
artifact_dir.ok_or_else(|| anyhow!("pump requires --artifact-dir"))?;
|
||||
|
|
@ -299,7 +325,11 @@ fn main() -> Result<()> {
|
|||
println!("{}", result);
|
||||
}
|
||||
"heat" => {
|
||||
assert_swarm_brake_allows_heartbeat(&local_verse_store, "heat")?;
|
||||
assert_swarm_brake_allows_heartbeat(
|
||||
&local_verse_store,
|
||||
release_runtime_id.as_deref(),
|
||||
"heat",
|
||||
)?;
|
||||
let store_path = store_path.ok_or_else(|| anyhow!("heat requires --store"))?;
|
||||
let result = update_heartbeat_heat_store(
|
||||
&store_path,
|
||||
|
|
@ -317,7 +347,11 @@ fn main() -> Result<()> {
|
|||
println!("{}", result);
|
||||
}
|
||||
"queue-mention" => {
|
||||
assert_swarm_brake_allows_heartbeat(&local_verse_store, "queue-mention")?;
|
||||
assert_swarm_brake_allows_heartbeat(
|
||||
&local_verse_store,
|
||||
release_runtime_id.as_deref(),
|
||||
"queue-mention",
|
||||
)?;
|
||||
let store_path = store_path.ok_or_else(|| anyhow!("queue-mention requires --store"))?;
|
||||
let target_role_id = role.unwrap_or_else(|| "Persona".to_string());
|
||||
let result = queue_heartbeat_pending_mention_store(
|
||||
|
|
@ -371,7 +405,11 @@ fn main() -> Result<()> {
|
|||
}
|
||||
}
|
||||
"routine" => {
|
||||
assert_swarm_brake_allows_heartbeat(&local_verse_store, "routine")?;
|
||||
assert_swarm_brake_allows_heartbeat(
|
||||
&local_verse_store,
|
||||
release_runtime_id.as_deref(),
|
||||
"routine",
|
||||
)?;
|
||||
let store_path = store_path.ok_or_else(|| anyhow!("routine requires --store"))?;
|
||||
let artifact_dir =
|
||||
artifact_dir.ok_or_else(|| anyhow!("routine requires --artifact-dir"))?;
|
||||
|
|
@ -404,6 +442,33 @@ fn main() -> Result<()> {
|
|||
let store_path = store_path.ok_or_else(|| anyhow!("serve requires --store"))?;
|
||||
let artifact_dir =
|
||||
artifact_dir.ok_or_else(|| anyhow!("serve requires --artifact-dir"))?;
|
||||
let provider_release = if resident_self_store.is_some() {
|
||||
let release_store = release_store
|
||||
.as_deref()
|
||||
.ok_or_else(|| anyhow!("resident heartbeat serve requires --release-store"))?;
|
||||
let runtime_id = release_runtime_id.as_deref().ok_or_else(|| {
|
||||
anyhow!("resident heartbeat serve requires --release-runtime-id")
|
||||
})?;
|
||||
let release_id = release_id
|
||||
.as_deref()
|
||||
.ok_or_else(|| anyhow!("resident heartbeat serve requires --release-id"))?;
|
||||
let witness = release_witness_sha256.as_deref().ok_or_else(|| {
|
||||
anyhow!("resident heartbeat serve requires --release-witness-sha256")
|
||||
})?;
|
||||
Some(authenticate_epiphany_packaged_release(
|
||||
release_store,
|
||||
runtime_id,
|
||||
release_id,
|
||||
witness,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let provider_process = if provider_release.is_some() {
|
||||
Some(capture_process_instance(std::process::id())?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(agent_store) = &agent_store {
|
||||
let errors = validate_agent_memory_store(agent_store)?;
|
||||
if !errors.is_empty() {
|
||||
|
|
@ -427,8 +492,71 @@ fn main() -> Result<()> {
|
|||
break;
|
||||
}
|
||||
let iteration = completed_iterations + 1;
|
||||
if let (Some(release), Some(process)) = (&provider_release, &provider_process) {
|
||||
publish_resident_provider_readiness(
|
||||
&store_path,
|
||||
ResidentProviderReadiness {
|
||||
schema_version:
|
||||
epiphany_core::RESIDENT_PROVIDER_READINESS_SCHEMA_VERSION.into(),
|
||||
provider: "heartbeat".into(),
|
||||
runtime_id: release.runtime_id.clone(),
|
||||
release_id: release.release_id.clone(),
|
||||
release_witness_sha256: release_witness_sha256
|
||||
.clone()
|
||||
.expect("authenticated witness"),
|
||||
source_commit: release.source_commit_sha.clone(),
|
||||
publisher_sequence: 0,
|
||||
observed_at_millis: chrono::Utc::now().timestamp_millis().max(0) as u64,
|
||||
process_id: process.process_id,
|
||||
process_creation_token: process.creation_token,
|
||||
process_executable_path: process.executable_path.display().to_string(),
|
||||
status: heartbeat_local_provider_status(
|
||||
&store_path,
|
||||
resident_self_store.as_deref().expect("resident store"),
|
||||
)
|
||||
.into(),
|
||||
private_state_exposed: false,
|
||||
},
|
||||
)?;
|
||||
}
|
||||
let iteration_dir = artifact_dir.join(format!("pulse-{iteration:06}"));
|
||||
if let Some(brake) = active_swarm_brake(&local_verse_store)? {
|
||||
let brake = active_swarm_brake(
|
||||
&local_verse_store,
|
||||
provider_release
|
||||
.as_ref()
|
||||
.map(|release| release.runtime_id.as_str())
|
||||
.or(release_runtime_id.as_deref()),
|
||||
)?;
|
||||
if let Some(resident_store) = resident_self_store.as_deref() {
|
||||
let pulse = pulse_resident_self_heartbeat(
|
||||
&store_path,
|
||||
resident_store,
|
||||
&iteration_dir,
|
||||
brake.is_some(),
|
||||
&format!("{schedule_id}.serve-{iteration:06}"),
|
||||
&source_scene_ref,
|
||||
agent_store.clone(),
|
||||
)?;
|
||||
if pulse.status != "idle" {
|
||||
completed_iterations = iteration;
|
||||
refused_pulses += u64::from(brake.is_some());
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({
|
||||
"schemaVersion":"epiphany.heartbeat.serve_pulse.v0", "status":pulse.status,
|
||||
"owner":"heartbeat", "iteration":iteration, "artifactDir":iteration_dir,
|
||||
"acknowledgedTerminalId":pulse.acknowledged_terminal_id, "grantId":pulse.grant_id,
|
||||
"brakeId":brake.as_ref().map(|value| &value.brake_id), "privateStateExposed":false
|
||||
})
|
||||
);
|
||||
if max_iterations > 0 && completed_iterations >= max_iterations {
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_secs(interval_seconds));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(brake) = brake {
|
||||
completed_iterations = iteration;
|
||||
refused_pulses += 1;
|
||||
println!(
|
||||
|
|
@ -542,9 +670,10 @@ fn usage() -> Result<()> {
|
|||
|
||||
fn assert_swarm_brake_allows_heartbeat(
|
||||
local_verse_store: &Option<PathBuf>,
|
||||
runtime_id: Option<&str>,
|
||||
command: &str,
|
||||
) -> Result<()> {
|
||||
if let Some(brake) = active_swarm_brake(local_verse_store)? {
|
||||
if let Some(brake) = active_swarm_brake(local_verse_store, runtime_id)? {
|
||||
anyhow::bail!(
|
||||
"epiphany-heartbeat-store {command} refusing to run: local Verse swarm brake engaged; scope={}; protected={}; affected={}; reason={}",
|
||||
brake.scope,
|
||||
|
|
@ -558,6 +687,7 @@ fn assert_swarm_brake_allows_heartbeat(
|
|||
|
||||
fn active_swarm_brake(
|
||||
local_verse_store: &Option<PathBuf>,
|
||||
runtime_id: Option<&str>,
|
||||
) -> Result<Option<EpiphanyCultMeshSwarmBrakeEntry>> {
|
||||
let Some(local_verse_store) = local_verse_store else {
|
||||
return Ok(None);
|
||||
|
|
@ -565,12 +695,41 @@ fn active_swarm_brake(
|
|||
if !local_verse_store.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let runtime_id = runtime_id.ok_or_else(|| {
|
||||
anyhow!("heartbeat local Verse brake lookup requires --release-runtime-id")
|
||||
})?;
|
||||
Ok(
|
||||
load_epiphany_cultmesh_swarm_brake(local_verse_store, "epiphany-local")?
|
||||
load_epiphany_cultmesh_swarm_brake(local_verse_store, runtime_id)?
|
||||
.filter(|brake| brake.status == "engaged"),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod brake_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn heartbeat_uses_exact_release_runtime_brake_namespace() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let store = temp.path().join("verse.cc");
|
||||
let store_arg = Some(store.clone());
|
||||
let mut brake =
|
||||
epiphany_core::default_epiphany_cultmesh_swarm_brake("2026-07-18T00:00:00Z");
|
||||
brake.status = "engaged".into();
|
||||
brake.reason = "test".into();
|
||||
let mut legacy_node =
|
||||
epiphany_core::open_epiphany_cultmesh_node(&store, "legacy-writer-runtime")?;
|
||||
legacy_node.put("epiphany-local/swarm-brake", &brake)?;
|
||||
legacy_node.flush()?;
|
||||
assert!(active_swarm_brake(&store_arg, Some("epiphany-yggdrasil"))?.is_some());
|
||||
epiphany_core::write_epiphany_cultmesh_swarm_brake(&store, "wrong-runtime", brake.clone())?;
|
||||
assert!(active_swarm_brake(&store_arg, Some("epiphany-yggdrasil"))?.is_none());
|
||||
epiphany_core::write_epiphany_cultmesh_swarm_brake(&store, "epiphany-yggdrasil", brake)?;
|
||||
assert!(active_swarm_brake(&store_arg, Some("epiphany-yggdrasil"))?.is_some());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_scene_participant(raw: &str) -> Result<GhostlightSceneParticipantSeed> {
|
||||
let parts = raw.split('|').collect::<Vec<_>>();
|
||||
if parts.len() != 6 {
|
||||
|
|
|
|||
|
|
@ -92,6 +92,7 @@ struct Args {
|
|||
resident_binding: BTreeMap<String, String>,
|
||||
resident_state_store: Option<PathBuf>,
|
||||
resident_preparation_id: Option<String>,
|
||||
runtime_id: Option<String>,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
|
|
@ -128,6 +129,7 @@ impl Args {
|
|||
resident_binding: BTreeMap::new(),
|
||||
resident_state_store: None,
|
||||
resident_preparation_id: None,
|
||||
runtime_id: None,
|
||||
};
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
|
|
@ -173,6 +175,7 @@ impl Args {
|
|||
parsed.resident_preparation_id =
|
||||
Some(take_string(&mut args, "--resident-preparation-id")?)
|
||||
}
|
||||
"--runtime-id" => parsed.runtime_id = Some(take_string(&mut args, "--runtime-id")?),
|
||||
"--cwd" => parsed.cwd = take_path(&mut args, "--cwd")?,
|
||||
"--codex-home" => parsed.codex_home = take_path(&mut args, "--codex-home")?,
|
||||
"--artifact-dir" => parsed.artifact_dir = take_path(&mut args, "--artifact-dir")?,
|
||||
|
|
@ -214,6 +217,11 @@ impl Args {
|
|||
other => return Err(anyhow!("unknown argument: {other}")),
|
||||
}
|
||||
}
|
||||
if parsed.runtime_id.as_deref().is_none_or(str::is_empty) {
|
||||
return Err(anyhow!(
|
||||
"coordinator requires exact --runtime-id for local Verse authority"
|
||||
));
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
}
|
||||
|
|
@ -242,7 +250,11 @@ fn run_coordinator(args: &Args) -> Result<Value> {
|
|||
}
|
||||
}
|
||||
let local_verse_store = status_cli::absolute_path(&args.local_verse_store)?;
|
||||
assert_local_verse_brake_released(&local_verse_store, "epiphany-mvp-coordinator")?;
|
||||
assert_local_verse_brake_released(
|
||||
&local_verse_store,
|
||||
args.runtime_id.as_deref().expect("validated runtime id"),
|
||||
"epiphany-mvp-coordinator",
|
||||
)?;
|
||||
let cwd = status_cli::absolute_path(&args.cwd)?;
|
||||
let model_runtime_bin = resolve_model_runtime_bin(&root, &args.model_runtime_bin)?;
|
||||
let tool_adapter_bin = resolve_model_runtime_bin(&root, &args.tool_adapter_bin)?;
|
||||
|
|
@ -796,12 +808,15 @@ fn intake_operator_objective(
|
|||
})
|
||||
}
|
||||
|
||||
fn assert_local_verse_brake_released(local_verse_store: &Path, runner_name: &str) -> Result<()> {
|
||||
fn assert_local_verse_brake_released(
|
||||
local_verse_store: &Path,
|
||||
runtime_id: &str,
|
||||
runner_name: &str,
|
||||
) -> Result<()> {
|
||||
if !local_verse_store.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(brake) = load_epiphany_cultmesh_swarm_brake(local_verse_store, "epiphany-local")?
|
||||
else {
|
||||
let Some(brake) = load_epiphany_cultmesh_swarm_brake(local_verse_store, runtime_id)? else {
|
||||
return Ok(());
|
||||
};
|
||||
if brake.status == "engaged" {
|
||||
|
|
|
|||
|
|
@ -2,13 +2,16 @@ use anyhow::{Context, Result, anyhow};
|
|||
use chrono::Utc;
|
||||
use epiphany_core::{
|
||||
ChildObservation, CoordinatorLaunch, LaunchedCoordinator, ProcessInstanceIdentity,
|
||||
ProcessInstanceObservation, ResidentSelfOutcome, ResidentSelfPolicy, ResidentSelfPorts,
|
||||
ResidentSelfPressure, ResidentSelfState, acknowledge_resident_self_launch,
|
||||
authenticate_resident_self_policy, cancel_resident_self_turn, capture_process_instance,
|
||||
complete_resident_self_turn, coordinator_run_receipts, enqueue_resident_self_pressure,
|
||||
ProcessInstanceObservation, ResidentProviderReadiness, ResidentReadinessRequest,
|
||||
ResidentSelfOutcome, ResidentSelfPolicy, ResidentSelfPorts, ResidentSelfPressure,
|
||||
ResidentSelfState, acknowledge_resident_self_launch, authenticate_resident_self_policy,
|
||||
cancel_resident_self_turn, capture_process_instance, complete_resident_self_turn,
|
||||
coordinator_run_receipts, derive_resident_cognition_readiness, enqueue_resident_self_pressure,
|
||||
ingest_resident_self_domain_pressure, load_epiphany_cultmesh_swarm_brake,
|
||||
load_resident_self_state, observe_process_instance, prepare_resident_self_launch,
|
||||
resident_self_child_claim, terminate_process_instance, validate_resident_self_store_separation,
|
||||
publish_resident_provider_readiness, resident_self_child_claim,
|
||||
resident_self_local_provider_status, terminate_process_instance,
|
||||
validate_resident_self_store_separation,
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
|
@ -23,6 +26,27 @@ fn main() -> Result<()> {
|
|||
authenticate_resident_self_policy(&mut args.policy)?;
|
||||
args.policy.validate()?;
|
||||
validate_resident_self_store_separation(&args.state_store, &args.policy)?;
|
||||
if args.heartbeat_store == args.state_store {
|
||||
return Err(anyhow!(
|
||||
"heartbeat and resident Self stores must be physically separate"
|
||||
));
|
||||
}
|
||||
if matches!(args.command, CommandKind::Status) {
|
||||
let now = Utc::now().timestamp_millis().max(0) as u64;
|
||||
let projection = derive_resident_cognition_readiness(ResidentReadinessRequest {
|
||||
release_store: &args.policy.release_store,
|
||||
heartbeat_store: &args.heartbeat_store,
|
||||
resident_store: &args.state_store,
|
||||
policy: &args.policy,
|
||||
release_runtime_id: &args.policy.release_runtime_id,
|
||||
release_id: &args.policy.release_id,
|
||||
release_witness_sha256: &args.policy.release_witness_sha256,
|
||||
now_millis: now,
|
||||
freshness_millis: args.provider_freshness_seconds.saturating_mul(1000),
|
||||
});
|
||||
println!("{}", serde_json::to_string_pretty(&projection)?);
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(pressure) = args.pressure.as_ref() {
|
||||
enqueue_resident_self_pressure(&args.state_store, pressure)?;
|
||||
}
|
||||
|
|
@ -31,6 +55,7 @@ fn main() -> Result<()> {
|
|||
match args.command {
|
||||
CommandKind::Once => {
|
||||
let outcome = cycle(&args, &mut state, &mut ports)?;
|
||||
publish_self_readiness(&args)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&summary(&state, &outcome))?
|
||||
|
|
@ -38,6 +63,7 @@ fn main() -> Result<()> {
|
|||
}
|
||||
CommandKind::Serve => loop {
|
||||
let outcome = cycle(&args, &mut state, &mut ports)?;
|
||||
publish_self_readiness(&args)?;
|
||||
println!("{}", serde_json::to_string(&summary(&state, &outcome))?);
|
||||
let seconds = match outcome {
|
||||
ResidentSelfOutcome::Failed => args.policy.failure_backoff_seconds,
|
||||
|
|
@ -46,10 +72,34 @@ fn main() -> Result<()> {
|
|||
};
|
||||
thread::sleep(Duration::from_secs(seconds.max(1)));
|
||||
},
|
||||
CommandKind::Status => unreachable!("status returned before actuation setup"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn publish_self_readiness(args: &Args) -> Result<()> {
|
||||
let process = capture_process_instance(std::process::id())?;
|
||||
publish_resident_provider_readiness(
|
||||
&args.state_store,
|
||||
ResidentProviderReadiness {
|
||||
schema_version: epiphany_core::RESIDENT_PROVIDER_READINESS_SCHEMA_VERSION.into(),
|
||||
provider: "resident-self".into(),
|
||||
runtime_id: args.policy.release_runtime_id.clone(),
|
||||
release_id: args.policy.release_id.clone(),
|
||||
release_witness_sha256: args.policy.release_witness_sha256.clone(),
|
||||
source_commit: args.policy.release_commit.clone(),
|
||||
publisher_sequence: 0,
|
||||
observed_at_millis: Utc::now().timestamp_millis().max(0) as u64,
|
||||
process_id: process.process_id,
|
||||
process_creation_token: process.creation_token,
|
||||
process_executable_path: process.executable_path.display().to_string(),
|
||||
status: resident_self_local_provider_status(&args.state_store, &args.policy).into(),
|
||||
private_state_exposed: false,
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cycle(
|
||||
args: &Args,
|
||||
state: &mut ResidentSelfState,
|
||||
|
|
@ -220,11 +270,14 @@ fn summary(state: &ResidentSelfState, outcome: &ResidentSelfOutcome) -> serde_js
|
|||
enum CommandKind {
|
||||
Once,
|
||||
Serve,
|
||||
Status,
|
||||
}
|
||||
|
||||
struct Args {
|
||||
command: CommandKind,
|
||||
state_store: PathBuf,
|
||||
heartbeat_store: PathBuf,
|
||||
provider_freshness_seconds: u64,
|
||||
policy: ResidentSelfPolicy,
|
||||
pressure: Option<ResidentSelfPressure>,
|
||||
}
|
||||
|
|
@ -235,9 +288,10 @@ impl Args {
|
|||
let command = match it.next().as_deref() {
|
||||
Some("once") => CommandKind::Once,
|
||||
Some("serve") => CommandKind::Serve,
|
||||
Some("status") => CommandKind::Status,
|
||||
_ => {
|
||||
return Err(anyhow!(
|
||||
"usage: epiphany-swarm <once|serve> with exact absolute packaged paths"
|
||||
"usage: epiphany-swarm <once|serve|status> with exact absolute packaged paths"
|
||||
));
|
||||
}
|
||||
};
|
||||
|
|
@ -277,7 +331,7 @@ impl Args {
|
|||
model_provider: value
|
||||
.get("--model-provider")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "local".into()),
|
||||
.ok_or_else(|| anyhow!("missing --model-provider"))?,
|
||||
max_steps: u64v("--max-steps", 4)?,
|
||||
turn_timeout_seconds: u64v("--turn-timeout-seconds", 600)?,
|
||||
cooldown_seconds: u64v("--cooldown-seconds", 60)?,
|
||||
|
|
@ -316,6 +370,8 @@ impl Args {
|
|||
Ok(Self {
|
||||
command,
|
||||
state_store: path("--state-store")?,
|
||||
heartbeat_store: path("--heartbeat-store")?,
|
||||
provider_freshness_seconds: u64v("--provider-freshness-seconds", 180)?,
|
||||
policy,
|
||||
pressure,
|
||||
})
|
||||
|
|
@ -338,11 +394,10 @@ impl<'a> NativePorts<'a> {
|
|||
|
||||
impl ResidentSelfPorts for NativePorts<'_> {
|
||||
fn brake_engaged(&mut self) -> Result<bool> {
|
||||
Ok(load_epiphany_cultmesh_swarm_brake(
|
||||
resident_self_brake_engaged(
|
||||
&self.policy.local_verse_store,
|
||||
"epiphany-resident-self",
|
||||
)?
|
||||
.is_some_and(|brake| brake.status == "engaged"))
|
||||
&self.policy.release_runtime_id,
|
||||
)
|
||||
}
|
||||
|
||||
fn observe_child(
|
||||
|
|
@ -430,3 +485,33 @@ impl ResidentSelfPorts for NativePorts<'_> {
|
|||
Ok(receipts.last().map(|receipt| receipt.receipt_id.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
fn resident_self_brake_engaged(
|
||||
local_verse_store: &std::path::Path,
|
||||
runtime_id: &str,
|
||||
) -> Result<bool> {
|
||||
Ok(
|
||||
load_epiphany_cultmesh_swarm_brake(local_verse_store, runtime_id)?
|
||||
.is_some_and(|brake| brake.status == "engaged"),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod brake_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resident_self_uses_exact_release_runtime_brake_namespace() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let store = temp.path().join("verse.cc");
|
||||
let mut brake =
|
||||
epiphany_core::default_epiphany_cultmesh_swarm_brake("2026-07-18T00:00:00Z");
|
||||
brake.status = "engaged".into();
|
||||
brake.reason = "test".into();
|
||||
epiphany_core::write_epiphany_cultmesh_swarm_brake(&store, "wrong-runtime", brake.clone())?;
|
||||
assert!(!resident_self_brake_engaged(&store, "epiphany-yggdrasil")?);
|
||||
epiphany_core::write_epiphany_cultmesh_swarm_brake(&store, "epiphany-yggdrasil", brake)?;
|
||||
assert!(resident_self_brake_engaged(&store, "epiphany-yggdrasil")?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -490,6 +490,7 @@ fn run_cli() -> Result<()> {
|
|||
"Runners should treat engaged brakes as fail-closed launch pressure for the protected surfaces.".to_string(),
|
||||
"The brake carries scope and reason only; it does not expose private worker state.".to_string(),
|
||||
],
|
||||
runtime_id: args.runtime_id.clone(),
|
||||
}
|
||||
};
|
||||
if status == "released" {
|
||||
|
|
|
|||
|
|
@ -1821,6 +1821,8 @@ pub struct EpiphanyCultMeshSwarmBrakeEntry {
|
|||
pub private_state_exposed: bool,
|
||||
#[cultcache(key = 11)]
|
||||
pub notes: Vec<String>,
|
||||
#[cultcache(key = 12, default)]
|
||||
pub runtime_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
|
|
@ -4505,14 +4507,17 @@ pub fn default_epiphany_cultmesh_swarm_brake(
|
|||
"It may stop scheduling and daemon pokes, but it must not expose worker thoughts or private Verse state.".to_string(),
|
||||
"Engaged brakes require a scoped reason so silence cannot masquerade as consent.".to_string(),
|
||||
],
|
||||
runtime_id: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_epiphany_cultmesh_swarm_brake(
|
||||
store_path: impl AsRef<Path>,
|
||||
runtime_id: impl Into<String>,
|
||||
brake: EpiphanyCultMeshSwarmBrakeEntry,
|
||||
mut brake: EpiphanyCultMeshSwarmBrakeEntry,
|
||||
) -> Result<EpiphanyCultMeshSwarmBrakeEntry> {
|
||||
let runtime_id = runtime_id.into();
|
||||
brake.runtime_id = runtime_id.clone();
|
||||
validate_swarm_brake(&brake)?;
|
||||
let mut node = open_epiphany_cultmesh_node(store_path, runtime_id)?;
|
||||
let written = node.put(EPIPHANY_CULTMESH_SWARM_BRAKE_KEY, &brake)?;
|
||||
|
|
@ -4524,8 +4529,11 @@ pub fn load_epiphany_cultmesh_swarm_brake(
|
|||
store_path: impl AsRef<Path>,
|
||||
runtime_id: impl Into<String>,
|
||||
) -> Result<Option<EpiphanyCultMeshSwarmBrakeEntry>> {
|
||||
let node = open_epiphany_cultmesh_node(store_path, runtime_id)?;
|
||||
node.get(EPIPHANY_CULTMESH_SWARM_BRAKE_KEY)
|
||||
let runtime_id = runtime_id.into();
|
||||
let node = open_epiphany_cultmesh_node(store_path, runtime_id.clone())?;
|
||||
Ok(node
|
||||
.get::<EpiphanyCultMeshSwarmBrakeEntry>(EPIPHANY_CULTMESH_SWARM_BRAKE_KEY)?
|
||||
.filter(|brake| brake.runtime_id.is_empty() || brake.runtime_id == runtime_id))
|
||||
}
|
||||
|
||||
pub fn write_epiphany_cultmesh_persona_speech_audit(
|
||||
|
|
@ -4658,6 +4666,9 @@ fn validate_swarm_brake(brake: &EpiphanyCultMeshSwarmBrakeEntry) -> Result<()> {
|
|||
if brake.brake_id.trim().is_empty() || brake.scope.trim().is_empty() {
|
||||
return Err(anyhow!("swarm brake requires brake id and scope"));
|
||||
}
|
||||
if brake.runtime_id.trim().is_empty() {
|
||||
return Err(anyhow!("swarm brake requires its owning runtime id"));
|
||||
}
|
||||
if brake.created_at_utc.trim().is_empty() {
|
||||
return Err(anyhow!("swarm brake requires a creation timestamp"));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -294,6 +294,182 @@ pub fn tick_heartbeat_store(
|
|||
}))
|
||||
}
|
||||
|
||||
pub fn reconcile_resident_self_heartbeat_ack(
|
||||
heartbeat_store: impl AsRef<Path>,
|
||||
resident_store: impl AsRef<Path>,
|
||||
) -> Result<Option<String>> {
|
||||
let heartbeat_store = heartbeat_store.as_ref();
|
||||
let resident_store = resident_store.as_ref();
|
||||
if heartbeat_store == resident_store {
|
||||
return Err(anyhow!("heartbeat and resident Self stores must differ"));
|
||||
}
|
||||
let (state, expected) = load_heartbeat_state_transaction(heartbeat_store)?;
|
||||
let Some(mut state) = state else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some((index, pending)) = state
|
||||
.participants
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, participant)| participant.role_id == "coordinator")
|
||||
.and_then(|(index, participant)| {
|
||||
participant
|
||||
.pending_turn
|
||||
.clone()
|
||||
.map(|pending| (index, pending))
|
||||
})
|
||||
else {
|
||||
// Recovery for a crash after heartbeat completion committed but before the
|
||||
// acknowledgement was marked consumed in the separate resident store.
|
||||
let completed = crate::pending_resident_self_acks(resident_store)?
|
||||
.into_iter()
|
||||
.find(|ack| {
|
||||
state.history.iter().any(|event| {
|
||||
event.selected_role == "coordinator"
|
||||
&& event.schedule_id == ack.heartbeat_schedule_id
|
||||
&& event.action_id == ack.heartbeat_action_id
|
||||
&& event.turn_status.as_deref() == Some("completed")
|
||||
})
|
||||
});
|
||||
if let Some(ack) = completed {
|
||||
crate::heartbeat_consume_resident_self_ack(
|
||||
resident_store,
|
||||
&ack.ack_id,
|
||||
Utc::now().timestamp_millis().max(0) as u64,
|
||||
)?;
|
||||
return Ok(Some(ack.ack_id));
|
||||
}
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(ack) = crate::pending_resident_self_ack_for(
|
||||
resident_store,
|
||||
&pending.schedule_id,
|
||||
&pending.action_id,
|
||||
)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let completed = complete_pending_turn(&mut state, index)?;
|
||||
let participant = &state.participants[index];
|
||||
state.history.push(HeartbeatHistoryEvent {
|
||||
ts: now_iso(),
|
||||
schedule_id: completed.schedule_id.clone(),
|
||||
selected_role: participant.role_id.clone(),
|
||||
selected_agent_id: participant.agent_id.clone(),
|
||||
action_id: completed.action_id.clone(),
|
||||
action_type: completed.action_type.clone(),
|
||||
arena: participant_arena(participant).to_string(),
|
||||
participant_kind: participant_kind(participant).to_string(),
|
||||
action_scale: completed.action_scale.clone(),
|
||||
coordinator_action: None,
|
||||
target_role: None,
|
||||
work_role: None,
|
||||
scene_clock: Some(state.scene_clock),
|
||||
next_ready_at: Some(participant.next_ready_at),
|
||||
turn_status: Some("completed".into()),
|
||||
cooldown_started_after_completion: Some(true),
|
||||
});
|
||||
trim_history(&mut state);
|
||||
commit_heartbeat_state_transaction(heartbeat_store, expected, &state)?;
|
||||
crate::heartbeat_consume_resident_self_ack(
|
||||
resident_store,
|
||||
&ack.ack_id,
|
||||
Utc::now().timestamp_millis().max(0) as u64,
|
||||
)?;
|
||||
Ok(Some(ack.ack_id))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResidentSelfHeartbeatPulse {
|
||||
pub status: String,
|
||||
pub acknowledged_terminal_id: Option<String>,
|
||||
pub grant_id: Option<String>,
|
||||
}
|
||||
|
||||
pub fn pulse_resident_self_heartbeat(
|
||||
heartbeat_store: impl AsRef<Path>,
|
||||
resident_store: impl AsRef<Path>,
|
||||
artifact_dir: impl AsRef<Path>,
|
||||
brake_engaged: bool,
|
||||
schedule_id: &str,
|
||||
source_scene_ref: &str,
|
||||
agent_store: Option<std::path::PathBuf>,
|
||||
) -> Result<ResidentSelfHeartbeatPulse> {
|
||||
let heartbeat_store = heartbeat_store.as_ref();
|
||||
let resident_store = resident_store.as_ref();
|
||||
let acknowledged_terminal_id =
|
||||
reconcile_resident_self_heartbeat_ack(heartbeat_store, resident_store)?;
|
||||
if brake_engaged {
|
||||
return Ok(ResidentSelfHeartbeatPulse {
|
||||
status: "braked-after-ack-reconciliation".into(),
|
||||
acknowledged_terminal_id,
|
||||
grant_id: None,
|
||||
});
|
||||
}
|
||||
let state = load_heartbeat_state_entry(heartbeat_store)?;
|
||||
let active = state
|
||||
.as_ref()
|
||||
.and_then(|state| {
|
||||
state
|
||||
.participants
|
||||
.iter()
|
||||
.find(|participant| participant.role_id == "coordinator")
|
||||
})
|
||||
.and_then(|participant| participant.pending_turn.as_ref())
|
||||
.filter(|turn| turn.status == "running")
|
||||
.cloned();
|
||||
if let Some(active) = active {
|
||||
if crate::pending_resident_self_pressure(resident_store)? {
|
||||
let grant = crate::heartbeat_issue_resident_self_grant(
|
||||
resident_store,
|
||||
&active.schedule_id,
|
||||
&active.action_id,
|
||||
Utc::now().timestamp_millis().max(0) as u64,
|
||||
)?;
|
||||
return Ok(ResidentSelfHeartbeatPulse {
|
||||
status: "recovered-committed-grant".into(),
|
||||
acknowledged_terminal_id,
|
||||
grant_id: grant.map(|grant| grant.grant_id),
|
||||
});
|
||||
}
|
||||
return Ok(ResidentSelfHeartbeatPulse {
|
||||
status: "active-coordinator-turn".into(),
|
||||
acknowledged_terminal_id,
|
||||
grant_id: None,
|
||||
});
|
||||
}
|
||||
if !crate::pending_resident_self_pressure(resident_store)? {
|
||||
return Ok(ResidentSelfHeartbeatPulse {
|
||||
status: "idle".into(),
|
||||
acknowledged_terminal_id,
|
||||
grant_id: None,
|
||||
});
|
||||
}
|
||||
tick_heartbeat_store(
|
||||
heartbeat_store,
|
||||
artifact_dir,
|
||||
HeartbeatTickOptions {
|
||||
target_heartbeat_rate: 1.0,
|
||||
coordinator_action: None,
|
||||
target_role: None,
|
||||
urgency: 0.0,
|
||||
schedule_id: schedule_id.into(),
|
||||
source_scene_ref: source_scene_ref.into(),
|
||||
defer_completion: true,
|
||||
agent_store,
|
||||
resident_self_store: Some(resident_store.to_path_buf()),
|
||||
},
|
||||
)?;
|
||||
let grant = crate::pending_resident_self_grant(resident_store)?
|
||||
.ok_or_else(|| anyhow!("heartbeat selected resident Self pressure but emitted no grant"))?;
|
||||
Ok(ResidentSelfHeartbeatPulse {
|
||||
status: "granted".into(),
|
||||
acknowledged_terminal_id,
|
||||
grant_id: Some(grant.grant_id),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn pump_heartbeat_store(
|
||||
store_path: impl AsRef<Path>,
|
||||
artifact_dir: impl AsRef<Path>,
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ mod proposal;
|
|||
mod repo_model_gateway;
|
||||
mod repository_body_observer;
|
||||
mod repository_readiness;
|
||||
mod resident_readiness;
|
||||
mod resident_self;
|
||||
mod runtime_spine;
|
||||
mod semantic_backend;
|
||||
|
|
@ -646,6 +647,7 @@ pub use heartbeat_state::HeartbeatQueueMentionOptions;
|
|||
pub use heartbeat_state::HeartbeatSelectionPolicy;
|
||||
pub use heartbeat_state::HeartbeatStaleTurnRepairOptions;
|
||||
pub use heartbeat_state::HeartbeatTickOptions;
|
||||
pub use heartbeat_state::ResidentSelfHeartbeatPulse;
|
||||
pub use heartbeat_state::VoidRoutineOptions;
|
||||
pub use heartbeat_state::complete_heartbeat_store;
|
||||
pub use heartbeat_state::default_heartbeat_state;
|
||||
|
|
@ -657,8 +659,10 @@ pub use heartbeat_state::initialize_heartbeat_store;
|
|||
pub use heartbeat_state::load_heartbeat_cognition_entry;
|
||||
pub use heartbeat_state::load_heartbeat_state_entry;
|
||||
pub use heartbeat_state::load_latest_heartbeat_stale_turn_repair_receipt;
|
||||
pub use heartbeat_state::pulse_resident_self_heartbeat;
|
||||
pub use heartbeat_state::pump_heartbeat_store;
|
||||
pub use heartbeat_state::queue_heartbeat_pending_mention_store;
|
||||
pub use heartbeat_state::reconcile_resident_self_heartbeat_ack;
|
||||
pub use heartbeat_state::recover_stale_heartbeat_store;
|
||||
pub use heartbeat_state::run_void_routine_store;
|
||||
pub use heartbeat_state::tick_heartbeat_store;
|
||||
|
|
@ -867,6 +871,7 @@ pub use proposal::propose_map_update;
|
|||
pub use repo_model_gateway::*;
|
||||
pub use repository_body_observer::*;
|
||||
pub use repository_readiness::*;
|
||||
pub use resident_readiness::*;
|
||||
pub use resident_self::*;
|
||||
pub use runtime_spine::COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION;
|
||||
pub use runtime_spine::COORDINATOR_RUN_RECEIPT_TYPE;
|
||||
|
|
|
|||
|
|
@ -95,6 +95,7 @@ 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")),
|
||||
("heartbeat", file_name("epiphany-heartbeat-store")),
|
||||
("coordinator", file_name("epiphany-mvp-coordinator")),
|
||||
("model-runtime", file_name("epiphany-model-runtime")),
|
||||
(
|
||||
|
|
@ -339,6 +340,7 @@ 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")),
|
||||
"heartbeat" => Ok(("epiphany-core", "epiphany-heartbeat-store")),
|
||||
"coordinator" => Ok(("epiphany-core", "epiphany-mvp-coordinator")),
|
||||
"model-runtime" => Ok(("epiphany-openai-runtime", "epiphany-model-runtime")),
|
||||
"tool-codex-mcp-spine" => Ok((
|
||||
|
|
@ -741,6 +743,7 @@ mod tests {
|
|||
.collect::<BTreeSet<_>>();
|
||||
for role in [
|
||||
"swarm",
|
||||
"heartbeat",
|
||||
"coordinator",
|
||||
"model-runtime",
|
||||
"tool-codex-mcp-spine",
|
||||
|
|
@ -751,6 +754,10 @@ mod tests {
|
|||
required_release_build_target("swarm").unwrap(),
|
||||
("epiphany-core", "epiphany-swarm")
|
||||
);
|
||||
assert_eq!(
|
||||
required_release_build_target("heartbeat").unwrap(),
|
||||
("epiphany-core", "epiphany-heartbeat-store")
|
||||
);
|
||||
assert_eq!(
|
||||
required_release_build_target("coordinator").unwrap(),
|
||||
("epiphany-core", "epiphany-mvp-coordinator")
|
||||
|
|
|
|||
777
epiphany-core/src/resident_readiness.rs
Normal file
777
epiphany-core/src/resident_readiness.rs
Normal file
|
|
@ -0,0 +1,777 @@
|
|||
use crate::{
|
||||
ProcessInstanceIdentity, ProcessInstanceObservation, ResidentSelfPolicy,
|
||||
authenticate_epiphany_packaged_release, epiphany_packaged_release_binary_path,
|
||||
load_epiphany_cultmesh_swarm_brake, load_heartbeat_state_entry, load_resident_self_state,
|
||||
observe_process_instance, validate_resident_self_store_separation,
|
||||
};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use serde::Serialize;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const RESIDENT_PROVIDER_READINESS_SCHEMA_VERSION: &str =
|
||||
"epiphany.resident_cognition.provider_readiness.v0";
|
||||
const PROVIDER_READINESS_KEY: &str = "provider-readiness";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.resident_cognition.provider_readiness",
|
||||
schema = "ResidentProviderReadiness"
|
||||
)]
|
||||
pub struct ResidentProviderReadiness {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_version: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub provider: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub runtime_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub release_id: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub release_witness_sha256: String,
|
||||
#[cultcache(key = 5)]
|
||||
pub source_commit: String,
|
||||
#[cultcache(key = 6)]
|
||||
pub publisher_sequence: u64,
|
||||
#[cultcache(key = 7)]
|
||||
pub observed_at_millis: u64,
|
||||
#[cultcache(key = 8)]
|
||||
pub process_id: u32,
|
||||
#[cultcache(key = 9)]
|
||||
pub process_creation_token: u64,
|
||||
#[cultcache(key = 10)]
|
||||
pub process_executable_path: String,
|
||||
#[cultcache(key = 11)]
|
||||
pub status: String,
|
||||
#[cultcache(key = 12, default)]
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
impl ResidentProviderReadiness {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if self.schema_version != RESIDENT_PROVIDER_READINESS_SCHEMA_VERSION {
|
||||
bail!("resident provider readiness schema is unsupported");
|
||||
}
|
||||
if !matches!(self.provider.as_str(), "heartbeat" | "resident-self") {
|
||||
bail!("resident provider readiness owner is invalid");
|
||||
}
|
||||
if self.runtime_id.trim().is_empty()
|
||||
|| self.release_id.trim().is_empty()
|
||||
|| self.source_commit.trim().is_empty()
|
||||
|| self.process_executable_path.trim().is_empty()
|
||||
|| self.process_id == 0
|
||||
|| self.process_creation_token == 0
|
||||
{
|
||||
bail!("resident provider readiness lacks exact provider or release identity");
|
||||
}
|
||||
if !self.release_witness_sha256.starts_with("sha256-")
|
||||
|| self.release_witness_sha256.len() != 71
|
||||
{
|
||||
bail!("resident provider readiness release witness is invalid");
|
||||
}
|
||||
if !matches!(self.status.as_str(), "ready" | "warming" | "degraded") {
|
||||
bail!("resident provider readiness status is invalid");
|
||||
}
|
||||
if self.private_state_exposed {
|
||||
bail!("resident provider readiness exposed private state");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn cache(path: &Path) -> Result<CultCache> {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<ResidentProviderReadiness>()?;
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path));
|
||||
cache.pull_all_backing_stores()?;
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
pub fn publish_resident_provider_readiness(
|
||||
store: &Path,
|
||||
mut readiness: ResidentProviderReadiness,
|
||||
) -> Result<ResidentProviderReadiness> {
|
||||
readiness.validate()?;
|
||||
let cache = cache(store)?;
|
||||
let expected = cache.snapshot_envelopes().into_iter().find(|entry| {
|
||||
entry.r#type == <ResidentProviderReadiness as DatabaseEntry>::TYPE
|
||||
&& entry.key == PROVIDER_READINESS_KEY
|
||||
});
|
||||
let previous = cache.get::<ResidentProviderReadiness>(PROVIDER_READINESS_KEY)?;
|
||||
readiness.publisher_sequence = previous
|
||||
.as_ref()
|
||||
.map_or(1, |value| value.publisher_sequence.saturating_add(1));
|
||||
if let Some(previous) = previous {
|
||||
if previous.provider != readiness.provider {
|
||||
bail!("resident provider readiness store has another owner");
|
||||
}
|
||||
if readiness.observed_at_millis < previous.observed_at_millis {
|
||||
bail!("resident provider readiness time moved backwards");
|
||||
}
|
||||
}
|
||||
let (replacement, _) = cache.prepare_entry(PROVIDER_READINESS_KEY, &readiness)?;
|
||||
let backing = SingleFileMessagePackBackingStore::new(store);
|
||||
let committed = match expected {
|
||||
Some(expected) => backing.compare_and_swap_entry(&expected, replacement)?,
|
||||
None => backing.insert_entry_if_absent(replacement)?,
|
||||
};
|
||||
if !committed {
|
||||
return Err(anyhow!("resident provider readiness lost exact CAS"));
|
||||
}
|
||||
Ok(readiness)
|
||||
}
|
||||
|
||||
pub fn load_resident_provider_readiness(store: &Path) -> Result<Option<ResidentProviderReadiness>> {
|
||||
let value = cache(store)?.get::<ResidentProviderReadiness>(PROVIDER_READINESS_KEY)?;
|
||||
if let Some(value) = value.as_ref() {
|
||||
value.validate()?;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub fn heartbeat_local_provider_status(
|
||||
heartbeat_store: &Path,
|
||||
resident_store: &Path,
|
||||
) -> &'static str {
|
||||
if distinct_physical_paths(heartbeat_store, resident_store)
|
||||
&& load_heartbeat_state_entry(heartbeat_store)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some()
|
||||
{
|
||||
"ready"
|
||||
} else {
|
||||
"warming"
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resident_self_local_provider_status(
|
||||
resident_store: &Path,
|
||||
policy: &ResidentSelfPolicy,
|
||||
) -> &'static str {
|
||||
if validate_resident_self_store_separation(resident_store, policy).is_err()
|
||||
|| !directory_ready(&policy.workspace)
|
||||
|| !codex_credentials_ready(&policy.codex_home)
|
||||
{
|
||||
return "warming";
|
||||
}
|
||||
let Ok(state) = load_resident_self_state(resident_store) else {
|
||||
return "degraded";
|
||||
};
|
||||
let Some(lease) = state.active_turn else {
|
||||
return "ready";
|
||||
};
|
||||
let identity = ProcessInstanceIdentity {
|
||||
process_id: lease.process_id,
|
||||
creation_token: lease.process_creation_token,
|
||||
created_at_rfc3339: None,
|
||||
executable_path: lease.process_executable_path,
|
||||
};
|
||||
if observe_process_instance(&identity) == ProcessInstanceObservation::ExactAlive {
|
||||
"ready"
|
||||
} else {
|
||||
"degraded"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ResidentReadinessRequest<'a> {
|
||||
pub release_store: &'a Path,
|
||||
pub heartbeat_store: &'a Path,
|
||||
pub resident_store: &'a Path,
|
||||
pub policy: &'a ResidentSelfPolicy,
|
||||
pub release_runtime_id: &'a str,
|
||||
pub release_id: &'a str,
|
||||
pub release_witness_sha256: &'a str,
|
||||
pub now_millis: u64,
|
||||
pub freshness_millis: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResidentCognitionReadinessProjection {
|
||||
pub schema_version: String,
|
||||
pub status: String,
|
||||
pub runtime_id: Option<String>,
|
||||
pub release_id: Option<String>,
|
||||
pub release_witness_sha256: Option<String>,
|
||||
pub source_commit: Option<String>,
|
||||
pub release_authenticated: bool,
|
||||
pub physical_stores_separate: bool,
|
||||
pub heartbeat_initialized: bool,
|
||||
pub heartbeat_provider_fresh: bool,
|
||||
pub resident_provider_fresh: bool,
|
||||
pub resident_state_coherent: bool,
|
||||
pub active_lease_observation: String,
|
||||
pub brake_engaged: bool,
|
||||
pub workspace_ready: bool,
|
||||
pub credential_ready: bool,
|
||||
pub reasons: Vec<String>,
|
||||
pub private_state_exposed: bool,
|
||||
}
|
||||
|
||||
pub fn derive_resident_cognition_readiness(
|
||||
request: ResidentReadinessRequest<'_>,
|
||||
) -> ResidentCognitionReadinessProjection {
|
||||
let mut reasons = Vec::new();
|
||||
let release = authenticate_epiphany_packaged_release(
|
||||
request.release_store,
|
||||
request.release_runtime_id,
|
||||
request.release_id,
|
||||
request.release_witness_sha256,
|
||||
);
|
||||
let release_authenticated = release.is_ok();
|
||||
let expected_source_commit = release
|
||||
.as_ref()
|
||||
.ok()
|
||||
.map(|value| value.source_commit_sha.as_str());
|
||||
let heartbeat_executable = release
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|value| epiphany_packaged_release_binary_path(value, "heartbeat").ok());
|
||||
let resident_executable = release
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|value| epiphany_packaged_release_binary_path(value, "swarm").ok());
|
||||
if let Err(error) = release.as_ref() {
|
||||
reasons.push(format!("packaged release authentication failed: {error:#}"));
|
||||
}
|
||||
let physical_stores_separate =
|
||||
validate_resident_self_store_separation(request.resident_store, request.policy).is_ok()
|
||||
&& distinct_physical_paths(request.heartbeat_store, request.resident_store);
|
||||
if !physical_stores_separate {
|
||||
reasons.push("resident cognition stores are not physically separated".into());
|
||||
}
|
||||
let heartbeat_initialized = load_heartbeat_state_entry(request.heartbeat_store)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some();
|
||||
if !heartbeat_initialized {
|
||||
reasons.push("heartbeat state is absent or unreadable".into());
|
||||
}
|
||||
let heartbeat_provider_fresh = provider_is_fresh(
|
||||
request.heartbeat_store,
|
||||
"heartbeat",
|
||||
&request,
|
||||
expected_source_commit,
|
||||
heartbeat_executable.as_deref(),
|
||||
&mut reasons,
|
||||
);
|
||||
let resident_provider_fresh = provider_is_fresh(
|
||||
request.resident_store,
|
||||
"resident-self",
|
||||
&request,
|
||||
expected_source_commit,
|
||||
resident_executable.as_deref(),
|
||||
&mut reasons,
|
||||
);
|
||||
let (resident_state_coherent, active_lease_observation) =
|
||||
match load_resident_self_state(request.resident_store) {
|
||||
Ok(state) => match state.active_turn.as_ref() {
|
||||
None if state.prepared_launch.is_none() => (true, "none".into()),
|
||||
None => (true, "prepared-fail-closed".into()),
|
||||
Some(lease) => {
|
||||
let identity = ProcessInstanceIdentity {
|
||||
process_id: lease.process_id,
|
||||
creation_token: lease.process_creation_token,
|
||||
created_at_rfc3339: None,
|
||||
executable_path: lease.process_executable_path.clone(),
|
||||
};
|
||||
classify_active_lease_observation(
|
||||
observe_process_instance(&identity),
|
||||
&mut reasons,
|
||||
)
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
reasons.push(format!("resident state is incoherent: {error:#}"));
|
||||
(false, "unreadable".into())
|
||||
}
|
||||
};
|
||||
let brake_engaged = load_epiphany_cultmesh_swarm_brake(
|
||||
&request.policy.local_verse_store,
|
||||
&request.policy.release_runtime_id,
|
||||
)
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some_and(|brake| brake.status == "engaged");
|
||||
let workspace_ready = directory_ready(&request.policy.workspace);
|
||||
if !workspace_ready {
|
||||
reasons.push("workspace is absent, inaccessible, or read-only".into());
|
||||
}
|
||||
let credential_ready = codex_credentials_ready(&request.policy.codex_home);
|
||||
if !credential_ready {
|
||||
reasons.push("Codex credential material is unavailable".into());
|
||||
}
|
||||
let ready = release_authenticated
|
||||
&& physical_stores_separate
|
||||
&& heartbeat_initialized
|
||||
&& heartbeat_provider_fresh
|
||||
&& resident_provider_fresh
|
||||
&& resident_state_coherent
|
||||
&& workspace_ready
|
||||
&& credential_ready;
|
||||
ResidentCognitionReadinessProjection {
|
||||
schema_version: "epiphany.resident_cognition.readiness.v0".into(),
|
||||
status: if ready {
|
||||
"active"
|
||||
} else if release_authenticated {
|
||||
"warming"
|
||||
} else {
|
||||
"degraded"
|
||||
}
|
||||
.into(),
|
||||
runtime_id: release.as_ref().ok().map(|value| value.runtime_id.clone()),
|
||||
release_id: release.as_ref().ok().map(|value| value.release_id.clone()),
|
||||
release_witness_sha256: release
|
||||
.as_ref()
|
||||
.ok()
|
||||
.map(|_| request.release_witness_sha256.to_string()),
|
||||
source_commit: release
|
||||
.as_ref()
|
||||
.ok()
|
||||
.map(|value| value.source_commit_sha.clone()),
|
||||
release_authenticated,
|
||||
physical_stores_separate,
|
||||
heartbeat_initialized,
|
||||
heartbeat_provider_fresh,
|
||||
resident_provider_fresh,
|
||||
resident_state_coherent,
|
||||
active_lease_observation,
|
||||
brake_engaged,
|
||||
workspace_ready,
|
||||
credential_ready,
|
||||
reasons,
|
||||
private_state_exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_active_lease_observation(
|
||||
observation: ProcessInstanceObservation,
|
||||
reasons: &mut Vec<String>,
|
||||
) -> (bool, String) {
|
||||
match observation {
|
||||
ProcessInstanceObservation::ExactAlive => (true, "exact-alive".into()),
|
||||
ProcessInstanceObservation::ExactExited { .. } => {
|
||||
reasons.push("active resident lease names an exited process".into());
|
||||
(false, "exact-exited".into())
|
||||
}
|
||||
ProcessInstanceObservation::Missing => {
|
||||
reasons.push("active resident lease process is missing".into());
|
||||
(false, "missing".into())
|
||||
}
|
||||
ProcessInstanceObservation::Replaced { .. } => {
|
||||
reasons.push("active resident lease PID was reused".into());
|
||||
(false, "replaced".into())
|
||||
}
|
||||
ProcessInstanceObservation::Inaccessible => {
|
||||
reasons.push("active resident lease cannot be authenticated".into());
|
||||
(false, "inaccessible".into())
|
||||
}
|
||||
ProcessInstanceObservation::Indeterminate { .. } => {
|
||||
reasons.push("active resident lease observation is indeterminate".into());
|
||||
(false, "indeterminate".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResidentProviderPairHealth {
|
||||
pub terminal_current: usize,
|
||||
pub warming: usize,
|
||||
pub contradictions: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn authenticate_resident_provider_pair(
|
||||
release: &crate::EpiphanyPackagedReleaseEntry,
|
||||
witness: &str,
|
||||
heartbeat_store: &Path,
|
||||
resident_store: &Path,
|
||||
now_millis: u64,
|
||||
freshness_millis: u64,
|
||||
) -> ResidentProviderPairHealth {
|
||||
let mut result = ResidentProviderPairHealth {
|
||||
terminal_current: 0,
|
||||
warming: 0,
|
||||
contradictions: Vec::new(),
|
||||
};
|
||||
if !distinct_physical_paths(heartbeat_store, resident_store) {
|
||||
result
|
||||
.contradictions
|
||||
.push("heartbeat and resident Self provider stores alias physically".into());
|
||||
return result;
|
||||
}
|
||||
for (owner, store, role) in [
|
||||
("heartbeat", heartbeat_store, "heartbeat"),
|
||||
("resident-self", resident_store, "swarm"),
|
||||
] {
|
||||
let executable = epiphany_packaged_release_binary_path(release, role).ok();
|
||||
let value = match load_resident_provider_readiness(store) {
|
||||
Ok(Some(value)) => value,
|
||||
Ok(None) => {
|
||||
result.warming += 1;
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
result
|
||||
.contradictions
|
||||
.push(format!("{owner} provider readiness is invalid: {error:#}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let exact_process = observe_process_instance(&ProcessInstanceIdentity {
|
||||
process_id: value.process_id,
|
||||
creation_token: value.process_creation_token,
|
||||
created_at_rfc3339: None,
|
||||
executable_path: PathBuf::from(&value.process_executable_path),
|
||||
}) == ProcessInstanceObservation::ExactAlive;
|
||||
if provider_matches_authority(
|
||||
&value,
|
||||
owner,
|
||||
&release.runtime_id,
|
||||
&release.release_id,
|
||||
witness,
|
||||
Some(&release.source_commit_sha),
|
||||
executable.as_deref(),
|
||||
now_millis,
|
||||
freshness_millis,
|
||||
exact_process,
|
||||
) {
|
||||
result.terminal_current += 1;
|
||||
} else if value.runtime_id == release.runtime_id && value.release_id == release.release_id {
|
||||
result.warming += 1;
|
||||
} else {
|
||||
result
|
||||
.contradictions
|
||||
.push(format!("{owner} provider readiness names another release"));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn provider_is_fresh(
|
||||
store: &Path,
|
||||
owner: &str,
|
||||
request: &ResidentReadinessRequest<'_>,
|
||||
expected_source_commit: Option<&str>,
|
||||
expected_executable: Option<&Path>,
|
||||
reasons: &mut Vec<String>,
|
||||
) -> bool {
|
||||
let value = match load_resident_provider_readiness(store) {
|
||||
Ok(Some(value)) => value,
|
||||
Ok(None) => {
|
||||
reasons.push(format!("{owner} provider readiness is absent"));
|
||||
return false;
|
||||
}
|
||||
Err(error) => {
|
||||
reasons.push(format!("{owner} provider readiness is invalid: {error:#}"));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let exact_process = observe_process_instance(&ProcessInstanceIdentity {
|
||||
process_id: value.process_id,
|
||||
creation_token: value.process_creation_token,
|
||||
created_at_rfc3339: None,
|
||||
executable_path: PathBuf::from(&value.process_executable_path),
|
||||
}) == ProcessInstanceObservation::ExactAlive;
|
||||
let ready = provider_matches_authority(
|
||||
&value,
|
||||
owner,
|
||||
request.release_runtime_id,
|
||||
request.release_id,
|
||||
request.release_witness_sha256,
|
||||
expected_source_commit,
|
||||
expected_executable,
|
||||
request.now_millis,
|
||||
request.freshness_millis,
|
||||
exact_process,
|
||||
);
|
||||
if !ready {
|
||||
reasons.push(format!(
|
||||
"{owner} provider readiness is stale or release-substituted"
|
||||
));
|
||||
}
|
||||
ready
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn provider_matches_authority(
|
||||
value: &ResidentProviderReadiness,
|
||||
owner: &str,
|
||||
runtime_id: &str,
|
||||
release_id: &str,
|
||||
witness: &str,
|
||||
source_commit: Option<&str>,
|
||||
executable: Option<&Path>,
|
||||
now_millis: u64,
|
||||
freshness_millis: u64,
|
||||
exact_process_alive: bool,
|
||||
) -> bool {
|
||||
value.provider == owner
|
||||
&& value.runtime_id == runtime_id
|
||||
&& value.release_id == release_id
|
||||
&& value.release_witness_sha256 == witness
|
||||
&& source_commit.is_some_and(|commit| commit == value.source_commit)
|
||||
&& executable.is_some_and(|path| {
|
||||
canonical_or_absolute(path)
|
||||
== canonical_or_absolute(Path::new(&value.process_executable_path))
|
||||
})
|
||||
&& value.status == "ready"
|
||||
&& exact_process_alive
|
||||
&& now_millis >= value.observed_at_millis
|
||||
&& now_millis.saturating_sub(value.observed_at_millis) <= freshness_millis
|
||||
}
|
||||
|
||||
fn distinct_physical_paths(left: &Path, right: &Path) -> bool {
|
||||
canonical_or_absolute(left) != canonical_or_absolute(right)
|
||||
&& matches!(crate::same_existing_file(left, right), Ok(false))
|
||||
}
|
||||
|
||||
fn canonical_or_absolute(path: &Path) -> PathBuf {
|
||||
fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
fn directory_ready(path: &Path) -> bool {
|
||||
fs::metadata(path).is_ok_and(|value| value.is_dir() && !value.permissions().readonly())
|
||||
}
|
||||
|
||||
fn codex_credentials_ready(codex_home: &Path) -> bool {
|
||||
directory_ready(codex_home)
|
||||
&& ["auth.json", "credentials.json"]
|
||||
.iter()
|
||||
.any(|name| credential_file_ready(&codex_home.join(name)))
|
||||
}
|
||||
|
||||
fn credential_file_ready(path: &Path) -> bool {
|
||||
let Ok(metadata) = fs::metadata(path) else {
|
||||
return false;
|
||||
};
|
||||
if !metadata.is_file() {
|
||||
return false;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
return metadata.uid() == unsafe { libc::geteuid() } && metadata.mode() & 0o077 == 0;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn provider() -> ResidentProviderReadiness {
|
||||
ResidentProviderReadiness {
|
||||
schema_version: RESIDENT_PROVIDER_READINESS_SCHEMA_VERSION.into(),
|
||||
provider: "heartbeat".into(),
|
||||
runtime_id: "ygg".into(),
|
||||
release_id: "release-a".into(),
|
||||
release_witness_sha256: format!("sha256-{}", "a".repeat(64)),
|
||||
source_commit: "commit-a".into(),
|
||||
publisher_sequence: 1,
|
||||
observed_at_millis: 1_000,
|
||||
process_id: 4,
|
||||
process_creation_token: 5,
|
||||
process_executable_path: std::env::current_exe().unwrap().display().to_string(),
|
||||
status: "ready".into(),
|
||||
private_state_exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_wrong_release_and_nonexact_process_cannot_be_ready() {
|
||||
let value = provider();
|
||||
let executable = std::env::current_exe().unwrap();
|
||||
assert!(provider_matches_authority(
|
||||
&value,
|
||||
"heartbeat",
|
||||
"ygg",
|
||||
"release-a",
|
||||
&value.release_witness_sha256,
|
||||
Some("commit-a"),
|
||||
Some(&executable),
|
||||
1_050,
|
||||
100,
|
||||
true
|
||||
));
|
||||
assert!(!provider_matches_authority(
|
||||
&value,
|
||||
"heartbeat",
|
||||
"ygg",
|
||||
"release-b",
|
||||
&value.release_witness_sha256,
|
||||
Some("commit-a"),
|
||||
Some(&executable),
|
||||
1_050,
|
||||
100,
|
||||
true
|
||||
));
|
||||
assert!(!provider_matches_authority(
|
||||
&value,
|
||||
"heartbeat",
|
||||
"ygg",
|
||||
"release-a",
|
||||
&value.release_witness_sha256,
|
||||
Some("commit-a"),
|
||||
Some(&executable),
|
||||
1_101,
|
||||
100,
|
||||
true
|
||||
));
|
||||
assert!(!provider_matches_authority(
|
||||
&value,
|
||||
"heartbeat",
|
||||
"ygg",
|
||||
"release-a",
|
||||
&value.release_witness_sha256,
|
||||
Some("commit-a"),
|
||||
Some(&executable),
|
||||
1_050,
|
||||
100,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_provider_is_absent_and_private_state_is_rejected() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
assert!(load_resident_provider_readiness(&temp.path().join("missing.cc"))?.is_none());
|
||||
let mut value = provider();
|
||||
value.private_state_exposed = true;
|
||||
assert!(
|
||||
value
|
||||
.validate()
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("private state")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hardlink_store_aliases_are_not_physically_distinct() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let first = temp.path().join("first.cc");
|
||||
let alias = temp.path().join("alias.cc");
|
||||
fs::write(&first, b"cultcache")?;
|
||||
fs::hard_link(&first, &alias)?;
|
||||
assert!(!distinct_physical_paths(&first, &alias));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn unix_credentials_reject_group_or_other_access() -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let temp = tempfile::tempdir()?;
|
||||
let auth = temp.path().join("auth.json");
|
||||
fs::write(&auth, b"{}")?;
|
||||
fs::set_permissions(&auth, fs::Permissions::from_mode(0o644))?;
|
||||
assert!(!codex_credentials_ready(temp.path()));
|
||||
fs::set_permissions(&auth, fs::Permissions::from_mode(0o600))?;
|
||||
assert!(codex_credentials_ready(temp.path()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_schema_has_no_systemd_or_secret_substitution_surface() {
|
||||
let projection = ResidentCognitionReadinessProjection {
|
||||
schema_version: "epiphany.resident_cognition.readiness.v0".into(),
|
||||
status: "warming".into(),
|
||||
runtime_id: Some("epiphany-yggdrasil".into()),
|
||||
release_id: Some("release-1".into()),
|
||||
release_witness_sha256: Some("sha256:witness".into()),
|
||||
source_commit: Some("commit-1".into()),
|
||||
release_authenticated: true,
|
||||
physical_stores_separate: true,
|
||||
heartbeat_initialized: true,
|
||||
heartbeat_provider_fresh: false,
|
||||
resident_provider_fresh: false,
|
||||
resident_state_coherent: true,
|
||||
active_lease_observation: "none".into(),
|
||||
brake_engaged: true,
|
||||
workspace_ready: true,
|
||||
credential_ready: true,
|
||||
reasons: vec!["provider absent".into()],
|
||||
private_state_exposed: false,
|
||||
};
|
||||
let json = serde_json::to_string(&projection).unwrap();
|
||||
assert!(!json.contains("systemd"));
|
||||
assert!(!json.contains("credentialPath"));
|
||||
assert!(!json.contains("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incoherent_or_reused_active_lease_is_not_ready() {
|
||||
let mut reasons = Vec::new();
|
||||
let (coherent, status) = classify_active_lease_observation(
|
||||
ProcessInstanceObservation::Replaced {
|
||||
observed: ProcessInstanceIdentity {
|
||||
process_id: 99,
|
||||
creation_token: 100,
|
||||
created_at_rfc3339: None,
|
||||
executable_path: PathBuf::from("alien"),
|
||||
},
|
||||
},
|
||||
&mut reasons,
|
||||
);
|
||||
assert!(!coherent);
|
||||
assert_eq!(status, "replaced");
|
||||
assert!(reasons[0].contains("PID was reused"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_pair_warms_on_missing_and_rejects_wrong_release() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let heartbeat = temp.path().join("heartbeat.cc");
|
||||
let resident = temp.path().join("resident.cc");
|
||||
let executable = std::env::current_exe()?;
|
||||
let binary = |role: &str| crate::EpiphanyPackagedReleaseBinary {
|
||||
role: role.into(),
|
||||
file_name: executable.file_name().unwrap().to_string_lossy().into(),
|
||||
canonical_path: executable.display().to_string(),
|
||||
sha256: format!("sha256-{}", "b".repeat(64)),
|
||||
byte_len: 1,
|
||||
};
|
||||
let release = crate::EpiphanyPackagedReleaseEntry {
|
||||
schema_version: crate::EPIPHANY_PACKAGED_RELEASE_SCHEMA_VERSION.into(),
|
||||
release_id: "release-a".into(),
|
||||
runtime_id: "ygg".into(),
|
||||
source_commit_sha: "commit-a".into(),
|
||||
target_triple: "test".into(),
|
||||
cargo_profile: "release".into(),
|
||||
toolchain_fingerprint: "toolchain".into(),
|
||||
created_at_utc: "now".into(),
|
||||
package_root: temp.path().display().to_string(),
|
||||
binaries: vec![binary("heartbeat"), binary("swarm")],
|
||||
private_state_exposed: false,
|
||||
};
|
||||
let witness = format!("sha256-{}", "a".repeat(64));
|
||||
let missing =
|
||||
authenticate_resident_provider_pair(&release, &witness, &heartbeat, &resident, 10, 10);
|
||||
assert_eq!(missing.warming, 2);
|
||||
let process = crate::capture_process_instance(std::process::id())?;
|
||||
let mut wrong = provider();
|
||||
wrong.runtime_id = "ygg".into();
|
||||
wrong.release_id = "other-release".into();
|
||||
wrong.release_witness_sha256 = witness.clone();
|
||||
wrong.source_commit = "commit-a".into();
|
||||
wrong.observed_at_millis = 10;
|
||||
wrong.process_id = process.process_id;
|
||||
wrong.process_creation_token = process.creation_token;
|
||||
wrong.process_executable_path = process.executable_path.display().to_string();
|
||||
publish_resident_provider_readiness(&heartbeat, wrong)?;
|
||||
let rejected =
|
||||
authenticate_resident_provider_pair(&release, &witness, &heartbeat, &resident, 10, 10);
|
||||
assert!(
|
||||
rejected
|
||||
.contradictions
|
||||
.iter()
|
||||
.any(|reason| reason.contains("another release"))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -286,7 +286,7 @@ fn canonical_store_path(path: &Path) -> Result<PathBuf> {
|
|||
))
|
||||
}
|
||||
|
||||
fn same_existing_file(left: &Path, right: &Path) -> Result<bool> {
|
||||
pub fn same_existing_file(left: &Path, right: &Path) -> Result<bool> {
|
||||
if !left.exists() || !right.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
|
@ -495,6 +495,8 @@ pub fn coordinator_argv(
|
|||
policy.tool_adapter_bin.display().to_string(),
|
||||
"--model-provider".into(),
|
||||
policy.model_provider.clone(),
|
||||
"--runtime-id".into(),
|
||||
policy.release_runtime_id.clone(),
|
||||
"--thread-id".into(),
|
||||
turn_id.into(),
|
||||
"--cwd".into(),
|
||||
|
|
@ -1328,6 +1330,14 @@ pub fn pending_resident_self_ack_for(
|
|||
}))
|
||||
}
|
||||
|
||||
pub fn pending_resident_self_acks(path: &Path) -> Result<Vec<ResidentSelfTerminalAck>> {
|
||||
Ok(state_cache(path)?
|
||||
.get_all::<ResidentSelfTerminalAck>()?
|
||||
.into_iter()
|
||||
.filter(|ack| ack.consumed_by_heartbeat_at_millis.is_none())
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn heartbeat_consume_resident_self_ack(
|
||||
path: &Path,
|
||||
ack_id: &str,
|
||||
|
|
@ -1679,21 +1689,20 @@ mod tests {
|
|||
private_state_exposed: false,
|
||||
};
|
||||
state_cache(&resident_store)?.put(&ack.ack_id, &ack)?;
|
||||
crate::tick_heartbeat_store(
|
||||
let ack_pulse = crate::pulse_resident_self_heartbeat(
|
||||
&heartbeat_store,
|
||||
&resident_store,
|
||||
&artifacts,
|
||||
crate::HeartbeatTickOptions {
|
||||
target_heartbeat_rate: 1.0,
|
||||
coordinator_action: None,
|
||||
target_role: None,
|
||||
urgency: 0.0,
|
||||
schedule_id: "heartbeat-after-ack".into(),
|
||||
source_scene_ref: "test/resident-self".into(),
|
||||
defer_completion: false,
|
||||
agent_store: None,
|
||||
resident_self_store: Some(resident_store.clone()),
|
||||
},
|
||||
true,
|
||||
"heartbeat-after-ack",
|
||||
"test/resident-self",
|
||||
None,
|
||||
)?;
|
||||
assert_eq!(ack_pulse.status, "braked-after-ack-reconciliation");
|
||||
assert_eq!(
|
||||
ack_pulse.acknowledged_terminal_id.as_deref(),
|
||||
Some(ack.ack_id.as_str())
|
||||
);
|
||||
let heartbeat = crate::load_heartbeat_state_entry(&heartbeat_store)?.expect("heartbeat");
|
||||
assert!(
|
||||
heartbeat
|
||||
|
|
@ -1707,6 +1716,143 @@ mod tests {
|
|||
.get::<ResidentSelfTerminalAck>(&ack.ack_id)?
|
||||
.is_some_and(|ack| ack.consumed_by_heartbeat_at_millis.is_some())
|
||||
);
|
||||
let mut crash_gap_ack = ack.clone();
|
||||
crash_gap_ack.consumed_by_heartbeat_at_millis = None;
|
||||
state_cache(&resident_store)?.put(&crash_gap_ack.ack_id, &crash_gap_ack)?;
|
||||
assert_eq!(
|
||||
crate::reconcile_resident_self_heartbeat_ack(&heartbeat_store, &resident_store)?,
|
||||
Some(crash_gap_ack.ack_id.clone())
|
||||
);
|
||||
assert!(
|
||||
state_cache(&resident_store)?
|
||||
.get::<ResidentSelfTerminalAck>(&crash_gap_ack.ack_id)?
|
||||
.is_some_and(|ack| ack.consumed_by_heartbeat_at_millis.is_some())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heartbeat_daemon_retains_pressure_under_brake_then_grants_once() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let heartbeat = temp.path().join("heartbeat.cc");
|
||||
let resident = temp.path().join("resident.cc");
|
||||
crate::initialize_heartbeat_store(&heartbeat, 1.0)?;
|
||||
enqueue_resident_self_pressure(
|
||||
&resident,
|
||||
&ResidentSelfPressure {
|
||||
schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(),
|
||||
pressure_id: "body-pressure-braked".into(),
|
||||
kind: "body-map-drift".into(),
|
||||
provenance_ref: "cultcache://repo-model/hash".into(),
|
||||
objective: "Inspect drift.".into(),
|
||||
created_at_millis: 1,
|
||||
status: "pending".into(),
|
||||
consumed_by_grant_id: None,
|
||||
private_state_exposed: false,
|
||||
},
|
||||
)?;
|
||||
let braked = crate::pulse_resident_self_heartbeat(
|
||||
&heartbeat,
|
||||
&resident,
|
||||
temp.path(),
|
||||
true,
|
||||
"pulse-1",
|
||||
"test",
|
||||
None,
|
||||
)?;
|
||||
assert_eq!(braked.status, "braked-after-ack-reconciliation");
|
||||
assert!(pending_resident_self_pressure(&resident)?);
|
||||
assert!(pending_resident_self_grant(&resident)?.is_none());
|
||||
let granted = crate::pulse_resident_self_heartbeat(
|
||||
&heartbeat,
|
||||
&resident,
|
||||
temp.path(),
|
||||
false,
|
||||
"pulse-2",
|
||||
"test",
|
||||
None,
|
||||
)?;
|
||||
assert_eq!(granted.status, "granted");
|
||||
let exact = pending_resident_self_grant(&resident)?
|
||||
.expect("one grant")
|
||||
.grant_id;
|
||||
let repeat = crate::pulse_resident_self_heartbeat(
|
||||
&heartbeat,
|
||||
&resident,
|
||||
temp.path(),
|
||||
false,
|
||||
"pulse-3",
|
||||
"test",
|
||||
None,
|
||||
)?;
|
||||
assert_eq!(repeat.status, "active-coordinator-turn");
|
||||
assert_eq!(
|
||||
pending_resident_self_grant(&resident)?
|
||||
.expect("same grant")
|
||||
.grant_id,
|
||||
exact
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heartbeat_restart_recovers_committed_turn_to_one_grant() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let heartbeat = temp.path().join("heartbeat.cc");
|
||||
let resident = temp.path().join("resident.cc");
|
||||
crate::initialize_heartbeat_store(&heartbeat, 1.0)?;
|
||||
let mut state = crate::load_heartbeat_state_entry(&heartbeat)?.expect("heartbeat");
|
||||
let coordinator = state
|
||||
.participants
|
||||
.iter_mut()
|
||||
.find(|participant| participant.role_id == "coordinator")
|
||||
.expect("coordinator");
|
||||
coordinator.pending_turn = Some(crate::HeartbeatPendingTurn {
|
||||
status: "running".into(),
|
||||
schedule_id: "committed-before-crash".into(),
|
||||
action_id: "self-action".into(),
|
||||
..Default::default()
|
||||
});
|
||||
crate::write_heartbeat_state_entry(&heartbeat, &state)?;
|
||||
enqueue_resident_self_pressure(
|
||||
&resident,
|
||||
&ResidentSelfPressure {
|
||||
schema_version: RESIDENT_SELF_PRESSURE_SCHEMA_VERSION.into(),
|
||||
pressure_id: "restart-pressure".into(),
|
||||
kind: "imagination-proposal".into(),
|
||||
provenance_ref: "cultmesh://imagination/1".into(),
|
||||
objective: "Review proposal.".into(),
|
||||
created_at_millis: 1,
|
||||
status: "pending".into(),
|
||||
consumed_by_grant_id: None,
|
||||
private_state_exposed: false,
|
||||
},
|
||||
)?;
|
||||
let recovered = crate::pulse_resident_self_heartbeat(
|
||||
&heartbeat,
|
||||
&resident,
|
||||
temp.path(),
|
||||
false,
|
||||
"new-pulse",
|
||||
"test",
|
||||
None,
|
||||
)?;
|
||||
assert_eq!(recovered.status, "recovered-committed-grant");
|
||||
let grant = pending_resident_self_grant(&resident)?.expect("recovered grant");
|
||||
assert_eq!(grant.heartbeat_schedule_id, "committed-before-crash");
|
||||
assert!(
|
||||
crate::pulse_resident_self_heartbeat(
|
||||
&heartbeat,
|
||||
&resident,
|
||||
temp.path(),
|
||||
false,
|
||||
"again",
|
||||
"test",
|
||||
None
|
||||
)?
|
||||
.grant_id
|
||||
.is_none()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Reference in a new issue