use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use hird::identity::{self, ACTOR_CLI};
use hird::Db;
use hird_factory::Role;
use crate::roster::Roster;
pub struct Options {
pub dir: PathBuf,
pub harnesses: Vec<String>,
pub project: Option<PathBuf>,
pub bind: String,
pub port: u16,
}
pub struct Prepared {
pub roster: PathBuf,
pub db: PathBuf,
pub guide: String,
pub crew: Crew,
pub playground: Option<PathBuf>,
}
pub struct Crew {
pub project: String,
pub human: (String, String),
pub ci: String,
pub agents: Vec<(String, String)>,
}
const SAMPLE: &[(&str, &str, &[i64])] = &[
(
"Write fizzbuzz",
"Create `fizzbuzz.py` with a function `fizzbuzz(n: int) -> str` that \
returns \"Fizz\" for multiples of 3, \"Buzz\" for multiples of 5, \
\"FizzBuzz\" for multiples of both, and the number otherwise. Running \
`python3 fizzbuzz.py` prints 1 to 100. Commit it.",
&[],
),
(
"Test fizzbuzz",
"Add `test_fizzbuzz.py`, using `unittest`, covering 1, 3, 5, 15 and a \
large multiple of 15. `python3 -m unittest` must pass. Commit it.",
&[1],
),
(
"Document fizzbuzz in the README",
"Add a short section to `README.md`: what `fizzbuzz.py` does and how \
to run it and its tests. Commit it.",
&[1],
),
];
pub fn prepare(opts: &Options) -> anyhow::Result<Prepared> {
fs::create_dir_all(&opts.dir)?;
let dir = fs::canonicalize(&opts.dir)?;
let roster_path = dir.join("roster.toml");
let db_path = dir.join("factory.db");
let fresh_db = !db_path.exists();
let mut notes = Vec::new();
let roster = if roster_path.exists() {
let roster = Roster::load(&roster_path)?;
notes.push(format!(
"Using the factory already set up in {} — same tokens, same board.",
dir.display()
));
if let Some(asked) = &opts.project {
let asked = identity::canonical_project(asked);
let has = crew_of(&roster)?.project;
if asked != has {
anyhow::bail!(
"{} is already set up for {has}; pass another --dir to set one up for {asked}",
dir.display()
);
}
}
roster
} else {
let harnesses = harnesses(&opts.harnesses)?;
let project = match &opts.project {
Some(path) => {
if !path.is_dir() {
anyhow::bail!("--project {} is not a directory", path.display());
}
identity::canonical_project(path)
}
None => playground(&dir.join("playground"))?,
};
let text = roster_text(&project, &person(), &harnesses)?;
write_private(&roster_path, &text)?;
Roster::parse(&text)?
};
let crew = crew_of(&roster)?;
let playground = dir.join("playground");
let is_playground = crew.project == identity::canonical_project(&playground);
if fresh_db && is_playground {
seed(&db_path, &crew.project)?;
}
if crew.agents.len() < 2 {
notes.push(
"Only one agent harness is in the roster. No harness reviews work it built, so \
reviews will wait for you: approve them with `human approve <seq>`, or add a \
second harness to roster.toml."
.to_string(),
);
}
let url = format!("http://{}:{}", opts.bind, opts.port);
write_connect(&dir, &url, &crew)?;
write_script(&dir.join("ci"), &url, &crew.ci, "ci", &crew.project)?;
write_script(
&dir.join("human"),
&url,
&crew.human.1,
"human",
&crew.project,
)?;
let guide = guide(&dir, &db_path, &url, &crew, is_playground, ¬es);
write_private(&dir.join("GUIDE.md"), &guide)?;
Ok(Prepared {
roster: roster_path,
db: db_path,
guide,
crew,
playground: is_playground.then_some(playground),
})
}
fn harnesses(raw: &[String]) -> anyhow::Result<Vec<String>> {
let mut out: Vec<String> = Vec::new();
for name in raw {
let Some(name) = identity::harness_name(name) else {
anyhow::bail!("{name:?} is not a harness name");
};
if matches!(name.as_str(), "human" | "ci") {
anyhow::bail!("{name:?} is a role in the quickstart, not an agent harness");
}
if !out.contains(&name) {
out.push(name);
}
}
if out.is_empty() {
anyhow::bail!("name at least one agent harness with --harness");
}
Ok(out)
}
fn person() -> String {
std::env::var("USER")
.or_else(|_| std::env::var("USERNAME"))
.ok()
.and_then(|name| identity::harness_name(&name))
.unwrap_or_else(|| "you".to_string())
}
fn token() -> anyhow::Result<String> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|e| anyhow::anyhow!("no randomness for a token: {e}"))?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
fn roster_text(project: &str, person: &str, harnesses: &[String]) -> anyhow::Result<String> {
let mut text = format!(
"# Written by `hird-server quickstart`. Every token here is a credential:\n\
# keep this file private, and out of any repository.\n\
#\n\
# Each agent harness gets one token with both roles. A harness never\n\
# reviews work it built, so with two or more harnesses each reviews the\n\
# others' work. See examples/factory-roster.toml for every option.\n\
\n\
project = {project:?}\n\
\n\
[factory]\n\
reviewer_harness_differs = true\n\
max_attempts = 3\n\
require_ci_to_merge = true\n\
require_ci_before_review = false\n"
);
for harness in harnesses {
writeln!(
text,
"\n[[worker]]\ntoken = \"{}\"\nidentity = {person:?}\nharness = {harness:?}\n\
roles = [\"builder\", \"reviewer\"]",
token()?
)?;
}
writeln!(
text,
"\n# Reports test runs and records merges: the `ci` script in this directory.\n\
[[worker]]\ntoken = \"{}\"\nidentity = \"ci\"\nharness = \"ci\"\nroles = [\"ci\"]",
token()?
)?;
writeln!(
text,
"\n# You: escalations, overrides, merges, and the /watch page. The `human` script.\n\
[[worker]]\ntoken = \"{}\"\nidentity = {person:?}\nharness = \"human\"\nroles = [\"human\"]",
token()?
)?;
Ok(text)
}
fn crew_of(roster: &Roster) -> anyhow::Result<Crew> {
let mut project = None;
let (mut human, mut ci, mut agents) = (None, None, Vec::new());
for (token, worker) in roster.entries() {
project.get_or_insert_with(|| worker.project.clone());
if worker.roles.has(Role::Human) && human.is_none() {
human = Some((worker.identity.clone(), token.clone()));
} else if worker.roles.has(Role::Ci) && ci.is_none() {
ci = Some(token.clone());
} else if worker.roles.has(Role::Builder) {
if let Some(harness) = &worker.harness {
agents.push((harness.clone(), token.clone()));
}
}
}
agents.sort();
match (project, human, ci) {
(Some(project), Some(human), Some(ci)) => Ok(Crew {
project,
human,
ci,
agents,
}),
_ => anyhow::bail!(
"this roster has no worker with the human role, or none with ci: \
quickstart needs both"
),
}
}
fn playground(path: &Path) -> anyhow::Result<String> {
fs::create_dir_all(path)?;
let readme = path.join("README.md");
if !readme.exists() {
fs::write(
&readme,
"# playground\n\nA project for trying the hird factory. The agents build here.\n",
)?;
}
if !path.join(".git").exists() {
let git = |args: &[&str]| {
std::process::Command::new("git")
.args(args)
.current_dir(path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
};
if git(&["init", "--quiet"]) {
git(&["add", "README.md"]);
git(&[
"-c",
"user.name=hird quickstart",
"-c",
"user.email=quickstart@hird.invalid",
"commit",
"--quiet",
"-m",
"playground",
]);
}
}
Ok(identity::canonical_project(path))
}
fn seed(db_path: &Path, project: &str) -> anyhow::Result<()> {
let db = Db::open(db_path)?;
for (title, body, needs) in SAMPLE {
let task = db.tasks().create(project, title, body, 0, ACTOR_CLI)?;
for needed in *needs {
db.deps().add(task.seq, *needed, ACTOR_CLI)?;
}
}
Ok(())
}
fn connect_snippet(harness: &str, url: &str, token: &str) -> (String, String) {
let mcp = format!("{url}/mcp");
let auth = format!("Bearer {token}");
match harness {
"claude-code" => (
"Run this in the project directory:".into(),
format!(
"claude mcp add --transport http hird {mcp} \\\n --header \"Authorization: {auth}\""
),
),
"codex" => (
format!(
"Add this to ~/.codex/config.toml. Codex reads the token from the \
environment, so also run this in the shell that starts it:\n\n\
```\nexport HIRD_TOKEN={token}\n```\n\nThe config:"
),
format!("[mcp_servers.hird]\nurl = \"{mcp}\"\nbearer_token_env_var = \"HIRD_TOKEN\""),
),
"copilot" => (
"Write this to .vscode/mcp.json in the project:".into(),
format!(
"{{\n \"servers\": {{\n \"hird\": {{\n \"type\": \"http\",\n \
\"url\": \"{mcp}\",\n \"headers\": {{ \"Authorization\": \"{auth}\" }}\n \
}}\n }}\n}}"
),
),
"copilot-cli" => (
"Merge this into ~/.copilot/mcp-config.json:".into(),
format!(
"{{\n \"mcpServers\": {{\n \"hird\": {{\n \"type\": \"http\",\n \
\"url\": \"{mcp}\",\n \"headers\": {{ \"Authorization\": \"{auth}\" }},\n \
\"tools\": [\"*\"]\n }}\n }}\n}}"
),
),
"gemini" => (
"Merge this into .gemini/settings.json in the project:".into(),
format!(
"{{\n \"mcpServers\": {{\n \"hird\": {{\n \"httpUrl\": \"{mcp}\",\n \
\"headers\": {{ \"Authorization\": \"{auth}\" }}\n }}\n }}\n}}"
),
),
"opencode" => (
"Merge this into opencode.json in the project:".into(),
format!(
"{{\n \"$schema\": \"https://opencode.ai/config.json\",\n \"mcp\": {{\n \
\"hird\": {{\n \"type\": \"remote\",\n \"url\": \"{mcp}\",\n \
\"headers\": {{ \"Authorization\": \"{auth}\" }}\n }}\n }}\n}}"
),
),
_ => (
"Point the harness at this MCP server (streamable HTTP) with this header:".into(),
format!("url: {mcp}\nheader: Authorization: {auth}"),
),
}
}
fn write_connect(dir: &Path, url: &str, crew: &Crew) -> anyhow::Result<()> {
let connect = dir.join("connect");
fs::create_dir_all(&connect)?;
for (harness, token) in &crew.agents {
let (where_, what) = connect_snippet(harness, url, token);
let text = format!(
"# Connecting {harness} to the factory\n\n\
This token is {harness}'s alone: the server pins it to that harness and\n\
gives it the builder and reviewer roles. Keep it private.\n\n\
{where_}\n\n```\n{what}\n```\n\n\
Then start {harness} in {project} and say: *work the hird queue*.\n\n\
If your version of {harness} spells remote MCP servers differently, the\n\
parts are: streamable HTTP, `{url}/mcp`, and the header\n\
`Authorization: Bearer <the token above>`.\n",
project = crew.project,
);
write_private(&connect.join(format!("{harness}.md")), &text)?;
}
Ok(())
}
fn write_script(
path: &Path,
url: &str,
token: &str,
role: &str,
project: &str,
) -> anyhow::Result<()> {
let usage = if role == "ci" {
"usage: ci pass <seq> [evidence] report a passing test run\n\
\x20 ci fail <seq> <output> report a failure: the work goes back with it\n\
\x20 ci merge <seq> [evidence] record approved work as in (default: the project's HEAD)\n\
\x20 ci board every task's stage"
} else {
"usage: human board every task's stage\n\
\x20 human approve <seq> [why] approve built or in-review work\n\
\x20 human reject <seq> <findings> send it back, as an attempt\n\
\x20 human answer <seq> <answer> answer an escalation\n\
\x20 human reopen <seq> [why] reopen escalated, approved or merged work\n\
\x20 human cancel <seq> [why] cancel unfinished work\n\
\x20 human merge <seq> [evidence] record approved work as in (default: the project's HEAD)"
};
let commands = if role == "ci" {
r#" pass) need 1; call factory_gate "{\"seq\":$1,\"outcome\":\"pass\",\"evidence\":\"$(esc "${2:-}")\"}" ;;
fail) need 2; call factory_gate "{\"seq\":$1,\"outcome\":\"fail\",\"output\":\"$(esc "$2")\"}" ;;"#
} else {
r#" approve|reject|answer|reopen|cancel)
need 1; text="${2:-}"
if [ -z "$text" ] && { [ "$cmd" = reject ] || [ "$cmd" = answer ]; }; then usage; fi
call factory_decide "{\"seq\":$1,\"action\":\"$cmd\",\"text\":\"$(esc "${text:-$cmd}")\"}" ;;"#
};
let script = format!(
r##"#!/usr/bin/env bash
# Written by `hird-server quickstart`: the {role} role, one tool call per command.
# It holds the {role} token, so keep it private.
set -euo pipefail
URL="{url}/mcp"
TOKEN="{token}"
PROJECT="{project}"
usage() {{
cat >&2 <<'USAGE'
{usage}
USAGE
exit 2
}}
# JSON-escape one string argument.
esc() {{
local s="$1"
s="${{s//\\/\\\\}}"; s="${{s//\"/\\\"}}"; s="${{s//$'\n'/\\n}}"; s="${{s//$'\t'/\\t}}"
printf '%s' "$s"
}}
# One MCP 2026-07-28 tool call: no handshake, the token, and _meta.
call() {{
local meta='{{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{{"name":"hird-quickstart","version":"0"}},"io.modelcontextprotocol/clientCapabilities":{{}}}}'
local answer
answer=$(curl -sS "$URL" \
-H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2026-07-28' \
-H 'Mcp-Method: tools/call' -H "Mcp-Name: $1" \
-d "{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"$1\",\"arguments\":$2,\"_meta\":$meta}}}}" |
sed -n 's/^data: //p' | grep -v '^$' | head -n1) || {{
echo "the factory is not answering on $URL — is hird-server quickstart running?" >&2
exit 1
}}
if ! command -v jq >/dev/null 2>&1; then
printf '%s\n' "$answer"
return
fi
if [ "$1" = factory_board ]; then
printf '%s\n' "$answer" | jq -r '.result.content[0].text | fromjson? // . |
if type == "object" then .tasks[] |
"#\(.seq) \(.stage | . + " " * (10 - length)) \(.title)"
+ (if .attempts > 0 then " · attempts \(.attempts)" else "" end)
+ (if (.waiting_on | length) > 0 then " · waits on \(.waiting_on | map("#\(.)") | join(", "))" else "" end)
else . end'
else
printf '%s\n' "$answer" | jq -r '.result
| (if .isError then "refused: " else "" end) + .content[0].text'
fi
}}
head_of_project() {{
git -C "$PROJECT" rev-parse --short HEAD 2>/dev/null || {{
echo "no evidence given, and $PROJECT has no git HEAD to use: pass a SHA or PR URL" >&2
exit 2
}}
}}
cmd="${{1:-}}"; [ $# -gt 0 ] && shift
need() {{ [ "$ARGC" -ge "$1" ] || usage; }}
ARGC=$#
case "$cmd" in
{commands}
merge) need 1; call factory_merge "{{\"seq\":$1,\"evidence\":\"$(esc "${{2:-$(head_of_project)}}")\"}}" ;;
board) call factory_board '{{}}' ;;
*) usage ;;
esac
"##
);
fs::write(path, script)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
fn guide(
dir: &Path,
db: &Path,
url: &str,
crew: &Crew,
playground: bool,
notes: &[String],
) -> String {
let d = dir.display();
let project = &crew.project;
let mut crew_line = format!("{} (human)", crew.human.0);
for (harness, _) in &crew.agents {
write!(crew_line, " · {harness} (builder, reviewer)").ok();
}
crew_line.push_str(" · ci");
let mut g = String::new();
writeln!(g, "# Your hird factory\n").ok();
for note in notes {
writeln!(g, "> {note}\n").ok();
}
writeln!(
g,
"| | |\n|---|---|\n| project | `{project}`{} |\n| roster | `{d}/roster.toml` (tokens: keep it private) |\n\
| database | `{}` |\n| crew | {crew_line} |\n",
if playground {
" — a playground with a three-task sample release"
} else {
""
},
db.display()
)
.ok();
writeln!(
g,
"## 1. Watch the floor\n\nOpen this while the server runs. It is read-only, and the link carries your \
token:\n\n {url}/watch#token={}\n",
crew.human.1
)
.ok();
writeln!(g, "## 2. Connect your agents\n").ok();
writeln!(
g,
"Each harness has its own token and its own snippet in `{d}/connect/`:\n"
)
.ok();
for (harness, token) in &crew.agents {
if harness == "claude-code" {
let (_, what) = connect_snippet(harness, url, token);
writeln!(
g,
"- **claude-code**: in `{project}`, run\n\n {}\n",
what.replace("\n", "\n ")
)
.ok();
} else {
writeln!(g, "- **{harness}**: `{d}/connect/{harness}.md`").ok();
}
}
writeln!(g).ok();
writeln!(
g,
"## 3. Put them to work\n\nStart each agent in `{project}` and tell it: *work the hird queue*.\n\n\
A builder pulls the next task it may build and claims it. When it finishes, the factory \
files a review that only a **different** harness may take: no harness reviews its own \
work. Upheld work is *approved* — but not yet *merged*.\n"
)
.ok();
if playground {
writeln!(
g,
"The sample release is already filed: **#1** *Write fizzbuzz*, then **#2** *Test \
fizzbuzz* and **#3** *Document fizzbuzz*, which both wait on #1 — until it is \
**merged**, not merely done.\n"
)
.ok();
}
let test = if playground {
format!("cd {project} && python3 -m unittest")
} else {
format!("cd {project} && <run your tests>")
};
writeln!(
g,
"## 4. Be CI\n\nCI is a role with a token, and here it is you, with a script. Run the tests, \
then report:\n\n {test}\n {d}/ci pass 1\n {d}/ci fail 1 \"what broke\" # \
back to ready, the output handed to the next builder\n"
)
.ok();
writeln!(
g,
"## 5. Merge\n\nOnly approved work that CI last passed can merge, and a merge names its \
evidence:\n\n {d}/ci merge 1 # uses the project's git HEAD\n\n\
Whatever waited on it is free now.\n"
)
.ok();
writeln!(
g,
"## 6. Decide what agents may not\n\n {d}/human board\n {d}/human approve 2 \
\"looks right\" # or reject · answer · reopen · cancel\n\nThe third rejection of \
the same work asks you instead of retrying: `{d}/human answer <seq> \"...\"`.\n"
)
.ok();
writeln!(
g,
"## Next\n\n- **A guided tour first**: `hird-server quickstart --tour --dir \
<another dir>` plays a sample task through every gate, step by step.\n- **Add work**: `hird add --db {} --project {project} \"title\" --body \
\"...\"` (`cargo install hird --locked`).\n- **Come back**: `hird-server quickstart --dir \
{d}` — same tokens, same board.\n- **Your own repository**: `hird-server quickstart --dir \
<another dir> --project /path/to/repo`.\n- **Read more**: \
https://aoprisan.github.io/hird/factory.html\n",
db.display()
)
.ok();
g
}
fn write_private(path: &Path, text: &str) -> anyhow::Result<()> {
fs::write(path, text)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn opts(dir: &Path, harnesses: &[&str]) -> Options {
Options {
dir: dir.to_path_buf(),
harnesses: harnesses.iter().map(|h| h.to_string()).collect(),
project: None,
bind: "127.0.0.1".into(),
port: 7474,
}
}
#[test]
fn quickstart_writes_a_factory_roster_the_server_accepts() {
let tmp = tempfile::tempdir().unwrap();
let ready = prepare(&opts(tmp.path(), &["claude-code", "codex"])).unwrap();
let roster = Roster::load(&ready.roster).unwrap();
assert!(roster.factory().is_some(), "the factory is on");
assert_eq!(roster.len(), 4, "two agents, ci and the human");
let crew = crew_of(&roster).unwrap();
let harnesses: Vec<_> = crew.agents.iter().map(|(h, _)| h.as_str()).collect();
assert_eq!(harnesses, ["claude-code", "codex"]);
for path in [
"ci",
"human",
"GUIDE.md",
"connect/codex.md",
"connect/claude-code.md",
] {
assert!(tmp.path().join(path).exists(), "{path} is missing");
}
assert!(ready.guide.contains("/watch#token="));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for path in ["roster.toml", "GUIDE.md", "connect/codex.md", "ci", "human"] {
let mode = fs::metadata(tmp.path().join(path))
.unwrap()
.permissions()
.mode();
assert_eq!(
mode & 0o077,
0,
"{path} holds a token and is readable by others"
);
}
}
}
#[test]
fn quickstart_seeds_the_sample_release_into_the_playground() {
let tmp = tempfile::tempdir().unwrap();
let ready = prepare(&opts(tmp.path(), &["claude-code", "codex"])).unwrap();
let db = Db::open(&ready.db).unwrap();
let project = identity::canonical_project(&tmp.path().join("playground"));
let titles: Vec<String> = (1..=3)
.map(|seq| db.tasks().get(seq).unwrap().title)
.collect();
assert_eq!(titles[0], "Write fizzbuzz");
assert_eq!(db.tasks().get(2).unwrap().project, project);
assert!(
db.tasks().get(4).is_err(),
"only the sample release is filed"
);
}
#[test]
fn running_quickstart_again_keeps_the_tokens_and_the_board() {
let tmp = tempfile::tempdir().unwrap();
let first = prepare(&opts(tmp.path(), &["claude-code", "codex"])).unwrap();
let before = fs::read_to_string(&first.roster).unwrap();
let again = prepare(&opts(tmp.path(), &["gemini"])).unwrap();
assert_eq!(fs::read_to_string(&again.roster).unwrap(), before);
assert!(again.guide.contains("already set up"));
let db = Db::open(&again.db).unwrap();
assert!(db.tasks().get(4).is_err(), "the sample is not filed twice");
}
#[test]
fn one_harness_is_warned_that_reviews_will_wait_for_the_human() {
let tmp = tempfile::tempdir().unwrap();
let ready = prepare(&opts(tmp.path(), &["claude-code"])).unwrap();
assert!(ready.guide.contains("reviews will wait for you"));
}
#[test]
fn the_human_and_ci_are_not_agent_harnesses() {
let tmp = tempfile::tempdir().unwrap();
assert!(prepare(&opts(tmp.path(), &["human"])).is_err());
}
}