artifactize-core 0.29.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Where an Artifact is declared: its target and the file that binds it. Moving a binding to
//! another file, or its target elsewhere, is a move; anything else about the file is not.
use super::*;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Site {
    pub path: Target,
    pub definition: PathBuf,
}
impl Site {
    /// Base of relative commands and inputs, not the definition's containing folder.
    pub fn folder(&self) -> &Path {
        folder_of(self.path.kind(), &self.path)
    }
    pub fn declaration_path(&self) -> PathBuf {
        self.definition.clone()
    }
}
pub(super) fn folder_of(kind: ArtifactKind, path: &Target) -> &Path {
    match kind {
        ArtifactKind::Folder | ArtifactKind::Aspect | ArtifactKind::Graph => {
            path.local().expect("filesystem kind")
        }
        ArtifactKind::File => path
            .local()
            .expect("filesystem kind")
            .parent()
            .unwrap_or(Path::new("")),
        ArtifactKind::Live => Path::new(""),
    }
}
/// Old locations are used only while migrating and when reading pre-migration saved Runs.
pub(super) fn declaration_of(kind: ArtifactKind, target: &Target) -> PathBuf {
    let path = target.local().unwrap_or(Path::new(""));
    match kind {
        ArtifactKind::Live => PathBuf::new(),
        ArtifactKind::Graph => PathBuf::from(".artf"),
        ArtifactKind::Folder => logical_join(path, std::ffi::OsStr::new(CONFIG_FILE)),
        ArtifactKind::File | ArtifactKind::Aspect => {
            let mut path = path.as_os_str().to_owned();
            path.push(".artf");
            PathBuf::from(path)
        }
    }
}

/// Names and files reached from recorded declarations, not a grant of access. Each file is
/// opened again and live declarations are resolved before the operation uses them.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DeclarationScope {
    names: BTreeSet<ArtifactName>,
    files: BTreeSet<LogicalPath>,
}

impl DeclarationScope {
    pub(crate) fn of<'a>(
        config: &RepoConfig,
        roots: impl IntoIterator<Item = &'a ArtifactName>,
    ) -> Self {
        Self::collect(roots.into_iter().cloned(), |name| {
            let artifact = config.artifacts.get(name)?;
            Some((imports(config, artifact), links(config, artifact)))
        })
    }

    fn collect(
        roots: impl IntoIterator<Item = ArtifactName>,
        mut entry: impl FnMut(&ArtifactName) -> Option<(BTreeSet<LogicalPath>, BTreeSet<ArtifactName>)>,
    ) -> Self {
        let mut scope = Self {
            names: BTreeSet::new(),
            files: BTreeSet::new(),
        };
        let mut pending: Vec<_> = roots.into_iter().collect();
        while let Some(name) = pending.pop() {
            if scope.names.insert(name.clone())
                && let Some((files, links)) = entry(&name)
            {
                scope.files.extend(files);
                pending.extend(links);
            }
        }
        scope
    }

    pub(crate) fn read(
        &self,
        repo: &Path,
        evals: Evals<'_>,
        environment: lang::Environment<'_>,
    ) -> Result<RepoConfig, ConfigError> {
        let files = self
            .files
            .iter()
            .map(|file| PathBuf::from(file.as_str()))
            .collect();
        let config = discovery::read_subset(repo, &self.names, &files, evals, environment)?;
        if let Some(name) = self
            .names
            .iter()
            .find(|name| !config.artifacts.contains_key(*name))
        {
            return Err(ConfigError::new(
                repo,
                format!("No recorded site still declares {name}."),
            ));
        }
        Ok(config)
    }
}

#[derive(Clone, Copy)]
pub(crate) enum Evals<'a> {
    All,
    One(&'a EvalId),
    None,
}

fn imports(config: &RepoConfig, artifact: &Artifact) -> BTreeSet<LogicalPath> {
    let from_program = config.program.as_ref().into_iter().flat_map(|program| {
        let items = &program.artifacts;
        items
            .binary_search_by(|item| item.name.as_str().cmp(artifact.name.as_str()))
            .ok()
            .into_iter()
            .flat_map(|at| &items[at].imports)
            .map(|&id| program.sources.file(id).path.as_path())
    });
    std::iter::once(artifact.definition.as_path())
        .chain(from_program)
        .filter_map(|path| crate::platform::path_text(path).parse().ok())
        .collect()
}

fn links(config: &RepoConfig, artifact: &Artifact) -> BTreeSet<ArtifactName> {
    use crate::scope::Argument;
    let agent = artifact
        .views
        .agent_tools
        .values()
        .filter_map(|tool| match tool {
            AgentTool::Command(command) => Some(command.args.as_slice()),
            _ => None,
        });
    let human = artifact
        .views
        .human_tools
        .values()
        .filter_map(|tool| match tool {
            HumanTool::Command(command) => Some(command.args.as_slice()),
            HumanTool::Builtin(builtin) => Some(builtin.args.as_slice()),
            HumanTool::Viewer(_) => None,
        });
    let fingerprint = match &artifact.fingerprint {
        Some(Fingerprint::Script { args, .. }) => Some(args.as_slice()),
        _ => None,
    };
    artifact
        .parts
        .iter()
        .chain(artifact.covering_part.iter())
        .cloned()
        .chain(
            agent
                .chain(human)
                .chain(fingerprint)
                .flatten()
                .filter_map(|argument| match argument {
                    Argument::Reference { name, .. } => config
                        .artifacts
                        .get_key_value(name.as_str())
                        .map(|(id, _)| id.clone()),
                    _ => None,
                }),
        )
        .collect()
}

