use std::fmt::Write as _;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use axum::body::Body;
use axum::http::Request;
use serde_json::{json, Value};
use tower_service::Service;
use crate::quickstart::Crew;
pub struct Tour<'a> {
pub app: axum::Router,
pub host: String,
pub crew: &'a Crew,
pub dir: &'a Path,
pub playground: PathBuf,
pub pause: bool,
}
#[derive(Clone, Copy, PartialEq)]
enum Expect {
Done,
Refused,
}
const BUGGY: &str = r#"def fizzbuzz(n: int) -> str:
if n % 3 == 0:
return "Fizz"
if n % 5 == 0:
return "Buzz"
if n % 15 == 0:
return "FizzBuzz"
return str(n)
if __name__ == "__main__":
for i in range(1, 101):
print(fizzbuzz(i))
"#;
const FIXED: &str = r#"def fizzbuzz(n: int) -> str:
if n % 15 == 0:
return "FizzBuzz"
if n % 3 == 0:
return "Fizz"
if n % 5 == 0:
return "Buzz"
return str(n)
if __name__ == "__main__":
for i in range(1, 101):
print(fizzbuzz(i))
"#;
const CI_OUTPUT: &str = "fizzbuzz(15) returned 'Fizz', expected 'FizzBuzz'";
impl Tour<'_> {
pub async fn can_start(&self) -> anyhow::Result<bool> {
let board = self
.call(&self.crew.human.1, "factory_board", json!({}))
.await?;
let Ok(board) = board else {
return Ok(false);
};
let first = board["tasks"]
.as_array()
.and_then(|tasks| tasks.iter().find(|t| t["seq"] == 1));
Ok(
first.is_some_and(|t| t["stage"] == "ready" && t["attempts"] == 0)
&& !self.playground.join("fizzbuzz.py").exists(),
)
}
pub async fn run(&self) -> anyhow::Result<()> {
self.play(&mut std::io::stdout()).await
}
pub async fn play(&self, out: &mut (dyn std::io::Write + Send)) -> anyhow::Result<()> {
let [(builder, b_token), (reviewer, r_token), ..] = self.crew.agents.as_slice() else {
anyhow::bail!("the tour plays two agent harnesses: set up with two --harness");
};
let (builder, b_token) = (builder.as_str(), b_token.as_str());
let (reviewer, r_token) = (reviewer.as_str(), r_token.as_str());
let ci = self.crew.ci.as_str();
let human = self.crew.human.1.as_str();
let d = self.dir.display();
let play = self.dir.join("playground");
let play = play.display();
let total = 8;
self.step(
out,
1,
total,
"The board",
&format!(
"The playground has a sample release of three tasks. #2 and #3 wait on #1, and in a \
factory a dependency clears only when the work is merged, not merely done.\n\n\
The crew: {builder} and {reviewer} are agent harnesses, each allowed to build and \
to review. ci reports test runs and records merges. You are the human. Here the \
tour plays all four, with each one's own token, so every answer below \
comes from the server."
),
)?;
self.board(out, human).await?;
self.pause(out).await?;
self.step(
out,
2,
total,
"A builder asks for work",
&format!(
"An agent told to \"work the hird queue\" calls task_next. It gets the first task \
it may build, and the claim is atomic: no other agent can take #1 now. {reviewer} \
asks for #2 and is refused, because #1 is not merged yet."
),
)?;
let claimed = self
.act(out, builder, b_token, "task_next", json!({}), Expect::Done)
.await?;
self.said(out, &claim_of(&claimed))?;
self.act(
out,
reviewer,
r_token,
"task_claim",
json!({"seq": 2}),
Expect::Refused,
)
.await?;
self.pause(out).await?;
self.step(
out,
3,
total,
"It builds, and the factory files the review",
&format!(
"{builder} writes fizzbuzz.py into the playground, commits it, and completes #1. \
Done is not approved: the factory files a review task, and {builder}, which \
built the work, may not take it."
),
)?;
let sha = self.commit("fizzbuzz.py", BUGGY, builder, "Write fizzbuzz");
self.said(out, &format!("wrote {play}/fizzbuzz.py{}", at(&sha)))?;
let done = self
.act(
out,
builder,
b_token,
"task_complete",
json!({"seq": 1, "result": format!("fizzbuzz.py committed{}.", at(&sha))}),
Expect::Done,
)
.await?;
let review = done["review_filed"].as_i64().unwrap_or_default();
self.said(out, &format!("#1 is built; review #{review} is filed"))?;
self.act(
out,
builder,
b_token,
"task_claim",
json!({"seq": review}),
Expect::Refused,
)
.await?;
self.board(out, human).await?;
self.pause(out).await?;
self.step(
out,
4,
total,
"CI fails it",
"CI is a role with a token. Here it is you, with the ci script: run the tests, then \
report. Multiples of 15 print Fizz, so this run fails. A failure is an attempt: \
the work goes back to ready, the review is withdrawn, and the output is kept for \
the next builder. After three failed attempts the factory stops retrying and asks you.",
)?;
self.you(out, &format!("{d}/ci fail 1 \"{CI_OUTPUT}\""))?;
self.act(
out,
"ci",
ci,
"factory_gate",
json!({"seq": 1, "outcome": "fail", "output": CI_OUTPUT}),
Expect::Done,
)
.await?;
self.said(out, "#1 is back at ready, attempt 1 recorded")?;
self.board(out, human).await?;
self.pause(out).await?;
self.step(
out,
5,
total,
"Work that comes back carries its reason",
&format!(
"{builder} claims #1 again and is handed every earlier attempt: who rejected it \
and what they said. It fixes the order of the checks, commits, and completes. \
The factory files a new review."
),
)?;
let again = self
.act(
out,
builder,
b_token,
"task_claim",
json!({"seq": 1}),
Expect::Done,
)
.await?;
for attempt in again["attempts"].as_array().into_iter().flatten() {
self.said(
out,
&format!(
"handed attempt {} by {}: {}",
attempt["n"],
attempt["source"].as_str().unwrap_or("?"),
attempt["output"].as_str().unwrap_or("")
),
)?;
}
let sha = self.commit("fizzbuzz.py", FIXED, builder, "fizzbuzz: check 15 first");
let done = self
.act(
out,
builder,
b_token,
"task_complete",
json!({"seq": 1, "result": format!("Multiples of 15 are checked first{}.", at(&sha))}),
Expect::Done,
)
.await?;
let review = done["review_filed"].as_i64().unwrap_or_default();
self.said(
out,
&format!("#1 is built again; review #{review} is filed"),
)?;
self.pause(out).await?;
self.step(
out,
6,
total,
"Another harness reviews it",
&format!(
"{reviewer} held none of this work, so the review is its to take. Asking for work \
gets it the review; #2 and #3 are still waiting. It upholds the work, and #1 is \
approved. A reviewer that finds a problem rejects instead, and that counts as an \
attempt, like a failed CI run."
),
)?;
let got = self
.act(out, reviewer, r_token, "task_next", json!({}), Expect::Done)
.await?;
self.said(out, &claim_of(&got))?;
self.act(
out,
reviewer,
r_token,
"task_complete",
json!({"seq": review, "verdict": "upheld",
"result": "15 is checked before 3 and 5; the output is right."}),
Expect::Done,
)
.await?;
self.said(out, "#1 is approved")?;
self.board(out, human).await?;
self.pause(out).await?;
self.step(
out,
7,
total,
"Approved is not merged",
&format!(
"Only ci or the human merges, and only once CI's last word on the work is a pass. \
{builder} may not merge. ci may not merge yet either, because its last run \
failed. So you run the tests, report the pass, and merge. The merge names its \
evidence: the commit."
),
)?;
let evidence = sha.unwrap_or_else(|| "tour".to_string());
self.act(
out,
builder,
b_token,
"factory_merge",
json!({"seq": 1, "evidence": evidence}),
Expect::Refused,
)
.await?;
self.act(
out,
"ci",
ci,
"factory_merge",
json!({"seq": 1, "evidence": evidence}),
Expect::Refused,
)
.await?;
self.you(out, &format!("{d}/ci pass 1"))?;
self.act(
out,
"ci",
ci,
"factory_gate",
json!({"seq": 1, "outcome": "pass"}),
Expect::Done,
)
.await?;
self.said(out, "CI's last word on #1 is now a pass")?;
self.you(out, &format!("{d}/ci merge 1"))?;
self.act(
out,
"ci",
ci,
"factory_merge",
json!({"seq": 1, "evidence": evidence}),
Expect::Done,
)
.await?;
self.said(out, "#1 is merged, so #2 and #3 are free")?;
self.board(out, human).await?;
self.pause(out).await?;
let mut turn = format!(
"#2 (Test fizzbuzz) and #3 (Document fizzbuzz) are ready, and they are for your own \
agents. Leave this running, and in another terminal:\n\n\
1. Connect each agent. Its snippet is in {d}/connect/ (GUIDE.md has them all).\n"
);
if let Some((_, token)) = self.crew.agents.iter().find(|(h, _)| h == "claude-code") {
writeln!(
turn,
" For claude-code:\n\n cd {play}\n claude mcp add --transport http \
hird http://{}/mcp \\\n --header \"Authorization: Bearer {token}\"\n",
self.host
)
.ok();
}
writeln!(
turn,
"2. Start each agent in {play} and tell it: work the hird queue.\n\n\
3. Be CI as the work comes in:\n\n \
{d}/ci pass <seq> # or: {d}/ci fail <seq> \"why\"\n \
{d}/ci merge <seq>\n\n\
4. Decide what agents may not:\n\n \
{d}/human board\n \
{d}/human approve <seq>\n \
{d}/human answer <seq> \"...\" # when work is escalated to you",
)
.ok();
self.step(out, 8, total, "Your turn", &turn)?;
writeln!(
out,
"\nWatch the floor in a browser: http://{}/watch#token={human}\n",
self.host
)?;
Ok(())
}
async fn call(
&self,
token: &str,
tool: &str,
args: Value,
) -> anyhow::Result<Result<Value, String>> {
let meta = json!({
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {"name": "hird-tour", "version": env!("CARGO_PKG_VERSION")},
"io.modelcontextprotocol/clientCapabilities": {},
});
let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": tool, "arguments": args, "_meta": meta}});
let request = Request::post("/mcp")
.header("host", &self.host)
.header("authorization", format!("Bearer {token}"))
.header("content-type", "application/json")
.header("accept", "application/json, text/event-stream")
.header("mcp-protocol-version", "2026-07-28")
.header("mcp-method", "tools/call")
.header("mcp-name", tool)
.body(Body::from(body.to_string()))?;
let response = match self.app.clone().call(request).await {
Ok(response) => response,
Err(never) => match never {},
};
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
let text = String::from_utf8_lossy(&bytes);
let message: Value = text
.lines()
.filter_map(|l| l.strip_prefix("data:"))
.map(str::trim)
.find(|l| !l.is_empty())
.and_then(|l| serde_json::from_str(l).ok())
.or_else(|| serde_json::from_str(&text).ok())
.ok_or_else(|| anyhow::anyhow!("{tool}: no answer from the server: {text}"))?;
let result = &message["result"];
let Some(text) = result["content"][0]["text"].as_str() else {
anyhow::bail!("{tool}: not a tool result: {message}");
};
if result["isError"].as_bool().unwrap_or(false) {
return Ok(Err(text.to_string()));
}
Ok(Ok(
serde_json::from_str(text).unwrap_or(Value::String(text.into()))
))
}
async fn act(
&self,
out: &mut (dyn std::io::Write + Send),
who: &str,
token: &str,
tool: &str,
args: Value,
expect: Expect,
) -> anyhow::Result<Value> {
let shown = if args.as_object().is_some_and(|a| a.is_empty()) {
String::new()
} else {
args.to_string()
};
writeln!(out, "\n {who:<12} {tool} {shown}")?;
match (self.call(token, tool, args).await?, expect) {
(Ok(answer), Expect::Done) => Ok(answer),
(Err(refusal), Expect::Refused) => {
write_wrapped(out, "refused: ", &refusal)?;
Ok(Value::Null)
}
(Ok(answer), Expect::Refused) => {
anyhow::bail!(
"the tour expected {who}'s {tool} to be refused, and it was not: {answer}"
)
}
(Err(refusal), Expect::Done) => {
anyhow::bail!(
"the tour expected {who}'s {tool} to go through, and it was refused: {refusal}"
)
}
}
}
async fn board(
&self,
out: &mut (dyn std::io::Write + Send),
token: &str,
) -> anyhow::Result<()> {
let board = self
.call(token, "factory_board", json!({}))
.await?
.map_err(|e| anyhow::anyhow!("factory_board: {e}"))?;
writeln!(out)?;
for t in board["tasks"].as_array().into_iter().flatten() {
let mut line = format!(
" board #{} {:<10} {}",
t["seq"],
t["stage"].as_str().unwrap_or("?"),
t["title"].as_str().unwrap_or("")
);
if t["attempts"].as_i64().unwrap_or(0) > 0 {
write!(line, " · attempts {}", t["attempts"]).ok();
}
let waits: Vec<String> = t["waiting_on"]
.as_array()
.into_iter()
.flatten()
.map(|s| format!("#{s}"))
.collect();
if !waits.is_empty() {
write!(line, " · waits on {}", waits.join(", ")).ok();
}
writeln!(out, "{line}")?;
}
Ok(())
}
fn step(
&self,
out: &mut (dyn std::io::Write + Send),
n: usize,
total: usize,
title: &str,
text: &str,
) -> anyhow::Result<()> {
let rule = "─".repeat(72);
writeln!(out, "\n{rule}\n Step {n} of {total} · {title}\n{rule}\n")?;
for (i, paragraph) in text.split("\n\n").enumerate() {
if i > 0 {
writeln!(out)?;
}
if paragraph.starts_with(|c: char| c.is_ascii_digit() || c == ' ') {
for line in paragraph.lines() {
writeln!(out, " {line}")?;
}
} else {
write_wrapped(out, "", paragraph)?;
}
}
Ok(())
}
fn said(&self, out: &mut (dyn std::io::Write + Send), text: &str) -> anyhow::Result<()> {
Ok(write_wrapped(out, "→ ", text)?)
}
fn you(&self, out: &mut (dyn std::io::Write + Send), command: &str) -> anyhow::Result<()> {
writeln!(out, "\n (by hand, this is: {command})")?;
Ok(())
}
async fn pause(&self, out: &mut (dyn std::io::Write + Send)) -> anyhow::Result<()> {
if !self.pause || !std::io::stdin().is_terminal() {
return Ok(());
}
write!(
out,
"\n Press Enter for the next step, or open the floor to watch the cards move… "
)?;
out.flush()?;
tokio::task::spawn_blocking(|| {
let mut line = String::new();
std::io::stdin().read_line(&mut line)
})
.await??;
Ok(())
}
fn commit(&self, name: &str, text: &str, who: &str, message: &str) -> Option<String> {
std::fs::write(self.playground.join(name), text).ok()?;
let git = |args: &[&str]| {
Command::new("git")
.args(args)
.current_dir(&self.playground)
.stderr(Stdio::null())
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
};
git(&["add", name])?;
let email = format!("user.email={who}@hird.invalid");
let user = format!("user.name={who} (hird tour)");
git(&[
"-c", &user, "-c", &email, "commit", "--quiet", "-m", message,
])?;
git(&["rev-parse", "--short", "HEAD"])
}
}
fn claim_of(answer: &Value) -> String {
let task = if answer["claimed"].is_object() {
&answer["claimed"]
} else {
answer
};
format!(
"claimed #{}: {}",
task["claimed"]
.as_i64()
.or(task["seq"].as_i64())
.unwrap_or_default(),
task["title"].as_str().unwrap_or("")
)
}
fn at(sha: &Option<String>) -> String {
sha.as_ref().map(|s| format!(" as {s}")).unwrap_or_default()
}
fn write_wrapped(
out: &mut (dyn std::io::Write + Send),
lead: &str,
text: &str,
) -> std::io::Result<()> {
let indent = " ".repeat(2 + lead.chars().count());
let mut line = format!(" {lead}");
let mut fresh = true;
for word in text.split_whitespace() {
if !fresh && line.chars().count() + 1 + word.chars().count() > 76 {
writeln!(out, "{line}")?;
line = indent.clone();
fresh = true;
}
if !fresh {
line.push(' ');
}
line.push_str(word);
fresh = false;
}
writeln!(out, "{line}")
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use hird::config::Config;
use hird::mcp::Shared;
use hird::Db;
use super::*;
use crate::quickstart::{prepare, Options};
use crate::roster::Roster;
use crate::{route, Fleet};
async fn toured(dir: &Path) -> (String, Arc<Shared>, Tour<'static>) {
let ready = prepare(&Options {
dir: dir.to_path_buf(),
harnesses: vec!["claude-code".into(), "codex".into()],
project: None,
bind: "127.0.0.1".into(),
port: 7474,
})
.unwrap();
let roster = Roster::load(&ready.roster).unwrap();
let config = Config {
witness: false,
..Config::default()
};
let shared = Arc::new(Shared::new(Db::open(&ready.db).unwrap(), config.clone()));
let fleet = Fleet::assemble(&roster, shared.clone(), &config).unwrap();
let app = axum::Router::new()
.fallback(axum::routing::any(route))
.with_state(fleet);
let crew: &'static Crew = Box::leak(Box::new(ready.crew));
let dir: &'static Path = Box::leak(dir.to_path_buf().into_boxed_path());
let tour = Tour {
app,
host: "127.0.0.1:7474".into(),
crew,
dir,
playground: ready.playground.unwrap(),
pause: false,
};
let mut out = Vec::new();
assert!(
tour.can_start().await.unwrap(),
"a fresh factory can be toured"
);
tour.play(&mut out).await.unwrap();
(String::from_utf8(out).unwrap(), shared, tour)
}
#[tokio::test]
async fn the_tour_takes_the_first_task_through_every_gate_to_merged() {
let tmp = tempfile::tempdir().unwrap();
let (text, _, tour) = toured(tmp.path()).await;
for step in 1..=8 {
assert!(
text.contains(&format!("Step {step} of 8")),
"step {step} is missing"
);
}
assert!(text.contains("refused:"), "the refusals are shown");
assert!(
text.contains(CI_OUTPUT),
"the rebuild is handed CI's output"
);
let board = tour
.call(&tour.crew.human.1, "factory_board", json!({}))
.await
.unwrap()
.unwrap();
let stage = |seq: i64| {
board["tasks"]
.as_array()
.unwrap()
.iter()
.find(|t| t["seq"] == seq)
.unwrap()["stage"]
.clone()
};
assert_eq!(stage(1), "merged");
assert_eq!(stage(2), "ready");
assert_eq!(stage(3), "ready");
assert_eq!(
std::fs::read_to_string(tour.playground.join("fizzbuzz.py")).unwrap(),
FIXED
);
}
#[tokio::test]
async fn a_factory_already_toured_is_not_toured_again() {
let tmp = tempfile::tempdir().unwrap();
let (_, _, tour) = toured(tmp.path()).await;
assert!(!tour.can_start().await.unwrap());
}
#[test]
fn wrapped_text_stays_within_the_width() {
let mut out = Vec::new();
write_wrapped(&mut out, "→ ", &"word ".repeat(60)).unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.lines().count() > 1);
assert!(text.lines().all(|l| l.chars().count() <= 76));
}
}