use sha2::{Digest, Sha256};
use crate::history::invocation_scope;
use crate::model::{InvocationScopeKind, Recipe, RecipePortableDefinition, RecipeScopeKind};
pub(crate) fn recipe_scope(cwd: Option<&str>) -> (RecipeScopeKind, Option<String>) {
let scope = invocation_scope(cwd);
match scope.kind {
InvocationScopeKind::GitWorktree => (RecipeScopeKind::GitWorktree, scope.key),
InvocationScopeKind::Cwd | InvocationScopeKind::Unknown => {
(RecipeScopeKind::Cwd, scope.key.or(scope.cwd))
}
}
}
pub(crate) fn recipe_storage_key(
kind: RecipeScopeKind,
scope_key: Option<&str>,
name: &str,
) -> Result<String, String> {
match kind {
RecipeScopeKind::Global => Ok(format!("global::{name}")),
RecipeScopeKind::GitWorktree | RecipeScopeKind::Cwd => {
let scope_key = scope_key.ok_or_else(|| "Local recipe scope is missing".to_string())?;
let digest = Sha256::digest(scope_key.as_bytes());
Ok(format!("{:?}:{digest:x}::{name}", kind).to_ascii_lowercase())
}
}
}
pub(crate) fn validate_recipe_name(name: &str) -> Result<(), String> {
if name.is_empty()
|| name.split('.').any(|segment| {
segment.is_empty()
|| !segment.chars().all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
})
})
{
return Err(format!(
"Recipe name \"{name}\" must use non-empty dot-separated alphanumeric, '-' or '_' segments"
));
}
Ok(())
}
pub(crate) fn recipe_generation(recipe: &Recipe) -> Result<String, String> {
let mut portable = serde_json::json!({
"name": recipe.name,
"description": recipe.description,
"code": recipe.code,
"input_schema": recipe.input_schema,
"output_schema": recipe.output_schema,
"dependencies": recipe.dependencies,
"annotations": recipe.annotations,
});
if !recipe.required_env.is_empty() {
portable["required_env"] = serde_json::json!(recipe.required_env);
}
let encoded = portable.to_string().into_bytes();
Ok(format!("sha256:{:x}", Sha256::digest(encoded)))
}
pub(crate) fn recipe_expired(recipe: &Recipe, now: u64) -> bool {
recipe
.expires_at
.is_some_and(|expires_at| expires_at <= now)
}
pub(crate) fn portable_recipe(recipe: &Recipe) -> RecipePortableDefinition {
RecipePortableDefinition {
name: recipe.name.clone(),
description: recipe.description.clone(),
code: recipe.code.clone(),
input_schema: recipe.input_schema.clone(),
output_schema: recipe.output_schema.clone(),
dependencies: recipe.dependencies.clone(),
required_env: recipe.required_env.clone(),
annotations: recipe.annotations.clone(),
generation: recipe.generation.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validates_dotted_names_and_rejects_empty_segments() {
assert!(validate_recipe_name("release.verify_logs").is_ok());
assert!(validate_recipe_name("release..logs").is_err());
assert!(validate_recipe_name("release logs").is_err());
}
#[test]
fn storage_keys_separate_scopes_and_generations_ignore_expiry() {
assert!(recipe_storage_key(RecipeScopeKind::Cwd, None, "logs").is_err());
let first = recipe_storage_key(RecipeScopeKind::Cwd, Some("/tmp/a"), "logs").unwrap();
let second = recipe_storage_key(RecipeScopeKind::Cwd, Some("/tmp/b"), "logs").unwrap();
assert_ne!(first, second);
let mut recipe = Recipe {
name: "logs".to_string(),
description: String::new(),
code: "return input;".to_string(),
input_schema: None,
output_schema: None,
dependencies: Vec::new(),
required_env: Vec::new(),
annotations: Default::default(),
scope_kind: RecipeScopeKind::Global,
scope_key: None,
generation: String::new(),
expires_at: Some(10),
last_used_at: None,
created_at: 1,
updated_at: 1,
origin_suggestion_id: None,
origin_recording_id: None,
};
let generation = recipe_generation(&recipe).unwrap();
recipe.expires_at = Some(20);
assert_eq!(generation, recipe_generation(&recipe).unwrap());
}
}