hird-server 0.3.0

The central queue: hird served over HTTP for harnesses on other machines.
//! `hird-server` — the central queue.
//!
//! The `hird` binary is a local queue: one process per harness session, stdio,
//! no network, and a working tree it can read. This one is the other thing —
//! a process on a host two people reach from two machines, speaking MCP over
//! HTTP, with the queue's SQLite file underneath it.
//!
//! It is a separate binary rather than a flag on the first because a server is
//! a different kind of program. It carries a web stack the local binary must
//! not: `cargo tree -p hird` names no HTTP dependency at all, and that stays
//! true however large this one grows.
//!
//! ## How a connection becomes a session
//!
//! [`hird::mcp::Session`] holds who a connection is; the question a server has
//! to answer is who to believe. The far end of a socket can claim anything, so
//! nothing it says about its identity is taken: a request carries a bearer
//! token, the [`roster`] maps that token to a person, and the session is built
//! from the roster's entry. A client may still name its own harness — §29
//! permits that and never permits the other.
//!
//! Each roster entry gets its own MCP service, so identity is fixed when the
//! service is built rather than re-derived per call. Dispatch is a map lookup
//! on the token, and a request without a known one is refused before any of
//! the queue is touched.

mod factory;
mod quickstart;
mod roster;
mod watch;

#[cfg(test)]
mod tests;

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;

use axum::body::Body;
use axum::extract::State;
use axum::http::{Request, StatusCode};
use axum::response::{IntoResponse, Response};
use clap::{Args, Parser, Subcommand};
use hird::config::{self, Config};
use hird::identity::AgentId;
use hird::mcp::{HirdMcp, Session, Shared};
use hird::Db;
use hird_factory::{FactoryGate, Policy};
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::StreamableHttpService;
use tower_service::Service;

use crate::factory::{FactoryMcp, Membership};
use crate::roster::Roster;

/// One MCP endpoint, already bound to one person.
type Endpoint = StreamableHttpService<FactoryMcp, LocalSessionManager>;

#[derive(Debug, Parser)]
#[command(
    name = "hird-server",
    version,
    about = "Serve a hird queue over HTTP to harnesses on other machines.",
    long_about = "The central queue. Harnesses on other machines reach it over MCP \
                  streamable HTTP, each authenticated by a bearer token that the roster \
                  maps to a person. Every claim is still atomic, because there is still \
                  one SQLite file.\n\n\
                  Terminate TLS in front of this: it speaks plain HTTP, and a bearer \
                  token on an unencrypted connection is a token you have given away.\n\n\
                  New here? `hird-server quickstart` sets up a software factory to try, \
                  tells you what to do with it, and serves it.",
    subcommand_negates_reqs = true
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
    /// The roster file: which tokens may connect, and as whom.
    #[arg(long, value_name = "PATH", required = true)]
    roster: Option<PathBuf>,
    /// Address to listen on.
    #[arg(long, default_value = "127.0.0.1", value_name = "ADDR")]
    bind: String,
    /// Port to listen on.
    #[arg(long, default_value_t = 7474)]
    port: u16,
    /// Database file to use. Overrides HIRD_DB and the default location.
    #[arg(long, value_name = "PATH")]
    db: Option<PathBuf>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Set up a software factory to try, print a step-by-step guide, and serve it.
    ///
    /// Writes everything into one directory: a factory roster with fresh tokens
    /// (you as the human, one builder-reviewer token per agent harness, and CI),
    /// a database, the snippet that connects each harness, `ci` and `human`
    /// scripts for the moves no agent makes, and GUIDE.md. Without --project
    /// the project is a playground git repository with a three-task sample
    /// release already filed. Run it again to come back: the same tokens, the
    /// same board.
    Quickstart(QuickstartArgs),
}

#[derive(Debug, Args)]
struct QuickstartArgs {
    /// Where the factory lives. Created if missing; reused if already set up.
    #[arg(long, default_value = "hird-factory", value_name = "DIR")]
    dir: PathBuf,
    /// An agent harness to give a token: claude-code, codex, copilot,
    /// copilot-cli, gemini, opencode, or any other name. Repeatable. Two or
    /// more, so that each can review what the other built.
    #[arg(
        long = "harness",
        value_name = "NAME",
        default_values_t = ["claude-code".to_string(), "codex".to_string()]
    )]
    harnesses: Vec<String>,
    /// Work on this repository instead of a playground. Nothing is filed for you.
    #[arg(long, value_name = "PATH")]
    project: Option<PathBuf>,
    /// Address to listen on.
    #[arg(long, default_value = "127.0.0.1", value_name = "ADDR")]
    bind: String,
    /// Port to listen on.
    #[arg(long, default_value_t = 7474)]
    port: u16,
    /// Set up and print the guide, but do not start serving.
    #[arg(long)]
    no_serve: bool,
}

