anything-anything 0.1.0

anything-anything. Literally anything. Describe a tool, app or game in a line: your coding agent builds it in any stack and its own tests prove it works.
//! Stacks: what a tool is made of. Each one is a folder under templates/ with a stack.toml (how to
//! build, check and run it, what the agent should know) and three kinds of files:
//!
//! - shell/   owned by anything-anything: regenerated from anything.toml, restored if anyone edits them
//! - seed/    written once, then yours (README, the package manifest, the engine)
//! - command/ one per [[command]], written once: where each command's code goes
//!
//! A folder named in `include` (like _agent: skill, plugin, MCP config) is shared between stacks.
//! Adding a stack is adding a folder: no code.

use crate::codegen;
use crate::names::Meta;
use crate::render::{self, Ctx};
use crate::spec::{Run, Spec, Step};
use crate::templates::TEMPLATES;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use std::collections::BTreeSet;

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StackDef {
    #[serde(default)]
    pub id: String,
    pub about: String,
    /// cli, web or any: what the design task asks for.
    pub kind: String,
    /// Which code generator fills the shell: "rust", or "" (the stack reads manifest.json at runtime).
    #[serde(default)]
    pub codegen: String,
    /// Shared template folders to add (_base, _agent).
    #[serde(default)]
    pub include: Vec<String>,
    /// Whether the tool has [[command]]s (a CLI) and an MCP server that lists them.
    #[serde(default)]
    pub commands: bool,
    #[serde(default)]
    pub mcp: bool,
    /// Markdown for the build task: the layout, the conventions, what to run.
    #[serde(default)]
    pub brief: String,
    #[serde(default)]
    pub run: Run,
    #[serde(default, rename = "step")]
    pub steps: Vec<Step>,
    /// Text that means "not built yet". Found in the sources, it fails verify.
    #[serde(default)]
    pub stubs: Vec<String>,
    /// Folders the stubs are looked for in.
    #[serde(default)]
    pub sources: Vec<String>,
    /// Formatters for generated files, so the stack's own formatter leaves them alone.
    #[serde(default, rename = "format")]
    pub formats: Vec<Format>,
    /// How people install it, for the README and hub: "npm i -g {{npm}}".
    #[serde(default)]
    pub install: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Format {
    /// File extension, without the dot.
    pub ext: String,
    /// Reads the file on stdin, writes it formatted on stdout. {root} is the project.
    pub run: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Owner {
    /// anything-anything's: regenerated by sync, restored after an agent touches it.
    Shell,
    /// Yours once written.
    Seed,
}

#[derive(Debug, Clone)]
pub struct GenFile {
    pub path: String,
    pub text: String,
    pub owner: Owner,
}

/// Every stack, by id, with what it's for ("cli · A command-line tool...").
pub fn all() -> Vec<(String, String)> {
    let mut ids = BTreeSet::new();
    for (path, _) in TEMPLATES {
        if let Some((id, rest)) = path.split_once('/')
            && rest == "stack.toml"
            && !id.starts_with('_')
        {
            ids.insert(id.to_string());
        }
    }
    ids.into_iter()
        .map(|id| {
            let about = raw_def(&id).map(|d| format!("[{}] {}", d.kind, d.about)).unwrap_or_default();
            (id, about)
        })
        .collect()
}

fn template(path: &str) -> Option<&'static str> {
    TEMPLATES.iter().find(|(p, _)| *p == path).map(|(_, t)| *t)
}

/// The stack.toml with its templates left in, for listing.
fn raw_def(id: &str) -> Result<StackDef> {
    let text = template(&format!("{id}/stack.toml")).with_context(|| unknown(id))?;
    let mut def: StackDef = toml::from_str(text).with_context(|| format!("templates/{id}/stack.toml"))?;
    def.id = id.to_string();
    Ok(def)
}

fn unknown(id: &str) -> String {
    let ids: Vec<String> = all().into_iter().map(|(id, _)| id).collect();
    format!("no stack {id:?}; there's {}", ids.join(", "))
}

/// The stack of a spec, with its stack.toml rendered for this tool.
pub fn load(spec: &Spec) -> Result<StackDef> {
    let ctx = codegen::base(spec, &Meta::of(spec));
    load_with(&spec.stack, &ctx)
}

fn load_with(id: &str, ctx: &Ctx) -> Result<StackDef> {
    let text = template(&format!("{id}/stack.toml")).with_context(|| unknown(id))?;
    let rendered = render::render(text, ctx).with_context(|| format!("templates/{id}/stack.toml"))?;
    let mut def: StackDef = toml::from_str(&rendered).with_context(|| format!("templates/{id}/stack.toml"))?;
    def.id = id.to_string();
    Ok(def)
}

/// Every file the stack makes for this spec.
pub fn files(spec: &Spec) -> Result<(StackDef, Vec<GenFile>)> {
    let meta = Meta::of(spec);
    let base = codegen::base(spec, &meta);
    let def = load_with(&spec.stack, &base)?;
    let ctx = codegen::slots(spec, &meta, &def, base)?;
    let mut out: Vec<GenFile> = Vec::new();
    let mut folders = def.include.clone();
    folders.push(def.id.clone());
    for folder in &folders {
        let prefix = format!("{folder}/");
        if !TEMPLATES.iter().any(|(p, _)| p.starts_with(&prefix)) {
            bail!("stack {} includes {folder:?}, which isn't a template folder", def.id);
        }
        for (path, text) in TEMPLATES.iter().filter(|(p, _)| p.starts_with(&prefix)) {
            let rest = &path[prefix.len()..];
            let Some((kind, rel)) = rest.split_once('/') else { continue };
            let render_one = |ctx: &Ctx| render::render(text, ctx).with_context(|| format!("templates/{path}"));
            match kind {
                "shell" | "seed" => {
                    let owner = if kind == "shell" { Owner::Shell } else { Owner::Seed };
                    out.push(GenFile { path: render::path(rel, &ctx, None), text: render_one(&ctx)?, owner });
                }
                "command" => {
                    for c in &spec.commands {
                        let mut cctx = ctx.clone();
                        codegen::command_slots(spec, c, &mut cctx);
                        out.push(GenFile {
                            path: render::path(rel, &cctx, Some(&c.module())),
                            text: render_one(&cctx)?,
                            owner: Owner::Seed,
                        });
                    }
                }
                _ => {}
            }
        }
    }
    out.push(GenFile { path: "docs/logo.svg".into(), text: crate::logo::svg(&meta), owner: Owner::Seed });
    // a later folder (the stack's own) overrides an included one
    let mut seen = BTreeSet::new();
    out.reverse();
    out.retain(|f| seen.insert(f.path.clone()));
    out.reverse();
    Ok((def, out))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn spec(stack: &str) -> Spec {
        let commands = if stack.ends_with("-cli") {
            r#"
[[command]]
name = "list-all"
about = "List them all"
[[command.arg]]
name = "path"
kind = "path"
positional = true
default = "."
[[command.arg]]
name = "tag"
kind = "list"
default = "TODO,FIXME"
[[command.arg]]
name = "max"
kind = "int"
[[command.arg]]
name = "loud"
kind = "bool"
[[command.arg]]
name = "ratio"
kind = "float"
default = "0.5"
[[command]]
name = "show"
about = "Show one"
[[command.arg]]
name = "id"
kind = "string"
positional = true
required = true
"#
        } else {
            ""
        };
        Spec::parse(&format!(
            "name = \"probe-anything\"\npitch = \"Probes \\\"anything\\\".\"\nstack = \"{stack}\"\nowner = \"someone\"\n{commands}"
        ))
        .unwrap()
    }

    #[test]
    fn every_stack_renders() {
        let ids = all();
        assert!(ids.len() >= 5, "{ids:?}");
        for (id, about) in ids {
            assert!(!about.is_empty(), "{id} has no about");
            let (def, files) = files(&spec(&id)).unwrap_or_else(|e| panic!("{id}: {e:#}"));
            assert_eq!(def.id, id);
            assert!(files.iter().any(|f| f.path == "README.md"), "{id} has no README");
            assert!(
                files
                    .iter()
                    .all(|f| ["__name__", "__verb__", "__snake__", "__command__"].iter().all(|p| !f.path.contains(p))),
                "{id}: unrendered path"
            );
            if def.commands {
                assert!(files.iter().any(|f| f.path.contains("list_all")), "{id}: no command file");
                assert!(!def.run.cmd.is_empty(), "{id}: a CLI stack needs [run] cmd");
            }
        }
    }
}