agentstacks 0.1.0

Core library of agentstacks: packs, tool extensions, plans, and the executor that applies them.
Documentation
//! Writes a [`Lockfile`] as `agentstacks.lock` text.
//!
//! Writing is a unit apart from reading because it is the inverse: it owns the fixed field order
//! and spacing that make the text stable, while the reader owns the refusals.
//!
//! # Responsibilities
//!
//! - [`write_lock`] returns the whole text: `api = 0`, a generated-file comment, then `[airsl]`
//!   when the lock records one and every `[[tool]]`, `[[pack]]` and `[[file]]` in the
//!   lock's stored order, which is already sorted. Tables are separated by one blank line and the
//!   text ends with one newline.
//! - Fields come in a fixed order: for a tool or pack `name`, `version`, then `git`, `tag`,
//!   `subdir`, `rev` or `path`, then `tree`; for a file `path`, `hash`, `by`. A `tag` or `subdir` that is absent is left out.
//! - Each key is padded with spaces to the longest key of its table, and each value is a basic
//!   string with `"`, `\` and control characters escaped.
//!
//! The text is formatted here rather than serialised from a raw TOML table, because a raw table is
//! sorted by key and would write the fields alphabetically.
//!
//! # Non-responsibilities
//!
//! Writing the text to disk belongs to the code that applies a plan; this function only builds the
//! string.

use std::fmt::{Display, Write as _};

use crate::types::lock::entry::locked::{LockedEntry, LockedSource};
use crate::types::lock::file::Lockfile;

/// The two lines every lock starts with.
const HEADER: &str = "api = 0\n# Generated by agentstacks. Do not edit.\n";

