Awaken the Body coverage projector service
This commit is contained in:
parent
aa6b3efe4c
commit
3be68ea0d4
14 changed files with 2618 additions and 107 deletions
|
|
@ -45,6 +45,7 @@ use epiphany_core::write_epiphany_cultmesh_daemon_scheduler_receipt;
|
|||
use epiphany_core::write_epiphany_cultmesh_daemon_service_lifecycle_receipt;
|
||||
use epiphany_core::write_epiphany_cultmesh_managed_service_policy;
|
||||
use epiphany_core::write_epiphany_cultmesh_semantic_projector_service_policy;
|
||||
use epiphany_core::write_epiphany_cultmesh_workspace_coverage_projector_service_policy;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use sha2::Digest;
|
||||
|
|
@ -58,6 +59,9 @@ use uuid::Uuid;
|
|||
|
||||
const SEMANTIC_PROJECTOR_SERVICE_ID: &str = "epiphany-memory-semantic-projector-service";
|
||||
const SEMANTIC_PROJECTOR_EXECUTOR_ID: &str = "epiphany-memory-semantic-projector";
|
||||
const WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID: &str =
|
||||
"epiphany-workspace-coverage-projector-service";
|
||||
const WORKSPACE_COVERAGE_PROJECTOR_EXECUTOR_ID: &str = "epiphany-workspace-coverage-projector";
|
||||
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
|
@ -93,6 +97,9 @@ fn dispatch(args: Args) -> Result<()> {
|
|||
"service-launch" | "launch-service" | "start-service" => service_launch(args),
|
||||
"managed-service-policy" | "service-desired-state" => managed_service_policy(args),
|
||||
"semantic-projector-service-policy" => semantic_projector_service_policy(args),
|
||||
"workspace-coverage-projector-service-policy" => {
|
||||
workspace_coverage_projector_service_policy(args)
|
||||
}
|
||||
"managed-service-read" | "service-desired-state-read" => managed_service_read(args),
|
||||
"managed-service-reconcile" | "service-desired-state-reconcile" => {
|
||||
managed_service_reconcile(args)
|
||||
|
|
@ -787,39 +794,43 @@ fn service_launch(args: Args) -> Result<()> {
|
|||
let started_at = Utc::now();
|
||||
let command_path = service_command_path(&args)?;
|
||||
let service_args = service_serve_args(&args);
|
||||
let reserved_launch = if args.service_id == SEMANTIC_PROJECTOR_SERVICE_ID {
|
||||
let reserved_executor_id = match args.service_id.as_str() {
|
||||
SEMANTIC_PROJECTOR_SERVICE_ID => Some(SEMANTIC_PROJECTOR_EXECUTOR_ID),
|
||||
WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID => Some(WORKSPACE_COVERAGE_PROJECTOR_EXECUTOR_ID),
|
||||
_ => None,
|
||||
};
|
||||
let reserved_launch = if let Some(executor_id) = reserved_executor_id {
|
||||
let (policy, digest) = load_epiphany_cultmesh_managed_service_policy_with_digest(
|
||||
&args.store,
|
||||
args.runtime_id.clone(),
|
||||
SEMANTIC_PROJECTOR_SERVICE_ID,
|
||||
&args.service_id,
|
||||
)?
|
||||
.context("reserved semantic projector managed policy is absent")?;
|
||||
.context("reserved projector managed policy is absent")?;
|
||||
if command_path != PathBuf::from(&policy.command)
|
||||
|| service_args != policy.args
|
||||
|| args.cwd.as_ref().map(|path| path.display().to_string()) != policy.cwd
|
||||
{
|
||||
anyhow::bail!(
|
||||
"reserved semantic projector launch must use the exact current managed policy"
|
||||
);
|
||||
anyhow::bail!("reserved projector launch must use the exact current managed policy");
|
||||
}
|
||||
if args.wait_child {
|
||||
anyhow::bail!("reserved semantic projector launch is an infinite managed child");
|
||||
anyhow::bail!("reserved projector launch is an infinite managed child");
|
||||
}
|
||||
let executable_sha256 = local_file_sha256(&command_path.display().to_string())
|
||||
.map(|digest| format!("sha256-{digest}"))
|
||||
.context("reserved semantic projector executable cannot be fingerprinted")?;
|
||||
.context("reserved projector executable cannot be fingerprinted")?;
|
||||
Some((
|
||||
policy.policy_id,
|
||||
digest,
|
||||
Uuid::new_v4().to_string(),
|
||||
executable_sha256,
|
||||
executor_id.to_string(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut command = Command::new(&command_path);
|
||||
command.args(&service_args);
|
||||
if let Some((_, _, receipt_id, _)) = &reserved_launch {
|
||||
if let Some((_, _, receipt_id, _, _)) = &reserved_launch {
|
||||
command.env("EPIPHANY_STARTUP_LIFECYCLE_RECEIPT_ID", receipt_id);
|
||||
}
|
||||
if let Some(stdout_path) = &args.stdout_artifact {
|
||||
|
|
@ -878,11 +889,13 @@ fn service_launch(args: Args) -> Result<()> {
|
|||
.as_ref()
|
||||
.map(|path| path.display().to_string()),
|
||||
);
|
||||
if let Some((policy_id, policy_digest, receipt_id, executable_sha256)) = reserved_launch {
|
||||
if let Some((policy_id, policy_digest, receipt_id, executable_sha256, executor_id)) =
|
||||
reserved_launch
|
||||
{
|
||||
receipt.receipt_id = receipt_id.clone();
|
||||
receipt.managed_policy_id = policy_id;
|
||||
receipt.managed_policy_digest = policy_digest;
|
||||
receipt.provider_daemon_id = SEMANTIC_PROJECTOR_EXECUTOR_ID.to_string();
|
||||
receipt.provider_daemon_id = executor_id;
|
||||
receipt.startup_correlation_id = receipt_id;
|
||||
receipt.executable_sha256 = executable_sha256;
|
||||
}
|
||||
|
|
@ -893,7 +906,7 @@ fn service_launch(args: Args) -> Result<()> {
|
|||
) {
|
||||
Ok(written) => written,
|
||||
Err(error) => {
|
||||
if args.service_id == SEMANTIC_PROJECTOR_SERVICE_ID {
|
||||
if reserved_executor_id.is_some() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
|
@ -919,10 +932,10 @@ fn service_launch(args: Args) -> Result<()> {
|
|||
}
|
||||
|
||||
fn managed_service_policy(args: Args) -> Result<()> {
|
||||
if args.service_id == SEMANTIC_PROJECTOR_SERVICE_ID {
|
||||
anyhow::bail!(
|
||||
"reserved semantic projector service policy must use semantic-projector-service-policy"
|
||||
);
|
||||
if args.service_id == SEMANTIC_PROJECTOR_SERVICE_ID
|
||||
|| args.service_id == WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID
|
||||
{
|
||||
anyhow::bail!("reserved projector service policy must use its specialized policy command");
|
||||
}
|
||||
write_managed_service_policy(args)
|
||||
}
|
||||
|
|
@ -982,6 +995,12 @@ fn write_managed_service_policy(args: Args) -> Result<()> {
|
|||
args.runtime_id.clone(),
|
||||
policy,
|
||||
)?
|
||||
} else if policy.service_id == WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID {
|
||||
write_epiphany_cultmesh_workspace_coverage_projector_service_policy(
|
||||
&args.store,
|
||||
args.runtime_id.clone(),
|
||||
policy,
|
||||
)?
|
||||
} else {
|
||||
write_epiphany_cultmesh_managed_service_policy(
|
||||
&args.store,
|
||||
|
|
@ -1057,6 +1076,93 @@ fn semantic_projector_service_policy(mut args: Args) -> Result<()> {
|
|||
write_managed_service_policy(args)
|
||||
}
|
||||
|
||||
fn workspace_coverage_projector_service_policy(mut args: Args) -> Result<()> {
|
||||
if args.service_command.is_some() {
|
||||
anyhow::bail!(
|
||||
"workspace-coverage-projector-service-policy derives its packaged executable; --service-command is forbidden"
|
||||
);
|
||||
}
|
||||
let runtime_store = args
|
||||
.runtime_store
|
||||
.as_ref()
|
||||
.context("workspace-coverage-projector-service-policy requires --runtime-store")?;
|
||||
let qdrant_url = args
|
||||
.qdrant_url
|
||||
.as_deref()
|
||||
.context("workspace-coverage-projector-service-policy requires --qdrant-url")?;
|
||||
let ollama_base_url = args
|
||||
.ollama_base_url
|
||||
.as_deref()
|
||||
.context("workspace-coverage-projector-service-policy requires --ollama-base-url")?;
|
||||
args.service_id = WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID.to_string();
|
||||
args.policy_id = Some(format!(
|
||||
"managed-service-policy-{WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID}"
|
||||
));
|
||||
args.restart_mode = "always".to_string();
|
||||
args.service_command = Some(workspace_coverage_projector_command_path()?);
|
||||
args.service_args = workspace_coverage_projector_service_args(
|
||||
runtime_store,
|
||||
&args.store,
|
||||
&args.runtime_id,
|
||||
args.loop_interval_seconds,
|
||||
qdrant_url,
|
||||
ollama_base_url,
|
||||
&args.ollama_model,
|
||||
);
|
||||
if args.max_iterations != 0 {
|
||||
anyhow::bail!(
|
||||
"workspace coverage projector managed service must not have a finite iteration limit"
|
||||
);
|
||||
}
|
||||
write_managed_service_policy(args)
|
||||
}
|
||||
|
||||
fn workspace_coverage_projector_command_path() -> Result<PathBuf> {
|
||||
let binary = if cfg!(windows) {
|
||||
"epiphany-workspace-coverage-projector.exe"
|
||||
} else {
|
||||
"epiphany-workspace-coverage-projector"
|
||||
};
|
||||
let path = env::current_exe()
|
||||
.map(|path| path.with_file_name(binary))
|
||||
.context("failed to derive packaged workspace coverage projector executable")?;
|
||||
if !path.is_file() {
|
||||
anyhow::bail!(
|
||||
"packaged workspace coverage projector executable is missing at {}; build both supervisor and projector together",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn workspace_coverage_projector_service_args(
|
||||
runtime_store: &Path,
|
||||
local_verse_store: &Path,
|
||||
runtime_id: &str,
|
||||
interval_seconds: i64,
|
||||
qdrant_url: &str,
|
||||
ollama_base_url: &str,
|
||||
ollama_model: &str,
|
||||
) -> Vec<String> {
|
||||
vec![
|
||||
"serve".to_string(),
|
||||
"--runtime-store".to_string(),
|
||||
runtime_store.display().to_string(),
|
||||
"--local-verse-store".to_string(),
|
||||
local_verse_store.display().to_string(),
|
||||
"--runtime-id".to_string(),
|
||||
runtime_id.to_string(),
|
||||
"--interval-seconds".to_string(),
|
||||
interval_seconds.to_string(),
|
||||
"--qdrant-url".to_string(),
|
||||
qdrant_url.to_string(),
|
||||
"--ollama-base-url".to_string(),
|
||||
ollama_base_url.to_string(),
|
||||
"--ollama-model".to_string(),
|
||||
ollama_model.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
fn semantic_projector_command_path() -> Result<PathBuf> {
|
||||
let binary = if cfg!(windows) {
|
||||
"epiphany-memory-semantic-projector.exe"
|
||||
|
|
@ -2652,6 +2758,48 @@ mod semantic_projector_authority_tests {
|
|||
assert_eq!(args.iter().filter(|arg| arg.as_str() == "serve").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_workspace_coverage_projector_has_one_body_derived_runtime_input() {
|
||||
let args = workspace_coverage_projector_service_args(
|
||||
Path::new("runtime.ccmp"),
|
||||
Path::new("local-verse.ccmp"),
|
||||
"local-runtime",
|
||||
60,
|
||||
"http://127.0.0.1:16333",
|
||||
"http://10.77.0.1:11435",
|
||||
"qwen3-embedding:0.6b",
|
||||
);
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"serve",
|
||||
"--runtime-store",
|
||||
"runtime.ccmp",
|
||||
"--local-verse-store",
|
||||
"local-verse.ccmp",
|
||||
"--runtime-id",
|
||||
"local-runtime",
|
||||
"--interval-seconds",
|
||||
"60",
|
||||
"--qdrant-url",
|
||||
"http://127.0.0.1:16333",
|
||||
"--ollama-base-url",
|
||||
"http://10.77.0.1:11435",
|
||||
"--ollama-model",
|
||||
"qwen3-embedding:0.6b",
|
||||
]
|
||||
);
|
||||
for forbidden in [
|
||||
"--agent-store",
|
||||
"--body-store",
|
||||
"--workspace",
|
||||
"--collection",
|
||||
"--dimensions",
|
||||
] {
|
||||
assert!(!args.iter().any(|arg| arg == forbidden));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_projector_launch_seals_spawn_before_the_child_may_publish() {
|
||||
let source = include_str!("epiphany-daemon-supervisor.rs");
|
||||
|
|
|
|||
220
epiphany-core/src/bin/epiphany-workspace-coverage-projector.rs
Normal file
220
epiphany-core/src/bin/epiphany-workspace-coverage-projector.rs
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
use anyhow::{Context, Result, anyhow};
|
||||
use epiphany_core::{
|
||||
EPIPHANY_CULTMESH_DAEMON_HEARTBEAT_EVENT_SCHEMA_VERSION,
|
||||
EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID, EpiphanyCultMeshDaemonHeartbeatEventEntry,
|
||||
EpiphanyCultMeshDaemonServiceLifecycleReceiptEntry, WorkspaceCoverageProjectorConfig,
|
||||
WorkspaceCoverageProjectorPulseStatus, WorkspaceCoverageProjectorServiceBody,
|
||||
authenticate_epiphany_cultmesh_workspace_coverage_projector_launch,
|
||||
load_epiphany_cultmesh_daemon_service_lifecycle_receipt,
|
||||
write_epiphany_cultmesh_daemon_heartbeat_event,
|
||||
};
|
||||
use serde_json::json;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use uuid::Uuid;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse()?;
|
||||
let receipt = authenticate_managed_launch(&args)?;
|
||||
authenticate_process_body(&receipt)?;
|
||||
|
||||
let provider_incarnation = Uuid::new_v4().to_string();
|
||||
let mut config = WorkspaceCoverageProjectorConfig::from_env();
|
||||
config.qdrant_url = args.qdrant_url.clone();
|
||||
config.ollama_base_url = args.ollama_base_url.clone();
|
||||
config.ollama_model = args.ollama_model.clone();
|
||||
let mut projector = WorkspaceCoverageProjectorServiceBody::new(
|
||||
&args.runtime_store,
|
||||
&args.runtime_id,
|
||||
config,
|
||||
&provider_incarnation,
|
||||
&args.startup_lifecycle_receipt_id,
|
||||
)?;
|
||||
|
||||
let mut sequence = 0_u64;
|
||||
loop {
|
||||
sequence = sequence
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow!("workspace coverage heartbeat sequence exhausted"))?;
|
||||
let pulse = projector.pulse();
|
||||
// Contention describes canonical claim ownership, not provider health.
|
||||
// Publishing it as degraded would make a live successor unable to
|
||||
// establish the ready heartbeat required to fence an abandoned owner.
|
||||
let degraded = matches!(pulse.status, WorkspaceCoverageProjectorPulseStatus::Refused);
|
||||
let heartbeat = write_epiphany_cultmesh_daemon_heartbeat_event(
|
||||
&args.local_verse_store,
|
||||
args.runtime_id.clone(),
|
||||
EpiphanyCultMeshDaemonHeartbeatEventEntry {
|
||||
schema_version: EPIPHANY_CULTMESH_DAEMON_HEARTBEAT_EVENT_SCHEMA_VERSION.to_string(),
|
||||
heartbeat_id: Uuid::new_v4().to_string(),
|
||||
daemon_id: EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID.to_string(),
|
||||
cluster_id: "local".to_string(),
|
||||
provider_incarnation: projector.provider_incarnation().to_string(),
|
||||
sequence,
|
||||
status: if degraded { "degraded" } else { "ready" }.to_string(),
|
||||
heartbeat_at: chrono::Utc::now().to_rfc3339(),
|
||||
private_state_exposed: false,
|
||||
startup_lifecycle_receipt_id: projector.startup_lifecycle_receipt_id().to_string(),
|
||||
},
|
||||
)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&json!({
|
||||
"schemaVersion": "epiphany.workspace_coverage_projector_pulse.v0",
|
||||
"pulseSequence": sequence,
|
||||
"providerIncarnation": projector.provider_incarnation(),
|
||||
"heartbeatId": heartbeat.heartbeat_id,
|
||||
"providerStatus": heartbeat.status,
|
||||
"pulseStatus": pulse_status(pulse.status),
|
||||
"bodyObservationId": pulse.body_observation_id,
|
||||
"bodyGeneration": pulse.body_generation,
|
||||
"planId": pulse.plan_id,
|
||||
"receiptId": pulse.receipt_id,
|
||||
"fault": pulse.fault,
|
||||
"privateStateExposed": false,
|
||||
"authoritative": false
|
||||
}))?
|
||||
);
|
||||
thread::sleep(Duration::from_secs(args.interval_seconds));
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticate_managed_launch(
|
||||
args: &Args,
|
||||
) -> Result<EpiphanyCultMeshDaemonServiceLifecycleReceiptEntry> {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
if load_epiphany_cultmesh_daemon_service_lifecycle_receipt(
|
||||
&args.local_verse_store,
|
||||
args.runtime_id.clone(),
|
||||
&args.startup_lifecycle_receipt_id,
|
||||
)?
|
||||
.is_some()
|
||||
{
|
||||
return authenticate_epiphany_cultmesh_workspace_coverage_projector_launch(
|
||||
&args.local_verse_store,
|
||||
args.runtime_id.clone(),
|
||||
&args.startup_lifecycle_receipt_id,
|
||||
);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(anyhow!(
|
||||
"managed workspace coverage projector startup launch receipt was not persisted"
|
||||
));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticate_process_body(
|
||||
receipt: &EpiphanyCultMeshDaemonServiceLifecycleReceiptEntry,
|
||||
) -> Result<()> {
|
||||
if receipt.process_id != Some(std::process::id()) {
|
||||
return Err(anyhow!(
|
||||
"managed workspace coverage projector process disagrees with its launch receipt"
|
||||
));
|
||||
}
|
||||
let executable = env::current_exe().context("failed to resolve projector executable")?;
|
||||
let executable_sha256 = format!(
|
||||
"sha256-{:x}",
|
||||
Sha256::digest(fs::read(&executable).with_context(|| {
|
||||
format!(
|
||||
"failed to fingerprint projector executable {}",
|
||||
executable.display()
|
||||
)
|
||||
})?)
|
||||
);
|
||||
if receipt.executable_sha256 != executable_sha256 {
|
||||
return Err(anyhow!(
|
||||
"managed workspace coverage projector executable disagrees with its launch receipt"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pulse_status(status: WorkspaceCoverageProjectorPulseStatus) -> &'static str {
|
||||
match status {
|
||||
WorkspaceCoverageProjectorPulseStatus::Idle => "idle",
|
||||
WorkspaceCoverageProjectorPulseStatus::Executed => "executed",
|
||||
WorkspaceCoverageProjectorPulseStatus::Contended => "contended",
|
||||
WorkspaceCoverageProjectorPulseStatus::Refused => "refused",
|
||||
}
|
||||
}
|
||||
|
||||
struct Args {
|
||||
runtime_store: PathBuf,
|
||||
local_verse_store: PathBuf,
|
||||
runtime_id: String,
|
||||
interval_seconds: u64,
|
||||
startup_lifecycle_receipt_id: String,
|
||||
qdrant_url: String,
|
||||
ollama_base_url: String,
|
||||
ollama_model: String,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn parse() -> Result<Self> {
|
||||
let mut values = env::args().skip(1);
|
||||
let command = values.next().context("missing command; use serve")?;
|
||||
if command != "serve" {
|
||||
return Err(anyhow!("unknown command {command:?}; use serve"));
|
||||
}
|
||||
let mut runtime_store = None;
|
||||
let mut local_verse_store = None;
|
||||
let mut runtime_id = None;
|
||||
let mut interval_seconds = None;
|
||||
let mut qdrant_url = None;
|
||||
let mut ollama_base_url = None;
|
||||
let mut ollama_model = None;
|
||||
while let Some(flag) = values.next() {
|
||||
let mut value = || {
|
||||
values
|
||||
.next()
|
||||
.with_context(|| format!("missing value for {flag}"))
|
||||
};
|
||||
match flag.as_str() {
|
||||
"--runtime-store" => runtime_store = Some(PathBuf::from(value()?)),
|
||||
"--local-verse-store" => local_verse_store = Some(PathBuf::from(value()?)),
|
||||
"--runtime-id" => runtime_id = Some(value()?),
|
||||
"--interval-seconds" => interval_seconds = Some(value()?.parse::<u64>()?),
|
||||
"--qdrant-url" => qdrant_url = Some(value()?),
|
||||
"--ollama-base-url" => ollama_base_url = Some(value()?),
|
||||
"--ollama-model" => ollama_model = Some(value()?),
|
||||
_ => return Err(anyhow!("unexpected argument {flag:?}")),
|
||||
}
|
||||
}
|
||||
let interval_seconds = interval_seconds.context("missing --interval-seconds")?;
|
||||
if interval_seconds == 0 {
|
||||
return Err(anyhow!("--interval-seconds must be positive"));
|
||||
}
|
||||
let startup_lifecycle_receipt_id =
|
||||
env::var("EPIPHANY_STARTUP_LIFECYCLE_RECEIPT_ID").unwrap_or_default();
|
||||
if startup_lifecycle_receipt_id.trim().is_empty() {
|
||||
return Err(anyhow!(
|
||||
"managed workspace coverage projector requires its startup launch receipt id"
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
runtime_store: runtime_store.context("missing --runtime-store")?,
|
||||
local_verse_store: local_verse_store.context("missing --local-verse-store")?,
|
||||
runtime_id: runtime_id.context("missing --runtime-id")?,
|
||||
interval_seconds,
|
||||
startup_lifecycle_receipt_id,
|
||||
qdrant_url: required_nonempty(qdrant_url, "--qdrant-url")?,
|
||||
ollama_base_url: required_nonempty(ollama_base_url, "--ollama-base-url")?,
|
||||
ollama_model: required_nonempty(ollama_model, "--ollama-model")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn required_nonempty(value: Option<String>, flag: &str) -> Result<String> {
|
||||
let value = value.with_context(|| format!("missing {flag}"))?;
|
||||
if value.trim().is_empty() {
|
||||
return Err(anyhow!("{flag} must not be empty"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
|
@ -163,6 +163,10 @@ pub const EPIPHANY_CULTMESH_MANAGED_SERVICE_POLICY_TYPE: &str =
|
|||
pub const EPIPHANY_CULTMESH_MANAGED_SERVICE_POLICY_SCHEMA_VERSION: &str =
|
||||
"epiphany.cultmesh.managed_service_policy.v0";
|
||||
const EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID: &str = "epiphany-memory-semantic-projector-service";
|
||||
pub const EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID: &str =
|
||||
"epiphany-workspace-coverage-projector-service";
|
||||
pub const EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID: &str =
|
||||
"epiphany-workspace-coverage-projector";
|
||||
pub const EPIPHANY_CULTMESH_IDUNN_DEPLOYMENT_RECEIPT_SCHEMA_VERSION: &str =
|
||||
"gamecult.idunn.deployment_receipt.v0";
|
||||
pub const EPIPHANY_CULTMESH_IDUNN_DEPLOYMENT_RECEIPT_LATEST_KEY: &str =
|
||||
|
|
@ -4147,12 +4151,21 @@ pub fn write_epiphany_cultmesh_daemon_service_lifecycle_receipt(
|
|||
let (receipt_envelope, written) = node.cache().prepare_entry(receipt_key, &receipt)?;
|
||||
let mut expected = Vec::new();
|
||||
let mut replacements = vec![receipt_envelope];
|
||||
if written.service_id == EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID && written.action == "launch" {
|
||||
if matches!(
|
||||
written.service_id.as_str(),
|
||||
EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID | EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID
|
||||
) && written.action == "launch"
|
||||
{
|
||||
let reserved_name = if written.service_id == EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID {
|
||||
"semantic projector"
|
||||
} else {
|
||||
"workspace coverage projector"
|
||||
};
|
||||
let policy_key = epiphany_cultmesh_managed_service_policy_key(&written.service_id);
|
||||
let policy_envelope = node
|
||||
.cache()
|
||||
.get_envelope::<EpiphanyCultMeshManagedServicePolicyEntry>(&policy_key)?
|
||||
.ok_or_else(|| anyhow!("reserved semantic projector managed policy is absent"))?;
|
||||
.ok_or_else(|| anyhow!("reserved {reserved_name} managed policy is absent"))?;
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(policy_envelope.r#type.as_bytes());
|
||||
digest.update([0]);
|
||||
|
|
@ -4161,7 +4174,7 @@ pub fn write_epiphany_cultmesh_daemon_service_lifecycle_receipt(
|
|||
digest.update(&policy_envelope.payload);
|
||||
if written.managed_policy_digest != format!("sha256-{:x}", digest.finalize()) {
|
||||
return Err(anyhow!(
|
||||
"reserved semantic projector launch receipt has stale managed policy digest"
|
||||
"reserved {reserved_name} launch receipt has stale managed policy digest"
|
||||
));
|
||||
}
|
||||
expected.push(policy_envelope.clone());
|
||||
|
|
@ -4285,6 +4298,39 @@ pub fn authenticate_epiphany_cultmesh_semantic_projector_launch(
|
|||
Ok(receipt)
|
||||
}
|
||||
|
||||
pub fn authenticate_epiphany_cultmesh_workspace_coverage_projector_launch(
|
||||
store_path: impl AsRef<Path>,
|
||||
runtime_id: impl Into<String>,
|
||||
receipt_id: &str,
|
||||
) -> Result<EpiphanyCultMeshDaemonServiceLifecycleReceiptEntry> {
|
||||
let runtime_id = runtime_id.into();
|
||||
let receipt = load_epiphany_cultmesh_daemon_service_lifecycle_receipt(
|
||||
store_path.as_ref(),
|
||||
runtime_id.clone(),
|
||||
receipt_id,
|
||||
)?
|
||||
.ok_or_else(|| anyhow!("workspace coverage projector startup launch receipt is absent"))?;
|
||||
validate_workspace_coverage_projector_launch_receipt(&receipt)?;
|
||||
let (policy, digest) = load_epiphany_cultmesh_managed_service_policy_with_digest(
|
||||
store_path,
|
||||
runtime_id,
|
||||
EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID,
|
||||
)?
|
||||
.ok_or_else(|| anyhow!("workspace coverage projector managed policy is absent"))?;
|
||||
validate_workspace_coverage_projector_managed_service_policy(&policy)?;
|
||||
if receipt.managed_policy_id != policy.policy_id
|
||||
|| receipt.managed_policy_digest != digest
|
||||
|| receipt.command != policy.command
|
||||
|| receipt.args != policy.args
|
||||
|| receipt.cwd != policy.cwd
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"workspace coverage projector startup launch receipt disagrees with current managed policy"
|
||||
));
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
pub fn load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt(
|
||||
store_path: impl AsRef<Path>,
|
||||
runtime_id: impl Into<String>,
|
||||
|
|
@ -4328,6 +4374,11 @@ pub fn write_epiphany_cultmesh_managed_service_policy(
|
|||
"reserved semantic projector policy requires its specialized writer"
|
||||
));
|
||||
}
|
||||
if policy.service_id == EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID {
|
||||
return Err(anyhow!(
|
||||
"reserved workspace coverage projector policy requires its specialized writer"
|
||||
));
|
||||
}
|
||||
validate_managed_service_policy(&policy)?;
|
||||
write_validated_managed_service_policy(store_path, runtime_id, policy)
|
||||
}
|
||||
|
|
@ -4347,6 +4398,21 @@ pub fn write_epiphany_cultmesh_semantic_projector_service_policy(
|
|||
write_validated_managed_service_policy(store_path, runtime_id, policy)
|
||||
}
|
||||
|
||||
pub fn write_epiphany_cultmesh_workspace_coverage_projector_service_policy(
|
||||
store_path: impl AsRef<Path>,
|
||||
runtime_id: impl Into<String>,
|
||||
policy: EpiphanyCultMeshManagedServicePolicyEntry,
|
||||
) -> Result<EpiphanyCultMeshManagedServicePolicyEntry> {
|
||||
validate_managed_service_policy(&policy)?;
|
||||
if policy.service_id != EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID {
|
||||
return Err(anyhow!(
|
||||
"workspace coverage projector policy writer requires its reserved service id"
|
||||
));
|
||||
}
|
||||
validate_workspace_coverage_projector_managed_service_policy(&policy)?;
|
||||
write_validated_managed_service_policy(store_path, runtime_id, policy)
|
||||
}
|
||||
|
||||
fn write_validated_managed_service_policy(
|
||||
store_path: impl AsRef<Path>,
|
||||
runtime_id: impl Into<String>,
|
||||
|
|
@ -4806,6 +4872,55 @@ fn validate_semantic_projector_managed_service_policy(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_workspace_coverage_projector_managed_service_policy(
|
||||
policy: &EpiphanyCultMeshManagedServicePolicyEntry,
|
||||
) -> Result<()> {
|
||||
let expected_binary = if cfg!(windows) {
|
||||
"epiphany-workspace-coverage-projector.exe"
|
||||
} else {
|
||||
"epiphany-workspace-coverage-projector"
|
||||
};
|
||||
let expected_command = std::env::current_exe()
|
||||
.context("cannot resolve current executable for packaged projector policy")?
|
||||
.with_file_name(expected_binary);
|
||||
if Path::new(&policy.command) != expected_command {
|
||||
return Err(anyhow!(
|
||||
"reserved workspace coverage projector policy requires the packaged projector executable"
|
||||
));
|
||||
}
|
||||
if policy.policy_id != "managed-service-policy-epiphany-workspace-coverage-projector-service"
|
||||
|| policy.service_id != EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID
|
||||
|| policy.owner_daemon_id != "epiphany-daemon-supervisor"
|
||||
|| !policy.enabled
|
||||
|| policy.restart_mode != "always"
|
||||
|| policy.args.len() != 15
|
||||
|| policy.args[0] != "serve"
|
||||
|| policy.args[1] != "--runtime-store"
|
||||
|| policy.args[2].trim().is_empty()
|
||||
|| policy.args[3] != "--local-verse-store"
|
||||
|| policy.args[4].trim().is_empty()
|
||||
|| policy.args[5] != "--runtime-id"
|
||||
|| policy.args[6].trim().is_empty()
|
||||
|| policy.args[7] != "--interval-seconds"
|
||||
|| policy.args[8]
|
||||
.parse::<u64>()
|
||||
.ok()
|
||||
.filter(|value| *value > 0)
|
||||
.is_none()
|
||||
|| policy.args[9] != "--qdrant-url"
|
||||
|| policy.args[10].trim().is_empty()
|
||||
|| policy.args[11] != "--ollama-base-url"
|
||||
|| policy.args[12].trim().is_empty()
|
||||
|| policy.args[13] != "--ollama-model"
|
||||
|| policy.args[14].trim().is_empty()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"reserved workspace coverage projector policy must bind one packaged process to its authenticated runtime Body route"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_daemon_scheduler_receipt(
|
||||
receipt: &EpiphanyCultMeshDaemonSchedulerReceiptEntry,
|
||||
) -> Result<()> {
|
||||
|
|
@ -4909,6 +5024,11 @@ fn validate_daemon_service_lifecycle_receipt(
|
|||
if receipt.service_id == EPIPHANY_SEMANTIC_PROJECTOR_SERVICE_ID && receipt.action == "launch" {
|
||||
validate_semantic_projector_launch_receipt(receipt)?;
|
||||
}
|
||||
if receipt.service_id == EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID
|
||||
&& receipt.action == "launch"
|
||||
{
|
||||
validate_workspace_coverage_projector_launch_receipt(receipt)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -4936,6 +5056,31 @@ fn validate_semantic_projector_launch_receipt(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_workspace_coverage_projector_launch_receipt(
|
||||
receipt: &EpiphanyCultMeshDaemonServiceLifecycleReceiptEntry,
|
||||
) -> Result<()> {
|
||||
if receipt.schema_version != EPIPHANY_CULTMESH_DAEMON_SERVICE_LIFECYCLE_RECEIPT_SCHEMA_VERSION
|
||||
|| receipt.service_id != EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID
|
||||
|| receipt.action != "launch"
|
||||
|| receipt.status != "launched"
|
||||
|| receipt.process_id.is_none()
|
||||
|| receipt.exit_code.is_some()
|
||||
|| receipt.completed_at_utc.is_none()
|
||||
|| !receipt.executable_sha256.starts_with("sha256-")
|
||||
|| receipt.managed_policy_id
|
||||
!= "managed-service-policy-epiphany-workspace-coverage-projector-service"
|
||||
|| !receipt.managed_policy_digest.starts_with("sha256-")
|
||||
|| receipt.provider_daemon_id != EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID
|
||||
|| receipt.startup_correlation_id != receipt.receipt_id
|
||||
|| Uuid::parse_str(&receipt.receipt_id).is_err()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"reserved workspace coverage projector launch receipt must bind completed spawn to exact managed policy and provider identity"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn daemon_service_lifecycle_event_key(
|
||||
receipt: &EpiphanyCultMeshDaemonServiceLifecycleReceiptEntry,
|
||||
) -> (DateTime<FixedOffset>, &str) {
|
||||
|
|
@ -8177,6 +8322,175 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_workspace_coverage_projector_contract_is_exact_and_policy_bound() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let store = temp.path().join("verse.ccmp");
|
||||
let binary = std::env::current_exe()?.with_file_name(if cfg!(windows) {
|
||||
"epiphany-workspace-coverage-projector.exe"
|
||||
} else {
|
||||
"epiphany-workspace-coverage-projector"
|
||||
});
|
||||
let exact = EpiphanyCultMeshManagedServicePolicyEntry {
|
||||
schema_version: EPIPHANY_CULTMESH_MANAGED_SERVICE_POLICY_SCHEMA_VERSION.to_string(),
|
||||
policy_id: "managed-service-policy-epiphany-workspace-coverage-projector-service"
|
||||
.into(),
|
||||
service_id: EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID.into(),
|
||||
owner_daemon_id: "epiphany-daemon-supervisor".into(),
|
||||
command: binary.display().to_string(),
|
||||
args: vec![
|
||||
"serve",
|
||||
"--runtime-store",
|
||||
"runtime.ccmp",
|
||||
"--local-verse-store",
|
||||
"verse.ccmp",
|
||||
"--runtime-id",
|
||||
"local",
|
||||
"--interval-seconds",
|
||||
"60",
|
||||
"--qdrant-url",
|
||||
"http://127.0.0.1:6333",
|
||||
"--ollama-base-url",
|
||||
"http://127.0.0.1:11434",
|
||||
"--ollama-model",
|
||||
"qwen3-embedding:0.6b",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
cwd: None,
|
||||
enabled: true,
|
||||
restart_mode: "always".into(),
|
||||
cooldown_seconds: 0,
|
||||
backoff_multiplier: 1,
|
||||
stdout_artifact: "workspace-projector.stdout.log".into(),
|
||||
stderr_artifact: "workspace-projector.stderr.log".into(),
|
||||
updated_at_utc: "2026-07-15T12:00:00Z".into(),
|
||||
private_state_exposed: false,
|
||||
notes: vec![],
|
||||
};
|
||||
assert!(
|
||||
write_epiphany_cultmesh_managed_service_policy(&store, "local", exact.clone()).is_err()
|
||||
);
|
||||
let mut arbitrary_binary = exact.clone();
|
||||
arbitrary_binary.command = "arbitrary-projector.exe".into();
|
||||
assert!(
|
||||
write_epiphany_cultmesh_workspace_coverage_projector_service_policy(
|
||||
&store,
|
||||
"local",
|
||||
arbitrary_binary,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut injected_workspace = exact.clone();
|
||||
injected_workspace.args.insert(3, "--workspace".into());
|
||||
injected_workspace.args.insert(4, "stolen".into());
|
||||
assert!(
|
||||
write_epiphany_cultmesh_workspace_coverage_projector_service_policy(
|
||||
&store,
|
||||
"local",
|
||||
injected_workspace,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
write_epiphany_cultmesh_workspace_coverage_projector_service_policy(
|
||||
&store,
|
||||
"local",
|
||||
exact.clone(),
|
||||
)?;
|
||||
let (_, digest) = load_epiphany_cultmesh_managed_service_policy_with_digest(
|
||||
&store,
|
||||
"local",
|
||||
EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID,
|
||||
)?
|
||||
.context("workspace coverage policy missing")?;
|
||||
let receipt_id = "fd3b7be9-02b0-4ac7-a47e-2d25097ff1f5";
|
||||
let receipt = EpiphanyCultMeshDaemonServiceLifecycleReceiptEntry {
|
||||
schema_version: EPIPHANY_CULTMESH_DAEMON_SERVICE_LIFECYCLE_RECEIPT_SCHEMA_VERSION
|
||||
.into(),
|
||||
receipt_id: receipt_id.into(),
|
||||
service_id: EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID.into(),
|
||||
scheduler_id: "epiphany-daemon-supervisor".into(),
|
||||
runtime_id: "local".into(),
|
||||
daemon_selector: "epiphany-daemon-supervisor".into(),
|
||||
action: "launch".into(),
|
||||
status: "launched".into(),
|
||||
command: exact.command.clone(),
|
||||
args: exact.args.clone(),
|
||||
cwd: exact.cwd.clone(),
|
||||
process_id: Some(4242),
|
||||
exit_code: None,
|
||||
started_at_utc: "2026-07-15T12:00:00Z".into(),
|
||||
completed_at_utc: Some("2026-07-15T12:00:01Z".into()),
|
||||
operator_artifact_ref: "service://workspace-coverage-projector/launch".into(),
|
||||
private_state_exposed: false,
|
||||
notes: vec![],
|
||||
executable_sha256: "sha256-test-workspace-projector".into(),
|
||||
preflight_witness_id: String::new(),
|
||||
required_document_types: vec![],
|
||||
schema_preflight_passed: false,
|
||||
schema_catalog_sha256: String::new(),
|
||||
managed_policy_id: exact.policy_id.clone(),
|
||||
managed_policy_digest: digest.clone(),
|
||||
provider_daemon_id: EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID.into(),
|
||||
startup_correlation_id: receipt_id.into(),
|
||||
};
|
||||
let mut wrong_provider = receipt.clone();
|
||||
wrong_provider.receipt_id = "f6d454dd-3765-44cb-930a-bae0d47487aa".into();
|
||||
wrong_provider.startup_correlation_id = wrong_provider.receipt_id.clone();
|
||||
wrong_provider.provider_daemon_id = "epiphany-memory-semantic-projector".into();
|
||||
assert!(
|
||||
write_epiphany_cultmesh_daemon_service_lifecycle_receipt(
|
||||
&store,
|
||||
"local",
|
||||
wrong_provider,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut stale = receipt.clone();
|
||||
stale.receipt_id = "a0ea76d1-9a9a-4dc7-a8bc-a56ab1d8079a".into();
|
||||
stale.startup_correlation_id = stale.receipt_id.clone();
|
||||
stale.managed_policy_digest = "sha256-stale".into();
|
||||
assert!(
|
||||
write_epiphany_cultmesh_daemon_service_lifecycle_receipt(&store, "local", stale)
|
||||
.is_err()
|
||||
);
|
||||
let written = write_epiphany_cultmesh_daemon_service_lifecycle_receipt(
|
||||
&store,
|
||||
"local",
|
||||
receipt.clone(),
|
||||
)?;
|
||||
assert_eq!(
|
||||
load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt_for_service(
|
||||
&store,
|
||||
"local",
|
||||
EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID,
|
||||
)?,
|
||||
Some(written.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
authenticate_epiphany_cultmesh_workspace_coverage_projector_launch(
|
||||
&store, "local", receipt_id,
|
||||
)?,
|
||||
written
|
||||
);
|
||||
|
||||
let mut advanced = exact;
|
||||
advanced.updated_at_utc = "2026-07-15T12:00:02Z".into();
|
||||
write_epiphany_cultmesh_workspace_coverage_projector_service_policy(
|
||||
&store, "local", advanced,
|
||||
)?;
|
||||
assert!(
|
||||
authenticate_epiphany_cultmesh_workspace_coverage_projector_launch(
|
||||
&store, "local", receipt_id,
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("disagrees with current managed policy")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn semantic_health_input(
|
||||
store: &Path,
|
||||
swarm_id: &str,
|
||||
|
|
|
|||
|
|
@ -35,11 +35,8 @@ mod substrate_gate;
|
|||
mod surfaces;
|
||||
mod thread_state_store;
|
||||
mod weksa_interlingua;
|
||||
// Sealed foundation: intentionally unreachable until terminal success and
|
||||
// abandoned-claim recovery exist. Keeping the lint local makes that boundary
|
||||
// explicit without exporting mutation authority merely to silence dead-code.
|
||||
#[allow(dead_code)]
|
||||
mod workspace_coverage_projector;
|
||||
mod workspace_coverage_projector_service;
|
||||
#[allow(dead_code)]
|
||||
mod workspace_retrieval_coverage;
|
||||
|
||||
|
|
@ -335,6 +332,8 @@ pub use cultmesh_integration::EPIPHANY_CULTMESH_WEKSA_LOWERING_RECEIPT_TYPE;
|
|||
pub use cultmesh_integration::EPIPHANY_CULTMESH_WORK_LOOP_TELEMETRY_LATEST_KEY;
|
||||
pub use cultmesh_integration::EPIPHANY_CULTMESH_WORK_LOOP_TELEMETRY_SCHEMA_VERSION;
|
||||
pub use cultmesh_integration::EPIPHANY_CULTMESH_WORK_LOOP_TELEMETRY_TYPE;
|
||||
pub use cultmesh_integration::EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID;
|
||||
pub use cultmesh_integration::EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_SERVICE_ID;
|
||||
pub use cultmesh_integration::EpiphanyCultMeshAgentStateSoaSummaryEntry;
|
||||
pub use cultmesh_integration::EpiphanyCultMeshBifrostArtifactAcceptanceReceiptEntry;
|
||||
pub use cultmesh_integration::EpiphanyCultMeshBifrostBodyChangePublicationIntentEntry;
|
||||
|
|
@ -394,6 +393,7 @@ pub use cultmesh_integration::EpiphanyLocalVerseWorkLoopSummary;
|
|||
pub use cultmesh_integration::EpiphanyServiceExecutionAuditCheck;
|
||||
pub use cultmesh_integration::EpiphanyServiceExecutionAuditReport;
|
||||
pub use cultmesh_integration::authenticate_epiphany_cultmesh_semantic_projector_launch;
|
||||
pub use cultmesh_integration::authenticate_epiphany_cultmesh_workspace_coverage_projector_launch;
|
||||
pub use cultmesh_integration::default_epiphany_cultmesh_swarm_brake;
|
||||
pub use cultmesh_integration::epiphany_cluster_service_execution_audit_report;
|
||||
pub use cultmesh_integration::epiphany_cultmesh_agent_state_soa_summary_from_entry;
|
||||
|
|
@ -557,6 +557,7 @@ pub use cultmesh_integration::write_epiphany_cultmesh_swarm_brake;
|
|||
pub use cultmesh_integration::write_epiphany_cultmesh_verse_policies;
|
||||
pub use cultmesh_integration::write_epiphany_cultmesh_weksa_lowering_receipt;
|
||||
pub use cultmesh_integration::write_epiphany_cultmesh_work_loop_telemetry;
|
||||
pub use cultmesh_integration::write_epiphany_cultmesh_workspace_coverage_projector_service_policy;
|
||||
pub use distillation::EpiphanyDistillInput;
|
||||
pub use distillation::EpiphanyDistillProposal;
|
||||
pub use distillation::distill_observation;
|
||||
|
|
@ -1139,4 +1140,8 @@ pub use weksa_interlingua::build_weksa_interlingua_packet;
|
|||
pub use weksa_interlingua::build_weksa_lowering_prompt;
|
||||
pub use weksa_interlingua::build_weksa_target_lowering_request;
|
||||
pub use weksa_interlingua::record_weksa_target_lowering_receipt;
|
||||
pub use workspace_coverage_projector_service::WorkspaceCoverageProjectorConfig;
|
||||
pub use workspace_coverage_projector_service::WorkspaceCoverageProjectorPulseStatus;
|
||||
pub use workspace_coverage_projector_service::WorkspaceCoverageProjectorServiceBody;
|
||||
pub use workspace_coverage_projector_service::WorkspaceCoverageProjectorServicePulse;
|
||||
pub use workspace_retrieval_coverage::*;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ use cultcache_rs::{
|
|||
};
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
#[cfg(test)]
|
||||
use std::cell::Cell;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
use uuid::Uuid;
|
||||
|
|
@ -22,6 +24,22 @@ pub const BODY_BINDING_KEY: &str = "binding";
|
|||
pub const BODY_HEAD_KEY: &str = "current";
|
||||
pub const RUNTIME_BODY_STORE_BINDING_KEY: &str = "repository-body-store";
|
||||
pub const BODY_SCHEMA_VERSION: &str = "epiphany.repository_body.v2";
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static BODY_STORE_LOADS: Cell<usize> = const { Cell::new(0) };
|
||||
static BODY_FILE_READS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reset_repository_body_read_counters() {
|
||||
BODY_STORE_LOADS.set(0);
|
||||
BODY_FILE_READS.set(0);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn repository_body_read_counters() -> (usize, usize) {
|
||||
(BODY_STORE_LOADS.get(), BODY_FILE_READS.get())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
|
|
@ -183,6 +201,90 @@ pub(crate) struct VerifiedRepositoryBodyBytes {
|
|||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
/// One authenticated view of a persisted Repository Body generation.
|
||||
///
|
||||
/// Opening the session authenticates the runtime route and the complete
|
||||
/// binding/head/observation/manifest chain once. Reads reuse that sealed view;
|
||||
/// they never reload the whole CultCache store for each file.
|
||||
pub(crate) struct RepositoryBodyReadSession {
|
||||
basis: RepositoryBodyObservationBasis,
|
||||
manifest: RepositoryBodyManifest,
|
||||
root: PathBuf,
|
||||
body_store: PathBuf,
|
||||
}
|
||||
|
||||
impl RepositoryBodyReadSession {
|
||||
pub(crate) fn open(
|
||||
runtime_store: &Path,
|
||||
basis: &RepositoryBodyObservationBasis,
|
||||
) -> Result<Self> {
|
||||
let route = runtime_repository_body_store_binding(runtime_store)?
|
||||
.ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?;
|
||||
let entries = load_body_envelopes(Path::new(&route.body_store_path))?;
|
||||
let binding: RepositoryBodyBinding = decode(
|
||||
find(&entries, BODY_BINDING_TYPE, BODY_BINDING_KEY)
|
||||
.ok_or_else(|| anyhow!("runtime repository Body store has no Body binding"))?,
|
||||
)?;
|
||||
let head: RepositoryBodyHead = decode(
|
||||
find(&entries, BODY_HEAD_TYPE, BODY_HEAD_KEY)
|
||||
.ok_or_else(|| anyhow!("runtime repository Body store has no current Body head"))?,
|
||||
)?;
|
||||
let (observation, manifest) = validate_body_chain(&entries, &binding, &head)?;
|
||||
if basis.schema_version != BODY_SCHEMA_VERSION
|
||||
|| binding.runtime_id != route.runtime_id
|
||||
|| binding.swarm_id != route.swarm_id
|
||||
|| binding.workspace_id != route.workspace_id
|
||||
|| body_binding_sha256(&binding)? != route.body_binding_sha256
|
||||
|| basis.runtime_id != binding.runtime_id
|
||||
|| basis.swarm_id != binding.swarm_id
|
||||
|| basis.workspace_id != binding.workspace_id
|
||||
|| basis.scope != binding.scope
|
||||
|| basis.body_binding_sha256 != route.body_binding_sha256
|
||||
|| head.workspace_id != basis.workspace_id
|
||||
|| head.observation_id != basis.observation_id
|
||||
|| head.generation != basis.generation
|
||||
|| head.manifest_root_sha256 != basis.manifest_root_sha256
|
||||
|| observation.observation_id != basis.observation_id
|
||||
|| observation.generation != basis.generation
|
||||
|| observation.manifest_root_sha256 != basis.manifest_root_sha256
|
||||
|| observation.scan_started_at != basis.scan_started_at
|
||||
|| observation.scan_finished_at != basis.scan_finished_at
|
||||
{
|
||||
bail!("repository Body read session disagrees with its authenticated route or basis");
|
||||
}
|
||||
let root = std::fs::canonicalize(&binding.git_top_level)
|
||||
.context("bound repository root is missing")?;
|
||||
if root != PathBuf::from(&binding.git_top_level) {
|
||||
bail!("bound repository root is no longer canonical");
|
||||
}
|
||||
Ok(Self {
|
||||
basis: basis.clone(),
|
||||
manifest,
|
||||
root,
|
||||
body_store: PathBuf::from(route.body_store_path),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn basis(&self) -> &RepositoryBodyObservationBasis {
|
||||
&self.basis
|
||||
}
|
||||
|
||||
pub(crate) fn manifest(&self) -> &RepositoryBodyManifest {
|
||||
&self.manifest
|
||||
}
|
||||
|
||||
pub(crate) fn body_store(&self) -> &Path {
|
||||
&self.body_store
|
||||
}
|
||||
|
||||
pub(crate) fn read_regular_file(
|
||||
&self,
|
||||
relative_path: &str,
|
||||
) -> Result<VerifiedRepositoryBodyBytes> {
|
||||
read_verified_repository_body_bytes_from_session(self, relative_path)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(type = "epiphany.repository_body.head", schema = "RepositoryBodyHead")]
|
||||
pub struct RepositoryBodyHead {
|
||||
|
|
@ -293,6 +395,45 @@ pub fn observe_runtime_repository_body_basis(
|
|||
})
|
||||
}
|
||||
|
||||
/// Loads the authenticated current Repository Body basis already persisted for
|
||||
/// a runtime without observing the worktree or advancing the Body generation.
|
||||
pub fn load_current_runtime_repository_body_basis(
|
||||
runtime_store: &Path,
|
||||
) -> Result<RepositoryBodyObservationBasis> {
|
||||
let route = runtime_repository_body_store_binding(runtime_store)?
|
||||
.ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?;
|
||||
let entries = load_body_envelopes(Path::new(&route.body_store_path))?;
|
||||
let binding: RepositoryBodyBinding = decode(
|
||||
find(&entries, BODY_BINDING_TYPE, BODY_BINDING_KEY)
|
||||
.ok_or_else(|| anyhow!("runtime repository Body store has no Body binding"))?,
|
||||
)?;
|
||||
let head: RepositoryBodyHead = decode(
|
||||
find(&entries, BODY_HEAD_TYPE, BODY_HEAD_KEY)
|
||||
.ok_or_else(|| anyhow!("runtime repository Body store has no current Body head"))?,
|
||||
)?;
|
||||
let (observation, _) = validate_body_chain(&entries, &binding, &head)?;
|
||||
if binding.runtime_id != route.runtime_id
|
||||
|| binding.swarm_id != route.swarm_id
|
||||
|| binding.workspace_id != route.workspace_id
|
||||
|| body_binding_sha256(&binding)? != route.body_binding_sha256
|
||||
{
|
||||
bail!("current repository Body basis disagrees with its authenticated runtime route");
|
||||
}
|
||||
Ok(RepositoryBodyObservationBasis {
|
||||
schema_version: BODY_SCHEMA_VERSION.into(),
|
||||
workspace_id: binding.workspace_id,
|
||||
swarm_id: binding.swarm_id,
|
||||
runtime_id: binding.runtime_id,
|
||||
scope: binding.scope,
|
||||
body_binding_sha256: route.body_binding_sha256,
|
||||
observation_id: observation.observation_id,
|
||||
generation: observation.generation,
|
||||
manifest_root_sha256: observation.manifest_root_sha256,
|
||||
scan_started_at: observation.scan_started_at,
|
||||
scan_finished_at: observation.scan_finished_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate_repository_body_observation_basis(
|
||||
runtime_store: &Path,
|
||||
basis: &RepositoryBodyObservationBasis,
|
||||
|
|
@ -358,9 +499,16 @@ pub(crate) fn read_verified_repository_body_bytes(
|
|||
basis: &RepositoryBodyObservationBasis,
|
||||
relative_path: &str,
|
||||
) -> Result<VerifiedRepositoryBodyBytes> {
|
||||
let manifest = authenticated_repository_body_manifest(runtime_store, basis)?;
|
||||
RepositoryBodyReadSession::open(runtime_store, basis)?.read_regular_file(relative_path)
|
||||
}
|
||||
|
||||
fn read_verified_repository_body_bytes_from_session(
|
||||
session: &RepositoryBodyReadSession,
|
||||
relative_path: &str,
|
||||
) -> Result<VerifiedRepositoryBodyBytes> {
|
||||
validate_portable_relative_path(relative_path)?;
|
||||
let entry = manifest
|
||||
let entry = session
|
||||
.manifest
|
||||
.entries
|
||||
.iter()
|
||||
.find(|entry| entry.path == relative_path)
|
||||
|
|
@ -379,19 +527,8 @@ pub(crate) fn read_verified_repository_body_bytes(
|
|||
bail!("historical Body entry {relative_path:?} is not an authenticated regular file");
|
||||
}
|
||||
|
||||
let route = runtime_repository_body_store_binding(runtime_store)?
|
||||
.ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?;
|
||||
let entries = load_body_envelopes(Path::new(&route.body_store_path))?;
|
||||
let binding: RepositoryBodyBinding = decode(
|
||||
find(&entries, BODY_BINDING_TYPE, BODY_BINDING_KEY)
|
||||
.ok_or_else(|| anyhow!("runtime repository Body store has no Body binding"))?,
|
||||
)?;
|
||||
let root = std::fs::canonicalize(&binding.git_top_level)
|
||||
.context("bound repository root is missing")?;
|
||||
if root != PathBuf::from(&binding.git_top_level) {
|
||||
bail!("bound repository root is no longer canonical");
|
||||
}
|
||||
let path = safe_worktree_path(&root, relative_path)?;
|
||||
let root = &session.root;
|
||||
let path = safe_worktree_path(root, relative_path)?;
|
||||
reject_reparse_or_symlink_components(&root, relative_path)?;
|
||||
let resolved = std::fs::canonicalize(&path)
|
||||
.with_context(|| format!("historical Body path {relative_path:?} is missing"))?;
|
||||
|
|
@ -405,6 +542,8 @@ pub(crate) fn read_verified_repository_body_bytes(
|
|||
if !before.file_type().is_file() || metadata_is_reparse_point(&before) {
|
||||
bail!("historical Body path {relative_path:?} is no longer a regular file");
|
||||
}
|
||||
#[cfg(test)]
|
||||
BODY_FILE_READS.set(BODY_FILE_READS.get() + 1);
|
||||
let bytes = std::fs::read(&path)
|
||||
.with_context(|| format!("cannot read historical Body path {relative_path:?}"))?;
|
||||
let after = std::fs::symlink_metadata(&path)?;
|
||||
|
|
@ -989,6 +1128,8 @@ fn require_id(name: &str, value: &str) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
fn load_body_envelopes(store: &Path) -> Result<Vec<CultCacheEnvelope>> {
|
||||
#[cfg(test)]
|
||||
BODY_STORE_LOADS.set(BODY_STORE_LOADS.get() + 1);
|
||||
if !store.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
|
@ -1355,6 +1496,101 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn persisted_current_basis_load_is_read_only_and_does_not_scan() -> Result<()> {
|
||||
let d = repo()?;
|
||||
let state = tempfile::tempdir()?;
|
||||
let (store, runtime) = bound(d.path(), state.path(), "loaded", "runtime", "swarm")?;
|
||||
write(&d.path().join("tracked.txt"), "one")?;
|
||||
run(d.path(), &["add", "."])?;
|
||||
let observed = observe_runtime_repository_body_basis(&runtime)?;
|
||||
let before = std::fs::read(&store)?;
|
||||
|
||||
write(&d.path().join("tracked.txt"), "two")?;
|
||||
let first = load_current_runtime_repository_body_basis(&runtime)?;
|
||||
let second = load_current_runtime_repository_body_basis(&runtime)?;
|
||||
assert_eq!(first, observed);
|
||||
assert_eq!(second, observed);
|
||||
assert_eq!(std::fs::read(&store)?, before);
|
||||
|
||||
let advanced = observe_runtime_repository_body_basis(&runtime)?;
|
||||
assert!(advanced.generation > observed.generation);
|
||||
assert_ne!(advanced.manifest_root_sha256, observed.manifest_root_sha256);
|
||||
assert_eq!(
|
||||
load_current_runtime_repository_body_basis(&runtime)?,
|
||||
advanced
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn persisted_current_basis_refuses_substituted_runtime_route() -> Result<()> {
|
||||
let first_repo = repo()?;
|
||||
let first_state = tempfile::tempdir()?;
|
||||
let (_, first_runtime) = bound(
|
||||
first_repo.path(),
|
||||
first_state.path(),
|
||||
"first",
|
||||
"first-runtime",
|
||||
"first-swarm",
|
||||
)?;
|
||||
write(&first_repo.path().join("first.txt"), "first")?;
|
||||
observe_runtime_repository_body_basis(&first_runtime)?;
|
||||
|
||||
let second_repo = repo()?;
|
||||
let second_state = tempfile::tempdir()?;
|
||||
let (_, second_runtime) = bound(
|
||||
second_repo.path(),
|
||||
second_state.path(),
|
||||
"second",
|
||||
"second-runtime",
|
||||
"second-swarm",
|
||||
)?;
|
||||
write(&second_repo.path().join("second.txt"), "second")?;
|
||||
observe_runtime_repository_body_basis(&second_runtime)?;
|
||||
let substituted = runtime_repository_body_store_binding(&second_runtime)?.unwrap();
|
||||
|
||||
let backing = SingleFileMessagePackBackingStore::new(&first_runtime);
|
||||
let opening = backing.pull_all()?;
|
||||
let original = find(
|
||||
&opening,
|
||||
RUNTIME_BODY_STORE_BINDING_TYPE,
|
||||
RUNTIME_BODY_STORE_BINDING_KEY,
|
||||
)
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert!(backing.compare_and_swap_batch(
|
||||
&[original],
|
||||
vec![envelope(
|
||||
RUNTIME_BODY_STORE_BINDING_TYPE,
|
||||
RUNTIME_BODY_STORE_BINDING_KEY,
|
||||
&substituted,
|
||||
)?],
|
||||
)?);
|
||||
assert!(load_current_runtime_repository_body_basis(&first_runtime).is_err());
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn persisted_current_basis_refuses_substituted_body_binding() -> Result<()> {
|
||||
let d = repo()?;
|
||||
let state = tempfile::tempdir()?;
|
||||
let (store, runtime) = bound(d.path(), state.path(), "body", "runtime", "swarm")?;
|
||||
write(&d.path().join("tracked.txt"), "body")?;
|
||||
observe_runtime_repository_body_basis(&runtime)?;
|
||||
|
||||
let backing = SingleFileMessagePackBackingStore::new(&store);
|
||||
let opening = backing.pull_all()?;
|
||||
let original = find(&opening, BODY_BINDING_TYPE, BODY_BINDING_KEY)
|
||||
.unwrap()
|
||||
.clone();
|
||||
let mut substituted: RepositoryBodyBinding = decode(&original)?;
|
||||
substituted.workspace_id = "attacker-workspace".into();
|
||||
assert!(backing.compare_and_swap_batch(
|
||||
&[original],
|
||||
vec![envelope(BODY_BINDING_TYPE, BODY_BINDING_KEY, &substituted)?],
|
||||
)?);
|
||||
assert!(load_current_runtime_repository_body_basis(&runtime).is_err());
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn coverage_obligation_refuses_manifest_entries_substituted_under_declared_root() -> Result<()>
|
||||
{
|
||||
let d = repo()?;
|
||||
|
|
|
|||
|
|
@ -30,6 +30,18 @@ pub(crate) struct OllamaConfig {
|
|||
pub(crate) query_instruction: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct OllamaModelArtifact {
|
||||
pub(crate) tag: String,
|
||||
pub(crate) digest: String,
|
||||
}
|
||||
|
||||
impl OllamaModelArtifact {
|
||||
pub(crate) fn canonical_identity(&self) -> String {
|
||||
format!("{}@{}", self.tag, self.digest)
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact identity of a managed semantic projection.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
|
|
@ -60,6 +72,7 @@ pub(crate) struct SemanticCandidate<P> {
|
|||
pub(crate) struct SemanticStoredPoint<P> {
|
||||
pub(crate) id: String,
|
||||
pub(crate) payload: Option<P>,
|
||||
pub(crate) vector: Option<Vec<f32>>,
|
||||
}
|
||||
|
||||
pub(crate) struct QdrantBackend {
|
||||
|
|
@ -167,6 +180,31 @@ impl QdrantBackend {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes only the exact managed projection named by `contract`.
|
||||
/// Absence is already the retired state; incompatible metadata is never
|
||||
/// overwritten or deleted merely because its name collides.
|
||||
pub(crate) fn retire_exact_collection(
|
||||
&self,
|
||||
name: &str,
|
||||
contract: &CollectionCompatibility,
|
||||
) -> Result<()> {
|
||||
if !self.collection_exists(name)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.collection_compatibility(name)? != *contract {
|
||||
anyhow::bail!("refusing to retire Qdrant collection {name} with incompatible metadata");
|
||||
}
|
||||
let response = self
|
||||
.client
|
||||
.delete(format!("{}/collections/{name}", self.base_url))
|
||||
.query(&[("timeout", self.timeout_seconds)])
|
||||
.send()
|
||||
.with_context(|| format!("failed to retire Qdrant collection {name}"))?;
|
||||
parse_response::<bool>(response)
|
||||
.with_context(|| format!("failed to decode Qdrant retirement response for {name}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn upsert_points<P: Serialize>(
|
||||
&self,
|
||||
name: &str,
|
||||
|
|
@ -317,7 +355,7 @@ impl QdrantBackend {
|
|||
"limit": POINT_BATCH_SIZE,
|
||||
"offset": offset,
|
||||
"with_payload": true,
|
||||
"with_vector": false,
|
||||
"with_vector": true,
|
||||
}))
|
||||
.send()
|
||||
.with_context(|| format!("failed to observe Qdrant scope in {name}"))?;
|
||||
|
|
@ -331,6 +369,7 @@ impl QdrantBackend {
|
|||
.map(|point| SemanticStoredPoint {
|
||||
id: point.id,
|
||||
payload: point.payload,
|
||||
vector: point.vector,
|
||||
}),
|
||||
);
|
||||
offset = envelope.result.next_page_offset;
|
||||
|
|
@ -378,6 +417,43 @@ impl OllamaEmbedder {
|
|||
Ok(embeddings)
|
||||
}
|
||||
|
||||
/// Resolves the configured mutable Ollama tag to the immutable artifact
|
||||
/// digest currently installed behind it. Projection identity must use this
|
||||
/// value; embedding requests continue to use the configured tag.
|
||||
pub(crate) fn model_artifact(&self) -> Result<OllamaModelArtifact> {
|
||||
let response = self
|
||||
.client
|
||||
.get(format!("{}/api/tags", self.base_url))
|
||||
.send()
|
||||
.with_context(|| format!("failed to inspect Ollama models at {}", self.base_url))?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
let body = response.text().unwrap_or_default();
|
||||
anyhow::bail!("Ollama model inspection failed with {status}: {body}");
|
||||
}
|
||||
let tags: OllamaTagsResponse = response.json().with_context(|| {
|
||||
format!("failed to decode Ollama model tags from {}", self.base_url)
|
||||
})?;
|
||||
let mut matches = tags
|
||||
.models
|
||||
.into_iter()
|
||||
.filter(|candidate| candidate.name == self.model || candidate.model == self.model)
|
||||
.collect::<Vec<_>>();
|
||||
if matches.len() != 1 {
|
||||
anyhow::bail!(
|
||||
"configured Ollama model {} resolved to {} installed artifacts",
|
||||
self.model,
|
||||
matches.len()
|
||||
);
|
||||
}
|
||||
let candidate = matches.pop().expect("validated one artifact");
|
||||
let digest = normalize_ollama_digest(&candidate.digest)?;
|
||||
Ok(OllamaModelArtifact {
|
||||
tag: self.model.clone(),
|
||||
digest,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn embed_query(&self, query: &str) -> Result<Vec<f32>> {
|
||||
let formatted = format!("Instruct: {}\nQuery: {}", self.query_instruction, query);
|
||||
let mut embeddings = self.embed_batch(&[formatted])?;
|
||||
|
|
@ -385,6 +461,26 @@ impl OllamaEmbedder {
|
|||
Ok(embeddings.pop().expect("validated one embedding"))
|
||||
}
|
||||
|
||||
pub(crate) fn embedding_dimensions(&self) -> Result<u32> {
|
||||
const DIMENSION_PROBE: &str = "epiphany embedding dimension probe v0";
|
||||
|
||||
let embeddings = self.embed_batch(&[DIMENSION_PROBE.to_string()])?;
|
||||
if embeddings.len() != 1 {
|
||||
anyhow::bail!(
|
||||
"Ollama dimension probe returned {} vectors instead of one",
|
||||
embeddings.len()
|
||||
);
|
||||
}
|
||||
let vector = &embeddings[0];
|
||||
if vector.is_empty() {
|
||||
anyhow::bail!("Ollama dimension probe returned an empty vector");
|
||||
}
|
||||
if vector.iter().any(|value| !value.is_finite()) {
|
||||
anyhow::bail!("Ollama dimension probe returned a non-finite value");
|
||||
}
|
||||
u32::try_from(vector.len()).context("Ollama embedding dimensions exceed u32")
|
||||
}
|
||||
|
||||
fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
|
||||
let response = self
|
||||
.client
|
||||
|
|
@ -501,12 +597,34 @@ struct PayloadScrollResult<P> {
|
|||
struct PayloadScrollPoint<P> {
|
||||
id: String,
|
||||
payload: Option<P>,
|
||||
vector: Option<Vec<f32>>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct EmbedResponse {
|
||||
embeddings: Option<Vec<Vec<f32>>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct OllamaTagsResponse {
|
||||
models: Vec<OllamaTag>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OllamaTag {
|
||||
name: String,
|
||||
model: String,
|
||||
digest: String,
|
||||
}
|
||||
|
||||
fn normalize_ollama_digest(value: &str) -> Result<String> {
|
||||
let hex = value.strip_prefix("sha256:").unwrap_or(value);
|
||||
if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
anyhow::bail!("Ollama model artifact digest is not a SHA-256 digest");
|
||||
}
|
||||
Ok(format!("sha256:{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
fn parse_response<T: DeserializeOwned>(response: Response) -> Result<Envelope<T>> {
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
|
|
@ -524,3 +642,81 @@ fn normalize_base_url(value: &str) -> String {
|
|||
fn timeout_seconds(timeout_ms: u64) -> u64 {
|
||||
timeout_ms.div_ceil(1000).max(1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wiremock::matchers::{method, path};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
fn embedder(base_url: String, model: &str) -> Result<OllamaEmbedder> {
|
||||
OllamaEmbedder::new(OllamaConfig {
|
||||
base_url,
|
||||
model: model.into(),
|
||||
timeout_ms: 5_000,
|
||||
query_instruction: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_model_identity_is_bound_to_exact_installed_digest() -> Result<()> {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
let server_a = runtime.block_on(MockServer::start());
|
||||
let server_b = runtime.block_on(MockServer::start());
|
||||
for (server, digest) in [(&server_a, "aa".repeat(32)), (&server_b, "bb".repeat(32))] {
|
||||
runtime.block_on(
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/tags"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"models": [{
|
||||
"name": "nomic-embed-text:latest",
|
||||
"model": "nomic-embed-text:latest",
|
||||
"digest": digest
|
||||
}]
|
||||
})))
|
||||
.mount(server),
|
||||
);
|
||||
}
|
||||
let identity_a = embedder(server_a.uri(), "nomic-embed-text:latest")?
|
||||
.model_artifact()?
|
||||
.canonical_identity();
|
||||
let identity_b = embedder(server_b.uri(), "nomic-embed-text:latest")?
|
||||
.model_artifact()?
|
||||
.canonical_identity();
|
||||
assert_ne!(identity_a, identity_b);
|
||||
assert_eq!(
|
||||
identity_a,
|
||||
format!("nomic-embed-text:latest@sha256:{}", "aa".repeat(32))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_model_identity_refuses_absent_ambiguous_and_invalid_digest() -> Result<()> {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
for models in [
|
||||
json!([]),
|
||||
json!([
|
||||
{"name":"m","model":"m","digest":"aa".repeat(32)},
|
||||
{"name":"m","model":"m","digest":"bb".repeat(32)}
|
||||
]),
|
||||
json!([{"name":"m","model":"m","digest":"not-a-digest"}]),
|
||||
] {
|
||||
let server = runtime.block_on(MockServer::start());
|
||||
runtime.block_on(
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/api/tags"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(json!({"models": models})),
|
||||
)
|
||||
.mount(&server),
|
||||
);
|
||||
assert!(embedder(server.uri(), "m")?.model_artifact().is_err());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
407
epiphany-core/src/workspace_coverage_projector_service.rs
Normal file
407
epiphany-core/src/workspace_coverage_projector_service.rs
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
use crate::repository_body_observer::RepositoryBodyReadSession;
|
||||
use crate::semantic_backend::{OllamaConfig, OllamaEmbedder, QdrantBackend, QdrantConfig};
|
||||
use crate::workspace_coverage_projector::{
|
||||
WorkspaceCoverageAcquireResult, WorkspaceCoverageCurrentState,
|
||||
acquire_workspace_coverage_projection, classify_current_workspace_coverage,
|
||||
execute_workspace_coverage_projection, prepare_workspace_coverage_projection,
|
||||
retire_workspace_coverage_collections,
|
||||
};
|
||||
use crate::{
|
||||
EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID, load_current_runtime_repository_body_basis,
|
||||
runtime_repository_body_store_binding,
|
||||
};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use sha2::{Digest, Sha256};
|
||||
#[cfg(windows)]
|
||||
use std::ffi::OsStr;
|
||||
#[cfg(unix)]
|
||||
use std::fs::File;
|
||||
#[cfg(unix)]
|
||||
use std::os::fd::AsRawFd;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(windows)]
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GetLastError, HANDLE};
|
||||
#[cfg(windows)]
|
||||
use windows_sys::Win32::System::Threading::{CreateMutexW, ReleaseMutex};
|
||||
|
||||
const EMBEDDING_PROVIDER_ID: &str = "gamecult-ollama-embedding";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WorkspaceCoverageProjectorConfig {
|
||||
pub qdrant_url: String,
|
||||
pub qdrant_api_key: Option<String>,
|
||||
pub qdrant_timeout_ms: u64,
|
||||
pub ollama_base_url: String,
|
||||
pub ollama_model: String,
|
||||
pub ollama_timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl WorkspaceCoverageProjectorConfig {
|
||||
pub fn from_env() -> Self {
|
||||
let semantic = crate::MemorySemanticIndexConfig::from_env();
|
||||
Self {
|
||||
qdrant_url: semantic.qdrant_url,
|
||||
qdrant_api_key: semantic.qdrant_api_key,
|
||||
qdrant_timeout_ms: semantic.qdrant_timeout_ms,
|
||||
ollama_base_url: semantic.ollama_base_url,
|
||||
ollama_model: semantic.ollama_model,
|
||||
ollama_timeout_ms: semantic.ollama_timeout_ms,
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<()> {
|
||||
for (label, value) in [
|
||||
("Qdrant URL", self.qdrant_url.as_str()),
|
||||
("Ollama base URL", self.ollama_base_url.as_str()),
|
||||
("Ollama model", self.ollama_model.as_str()),
|
||||
] {
|
||||
if value.trim().is_empty() {
|
||||
bail!("workspace coverage projector requires a non-empty {label}");
|
||||
}
|
||||
}
|
||||
if self.qdrant_timeout_ms == 0 || self.ollama_timeout_ms == 0 {
|
||||
bail!("workspace coverage projector timeouts must be positive");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WorkspaceCoverageProjectorPulseStatus {
|
||||
Idle,
|
||||
Executed,
|
||||
Contended,
|
||||
Refused,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WorkspaceCoverageProjectorServicePulse {
|
||||
pub status: WorkspaceCoverageProjectorPulseStatus,
|
||||
pub body_observation_id: Option<String>,
|
||||
pub body_generation: Option<u64>,
|
||||
pub plan_id: Option<String>,
|
||||
pub receipt_id: Option<String>,
|
||||
pub fault: Option<String>,
|
||||
}
|
||||
|
||||
struct WorkspaceCoverageProjectorSingletonGuard {
|
||||
#[cfg(windows)]
|
||||
handle: HANDLE,
|
||||
#[cfg(unix)]
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl Drop for WorkspaceCoverageProjectorSingletonGuard {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(windows)]
|
||||
unsafe {
|
||||
let _ = ReleaseMutex(self.handle);
|
||||
CloseHandle(self.handle);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
let _ = libc::flock(self.file.as_raw_fd(), libc::LOCK_UN);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_workspace_coverage_projector_singleton(
|
||||
runtime_store: &Path,
|
||||
body_store: &Path,
|
||||
) -> Result<WorkspaceCoverageProjectorSingletonGuard> {
|
||||
let identity = format!(
|
||||
"{:x}",
|
||||
Sha256::digest(
|
||||
format!(
|
||||
"{}|{}",
|
||||
runtime_store.to_string_lossy().to_lowercase(),
|
||||
body_store.to_string_lossy().to_lowercase()
|
||||
)
|
||||
.as_bytes()
|
||||
)
|
||||
);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let name = OsStr::new(&format!(
|
||||
"Global\\EpiphanyWorkspaceCoverageProjector-{identity}"
|
||||
))
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let handle = unsafe { CreateMutexW(std::ptr::null_mut(), 1, name.as_ptr()) };
|
||||
if handle.is_null() {
|
||||
return Err(anyhow!(
|
||||
"workspace coverage projector singleton mutex creation failed: {}",
|
||||
unsafe { GetLastError() }
|
||||
));
|
||||
}
|
||||
if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {
|
||||
unsafe { CloseHandle(handle) };
|
||||
bail!("workspace coverage projector owner already exists for this runtime Body route");
|
||||
}
|
||||
return Ok(WorkspaceCoverageProjectorSingletonGuard { handle });
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("epiphany-workspace-coverage-{identity}.lock"));
|
||||
let file = File::options()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)?;
|
||||
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
|
||||
bail!("workspace coverage projector owner already exists for this runtime Body route");
|
||||
}
|
||||
return Ok(WorkspaceCoverageProjectorSingletonGuard { file });
|
||||
}
|
||||
#[allow(unreachable_code)]
|
||||
Err(anyhow!(
|
||||
"workspace coverage projector singleton is unsupported on this platform"
|
||||
))
|
||||
}
|
||||
|
||||
pub struct WorkspaceCoverageProjectorServiceBody {
|
||||
_singleton: WorkspaceCoverageProjectorSingletonGuard,
|
||||
runtime_store: PathBuf,
|
||||
executor_incarnation: String,
|
||||
startup_lifecycle_receipt_id: String,
|
||||
embedder: OllamaEmbedder,
|
||||
qdrant: QdrantBackend,
|
||||
}
|
||||
|
||||
impl WorkspaceCoverageProjectorServiceBody {
|
||||
pub fn new(
|
||||
runtime_store: impl AsRef<Path>,
|
||||
runtime_id: impl Into<String>,
|
||||
config: WorkspaceCoverageProjectorConfig,
|
||||
executor_incarnation: impl Into<String>,
|
||||
startup_lifecycle_receipt_id: impl Into<String>,
|
||||
) -> Result<Self> {
|
||||
config.validate()?;
|
||||
let executor_incarnation = executor_incarnation.into();
|
||||
if executor_incarnation.trim().is_empty() {
|
||||
bail!("workspace coverage projector requires its executor incarnation");
|
||||
}
|
||||
let startup_lifecycle_receipt_id = startup_lifecycle_receipt_id.into();
|
||||
Uuid::parse_str(&startup_lifecycle_receipt_id)
|
||||
.context("workspace coverage projector requires its authenticated launch receipt id")?;
|
||||
let runtime_id = runtime_id.into();
|
||||
if runtime_id.trim().is_empty() {
|
||||
bail!("workspace coverage projector requires its CultMesh runtime id");
|
||||
}
|
||||
let runtime_store = runtime_store
|
||||
.as_ref()
|
||||
.canonicalize()
|
||||
.context("workspace coverage projector runtime store is missing")?;
|
||||
if !runtime_store.is_file() {
|
||||
bail!("workspace coverage projector runtime store is not a file");
|
||||
}
|
||||
let route = runtime_repository_body_store_binding(&runtime_store)?
|
||||
.ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?;
|
||||
if route.runtime_id != runtime_id {
|
||||
bail!(
|
||||
"workspace coverage projector runtime Body route disagrees with authenticated runtime id"
|
||||
);
|
||||
}
|
||||
let body_store = PathBuf::from(route.body_store_path);
|
||||
let singleton =
|
||||
acquire_workspace_coverage_projector_singleton(&runtime_store, &body_store)?;
|
||||
let qdrant = QdrantBackend::new(QdrantConfig {
|
||||
url: config.qdrant_url,
|
||||
api_key: config.qdrant_api_key,
|
||||
timeout_ms: config.qdrant_timeout_ms,
|
||||
})?;
|
||||
let embedder = OllamaEmbedder::new(OllamaConfig {
|
||||
base_url: config.ollama_base_url,
|
||||
model: config.ollama_model,
|
||||
timeout_ms: config.ollama_timeout_ms,
|
||||
query_instruction: String::new(),
|
||||
})?;
|
||||
Ok(Self {
|
||||
_singleton: singleton,
|
||||
runtime_store,
|
||||
executor_incarnation,
|
||||
startup_lifecycle_receipt_id,
|
||||
embedder,
|
||||
qdrant,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn provider_incarnation(&self) -> &str {
|
||||
&self.executor_incarnation
|
||||
}
|
||||
|
||||
pub fn startup_lifecycle_receipt_id(&self) -> &str {
|
||||
&self.startup_lifecycle_receipt_id
|
||||
}
|
||||
|
||||
pub fn pulse(&mut self) -> WorkspaceCoverageProjectorServicePulse {
|
||||
match self.pulse_inner() {
|
||||
Ok(pulse) => pulse,
|
||||
Err(_error) => WorkspaceCoverageProjectorServicePulse {
|
||||
status: WorkspaceCoverageProjectorPulseStatus::Refused,
|
||||
body_observation_id: None,
|
||||
body_generation: None,
|
||||
plan_id: None,
|
||||
receipt_id: None,
|
||||
// Managed stdout is an operator-safe projection. Raw backend
|
||||
// bodies and filesystem paths remain private to the process.
|
||||
fault: Some("workspace_coverage_pulse_refused".into()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn pulse_inner(&mut self) -> Result<WorkspaceCoverageProjectorServicePulse> {
|
||||
let route = runtime_repository_body_store_binding(&self.runtime_store)?
|
||||
.ok_or_else(|| anyhow!("runtime has no repository Body-store binding"))?;
|
||||
// Retirement is derived from typed Body history and is deliberately
|
||||
// performed before the idle fast path. Qdrant never nominates its own
|
||||
// garbage and incompatible same-name collections stop the pulse.
|
||||
retire_workspace_coverage_collections(&route.body_store_path, &mut self.qdrant)?;
|
||||
let basis = load_current_runtime_repository_body_basis(&self.runtime_store)?;
|
||||
// Tags are mutable. Re-resolve the installed artifact every pulse so a
|
||||
// same-dimensional model replacement cannot reuse an older index.
|
||||
let embedding_model_identity = self.embedder.model_artifact()?.canonical_identity();
|
||||
let dimensions = self.embedder.embedding_dimensions()?;
|
||||
if let WorkspaceCoverageCurrentState::Current(receipt) =
|
||||
classify_current_workspace_coverage(
|
||||
&self.runtime_store,
|
||||
&basis,
|
||||
EMBEDDING_PROVIDER_ID,
|
||||
&embedding_model_identity,
|
||||
dimensions,
|
||||
)?
|
||||
{
|
||||
return Ok(WorkspaceCoverageProjectorServicePulse {
|
||||
status: WorkspaceCoverageProjectorPulseStatus::Idle,
|
||||
body_observation_id: Some(basis.observation_id),
|
||||
body_generation: Some(basis.generation),
|
||||
plan_id: Some(receipt.plan_id.clone()),
|
||||
receipt_id: Some(receipt.receipt_id),
|
||||
fault: None,
|
||||
});
|
||||
}
|
||||
let body = RepositoryBodyReadSession::open(&self.runtime_store, &basis)?;
|
||||
let prepared = prepare_workspace_coverage_projection(
|
||||
&body,
|
||||
EMBEDDING_PROVIDER_ID,
|
||||
&embedding_model_identity,
|
||||
dimensions,
|
||||
)?;
|
||||
let plan_id = prepared.plan.plan_id.clone();
|
||||
match acquire_workspace_coverage_projection(
|
||||
&prepared,
|
||||
EPIPHANY_WORKSPACE_COVERAGE_PROJECTOR_DAEMON_ID,
|
||||
&self.executor_incarnation,
|
||||
&self.startup_lifecycle_receipt_id,
|
||||
)? {
|
||||
WorkspaceCoverageAcquireResult::Contended => {
|
||||
Ok(WorkspaceCoverageProjectorServicePulse {
|
||||
status: WorkspaceCoverageProjectorPulseStatus::Contended,
|
||||
body_observation_id: Some(basis.observation_id),
|
||||
body_generation: Some(basis.generation),
|
||||
plan_id: Some(plan_id),
|
||||
receipt_id: None,
|
||||
fault: None,
|
||||
})
|
||||
}
|
||||
WorkspaceCoverageAcquireResult::Current(receipt) => {
|
||||
Ok(WorkspaceCoverageProjectorServicePulse {
|
||||
status: WorkspaceCoverageProjectorPulseStatus::Idle,
|
||||
body_observation_id: Some(basis.observation_id),
|
||||
body_generation: Some(basis.generation),
|
||||
plan_id: Some(plan_id),
|
||||
receipt_id: Some(receipt.receipt_id),
|
||||
fault: None,
|
||||
})
|
||||
}
|
||||
WorkspaceCoverageAcquireResult::Acquired(acquisition) => {
|
||||
let receipt = execute_workspace_coverage_projection(
|
||||
&acquisition,
|
||||
&prepared,
|
||||
&self.embedder,
|
||||
&mut self.qdrant,
|
||||
)?;
|
||||
Ok(WorkspaceCoverageProjectorServicePulse {
|
||||
status: WorkspaceCoverageProjectorPulseStatus::Executed,
|
||||
body_observation_id: Some(basis.observation_id),
|
||||
body_generation: Some(basis.generation),
|
||||
plan_id: Some(plan_id),
|
||||
receipt_id: Some(receipt.receipt_id),
|
||||
fault: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config() -> WorkspaceCoverageProjectorConfig {
|
||||
WorkspaceCoverageProjectorConfig {
|
||||
qdrant_url: "http://127.0.0.1:6333".into(),
|
||||
qdrant_api_key: None,
|
||||
qdrant_timeout_ms: 1,
|
||||
ollama_base_url: "http://127.0.0.1:11434".into(),
|
||||
ollama_model: "test-model".into(),
|
||||
ollama_timeout_ms: 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_refuses_empty_endpoints_and_zero_timeouts() {
|
||||
let mut value = config();
|
||||
value.ollama_model.clear();
|
||||
assert!(value.validate().is_err());
|
||||
let mut value = config();
|
||||
value.qdrant_timeout_ms = 0;
|
||||
assert!(value.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constructor_requires_lifecycle_identity_before_touching_runtime() {
|
||||
assert!(
|
||||
WorkspaceCoverageProjectorServiceBody::new(
|
||||
"missing",
|
||||
"runtime",
|
||||
config(),
|
||||
"",
|
||||
"not-a-uuid"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
WorkspaceCoverageProjectorServiceBody::new(
|
||||
"missing",
|
||||
"runtime",
|
||||
config(),
|
||||
"incarnation",
|
||||
"not-a-uuid",
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn singleton_is_host_wide_for_one_canonical_runtime_body_pair() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let runtime = temp.path().join("runtime.ccmp");
|
||||
let body = temp.path().join("body.ccmp");
|
||||
std::fs::write(&runtime, [])?;
|
||||
std::fs::write(&body, [])?;
|
||||
let runtime = runtime.canonicalize()?;
|
||||
let body = body.canonicalize()?;
|
||||
let first = acquire_workspace_coverage_projector_singleton(&runtime, &body)?;
|
||||
assert!(acquire_workspace_coverage_projector_singleton(&runtime, &body).is_err());
|
||||
drop(first);
|
||||
assert!(acquire_workspace_coverage_projector_singleton(&runtime, &body).is_ok());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -142,6 +142,13 @@ pub struct WorkspaceCoveragePointBinding {
|
|||
pub payload_sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WorkspaceCoverageVectorBinding {
|
||||
pub point_id: String,
|
||||
pub vector_sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "gamecult.epiphany.workspace_coverage_projection_plan",
|
||||
|
|
@ -212,6 +219,8 @@ pub(crate) struct WorkspaceCoverageReceipt {
|
|||
pub claim_id: String,
|
||||
#[cultcache(key = 14)]
|
||||
pub claim_epoch: u64,
|
||||
#[cultcache(key = 15)]
|
||||
pub observed_vector_binding_set_sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
|
|
@ -251,7 +260,7 @@ pub(crate) fn derive_workspace_coverage_obligation(
|
|||
derive_workspace_coverage_obligation_from_authenticated_manifest(basis, &manifest, policy)
|
||||
}
|
||||
|
||||
fn derive_workspace_coverage_obligation_from_authenticated_manifest(
|
||||
pub(crate) fn derive_workspace_coverage_obligation_from_authenticated_manifest(
|
||||
basis: &RepositoryBodyObservationBasis,
|
||||
manifest: &RepositoryBodyManifest,
|
||||
policy: &WorkspaceCoveragePolicy,
|
||||
|
|
@ -533,6 +542,7 @@ pub(crate) fn validate_workspace_coverage_receipt(
|
|||
|| receipt.vector_dimensions != plan.vector_dimensions
|
||||
|| receipt.observed_at.trim().is_empty()
|
||||
|| receipt.observation_method != "qdrant_scroll_exact_point_bindings"
|
||||
|| !sha256_hex(&receipt.observed_vector_binding_set_sha256)
|
||||
{
|
||||
bail!("workspace coverage receipt lacks exact observed-index authority");
|
||||
}
|
||||
|
|
@ -794,6 +804,31 @@ mod tests {
|
|||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immutable_model_artifact_identity_changes_projection_plan() -> Result<()> {
|
||||
let obligation = coverage_obligation("obligation-model-artifact");
|
||||
let first = derive_workspace_coverage_projection_plan(
|
||||
&obligation,
|
||||
"projection-v0",
|
||||
"chunker-v0",
|
||||
"provider",
|
||||
&format!("model:latest@sha256:{}", "aa".repeat(32)),
|
||||
3,
|
||||
chunks(),
|
||||
)?;
|
||||
let second = derive_workspace_coverage_projection_plan(
|
||||
&obligation,
|
||||
"projection-v0",
|
||||
"chunker-v0",
|
||||
"provider",
|
||||
&format!("model:latest@sha256:{}", "bb".repeat(32)),
|
||||
3,
|
||||
chunks(),
|
||||
)?;
|
||||
assert_ne!(first.plan_id, second.plan_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipt_and_head_cannot_substitute_payload_or_claim_authority() -> Result<()> {
|
||||
let obligation = coverage_obligation("obligation-1");
|
||||
|
|
@ -828,6 +863,7 @@ mod tests {
|
|||
observed_point_binding_set_sha256: plan.point_binding_set_sha256.clone(),
|
||||
claim_id: claim_id.clone(),
|
||||
claim_epoch,
|
||||
observed_vector_binding_set_sha256: "55".repeat(32),
|
||||
};
|
||||
assert!(validate_workspace_coverage_receipt(&obligation, &plan, &receipt).is_ok());
|
||||
let mut head = WorkspaceCoverageHead {
|
||||
|
|
|
|||
|
|
@ -911,5 +911,33 @@ not abandonment authority. If Body advanced, recovery terminalizes the stale
|
|||
claim and lets normal acquisition derive a new plan; it never resurrects stale
|
||||
work.
|
||||
|
||||
### Dedicated service and exact semantic proof
|
||||
|
||||
The dedicated service is now a real reserved managed body, not a generic job.
|
||||
Its policy fixes the packaged sibling executable and exact runtime/Verse/
|
||||
Qdrant/Ollama arguments. Startup authenticates the policy-bound launch receipt,
|
||||
PID, executable hash, runtime identity, immutable Body-store route, and one
|
||||
host-wide singleton. Claims and attempts bind that executor incarnation and
|
||||
startup receipt.
|
||||
|
||||
Each pulse reloads only the persisted current Body basis, resolves the mutable
|
||||
Ollama tag to its installed artifact digest, and probes dimensions. An exact
|
||||
head/obligation/plan/receipt fast path returns Current without reading worktree
|
||||
files. Needed work opens one authenticated Body read session, verifies every
|
||||
eligible file and chunk, embeds only after claim acquisition, and observes both
|
||||
typed payloads and exact stored vectors. Receipt identity includes the vector-
|
||||
binding set; wrong, missing, nonfinite, or wrong-dimensional vectors cannot mint
|
||||
success. Body history derives retirement candidates for terminal non-current
|
||||
claim collections; current and running collections are preserved, and Qdrant
|
||||
deletion requires exact managed metadata.
|
||||
|
||||
Recovery is deliberately not present. A newer launch and ready heartbeat prove
|
||||
a successor exists, not that the old writer died. Honest recovery first needs a
|
||||
supervisor-owned termination observation bound to host+boot incarnation,
|
||||
process-instance identity, exact old launch/PID/executable/policy, and the old
|
||||
launch-correlated heartbeat/provider incarnation. The existing process observer
|
||||
collapses access failure/PID reuse too aggressively and cannot issue that proof.
|
||||
Timeouts remain inadmissible.
|
||||
|
||||
This map must change when ownership changes. Historical scars belong in git,
|
||||
evidence, or an explicitly archived note—not in the machine's Modeling state.
|
||||
|
|
|
|||
|
|
@ -1763,6 +1763,39 @@ managed policy, Qdrant contents, and process guesses are forbidden recovery
|
|||
authority. If Body advanced, terminalize the obsolete claim and acquire a fresh
|
||||
plan; never resurrect it.
|
||||
|
||||
## Dedicated workspace coverage service proof (2026-07-16)
|
||||
|
||||
The dedicated service, binary, reserved supervisor policy, and specialized
|
||||
CultMesh launch contract now exist. Generic policy and caller-selected command,
|
||||
workspace, Body store, collection, or dimensions are rejected. Launch receipt,
|
||||
PID, executable hash, runtime identity, immutable Body route, and host singleton
|
||||
are authenticated before projection.
|
||||
|
||||
The service resolves the configured Ollama tag to its installed immutable
|
||||
artifact digest on every pulse, probes its dimensions, and uses an exact Current
|
||||
fast path that reads no repository files. Needed projection uses one
|
||||
authenticated Body read session, verifies source bytes/chunks, embeds only after
|
||||
claim acquisition, whole-scrolls Qdrant payloads plus vectors, and binds exact
|
||||
point/payload/vector observations into the receipt before terminal CAS. Body
|
||||
history owns retirement of terminal non-current claim collections; deletion is
|
||||
metadata-gated and idempotent. Raw backend/filesystem errors no longer leak into
|
||||
the operator-safe pulse projection.
|
||||
|
||||
Proof: 424 library tests passed, one ignored; core and OpenAI runtime all-target
|
||||
checks passed. The ignored live smoke then passed against local Qdrant 1.17.1
|
||||
and Ollama `qwen3-embedding:0.6b` (artifact digest
|
||||
`ac6da0dfba84a81fdbfbaf330198c33cd77c4cdfc53e8bc50eb581914a15621d`,
|
||||
1024 dimensions), proved exact vector observation and Current classification,
|
||||
deleted its GUID-scoped collection, verified no coverage collection remained,
|
||||
and restored the preflight-stopped Qdrant container state.
|
||||
|
||||
Recovery remains absent on purpose. A newer launch plus ready heartbeat is not
|
||||
death evidence. Next build: strengthen native process observation with host+
|
||||
boot and process-instance identity, then let the supervisor publish one
|
||||
immutable termination observation bound to the exact old launch/PID/executable/
|
||||
policy/heartbeat/provider. Only that proof plus a current replacement launch may
|
||||
authorize one Body-store recovery CAS. Do not add timeout recovery.
|
||||
|
||||
The deployment next action is unchanged and permission-bound. Do not reboot
|
||||
without exact live operator approval. With that approval, run the real
|
||||
reboot/logon recovery proof already specified above.
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -2,8 +2,8 @@ experiment:
|
|||
name: EpiphanyAgent
|
||||
repository_body_observer: "Native Rust explicitly binds caller workspace ID to an existing validated runtime/swarm/source identity plus canonical Git root/object format/scope/policy. Bind also installs one immutable runtime-side RuntimeRepositoryBodyStoreBinding naming the canonical external Body-store locator and exact Body-binding hash; every read revalidates runtime/swarm/workspace/path/body identity and refuses a second store. Two equal sanitized temporary-index scans enumerate ignore-aware UTF-8 paths, Git modes, and nonrecursive gitlinks with global excludes disabled; raw regular bytes/lengths and non-followed symlink-target bytes are SHA-256 hashed. The domain-separated ordered raw manifest root, not the clean-filtered auxiliary tree OID, is authoritative Body identity. Every Git subprocess strips ambient repository/worktree/object/ref/index/namespace/replacement/graft/shallow and config-injection authority. Observe cannot mint identity. CultCache MessagePack atomically commits immutable manifest+observation and a manifest-root head by exact CAS. Canonical store-path checks precede writes; corrupt HEAD, sparse checkout, unsafe/unrepresentable paths, racing reads, and repo/runtime substitution fail closed. Only accepted stable observations persist; errors advance no head. Unchanged raw manifest preserves generation; status is read-pure. The observer owns bounded current-state identity, makes no historical continuity claim, and has no Ready field. The runtime route is locator authority only, not proof of model grounding."
|
||||
modeling_body_grounding: "Every coordinator-owned Modeling launch observes and carries one typed RepositoryBodyObservationBasis before worker thought. The immutable launch binds runtime/swarm/workspace/scope, Body-binding hash, observation generation/id/root, and scan interval. Modeling output contract v3 requires the exact worker-authored echo; ingress reloads the immutable launch and rejects missing/swapped basis, while non-Modeling cargo is forbidden. Mind admission review v1 and receipt v5 preserve that basis; admission validates exact launch/result/review equality plus the immutable historical Body artifacts, then copies it into the CAS receipt. Admission never samples current Body as a substitute. Direct Mind plan adoption and legacy migration remain explicitly ungrounded."
|
||||
workspace_retrieval_coverage: "The production-unwired retrieval.rs oracle was deleted. Legacy EpiphanyRetrievalState is presentation-only: clean Ready projects Missing and the indexing job is Unavailable/unowned. Native v0 coverage contracts load only an authenticated historical Repository Body manifest through the immutable runtime Body-store route, classify every ordered Body entry under a versioned bounded-regular-file policy, and seal Body binding/root/generation, policy, complete classification, projection/chunker/embedding identity, and the deterministic point/payload binding set. The crate-private projector now owns exact Qdrant execution and receipt/head publication, but remains production-unreachable pending authenticated service identity and abandoned-claim fencing. Query admission and the readiness join remain absent."
|
||||
workspace_coverage_projector: "The sealed projector is the only coverage writer and persists in the Repository Body CultCache store. Acquisition authenticates the exact current Body chain, verifies regular-file bytes, excludes empty/oversize/non-UTF-8 files, derives UTF-8-safe 96-line chunks with 8-line overlap, seals UUIDv5 point descriptors plus the ID-to-payload binding root, and CAS-installs immutable obligation/plan with one running claim/attempt. Execution validates every supplied text/vector against that plan, ensures an exact managed claim/epoch Qdrant collection, skips empty upserts, whole-scrolls typed payloads while rejecting cyclic offsets and duplicate/extra/missing/substituted points, and terminal-CAS publishes receipt/head only while Body, plan, claim, attempt, and the acquired prior coverage head remain exact. Failure terminalizes the exact attempt even after Body advance. The module remains production-unreachable: claims do not yet bind an authenticated executor incarnation/startup receipt, there is no current/no-op pulse classification or sealed text rematerialization surface, and abandoned claims cannot yet be fenced. The selected shell is a dedicated workspace-coverage projector service; it must use a reserved managed policy and latest launch-correlated ready heartbeat, never timeout, generic policy, Qdrant state, or caller strings, as recovery authority."
|
||||
workspace_retrieval_coverage: "The production-unwired retrieval.rs oracle is deleted. Legacy EpiphanyRetrievalState is presentation-only: clean Ready projects Missing and its indexing job is unavailable/unowned. Native coverage now binds an authenticated Repository Body manifest, exhaustive versioned inclusion policy, deterministic chunks/point payloads, immutable Ollama tag+artifact digest identity, vector dimensions, exact Qdrant point/payload/vector observations, and one terminal-CAS receipt/head. Query admission and the race-bounded repository readiness join remain absent; coverage success proves only this exact Body projection."
|
||||
workspace_coverage_projector: "The dedicated workspace-coverage projector is the only coverage writer. Its reserved supervisor/CultMesh policy fixes the packaged sibling binary and exact runtime/Verse/Qdrant/Ollama args; generic policy, arbitrary command, workspace, Body-store, collection, and dimension inputs are forbidden. The binary authenticates current policy-bound launch receipt, PID, executable hash, runtime id, and host singleton before the service derives the immutable Body route. One persisted Body basis plus one authenticated read session prepares verified UTF-8 chunks; an exact Current fast path reads no worktree files. Claims/attempts bind executor incarnation/startup receipt and reject malformed prior state. Every pulse re-resolves the mutable Ollama tag to its installed artifact digest, probes dimensions, embeds only after claim acquisition, writes an epoch-fenced managed Qdrant collection, whole-scrolls typed payloads and unnamed vectors, rejects cyclic offsets and duplicate/extra/missing/substituted/nonfinite/wrong-dimension/wrong-vector points, then terminal-CASes receipt/head against exact Body/plan/claim/prior-head authority. Body history owns bounded retirement of terminal non-current collections; running/current collections are preserved and deletion requires exact managed metadata. Managed stdout exposes only sanitized fault classes. Recovery is intentionally absent: newer launch plus heartbeat is not death proof. Before recovery, the supervisor/process observer must publish immutable host+boot+process-instance termination evidence bound to the exact old launch, PID, executable, policy, heartbeat, and provider incarnation. Query admission/readiness remain absent."
|
||||
repository_readiness_join: "Mind must own one race-bounded derived repository-readiness operation from exact authenticated authorities: freshly observe Body root R1, validate canonical RepoModel plus exact Mind admission and Body-grounding receipt, authenticated semantic projection eligibility for that admitted model, and workspace retrieval coverage bound to R1 and a named scope policy, then freshly observe R2 and require R2=R1. Its output is observed-ready-at with a truth interval ending at the second scan, not timeless Ready; later reads revalidate. A→B→A is harmless for content-addressed artifacts. Watcher/journal continuity and Hands receipts are invalidation triggers only. Legacy retrieval Ready/empty dirty paths, timestamps, watcher silence, Git OIDs, Qdrant existence, counts, and unrelated generations are forbidden substitutes."
|
||||
status: active
|
||||
phase: phase_6_reflection_boundary
|
||||
|
|
|
|||
|
|
@ -4,6 +4,49 @@ This file is disposable working memory for the current bounded subgoal.
|
|||
|
||||
## Current Subgoal
|
||||
|
||||
No active scratch subgoal. The Aetheria dogfood lesson, Bifrost cardinality
|
||||
trace, and artifact/schema correction are distilled into the canonical map,
|
||||
handoff, conceptual-substitution audit, evidence ledger, and git history.
|
||||
Make Body-bound workspace coverage operational without letting Qdrant, mutable
|
||||
model tags, process guesses, or service telemetry impersonate truth.
|
||||
|
||||
Landed checkpoint `aa6b3efe` proves sealed text/vector input validation, exact
|
||||
managed Qdrant metadata, whole-collection point/payload observation, and exact
|
||||
Body/plan/claim/prior-head terminal CAS. The following service work is still
|
||||
uncommitted and under hostile review.
|
||||
|
||||
Current authority map:
|
||||
|
||||
- Repository Body CultCache owns source observation, obligation, plan, claim,
|
||||
attempt, receipt, and coverage head.
|
||||
- The dedicated workspace-coverage projector owns one authenticated execution
|
||||
incarnation. Its fixed supervisor policy derives only runtime store, Verse,
|
||||
interval, Qdrant endpoint, and Ollama tag. It cannot accept workspace,
|
||||
Body-store, collection, dimensions, or arbitrary command authority.
|
||||
- Qdrant is disposable projection. Ollama is an embedding actuator. Neither can
|
||||
mint coverage state.
|
||||
- A claim must bind executor incarnation and startup receipt. Unknown or
|
||||
malformed claim/attempt state refuses overwrite.
|
||||
- Recovery is intentionally absent. A newer launch plus ready heartbeat does
|
||||
not prove the prior owner dead. Add supervisor-issued typed termination/death
|
||||
evidence bound to the prior launch before any recovery CAS exists.
|
||||
|
||||
Soul blockers found 2026-07-15:
|
||||
|
||||
1. Bind authenticated launch runtime id to the runtime Body route before any
|
||||
Body access. This hardening is now in the worktree.
|
||||
2. Observe and hash exact stored vectors, not only point IDs/payloads.
|
||||
3. Bind the plan to immutable Ollama model artifact digest, not mutable tag plus
|
||||
dimensions.
|
||||
4. Replace per-file full Body-store reloads with one authenticated read session
|
||||
and classify exact Current before rematerializing bytes.
|
||||
5. Give failed, fenced, and superseded claim collections an explicit retirement
|
||||
owner; claim/epoch isolation without GC leaks a collection per retry.
|
||||
6. Do not print raw chained backend/filesystem faults while claiming
|
||||
`privateStateExposed=false`; publish typed sanitized fault classes.
|
||||
|
||||
Local backend proof: Ollama is live at `127.0.0.1:11434` with
|
||||
`qwen3-embedding:0.6b`, digest
|
||||
`ac6da0dfba84a81fdbfbaf330198c33cd77c4cdfc53e8bc50eb581914a15621d`,
|
||||
1024 dimensions. Docker container `voidbot-qdrant` uses Qdrant 1.17.1 but is
|
||||
stopped. The hostile proof fixes passed; a real ignored smoke started Qdrant,
|
||||
projected through Ollama, exact-scroll-verified payloads and vectors, classified
|
||||
the result Current, deleted its isolated collection, verified no coverage
|
||||
collection remained, and stopped Qdrant again.
|
||||
|
|
|
|||
Reference in a new issue