apoc 0.5.0

Agentic process control for LLMs
Documentation
//! Durable scoped environment definitions and secret-safe resolution.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::model::{
    EnvironmentEntry, EnvironmentGeneration, EnvironmentView, ExecutionSpec, RecipeScopeKind,
    SecretRef, now_ms,
};
use crate::recipe::recipe_scope;
use crate::store::Store;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ScopedEnvironment {
    pub(crate) scope_kind: RecipeScopeKind,
    pub(crate) scope_key: Option<String>,
    #[serde(default)]
    pub(crate) literals: BTreeMap<String, String>,
    #[serde(default)]
    pub(crate) secrets: BTreeMap<String, SecretRef>,
    pub(crate) generation: String,
    pub(crate) updated_at: u64,
}

impl ScopedEnvironment {
    pub(crate) fn empty(scope_kind: RecipeScopeKind, scope_key: Option<String>) -> Self {
        let mut value = Self {
            scope_kind,
            scope_key,
            literals: BTreeMap::new(),
            secrets: BTreeMap::new(),
            generation: String::new(),
            updated_at: now_ms(),
        };
        value.refresh_generation();
        value
    }

    pub(crate) fn refresh_generation(&mut self) {
        let portable = serde_json::json!({
            "literals": self.literals,
            "secrets": self.secrets,
        });
        let encoded = serde_json::to_vec(&portable).expect("environment definition serializes");
        self.generation = format!("sha256:{:x}", Sha256::digest(encoded));
        self.updated_at = now_ms();
    }

    fn provenance(&self) -> EnvironmentGeneration {
        EnvironmentGeneration {
            scope_kind: self.scope_kind,
            scope_key: self.scope_key.clone(),
            generation: self.generation.clone(),
        }
    }
}

pub(crate) fn selected_environment_scope(
    cwd: Option<&str>,
    global: bool,
) -> Result<(RecipeScopeKind, Option<String>), String> {
    if global {
        return Ok((RecipeScopeKind::Global, None));
    }
    let (kind, key) = recipe_scope(cwd);
    if key.is_none() {
        return Err("A local environment scope requires an invocation cwd".to_string());
    }
    Ok((kind, key))
}

pub(crate) fn validate_environment_name(name: &str) -> Result<(), String> {
    let mut characters = name.chars();
    let valid_first = characters
        .next()
        .is_some_and(|character| character == '_' || character.is_ascii_alphabetic());
    if !valid_first
        || !characters.all(|character| character == '_' || character.is_ascii_alphanumeric())
    {
        return Err(format!("Invalid environment variable name \"{name}\""));
    }
    Ok(())
}

pub(crate) fn effective_environment(
    store: &Store,
    cwd: Option<&str>,
) -> Result<Vec<ScopedEnvironment>, String> {
    let mut scopes = Vec::new();
    if let Some(global) = store.get_environment(RecipeScopeKind::Global, None)? {
        scopes.push(global);
    }
    let (kind, key) = recipe_scope(cwd);
    if key.is_some()
        && let Some(local) = store.get_environment(kind, key.as_deref())?
    {
        scopes.push(local);
    }
    Ok(scopes)
}

pub(crate) fn apply_environment(
    store: &Store,
    cwd: Option<&str>,
    spec: &mut ExecutionSpec,
) -> Result<(), String> {
    let explicit_literals = std::mem::take(&mut spec.env);
    let explicit_secrets = std::mem::take(&mut spec.secrets);
    let scopes = effective_environment(store, cwd)?;
    for scope in &scopes {
        merge_values(
            &mut spec.env,
            &mut spec.secrets,
            &scope.literals,
            &scope.secrets,
        );
    }
    merge_values(
        &mut spec.env,
        &mut spec.secrets,
        &explicit_literals,
        &explicit_secrets,
    );
    spec.environment_generations = scopes.iter().map(ScopedEnvironment::provenance).collect();
    Ok(())
}

fn merge_values(
    literals: &mut BTreeMap<String, String>,
    secrets: &mut BTreeMap<String, SecretRef>,
    next_literals: &BTreeMap<String, String>,
    next_secrets: &BTreeMap<String, SecretRef>,
) {
    for (name, value) in next_literals {
        secrets.remove(name);
        literals.insert(name.clone(), value.clone());
    }
    for (name, value) in next_secrets {
        literals.remove(name);
        secrets.insert(name.clone(), value.clone());
    }
}

pub(crate) fn environment_view(
    store: &Store,
    cwd: Option<&str>,
) -> Result<EnvironmentView, String> {
    let scopes = effective_environment(store, cwd)?;
    let mut visible = BTreeMap::<String, EnvironmentEntry>::new();
    for scope in &scopes {
        for name in scope.literals.keys() {
            visible.insert(
                name.clone(),
                EnvironmentEntry {
                    name: name.clone(),
                    kind: "literal".to_string(),
                    scope_kind: scope.scope_kind,
                    scope_key: scope.scope_key.clone(),
                    resolvable: true,
                    error_code: None,
                },
            );
        }
        for (name, secret) in &scope.secrets {
            let resolvable =
                secret.provider == "env" && std::env::var_os(&secret.reference).is_some();
            visible.insert(
                name.clone(),
                EnvironmentEntry {
                    name: name.clone(),
                    kind: "secret".to_string(),
                    scope_kind: scope.scope_kind,
                    scope_key: scope.scope_key.clone(),
                    resolvable,
                    error_code: (!resolvable).then(|| {
                        if secret.provider == "env" {
                            "SECRET_UNAVAILABLE"
                        } else {
                            "SECRET_PROVIDER_UNSUPPORTED"
                        }
                        .to_string()
                    }),
                },
            );
        }
    }
    Ok(EnvironmentView {
        entries: visible.into_values().collect(),
        generations: scopes.iter().map(ScopedEnvironment::provenance).collect(),
    })
}