//! Persisted project trust decisions (`SMH-SPEC-PLUG0001`, Project trust).
//!
//! Discovery receives a resolved decision only.
//! This store canonicalizes project paths before recording grants, so aliases
//! cannot receive independent authority.
use super::{Capability, NetScope, canonical_grants, canonical_net_scopes, native_path_identity};
use crate::wasm::SecretGrantConfig;
use smith::error::{ProviderFault, Result, SmithError};
use smith_ai::auth::CredentialKey;
use smith_ai::models::ProviderKind;
use std::io::Read;
use std::path::{Path, PathBuf};
const DECISIONS_FILE: &str = "project-trust.kdl";
const DECISIONS_BYTES_MAX: usize = 1024 * 1024;
/// Project trust decisions rooted at one Smith-owned directory.
pub struct TrustStore {
root: PathBuf,
}
impl TrustStore {
/// Create a trust store at an explicit Smith-owned directory.
#[must_use]
pub const fn at(root: PathBuf) -> Self {
Self { root }
}
/// Persist exactly these grants for a canonical project path.
///
/// # Errors
///
/// Returns a plugin fault when the project cannot be canonicalized or the
/// decision cannot be read or atomically replaced.
pub fn grant(&self, project: &Path, grants: &[Capability]) -> Result<()> {
self.grant_with_authority(project, grants, &[], &[])
}
/// Persist exactly these grants and network origins for a canonical project path.
///
/// # Errors
///
/// Returns a plugin fault when the project cannot be canonicalized or the
/// decision cannot be read or atomically replaced.
pub fn grant_with_net_scopes(
&self,
project: &Path,
grants: &[Capability],
net_scopes: &[NetScope],
) -> Result<()> {
self.grant_with_authority(project, grants, net_scopes, &[])
}
/// Persist exactly these grants, network origins, and secret authorities.
///
/// # Errors
///
/// Returns when project canonicalization or decision publication fails.
pub fn grant_with_authority(
&self,
project: &Path,
grants: &[Capability],
net_scopes: &[NetScope],
secret_grants: &[SecretGrantConfig],
) -> Result<()> {
let identity = project_identity(project)?;
let mut decisions = self.read()?;
let grants = canonical_grants(grants);
let net_scopes = canonical_net_scopes(net_scopes);
if let Some(decision) = decisions
.iter_mut()
.find(|decision| decision.identity == identity)
{
decision.grants = grants;
decision.net_scopes = net_scopes;
decision.secret_grants = secret_grants.to_vec();
} else {
decisions.push(Decision {
identity,
grants,
net_scopes,
secret_grants: secret_grants.to_vec(),
});
}
decisions.sort_by(|left, right| left.identity.cmp(&right.identity));
self.write(&decisions)
}
/// Resolve prior grants for one canonical project path.
///
/// `None` means trust remains unresolved and callers must not enumerate
/// package files.
///
/// # Errors
///
/// Returns a plugin fault when the project path or decision store is invalid.
pub fn decision(&self, project: &Path) -> Result