use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rusty_agent_runtime::learn::{
surface_for_kind, CandidateContent, CandidateKind, EnvironmentTag,
};
use rusty_agent_runtime::middleware::{instantiate_composition, MiddlewareChain};
use rusty_agent_runtime::record::{sha256_hex, RunManifest};
use rusty_agent_runtime::registry::{
pointer_admission, resolution_pin, ArtifactRecord, ConfigResolution,
};
use serde::{Deserialize, Serialize};
use crate::error::ApiError;
use crate::server_store::ServerStore;
pub(crate) fn artifacts_dir(root: &Path) -> PathBuf {
root.join("registry").join("artifacts")
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ArtifactFile {
key: String,
record: ArtifactRecord,
}
fn artifact_file_name(scoped_key: &str) -> String {
sha256_hex(scoped_key.as_bytes())
}
pub(crate) async fn persist_artifact(
root: &Path,
scoped_key: &str,
record: &ArtifactRecord,
) -> io::Result<()> {
let dir = artifacts_dir(root);
tokio::fs::create_dir_all(&dir).await?;
let file = ArtifactFile {
key: scoped_key.to_string(),
record: record.clone(),
};
let bytes = serde_json::to_vec_pretty(&file)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let name = artifact_file_name(scoped_key);
let tmp = dir.join(format!("{name}.tmp"));
tokio::fs::write(&tmp, bytes).await?;
tokio::fs::rename(&tmp, dir.join(format!("{name}.json"))).await
}
fn collect_json_files(root: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(root) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_json_files(&path, out);
} else if path.extension().and_then(|e| e.to_str()) == Some("json") {
out.push(path);
}
}
}
pub(crate) fn load_artifacts(root: &Path) -> HashMap<String, ArtifactRecord> {
let dir = artifacts_dir(root);
let mut out = HashMap::new();
let mut files = Vec::new();
collect_json_files(&dir, &mut files);
for path in files {
let parsed = std::fs::read_to_string(&path)
.ok()
.and_then(|raw| serde_json::from_str::<ArtifactFile>(&raw).ok());
let matches_name = parsed.as_ref().is_some_and(|file| {
path.file_stem().and_then(|s| s.to_str()) == Some(&*artifact_file_name(&file.key))
});
match (parsed, matches_name) {
(Some(file), true) => {
out.insert(file.key, file.record);
}
_ => {
tracing::warn!(path = %path.display(), "skipping unreadable artifact file")
}
}
}
out
}
#[derive(Debug, Clone, Deserialize)]
pub struct RegistryArtifactRef {
pub family: CandidateKind,
pub name: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct RegistryRunBinding {
#[serde(default)]
pub environment: Option<EnvironmentTag>,
pub artifacts: Vec<RegistryArtifactRef>,
}
#[derive(Debug, Clone)]
pub struct RegistryAdmission {
pub resolutions: Vec<ConfigResolution>,
pub manifest: RunManifest,
pub middleware: Option<MiddlewareChain>,
}
pub(crate) async fn resolve_admission(
store: &Arc<dyn ServerStore>,
tenant: &str,
default_tag: Option<&EnvironmentTag>,
run_id: &str,
binding: &RegistryRunBinding,
) -> Result<RegistryAdmission, ApiError> {
if binding.artifacts.is_empty() {
return Err(ApiError::unprocessable(
"registry binding names no artifacts — a binding exists to bind; omit the field \
to run unbound"
.to_owned(),
));
}
let model_settings = binding
.artifacts
.iter()
.filter(|artifact| artifact.family == CandidateKind::ModelSettings)
.count();
if model_settings > 1 {
return Err(ApiError::unprocessable(format!(
"registry binding names {model_settings} `model_settings` artifacts — the \
manifest's `model` slot is singular; a run pins one model settings artifact"
)));
}
let middleware_compositions = binding
.artifacts
.iter()
.filter(|artifact| artifact.family == CandidateKind::MiddlewareComposition)
.count();
if middleware_compositions > 1 {
return Err(ApiError::unprocessable(format!(
"registry binding names {middleware_compositions} `middleware_composition` \
artifacts — a run serves one middleware chain; a second composition is a \
configuration error, not a merge"
)));
}
let mut seen = std::collections::HashSet::new();
for artifact in &binding.artifacts {
if !seen.insert((artifact.family, artifact.name.clone())) {
return Err(ApiError::unprocessable(format!(
"registry binding names `{}:{}` twice — one artifact binds one version; a \
second naming is a configuration error, not a second pin",
artifact.family.as_str(),
artifact.name
)));
}
}
let tag = binding.environment.clone().or_else(|| default_tag.cloned());
let internal = |e: String| ApiError::internal(format!("registry admission read: {e}"));
let mut resolutions = Vec::with_capacity(binding.artifacts.len());
let mut manifest = RunManifest::new();
let mut middleware = None;
for artifact in &binding.artifacts {
let surface = surface_for_kind(artifact.family, &artifact.name);
let target = match &tag {
Some(tag) => surface.tagged(tag),
None => surface.clone(),
};
let pointer = store
.get_version_pointer(tenant, target.as_str())
.await
.map_err(internal)?
.ok_or_else(|| {
ApiError::not_found(format!(
"artifact `{target}` has no version pointer — nothing was ever promoted \
for this environment; an unpromoted artifact is unresolvable"
))
})?;
let (candidate_id, slot) = pointer_admission(&pointer, run_id).ok_or_else(|| {
ApiError::not_found(format!(
"artifact `{target}` serves nothing — its pointer has no active version and \
this run's draw did not admit a canary"
))
})?;
let record = store
.get_candidate(tenant, candidate_id.as_str())
.await
.map_err(internal)?
.ok_or_else(|| {
ApiError::unprocessable(format!(
"artifact `{target}` points at candidate `{candidate_id}`, which the store \
does not hold — the registry record is corrupt; re-commit the candidate"
))
})?;
record.candidate.verify_address().map_err(|e| {
ApiError::unprocessable(format!(
"artifact `{target}` resolved to a candidate failing its own content address: \
{e} — the registry record is corrupt"
))
})?;
if record.candidate.surface() != surface {
return Err(ApiError::unprocessable(format!(
"artifact `{target}` resolved to a candidate surfacing at `{}` — the registry \
record is corrupt; the pointer and the candidate disagree",
record.candidate.surface()
)));
}
let (digest, model) = resolution_pin(&record.candidate)
.map_err(|e| ApiError::unprocessable(e.to_string()))?;
let mut layers = None;
manifest = match &record.candidate.content {
CandidateContent::Prompt { name, prompt } => {
manifest.pin_prompt(name.clone(), prompt.as_str())
}
CandidateContent::ToolContract { tool, schema } => {
manifest.pin_tool_schema(tool.clone(), schema)
}
CandidateContent::ModelSettings {
model, parameters, ..
} => manifest.pin_model(model.clone(), parameters),
CandidateContent::MiddlewareComposition {
layers: declared, ..
} => {
middleware = Some(instantiate_composition(declared).map_err(|e| {
ApiError::unprocessable(format!(
"artifact `{target}` resolved to a middleware composition the \
compiled-in vocabulary cannot instantiate: {e}"
))
})?);
layers = Some(
declared
.iter()
.map(|layer| layer.layer.clone())
.collect::<Vec<_>>(),
);
let value = serde_json::to_value(declared).map_err(|e| {
ApiError::unprocessable(format!(
"artifact `{target}` resolved to a middleware composition whose \
layer list does not serialize: {e}"
))
})?;
manifest.pin_middleware(&value)
}
_ => unreachable!("resolution_pin refused every other kind"),
};
resolutions.push(ConfigResolution {
surface,
tag: tag.clone(),
candidate_id,
pointer: slot,
digest,
model,
layers,
});
}
Ok(RegistryAdmission {
resolutions,
manifest,
middleware,
})
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{DateTime, Utc};
use rusty_agent_runtime::learn::CandidateKind;
use rusty_agent_runtime::memory::ProvenanceAuthor;
use rusty_agent_runtime::registry::ArtifactCommit;
fn ts(millis: i64) -> DateTime<Utc> {
DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
}
fn artifact() -> ArtifactRecord {
let mut record = ArtifactRecord::new(
CandidateKind::Prompt,
"system",
ProvenanceAuthor::Human {
human_id: "amjad".into(),
},
ts(1_760_000_000_000),
)
.unwrap();
record.commits.push(ArtifactCommit {
candidate_id: rusty_agent_runtime::learn::CandidateId::from("a".repeat(64)),
committed_at: ts(1_760_000_001_000),
});
record
}
#[tokio::test]
async fn artifacts_round_trip_through_hashed_filenames() {
let root =
std::env::temp_dir().join(format!("rusty-registry-test-{}", uuid::Uuid::new_v4()));
let artifact = artifact();
let scoped = format!("acme/{}", artifact.surface.as_str());
persist_artifact(&root, &scoped, &artifact).await.unwrap();
let listing: Vec<String> = std::fs::read_dir(artifacts_dir(&root))
.unwrap()
.flatten()
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(
listing,
vec![format!("{}.json", sha256_hex(scoped.as_bytes()))]
);
let loaded = load_artifacts(&root);
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[&scoped], artifact);
std::fs::write(
artifacts_dir(&root).join(format!("{}.json", sha256_hex(b"forged-name"))),
serde_json::to_vec_pretty(&ArtifactFile {
key: "prompt:other".into(),
record: artifact.clone(),
})
.unwrap(),
)
.unwrap();
let loaded = load_artifacts(&root);
assert_eq!(loaded.len(), 1, "the forged-name file is skipped");
let _ = std::fs::remove_dir_all(root);
}
}