/// One roster entry's way in, by lifecycle.
///
/// A client that handshakes with `initialize` gets a protocol session, and
/// each such session is its own agent with its own suffix, as a local `hird
/// mcp` process is. A 2026-07-28 client has no protocol session: rmcp serves
/// each of its requests on a fresh service. Minting a fresh suffix per request
/// would make every call a different agent, unable to update a task it had
/// just claimed. So stateless requests on one token share one session, whose
/// suffix is minted once, when the server starts.
#[derive(Clone)]
struct Door {
    sessions: Endpoint,
    stateless: Endpoint,
}

/// Everything the HTTP layer needs: one door per token.
#[derive(Clone)]
struct Fleet {
    endpoints: Arc<BTreeMap<String, Door>>,
}

impl Fleet {
    /// Build one MCP endpoint per roster entry, all sharing one open database.
    ///
    /// The identity is closed over here rather than read per request, so a
    /// session cannot change who it is halfway through — the same invariant
    /// the local binary gets from having one process per session.
    fn assemble(roster: &Roster, shared: Arc<Shared>, config: &Config) -> anyhow::Result<Fleet> {
        let mut endpoints = BTreeMap::new();
        let policy = roster.factory().cloned().map(Arc::new);
        for (token, worker) in roster.entries() {
            let endpoint = |suffix: Option<String>| {
                let (policy, shared) = (policy.clone(), shared.clone());
                let (config, worker) = (config.clone(), worker.clone());
                StreamableHttpService::new(
                    move || {
                        connect(
                            &worker,
                            policy.clone(),
                            shared.clone(),
                            &config,
                            suffix.as_deref(),
                        )
                        .map_err(std::io::Error::other)
                    },
                    Arc::new(LocalSessionManager::default()),
                    Default::default(),
                )
            };
            // One suffix for this token's stateless session, for as long as
            // this process serves it: the same lifetime a local session has.
            let suffix = AgentId::fresh("").session().to_string();
            let door = Door {
                sessions: endpoint(None),
                stateless: endpoint(Some(suffix)),
            };
            endpoints.insert(token.clone(), door);
        }
        Ok(Fleet {
            endpoints: Arc::new(endpoints),
        })
    }
}

/// One connection for `worker`: its identity, and — in a factory — its roles,
/// stamped on everything it does and enforced on every claim and finish.
/// `suffix` names the session when it outlives a connection (the stateless
/// one); otherwise each connection mints its own.
fn connect(
    worker: &roster::Worker,
    policy: Option<Arc<Policy>>,
    shared: Arc<Shared>,
    config: &Config,
    suffix: Option<&str>,
) -> hird::Result<FactoryMcp> {
    let harness = worker.harness.clone().unwrap_or_default();
    let agent = match suffix {
        Some(suffix) => AgentId::new(harness, suffix),
        None => AgentId::fresh(harness),
    }
    .acting_for(worker.identity.clone())
    .running(worker.model.clone().unwrap_or_default());
    let session = Session::new(
        agent,
        worker.project.clone(),
        worker.capabilities.clone(),
        config,
    )?;
    let Some(policy) = policy else {
        return Ok(FactoryMcp::new(HirdMcp::connect(shared, session), None));
    };
    // Every worker in a factory gets a gate, roles or none: a token with no
    // role may read the board and do nothing else.
    let gate = FactoryGate::new(worker.roles.clone(), (*policy).clone());
    let session = session
        .with_role(worker.roles.to_string())
        .with_gate(Arc::new(gate));
    let member = Membership {
        policy,
        roles: worker.roles.clone(),
    };
    Ok(FactoryMcp::new(
        HirdMcp::connect(shared, session),
        Some(member),
    ))
}

/// The bearer token a request presents, if it presents one properly.
fn bearer(request: &Request<Body>) -> Option<&str> {
    request
        .headers()
        .get(axum::http::header::AUTHORIZATION)?
        .to_str()
        .ok()?
        .strip_prefix("Bearer ")
        .map(str::trim)
        .filter(|token| !token.is_empty())
}