#[derive(Debug, Clone)]
struct Indexed {
    site: Site,
    files: BTreeSet<LogicalPath>,
    links: BTreeSet<ArtifactName>,
    inputs: BTreeSet<ArtifactName>,
}

/// Compact per-name lookup built when a caller has already read the whole workspace. It
/// owns no syntax trees, instructions, tools or expanded declarations.
#[derive(Debug, Clone, Default)]
pub struct SiteIndex(BTreeMap<ArtifactName, Indexed>);

impl SiteIndex {
    pub fn read(repo: &Path) -> Result<Self, ConfigError> {
        let result = discovery::read_workspace_declarations(repo).map(|config| Self::new(&config));
        crate::platform::release_free_memory();
        result
    }

    pub(crate) fn new(config: &RepoConfig) -> Self {
        let mut entries: BTreeMap<_, _> = config
            .artifacts
            .iter()
            .map(|(id, artifact)| {
                (
                    id.clone(),
                    Indexed {
                        site: artifact.site(),
                        files: imports(config, artifact),
                        links: links(config, artifact),
                        inputs: BTreeSet::new(),
                    },
                )
            })
            .collect();
        for eval in &config.evals {
            entries
                .get_mut(&eval.target)
                .expect("eval target")
                .inputs
                .extend(eval.deps.iter().cloned());
        }
        Self(entries)
    }

    pub fn site(&self, name: &ArtifactName) -> Option<&Site> {
        self.0.get(name).map(|entry| &entry.site)
    }

    pub(crate) fn subset(
        &self,
        repo: &Path,
        roots: impl IntoIterator<Item = ArtifactName>,
        evals: Evals<'_>,
        environment: lang::Environment<'_>,
    ) -> Result<RepoConfig, ConfigError> {
        let scope = DeclarationScope::collect(roots, |name| {
            let entry = self.0.get(name)?;
            let mut links = entry.links.clone();
            if matches!(evals, Evals::All) {
                links.extend(entry.inputs.iter().cloned());
            }
            Some((entry.files.clone(), links))
        });
        let config = scope.read(repo, evals, environment)?;
        for (name, artifact) in &config.artifacts {
            check_site(&config, name, &self.0[name].site)
                .map_err(|error| ConfigError::new(repo, error))?;
            debug_assert_eq!(&artifact.name, name);
        }
        Ok(config)
    }
}

/// Where every Artifact of the project is declared now.
pub fn read_sites(repo: &Path) -> Result<BTreeMap<ArtifactName, Site>, ConfigError> {
    let config = discovery::read_workspace_declarations(repo)?;
    Ok(config
        .artifacts
        .into_iter()
        .map(|(name, artifact)| {
            let site = artifact.site();
            (name, site)
        })
        .collect())
}

#[derive(Debug, Error)]
pub enum ScopeReadError {
    #[error("{name} is no longer declared at {}.", crate::platform::path_text(.path))]
    Moved { name: ArtifactName, path: PathBuf },
    #[error(transparent)]
    Config(#[from] ConfigError),
}

fn check_site(config: &RepoConfig, name: &ArtifactName, site: &Site) -> Result<(), ScopeReadError> {
    if config
        .artifacts
        .get(name)
        .is_some_and(|artifact| artifact.site() == *site)
    {
        Ok(())
    } else {
        Err(ScopeReadError::Moved {
            name: name.clone(),
            path: site.declaration_path(),
        })
    }
}

pub(crate) fn read_artifact_scope(
    repo: &Path,
    name: &ArtifactName,
    site: &Site,
) -> Result<RepoConfig, ScopeReadError> {
    let mut config = discovery::read_workspace_declarations(repo)?;
    check_site(&config, name, site)?;
    config.evals.clear();
    Ok(config)
}

/// The project as declared now with only eval `id`, when every Artifact it reads is still
/// declared where `sites` says; none when the eval is no longer declared.
pub(crate) fn read_eval_scope(
    repo: &Path,
    id: &EvalId,
    sites: &BTreeMap<ArtifactName, Site>,
    saved: Option<&DeclarationScope>,
) -> Result<Option<RepoConfig>, ScopeReadError> {
    let legacy;
    let scope = match saved {
        Some(scope) => scope,
        None => {
            legacy = DeclarationScope {
                names: sites.keys().cloned().collect(),
                files: sites
                    .values()
                    .filter_map(|site| crate::platform::path_text(&site.definition).parse().ok())
                    .collect(),
            };
            &legacy
        }
    };
    let config = scope.read(repo, Evals::One(id), &lang::process_environment)?;
    for (name, site) in sites {
        check_site(&config, name, site)?;
    }
    Ok((!config.evals.is_empty()).then_some(config))
}

#[cfg(test)]
mod tests;