/// One key and its already-quoted value.
type Field = (&'static str, String);

/// The text of `lock`.
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// use agentstacks::types::{LockContents, Lockfile, write_lock};
///
/// // An empty lock is the header alone, and it reads back as an empty lock.
/// let lock = Lockfile::new(Path::new("agentstacks.lock"), LockContents::default())
///     .map_err(|refusals| format!("{refusals:?}"))?;
/// let text = write_lock(&lock);
/// assert_eq!(text, "api = 0\n# Generated by agentstacks. Do not edit.\n");
///
/// let reread = Lockfile::parse(Path::new("agentstacks.lock"), &text)
///     .map_err(|refusals| format!("{refusals:?}"))?;
/// assert_eq!(reread, lock);
/// # Ok::<(), String>(())
/// ```
#[must_use]
pub fn write_lock(lock: &Lockfile) -> String {
    let mut out = String::from(HEADER);
    if let Some(version) = lock.airsl() {
        push_table(
            &mut out,
            "[airsl]",
            &[("version", quote(&version.to_string()))],
        );
    }
    for tool in lock.tools() {
        push_table(&mut out, "[[tool]]", &entry_fields(tool));
    }
    for pack in lock.packs() {
        push_table(&mut out, "[[pack]]", &entry_fields(pack));
    }
    for file in lock.files() {
        push_table(
            &mut out,
            "[[file]]",
            &[
                ("path", quote(file.path().as_str())),
                ("hash", quote(&file.hash().to_string())),
                ("by", quote(file.by().as_str())),
            ],
        );
    }
    out
}

/// The fields of a tool or pack entry, in the order the lock writes them.
fn entry_fields<N: Display>(entry: &LockedEntry<N>) -> Vec<Field> {
    let mut fields = vec![
        ("name", quote(&entry.name().to_string())),
        ("version", quote(&entry.version().to_string())),
    ];
    match entry.source() {
        LockedSource::Git {
            url,
            tag,
            subdir,
            rev,
        } => {
            fields.push(("git", quote(url.as_str())));
            if let Some(tag) = tag {
                fields.push(("tag", quote(tag.as_str())));
            }
            if let Some(subdir) = subdir {
                fields.push(("subdir", quote(subdir.as_str())));
            }
            fields.push(("rev", quote(rev.as_str())));
        }
        LockedSource::Path(path) => fields.push(("path", quote(path.as_str()))),
    }
    fields.push(("tree", quote(&entry.tree().to_string())));
    fields
}

/// Appends a blank line, `header` and one line per field, keys padded to the longest.
fn push_table(out: &mut String, header: &str, fields: &[Field]) {
    let width = fields.iter().map(|(key, _)| key.len()).max().unwrap_or(0);
    out.push('\n');
    out.push_str(header);
    out.push('\n');
    for (key, value) in fields {
        let _ = writeln!(out, "{key:<width$} = {value}");
    }
}

/// `text` as a TOML basic string.
fn quote(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\r' => out.push_str("\\r"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            control if control.is_control() => {
                let _ = write!(out, "\\u{:04X}", u32::from(control));
            }
            plain => out.push(plain),
        }
    }
    out.push('"');
    out
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;
    use crate::types::lock::entry::written::FileEntry;
    use crate::types::lock::file::LockContents;
    use crate::types::lock::owner::Owner;
    use crate::types::lock::testing::{HEX40, HEX64, example_lock};
    use crate::types::manifest::PackVersion;
    use crate::types::name::PackName;
    use crate::types::name::ToolName;
    use crate::types::project::CommitId;
    use crate::types::project::GitUrl;
    use crate::types::project::LocalPath;
    use crate::types::project::SubPath;
    use crate::types::tree::ContentHash;

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    fn parsed(text: &str) -> Result<Lockfile, Box<dyn std::error::Error>> {
        Lockfile::parse(Path::new("agentstacks.lock"), text).map_err(|diagnostics| {
            let shown: Vec<String> = diagnostics
                .into_sorted()
                .iter()
                .map(ToString::to_string)
                .collect();
            shown.join("; ").into()
        })
    }

    fn hash() -> Result<ContentHash, Box<dyn std::error::Error>> {
        Ok(ContentHash::new(&format!("sha256:{HEX64}"))?)
    }

    fn git_pack(name: &str) -> Result<LockedEntry<PackName>, Box<dyn std::error::Error>> {
        Ok(LockedEntry::new(
            PackName::new(name)?,
            PackVersion::new("0.1.0")?,
            LockedSource::Git {
                url: GitUrl::new("https://example.org/r")?,
                tag: None,
                subdir: None,
                rev: CommitId::new(HEX40)?,
            },
            hash()?,
        ))
    }

    fn file(path: &str) -> Result<FileEntry, Box<dyn std::error::Error>> {
        Ok(FileEntry::new(
            SubPath::new(path)?,
            hash()?,
            Owner::new("core")?,
        ))
    }

    fn lock(
        packs: Vec<LockedEntry<PackName>>,
        files: Vec<FileEntry>,
    ) -> Result<Lockfile, Box<dyn std::error::Error>> {
        Lockfile::new(
            Path::new("agentstacks.lock"),
            LockContents {
                packs,
                files,
                ..LockContents::default()
            },
        )
        .map_err(|d| format!("{:?}", d.into_sorted()).into())
    }

    #[test]
    fn write_lock_reproduces_the_documented_example() -> TestResult {
        assert_eq!(write_lock(&parsed(&example_lock())?), example_lock());
        Ok(())
    }

    #[test]
    fn write_lock_round_trips_through_parse() -> TestResult {
        let original = parsed(&example_lock())?;
        let text = write_lock(&original);
        assert_eq!(text, write_lock(&original));

        let reread = parsed(&text)?;
        assert_eq!(reread, original);
        assert_eq!(write_lock(&reread), text);
        assert_eq!(
            reread.tools().first().map(|t| t.name().as_str()),
            Some("claude")
        );
        Ok(())
    }

    #[test]
    fn write_lock_starts_with_api_then_the_comment() -> TestResult {
        let with_airsl = write_lock(&parsed(&example_lock())?);
        let lines: Vec<&str> = with_airsl.lines().take(2).collect();
        assert_eq!(
            lines,
            ["api = 0", "# Generated by agentstacks. Do not edit."]
        );
        assert!(with_airsl.contains("\n[airsl]\nversion = \"0.1.4\"\n"));

        let without = write_lock(&lock(vec![git_pack("core")?], Vec::new())?);
        let lines: Vec<&str> = without.lines().take(2).collect();
        assert_eq!(
            lines,
            ["api = 0", "# Generated by agentstacks. Do not edit."]
        );
        assert!(!without.contains("[airsl]"));

        let empty = write_lock(&lock(Vec::new(), Vec::new())?);
        assert_eq!(empty, "api = 0\n# Generated by agentstacks. Do not edit.\n");
        Ok(())
    }

    #[test]
    fn write_lock_orders_fields_and_omits_absent_ones() -> TestResult {
        let path_pack = LockedEntry::new(
            PackName::new("team-lint")?,
            PackVersion::new("0.1.0")?,
            LockedSource::Path(LocalPath::new("packs/team-lint")?),
            hash()?,
        );
        let text = write_lock(&lock(vec![git_pack("core")?, path_pack], Vec::new())?);
        let expected = format!(
            "api = 0\n\
             # Generated by agentstacks. Do not edit.\n\
             \n\
             [[pack]]\n\
             name    = \"core\"\n\
             version = \"0.1.0\"\n\
             git     = \"https://example.org/r\"\n\
             rev     = \"{HEX40}\"\n\
             tree    = \"sha256:{HEX64}\"\n\
             \n\
             [[pack]]\n\
             name    = \"team-lint\"\n\
             version = \"0.1.0\"\n\
             path    = \"packs/team-lint\"\n\
             tree    = \"sha256:{HEX64}\"\n"
        );
        assert_eq!(text, expected);
        Ok(())
    }

    #[test]
    fn write_lock_sorts_entries() -> TestResult {
        let tools = vec![
            LockedEntry::new(
                ToolName::new("codex")?,
                PackVersion::new("1.0.0")?,
                LockedSource::Path(LocalPath::new("t/codex")?),
                hash()?,
            ),
            LockedEntry::new(
                ToolName::new("claude")?,
                PackVersion::new("1.0.0")?,
                LockedSource::Path(LocalPath::new("t/claude")?),
                hash()?,
            ),
        ];
        let lock = Lockfile::new(
            Path::new("agentstacks.lock"),
            LockContents {
                airsl: None,
                tools,
                packs: vec![git_pack("team-lint")?, git_pack("core")?],
                files: vec![file("b")?, file("a")?],
            },
        )
        .map_err(|d| format!("{:?}", d.into_sorted()))?;
        let text = write_lock(&lock);

        let order = [
            "name    = \"claude\"",
            "name    = \"codex\"",
            "name    = \"core\"",
            "name    = \"team-lint\"",
            "path = \"a\"",
            "path = \"b\"",
        ];
        let positions: Vec<usize> = order
            .iter()
            .map(|line| text.find(line).ok_or_else(|| format!("missing {line}")))
            .collect::<Result<_, _>>()?;
        let mut sorted = positions.clone();
        sorted.sort_unstable();
        assert_eq!(positions, sorted);
        Ok(())
    }

    #[test]
    fn write_lock_escapes_strings() -> TestResult {
        let path = "a\"b\td\ne\u{1}";
        let written = lock(vec![git_pack("core")?], vec![file(path)?])?;
        let text = write_lock(&written);
        assert!(text.contains(r#"path = "a\"b\td\ne\u0001""#), "{text}");

        let reread = parsed(&text)?;
        assert_eq!(
            reread.files().first().map(|f| f.path().as_str()),
            Some(path)
        );
        assert_eq!(reread, written);
        Ok(())
    }

    #[test]
    fn quote_escapes_a_backslash() {
        assert_eq!(quote("a\\b"), r#""a\\b""#);
    }

    #[test]
    fn write_lock_round_trips_an_in_memory_lock_with_every_path_shape() -> TestResult {
        let subdir_pack = LockedEntry::new(
            PackName::new("sub")?,
            PackVersion::new("0.2.0")?,
            LockedSource::Git {
                url: GitUrl::new("https://example.org/r")?,
                tag: None,
                subdir: Some(SubPath::new("packs/./sub")?),
                rev: CommitId::new(HEX40)?,
            },
            hash()?,
        );
        let climbing = LockedEntry::new(
            PackName::new("climb")?,
            PackVersion::new("0.1.0")?,
            LockedSource::Path(LocalPath::new("a/../b")?),
            hash()?,
        );
        let root = LockedEntry::new(
            PackName::new("root")?,
            PackVersion::new("0.1.0")?,
            LockedSource::Path(LocalPath::new(".")?),
            hash()?,
        );
        let built = lock(
            vec![git_pack("core")?, subdir_pack, climbing, root],
            vec![file("./a")?, file("b//c")?],
        )?;
        let text = write_lock(&built);
        assert_eq!(parsed(&text)?, built);
        assert_eq!(write_lock(&parsed(&text)?), text);
        Ok(())
    }
}