/// Whether a request is a 2026-07-28 one, which has no protocol session.
///
/// The protocol requires such a request to name its version in the
/// `MCP-Protocol-Version` header, and versions are dates, so they compare as
/// strings. A request carrying a session id belongs to a session whatever it
/// says. Getting this wrong costs nothing unsafe: both endpoints serve both
/// lifecycles, and they differ only in how long the agent's suffix lasts.
fn is_stateless(request: &Request<Body>) -> bool {
    let headers = request.headers();
    !headers.contains_key("mcp-session-id")
        && headers
            .get("mcp-protocol-version")
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.trim() >= "2026-07-28")
}

/// Route a request to the endpoint its token names.
///
/// A request with no token, or one the roster does not know, is refused here —
/// before the database is opened, before a session exists, and with the same
/// answer either way, so the response does not say which tokens are real.
async fn route(State(fleet): State<Fleet>, request: Request<Body>) -> Response {
    let Some(door) = bearer(&request).and_then(|token| fleet.endpoints.get(token)) else {
        return (
            StatusCode::UNAUTHORIZED,
            [(
                axum::http::header::WWW_AUTHENTICATE,
                "Bearer realm=\"hird\"",
            )],
            "this queue is not open to unnamed callers\n",
        )
            .into_response();
    };
    let mut endpoint = if is_stateless(&request) {
        door.stateless.clone()
    } else {
        door.sessions.clone()
    };
    match endpoint.call(request).await {
        Ok(response) => response.into_response(),
        Err(never) => match never {},
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    if let Some(Command::Quickstart(args)) = cli.command {
        return quickstart(args).await;
    }
    let roster_path = cli
        .roster
        .expect("clap requires --roster without a subcommand");
    let roster = Roster::load(&roster_path)?;
    let config = Config::load_default()?;
    let db_path = config::resolve_db_path(cli.db.as_deref());
    serve(&roster, &db_path, config, &cli.bind, cli.port).await
}

/// Set a factory up (or find it), say what to do with it, and serve it.
async fn quickstart(args: QuickstartArgs) -> anyhow::Result<()> {
    let ready = quickstart::prepare(&quickstart::Options {
        dir: args.dir,
        harnesses: args.harnesses,
        project: args.project,
        bind: args.bind.clone(),
        port: args.port,
    })?;
    println!("{}", ready.guide);
    if args.no_serve {
        let roster = ready.roster.display();
        println!(
            "Not serving (--no-serve). Start it with:\n\n    hird-server --roster {roster} --db {} --bind {} --port {}\n",
            ready.db.display(),
            args.bind,
            args.port
        );
        return Ok(());
    }
    let roster = Roster::load(&ready.roster)?;
    // The server reads no one's working tree: the agents may be anywhere.
    let mut config = Config::load_default()?;
    config.witness = false;
    println!("Serving. Leave this running; Ctrl-C stops it.\n");
    serve(&roster, &ready.db, config, &args.bind, args.port).await
}

async fn serve(
    roster: &Roster,
    db_path: &std::path::Path,
    config: Config,
    bind: &str,
    port: u16,
) -> anyhow::Result<()> {
    let shared = Arc::new(Shared::new(Db::open(db_path)?, config.clone()));
    let fleet = Fleet::assemble(roster, shared.clone(), &config)?;

    let app = axum::Router::new()
        .fallback(axum::routing::any(route))
        .with_state(fleet)
        .merge(watch::Watch::new(roster, shared).router());
    let listener = tokio::net::TcpListener::bind((bind, port)).await?;
    let addr = listener.local_addr()?;
    println!(
        "hird-server on http://{addr}  ({} in the roster)",
        roster.len()
    );
    println!("database: {}", db_path.display());
    println!("watch:    http://{addr}/watch  (read-only; asks for a roster token)");
    if let Some(policy) = roster.factory() {
        println!(
            "factory: on (max_attempts {}, CI to merge {}, CI before review {})",
            policy.max_attempts, policy.require_ci_to_merge, policy.require_ci_before_review
        );
    }
    if config.witness {
        println!(
            "note: the witness is on, and it reads this host's working tree — \
             nobody's checkout. Set `witness = false` for a shared queue."
        );
    }
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}