diff --git a/.github/workflows/scripts-test.yml b/.github/workflows/scripts-test.yml index 8e7cb8af3d..5c698e63e5 100644 --- a/.github/workflows/scripts-test.yml +++ b/.github/workflows/scripts-test.yml @@ -32,6 +32,10 @@ jobs: python-version: ${{ matrix.python-version }} - name: Run update-nixpkgs-inputs contract tests (#603) run: python3 -m unittest discover -s scripts/tests -p 'test_update_nixpkgs_inputs.py' -v + - name: Run fleet per-seat bootstrap contract tests (#12236) + run: | + test -f scripts/tests/test_fleet_bootstrap.py + python3 -m unittest discover -s scripts/tests -p 'test_fleet_bootstrap.py' -v - name: Run worker preflight contract tests (#4862) run: python3 -m unittest discover -s scripts/tests -p 'test_worker_preflight.py' -v - name: Run failure classifier contract tests (#2176) diff --git a/doc/agents/onboarding-an-agent.md b/doc/agents/onboarding-an-agent.md index aed0f0c533..3092fb7a24 100644 --- a/doc/agents/onboarding-an-agent.md +++ b/doc/agents/onboarding-an-agent.md @@ -24,6 +24,23 @@ fleet agent next # each time you want work done. Exit `5` means no rung had work this run. - `fleet agent doctor` repeats the reachability check at any time. +## One-command bootstrap per seat kind + +When starting on a bare seat that has no `fleet` binary yet, pick the +bootstrap script for the seat kind (#12236): + +| Seat kind | Script | Defaults | +| --------------- | ------------------------------------------- | ------------------------------ | +| Muse sandbox | `scripts/muse/bootstrap.sh` | `--kind muse`, restores home | +| Codespace | `scripts/fleet/bootstrap-codespace.sh` | `--kind generic --name codespace` | +| Laptop service | `scripts/fleet/bootstrap-laptop-service.sh` | `--kind laptop --name laptop` | +| Plain Linux box | `scripts/fleet/bootstrap-linux.sh` | `--kind generic` | + +All four also accept `scripts/fleet/bootstrap.sh --seat `. Each +non-Muse script installs the sha256-verified `fleet` binary, runs +`fleet agent enroll` and `fleet agent doctor`, and enters the three-line +`fleet agent next` loop. + ## An agent that can only make HTTPS requests Enrol it from any seat that has the binary, then give the agent its name: diff --git a/scripts/fleet/bootstrap-codespace.sh b/scripts/fleet/bootstrap-codespace.sh new file mode 100755 index 0000000000..dd53f43c92 --- /dev/null +++ b/scripts/fleet/bootstrap-codespace.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# bootstrap-codespace.sh — bootstrap a 'codespace' fleet seat (developing-today/code, #12236). +# Delegates to scripts/fleet/bootstrap.sh --seat codespace; rejects --seat overrides (#3352). +set -euo pipefail +SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +for arg in "$@"; do + case "$arg" in + --seat|--seat=*) + echo "fleet-bootstrap: usage error: ${0##*/} pins --seat codespace; do not pass $arg" >&2 + exit 2 + ;; + esac +done +exec bash "$SELF_DIR/bootstrap.sh" --seat codespace "$@" diff --git a/scripts/fleet/bootstrap-laptop-service.sh b/scripts/fleet/bootstrap-laptop-service.sh new file mode 100755 index 0000000000..a23810e310 --- /dev/null +++ b/scripts/fleet/bootstrap-laptop-service.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# bootstrap-laptop-service.sh — bootstrap a 'laptop-service' fleet seat (developing-today/code, #12236). +# Delegates to scripts/fleet/bootstrap.sh --seat laptop-service; rejects --seat overrides (#3352). +set -euo pipefail +SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +for arg in "$@"; do + case "$arg" in + --seat|--seat=*) + echo "fleet-bootstrap: usage error: ${0##*/} pins --seat laptop-service; do not pass $arg" >&2 + exit 2 + ;; + esac +done +exec bash "$SELF_DIR/bootstrap.sh" --seat laptop-service "$@" diff --git a/scripts/fleet/bootstrap-linux.sh b/scripts/fleet/bootstrap-linux.sh new file mode 100755 index 0000000000..347fc34eb5 --- /dev/null +++ b/scripts/fleet/bootstrap-linux.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# bootstrap-linux.sh — bootstrap a 'linux' fleet seat (developing-today/code, #12236). +# Delegates to scripts/fleet/bootstrap.sh --seat linux; rejects --seat overrides (#3352). +set -euo pipefail +SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +for arg in "$@"; do + case "$arg" in + --seat|--seat=*) + echo "fleet-bootstrap: usage error: ${0##*/} pins --seat linux; do not pass $arg" >&2 + exit 2 + ;; + esac +done +exec bash "$SELF_DIR/bootstrap.sh" --seat linux "$@" diff --git a/scripts/fleet/bootstrap.sh b/scripts/fleet/bootstrap.sh new file mode 100755 index 0000000000..538afbb13d --- /dev/null +++ b/scripts/fleet/bootstrap.sh @@ -0,0 +1,417 @@ +#!/usr/bin/env bash +# bootstrap.sh — bring up any fleet seat kind (developing-today/code, #12236). +# +# Operator script argument contract (#3352): every argument is declared and +# strictly parsed before any subprocess, network, file write, or lock step. +# Unknown flags, missing/empty option values, --opt= with empty value, and stray +# positional arguments exit 2 naming the offending token. +# +# Seat kinds: +# linux plain Linux box (default kind: generic) +# codespace GitHub Codespace (default kind: generic, name: codespace) +# laptop-service resident laptop service (default kind: laptop, name: laptop) +# muse Muse sandbox (delegates to scripts/muse/bootstrap.sh) +# +# Usage: +# bash scripts/fleet/bootstrap.sh --seat [options] +# bash scripts/fleet/bootstrap-linux.sh [options] +# bash scripts/fleet/bootstrap-codespace.sh [options] +# bash scripts/fleet/bootstrap-laptop-service.sh [options] +# +# Options: +# --seat linux | codespace | laptop-service | muse (default: linux) +# --kind fleet agent kind passed to `fleet agent enroll` +# --name stable agent name ([a-z0-9][a-z0-9._-]{0,62}) +# --groups comma-separated groups for `fleet agent enroll` +# --bin-dir install directory for `fleet` (default: ~/.local/bin) +# --fleet-url release URL for static fleet binary +# --fleet-sha256 expected 64-hex-char SHA-256 of the fleet binary +# --profile explicit profile path passed to `fleet agent enroll` +# --max-iterations max `fleet agent next` loop iterations (default: 1; 0 = none) +# --no-next enroll + doctor only; print the three-line loop +# --dry-run pass --dry-run to `fleet agent enroll`; skip doctor/next +# -h, --help show this help and exit 0 +# +# Three-line agent loop: +# fleet agent next --agent # exit 5 means no work on any rung this run +# # do the task it returns, then run its `then` lines +# # repeat while the run has budget +# +# Exit: 0 ok (including `fleet agent next` exit 5), 1 runtime/verification failure, 2 usage error. +set -euo pipefail + +DEFAULT_FLEET_URL="https://github.com/developing-today/code/releases/download/fleet-static-ad0707b/fleet-x86_64-linux-musl" +DEFAULT_FLEET_SHA256="762bac6318329f202e47f8aeb7727cf6351e22ca93c278fd4d95377febcfa5f2" + +SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +usage() { + sed -n '2,/^set -euo pipefail/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//' + exit "${1:-0}" +} + +die_usage() { + echo "fleet-bootstrap: usage error: $*" >&2 + exit 2 +} + +die() { + echo "fleet-bootstrap: error: $*" >&2 + exit 1 +} + +# ---- strict argument parsing (#3352) — no side effects before this completes ---- +SEAT="" +KIND="" +NAME="" +AGENT_GROUPS="" +BIN_DIR="" +FLEET_URL="" +FLEET_SHA256="" +PROFILE="" +MAX_ITERATIONS="" +NO_NEXT=0 +DRY_RUN=0 +MUSE_PASSTHROUGH=() + +need_value() { + local flag="$1" val="${2-}" has_eq="$3" + if [ "$has_eq" = "1" ]; then + [ -n "$val" ] || die_usage "$flag requires a non-empty value" + else + [ $# -ge 4 ] || die_usage "$flag requires a value" + local next="$4" + case "$next" in + ""|-*) die_usage "$flag requires a non-empty value (got '${next}')" ;; + esac + fi +} + +# If `--seat muse` is explicitly the first option (or any --seat=muse), hand off +# directly to scripts/muse/bootstrap.sh after checking that no conflicting seat was given. +RAW_ARGS=("$@") + +# Pre-scan only for --seat=muse / --seat muse vs another --seat before forwarding. +# Keep non-seat args intact if delegating to scripts/muse/bootstrap.sh. +i=0 +while [ $i -lt ${#RAW_ARGS[@]} ]; do + arg="${RAW_ARGS[$i]}" + case "$arg" in + --seat=*) + val="${arg#--seat=}" + [ -n "$val" ] || die_usage "--seat requires a non-empty value" + [ -z "$SEAT" ] || die_usage "duplicate --seat" + SEAT="$val" + ;; + --seat) + [ $((i + 1)) -lt ${#RAW_ARGS[@]} ] || die_usage "--seat requires a value" + val="${RAW_ARGS[$((i + 1))]}" + case "$val" in ""|-*) die_usage "--seat requires a value" ;; esac + [ -z "$SEAT" ] || die_usage "duplicate --seat" + SEAT="$val" + i=$((i + 1)) + ;; + *) + MUSE_PASSTHROUGH+=("$arg") + ;; + esac + i=$((i + 1)) +done + +if [ "$SEAT" = "muse" ]; then + MUSE_SCRIPT="$SELF_DIR/../muse/bootstrap.sh" + [ -f "$MUSE_SCRIPT" ] || die "missing Muse bootstrap at $MUSE_SCRIPT" + exec bash "$MUSE_SCRIPT" "${MUSE_PASSTHROUGH[@]}" +fi + +SEAT="" +while [ $# -gt 0 ]; do + arg="$1" + case "$arg" in + -h|--help) + usage 0 + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + --no-next) + NO_NEXT=1 + shift + ;; + --seat=*) + val="${arg#--seat=}" + [ -n "$val" ] || die_usage "--seat requires a non-empty value" + [ -z "$SEAT" ] || die_usage "duplicate --seat" + SEAT="$val" + shift + ;; + --seat) + [ $# -ge 2 ] || die_usage "--seat requires a value" + case "$2" in ""|-*) die_usage "--seat requires a non-empty value" ;; esac + [ -z "$SEAT" ] || die_usage "duplicate --seat" + SEAT="$2" + shift 2 + ;; + --kind=*) + val="${arg#--kind=}" + [ -n "$val" ] || die_usage "--kind requires a non-empty value" + [ -z "$KIND" ] || die_usage "duplicate --kind" + KIND="$val" + shift + ;; + --kind) + [ $# -ge 2 ] || die_usage "--kind requires a value" + case "$2" in ""|-*) die_usage "--kind requires a non-empty value" ;; esac + [ -z "$KIND" ] || die_usage "duplicate --kind" + KIND="$2" + shift 2 + ;; + --name=*) + val="${arg#--name=}" + [ -n "$val" ] || die_usage "--name requires a non-empty value" + [ -z "$NAME" ] || die_usage "duplicate --name" + NAME="$val" + shift + ;; + --name) + [ $# -ge 2 ] || die_usage "--name requires a value" + case "$2" in ""|-*) die_usage "--name requires a non-empty value" ;; esac + [ -z "$NAME" ] || die_usage "duplicate --name" + NAME="$2" + shift 2 + ;; + --groups=*) + val="${arg#--groups=}" + [ -n "$val" ] || die_usage "--groups requires a non-empty value" + [ -z "$AGENT_GROUPS" ] || die_usage "duplicate --groups" + AGENT_GROUPS="$val" + shift + ;; + --groups) + [ $# -ge 2 ] || die_usage "--groups requires a value" + case "$2" in ""|-*) die_usage "--groups requires a non-empty value" ;; esac + [ -z "$AGENT_GROUPS" ] || die_usage "duplicate --groups" + AGENT_GROUPS="$2" + shift 2 + ;; + --bin-dir=*) + val="${arg#--bin-dir=}" + [ -n "$val" ] || die_usage "--bin-dir requires a non-empty value" + [ -z "$BIN_DIR" ] || die_usage "duplicate --bin-dir" + BIN_DIR="$val" + shift + ;; + --bin-dir) + [ $# -ge 2 ] || die_usage "--bin-dir requires a value" + case "$2" in ""|-*) die_usage "--bin-dir requires a non-empty value" ;; esac + [ -z "$BIN_DIR" ] || die_usage "duplicate --bin-dir" + BIN_DIR="$2" + shift 2 + ;; + --fleet-url=*) + val="${arg#--fleet-url=}" + [ -n "$val" ] || die_usage "--fleet-url requires a non-empty value" + [ -z "$FLEET_URL" ] || die_usage "duplicate --fleet-url" + FLEET_URL="$val" + shift + ;; + --fleet-url) + [ $# -ge 2 ] || die_usage "--fleet-url requires a value" + case "$2" in ""|-*) die_usage "--fleet-url requires a non-empty value" ;; esac + [ -z "$FLEET_URL" ] || die_usage "duplicate --fleet-url" + FLEET_URL="$2" + shift 2 + ;; + --fleet-sha256=*) + val="${arg#--fleet-sha256=}" + [ -n "$val" ] || die_usage "--fleet-sha256 requires a non-empty value" + [ -z "$FLEET_SHA256" ] || die_usage "duplicate --fleet-sha256" + FLEET_SHA256="$val" + shift + ;; + --fleet-sha256) + [ $# -ge 2 ] || die_usage "--fleet-sha256 requires a value" + case "$2" in ""|-*) die_usage "--fleet-sha256 requires a non-empty value" ;; esac + [ -z "$FLEET_SHA256" ] || die_usage "duplicate --fleet-sha256" + FLEET_SHA256="$2" + shift 2 + ;; + --profile=*) + val="${arg#--profile=}" + [ -n "$val" ] || die_usage "--profile requires a non-empty value" + [ -z "$PROFILE" ] || die_usage "duplicate --profile" + PROFILE="$val" + shift + ;; + --profile) + [ $# -ge 2 ] || die_usage "--profile requires a value" + case "$2" in ""|-*) die_usage "--profile requires a non-empty value" ;; esac + [ -z "$PROFILE" ] || die_usage "duplicate --profile" + PROFILE="$2" + shift 2 + ;; + --max-iterations=*) + val="${arg#--max-iterations=}" + [ -n "$val" ] || die_usage "--max-iterations requires a non-empty value" + [ -z "$MAX_ITERATIONS" ] || die_usage "duplicate --max-iterations" + MAX_ITERATIONS="$val" + shift + ;; + --max-iterations) + [ $# -ge 2 ] || die_usage "--max-iterations requires a value" + case "$2" in ""|-*) die_usage "--max-iterations requires a non-empty value" ;; esac + [ -z "$MAX_ITERATIONS" ] || die_usage "duplicate --max-iterations" + MAX_ITERATIONS="$2" + shift 2 + ;; + --) + shift + [ $# -eq 0 ] || die_usage "unexpected positional argument: $1" + ;; + -*) + die_usage "unknown option: $arg" + ;; + *) + die_usage "unexpected positional argument: $arg" + ;; + esac +done + +SEAT="${SEAT:-linux}" +case "$SEAT" in + linux|codespace|laptop-service) ;; + *) die_usage "unknown --seat '$SEAT' (expected: linux, codespace, laptop-service, muse)" ;; +esac + +if [ -z "$KIND" ]; then + case "$SEAT" in + linux) KIND="generic" ;; + codespace) KIND="generic" ;; + laptop-service) KIND="laptop" ;; + esac +fi + +if [ -z "$NAME" ]; then + if [ -n "${FLEET_AGENT:-}" ]; then + NAME="$FLEET_AGENT" + else + case "$SEAT" in + linux) NAME="$KIND" ;; + codespace) NAME="codespace" ;; + laptop-service) NAME="laptop" ;; + esac + fi +fi + +if ! [[ "$NAME" =~ ^[a-z0-9][a-z0-9._-]{0,62}$ ]]; then + die_usage "invalid --name '$NAME' (must match ^[a-z0-9][a-z0-9._-]{0,62}$)" +fi + +if ! [[ "$KIND" =~ ^[a-z0-9][a-z0-9._-]{0,62}$ ]]; then + die_usage "invalid --kind '$KIND'" +fi + +BIN_DIR="${BIN_DIR:-$HOME/.local/bin}" +FLEET_URL="${FLEET_URL:-${FLEET_URL_ENV:-$DEFAULT_FLEET_URL}}" +FLEET_SHA256="${FLEET_SHA256:-${FLEET_SHA256_ENV:-$DEFAULT_FLEET_SHA256}}" +if ! [[ "$FLEET_SHA256" =~ ^[0-9a-fA-F]{64}$ ]]; then + die_usage "invalid --fleet-sha256 '$FLEET_SHA256' (expected 64 hex chars)" +fi +FLEET_SHA256="${FLEET_SHA256,,}" + +MAX_ITERATIONS="${MAX_ITERATIONS:-1}" +if ! [[ "$MAX_ITERATIONS" =~ ^[0-9]+$ ]]; then + die_usage "invalid --max-iterations '$MAX_ITERATIONS' (expected non-negative integer)" +fi + +# ---- 1. Install pinned fleet binary (exact filename `fleet`, sha256-verified) ---- +mkdir -p "$BIN_DIR" +FLEET_BIN="$BIN_DIR/fleet" + +verify_sha256() { + local file="$1" expected="$2" + echo "${expected} ${file}" | sha256sum -c - >/dev/null 2>&1 +} + +if [ -f "$FLEET_BIN" ] && verify_sha256 "$FLEET_BIN" "$FLEET_SHA256"; then + chmod +x "$FLEET_BIN" + echo "[fleet-bootstrap] binary: already installed and sha256-verified at $FLEET_BIN" +else + tmp_fleet="$(mktemp "$BIN_DIR/.fleet-download.XXXXXX")" + trap 'rm -f "$tmp_fleet"' EXIT + echo "[fleet-bootstrap] binary: downloading $FLEET_URL" + curl -fsSL -o "$tmp_fleet" "$FLEET_URL" || die "download failed from $FLEET_URL" + if ! verify_sha256 "$tmp_fleet" "$FLEET_SHA256"; then + actual="$(sha256sum "$tmp_fleet" | awk '{print $1}')" + die "sha256 mismatch for downloaded fleet binary (expected $FLEET_SHA256, got $actual)" + fi + chmod +x "$tmp_fleet" + mv -f "$tmp_fleet" "$FLEET_BIN" + trap - EXIT + echo "[fleet-bootstrap] binary: verified sha256 and installed $FLEET_BIN" +fi + +# ---- 2. Enroll ---- +ENROLL_ARGS=(agent enroll --kind "$KIND" --name "$NAME") +[ -n "$AGENT_GROUPS" ] && ENROLL_ARGS+=(--groups "$AGENT_GROUPS") +[ -n "$PROFILE" ] && ENROLL_ARGS+=(--profile "$PROFILE") +[ "$DRY_RUN" = "1" ] && ENROLL_ARGS+=(--dry-run) + +echo "[fleet-bootstrap] enroll: seat=$SEAT kind=$KIND name=$NAME" +set +e +"$FLEET_BIN" "${ENROLL_ARGS[@]}" +enroll_rc=$? +set -e + +if [ "$DRY_RUN" = "1" ]; then + echo "[fleet-bootstrap] dry-run complete (enroll exit $enroll_rc)" + echo "[fleet-bootstrap] next loop:" + echo " $FLEET_BIN agent next --agent $NAME" + echo " # do the task it returns, then run its \`then\` lines" + echo " # repeat while the run has budget" + exit "$enroll_rc" +fi + +if [ "$enroll_rc" -ne 0 ] && [ "$enroll_rc" -ne 3 ]; then + die "fleet agent enroll exited $enroll_rc" +fi + +# ---- 3. Doctor ---- +echo "[fleet-bootstrap] doctor: checking legs for $NAME" +set +e +"$FLEET_BIN" agent doctor --agent "$NAME" +doctor_rc=$? +set -e +if [ "$doctor_rc" -ne 0 ] && [ "$doctor_rc" -ne 3 ]; then + die "fleet agent doctor exited $doctor_rc" +fi +if [ "$enroll_rc" -eq 3 ] && [ "$doctor_rc" -eq 3 ]; then + die "no usable intake rungs reachable from this seat (enroll and doctor both returned 3)" +fi + +# ---- 4. Three-line loop ---- +echo "[fleet-bootstrap] loop:" +echo " $FLEET_BIN agent next --agent $NAME # exit 5 = no work on any rung" +echo " # do the task it returns, then run its \`then\` lines" +echo " # repeat while the run has budget" + +if [ "$NO_NEXT" = "1" ] || [ "$MAX_ITERATIONS" -eq 0 ]; then + exit 0 +fi + +iter=1 +while [ "$iter" -le "$MAX_ITERATIONS" ]; do + echo "[fleet-bootstrap] next ($iter/$MAX_ITERATIONS): $FLEET_BIN agent next --agent $NAME" + set +e + "$FLEET_BIN" agent next --agent "$NAME" + next_rc=$? + set -e + if [ "$next_rc" -eq 5 ]; then + echo "[fleet-bootstrap] next: no work on any rung (exit 5)" + exit 0 + elif [ "$next_rc" -ne 0 ]; then + die "fleet agent next exited $next_rc" + fi + iter=$((iter + 1)) +done diff --git a/scripts/tests/test_fleet_bootstrap.py b/scripts/tests/test_fleet_bootstrap.py new file mode 100644 index 0000000000..f834cc56b9 --- /dev/null +++ b/scripts/tests/test_fleet_bootstrap.py @@ -0,0 +1,429 @@ +#!/usr/bin/env python3 +"""Contract and behavior tests for per-seat fleet bootstrap scripts (#12236 item 3).""" + +from __future__ import annotations + +import hashlib +import http.server +import os +import shutil +import stat +import subprocess +import tempfile +import threading +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +FLEET_SCRIPTS = ROOT / "scripts" / "fleet" +BOOTSTRAP = FLEET_SCRIPTS / "bootstrap.sh" +BOOTSTRAP_LINUX = FLEET_SCRIPTS / "bootstrap-linux.sh" +BOOTSTRAP_CODESPACE = FLEET_SCRIPTS / "bootstrap-codespace.sh" +BOOTSTRAP_LAPTOP = FLEET_SCRIPTS / "bootstrap-laptop-service.sh" +MUSE_BOOTSTRAP = ROOT / "scripts" / "muse" / "bootstrap.sh" + + +FAKE_FLEET_SCRIPT = """#!/usr/bin/env bash +set -euo pipefail +# Enforce exact binary filename check just like the real fleet multicall binary. +if [ "$(basename "$0")" != "fleet" ]; then + echo "fleet: refused argv[0]=$0 (must be named fleet)" >&2 + exit 1 +fi +LOG_FILE="${FAKE_FLEET_LOG:?}" +printf '%s\\n' "$*" >> "$LOG_FILE" +case "${1:-}" in + version) + echo "fleet 0.1.0 (test)" + ;; + agent) + shift + case "${1:-}" in + enroll) + exit "${FAKE_ENROLL_EXIT:-0}" + ;; + doctor) + exit "${FAKE_DOCTOR_EXIT:-0}" + ;; + next) + COUNT_FILE="${FAKE_NEXT_COUNT_FILE:-}" + if [ -n "$COUNT_FILE" ]; then + n=0 + [ -f "$COUNT_FILE" ] && n=$(cat "$COUNT_FILE") + n=$((n + 1)) + printf '%s' "$n" > "$COUNT_FILE" + if [ "$n" -ge "${FAKE_NEXT_EXIT5_ON:-999}" ]; then + exit 5 + fi + fi + if [ "${FAKE_NEXT_EXIT:-0}" = "5" ]; then + exit 5 + fi + echo '{"agent":"test","rung":"shortlist","task":{"issue":12236}}' + exit "${FAKE_NEXT_EXIT:-0}" + ;; + *) + exit 2 + ;; + esac + ;; + *) + exit 2 + ;; +esac +""" + + +class _BytesHandler(http.server.BaseHTTPRequestHandler): + payload: bytes = b"" + requests_count: int = 0 + + def do_GET(self): # noqa: N802 + type(self).requests_count += 1 + self.send_response(200) + self.send_header("Content-Length", str(len(self.payload))) + self.end_headers() + self.wfile.write(self.payload) + + def log_message(self, format, *args): # noqa: A002 + return + + +def serve_bytes(payload: bytes): + class Handler(_BytesHandler): + pass + + Handler.payload = payload + Handler.requests_count = 0 + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + port = server.server_address[1] + return server, Handler, f"http://127.0.0.1:{port}/fleet" + + +class TestFleetBootstrap(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="fleet-bootstrap-test-")) + self.home = self.tmp / "home" + self.home.mkdir(parents=True) + self.bin_dir = self.tmp / "bin" + self.log_file = self.tmp / "fleet.log" + self.payload = FAKE_FLEET_SCRIPT.encode("utf-8") + self.sha256 = hashlib.sha256(self.payload).hexdigest() + + def tearDown(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + def base_env(self, extra=None): + env = os.environ.copy() + env.pop("FLEET_AGENT", None) + env.pop("FLEET_AGENT_GROUPS", None) + env["HOME"] = str(self.home) + env["FAKE_FLEET_LOG"] = str(self.log_file) + if extra: + env.update(extra) + return env + + def run_script(self, script: Path, args: list[str], extra_env=None): + return subprocess.run( + ["bash", str(script), *args], + cwd=ROOT, + env=self.base_env(extra_env), + text=True, + capture_output=True, + check=False, + ) + + def test_scripts_exist_and_help_exits_zero(self): + for script in ( + BOOTSTRAP, + BOOTSTRAP_LINUX, + BOOTSTRAP_CODESPACE, + BOOTSTRAP_LAPTOP, + ): + self.assertTrue(script.is_file(), f"missing script: {script}") + res = self.run_script(script, ["--help"]) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertIn("fleet agent next", res.stdout) + res_short = self.run_script(script, ["-h"]) + self.assertEqual(res_short.returncode, 0, res_short.stderr) + + def test_strict_argument_contract_rejects_bad_args_before_side_effects(self): + cases = [ + (BOOTSTRAP, ["--bogus"]), + (BOOTSTRAP, ["extra-positional"]), + (BOOTSTRAP, ["--seat"]), + (BOOTSTRAP, ["--seat="]), + (BOOTSTRAP, ["--seat=unknown"]), + (BOOTSTRAP, ["--kind"]), + (BOOTSTRAP, ["--name", "Bad Name!"]), + (BOOTSTRAP, ["--bin-dir"]), + (BOOTSTRAP, ["--fleet-sha256", "not-hex"]), + (BOOTSTRAP, ["--max-iterations", "abc"]), + (BOOTSTRAP_LINUX, ["--seat", "codespace"]), + (BOOTSTRAP_CODESPACE, ["--seat=linux"]), + (BOOTSTRAP_LAPTOP, ["stray"]), + ] + for script, args in cases: + with self.subTest(script=script.name, args=args): + res = self.run_script(script, args) + self.assertEqual(res.returncode, 2, (res.stdout, res.stderr)) + self.assertFalse( + self.bin_dir.exists(), + f"{script.name} {args} created bin_dir despite invalid args", + ) + + def test_sha256_mismatch_fails_and_leaves_no_fleet_binary(self): + server, _, url = serve_bytes(self.payload) + try: + bad_sha = "0" * 64 + res = self.run_script( + BOOTSTRAP_LINUX, + [ + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + bad_sha, + ], + ) + self.assertEqual(res.returncode, 1, (res.stdout, res.stderr)) + self.assertIn("sha256", res.stderr.lower()) + self.assertFalse((self.bin_dir / "fleet").exists()) + self.assertFalse(self.log_file.exists()) + finally: + server.shutdown() + server.server_close() + + def test_linux_installs_verifies_enrolls_doctors_and_runs_loop_idempotently(self): + server, handler, url = serve_bytes(self.payload) + try: + res = self.run_script( + BOOTSTRAP_LINUX, + [ + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + ], + ) + self.assertEqual(res.returncode, 0, (res.stdout, res.stderr)) + fleet_bin = self.bin_dir / "fleet" + self.assertTrue(fleet_bin.is_file()) + self.assertTrue(bool(fleet_bin.stat().st_mode & stat.S_IXUSR)) + self.assertEqual(handler.requests_count, 1) + + calls = self.log_file.read_text().splitlines() + self.assertEqual( + calls, + [ + "agent enroll --kind generic --name generic", + "agent doctor --agent generic", + "agent next --agent generic", + ], + ) + + # Second run with matching sha256 must skip re-downloading. + res2 = self.run_script( + BOOTSTRAP_LINUX, + [ + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + "--no-next", + ], + ) + self.assertEqual(res2.returncode, 0, (res2.stdout, res2.stderr)) + self.assertEqual(handler.requests_count, 1) + calls2 = self.log_file.read_text().splitlines() + self.assertEqual( + calls2[3:], + [ + "agent enroll --kind generic --name generic", + "agent doctor --agent generic", + ], + ) + finally: + server.shutdown() + server.server_close() + + def test_codespace_and_laptop_service_defaults_and_overrides(self): + server, _, url = serve_bytes(self.payload) + try: + res_cs = self.run_script( + BOOTSTRAP_CODESPACE, + [ + "--kind", + "claude-code", + "--name", + "cs-1", + "--groups", + "claude-code,codespace", + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + ], + ) + self.assertEqual(res_cs.returncode, 0, (res_cs.stdout, res_cs.stderr)) + + res_lap = self.run_script( + BOOTSTRAP_LAPTOP, + [ + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + ], + ) + self.assertEqual(res_lap.returncode, 0, (res_lap.stdout, res_lap.stderr)) + + calls = self.log_file.read_text().splitlines() + self.assertEqual( + calls, + [ + "agent enroll --kind claude-code --name cs-1 --groups claude-code,codespace", + "agent doctor --agent cs-1", + "agent next --agent cs-1", + "agent enroll --kind laptop --name laptop", + "agent doctor --agent laptop", + "agent next --agent laptop", + ], + ) + finally: + server.shutdown() + server.server_close() + + def test_dry_run_and_exit5_and_loop_iterations(self): + server, _, url = serve_bytes(self.payload) + try: + res_dry = self.run_script( + BOOTSTRAP_LINUX, + [ + "--dry-run", + "--name", + "grok", + "--kind", + "grok", + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + ], + ) + self.assertEqual(res_dry.returncode, 0, (res_dry.stdout, res_dry.stderr)) + self.assertEqual( + self.log_file.read_text().splitlines(), + ["agent enroll --kind grok --name grok --dry-run"], + ) + + self.log_file.unlink() + count_file = self.tmp / "next-count" + res_loop = self.run_script( + BOOTSTRAP_LINUX, + [ + "--name", + "grok", + "--kind", + "grok", + "--max-iterations", + "3", + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + ], + extra_env={ + "FAKE_NEXT_COUNT_FILE": str(count_file), + "FAKE_NEXT_EXIT5_ON": "2", + }, + ) + self.assertEqual(res_loop.returncode, 0, (res_loop.stdout, res_loop.stderr)) + self.assertEqual( + self.log_file.read_text().splitlines(), + [ + "agent enroll --kind grok --name grok", + "agent doctor --agent grok", + "agent next --agent grok", + "agent next --agent grok", + ], + ) + self.assertIn("no work on any rung", res_loop.stdout) + finally: + server.shutdown() + server.server_close() + + def test_muse_seat_delegates_to_muse_bootstrap_help(self): + self.assertTrue(MUSE_BOOTSTRAP.is_file()) + res = self.run_script(BOOTSTRAP, ["--seat", "muse", "--help"]) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertIn("Phases", res.stdout) + + + + def test_fleet_agent_env_default_and_no_rungs_fails(self): + server, _, url = serve_bytes(self.payload) + try: + res_env = self.run_script( + BOOTSTRAP_LINUX, + [ + "--kind", + "grok", + "--no-next", + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + ], + extra_env={"FLEET_AGENT": "grok-2"}, + ) + self.assertEqual(res_env.returncode, 0, (res_env.stdout, res_env.stderr)) + self.assertEqual( + self.log_file.read_text().splitlines(), + [ + "agent enroll --kind grok --name grok-2", + "agent doctor --agent grok-2", + ], + ) + + res_down = self.run_script( + BOOTSTRAP_LINUX, + [ + "--name", + "grok-down", + "--bin-dir", + str(self.bin_dir), + "--fleet-url", + url, + "--fleet-sha256", + self.sha256, + ], + extra_env={"FAKE_ENROLL_EXIT": "3", "FAKE_DOCTOR_EXIT": "3"}, + ) + self.assertEqual(res_down.returncode, 1, (res_down.stdout, res_down.stderr)) + self.assertIn("no usable intake rungs", res_down.stderr) + finally: + server.shutdown() + server.server_close() + + +if __name__ == "__main__": + unittest.main()