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
//! `hird-server quickstart`: a factory to try in five minutes.
//!
//! Everything a first factory needs, written into one directory: a roster
//! with fresh tokens (the person running it as `human`, one builder-reviewer
//! token per agent harness, and `ci`), a database, the snippet that connects
//! each harness, two small scripts for the moves no agent makes (`ci` and
//! `human`), and a guide that says what to do with all of it. By default the
//! project is a playground — a fresh git repository with a three-task sample
//! release already filed — so the first run touches nothing of yours.
//!
//! The directory is the state. Running the command again reads the roster
//! back rather than writing a new one, so tokens already pasted into a
//! harness keep working and the board keeps its history. Only the files
//! derived from the roster (snippets, scripts, guide) are written again.

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;

/// What the person asked for.
pub struct Options {
    pub dir: PathBuf,
    pub harnesses: Vec<String>,
    pub project: Option<PathBuf>,
    pub bind: String,
    pub port: u16,
}

/// A factory ready to serve.
pub struct Prepared {
    pub roster: PathBuf,
    pub db: PathBuf,
    pub guide: String,
    /// Who holds which token.
    pub crew: Crew,
    /// The playground, when the project is one.
    pub playground: Option<PathBuf>,
}

/// The crew as the guide and the scripts need it, read back from the roster.
pub struct Crew {
    pub project: String,
    /// (identity, token)
    pub human: (String, String),
    /// The ci token.
    pub ci: String,
    /// (harness, token), sorted by harness.
    pub agents: Vec<(String, String)>,
}

/// The sample release filed into the playground: (title, body, needs).
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],
    ),
];

/// Set the directory up, or read it back, and say what to do next.
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, &notes);
    write_private(&dir.join("GUIDE.md"), &guide)?;

    Ok(Prepared {
        roster: roster_path,
        db: db_path,
        guide,
        crew,
        playground: is_playground.then_some(playground),
    })
}

/// The harnesses asked for, cleaned and deduplicated.
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)
}

/// Who is running this: the `human` in the roster.
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())
}

/// A fresh bearer token: 32 bytes from the operating system, as hex.
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)
}

/// Read the crew back out of a roster, whoever wrote it.
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"
        ),
    }
}

/// A fresh git repository to try the factory in. Git is best-effort: agents
/// work without it, it only makes the merge evidence a real commit.
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))
}

/// File the sample release, as `hird add` would.
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(())
}

/// How one harness connects: (where it goes, what to write or run).
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(())
}

/// The `ci` and `human` scripts: one tool call per command, over curl.
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
}

/// Write a file only its owner may read: it holds tokens.
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());
    }
}