AkurAI Build
Menu

AkurAI-Build

public

Latest change d51ca48852e1ab45c30f982e72051f93f17ebda7 - fix: migrate schema before serving by Ólafur Búi Ólafsson

use std::{env, net::SocketAddr, path::PathBuf};

use akurai_build::{
    DEFAULT_ADDRESS,
    db::{Database, generate_secret, load_secret},
    mcp,
    server::{self, ServerOptions},
};
use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
use serde::Serialize;
use serde_json::json;
use tracing_subscriber::EnvFilter;

#[derive(Parser)]
#[command(
    name = "akurai",
    version,
    about = "Lean Git-native CI/CD on the Bunfork foundation"
)]
struct Cli {
    #[arg(long, env = "AKURAI_DATA")]
    data: Option<PathBuf>,
    #[arg(long, env = "AKURAI_KEY_FILE")]
    key_file: Option<PathBuf>,
    #[command(subcommand)]
    command: Action,
}

#[derive(Subcommand)]
enum Action {
    /// Generate a private 256-bit key or token.
    Keygen {
        #[arg(long)]
        out: PathBuf,
    },
    /// Create or update the encrypted database schema.
    Migrate,
    /// Serve the full AkurAI Build Model Context Protocol tool set over stdio.
    Mcp,
    /// Serve the MiniJinja dashboard, API, webhooks, and worker.
    Serve(ServeArgs),
}

#[derive(Args)]
struct ServeArgs {
    #[arg(long, env = "AKURAI_ADDRESS", default_value = DEFAULT_ADDRESS)]
    address: SocketAddr,
    #[arg(long, env = "AKURAI_TOKEN_FILE")]
    token_file: Option<PathBuf>,
    #[arg(long, env = "AKURAI_WEBHOOK_SECRET_FILE")]
    webhook_secret_file: Option<PathBuf>,
    #[arg(long, env = "AKURAI_PUBLIC_ORIGIN")]
    public_origin: Option<String>,
    #[arg(long, env = "AKURAI_ALLOW_NATIVE", default_value_t = false)]
    allow_native: bool,
    #[arg(long, env = "AKURAI_WORKERS", default_value_t = 2)]
    worker_count: usize,
}

#[derive(Serialize)]
struct Envelope<T: Serialize> {
    ok: bool,
    data: T,
}

#[tokio::main]
async fn main() {
    init_logging();
    let cli = Cli::parse();
    if let Err(error) = execute(cli).await {
        let body = json!({"ok":false,"error":{"code":"failed","message":format!("{error:#}")}});
        println!(
            "{}",
            serde_json::to_string(&body).unwrap_or_else(|_| "{\"ok\":false}".into())
        );
        std::process::exit(1);
    }
}

async fn execute(cli: Cli) -> Result<()> {
    let paths = Paths::new(cli.data, cli.key_file)?;
    match cli.command {
        Action::Keygen { out } => {
            generate_secret(&out)?;
            print(json!({"path":out,"created":true}))?;
        }
        Action::Migrate => {
            let key = load_secret(&paths.key_file, "AKURAI_DB_KEY")?;
            let database = Database::open(&paths.database, &key, true)?;
            let applied = database.migrate()?;
            print(json!({"database":paths.database,"migrations_applied":applied}))?;
        }
        Action::Mcp => mcp::serve(open(&paths)?, paths.root.clone(), native_allowed())?,
        Action::Serve(args) => {
            let key = load_secret(&paths.key_file, "AKURAI_DB_KEY")?;
            let database = Database::open(&paths.database, &key, false)?;
            let token_file = args
                .token_file
                .unwrap_or_else(|| paths.config.join("api.token"));
            let webhook_file = args
                .webhook_secret_file
                .unwrap_or_else(|| paths.config.join("webhook.token"));
            let token = load_secret(&token_file, "AKURAI_API_TOKEN")?;
            let webhook_secret = load_secret(&webhook_file, "AKURAI_WEBHOOK_SECRET")?;
            let public_origin = args
                .public_origin
                .context("AKURAI_PUBLIC_ORIGIN is required")?;
            database.migrate()?;
            server::serve(
                database,
                ServerOptions {
                    address: args.address,
                    token: token.to_string(),
                    webhook_secret: webhook_secret.to_string(),
                    public_origin,
                    data_root: paths.root,
                    allow_native: args.allow_native,
                    worker_count: args.worker_count,
                },
            )
            .await?;
        }
    }
    Ok(())
}

struct Paths {
    root: PathBuf,
    database: PathBuf,
    config: PathBuf,
    key_file: PathBuf,
}

impl Paths {
    fn new(data: Option<PathBuf>, key_file: Option<PathBuf>) -> Result<Self> {
        let home = env::var_os("HOME")
            .map(PathBuf::from)
            .context("HOME is not set")?;
        let root = data.unwrap_or_else(|| home.join(".local/share/akurai-build"));
        let config = home.join(".config/akurai-build");
        let database = root.join("akurai.db");
        let key_file = key_file.unwrap_or_else(|| config.join("database.key"));
        Ok(Self {
            root,
            database,
            config,
            key_file,
        })
    }
}

fn open(paths: &Paths) -> Result<Database> {
    let key = load_secret(&paths.key_file, "AKURAI_DB_KEY")?;
    let database = Database::open(&paths.database, &key, false)?;
    database.validate_schema()?;
    Ok(database)
}

fn print<T: Serialize>(data: T) -> Result<()> {
    println!(
        "{}",
        serde_json::to_string_pretty(&Envelope { ok: true, data })?
    );
    Ok(())
}

fn native_allowed() -> bool {
    env::var("AKURAI_ALLOW_NATIVE")
        .is_ok_and(|value| matches!(value.as_str(), "1" | "true" | "yes"))
}

fn init_logging() {
    let filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new("akurai_build=info,tower_http=info"));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .init();
}