hird-server 0.3.1

The central queue: hird served over HTTP for harnesses on other machines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! `hird-server quickstart --tour`: the sample release, one gate at a time.
//!
//! The quickstart leaves a factory ready for agents. The tour shows what the
//! agents and the gates will do in it before anyone connects one: it plays the
//! two agent harnesses, CI and the human for task #1 of the sample — build,
//! a failing CI run, a rebuild, a review by the other harness, the merge — and
//! stops after each step to say what happened and why. Every move is a real
//! tool call on the server being toured, made with the token the roster gives
//! that member of the crew, so each refusal on the way is the server's own.
//!
//! It ends where the person's own agents begin: #1 merged, #2 and #3 free.

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;

/// Everything the tour needs to know about the factory it plays in.
pub struct Tour<'a> {
    /// The server's routes, called in process.
    pub app: axum::Router,
    /// The `Host` the server is reached as.
    pub host: String,
    pub crew: &'a Crew,
    /// The quickstart directory as the person named it, for the commands
    /// the steps show.
    pub dir: &'a Path,
    pub playground: PathBuf,
    /// Wait for Enter between steps.
    pub pause: bool,
}

/// What the tour expects a move to do.
#[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<'_> {
    /// Whether the board is where the tour starts: #1 untouched and ready.
    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(),
        )
    }

    /// Play the tour, writing it to stdout.
    pub async fn run(&self) -> anyhow::Result<()> {
        self.play(&mut std::io::stdout()).await
    }

    /// Play the tour, writing it to `out`.
    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;

        // ------------------------------------------------------------ 1
        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?;

        // ------------------------------------------------------------ 2
        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?;

        // ------------------------------------------------------------ 3
        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?;

        // ------------------------------------------------------------ 4
        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?;

        // ------------------------------------------------------------ 5
        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?;

        // ------------------------------------------------------------ 6
        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?;

        // ------------------------------------------------------------ 7
        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?;

        // ------------------------------------------------------------ 8
        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(())
    }

    // ------------------------------------------------------------ the wire

    /// One stateless tool call: `Ok(answer)` or `Err(refusal)`.
    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()))
        ))
    }

    /// Make a move as `who`, show it, and check it went as the tour expects.
    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(())
    }

    // ------------------------------------------------------------ the page

    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 == ' ') {
                // A list or a command: keep its lines as written, indented.
                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(())
    }

    /// Write a file into the playground and commit it as `who`. The commit's
    /// short SHA, if git is there to make one.
    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"])
    }
}

/// "claimed #n: title", from a claim answered either way: task_claim's flat
/// answer, or task_next's, which holds the task under `claimed`.
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("")
    )
}

/// " as <sha>", or nothing without one.
fn at(sha: &Option<String>) -> String {
    sha.as_ref().map(|s| format!(" as {s}")).unwrap_or_default()
}

/// Write `text` wrapped at 76 columns, indented under `lead`.
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));
    }
}