diff --git a/.github/workflows/fleet-docs.yml b/.github/workflows/fleet-docs.yml new file mode 100644 index 0000000000..f7474ad440 --- /dev/null +++ b/.github/workflows/fleet-docs.yml @@ -0,0 +1,53 @@ +name: fleet docs + +# CI tier policy: see .github/ci-policy.md + +# Build the fleet book (#13165): pkgs/fleet/book.toml + pkgs/fleet/book, +# rendered by the flake output .#fleet-docs (pkgs/fleet/docs.nix) — the +# same `nix build` locally and in CI, mirroring the mcpx book's build +# job in mcpx-docs.yml. +# +# This workflow only builds; it never deploys. A repository has exactly +# one GitHub Pages site and every Pages deployment replaces the whole +# site, so the fleet book is deployed by the mcpx-docs workflow's +# deploy job, staged under fleet/ with siteUrl "/code/fleet/" — a +# fleet-only deploy from here would wipe the mcpx book (and vice +# versa). See the book's "Deploying this book" chapter: +# pkgs/fleet/book/operations/deploying-this-book.md. + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + name: "build: nix build .#fleet-docs" + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + + - uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23 + + - uses: DeterminateSystems/magic-nix-cache-action@84c0677f58dcedf3b91f8223ce36a9ea5b3c84b7 # v15 + continue-on-error: true + with: + # Same cache posture as mcpx-docs.yml: no FlakeHub, the + # GitHub Actions cache is the cache. + use-flakehub: false + use-gha-cache: true + + - name: Nix build + run: nix build .#fleet-docs --print-build-logs + + # The nix result is a symlink into the store; copy it + # dereferenced so the staged tree is a plain static site. + - name: Stage site + run: | + rm -rf site + cp -rL result site + test -f site/index.html diff --git a/.github/workflows/mcpx-docs.yml b/.github/workflows/mcpx-docs.yml index ed976b1f57..9d0bd09e3e 100644 --- a/.github/workflows/mcpx-docs.yml +++ b/.github/workflows/mcpx-docs.yml @@ -116,6 +116,29 @@ jobs: cp -rL result site test -f site/index.html + # The fleet book (#13165, pkgs/fleet/book) shares this + # repository's single Pages site: a deployment replaces the + # whole site, so the fleet book is built with its own siteUrl + # and staged under fleet/ here, in the same deploy — a separate + # fleet-only deploy would wipe the mcpx book. Its build-only + # workflow is fleet-docs.yml; see the book's "Deploying this + # book" chapter (pkgs/fleet/book/operations/deploying-this-book.md). + - name: Nix build (fleet book, siteUrl /code/fleet/) + run: | + # Intentional: the single-quoted string in this block is a Nix expression + # evaluated by nix, not the shell -- ${builtins.currentSystem} in it is + # Nix's, and letting the shell expand it would break the build. + # shellcheck disable=SC2016 + nix build --impure --print-build-logs --expr \ + '(builtins.getFlake (toString ./.)).packages.${builtins.currentSystem}.fleet-docs.override { siteUrl = "/code/fleet/"; }' \ + --out-link result-fleet-docs + + - name: Stage fleet book into site/fleet + run: | + rm -rf site/fleet + cp -rL result-fleet-docs site/fleet + test -f site/fleet/index.html + - uses: actions/configure-pages@v6 - uses: actions/upload-pages-artifact@v5 diff --git a/lib/default.nix b/lib/default.nix index 5b0760ae3e..f84b0ee599 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -737,6 +737,7 @@ let genericJsRuntime = pkgs.callPackage ../pkgs/generic-containers/js-runtime.nix { }; genericPythonRuntime = pkgs.callPackage ../pkgs/generic-containers/python-runtime.nix { }; mcpxDocs = pkgs.callPackage ../pkgs/mcpx/docs.nix { }; + fleetDocs = pkgs.callPackage ../pkgs/fleet/docs.nix { }; mcpxRealServers = pkgs.callPackage ../pkgs/mcpx/real-servers.nix { }; idMailDeploy = pkgs.callPackage ../nixos/services/id-mail/worker/deploy.nix { }; pkarrDeploy = pkgs.callPackage ../pkgs/pkarr-worker/deploy.nix { @@ -789,6 +790,7 @@ let messageBridgeDeploy ; mcpx-docs = mcpxDocs; + fleet-docs = fleetDocs; mcpx-real-servers = mcpxRealServers; mcpx-container = mcpxContainer; identity-image = identityImage; diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index c1bb4480bc..f93f8a73c2 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -304,6 +304,17 @@ built-ins `fleet init`, `fleet session`, `fleet version`, The per-domain `subcommands` arrays are the top-level command inventory rendered by `fleet --help`. The argument grammar and nested leaves live in the domain handlers and are documented in [`docs/verbs.md`](docs/verbs.md). That reference covers all shipped Fleet domains, top-level verbs, nested queue and agent commands, and where to ask a leaf for exact usage. The queue client dispatches 32 top-level verbs, including `show`; grouped surfaces (`fallback`, `dispatch`, `session`, `surfaces`, `outbox`, and `stack`) document their nested commands and flags in the same reference. Before scripting an unfamiliar command, check `fleet capabilities` and the leaf's `--help`. +The same contract covers the book. [`book/`](book/) (mdBook sources, +`book.toml` at this package's root) is the complete, self-contained +reference for the binary — every domain, subcommand, flag, default and +operational procedure — and any change to a command, flag, default, +capability, surface or procedure updates the matching chapter in the +same change. The rule is recorded for agents in +[`doc/agents/documentation.md`](doc/agents/documentation.md) and in +the book's own "Keeping this book current" chapter. The book builds +with `nix build .#fleet-docs`; `create-missing = false` in +`book.toml` makes a missing chapter a build failure, never a stub. + Shipped examples — every verb below is dispatchable today: ```sh diff --git a/pkgs/fleet/book.toml b/pkgs/fleet/book.toml new file mode 100644 index 0000000000..74d6403995 --- /dev/null +++ b/pkgs/fleet/book.toml @@ -0,0 +1,18 @@ +# mdBook configuration for the fleet book (#13165). +# The book root is pkgs/fleet itself so the sources stay next to the +# binary they document: plain markdown under book/, readable on GitHub +# exactly as written, and rendered as a book via the .#fleet-docs +# flake output (pkgs/fleet/docs.nix). +[book] +title = "fleet" +authors = ["developing-today"] +language = "en" +src = "book" + +[build] +build-dir = "rendered" +# Every chapter in SUMMARY.md must exist on disk; never invent stubs. +create-missing = false + +[output.html] +git-repository-url = "https://github.com/developing-today/code" diff --git a/pkgs/fleet/book/SUMMARY.md b/pkgs/fleet/book/SUMMARY.md new file mode 100644 index 0000000000..a7fa19a99d --- /dev/null +++ b/pkgs/fleet/book/SUMMARY.md @@ -0,0 +1,66 @@ +# Summary + + + +- [fleet](index.md) + +- [Installation and bootstrap](getting-started/installation.md) +- [Quickstart](getting-started/quickstart.md) +- [The shape of the binary](getting-started/shape.md) + +- [Architecture](concepts/architecture.md) +- [The queue: tasks, lanes and leases](concepts/queue.md) +- [Placement and remote dispatch](concepts/placement.md) +- [Secrets and the secrets broker](concepts/secrets.md) +- [The bridge: fleet messaging](concepts/bridge.md) +- [Agents: enrolment, doctor and the intake ladder](concepts/agents.md) +- [Proxy, sessions and recovery](concepts/proxy.md) +- [Search: the Atlas corpus](concepts/search.md) +- [The gh passthrough](concepts/gh.md) +- [Dispatch and dispatch-test](concepts/dispatch.md) + +- [Built-in commands](reference/builtins.md) +- [fleet queue: core verbs](reference/queue-core.md) +- [fleet queue: lifecycle verbs](reference/queue-lifecycle.md) +- [fleet queue: the fallback queue](reference/queue-fallback.md) +- [fleet queue: dispatch and sessions](reference/queue-dispatch.md) +- [fleet queue: inspection and admin](reference/queue-admin.md) +- [fleet serve](reference/serve.md) +- [fleet proxy](reference/proxy.md) +- [fleet dispatch](reference/dispatch.md) +- [fleet dispatch-test](reference/dispatch-test.md) +- [fleet secrets](reference/secrets.md) +- [fleet gh](reference/gh.md) +- [fleet bridge](reference/bridge.md) +- [fleet agent](reference/agent.md) +- [fleet shell](reference/shell.md) +- [fleet search](reference/search.md) +- [fleet laptop-agent](reference/laptop-agent.md) + +- [Tutorial: enrol a new seat](tutorials/enrol-a-seat.md) +- [Tutorial: claim and complete a queue task](tutorials/claim-and-complete.md) +- [Tutorial: dispatch a build remotely](tutorials/dispatch-a-build.md) +- [Tutorial: resolve a secret](tutorials/resolve-a-secret.md) +- [Tutorial: bridge messaging](tutorials/bridge-messaging.md) +- [Tutorial: run the brokers](tutorials/run-the-brokers.md) + +- [The crates](library/crates.md) +- [The queue client](library/queue-client.md) +- [Placement and surfaces as data](library/placement.md) +- [Registry, config and capabilities](library/registry-and-config.md) + +- [Repository layout](development/layout.md) +- [Building fleet](development/building.md) +- [Testing](development/testing.md) +- [Add a subcommand](development/add-a-subcommand.md) +- [Add a flag](development/add-a-flag.md) +- [Register a domain or capability](development/register-a-domain.md) +- [Release and rollout](development/release-and-rollout.md) +- [Keeping this book current](development/keeping-this-book-current.md) + +- [Running the brokers as services](operations/services.md) +- [Health checks and the heal stack](operations/health-and-healing.md) +- [Troubleshooting](operations/troubleshooting.md) +- [Deploying this book](operations/deploying-this-book.md) +- [FAQ](operations/faq.md) +- [Glossary](operations/glossary.md) diff --git a/pkgs/fleet/book/concepts/agents.md b/pkgs/fleet/book/concepts/agents.md new file mode 100644 index 0000000000..1a92373308 --- /dev/null +++ b/pkgs/fleet/book/concepts/agents.md @@ -0,0 +1,208 @@ +# Agents: enrolment, doctor and the intake ladder + +The fleet already had the legs — bridge mailboxes, the queue, the laptop +transport, GitHub, secrets by name. What a new kind of agent lacked was one +place to enrol, check its seat, and take work. `fleet agent` is that place. +Its verbs are `kinds`, `enroll`, `doctor`, `next`, and `shortlist`; every +verb prints one JSON object. `fleet shell` is its sibling domain, riding on +the same `agent` capability. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-agent/src/lib.rs + +As with the bridge, every per-verb `--help` prints the same shared usage +text; there is no per-verb help in source. This chapter is the per-verb +reference. + +## Kinds and seat shapes: 16 × 3 + +A *kind* says three things: which bridge groups the agent joins, how it +reaches the fleet from where it runs, and what to tell it at enrolment. +`fleet agent kinds` prints the table as JSON — for each kind its name, +summary, bridge groups, seat, and enrolment note, plus the three seat +definitions. Adding a kind is adding a row; no verb changes. + +A *seat shape* is how the agent runs: + +- **binary** — has a shell and runs the fleet binary itself: `enroll`, then + `next`. +- **http** — no shell of its own; speaks the bridge's fleet routes over + HTTPS (the reference client is `scripts/fleet/bridge-mailbox.py`) and gets + work from its mailbox. +- **connector** — a chat assistant with the Message Bridge connector + attached; it has a channel address, not a mailbox. + +The 16 kinds: + +| Kind | Groups | Seat | Note | +|---|---|---|---| +| `muse` | muse | binary | A fresh Muse gets a bridge-capable static build from `scripts/muse/bootstrap.sh`; older installs run the same commands on the laptop install via `~/tools/laptop-ssh.sh`. | +| `opencode` | opencode | binary | Runs on the laptop seat, so every leg is local. | +| `openchamber` | opencode, openchamber | binary | Joins `opencode` too, so `group:opencode` reaches both pipelines. | +| `openclaw` | openclaw | binary | | +| `claude-code` | claude-code | binary | A cloud session has no tailnet: messaging and the priority rung work over HTTPS; builds go through `fleet shell`. | +| `codex` | codex | binary | | +| `gemini` | gemini | binary | | +| `antigravity` | antigravity | binary | | +| `grok` | grok | binary | A bot with no shell enrols as kind `http` under the same name and groups. | +| `dot` | dot | http | Its Slack and ChatGPT transports are carried elsewhere; the mailbox is the same store. | +| `duet` | duet | http | | +| `claude` | (none) | connector | Fixed bridge address `claude`; set a wake hook for channel:claude so a send starts a session. | +| `chatgpt` | (none) | connector | Fixed address `chatgpt`; woken by its MCP Events subscription. | +| `laptop` | laptop | binary | A job or service on the fleet laptop. | +| `http` | (none) | http | Anything that can make an HTTPS request and nothing else. | +| `generic` | (none) | binary | Any other agent with a shell — the fallback the enrolment error names. | + +## Enrolment and the profile + +``` +fleet agent enroll --kind K --name N [--groups a,b] [--dry-run] [--profile PATH] +``` + +The kind is validated (an unknown kind is a usage error listing all kinds — +"use generic for anything with a shell"). `--groups` adds to the kind's +built-in groups. For a binary or http seat, the bridge leg is probed in +*register* mode — a bridge `hello` with the name and groups, which is what +actually registers the mailbox. Connector kinds instead get the "attach the +connector" instruction and a fixed channel address. The four legs are +probed (below) and the saved *profile* — at the default path, or `--profile` +— records the agent, kind, groups, and leg state. `--dry-run` probes nothing +and registers nothing. + +The JSON answer carries the profile, `registered` (true only when it is not +a dry run *and* the bridge leg answered), the legs, the *rungs* map (below), +and seat-specific next-step lines: for a binary seat, the run loop +(`fleet agent next --agent `, do the task, run its `then` lines, +repeat while the run has budget) and the `fleet shell` line ("runs where +builds belong; never build in a limited sandbox"); for an http seat, the +token-by-name note and the reference-client commands; for central, the +`fleet bridge send` lines. Exit 0 for a dry run, or when any intake rung is +live; otherwise 3. + +## Doctor: the four legs + +``` +fleet agent doctor [--agent N] +``` + +**The four legs are `bridge`, `queue`, `github`, and `shell`.** There is no +secrets leg: secrets is folded into the bridge leg's stated need ("HTTPS to +the message bridge, and the fleet token by name through fleet secrets"). +Any text describing the legs as bridge/queue/secrets/shell is wrong — the +source is explicit, and this book follows the source. + +The four probes are independent, issued together (one parallel call), and +each is a real fleet verb run as this seat: + +| Leg | Probe | Needs | +|---|---|---| +| bridge | `bridge hello` (enrol) / `bridge inbox --agent A --limit 1` (doctor with a name) / `bridge health` (no name known) | HTTPS to the bridge + the fleet token by name through fleet secrets | +| queue | `queue health` | The queue broker: its socket on the laptop, or the laptop transport from elsewhere | +| github | `gh api rate_limit` via `fleet gh`; if that fails, plain signed-in `gh api rate_limit` (the answer records `route: "fleet"` or `"plain"`) | `gh` with a token: fleet gh's rotation, or a signed-in gh | +| shell | `laptop-agent health` | A route to the laptop: its broker, the Cloudflare tunnel, the tailnet, or SSH | + +Doctor's bridge probe with a known agent is a read that takes nothing +(`inbox --limit 1`): service health alone proves nothing about whether this +seat holds the fleet token, so only a call made *as* an agent counts. With +no agent name, the bridge leg is reported **not ok** even when the service +answers ("the service answers, but no agent name is known to read a mailbox +with: enrol, or pass --agent"). + +From the legs, doctor derives the **rungs** map — which intake rungs this +seat still has: `push` = the bridge leg, `queue` = the queue leg, +`shortlist` = **always true** (it is a local file), `priority` = the github +leg. It also reports `builds`: "fleet shell reaches the laptop" when the +shell leg answers, else "fleet shell has no laptop route from here; it will +try a codespace, then run here". Exit 0 when any intake rung is live +(bridge, queue, or github), else 3. + +## `next`: the intake ladder + +``` +fleet agent next [--agent N] [--lane L] [--repo OWNER/NAME] [--low-water N] + [--shortlist PATH] [--platform P] [--pool P] + [--remaining-budget-minutes N] [--filter EXPR] [--queue Q] + [--no-push] [--no-queue] [--no-shortlist] [--no-priority] +``` + +`next` tries four rungs **in order** and returns the first that yields work. +A rung that is *down* (bridge unreachable, broker not answering) is not the +same as a rung that is *empty*: down rungs are recorded and skipped, so a +seat with only HTTPS still gets work from rungs 1 and 4. Every answer is +`{agent, rung, task, then, tried}` — `tried` is the per-rung log +(`skipped`/`empty`/`down`/`rejected`, with a reason), and `then` is the list +of follow-up commands the runner should execute for the handed-out task. +The default repo is `developing-today/code`. The `--no-*` flags skip +individual rungs (recorded as `skipped`); `--low-water N` overrides the +shortlist low-water mark for this call; `--lane`, `--queue`, `--platform`, +`--pool`, `--remaining-budget-minutes`, and `--filter` are carried into the +queue claim. + +1. **Push** — a command addressed to this agent on the bridge + (`bridge inbox --commands --take`). This rung outranks everything: a + command a person (or central) pushed is work already chosen. +2. **Queue** — a claim on the one fleet queue (`queue claim` with the + agent's lane; the lane defaults from the agent name, known lane families + are validated by the queue, and a lane registered to a shared queue + worker is honoured). `next` claims with a **4-hour lease** (14,400 s, + overriding the queue's 45-minute default, which lapses mid-task), and + the task's `then` lines name the lease deadline plus the + `queue checkpoint` / `queue complete` commands with the claimed + worker/lane. A broker refusal that is really a lane verdict (lane bound + to another queue, registration did not land) is reported as rung + `rejected`, distinct from `down`. +3. **Shortlist** — the top of this host's local shortlist. Entries are + re-checked against GitHub before hand-out (an issue closed, assigned, or + owner-parked since listing is dropped with a named reason), then handed + out in rank order. **Refill switch:** if the list is at or below + low-water with nobody refilling, `next` does not hand out a stale + remnant — it returns rung **`refill`** instead, a purpose-switch task + (`purpose: "refill-shortlist"`, target the shortlist default target) + whose instructions and `then` lines are the `shortlist fill` / + `shortlist add` commands. One run refills; the marker it leaves keeps + the rest working. +4. **Priority** — the highest-priority open issue straight from GitHub. + Label queries run soonest-first over the priority label family + (`priority/critical`, then `priority/high`, … — the same ordering as the + shortlist ranks below); candidates are filtered (owner-parked labels — + the `user/owned`, `user/review`, `user/escalated` class — are kept out), + and the winner is **reserved into the shortlist file** as it is handed + out, so two seats on one host do not take the same issue. + +## The shortlist: ranks, low-water, refill + +The shortlist is a local JSON file on this host (default path from the +profile/state directory; `--shortlist PATH` overrides), guarded by a lock +file (stale after 30 s; 100 tries at 50 ms). Entries are +`{repo, issue, title, rank, why, added_at}`, plus handed-out records and an +optional refill marker. The queue verbs neither read nor write it — the +shortlist is the agent domain's concern, and any interplay is at the caller +level. + +**Rank** (lower is sooner): `expedite` → 0, `priority/critical` → 1, +`now` → 2, `priority/high` → 3, `next` → 4, `priority/normal` → 5, anything +else unranked = 6. Hand-out order is lowest rank, then oldest `added_at`, +then lowest issue number. + +**Defaults: low-water 3, target 8.** A list is *low* when +`entries ≤ low_water` — so a list of exactly 3 is already low. +`shortlist status [--low-water N]` reports the list, its count, `low`, and +the refill state. `shortlist add --issue N --title T [--repo R] [--rank N] +[--why TEXT]` adds one entry (rank defaults to unranked 6; duplicates — +same repo and issue already listed — are refused). `shortlist take` hands +out the soonest entry; `shortlist clear` empties the list and clears the +refill marker. `shortlist fill [--repo R] [--target N]` tops the list up to +the target (default 8, clamped 1–50) from the priority candidates: it +fetches **2× target** candidates from GitHub, adds them in rank order until +the target is met, records the fill, and clears the refill marker. + +**Refill bookkeeping.** A refill marker `(by, at)` lasts **1800 s +(30 minutes)**; a list needs refill when it is low, no marker is live, and +no fill finished within the window. A handed-out issue is kept from being +handed out again on this host for **7200 s (2 hours)**; pruning drops +expired handed records and expired markers. + +## Exit codes + +The agent domain's vocabulary: **0** ok; **2** usage; **3** a needed leg is +down (doctor/enrol with no intake rung live); **5** — `next` only — no work +on any rung. diff --git a/pkgs/fleet/book/concepts/architecture.md b/pkgs/fleet/book/concepts/architecture.md new file mode 100644 index 0000000000..2dae6adcf8 --- /dev/null +++ b/pkgs/fleet/book/concepts/architecture.md @@ -0,0 +1,170 @@ +# Architecture + +Fleet is a self-contained Cargo workspace at `pkgs/fleet/` in +developing-today/code: its own `Cargo.toml`, `Cargo.lock`, and +`rust-toolchain.toml` (channel 1.99.1), with no workspace relationship to the +repo root. The workspace package is version 0.1.0, edition 2024, Rust 1.85 +minimum, licensed MIT OR Apache-2.0. The release profile is a size contract, +not a speed profile (`opt-level = "z"`, LTO on, one codegen unit, stripped): +the connect variant's budget is a target of at most 1.5 MiB and a hard limit +of 2 MiB, stripped. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/Cargo.toml + +## The crates map: 13 crates + +| Crate | Owns | +|---|---| +| `fleet` (the bin) | The multicall entrypoint (`src/main.rs`), root built-ins, dispatch and the stub machinery, plus the domains that live in the bin crate itself: `secrets` verbs (over `fleet-secrets`), and `gh` with its cache, closure, guard, and metadata modules. | +| `fleet-registry` | The domain registry: the 15 capability atoms, the three variants and their capability sets, the 12 domain entries (name, summary, capabilities, primary capability, aliases, subcommand inventory), and the argv0 alias map. Dependency-free; compiled into every variant so help is always complete. | +| `fleet-config` | The one place config resolves: `fleet.toml` (default `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`, overridable with `FLEET_CONFIG`), the `[domains]` switches, `[proxy]`, `[secrets]`, `[queue-broker]`, `[secrets-broker]`, `[dispatch]`, `[host]` sections, and the fleet's path/port/socket constants. Resolution order is environment → config file → compiled-in defaults. A missing file is not an error; a malformed file — including unknown sections or keys — is a loud error on every path, never a silent fallback. | +| `fleet-secrets` | The secret resolver library: the broker-first, Bitwarden-fallback chain, by name only. Every domain that needs a secret resolves it through this crate; no domain shells out to `bws` or reads a token file on its own. | +| `fleet-proxy-proto` | The session-broker wire protocol: 8-byte big-endian length-prefixed JSON frames, the hello/capability handshake, and the protocol version window (current and previous major, plus legacy proto 0). | +| `fleet-proxy` | The session proxy: the broker (`serve`), the client (`connect`, `init`, `ssh`, `get`/`put`), raw splice, tunnels, and shims. The client half is in every variant; only the broker half is feature-gated. | +| `fleet-queue` | The queue domain end to end: the client (32 verbs), the queue broker, the secrets broker, the Turso queue store, packet validation, the GitHub fallback queue, placement, the creation outbox, and merge-intent stacks. Its features split the surfaces: `client`, `queue-broker`, `secrets-broker`. | +| `fleet-dispatch` | The `dispatch` domain: a single-file thin client over the pm-dispatch HTTP service. | +| `fleet-dispatch-test` | The `dispatch-test` domain: scan/submit/status over GitHub and its Turso jobs store. | +| `fleet-laptop-agent` | The `laptop-agent` client: verbs, transport legs, and the connection ladder for the laptop-agent daemon. | +| `fleet-search` | The `search` domain: the Atlas client surface, and — behind its `serve` feature — the Atlas search service itself, consuming the `atlas-core`/`atlas-embed`/`atlas-proto` crates from `pkgs/atlas-search` by relative path. | +| `fleet-bridge` | The `bridge` domain: the mailbox client for the message bridge (send/agents/log for central; hello/inbox/post/ack/health for agents). | +| `fleet-agent` | The `agent` and `shell` domains: kinds, enrolment, doctor, the intake ladder (`next`), the shortlist, and the shell target planner. It links only `fleet-config`: it runs the other domains' verbs through this same binary rather than linking them. | + +Domain ownership, one line each: `queue` → `fleet-queue`; `serve` → bin-crate +glue over `fleet-queue` / `fleet-search` / `fleet-proxy`; `proxy` → +`fleet-proxy` (+ `fleet-proxy-proto`); `dispatch` → `fleet-dispatch`; +`dispatch-test` → `fleet-dispatch-test`; `secrets` → the bin crate over +`fleet-secrets`; `gh` → the bin crate; `bridge` → `fleet-bridge`; `agent` and +`shell` → `fleet-agent`; `search` → `fleet-search`; `laptop-agent` → +`fleet-laptop-agent`. + +## The brokers and their ports and sockets + +A *broker* in fleet is a resident process that other processes ask for a +service, as distinct from a library they link. There are three fleet brokers, +plus the laptop-agent daemon and two auxiliary services: + +| Service | Port | Unix socket (default) | Notes | +|---|---|---|---| +| laptop-agent daemon | 4799 | — | The Python daemon on the laptop that runs jobs. Not a fleet binary, but the proxy's routing table names it. | +| secrets-broker | 4800 | `~/.config/secrets-broker/broker.sock` | The Bitwarden cache. Dual-binds TCP and the Unix socket with identical routes and auth. On the sandbox its TCP bind is forced to `127.0.0.1:4800`. | +| queue-broker | 4801 | `~/.config/queue-broker/broker.sock` | The work queue service. Dual-binds TCP (`100.99.113.103:4801`, the laptop tailnet address) and the Unix socket. | +| gh cache daemon | 4802 | — | Loopback token/secret cache for the `gh` passthrough. See [The gh passthrough](gh.md). | +| pm-dispatch | 4879 | — | The TypeScript/Bun dispatch service the `dispatch` domain is a client of. | +| session broker (proxy) | — (socket only) | `~/.cache/laptop-agent/broker.sock` | The sandbox-side broker every local client talks to; it tunnels framed requests to the laptop's services. Socket overridable with `FLEET_BROKER_SOCKET`. | +| RustDesk direct access | 21118 | — | Also the loopback listen port of `fleet proxy splice`. | +| tailnet egress proxy | 3130 | — | The host session's CONNECT proxy. Not a fleet listener; fleet is its client. | + +The session broker's routing table maps port → service name — 4799 +laptop-agent, 4800 secrets-broker, 4801 queue-broker, 21118 rustdesk — and +that map is what its hello frame advertises to clients. + +Daemon-side token files live in each broker's own config directory +(`~/.config/queue-broker/token`, `~/.config/secrets-broker/token`). They are +different files from the client-side token files under `~/tools/`; see +[Secrets and the secrets broker](secrets.md). + +The brokers are run by `fleet serve`: one role in the foreground, or a list +of roles in one process, one thread each, fail-fast — the first role thread +to return or panic takes the whole process down and the external supervisor +(systemd) restarts the unit. A role that exits cleanly is converted to exit +1, because a daemon role returning at all is abnormal. See +[Proxy, sessions and recovery](proxy.md) for the proxy's own serve +behaviour. + +## The Turso store + +The queue's only backend is a dedicated Turso (libSQL) database named +`fleet-queue`. The queue broker is the only process that talks to it; clients +never touch the database. Because libSQL is single-writer, a claim is one +conditional UPDATE whose WHERE clause re-checks claimability against the +picked row — the equivalent of `FOR UPDATE SKIP LOCKED`; a competing claim +that loses matches no row and is answered as "no claim". The schema (tasks, +leases, lanes, workers, checkpoints, the lane ledger, events, the creation +outbox, merge intents) is detailed in +[The queue: tasks, lanes and leases](queue.md#the-turso-store). + +`dispatch-test` keeps a second, separate Turso database for its job rows; +see [Dispatch and dispatch-test](dispatch.md). + +## The session proxy + +Sandbox seats cannot dial the laptop's services directly. The session proxy +is the bridge: a broker process on the sandbox side, owning the session +broker Unix socket, which tunnels framed requests (8-byte big-endian +length-prefixed JSON) to the laptop. Token files are read per request and +never stored or logged; the broker persists nothing — its routing table comes +from config and its tunnels live in memory. The full mechanics — warm tunnel +pools, the Cloudflare leg versus the tailnet fallback, recovery — are in +[Proxy, sessions and recovery](proxy.md). + +## Data flows + +### The claim path (an agent takes queue work) + +1. The agent runs `fleet agent next`; the queue rung runs `fleet queue claim` + through this same binary, with a 4-hour lease. +2. The queue client chooses a route to the queue broker: a configured direct + URL (TCP or the broker's Unix socket) on the laptop, or — the sandbox + default — a framed exchange through the session broker socket to port + 4801, naming the client token file `~/tools/queue-broker-token`. The + session broker reads that file on the laptop side and forwards the token + as the `X-Agent-Token` header. +3. The broker authenticates from headers alone (a wrong or missing token is + 401, an oversized body 413, before any body byte is read), then runs the + claim against the Turso store: expire lapsed leases, pick the + highest-priority due row, stamp worker/lane/session/model, set the lease, + write the `claimed` event — in one conditional update. +4. The client checks the claimed task's issue against the GitHub fallback + queue; if the fallback currently holds that issue under a different + worker, the client blocks the task back with reason class `fallback_held` + and reports no claim (exit 5). If the GitHub check itself fails, the claim + is served with a warning — the guard fails open. +5. The client prints the task row as JSON, plus a `mode_line` describing the + route the claim took. No matching row is `{"task": null}`, exit 5. + +### The secret path (a caller resolves a name) + +1. A caller — a domain inside fleet, or `fleet secrets get ` — asks + `fleet-secrets` to resolve a name. Nothing else in the system resolves + secrets. +2. The chain tries the broker leg first: directly over the secrets broker's + Unix socket where that socket answers (the laptop), else by a framed + exchange through the session broker to port 4800, naming the token file + `~/tools/secrets-broker-token`. The session broker reads the file per + request; the value never transits fleet's own memory on this leg. +3. A broker answer of 404 is definitive about the name and is not retried. A + broker that cannot answer is retried with a bounded backoff budget sized + to real restart windows, then the chain moves on. +4. The fallback leg runs `bws secret list` + `bws secret get`, with the + machine-account credential from the `BWS_ACCESS_TOKEN` environment + variable or the on-disk token file. +5. The value is returned in a type whose debug output is redacted. For + `fleet secrets get`, it goes to stdout and nowhere else. Broker-side cache + semantics — ages, read-through, refresh — are in + [Secrets and the secrets broker](secrets.md). + +### The dispatch path (a build runs remotely) + +1. A caller runs `fleet queue dispatch --repo --command '' + --dispatch` (or `fleet shell --target actions`, which drives the same + verb). +2. Placement loads the surface registry — data, not code: `--registry` or + `FLEET_PLACE_REGISTRY`, else a home copy, else the source-tree path, else + the copy embedded in the binary — and measures live load: for each owner, + the in-progress plus queued run counts on that owner's fleet runner-host + repos, read from the GitHub API. +3. The tier cascade picks a surface: a hard `--surface` pin first, then + follow-up affinity, then free GitHub-hosted Actions (least-loaded owner, + least-recently-used rotation), then Blacksmith within its minute budget, + then codespaces as the last resort. Every step appends a reasoning line. +4. The adapter mints the token the surface dispatches as (a GitHub App + installation token, or the signed-in user's token), snapshots the host + repo's existing workflow runs, and POSTs the `fleet-command.yml` workflow + dispatch. Anything but HTTP 204 is fatal. +5. It polls the run list (up to 12 polls, 3 s apart) for the new run — + matched by a fresh dispatch id in the run title when the surface declares + one — and writes a session record under a handle `fp_` plus 32 hex + characters in `~/.local/state/fleet-place/sessions.json`. +6. The caller follows the run with `fleet queue session status|result + `; the portable form `OWNER/REPO#RUN_ID` resolves the same run + without the local store. Full detail: [Placement and remote dispatch](placement.md). diff --git a/pkgs/fleet/book/concepts/bridge.md b/pkgs/fleet/book/concepts/bridge.md new file mode 100644 index 0000000000..e0e3aa90b0 --- /dev/null +++ b/pkgs/fleet/book/concepts/bridge.md @@ -0,0 +1,94 @@ +# The bridge: fleet messaging + +The bridge is the fleet's message bus. The bridge service itself lives at +https://bridge.security.cab (a separate worker, `pkgs/message-bridge`); the +`fleet bridge` domain is its mailbox client. The model: every fleet agent +has a *mailbox* on the bridge named after it, and registers with optional +*groups* (for example `muse`, `codex`, `code-lanes`). Central sends a +message or a command to one agent, a group, or all; the agent reads its +mailbox, does the work, and posts its answer back, which marks the command +handled. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-bridge/src/lib.rs + +One documentation fact first: there is **one usage text for the whole +domain** and no per-verb help in source — every per-verb `--help` prints the +same shared usage block, despite the domain help's "(options: fleet bridge +<command> --help)" status line. This chapter is the per-verb reference the +help does not provide. + +## The two verb families + +The verbs split by which token they use and which routes they call. + +**Central verbs** (the owner token — full control): + +| Verb | Route | Behaviour | +|---|---|---| +| `send --to [--command] [--sender NAME] ` | `POST /api//fleet/send` | Targets: `agent:` (or a bare name), `group:`, `all`; repeat `--to` or comma-separate. `--command` marks the item a command (default: a plain message). `-` reads the text from stdin. | +| `agents` | `GET /api//fleet/agents` | Registered agents, their groups, and unread counts. | +| `log [--agent A] [--direction inbound\|outbound] [--kind message\|command] [--since-id N] [--before-id N] [--limit N] [--order asc\|desc]` | `GET /api//fleet/messages?…` | The central message log, filtered. | + +**Agent verbs** (the fleet token — mailbox access only; it cannot send +commands): + +| Verb | Route | Behaviour | +|---|---|---| +| `hello [--agent A] [--groups g1,g2]` | `POST /fleet//hello` with `{agent, groups}` | Register or refresh this agent and its groups. This is the registry write: the bridge's agent registry is exactly the set of agents that have said hello (name, groups, last-seen, unread counts). | +| `inbox [--agent A] [--groups g1,g2] [--commands \| --messages] [--all] [--since-id N] [--limit N] [--take] [--wait SECS] [--interval SECS]` | `GET /fleet//inbox?…` | Unread items by default; `--all` includes read ones; `--take` marks what it returns as read; `--wait` polls (default interval 15 s; wait capped at 24 h in source) until something arrives or the seconds pass. | +| `post [--agent A] [--reply-to ID] [--to ADDR] [--instruction \| --kind K] ` | `POST /fleet//send` | A message to central by default. With `--reply-to` it answers that row (and marks it read). `--to` sends to any address instead: `drew`, `claude`, `chatgpt`, `connectors`, `agent:` (or a bare name), `group:`, `agents`, `all`; repeat or comma-separate. `--instruction` (or `--kind instruction`) makes it an instruction, which requires `--to`. | +| `ack [--agent A] (--up-to ID \| ID...)` | `POST /fleet//ack` | Mark messages read: either a list of ids, or everything up to an id. | +| `health` | `GET /healthz` | The bridge's health probe. No token. | + +Defaults and config: the agent name defaults to `$FLEET_AGENT`, then +`[bridge] agent`; groups to `$FLEET_AGENT_GROUPS`, then `[bridge] groups`; +the bridge URL to `$FLEET_BRIDGE_URL`, then `[bridge] url`, then +`https://bridge.security.cab` — environment beats file throughout. Output is +the bridge's JSON, passed through. + +Exit codes: 0 ok, 2 usage, 3 transport or credentials, **4 the bridge +refused the request** (its JSON error goes to stderr). + +## Mailbox and ack semantics + +A mailbox item is a *message* or a *command* (the kind is set by the +sender: `send --command`, and the intake ladder's push rung reads commands +only). Items are read or unread. Reading is non-destructive by default: +`inbox` without `--take` shows unread items and leaves them unread. Three +operations change read state: + +- `inbox --take` marks exactly what it returns as read — the "I have this + now" claim. `fleet agent next`'s push rung uses `--commands --take`, so a + pushed command is consumed by exactly the hand-out that returns it. +- `post --reply-to ID` answers a row and marks that row read. +- `ack` marks explicit ids, or everything up to an id with `--up-to`. + +The registry side is equally simple: there is no separate enrolment store +on the bridge. Saying `hello` *is* registering — name, groups, and last-seen +are refreshed on every hello — and `agents` reports the registry as the set +of agents that have said hello, with their unread counts. `fleet agent +enroll` builds on this: its bridge-leg probe is a `hello` in register mode +(see [Agents: enrolment, doctor and the intake ladder](agents.md)). + +## Tokens and the HMAC derivation + +Auth is by secret name through `fleet-secrets`; values are never printed, +logged, or put in argv. Central verbs use the **owner token**, secret name +`message-bridge.access-token` (`[bridge] owner_token_name` can rename it). +Agent verbs use the **fleet token**, secret name +`message-bridge.fleet-token`, which opens only the agent routes. + +Tokens travel **in the URL path** (see the routes above), so every error +string is scrubbed of token values (replaced with ``) before it is +printed, and a 404 is reported as "a wrong token, an old bridge without +fleet mailboxes, or a wrong URL". Plain `http` URLs are accepted only to +this machine; anything else must be `https`, because tokens ride the path. + +**Derivation fallback.** When the fleet token's secret is missing but the +owner token resolves (the laptop seat's shape), the fleet token is +**derived from the owner token exactly as the bridge derives it**: +`base64url(HMAC-SHA256(key = owner token bytes, message = +"message-bridge/fleet-token/v1"))` — the fixed label constant is the string +`message-bridge/fleet-token/v1`. The derived value is used in-process only; +it is never written anywhere. (Construction and label named, no values — +that is the whole public shape of the derivation.) diff --git a/pkgs/fleet/book/concepts/dispatch.md b/pkgs/fleet/book/concepts/dispatch.md new file mode 100644 index 0000000000..302b05ad69 --- /dev/null +++ b/pkgs/fleet/book/concepts/dispatch.md @@ -0,0 +1,248 @@ +# Dispatch and dispatch-test + +Two different domains share the word "dispatch", and a third verb besides. +This chapter keeps them apart: + +- **`fleet dispatch`** — a thin client over pm-dispatch, an existing + TypeScript/Bun service that is *not* rewritten in fleet. Its verbs are + `status`, `launch`, and `enqueue`. +- **`fleet dispatch-test`** — an explicit-dispatch CI test: scan fleet repos + for free Actions capacity, submit a job, track its stored status. Nothing + here is trigger-driven; every verb runs only when a caller invokes it. +- Not this chapter: `fleet queue dispatch`, which is placement — see + [Placement and remote dispatch](placement.md). + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-dispatch/src/lib.rs and https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-dispatch-test/src/lib.rs + +## `fleet dispatch`: the pm-dispatch client + +Per-task status is deliberately **not** here: a task's state is the repo +queue itself, so per-task status reads ride the queue domain +(`fleet queue list`). The client's routes are exactly three: + +| Verb | Route | Auth | +|---|---|---| +| `fleet dispatch status` | `GET /health` | unauthenticated | +| `fleet dispatch launch …` | `POST /v1/sessions` | Bearer | +| `fleet dispatch enqueue …` | `POST /v1/tasks` | Bearer | + +**The connection ladder** (transport selection, in order): + +1. **Direct URL**: env `FLEET_DISPATCH_URL` or fleet.toml `[dispatch] url` + (must be `http://host[:port]` with **no path** — a path is a usage error; + a missing port gets the configured port appended). +2. **Laptop zero-config**: probe `127.0.0.1:{port}` with a 750 ms connect + timeout; if it answers, direct to loopback. The port is `[dispatch] + port`, default **4879**. +3. If config `proxy_direct()` is set: direct to `{target_host}:{port}`. +4. **Tunnel**: a CONNECT through the fleet proxy egress to the target host's + dispatch port (the sandbox route). The client opens its own tunnel on + the egress because the framed session-broker shape forwards only an + `X-Agent-Token` header, which pm-dispatch does not accept. + +Auth is `Authorization: Bearer `, the token resolved **by name** +through fleet-secrets: default name `pm-dispatch.api-token`, overridable +with `[dispatch] token_name`. The value enters exactly one header per +request and is never printed, logged, or stored. An HTTP 401 is reported as +a transport-class error naming the mismatch with the service's own token +env (name only). + +Exit codes: **0** ok, **2** usage, **3** transport down / credentials +unresolved or rejected, **4** the service answered with an HTTP error +status. Success bodies print to stdout as pretty JSON exactly as the +service sent them; errors go to stderr prefixed `fleet dispatch: `. The +shared argument parser accepts `--flag value` and `--flag=value`; duplicate +value flags, unknown options, values on boolean flags, and stray +positionals are all usage errors. + +### `status` + +No arguments (any argument is a usage error; `--help`/`-h` prints usage and +succeeds without contacting the service). It prints the service's `/health` +body as a JSON object **plus** an added `"transport"` field describing the +route taken, for example `direct http://127.0.0.1:4879` or +`tunnel via proxy egress to {host}:4879`. A non-object health body is +wrapped as `{"health": , "transport": …}`. + +### `launch` + +``` +fleet dispatch launch --repo --prompt [options] + --prompt-file read the prompt from a file + --title default: the prompt's first line + --model model hint for the session + --directory must be the repo's laptop primary or inside it + --priority

integer 10-90, or critical|high|normal|low + --issue / --no-issue create the tracking issue (default: issue) + --wait / --no-wait wait for the launch to complete (default: wait) +``` + +`--repo` must be an allowlisted fleet repo (the allowlist check is +service-side). The POST to `/v1/sessions` creates the tracking issue and +queue task, starts the session, and assigns the task to it — all +service-side. The client sends **only the fields the caller set**: `repo` +and `prompt` always; `title`, `model`, `directory`, `priority` when given; +`issue` only when `--issue`/`--no-issue` was given; `wait` only when +`--wait`/`--no-wait` was given. The defaults named in the help (title = +first prompt line, issue on, wait on) are the **service's** defaults, +applied because the client omits the fields. `--prompt` + `--prompt-file` +together is a usage error (never a silent preference), as are +`--issue --no-issue` and `--wait --no-wait` in either order. `--priority` +crosses the wire as a JSON number when it parses as an integer, otherwise +as the raw string — validating the 10–90 range and the named scale is the +service's job, not the thin client's. + +### `enqueue` + +``` +fleet dispatch enqueue --repo --title --prompt [options] + --prompt-file read the prompt from a file + --kind triage|small_fix|pr_shepherd|ci_investigation (default: triage) + --priority

integer 10-90, or critical|high|normal|low + --model stored as the payload's model hint only + --issue create a tracking issue first (default: no issue) + --issue-number attach to this existing issue instead + --dedupe-key default: canonical key from the issue, else unique +``` + +Enqueue only, no session (POST `/v1/tasks`). Differences from launch: +`--title` is required; `--kind` **is** validated client-side against the +four kinds — an unknown kind is a usage error listing the four — but is +only sent when given (the `triage` default is service-side); `--issue` is +a one-way boolean with no `--no-issue`, and the service default is *no* +issue — the opposite default from launch; `--issue-number` must parse as +an integer (sent as `issue_number`); `--dedupe-key` is sent as +`dedupe_key`; `--model` goes in the task payload as a hint only. + +## `fleet dispatch-test`: scan, submit, status + +Verbs: `scan`, `submit`, `status`. Exit codes: **0** ok, **2** usage, +**3** transport down / credentials unresolved / **no eligible scope**, +**4** an HTTP error status from GitHub or Turso (including an unknown job +id on `status`). + +**Execution homes.** One repo — the fleet repo, config `[dispatch-test] +fleet_repo`, default **`dezren39/fleet`** — holds the other fleet repos as +git submodules and carries the generic workflow `fleet-dispatch-test.yml`. +Eligible homes are its *copies*: the source repo plus its fork network, +discovered per invocation by breadth-first traversal of +`GET /repos/{r}/forks`, **depth-capped at 8 levels**, deduplicated, source +first, then copies in API order — unless `[dispatch-test] scopes` pins an +explicit list (the pin wins; scan output reports `scopes_source: "config"` +vs `"fork-network"`). + +**Capacity counting.** For each scope, ACTIVE = (jobs with status +`in_progress` or `queued` across all `in_progress` runs — fetched paginated, +page size 100, max 100 pages) + (the number of `queued` runs, from +`total_count`, counted as **1 active unit each** — a queued run has not +started and exposes no jobs, so it counts once regardless of its eventual +fan-out). **Workflow presence**: the repo's workflows list contains a +workflow whose `path` ends with `fleet-dispatch-test.yml` and whose `state` +is `active` (a missing state counts as active). **Eligible** = workflow +present **and** active < threshold. The threshold is `--threshold N`, else +`[dispatch-test] threshold`, else **40**; `--threshold 0` is a usage error +("can never be satisfied") — a rule the help text does not mention. + +**Auth, by name through fleet-secrets only**: the GitHub token name is +`[dispatch-test] token_name`, default `github.ghcr-classic-pat`; the Turso +token name is `[dispatch-test] turso_token_name`, default +`turso.fleet-dispatch-jobs-token`. Each value enters exactly one +`Authorization` header per request. + +### `scan` + +``` +fleet dispatch-test scan [--threshold N] [--json] +``` + +Scans every scope in order. Human output: a first line +`scopes source: {config|fork-network} (fleet repo {repo})`, then one line +per scope ` active= workflow= eligible=`, then +`chosen: ` (the first eligible scope). `--json` prints +`{threshold, fleet_repo, scopes_source, scopes: [{repo, active, workflow, +eligible}], chosen}`. + +### `submit` + +``` +fleet dispatch-test submit --submodule NAME [--threshold N] + [--repo owner/name] [--ref REF] + [--name TEXT] + [--commands TEXT | --commands-file PATH] +``` + +`--submodule` is required: a single path segment (alphanumerics, `-`, `_`, +`.`; never empty, `.` or `..`, never a slash). Examples: `code`, `opencode`, +`openchamber`, `nix`, `hatch`. `--ref` is a ref *inside the submodule repo*; +default empty = the submodule stays at the umbrella's recorded SHA. +`--commands` / `--commands-file` are mutually exclusive; the default +commands are `set -eux; echo dispatch-test smoke; git rev-parse HEAD; +uname -a`. The job id is generated client-side (a time-based base36 string +plus a random hex suffix). + +Forcing `--repo` **bypasses the eligibility rule**: the forced repo is +scanned only to report `active_at_scan`; `active < threshold` and workflow +presence are not checked for it. + +The sequence is load-bearing, in this order: + +1. Connect to GitHub and to the Turso jobs store; run the idempotent schema + migration. +2. INSERT the job row with `status='queued'`, `target_repo=NULL`, + `target_ref`, `script` and `commands` (both carry the commands, so + MVP-era readers still see the payload), `submodule`, and + `run_id/run_url/exit_code/output_tail=NULL`. +3. Pick the home: the forced `--repo`, else the scan rule. No eligible + scope is a transport-class error (exit 3): "no eligible scope … (job + {id} remains queued in the store)". +4. Dispatch: UPDATE the row's `target_repo`; POST the + `fleet-dispatch-test.yml` workflow dispatch with `{"ref": , "inputs": {"job_id": id}}` — the job id is the + workflow's **only** input; only then UPDATE the row to + `status='dispatched'`. Any failure stops the sequence: a failed dispatch + leaves the row `queued`, with its target repo recorded. +5. Print `{job_id, repo, submodule, ref (null when empty), active_at_scan, + threshold, status: "dispatched"}` as JSON. + +### The Turso jobs store + +The endpoint is `[dispatch-test] turso_url`, default +`https://fleet-dispatch-jobs-dezren39.aws-us-east-1.turso.io`; requests are +`POST {url}/v2/pipeline` in the hrana-over-HTTP v2 shape. A non-2xx is exit +4 with the first 300 characters of the body; a non-JSON body or a +pipeline-level error object is a failure, never an empty result. + +The `jobs` table's full row is: `id, created_at, name, target_repo, +target_ref, script, status, run_id, run_url, exit_code, output_tail, +updated_at, submodule, commands`. The phase-2 migration (adding `submodule` +and `commands`) is applied idempotently by submit and status; a +"duplicate column" error means already-migrated and is ignored. + +Row lifecycle: `queued` (the client's insert) → `dispatched` (the client, +after the workflow POST) → `running` (the workflow itself writes this, with +`run_id`/`run_url`, when it fetches the job) → a terminal status with +`exit_code`/`output_tail`, written back by the workflow **always**, even on +failure — with one exception: a cancelled run is best-effort, and its row +may stay `running`, which `status` reports honestly. + +The workflow itself (`fleet-dispatch-test.yml` in the fleet repos) is +`workflow_dispatch` only, with the single required input `job_id`. Its one +job runs on `ubuntu-24.04` with a 120-minute timeout in the container +`ghcr.io/developing-today/fleet-build:full`: it reads the job from the +Turso store, marks it `running` with the run id and URL, checks out the +fleet repo, checks out the named submodule at the named ref, runs the +commands inside it, and writes status and output back. Its baked-in Nix +substituters are `https://nix-cache.developing-today.workers.dev` and +`https://developing-today.cachix.org`. + +### `status` + +``` +fleet dispatch-test status +``` + +Exactly one positional (else a usage error). It prints the stored row as +pretty JSON with **all columns**, values typed from the Turso cells. An +unknown id is an HTTP-class error 404, **exit 4**: "job {id} not found in +the jobs store". This reads the store only — it never queries GitHub for +live run state. diff --git a/pkgs/fleet/book/concepts/gh.md b/pkgs/fleet/book/concepts/gh.md new file mode 100644 index 0000000000..034cf15d08 --- /dev/null +++ b/pkgs/fleet/book/concepts/gh.md @@ -0,0 +1,157 @@ +# The gh passthrough + +`fleet gh` runs the real `gh` CLI (GitHub's command-line tool) under a +rotating fleet token. Every argument passes to the real `gh` binary +unchanged (`FLEET_GH_BIN` selects the binary, default `gh`) — except the +four *shadow subcommands* (`tiers`, `cache-serve`, `cache-status`, +`closures`), which fleet implements itself. The domain help's status line +still claims the implementation "lands in a later step" of the multicall +epic; that wording is stale — the source is a complete implementation, and +this chapter documents the source. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet/src/gh.rs + +## The passthrough contract + +Before each attempt, one token is resolved by name through the fleet +secrets chain and exported as `GH_TOKEN` **for that attempt only**. +Attempts are *captured* (piped), not streamed, because the failure text is +what classifies a failover; the caller sees the final attempt's stdout, +stderr, and exit code **byte-exact** as `gh` produced them. Attempts are +silent by default; `FLEET_GH_TRACE=1` names each attempt's token *source* +(never a value) on stderr. Tokens are never printed, logged, or written to +a file; provider errors name source and stage only. The audit log redacts +secret-carrying arguments (`gh secret set` bodies, `Authorization` headers) +in its copy only. + +**Raw mode** — `fleet gh --raw ` or `FLEET_GH_RAW=1` — is the +first-class bypass: the real `gh` execs directly with the caller's ambient +credentials; no token is resolved or injected, and there is no rotation or +failover. It exists so callers that must pin one identity — and the +`gh` → `fleet gh` PATH shim, whose escape hatch this is — never have to +choose between the rotation and bypassing fleet entirely. + +## Token rotation: personal, then three Apps + +The rotation order in source (the top-level help understates it as one +App): + +1. **Personal** — the user's `gh` OAuth token, parsed out of the broker + secret named `github-cli.hosts-yml` (the hosts.yml file itself, stored + by name; the parser extracts its `oauth_token`). +2. **Fleet App installations** — the "developing.today fleet" App, App ID + **5612056** (`FLEET_GH_APP_ID` may override). Private key by secret name + `github-app.developing-today-fleet.private-key`. Default owners, in + order: `developing-today`, `developing-today-forks`, `dezren39`. +3. **developing.today App installations** — App ID and key both by name + (`kaneo.github-app-id`, `kaneo.github-app-private-key`). Default owners: + `developing-today`, `dezren39`. +4. **developing-today-backup App installations** — by name + (`github-app.backup-app-id`, `github-app.backup-private-key`). Default + owner: `developing-today`. + +Per App leg: the private key is resolved by name; an RS256 JSON Web Token +is signed with the system `openssl`, the key passed over an inherited file +descriptor — never written to disk, never in argv; the owner's installation +is resolved live from `GET /app/installations`, paginated at 100 per page +(the App has 100+ installations). + +**Hint-first.** When the call names a repo or org, that owner's +installation moves to the front of *each* App leg, because an installation +token only sees its own installation's scope. + +Controls: `FLEET_GH_ORDER` (a comma list fixing the rotation exactly: +`personal`, `app:`, `devtoday:`, `backup:`); +`FLEET_GH_APP_OWNERS` / `FLEET_GH_DEVTODAY_OWNERS` / `FLEET_GH_BACKUP_OWNERS` +(comma lists replacing an App's default owners). + +## Failover triggers: the retry-safety rule + +A failed attempt's combined stdout+stderr is classified: + +| Class | Trigger strings (case-insensitive) | Retry? | +|---|---|---| +| RateLimit | `rate limit`, `rate_limit`, `too many requests`, `http 429` | Yes — any call | +| Permission | `missing required scopes`, `insufficient_scopes`, `resource not accessible`, `not accessible by integration`, `not accessible by personal access token`, `this endpoint requires you to be authenticated`, `bad credentials`, `http 401` | Yes — any call | +| NodeResolution | `could not resolve to a node` | **Read-only calls only** | +| Other | anything else | **Read-only calls only** | + +The rule: **a write is only repeated under a fresh token when the failure +proves GitHub refused the request before processing it.** Rate-limit +rejections (the limiter answers before the mutation runs) and +permission/scope rejections are both pre-execution refusals. +Node-resolution is explicitly *not* one: GraphQL executes mutation fields +serially, so a batched mutation may already have run an earlier field +before a later field's node fails to resolve; replaying would duplicate +the part that landed. Any other write failure is returned as-is — the +request may have landed, and repeating it could double-post. **Reads repeat +on any failure class.** + +A token *provider* failure (a source that cannot resolve or mint) skips +that source silently (named under trace) and the rotation continues; if no +attempt produced output, the caller gets the provider errors and exit 3. +If the last failover has no successor, the caller is shown the real `gh` +failure, not a summary. + +Two wrappers sit in front of the rotation: + +- **Close guard.** `issue close` and `issue edit --add-label status:done` + are refused (exit 2, never reaching the rotation) when the queue broker + has a claimed or parked task bound to that repo#issue, unless the bound + task's completion record (a `fleet-closure/v1` record carrying its task + id) is presented with the wrapper-only flag `--completion-record `, + stripped before `gh` runs. The queue query **fails open** — a broker + outage must not block every close. +- **Metadata create path.** `issue create` / `pr create` bodies are stamped + with the fleet metadata block before the rotation runs, and the full + record is inserted into the metadata store after a successful create; a + malformed caller block refuses the create before any write; a failed + insert never loses the item (reported on stderr; ingestion heals it). + +## The 4802 cache + +`fleet gh cache-serve [--bind ]` runs the credential/token cache +daemon in the foreground. It caches four things, **memory-only, with +single-flight minting** (concurrent requests for one key block on the +in-flight mint): + +| Entry kind | TTL | +|---|---| +| Secret resolutions | 60 s | +| App JWTs | within their expiry, minus a 60 s skew | +| Installation tokens | until shortly before `expires_at`, minus the same 60 s skew, floored at 1 s | +| Per-App installation lists | 300 s | + +Nothing is written to disk; a restart is a cold cache, never a stale one. +The wire is newline-delimited JSON over TCP, protocol version 1 — a daemon +that does not know a request's version answers `{ok:false, …}` rather than +guessing. Bind: `--bind` beats `FLEET_GH_CACHE_BIND` beats the default +**`127.0.0.1:4802`**; a bind without a port gets 4802. Every normal +`fleet gh` call resolves through the localhost daemon first, then the +laptop daemon (the proxy's reach target at the same port); with no daemon +answering it resolves in-process over the *same* cache implementation and +says so on stderr ("resolving in-process"). + +`fleet gh cache-status` probes the configured cache daemons and prints each +one's snapshot — entry counts by kind, hit/miss counters, soonest expiry. +Key names and values never leave the daemon; counts only. It exits 3 when +no daemon answered. + +## The shadow verbs: tiers and closures + +**`fleet gh tiers`** probes *every* rotation source and prints its core and +GraphQL rate-limit headroom — labels and numbers only; token values never +leave the provider. Exit 0 when every source answers, **3 when any source +is down**. Source behaviour: `tiers` takes no `--help` — `fleet gh tiers +--help` errors with "unexpected argument '--help'". + +**`fleet gh closures []`** reads back the closure log. The policy +layer behind it: `issue|pr close|reopen` through the rotation must carry a +`--reason` from the taxonomy — `implemented`, `superseded`, `cancelled`, +`started-incorrectly` — enforced with the policy error "Please give a +reason. This is required by policy." The reason is written into the close +comment, and every successful close or reopen appends one `fleet-closure/v1` +JSON-line record to `closure-records.jsonl` in the fleet state directory +(backed up with it); `closures` prints the log, optionally filtered to one +item. Source behaviour: the verb produces **no help output at all** — its +behaviour is documented only in source, and here. diff --git a/pkgs/fleet/book/concepts/placement.md b/pkgs/fleet/book/concepts/placement.md new file mode 100644 index 0000000000..3b6253f7e4 --- /dev/null +++ b/pkgs/fleet/book/concepts/placement.md @@ -0,0 +1,269 @@ +# Placement and remote dispatch + +*Placement* is the decision of where a build job runs. The live engine is +Rust, inside the queue crate, exposed as `fleet queue dispatch`, +`fleet queue session …`, and `fleet queue surfaces`. (A Go directory at +`pkgs/fleet/placement/` is an unwired proof of concept for a different +placement-record design; it is not this engine, and its own README says so.) + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/placement.rs + +## Surfaces as data: the registry + +No surface is hardcoded. A *surface* is one entry in the registry file +`fleet-surfaces.json` (version 2), and adding a location is adding an entry. +Resolution order: `--registry ` or the `FLEET_PLACE_REGISTRY` +environment variable (strict — a bad path is fatal, never a silent fallback); +else `$HOME/git/code/pkgs/fleet/fleet-surfaces.json` when it exists; else the +cwd-relative `pkgs/fleet/fleet-surfaces.json`; else the copy embedded in the +binary. `fleet queue surfaces` prints the resolved registry verbatim as +pretty JSON. + +The top level is `{comment, version, laptop: {busy, busy_source, note}, +owners: {…}, surfaces: […]}`. Each surface entry carries: + +| Field | Meaning | +|---|---| +| `id` | Surface identity; the `--surface` pin, session records, and tie-breaks key on it. | +| `kind` | Adapter selector: `github-actions`, `blacksmith`, `codespace`, or `laptop`. Any other value has no adapter and is invisible to the cascade (and cannot be pinned). | +| `status` | `base_eligible` requires exactly `active` for Actions/Blacksmith surfaces. Shipped values: `active`, `standby`, `pending-scope`, `handoff-only`. | +| `owner` | The account whose cap, load, and budget the surface draws on. Load is aggregated per owner, not per surface. | +| `repo` | The *runner-host* repo the workflow is dispatched in (not the target repo); null for codespace and laptop. | +| `workflow` | The workflow file dispatched; `fleet-command.yml` for all Actions/Blacksmith surfaces. | +| `targets` | Target-repo patterns: exact `owner/repo`, `owner/*`, or `*`. | +| `dispatch_as` | `user` = the signed-in user's token; absent/`app` = a GitHub App installation token. Any other value fails eligibility. | +| `dispatch_id_input` | The workflow declares a `dispatch_id` input (used for exact run correlation). | +| `platform_input` | The workflow declares a `platform` input; gates macOS eligibility and sending the input. | +| `previous_run_id_input` | The workflow accepts the follow-up output-download inputs. | +| `container_input` | The workflow accepts `container_image`; `--container` is only sent when this is true. | +| `sticky_queue_threshold` | Follow-up stickiness threshold; code default 2, minimum 1. All shipped surfaces: 2. | +| `selection_priority` | Tier-1 sort key; code default 50. Shipped: 10 everywhere except `org-run` at 20. Lower sorts first. | +| `public_targets_only` | Only `fleet-forks` (true): eligibility does a live repo read and requires `"private": false`. | +| `budget` | Blacksmith: `{free_minutes_monthly, paid_cap_minutes, rate_note}`. Codespace: `{core_hours_monthly, note}`. | +| `max_live` | Only `codespace-overflow`: 3. Printed in the capacity summary; **never enforced** (source behaviour). | + +The seven shipped surfaces: `fleet-personal` (github-actions, dezren39/fleet, +App dispatch, active), `fleet-org` (github-actions, developing-today/fleet, +user dispatch, active; also the Blacksmith host), `fleet-forks` +(github-actions, developing-today-forks/fleet, user dispatch, active, +public targets only), `org-run` (standby — because eligibility requires +`active`, it can never be selected or pinned; retained for manual use), +`fleet-org-blacksmith` (blacksmith, Linux-only fallback on the fleet-org +host), `codespace-overflow` (codespace, `pending-scope`), and `laptop` +(`handoff-only` — a placement record only; its adapter never runs shell +commands on the laptop). Actions/Blacksmith surfaces target +`dezren39/*`, `developing-today/*`, and `developing-today-forks/*`, except +`org-run`, which targets only `developing-today/*`. + +Target matching: a repo must be a valid `owner/name` (one slash, both parts +non-empty, characters `[A-Za-z0-9._-]`); `*` matches any valid repo, +`owner/*` matches that owner exactly with a single-segment name, anything +else is exact equality. A `--repo` failing validation is a fatal usage +error, exit 2 — and every error in the dispatch/session family prints +`repo-queue: ` and exits 2. + +## Owners and caps + +From the registry's `owners` table: + +| Owner | `concurrent_jobs_cap` | `concurrent_macos_cap` | `plan` | `private_minutes_monthly` | +|---|---|---|---|---| +| `dezren39` | **40** | **5** | `pro` | 3000 | +| `developing-today` | **20** | **5** | `free-org` | 2000 | +| `developing-today-forks` | **20** | **5** | `free-org (assumed - confirm)` | 2000 | + +So the working summary is caps of 40/20/20, and a macOS cap of 5 for every +owner. An owner missing from the table, or a missing cap field, yields cap 0 +— zero free slots, unusable in Tier 1. `plan` and `private_minutes_monthly` +are registry documentation only; the placement code never reads them, and +GitHub private-repo minute billing is not modelled in the cascade. + +For a macOS job the effective cap is `min(concurrent_jobs_cap, +concurrent_macos_cap)` — 5 for every owner — and the adapter counts *all* of +the owner's active host runs (Linux included) against that minimum, so +dispatch never oversubscribes the small macOS pool. There is no +macOS-specific load measurement anywhere. + +## The tier cascade + +`decide` evaluates, in order: + +0. **Hard pin.** `--surface ID` looks the id up in the adapter map (unknown + id is fatal) and runs that adapter's eligibility; ineligible is fatal — + no fall-through. A pin is a placement choice, not a paid-usage + authorisation: a pinned Blacksmith surface is still subject to its budget + check. +1. **Follow-up affinity** — a soft preference (below); falls through on + failure. +2. **Tier 1 — free GitHub-hosted Actions.** Every `github-actions` surface + that is eligible with `free_slots > 0`, sorted ascending by + `(load, owner_last_dispatch, selection_priority, surface_last_dispatch, + surface_id)`: least-loaded owner first; among equals, the + least-recently-used owner (an owner never used sorts before all used + owners); then registry priority; then per-surface last dispatch; then the + surface id alphabetically. The rotation is owner-first. +3. **Tier 2 — Blacksmith.** `blacksmith` surfaces in registry order; the + first eligible one with `remaining_total_minutes > 0` wins. +4. **Tier 3 — Codespaces.** `codespace` surfaces in registry order; the + first eligible wins. Eligibility itself enforces the last-resort + condition. +5. **Exhaustion.** The decision is `queued`: with `--dispatch`, a session + record with `state: "queued"` and no surface or run is still written and + its handle printed — the job stays queued, recorded, never dropped; the + repo queue remains its system of record. + +Runner pinning interacts before sorting: `--runner blacksmith` makes every +github-actions adapter ineligible, `--runner github` makes the Blacksmith +adapter ineligible, and `--runner auto` (the default) leaves both open. + +## Load measurement + +There is no account-wide Actions endpoint, so load is a proxy counted only +over each owner's *fleet runner-host repos* (the distinct `repo` values of +that owner's github-actions/blacksmith surfaces). For each host repo, with +that surface's token, placement reads only `total_count` from +`GET /repos/{host}/actions/runs?status=in_progress&per_page=1` and the same +with `status=queued` — the run lists themselves are never enumerated. Tier-1 +load per owner is `running + queued`, summed across its host repos. Failures +are soft: no token, a non-200, or a transport error contributes 0 for that +repo/status and adds a `load_read_errors` entry, which is surfaced in the +dispatch output when non-empty. Owner and surface last-dispatch times come +from the local session store, not the API. Two testing overrides exist +(`--assume-owner-load owner=N,…` and `--assume-blacksmith-used MINUTES`); +they are simulation, are labelled as such in the output, and do not appear +in the printed usage string. + +## LRU rotation + +The Tier-1 sort's second and fourth keys are the rotation: `owner_last_dispatch` +and `surface_last_dispatch` are the epoch of the most recent stored session +for that owner/surface, or 0 if never. Because load dominates, rotation only +decides among equally loaded owners — which is the common case at zero load, +where it spreads work across owners instead of always picking the first. + +## Follow-up affinity + +`--followup HANDLE|OWNER/REPO#RUN_ID` chains a dispatch after a previous +run: it sets the preferred surface to the previous session's surface and +carries the previous run id and runner-host repo for the output-download +inputs. Before Tier 1, the preferred surface is kept if and only if its +adapter exists and is eligible, it has capacity, **and the owner's queued +count is strictly below the surface's `sticky_queue_threshold` — shipped +value 2 on every surface**. With 2 or more runs already queued on that +owner, stickiness is released and the cascade proceeds; the reasoning line +records exactly why. Two pre-dispatch guards apply to real dispatches: a +previous run that is not yet terminal is fatal ("wait for a terminal result +before downloading its output"), and one still in `dispatched` state (no run +correlated yet) is fatal. In dry-run mode neither guard fires. + +Staying on the same host matters beyond queueing: GitHub Actions caches are +scoped to the repository the workflow runs in, so the same cache key string +in two host repos is two different caches. + +## Blacksmith budget rules + +Blacksmith is orgs-only: **3,000 free minutes per month**, then paid +per-minute (it charges for public-repo minutes past the free tier). The +registry budget on `fleet-org-blacksmith` is `free_minutes_monthly: 3000`, +`paid_cap_minutes: 0` — paid overage is disabled unless a dispatch +explicitly supplies `--allow-paid-blacksmith`. Code defaults if the budget +object is absent: free 3000, paid cap 0. + +Eligibility, in order: the owner must not be `dezren39` ("Blacksmith is +orgs-only; never the personal copy" — a hardcoded owner check, not a +registry flag); Linux only; base eligibility (active, targets, +`dispatch_as`); not runner-pinned to `github`; a surface token must be +obtainable; and the budget must have minutes left: +`remaining = free_minutes_monthly + paid_cap_minutes + +job.allow_paid_blacksmith − blacksmith_used_minutes`. + +`--allow-paid-blacksmith MINUTES` semantics, precisely: it is parsed as a +floating-point number (fractional minutes are accepted, default 0) and +**added to the paid cap for this one decision only**. It is an eligibility +allowance — not a per-run spending cap, not a workflow input, and not +persisted as an allowance anywhere. Once eligible, the run runs to +completion however long it takes; the actual minutes are reconciled into +the ledger afterwards and count against future decisions. `--runner +blacksmith` alone does not authorise paid minutes. + +Usage accounting is local: `blacksmith_used_minutes` is the sum of `minutes` +over the session store's `blacksmith_dispatches` entries for the current UTC +month. A new dispatch appends an entry with `minutes: 0.0, reconciled: +false`; when the run reaches a terminal state, reconciliation replaces the +minutes with the run's real duration, rounded to 2 decimal places. Before +any real dispatch decision, outstanding Blacksmith handles are reconciled +first (unless the used-minutes override was given). The runner name on the +wire is `blacksmith-4vcpu-ubuntu-2404`; the workflow's normalize job also +errors if `runner=blacksmith` arrives with `platform=macos` or from any host +repo other than `developing-today/fleet`. + +## The Actions cache and the Nix cache push + +`--actions-cache KEY:PATH` (a single value; both sides must be non-empty) +becomes the workflow inputs `actions_cache_key` / `actions_cache_path`; +`--actions-cache-restore-key PREFIX` is repeatable, requires +`--actions-cache`, and travels newline-joined. Without `--actions-cache`, +placement sends no cache inputs and the workflow's own defaults apply: +key prefix **`fleet-deps-v1`**, empty path, empty restore keys. + +On the workflow side, the cache root is `$GITHUB_WORKSPACE/.fleet/cache` +with cargo, cargo-target, rustup, and Go subdirectories exported as the +matching environment variables. A dependency hash (the first 20 hex +characters of a SHA-256) is computed over every lockfile-shaped file in the +target checkout plus the `rustc`/`go`/`nix` version strings. The full cache +key is `{PREFIX}-{RUNNER_OS}-{dependency_hash}-{target_ref}`, per host repo +in effect. Restore keys, in order: the caller's prefixes, then +`{PREFIX}-{RUNNER_OS}-{dependency_hash}-`, then `{PREFIX}-{RUNNER_OS}-`. +Prior-output reuse is a separate channel: when a follow-up supplies a +previous run, the action downloads that run's `fleet-output` artifact +(14-day retention) into `.fleet/previous-output`. + +`--push-nix-cache` sends `push_nix_cache: true`. The push step runs only on +success with the flag set; if either of the repo secrets named +`NIX_CACHE_SIGNING_KEY` / `NIX_CACHE_UPLOAD_URL` is unset, or `./result` +does not exist in the target checkout, it notices and skips. Otherwise it +signs the result's recursive path closure with the key (written to a 0600 +temp file) and copies it to the upload URL — the shared Fleet R2 cache. The +endpoint is secret-configured, never hardcoded in the workflow. + +Two workflow-contract facts placement users hit: placement never sends the +workflow's `timeout_minutes` input, so **all dispatches run under the +60-minute default** (the workflow validates 5–120); and the `dispatch_id` +input is a *fresh* correlation id minted per dispatch, not the session +handle, despite the workflow describing it as one. + +## Sessions: `fp_` handles and portable references + +A dispatched job gets a session handle: `fp_` plus 16 random bytes from +`/dev/urandom`, hex-encoded — `fp_` plus 32 lowercase hex characters, 128 +bits. Records live in the local store at `$FLEET_PLACE_STATE/sessions.json`, +default `~/.local/state/fleet-place/sessions.json` — a labelled stopgap with +the reference implementation's path and record shape, so records migrate +when the designed queue-backend table lands. The store is guarded by a lock +directory (waiters poll every 50 ms up to 15 s; a lock older than 120 s is +stale and is broken) and written by rename of a temp file, with keys +recursively sorted. + +A record carries the job, the surface (null in the queued case), the runner +repo, the decision reasoning, the run id and URL, the state +(`queued|dispatched|running|succeeded|failed|cancelled`), `submitted_by`, +timestamps, and — when the run is known — the **portable id** +`OWNER/REPO#RUN_ID` (for example `developing-today/fleet#45146933211`). One +recorded-field caveat, stated as the source behaves: `actor` is hardcoded +to `developing-today[bot] (GitHub App dispatch)` even for surfaces that +dispatch as the user. + +`fleet queue session status|result|list` reads the store: `status` refreshes +the record from GitHub and prints its state, surface, and run URL; `result` +adds `terminal` (true exactly for `succeeded|failed|cancelled`) and, when +not terminal, the note "not terminal yet — reconnect with the same handle"; +`list` prints stored records newest first without refreshing (`--mine` +filters to the current `USER@hostname`). Anywhere a handle is accepted, the +portable `OWNER/REPO#RUN_ID` is accepted too and is resolved **directly +against GitHub without the local store** — the repo must be a registered +Actions/Blacksmith surface's host repo. Session state mapping from GitHub: +`queued|waiting|pending|requested` → `queued`; `in_progress` → `running`; +completed with conclusion `success|skipped|neutral` → `succeeded`, +`cancelled` → `cancelled`, anything else → `failed`. Note that +`session status --help` does not print help — `--help` is taken as the +handle and errors; only bare `session --help` prints the usage. diff --git a/pkgs/fleet/book/concepts/proxy.md b/pkgs/fleet/book/concepts/proxy.md new file mode 100644 index 0000000000..3b8650dee9 --- /dev/null +++ b/pkgs/fleet/book/concepts/proxy.md @@ -0,0 +1,209 @@ +# Proxy, sessions and recovery + +The *session proxy* is how a sandbox seat reaches the laptop's services. The +proxy domain's verbs are `serve`, `connect`, `init`, `ssh`, `splice`, +`get`, and `put`, gated per verb on the capabilities `proxy-serve` (serve), +`proxy-connect` (connect/init/get/put/ssh), and `proxy-raw-splice` +(splice). The proxy succeeds an earlier Python trio of broker/connect +scripts, behaviour for behaviour. The wire is the `fleet-proxy-proto` +protocol alone: **8-byte big-endian length-prefixed JSON** frames. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-proxy/src/serve.rs + +## The session broker socket + +`fleet proxy serve` runs the broker. It takes no arguments (a trailing +argument is a usage error naming it, exit 2; `--help` prints the usage, +exit 0). It binds the **session broker Unix socket** from fleet config — +`FLEET_BROKER_SOCKET` or `[proxy] broker_socket`, default +`~/.cache/laptop-agent/broker.sock`. If a live broker already owns the +socket, it exits quietly; if the socket file is stale, it unlinks and +binds. + +The broker persists nothing: its routing table comes from config, its +tunnels live in memory, and token files are read per request and never +stored or logged. The routing table — the *services map* — is port → +service name: **4799 laptop-agent, 4800 secrets-broker, 4801 queue-broker, +21118 rustdesk**. The hello response carries that map and the broker's +capability list. + +**Hello negotiation.** Sessions speak the legacy dialect (**proto 0**: +request frames from the first frame — the old Python clients) or negotiate +a hello first (**proto 1**, fleet clients), decided per connection by +peeking at the first frame, never by configuration. A too-old peer gets the +proto-too-old frame and exit 69 on the client side. + +**Keepalive and idle exit.** A keepalive thread pings the laptop-agent's +`/health` every **180 s**. The broker exits once *client requests* have +been idle for `idle_exit_secs` (`[proxy] idle_exit_secs`, default **3600 s**; +0 is rejected at config load) — keepalive traffic does not count as use. A +warmth cache that exits when cold is a feature on a shared sandbox. Inside +a multi-role `fleet serve` list, the idle exit is disabled, so an idle +proxy cannot exit the shared process and kill its sibling roles. + +**Colocated brokers.** For the queue/secrets broker ports, the broker first +tries the role's own Unix socket with a bounded dial — the dial *is* the +probe; a socket that answers within the deadline is used, any other outcome +selects TCP within the same attempt — before tunnelling to the laptop. + +## Warm pools + +The broker keeps per-port pools of warm CONNECT tunnels to the laptop's +services. Pool size comes from `LAPTOP_AGENT_POOL`, compiled default +**50** (sized from a concurrency benchmark: the old default of 12 cliffed at +roughly 12 concurrent consumers; 32 already restored direct-class latency). +A request takes a pooled connection and on any failure retries **once on a +fresh one**. Overflow policy: idle → grow (below the live ceiling) → wait +briefly for a returned tunnel → grow anyway. A request never fails because +of the pool. Pools key on `(port, transport)`, so the two laptop reaches +(below) never share warmth or failure state. + +## Two reaches to the laptop: the CF leg and the tailnet fallback + +Sandbox↔laptop transport lives in this binary. There are two legs: + +1. **The Cloudflare leg is primary** for the laptop-agent daemon port + *when its Access file exists*: `~/tools/laptop-agent-cf-access.json` — a + JSON `{client_id, client_secret}` file, mode 600, read per request, sent + only as `CF-Access-*` headers, never stored or logged. No file, no leg. + The leg is TLS through the platform egress proxy to the tunnel hostname + `sandbox-link.security.cab`, whose ingress lands on the daemon's own + listener laptop-side; the daemon's token auth is preserved end to end. +2. **The tailnet leg is the automatic fallback**: a CONNECT through the + host egress proxy to the tailnet target host `100.99.113.103`. It is + selected on connection failure *and* on a Cloudflare edge error status + (502/503/530) alike. + +Port **3130** is the host egress proxy port — the CONNECT proxy named by +the session's `HTTPS_PROXY` environment. It is **not a fleet listener**. +The tailnet leg's shape is: fleet → HTTP CONNECT to the egress proxy at +`:3130` → tailnet target `100.99.113.103:`. (The +URL's own port in `HTTPS_PROXY` is not used; 3130 is fixed by the tunnel +setup.) Fleet contains no 3130 listener to restart — 3130 belongs to the +session/host layer, and the recovery story below is layered accordingly. + +## `connect` and `init` + +`fleet proxy connect` ensures a broker answers — spawning `fleet serve +proxy` detached when the socket does not answer, then waiting for the hello +(a legacy proto-0 answer still counts as running; its services map is the +built-in table) — syncs the PATH shims from the broker's services map, and +optionally issues one request over the negotiated stream: + +``` +fleet proxy connect [--print-path] [--stdio [--host H] [--port N]] + [--request METHOD PATH [--service-port N] [--token-file F] [--body JSON]] +``` + +`--print-path` prints the shim directory and exits (the shell-integration +spelling). `--request` prints `{"status": …, "body": …}` as JSON; +`--service-port N` selects the laptop service port (default: the request's +implied route, 4799), `--token-file F` names the token file the broker +should read for this request, and `--body JSON` must be valid JSON. +`--stdio` is the raw relay spelling (SSH's ProxyCommand shape): `--host H` +(default: the config target host) and `--port N` (default 22) relay +stdin/stdout over one tunnel. Flag discipline: each flag at most once; +`--stdio` and `--print-path` are mutually exclusive with `--request`; +`--host`/`--port` require `--stdio`; `--service-port`/`--token-file`/ +`--body` must follow `--request`. Exit codes: 2 usage, 3 transport, 69 +protocol/capability unavailable. + +`fleet init` (byte-identical to `fleet proxy init` — one implementation) +autostarts this host's roles per the `[host]` manifest. Manifest resolution: +`FLEET_HOST_CONFIG` (a complete inline manifest; wins outright) → +`FLEET_LOCATION` (roles from the config file's `[host]` only if its location +matches, else the built-in map) → the config file's `[host]` section. Only +two built-in locations exist: `sandbox` (init mode `spawn`; roles `proxy`, +`secrets-broker`) and `laptop` (init mode `systemd`; roles `laptop-agent`, +`queue-broker`, `search`, `secrets-broker`). The full role vocabulary is +five names — those four plus `proxy`. + +- **Unknown location:** init reports state (every source consulted, plus + detected hostname/OS/systemd for the report only — detection never selects + roles), starts nothing, and exits **69**. It never guess-starts a role. +- **Spawn mode (sandbox):** for the proxy, init probes the broker socket and + says hello; a live broker means status plus PATH-shim sync and out — a + strict no-op, never a spawn, never a restart; init never fights an + incumbent broker. Only an unanswered socket spawns `fleet serve proxy` + detached. For the secrets broker, a live socket answer means status and + out; otherwise init spawns `fleet serve secrets-broker` detached with + `SECRETS_BROKER_BIND=127.0.0.1:4800` set explicitly, then waits (50 × + 100 ms probes) for the socket to answer. Any other role in a spawn + manifest is reported and skipped, never spawned. +- **Systemd mode (laptop):** init never detached-spawns a daemon systemd + owns. For each role it reports `fleet-.service` state via + `systemctl --user is-active`; an active unit is a no-op; an inactive but + existing unit is started; a missing unit is reported and skipped, not an + error. +- Roles the manifest itself disables are reported as skipped with their + reason, and the `[domains]` config gate is applied after the manifest and + wins over it. + +## Recovery: connect and ssh pinning + +The recovery story is layered: the broker's Cloudflare leg is independent +of the tailnet CONNECT path, so it carries the laptop-agent port when the +tailnet leg is what is broken; `proxy connect` re-ensures a dead broker; +stale sockets are unlinked and rebound. The operator's recovery shell is +`fleet proxy ssh`: + +``` +fleet proxy ssh -- [ssh args...] +``` + +It runs system OpenSSH through the fleet proxy, as the route you use when +the normal laptop channel is what is broken. Everything that decides where +the connection lands is **pinned by fleet**; the caller supplies only extra +SSH options and an optional remote command. A literal `--` is required +first; a second `--` inside the SSH arguments is an error ("the SSH +destination is fixed; do not pass a second '--'"). + +The pinned argv: destination `user@` with +`HostName=` (default `100.99.113.103`), `User=user`, identity +`~/.ssh/id_ed25519` with `IdentitiesOnly=yes`, +`UserKnownHostsFile=~/.ssh/known_hosts_laptop`, +`StrictHostKeyChecking=yes`, `ConnectTimeout=60`, `ConnectionAttempts=3`, +`ServerAliveInterval=15`, `ServerAliveCountMax=8`, `ControlMaster=auto` +with `ControlPath=~/.ssh/cm-%r@%h:%p` and `ControlPersist=3600`, and +`ProxyCommand= proxy connect --stdio --host --port %p`. The fleet proxy credential stays in the environment and is +sent only by the CONNECT relay — never in the SSH argv. The command `exec`s +the system `ssh` (Unix only; elsewhere exit 69). + +## `get`/`put`: verified transfers + +Both verbs talk to the laptop-agent daemon's file routes (port 4799) +through the broker, in JSON envelopes carrying **2 MiB raw chunks, +base64-encoded** (about 2.67 MiB on the wire, far under the 64 MiB frame +ceiling). The whole file's SHA-256 is verified at commit (put) and after +the last chunk (get). Transfer temps are deterministic — +`..fleet-part-` beside the destination — so an +interrupted transfer resumes by re-issuing `begin` and continuing from the +temp's size. + +- `fleet proxy put [--mode OCTAL] [--no-resume] ` + hashes the file, uploads it in chunks to the deterministic temp on the + laptop, and **atomically renames it over the destination only after the + daemon verifies the hash**. The recursive form is `put -r … + `. `-` reads stdin (spooled locally first; mode defaults to + 0644). Progress and the final sha256 go to stderr. +- `fleet proxy get [--mode OCTAL] [--no-resume] ` + lands chunks in a deterministic local temp; the SHA-256 from the daemon's + `stat` must match before the temp is renamed over the destination. `-` + streams to stdout — the hash is still verified at the end, and a mismatch + fails the command *after* the bytes were emitted, so check stderr. + **Recursive get is deferred in v1**: the daemon protocol has no + directory-listing route. + +Exit codes for both: 2 usage, 3 transport, 69 capability-unavailable. + +## Splice: raw TCP for RustDesk + +`fleet proxy splice` takes no arguments. It listens on **`127.0.0.1:21118`** +(loopback only — a pinned constant with a test asserting both properties) +and relays each accepted TCP stream through the fleet broker to the +laptop's RustDesk direct-access service (port 21118 laptop-side). It +requires the broker to advertise raw-splice support in its hello (the +`proxy-raw-splice` capability plus the service flag); a legacy or +non-advertising broker is a transport error, not a silent fallback. This is +the RustDesk direct-access path that avoids the relayed session. diff --git a/pkgs/fleet/book/concepts/queue.md b/pkgs/fleet/book/concepts/queue.md new file mode 100644 index 0000000000..504d9aa255 --- /dev/null +++ b/pkgs/fleet/book/concepts/queue.md @@ -0,0 +1,364 @@ +# The queue: tasks, lanes and leases + +The queue is the fleet's shared work queue: one queue of *tasks* (units of +repo work), served by the queue broker over a dedicated Turso store, with a +GitHub-issue-comment fallback queue behind it. The client surface is +`fleet queue` (argv0 alias `repo-queue`) with 32 verbs. Inside the binary, +every per-verb usage string spells the program `repo-queue`; the two +spellings are the same code path. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client.rs + +## The task model + +A task is created from a *packet*: a JSON document validated against +`repo-task-v1.schema.json` plus the fleet queue validator. The envelope +fields live outside the payload: `title`, `body`, `dedupe_key`, `priority`, +`not_before`, `max_attempts`. The payload (`schema` const `"repo-task/v1"`) +carries: + +| Field | Shape | Notes | +|---|---|---| +| `kind` | enum | The validator accepts six: `pr_shepherd`, `triage`, `small_fix`, `ci_investigation`, plus `second_pass` and `feature_slice`. (The schema file lists only the first four; the validator is the wider, operative list — source behaviour wins.) | +| `repo` | enum | The validator's allowlist has nine repos, including the legacy `dezren39/nix` name kept valid for in-flight dedupe keys. (The schema lists eight.) | +| `implementation_repo` | `owner/name`, optional | The repo receiving the implementation when it differs from the issue repo. Required when `risk.flags` contains `cross-repo-change`. | +| `problem` | string, non-empty | | +| `evidence` | string array, at least 1 | | +| `acceptance` | string array, at least 1 | | +| `scope` | `{include, exclude}`, both required, `exclude` non-empty | | +| `tests` | string array, at least 1 | | +| `risk` | `{level: low\|medium\|high, flags: string[]}` | | +| `priority_reason` | string, non-empty | | +| `timebox_minutes` | integer 1..=240 | Design values are 20 (triage) and 45 (standard); other values warn. | +| `max_attempts` | integer 1..=1000 | Design default 1000 for every kind. | +| `context_refs` | string array | | +| `dedupe` | `{checked_at, basis}`, both non-empty | The producer's dedupe attestation. | +| `required_budget_minutes` | integer ≥ 1, optional | The minimum uninterrupted budget a claimer must declare; absent means no requirement. | +| identity | one of `issue`, `prs`, `set`, `source` | At least one is required: an issue `{number ≥ 1, url?, title?, state_checked_at?}`, a non-empty PR list, a PR-set, or a pre-filing triage source `{pr, finding}`. | + +Envelope rules: `priority` must be on the design scale +**[10, 20, 30, 40, 50, 70, 90]** (lower is sooner); payload size has a hard +ceiling of 16,384 bytes (a warning above 4,096); `not_before` must be a +non-empty RFC 3339 timestamp no more than 366 days in the future. Durations +and limits throughout the queue are **rejected, never clamped**, identically +at client and broker. + +Two stored-priority exceptions: at enqueue, a payload whose `labels` array +contains `expedite` stores priority **15**, else `next-up` stores **25**. +These stored values are deliberately not on the packet scale. + +**Dedupe.** Enqueue dedupes on `(queue, dedupe_key)` among *live* rows, and +separately on work identity (repo, issue, kind family): a live task already +holding the work identity means nothing is filed, unless the packet sets +`payload.dedupe_override`. A key held only by terminal rows accepts a new +row. A *cancelled* row is revived in place by a re-enqueue; a *failed* row +deliberately is not — re-enqueueing a failed identity files a new row. + +**Enqueue has no default queue.** The queue resolves from `--queue`, else +the packet's own `queue` field, else the `REPO_QUEUE_DEFAULT_QUEUE` +environment variable; with none of the three, enqueue exits 2. (The old +shadow default silently misrouted work.) Enqueueing into a queue whose name +ends in `-shadow` additionally requires `--shadow-intent`. Most other verbs +default `--queue` to `repo-health-code-shadow` via the same environment +variable, but `claim` and `list` are *unscoped* when neither flag nor env is +present: the broker works across the one fleet queue. + +## States and transitions + +Live states: `queued`, `claimed`, `parked`, `blocked`, `needs_review`. +Terminal states: `done`, `failed`, `cancelled`. + +- `enqueue` → `queued` (`attempts = 0`). +- `claim`: `queued` → `claimed`; a due `parked` row is also claimable and + resumes without consuming an attempt. +- `release`: `claimed` → `queued`, immediately claimable. +- `park` / `wake`: `claimed` → `parked` → (condition met, due, or woken) + `queued`. +- `block` / `unblock`: `claimed` → `blocked` → `queued`. +- `complete`: `claimed` → `done`. `fail`: `claimed` → `failed`. + `cancel`: `queued` or `parked` → `cancelled`, for a task that will never be + worked. +- `revive`: a terminal row, or a queued row dead at the attempt cap, is + resurrected in place with `attempts = 0`. +- Lease expiry: `claimed` → `queued` with a `lease_expired` event, or — when + the row is out of attempts — it sits dead at cap with a + `lease_expired_at_cap` event until `revive`. + +Every transition writes an event row; `fleet queue timeline ` +(aliased `history`) renders the 14 event kinds the timeline reads. + +## Lanes and workers + +A *worker* is the claiming identity stamped on a row (default +`repo-worker-code`; `cancel` defaults its worker to `fleet-monitor`). A +*lane* is a finer identity used when many scheduled lanes share one worker +id: the lane tells the broker whose claim a holder verb acts on. Holder +verbs (heartbeat, checkpoint, park, release, block, fail, complete) resolve +`--lane` from the flag, else the `REPO_QUEUE_LANE` environment variable, +else null — in which case the broker checks the worker alone. A lane is +validated broker-side against the lane registry at claim time: an unknown +lane, a worker mismatch, a disabled lane, or a queue mismatch each refuse +and claim nothing. The canonical lane universe is 6 families (`code`, `any`, +`not-code`, `opencode`, `openchamber`, `nix`) × `a`..=`z` = **156 lanes**, +all enabled, seeded into the store's `lanes` table. + +The claim pick is atomic: highest priority first (`priority ASC, +created_at ASC`) among due `queued` rows and due `parked` rows. A claim with +no task, no filter, no queue scope, no count, no handoff/bind, and no +identity marks is refused before any broker contact, exit 2 — a bare claim +has repeatedly stolen the queue's top task during CLI probing. Batch claims +take 1..=5 rows (`--count`). Claim flags also carry marks, not filters: the +claimer's platform, pool, session id, and model stamp +(`--model-provider`/`--model-id`/`--model-variant`, derived from the +session's own record when not given) are recorded on the row. A +`--remaining-budget-minutes` declaration gates requirement-bearing tasks: +the broker only matches tasks whose `required_budget_minutes` fits, and +omitting it leaves such tasks unclaimed. No claimable task is +`{"task": null}`, exit **5**, with counts (`queued`, `at_cap_queued`, +`queued_not_yet_due`, `parked_due`) explaining why. + +## Leases and heartbeat + +A *lease* is the claim's expiry. Claim's default lease is **2700 s +(45 minutes)**, range 1..=86400, rejected outside it; a zero or negative +lease is born expired. `fleet agent next` claims with a 14,400 s (4-hour) +lease instead, because 45 minutes lapses mid-task. + +`heartbeat` extends the lease: `lease_until = now + extend_seconds`, default +extend **900 s (15 minutes)**, range 1..=86400 — note the asymmetry: a +heartbeat adds 900 s, not a fresh 2700 s, unless told otherwise. It may also +merge a progress value (`--progress` / `--progress-file`, mutually +exclusive). `checkpoint` records progress plus a required `--stage` (the +help line brackets it optional; the source requires it — missing `--stage` +exits 2) without touching the lease. Lease expiry is opportunistic — every +claim first sweeps expired leases — plus a broker sweep, because a scheduler +firing irregularly must not strand work. + +Holder verbs are holder-checked: the row must be claimed by this worker +(and lane, when supplied) and non-terminal, else exit 5 with "no matching +claimed row". `release` requires `--reason` (the help line brackets it +optional; the source exits 2 without a non-empty reason). `cancel` likewise +requires `--reason`. `fail` requires `--error`, and its `--reason-class` is +a closed enum — `transient` (the default), `deterministic`, `blocked` — +whereas `block`'s `--reason-class` is free-form. + +## Park, wake, and ready-conditions + +`park` moves a claimed task out of the way until a *ready-condition* says the +wait is over. `--reason` is required; `--delay-seconds` (range 1..=604800, +7 days; 0 is rejected — a zero-second park is a requeue, and `release` +exists) and `--not-before` are mutually exclusive; with neither, the +broker's historical default delay is **1200 s**. + +The ready-condition is a JSON object. Kinds a database sweeper can verify +from store state: `task_terminal {task_id}`, `task_status {task_id, +status}`, `event_seen {task_id?, event_kind}`, `time {until}`. External +kinds (`ci`, `pr_merged`, `issue_closed`, `person_answer`, `review`, …) are +recorded faithfully but cannot be verified by the sweeper. With no explicit +condition the broker derives one from `progress.ready_condition`, else +`{"kind":"time","until":}`. The condition kind determines the +*wait kind* (`time`→`timer`; `ci`/`ci_green`/`pr_merged`/`issue_closed`/ +`upstream_pr`→`ci`; `review`/`codex_review`/`pr_review`/`person_answer`→ +`review`; `capacity`/`quota_reset`→`capacity`; `triage`→`triage`; anything +else→`external`), and the broker enforces wait floors whatever delay was +asked: a `triage` wait is held at least **6 h (21,600 s)**, a `ci` or +`capacity` wait at least **1 h (3,600 s)**. The park revalidation sweeper +later records `check_outcome` as `confirmed` (condition unmet), `released` +(condition met → back to `queued`), or `stale` (cannot verify). `wake` +releases a parked wait now that its condition is satisfied. + +A park (or block) that waits on a *person* — a `person_answer` condition, a +person-wait reason class, or blocker text naming the owner as the release — +is refused client-side, exit 2, unless it is a valid *hands item*: +`--hands physical|interactive-login|payment|signature` plus `--action` with +one sentence a person can do in five minutes (a single line, at most 200 +characters, not itself asking for a decision). The rule's point: a choice +that is the worker's to make is never parked onto a person. + +## Block and dependencies (`dep_blocked`) + +`block` sets status `blocked`. `--reason-class` and `--blocker` are both +required. A classic block waits for a manual `unblock`. A *typed dependency +block* names machine-watchable dependencies instead of prose: +`--blocked-by-pr`, `--blocked-by-issue`, `--blocked-by-ci` take +comma-separated `owner/repo#N` refs (for CI, `N` is an Actions run id), and +`--blocked-by-task` takes bare task ids. Bad refs die client-side, exit 2. + +The parsed deps are stored on the task row in the **`blocked_deps`** column +(JSON); a task with a non-empty `blocked_deps` is in the `dep_blocked` +state. Alongside sit `dep_recheck_seconds` (clamped broker-side to +300..=3600, default **900**), `dep_next_recheck_at`, and `dep_blocked_until` +from `--dep-max-ttl-seconds` (default **3 days (259,200 s)**, floor 60 s, +ceiling 7 days). The broker's sweep rechecks deps every minute and releases +the task itself when they clear or the TTL expires; `dep-recheck` is the +manual trigger. `unblock` is the manual override: without `--drop-dep` it +clears the blocked state entirely; with `--drop-dep ` (comma-separated +`kind:ref` — `issue:owner/repo#N`, `pr:owner/repo#N`, `ci:owner/repo#RUN`, +`task:ID`) it drops only the named entries — the task stays blocked on the +remaining deps, and dropping the last one releases it. The broker audits who +overrode and what was discarded. A separate sweep, `quarantine-recheck`, +re-validates blocked dep-free rows whose recorded error is a claim-path +quarantine and requeues the ones whose error no longer reproduces. + +## The evidence gate and verify-disposition verdicts + +Shape validation alone once let a fix-class task complete `done` on any +non-empty evidence string while its issue was still open and a draft PR +still carried the work. Now a completion that requires a disposition must +carry `result.disposition`: a verified readback record produced by +`fleet queue verify-disposition --repo `. + +`verify-disposition` reads the issue and its linked PRs **back from GitHub, +live** — never from a remembered claim. A PR counts as linked when named by +queue provenance or `--pr`, or when its body carries an explicit marker +(`Refs #n`, `Fixes #n`, `Related program: #n`); a bare prose `#n` is not a +link. `--repo` is required (exit 2 without it). The record is +`{checked_at, source, issue: {number, state, state_reason, closed_at, +closed_by}, pulls: [{number, state, is_draft, merged_at}], verdict, +follow_up}`. + +The gate is pure (no network). It checks freshness (at most **1800 s** old +by default; more than 300 s in the future is unreadable clock skew), that +the record describes the task's issue, that the verdict matches the +readback, that every PR the completion result links appears in the readback, +and any follow-up. **Every rejection leaves the task claimed** and names the +defect. `verify-disposition` itself exits 0 when its record would pass the +gate, 1 when the gate would reject it or the readback cannot be read. + +The five verdicts: + +| Verdict | Derived when | Gate requires | +|---|---|---| +| `merged_verified` | some pull in the readback is merged | at least 1 merged pull in the readback | +| `closed_verified` | issue closed and no unfinished pulls | the issue state actually `closed` | +| `open_draft_with_followup` | unfinished pulls exist, nothing merged, issue not cleanly closed | a recorded `follow_up` | +| `open_draft_superseded` | operator-asserted, same family | a recorded `follow_up` | +| `invalid_no_work` | none of the above | rejected if any linked pull still carries work | + +A pull is *unfinished* when it is not merged and not closed. A follow-up is +exactly one of `--follow-up-task ` (checked by the broker at completion — +only the queue knows if it is live), `--follow-up-issue ` (same-repo, +open, must link the completed issue and every unfinished PR), or +`--follow-up-pr ` (must be in the readback and merged); any follow-up +target requires `--reason`. One exception: a closed issue may leave related +work open when the close was a deliberate act by a person (the readback's +`closed_by` is checked against automation) *and* a verified follow-up owns +the remainder. + +`complete`'s other rules: `--result`/`--result-file` must be a JSON object +(the file wins when both are given); `--telemetry` accepts only the keys +`pool, model, effort, cost_usd`; `--queue` is parsed but never used — a dead +flag, stated here because the source says so. + +## The fallback queue and the permanent fallback switch + +The fallback queue is a queue with no database: all state lives in GitHub +issue comments. Work items are open issues carrying the labels +`queue/queued` (waiting), `queue/claimed` (held), or `queue/blocked` +(blocked) — the same labels the broker-backed system maintains. The sweep +covers five repos in pilot order: `developing-today/code`, +`developing-today-forks/opencode`, `developing-today-forks/openchamber`, +`dezren39/darwin-nix`, `dezren39/fleet` (shortcuts `code`, `opencode`, +`openchamber`, `nix`, `fleet`). + +A claim is the first line of a comment, exactly +`` (kinds: +`claim`, `heartbeat`, `release`, `unblock`), with a human-readable line +under it. Because every fleet worker posts to GitHub as the same account, +the marker's worker id is the only identity the lease can be keyed on, so +`--worker` is **required, never defaulted** (or the `FLEET_FALLBACK_WORKER` +environment variable). The lease window is **30 minutes** by default +(`--lease-min` per verb, or `FLEET_QUEUE_FALLBACK_LEASE_MIN`). Folding an +issue's markers in comment order gives its claim state: `free`, `released`, +`live`, `stale` (older than the lease — any worker may claim, superseding), +or `contested` (a claim posted during another's live claim; hands-off for +everyone while the contest is younger than the lease). Claimable = free, +released, or stale. Fallback `complete` runs the same offline disposition +gate as the broker path before posting anything; a rejection posts nothing +and exits 1. + +**The fallback switch is permanently armed.** For the work verbs — claim, +heartbeat, checkpoint, complete, health — *any* primary-store failure +(broker unreachable, or an `{ok:false}` envelope) switches the caller to the +GitHub fallback for that work instead of dying: a message on stderr, one +JSON object on stdout with `"fallback": true, "switch_to": +"github-fallback"` and a hint naming the fallback verbs, and exit code +**6**, so a worker loop can branch on it without parsing prose. The escape +hatch `REPO_QUEUE_NO_FALLBACK_SWITCH=1` restores plain die-on-error. The +primary claim path also guards the other direction: it refuses to +double-serve an issue the fallback currently holds (see the claim path in +[Architecture](architecture.md#data-flows)). + +Queue client exit codes, in full: 0 success; 1 gate failure / task not +found; 2 usage; 3 transport or broker-path failure; 4 a broker `{ok:false}` +envelope carrying no exit of its own (and broker-side store failures); 5 no +matching claimed row / no claimable task; 6 the fallback switch. + +## The creation outbox + +Creating GitHub objects (issues, PRs, comments) must survive crashes and +rate limits, so creation goes through the *creation outbox*: producers +enqueue, a single serial drainer creates through `gh`, verifies by +read-back, and resolves. There is no dual-write and no automatic fallback to +direct creation — a broker failure stops the drain visibly. + +Entry kinds: `issue`, `pull_request`, `issue_comment`, `pr_comment`. States: +`pending`, `leased`, `uncertain`, `done`, `blocked`. Constants: claim lease +**120 s**, minimum gap between creates **2 s**, hourly create budget +**300**, retry backoff base **30 s** capped at **3600 s**, a circuit breaker +that opens after **3** consecutive rate limits for **300 s**, default max +attempts **8**. Entries carry a `fleet-outbox:` marker in the created +object's body so the drainer can reconcile by search and read-back. The +verbs are `outbox enqueue|list|metrics|claim|resolve|drain`; `drain` +defaults to at most 20 items (`--max`, floored at 1), and an `uncertain` +entry is reconciled by marker first — a lookup that *could not check* keeps +the entry uncertain and never re-creates. + +## Merge-intent stacks + +A *stack* is a recorded, ordered set of merge intents — finished branches +with their authoring lane, worker, and session — stored in the broker's +`merge_intents` table, unique on `(stack_id, position)` and `(repo, +branch)`. Intent states: `intended → replaying → landed`, plus `conflicted` +and `abandoned`; the legality of every move is decided by a pure transition +table, never in SQL, and a conflicted intent returns only through its +recorded authoring lane. + +The verbs are `stack record|list|transition|restack|replay`. `record` +requires `--stack`, `--repo`, `--branch`, and `--lane`. A transition to +`conflicted` requires `--conflict-detail` naming what the authoring lane +must resolve. `replay` is the executor: it walks the stack's recorded merge +order bottom-up — rebase onto new main, push (force-with-lease pinned to the +verified pre-rebase tip), open PR, merge, mark landed, post the outcome note +— one intent at a time. Replay never resolves a conflict itself. Its exit +codes: 0 landed or idle, **4** a conflict was recorded `conflicted` and +routed to its authoring lane, **3** any other step failure (the intent is +left `replaying` and a later `replay` resumes it). + +## The Turso store + +The broker creates its schema at backend start. The `tasks` table carries: +`id`, `queue`, `title`, `body`, `payload` (default `'{}'`), `dedupe_key`, +`priority`, `status` (default `'queued'`), `not_before`, `worker_id`, +`claimed_at`, `lease_until`, `lane_id`, `platform`, `attempts` (default 0), +`max_attempts` (default 1000), the claim stamps (`claim_provider`, +`claim_model`, `claim_variant`, `claim_session_id`), `progress` and `result` +(default `'{}'`), `last_error`, the park columns (`park_kind`, `wait_kind`, +`ready_condition`, `required_budget_minutes`, `last_checked_at`, +`check_outcome`), the dep-block columns (`blocked_deps`, +`dep_next_recheck_at`, `dep_blocked_until`, `dep_recheck_seconds`), +timestamps, and `completed_at`. Its `(queue, dedupe_key)` index is +deliberately **not unique** — enqueue dedupe is a read-then-insert check. +Alongside: `leases` (one row per task), `lanes` (seeded with the 156 +canonical lanes when empty), `workers`, `checkpoints`, `repo_task_lane_ledger`, +`events`, `creation_outbox` (+ its circuit singleton), and `merge_intents`. + +Broker protocol facts: every verb is one `POST /` with a JSON args +object; the response envelope is `{ok:true, ...}` or `{ok:false, exit, +error}`. The only unauthenticated route is `GET /healthz`. The broker binds +*first* and brings the Turso backend up on a startup thread, so `/healthz` +and `/validate` answer immediately while other verbs answer exit 3 with a +`turso_pending` reason until the backend is ready. A transient store error +carrying PostgREST code `57014` or `PGRST002` is retried client-side with +exponential backoff and jitter: base 500 ms, doubling, cap 20 s, at most 6 +attempts. diff --git a/pkgs/fleet/book/concepts/search.md b/pkgs/fleet/book/concepts/search.md new file mode 100644 index 0000000000..2cb902cbed --- /dev/null +++ b/pkgs/fleet/book/concepts/search.md @@ -0,0 +1,146 @@ +# Search: the Atlas corpus + +The `search` domain (argv0 alias `atlas-search`) is the client surface for +Atlas: hybrid search over the fleet's session-history corpus. The domain has +two client verbs — `search` and `get-chunk` — and, under `fleet serve +search`, the search service itself. `init` and `fetch-model` deliberately +stay on the standalone atlas-search artifact; invoking them through fleet is +a usage error naming that artifact. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-search/src/cli.rs + +## Hybrid FTS + vector + +A search is **hybrid**: a full-text (FTS) branch and a vector branch each +produce candidates, and the results are fused. The default mode is `hybrid`; +`--mode fts|vector` runs one branch. The embedding model is Snowflake +arctic-embed-m-v2.0 — the source constant is +`Snowflake/snowflake-arctic-embed-m-v2.0` (the help text's spelling drops +the org slash; the source spelling is the operative one). + +Client flags with their defaults: + +| Flag | Default | Meaning | +|---|---|---| +| `--k N` | 10 | Final result count. | +| `--pool N` | 100 | Per-branch candidates; validated 1..=400. | +| `--mode MODE` | `hybrid` | `hybrid \| fts \| vector`. | +| `--kind CSV` / `--topic CSV` / `--project CSV` / `--client CSV` | — | Classification filters. | +| `--since YYYY-MM-DD` / `--until YYYY-MM-DD` | — | Sessions created on/after / on/before (inclusive). | +| `--max-sensitivity LV` | `personal` | `shareable \| personal \| local-only \| secret-bearing`. A *request*; the server clamps it (below). | +| `--group-by-session` | off | Roll chunk hits up to sessions. | +| `--expand N` | 0 | Include N neighbouring chunks around each hit. | +| `--with-message` | off | Include the parent message text. | +| `--no-cache` | off | Bypass service cache *reads*; the fresh result still lands in the cache. | +| `--no-wait` | off | Do not block: print the service job handle and return. (The one-shot default waits for the job.) | +| `--hydrate N` | 0 | Hydrate the top N results to full content. | +| `--raw-rows[=branches]` | — | Ungrouped rows: bare = flat fused rows; `=branches` = pre-fusion branch rows. | +| `--text` | off | Human-readable output instead of JSON (JSON is the default). | +| `--model NAME` | Snowflake arctic-embed-m-v2.0 | Embedding model. | +| `--embedder NAME` | `auto` | `auto \| fastembed \| st`. | +| `--trunc N` | 0 | Truncate vectors to N dims (0 = full). | +| `--vector-backend B` | `scan` | `scan \| index-fill \| index-fixed`. | +| `--service-url URL` | `http://127.0.0.1:18760` | Service base URL; env `ATLAS_SEARCH_URL`, then fleet.toml `[search] url`, override it. | + +Standalone-only engine knobs (`--backend`, `--db`) are deliberately not part +of this surface. + +`get-chunk [--neighbors N] [--text]` fetches one chunk with its +provenance (session, client, sensitivity); `--neighbors N` includes N +chunks either side **in the same message**. + +Invocation shapes: `fleet search [options]`, and +`fleet search search [options]` (atlas-search's own shape — the +leading `search` token is stripped). Exit codes mirror atlas-search: 0 ok, +2 usage/validation, 1 service-job/backend failure surfaced without a +fallback, 3 routing unavailable (no service and no standalone artifact). + +## Via-service vs standalone, by seat + +There are two routes, and the seat decides the default: + +- **Via-service**: an in-process client speaking the Atlas service's + loopback HTTP job protocol to the service at `--service-url` (default + `http://127.0.0.1:18760`): submit a search job, wait for it (unless + `--no-wait`), and render the result through writers ported for + byte-for-byte shape compatibility with atlas-search. The backend behind + the service is a read-only Turso corpus store with one shared Snowflake + embedder. +- **Standalone**: there is no second embedder or backend in the fleet + workspace — the client **delegates to the kept standalone `atlas-search` + binary on PATH**, passing the caller's arguments in atlas-search's own + shape (with `--via-service`/`--standalone` stripped, and `ATLAS_SEARCH_VIA` + removed from the child's environment so an ambient value cannot silently + re-route it), inheriting its stdout byte-for-byte. A missing artifact is + exit 3, naming it as "the search domain's kept standalone". + +Routing precedence: explicit `--via-service` / `--standalone` first (the +two together are a usage error); then env `ATLAS_SEARCH_VIA=service|standalone`; +then fleet.toml `[search] via`; then the seat default: + +- **Sandbox seat → via-service**, with a **loud** standalone fallback (a + warning on stderr naming the failure). The via-service client is + proxy-blind; the sandbox reaches the laptop's loopback service through + the loopback forward on the shared laptop-ssh control connection — the + deployed atlas-search wrapper's pattern, not a second mechanism. +- **Laptop seat → standalone.** The seat signal is the service's own config + file, `~/.local/state/atlas-search/service.json`: only the serving host + has one. + +`get-chunk` **always runs standalone** — it is job-scoped in the protocol, +so it cannot ride the service route. When via-service was *requested* (by +flag, env, or config — the seat default does not count) it prints the loud +fallback note first. + +## Sensitivity clamping + +The via-service client presents a per-seat bearer token — env +`ATLAS_SEARCH_TOKEN`, else the JSON file at +**`~/.config/atlas-search/client.json`** (a JSON object with one token +string field, file mode 0600). Identities are named in the service config, +and the **server** clamps `--max-sensitivity` to the identity's ceiling: +identity `drew-cli` → `secret-bearing`; identity `sandbox-scripts` → +`personal`. The fleet verb adds no ceiling logic of its own — a client can +ask for more than its ceiling, and the service silently serves at the +ceiling. A seat with no `client.json` cannot use the service route and +falls back to standalone. + +## The serve search service shape + +`fleet serve search` (also spelled `fleet search serve`, and reachable via +the `atlas-search serve` argv0 route) is the atlas-search service rehomed +into fleet — same config, same wire. Both spellings require the +`search-serve` capability, not the `search` client capability. + +``` +usage: fleet serve search [options] + --config PATH service config (default ~/.local/state/atlas-search/service.json; + env ATLAS_SEARCH_SERVICE_CONFIG) + --listen ADDR listen address override (loopback only) + --job-ttl-ms N completed-job TTL override, ms (default 600000) + --hard-ttl-ms N submit hard-cap override, ms (default 3600000) +``` + +Its guarantees: + +- **One shared embedder per process**: a single lazily loaded embedder (one + ONNX session, mutex-held), loaded on the first vector query only — + FTS-only jobs and a cold service work without it. Its load state is what + `/health` reports. The model is the Snowflake + `snowflake-arctic-embed-m-v2.0` model at a pinned snapshot revision; the + model directory resolves from `ATLAS_MODEL_DIR` or the Nix closure. +- **A mechanically read-only backend**: the Turso backend's token comes only + from the service config chain, never the environment; the resolution chain + is env, the Bitwarden item named `atlas-ro`, or the turso CLI's + `--read-only` mint; the query layer issues nothing but SELECTs. There is + no write path to opt into. +- **The job protocol** is a bounded async queue with in-memory temp state, + per-client recovery listing, and dedupe keyed by the effective request + (never across effective sensitivity ceilings). +- The engine is a verbatim copy of atlas-search's, held byte-for-byte by a + parity check script and the code repo's `fleet-search-parity-guard` + workflow. Rollback is pointing the unit's ExecStart back at + `atlas-search serve`. + +Exit codes for the service: 2 usage/config, 1 runtime failure; a running +service never exits 0. diff --git a/pkgs/fleet/book/concepts/secrets.md b/pkgs/fleet/book/concepts/secrets.md new file mode 100644 index 0000000000..0bc1503c25 --- /dev/null +++ b/pkgs/fleet/book/concepts/secrets.md @@ -0,0 +1,176 @@ +# Secrets and the secrets broker + +Fleet resolves secrets *by name, through one crate* (`fleet-secrets`). No +domain shells out to `bws` (the Bitwarden Secrets Manager command-line tool) +or reads a token file on its own. A caller names a secret; the chain finds +the value; the value goes only where the caller's contract says it goes. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/secrets_broker.rs and https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-secrets/src/lib.rs + +## The broker: a resident cache of the vault + +The *secrets broker* is a resident cache of the Bitwarden Secrets Manager +vault. It exists because the per-call alternative — `bws secret list` plus +`bws secret get` on every invocation — made every queue call pay 10–40 +seconds. The broker binds the laptop tailnet address `100.99.113.103:4800` +plus a Unix-socket dual-bind at `~/.config/secrets-broker/broker.sock`, with +identical routes and auth on both transports; a socket bind failure degrades +to TCP-only with a log line. Sandbox consumers reach it through the session +proxy — except on the sandbox itself, where `fleet init` runs a local +loopback copy: when `FLEET_LOCATION=sandbox`, the bind is **forced to +`127.0.0.1:4800`** at the bind itself, whatever the environment says, so a +stale or widened bind can never expose the vault off-host. (The domain +summary's phrase "the laptop secrets-broker" is therefore +location-relative.) + +Endpoints (the `X-Agent-Token` header is required on everything except +`/health`; an empty expected token never authenticates, not even against an +empty header): + +| Route | Answer | +|---|---| +| `GET /health` | `{ok, serving, secrets, last_refresh_unix, refreshing, oldest_secret_age_seconds}`; **503 while `serving` is false** | +| `GET /secrets` | `{names: [...]}` — names only, sorted | +| `GET /secret/` | `{key, value, fetched_at_unix, age_seconds, source}`, or 404 / 502 / 503 (below) | +| `POST /refresh` | 202 `{ok: true, refresh: "started"}` — kicks a refresh on a new thread | + +Auth failures are 401. Startup exit codes: 2 for a bad home or a refused +TTL, 3 for a token-file or bind failure. The broker's own token file is +`~/.config/secrets-broker/token` (`SECRETS_BROKER_TOKEN_FILE`). + +## The serving gate: 503 until loaded + +`serving` is true only once at least one refresh has *succeeded*. Before +that, `/health` answers **503** with `ok:false, serving:false` (plus +`refresh_error` when a refresh has failed), and `GET /secret/` +answers 503 `{error: "secrets not loaded yet", …}`. A live process whose +`bws` cannot run is *not* serving, and health says so: not-loaded is a +distinct, diagnosable state, not a 404. Clients key on this gate. + +## Cache semantics: age and source + +A cache hit answers 200 immediately with `source: "cache"`, the value's +`fetched_at_unix`, and its computed `age_seconds`. Every cached value +carries the time the broker last fetched it from Bitwarden, precisely so a +rotation runbook can tell "the broker is serving a value N seconds old" +from "Bitwarden itself holds this value". + +**Read-through on miss.** A miss on a *loaded* cache is not final: the +broker reads through to Bitwarden for that one name and serves what it +finds with `source: "bitwarden-read-through"`, `age_seconds: 0` — a secret +minted moments ago is visible immediately instead of at the next TTL tick. +Read-through is single-flighted per name: concurrent misses for the same +name wait on one gate instead of stampeding `bws`, and the cache is +re-checked after acquiring the gate in case a refresh landed the value +meanwhile. Outcomes: found → 200; definitely absent → 404 +`{error: "no such secret"}`; source failure → a loud **502** +`{error: "bitwarden read-through failed"}` — never a silent +404-as-if-absent. + +## Refresh: startup, TTL, and per-secret install + +A background thread runs a full refresh immediately at startup, then sleeps +the TTL and repeats — stale-while-revalidate: the cache keeps serving +during a refresh, and a failed refresh keeps the old values. One refresh is +`bws secret list` (parsed strictly — a malformed entry fails the parse +loudly rather than silently dropping a secret), then one `bws secret get` +per secret, fetched **8-way parallel** (an 8-worker pool over the name +list). Each `bws` child has a deadline, so a hung child fails its fetch +instead of wedging the refresh — and the `refreshing` flag — forever. A +second refresh requested while one is in progress is refused +(`refresh already in progress`). + +A refresh installs **per secret**, not all-or-nothing: fetches that succeed +land immediately with the batch's install time; a secret whose fetch fails +keeps its previous value *and age*; deletions follow the authoritative +list. Only a refresh in which *every* fetch fails keeps the whole previous +cache untouched. Net effect: a rotation lands within one TTL of the edit, +bounded and observable via the exposed age, and one broken fetch cannot +block every rotation in the vault. + +**TTL.** `SECRETS_BROKER_TTL_S`: default **900 s (15 minutes)**, minimum +**30 s**. Unset → 900, no warning. Unparseable → 900 with a warning naming +the offending value. Parsed but below 30 (including 0) → startup refuses to +run, exit 2, with an error naming the variable, the value, and the minimum +— because one interval costs a full vault refresh, and 0 would spin that +loop with no sleep at all (measured at roughly 110 full refreshes per +second). + +## The client chain: broker-first resolution + +`fleet secrets get ` takes exactly one name. The value goes to stdout +and nowhere else; errors are value-free shapes on stderr; a broken pipe on +stdout is a quiet success (the Unix-filter rule). `fleet secrets list` +prints the names in the broker's cache, one per line, never values. Exit +codes for both: 0 ok, 2 usage, 3 unresolved / broker unavailable. + +The resolution chain (`Resolver::default_chain`): + +1. **Broker leg(s) first.** Where the secrets broker's own socket answers + (the laptop), a direct source speaks `GET /secret/` over that Unix + socket. Elsewhere (the sandbox), the broker leg is a framed exchange + through the session broker to port 4800: the request names the token + *file* (`[secrets] token_file`, default `~/tools/secrets-broker-token`); + the session broker reads the file per request and sends its contents as + `X-Agent-Token` — fleet only ever names the file, and the value never + transits fleet's own memory on this leg. Exactly one broker leg owns the + retry budget; when a direct leg exists, the session-broker leg behind it + gets no retries. +2. **`bws` fallback.** `bws secret list` + `get`, the same shape the broker + itself uses. The fallback carries its own credential: the + `BWS_ACCESS_TOKEN` environment variable when non-empty, else the on-disk + machine-account token file, handed to the `bws` child via its + environment. +3. At library level, a 1Password source exists for seats that keep secrets + there; the same names resolve without a broker or a Bitwarden token. It + is not part of the `fleet secrets` command's headline chain. + +Retry semantics: a broker leg that cannot answer is retried before the +chain moves on — the budget is sized to real restart windows (a full switch +restarts broker and tunnel together; the broker is back in about 16 s) +without making a genuinely dead broker a hang: the first pause doubles per +attempt up to a cap, with a per-attempt ceiling on a single exchange. A +broker **404 is definitive** about the name and is not retried. If the +session-broker socket file does not exist at all, the leg does not burn the +retry budget — no broker on this box is not a broker mid-restart. + +**`list` has no `bws` fallback.** A broker failure is loud (stderr, exit 3), +because a `bws` listing enumerates the vault, not the broker's cache, and is +never silently substituted. For `list`, the source selection mirrors `get`'s +first leg only. + +## The three token files and bootstrap provisioning + +Names and paths only — never values. + +In Bitwarden Secrets Manager, the three broker service tokens are published +under the names `fleet.secrets-broker-token`, `fleet.queue-broker-token`, +and `fleet.laptop-agent-token`. On a seat they live as mode-0600 files: +`~/tools/secrets-broker-token`, `~/tools/queue-broker-token`, and +`~/tools/laptop-agent-token`. Two of the paths are compiled defaults in +`fleet-config`: the secrets token file is the one the session broker reads +per request for secrets-broker calls (overridable via `[secrets] +token_file`), and the laptop-agent token file is the one the session broker +reads when a request names none. Do not conflate these client-side +`~/tools/*-token` files with the daemon-side files in each broker's own +config directory (`~/.config/secrets-broker/token`, +`~/.config/queue-broker/token`). + +A newly enrolled seat does not arrive with these files. The bootstrap token +phase (in `scripts/muse/bootstrap.sh`'s restore phase — the seat-bootstrap +layer, **not** the fleet crates; no code under `pkgs/fleet/crates/` reads +those three Bitwarden names to create the files) fetches the three names +into the `~/tools/*-token` paths with 0600 permissions, so a seat can speak +to all three brokers from its first command. The known failure shape this +prevents: a seat kind whose bootstrap skips the token phase can enrol — its +bridge leg answers, because that leg is HTTPS plus a by-name secret — yet +fail its queue, secrets, and shell legs with synthesised transport errors, +because the three shared files were never provisioned for it. Note that the +older Bitwarden name `secrets-broker.token` is a *different* value and is +never used as the client token. + +What the binary itself provisions at runtime is narrower: `fleet init` +*spawns* the sandbox secrets broker (which then reads its own daemon token +file), and the brokers read their token files per startup or per request. +Token files stay files — read per request, never stored in memory +long-term, never logged. diff --git a/pkgs/fleet/book/development/add-a-flag.md b/pkgs/fleet/book/development/add-a-flag.md new file mode 100644 index 0000000000..47e6033c95 --- /dev/null +++ b/pkgs/fleet/book/development/add-a-flag.md @@ -0,0 +1,92 @@ +# Add a flag + +Adding a flag to an existing verb is a small change with more touch points than it looks like. This chapter uses the one fully traced example — `--drop-dep` on `fleet queue unblock` (#12777) — which took exactly five touches. Treat that list as the checklist for any flag; the parity test at the end is the gate that catches most misses. + +For adding a whole verb, see [Add a subcommand](add-a-subcommand.md). For the parser and usage machinery referenced throughout, see [Testing](testing.md) for the parity test and its known gap. + +## The case study: `--drop-dep` on `unblock` + +`unblock` clears a task's block. `--drop-dep ` additionally drops named dependencies in the same operation, surgically, instead of leaving the task blocked on a dependency that will never land. The list grammar is comma-separated `kind:ref` entries: `issue:`, `pr:`, or `ci:` followed by `owner/repo#N`, or `task:ID`. + +### Touch 1 — the parser declaration slice + +In the handler `cmd_unblock` (`crates/fleet-queue/src/client/commands_lifecycle.rs`), the flag is declared by adding one string to the flags slice of the existing `parse_verb_args` call: + +```rust +parse_verb_args("unblock", rest, &["worker", "reason", "drop-dep"], &[]) +``` + +The first slice is value flags; the second, empty here, is boolean flags — a boolean flag goes there instead. Nothing else about parsing changes: duplicates, missing values, and the `--drop-dep=` inline form all inherit the rules of `parse_args_inner` in `crates/fleet-queue/src/client/support.rs` (duplicate value flags are errors, a value flag followed by another `--flag` token is an error, unknown flags are `unrecognized argument: --`). + +### Touch 2 — the value parser + +A flag with a non-trivial value grammar gets a dedicated parser next to the handler: + +```rust +pub(super) fn parse_drop_dep_list(list: &str) -> Result, String> +``` + +in `commands_lifecycle.rs`. It parses the comma-separated `kind:ref` grammar and returns an error string on a bad reference. The accessor `drop_dep_flags(&args)` calls it and dies at the caller's terminal with exit 2 (`unblock: --drop-dep expects …`) on error. The handler then wires the result into the broker body only when it is non-empty: + +```rust +let drops = drop_dep_flags(&args); +if !drops.is_empty() { body["drop_deps"] = json!(drops); } +``` + +That conditional is deliberate: when the flag is absent, the body keeps exactly the old shape, so an older broker sees a request it already understands. + +### Touch 3 — both usage strings + +Both hand-maintained usage surfaces in `crates/fleet-queue/src/client/support.rs` gain the flag: + +- the `TOP_USAGE` synopsis line becomes `unblock [--worker ] [--reason ] [--drop-dep ]`; +- the `usage("unblock")` arm gains the synopsis plus the long explanation of `--drop-dep` semantics. + +Updating only one is the classic miss. The parity test (touch 5) enforces the second; the first is on you — see the discrepancy note in [Testing](testing.md). + +### Touch 4 — broker re-validation + +The broker does not trust the client's parse. `verb_unblock` in `crates/fleet-queue/src/turso_queue/admin.rs` reads `drop_deps` from the request body and routes to `fn unblock_drop(...)`, which re-validates every spec. The client's own comment states the contract: the broker re-validates every spec; a bad reference dies there first, at the caller's terminal. Client-side validation exists for fast, legible errors; broker-side validation is the authority, because the broker is the component that mutates state and other clients exist. + +### Touch 5 — docs and tests + +- `pkgs/fleet/docs/verbs.md` gains the flag in the verb's prose where it is user-facing, and this book's matching chapter is updated in the same change (DOC-01 — see [Keeping this book current](keeping-this-book-current.md)). +- Oracle-named tests cover the new behaviour. For `--drop-dep`, the fallback-side oracles from #12777 assert that the unblock marker stays audit-only and does not fold claim state. + +One deliberate non-touch: the flag was **not** added to the fallback grammar. Fallback `unblock` in `crates/fleet-queue/src/fallback.rs` still takes only `--worker` and `--reason`. A flag does not automatically exist in both transports; decide for each one, and record the decision in the change. + +## Step by step: add a flag + +1. Add the flag name to the correct slice of the handler's `parse_verb_args` call — value flags in the first slice, booleans in the second (`bools`). +2. If the value has a grammar, write a dedicated value parser next to the handler, returning `Result<_, String>`, and an accessor that dies with exit 2 and a message naming the expected shape. Wire the parsed value into the request body, conditionally if omitting it preserves the old body shape for older brokers. +3. Update **both** usage strings in `client/support.rs`: the `TOP_USAGE` synopsis and the `usage(verb)` long text. +4. Re-validate on the broker side if the flag reaches a broker verb. Never let a client parse be the only validation of a value that mutates state. +5. Decide the fallback grammar explicitly: add the flag to the `fallback.rs` twin, or record that it is primary-only. +6. Update `docs/verbs.md` and this book in the same change, and add oracle-named tests. + +## Defaults discipline + +- A new flag is optional unless the verb is meaningless without it. Adding a *required* flag to a shipped verb is a breaking change to every script that calls it; that needs its own justification, not a ride-along. +- An omitted flag must reproduce the old behaviour exactly — including the old request-body shape where a broker is involved, as the `drop_deps` conditional above does. +- Defaults that already exist are part of the contract: for example `--worker` defaults to `repo-worker-code` (with named exceptions such as `cancel`, whose worker defaults to `fleet-monitor`), and `--queue` defaults are verb-specific (see the queue chapters). Do not quietly change a default while adding an unrelated flag. +- Numeric flags die with exit 2 naming the flag when given a non-numeric value. Follow that shape for any new validated value. + +## Hidden flags: the `--reason-class` precedent + +Not every flag belongs in the usage strings. `fail` carries `--reason-class`, a hidden flag: it is accepted by the parser, it is a closed enum, and it defaults to `transient` — but it is not advertised in the verb's help. It exists so automated callers can classify a failure for the broker's retry and reporting logic without turning an internal taxonomy into a user-facing promise. + +Use the hidden-flag shape only when all three hold: + +1. The value set is a closed enum with a safe default, so omitting the flag is always correct for a human caller. +2. The intended callers are programs, not people reading `--help`. +3. The flag is still declared in the parser slice like any other — hidden means unadvertised, not unparsed or unvalidated. + +## The parity test is the gate + +`every_verb_usage_matches_its_parser` (in the `client.rs` test module) asserts that every verb's `usage()` text names exactly the flags its parser accepts. Add a flag to the parser without the usage text — or to the usage text without the parser — and the workspace test suite fails. Run it before you push: + +```sh +cargo test --workspace +``` + +Remember its one blind spot: it does not cross-check `TOP_USAGE`. Check that line yourself. diff --git a/pkgs/fleet/book/development/add-a-subcommand.md b/pkgs/fleet/book/development/add-a-subcommand.md new file mode 100644 index 0000000000..03476b834e --- /dev/null +++ b/pkgs/fleet/book/development/add-a-subcommand.md @@ -0,0 +1,82 @@ +# Add a subcommand + +There is no clap anywhere in the fleet workspace — no `clap` dependency in any fleet `Cargo.toml`, no derive macros. Every layer is hand-rolled by design: the top-level dispatch in `crates/fleet/src/main.rs` must behave identically in every variant, including the tiny connect build where the registry and the stub machinery are the product, and multicall routing happens before any per-domain parsing exists. Domains adopt their own parsers as they land. + +This chapter traces one real verb end to end — `fleet queue unblock` — and then gives the step-by-step for adding a new one. For adding a flag to an existing verb instead, see [Add a flag](add-a-flag.md). + +## The worked trace: `queue unblock` + +`unblock` is a good trace because it arrived later (#8276) and then grew a flag (#12777), so every seam shows. + +### 1. The registry entry + +In `crates/fleet-registry/src/lib.rs`, the `queue` entry of `pub const DOMAINS` lists `"unblock"` as one string in its `subcommands` array. That alone puts the verb in `fleet --help`, `fleet queue --help`, and `fleet capabilities` on *every* variant — including builds where the queue client is not compiled, which then answer the verb with the capability stub at exit 69. + +### 2. The client dispatch arm + +In `crates/fleet-queue/src/client.rs`, `pub fn run(args: &[String]) -> i32` is one match over the verb name. The arm is: + +```rust +"unblock" => cmd_unblock(rest) +``` + +where `rest = &args[1..]`. Bare invocation and `--help` are handled above the match (bare prints `TOP_USAGE` and exits 2; a lone help argument exits 0). An unknown verb prints `repo-queue: unknown command {:?}` plus `TOP_USAGE` and returns 2. The registry's 32 queue subcommands match the 32 arms of this match. + +### 3. The handler: `cmd_unblock` + +The handler is `pub(super) fn cmd_unblock(rest: &[String]) -> i32` in `crates/fleet-queue/src/client/commands_lifecycle.rs` — the module for lifecycle verbs (claim, lane, bind, heartbeat, checkpoint, park, wake, block/unblock, the dependency and quarantine rechecks, cancel, revive, fail, complete, health, signal, and the small outbox verbs). Query verbs live in the sibling module `commands_query.rs`. + +Its shape is the canonical shape for a broker-backed verb: + +```rust +let args = parse_verb_args("unblock", rest, &["worker", "reason", "drop-dep"], &[]); +reject_extra_pos("unblock", &args, 1); +let mut body = json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "reason": args.get("reason").unwrap_or_default(), +}); +let drops = drop_dep_flags(&args); +if !drops.is_empty() { body["drop_deps"] = json!(drops); } +let resp = unwrap_ok(call("/unblock", &body)); +print_json(&require_row(&resp, "unblock_task")); +0 +``` + +Five moves: declare the flags, validate the positionals, build the JSON body, call the broker, print the returned row. The helpers live in `crates/fleet-queue/src/client/support.rs`: + +- `parse_verb_args(verb, rest, flags, bools)` — `flags` are value flags, `bools` are boolean flags. Its pure core is `parse_args_inner`: duplicate value flags are errors (never silent last-wins), a boolean given `--flag=value` is an error, a value flag followed by another `--flag` token is an error, and an unknown flag is `unrecognized argument: --`. A help token that is not a flag *value* prints the verb's usage and exits 0; any shape rejection exits 2 with the message plus usage. +- `Args` — the parsed result, with `get`, `has`, `get_i64`, and `pos_i64` accessors. +- `call("/unblock", &body)` — the transport in `src/client/transport.rs`: session-proxy Unix socket from the sandbox, direct HTTP on the laptop, probe-selected. Exit 3 means the broker path was unavailable. +- `unwrap_ok` / `require_row(resp, "unblock_task")` / `print_json` — envelope handling: a broker envelope is `{ok: true, …}` or `{ok: false, exit, error}`; the client prints `error` and exits with `exit`. + +Help text is two hand-maintained strings in `support.rs`, both keyed by verb name: the `TOP_USAGE` synopsis line (`unblock [--worker ] [--reason ] [--drop-dep ]`) and the `usage(verb)` match arm (synopsis plus the long explanation). The parity test `every_verb_usage_matches_its_parser` fails the suite if they drift from the parser — with one known gap for `TOP_USAGE`, documented in [Testing](testing.md). + +### 4. The broker verb + +The client is not the end of the verb. Queue-broker routing in `crates/fleet-queue/src/queue_broker.rs` maps `POST /unblock` to `pub(crate) fn verb_unblock(t: &TursoBackend, req: &Value) -> Value` in `crates/fleet-queue/src/turso_queue/admin.rs`. It refuses a missing task and any task whose status is not `blocked` (`unblock_task: task is , not blocked`); otherwise it flips the task to `queued`, writes the audit events (`unblocked`, and `dep_unblock_override` with `via: "unblock_task_turso"`, worker and reason recorded), and returns the row the client prints as `unblock_task`. The surgical dependency-dropping path is `fn unblock_drop(...)` in the same file. + +### 5. The fallback twin + +A queue verb that must work while the broker is down also lands in `crates/fleet-queue/src/fallback.rs` (compiled only under the `client` feature — see [Testing](testing.md)). The fallback is the GitHub-issues transport of the same queue. For `unblock` it has: + +- its own dispatch arm, `"unblock" => cmd_unblock(rest)`; +- its own `fn cmd_unblock`, whose grammar is narrower — flags `&["worker", "reason"]` only; `--drop-dep` was deliberately not added to the fallback grammar; +- its own usage arm in `fallback_help`; +- the guard `fn unblock_refusal(open, labels, &ClaimState)`, which the comments require to *mirror* the broker's `verb_unblock` refusal rules; +- a marker discipline: the GitHub side records the override as an audit-only marker comment (``, `MarkerKind::Unblock`) that does not fold claim state. + +Fallback switching itself: a work verb that hits a primary-store failure switches to the GitHub fallback with exit 6 and one JSON object naming the switch. + +## Step by step: add a new verb + +The queue domain is written out in full; other domains follow the same shape minus the broker and fallback steps. + +1. **Registry entry.** Add the verb name to the domain's `subcommands` array in `crates/fleet-registry/src/lib.rs`. Do this only for a *top-level* verb of the domain — nested leaves such as `outbox claim` live only in the handler and the usage strings, not in the registry. +2. **Usage strings, both of them.** In `crates/fleet-queue/src/client/support.rs`, add the one-line synopsis to `TOP_USAGE` and the long-text arm to `usage(verb)`. The parity test checks the second; nothing checks the first, so review it by eye (see the discrepancy note in [Testing](testing.md)). +3. **Parser and handler.** Add the match arm in the domain's `run` (queue: `crates/fleet-queue/src/client.rs`) and write `cmd_` in the domain's commands module — lifecycle verbs in `client/commands_lifecycle.rs`, query verbs in `client/commands_query.rs`. Build it on `parse_verb_args` and, for a broker verb, on `call("/", body)` followed by `unwrap_ok` / `require_row` / `print_json`. +4. **Broker verb, if it mutates state.** Implement `verb_` in the appropriate `crates/fleet-queue/src/turso_queue/*.rs` module and route `POST /` to it from `src/queue_broker.rs`. The broker re-validates everything the client validated; the client-side checks are for fast, legible failure at the caller's terminal, not for safety. +5. **Fallback twin, if it must work broker-down.** Mirror the verb in `src/fallback.rs`: dispatch arm, handler, `fallback_help` arm, and a guard that mirrors the broker's refusal rules. Decide deliberately which flags the fallback grammar carries — parity with the primary grammar is not automatic, as `--drop-dep` shows. +6. **Tests.** Add oracle-named tests next to the code (see [Testing](testing.md)): parser invariants in the client tests, guard-mirror tests in `fallback.rs` where a twin exists, broker behaviour where the verb mutates state. Every test names its oracle and its issue. +7. **Docs in the same change (DOC-01).** Update `pkgs/fleet/docs/verbs.md` and the matching chapter of this book in the same change — the same pull request, not a follow-up. The full contract is in [Keeping this book current](keeping-this-book-current.md). +8. **Ship it.** A merged verb is not shipped until both live installs report it. Follow [Release and rollout](release-and-rollout.md) and verify by verb surface (`fleet queue --help`, the new verb's own `--help`), not by version string alone. diff --git a/pkgs/fleet/book/development/building.md b/pkgs/fleet/book/development/building.md new file mode 100644 index 0000000000..c3c99da4b9 --- /dev/null +++ b/pkgs/fleet/book/development/building.md @@ -0,0 +1,125 @@ +# Building fleet + +Fleet is one Rust workspace that produces one binary. Capability variants are selected by Cargo features; the installed binary is always named `fleet`, and hyphenated names (`fleet-serve`, `fleet-connect`, `repo-queue`, and so on) are argv0 personalities of that one binary, not separate artefacts. See [Repository layout](layout.md) for the workspace map and [Register a domain or capability](register-a-domain.md) for how features, capabilities, and profiles fit together. + +## Build with Nix (the normal route) + +1. From the repository root, build the package you need: + + ```sh + nix build .#fleet + ``` + +2. To build the full smoke set in one go: + + ```sh + nix build .#fleet .#fleet-serve .#fleet-connect .#fleet-connect-static + ``` + +3. Run the smoke suite over the results (see [Testing](testing.md)): + + ```sh + ./pkgs/fleet/smoke.sh ./result ./result-1 ./result-2 ./result-3 + ``` + +The builder is `pkgs/fleet/default.nix`. Its internal `mkFleet` function takes a package name, a Cargo feature set, an optional argv0 alias, an optional size gate, a platform, and a static flag. Cargo flags are always `-p fleet`, plus `--no-default-features` when the feature set is not the default, plus `--features ` when the set is non-empty — so the Nix attribute *is* the Cargo feature set. + +### The six attributes + +`default.nix` returns six attributes: + +| Attribute | Cargo features | Platform | Alias link | Size gate | +|---|---|---|---|---| +| `fleet` | default (= `full`) | glibc | — | no | +| `fleet-serve` | `serve` | glibc | `fleet-serve` | no | +| `fleet-connect` | none (`--no-default-features`) | glibc | `fleet-connect` | **yes** | +| `fleet-brokers` | separate build, see below | glibc | — | no | +| `fleet-static` | default (= `full`) | musl (`pkgsStatic.rustPlatform`) | — | no | +| `fleet-connect-static` | none | musl (`pkgsStatic.rustPlatform`) | `fleet-connect` | **yes** | + +Notes on each: + +- `fleet` is the full build: every domain and every serve role in the registry runs for real in it. +- `fleet-serve` and `fleet-connect` install side by side under their hyphenated names as a symlink to the same binary (`ln -s fleet $out/bin/` in `postInstall`). Invoking through that name narrows the surface to that variant's profile — narrowing only, never widening. +- `fleet-static` is the full profile linked for foreign soil: the artefact non-Nix hosts install, and the artefact `publish-fleet.sh` ships. See [Release and rollout](release-and-rollout.md). A glibc-dynamic build names Nix store paths a foreign host does not have, which is why the static exists. +- `fleet-connect-static` is the same idea for the connect profile. +- `fleet-brokers` is a separate `buildRustPackage` invocation on `-p fleet-queue --features client,queue-broker,secrets-broker --bins`. It produces the three standalone artefacts `repo-queue`, `queue-broker`, and `secrets-broker` from `fleet-queue/src/bin/*.rs` (each binary declares its `required-features` in `fleet-queue`'s `Cargo.toml`). Its header calls it the migration's rollback inventory: the standalone brokers retire only at the epic's close, not before. + +There is no `deploy` package in `pkgs/fleet/default.nix`. Deployment tooling is its own package tree, `pkgs/deploy/`. See [Release and rollout](release-and-rollout.md). + +### The D7 2 MiB connect gate + +Size, not speed, is the release profile's job. `pkgs/fleet/Cargo.toml` sets `[profile.release]` to `opt-level = "z"`, `lto = true`, `codegen-units = 1`, `strip = true`, against a design budget for the connect variant of target ≤ 1.5 MiB and hard ≤ 2 MiB, stripped. + +The hard bound is enforced in the build. For size-gated attributes, `postFixup` in `default.nix`: + +1. Strips explicitly and fully with `${binutils}/bin/strip` (the nixpkgs fixup phase only strips debug symbols, leaving the symbol table behind). +2. Reads the binary size with `stat -c %s`. +3. Fails the build if the size exceeds `connectMaxBytes = 2 * 1024 * 1024` (2,097,152 bytes). + +The gate is enforced a second time in `smoke.sh`, which runs both connect flavours under `env -i` and checks them against the same bound. Anything that would push the connect build over the gate — for example the `opencode-probe` feature, whose `ureq` + rustls stack would break it, or the optional `fleet-secrets` dependency — is kept out of the connect feature set by construction. + +### The crane deps split, and why the statics stay monolithic + +When the root flake's `make-fleet` passes a `craneLib`, `default.nix` splits the build: dependencies are built once via crane's `buildDepsOnly`, keyed on the manifests and the lockfile, so a source change rebuilds only the workspace crates instead of the whole dependency tree. + +Three attributes deliberately stay on the monolithic `buildRustPackage` path: + +- `fleet-static` and `fleet-connect-static` — under `pkgsStatic`, crane applies `crt-static` to host build scripts, and a libc build script then fails to link. +- `fleet-brokers` — its `--bins` build and its lib-tests check split do not map onto crane's single `cargoExtraArgs`. + +The build source is the whole `pkgs/` tree (a fileset union of `pkgs/fleet`, `../atlas-search/Cargo.toml`, `../atlas-search/crates`, and `../atlas-search/schema`), because `fleet-search` consumes the atlas crates by path. `sourceRoot` is the `fleet` directory inside it and `cargoLock` is `./Cargo.lock`. + +The check phase runs `cargoWithProfile test --locked` — deliberately flagless and workspace-wide. Crane's default would append `-p fleet` and narrow the run to the binary crate's tests alone. `preCheck` points `HOME` at a build-temporary directory because some atlas-search server tests write under `$HOME/.local/state/atlas-search` and the sandbox `HOME` is not writable. + +One environment detail: non-static, non-connect builds bake `ATLAS_SEARCH_ORT_LIB_DEFAULT` to the pinned ONNX Runtime library (ONNX Runtime is `dlopen`'d at runtime). The statics get no such default — a glibc `libonnxruntime` cannot be `dlopen`'d from a static binary — so the search-serve role in a static binary needs `ATLAS_ORT_LIB` supplied at runtime. + +## Build with Cargo (inside the workspace) + +1. Change into `pkgs/fleet/`. +2. Build the default (full) variant: + + ```sh + cargo build --release + ``` + +3. Build a narrowed variant by selecting features exactly as `default.nix` does. For the connect variant: + + ```sh + cargo build --release -p fleet --no-default-features + ``` + + For the serve variant: + + ```sh + cargo build --release -p fleet --no-default-features --features serve + ``` + +4. Run the workspace tests the same way CI and the Nix check phase do: + + ```sh + cargo test --workspace + ``` + +Feature sets are defined in `crates/fleet/Cargo.toml` under `[features]`: `default = ["full"]`; `full` lists every domain feature plus `opencode-probe`; `serve` is the broker-side subset shipped as one feature for the Nix build. `proxy-connect` is not a feature at all — it is compiled into every variant. + +### The toolchain pin + +`pkgs/fleet/rust-toolchain.toml` pins channel `1.99.1` with components `rustfmt` and `clippy` and profile `default`. Its header warns: do not delete the file — it is required for Nix builds — and a channel bump may cause rustc itself to build, so check that nixpkgs has the new channel cached before committing a bump. The nightly CI workflow installs this same pin; see [Testing](testing.md). + +`crates/fleet/build.rs` bakes the version facts into the binary: `FLEET_SOURCE_REV` (from the environment, else `git rev-parse`, else the honest string `unknown` — the Nix sandbox has no `.git`) and `FLEET_DERIVED_VERSION` (derived, never hand-maintained, from `git describe` over `fleet/v*` tags via the shared derivation in `src/derived_version.rs`, with fallbacks). + +## Serialising heavy builds: `fleet-build-lock` + +`pkgs/fleet/fleet-build-lock` serialises heavy builds (Cargo, Nix) so a host is never running more of them than it can bear. It implements the fleet build policy of at most `FLEET_BUILD_SLOTS` heavy builds at once on the host running it — **2 slots by default** — using `flock` slot files under `FLEET_BUILD_LOCKDIR` (default `~/.fleet-build-locks`). + +Properties that matter: + +- A build *waits* for a free slot. Load alone never parks work; the lock queues, it does not reject. +- It sets `CARGO_BUILD_JOBS` to half the host's cores unless that variable is already set. +- Usage is `fleet-build-lock [--] command [args…]`, run on the building host (the laptop), for example via the laptop agent. `fleet shell --build` takes a slot through it automatically. + +```sh +fleet-build-lock -- nix build .#fleet +fleet-build-lock -- cargo test --workspace +``` diff --git a/pkgs/fleet/book/development/keeping-this-book-current.md b/pkgs/fleet/book/development/keeping-this-book-current.md new file mode 100644 index 0000000000..1bfa1482c5 --- /dev/null +++ b/pkgs/fleet/book/development/keeping-this-book-current.md @@ -0,0 +1,70 @@ +# Keeping this book current + +A book that drifts from the binary is worse than no book: operators script against what it says. Fleet already had a documentation contract before this book existed — DOC-01, in the fleet README — and this chapter states that contract, then extends it to the book itself. + +## The DOC-01 contract + +DOC-01 is the "Operator and contributor contract" section of `pkgs/fleet/README.md` (#10728). Its contributor paragraph, in substance: + +> Keep the command contract together: update `crates/fleet-registry/src/lib.rs` when a top-level help inventory changes, and update `docs/verbs.md` for every changed or added command, including nested leaves and examples, in the same change. Docs must not present a designed spelling as shipped: the runtime dispatch is the authority on what a binary can run. And a change to any settled semantic the section records (claim/park/resume, supervision and stop authority, cap policy, attribution/logging) requires a decision record in the same body of work. + +The supporting rules in the same section: + +- **The inventory is the registry.** `fleet --help` renders the full registry on every variant and `fleet capabilities` prints it as JSON. The registered inventory lives in one place — `crates/fleet-registry/src/lib.rs` — so no build can know a domain another build forgot. See [Register a domain or capability](register-a-domain.md). +- **Designed-versus-shipped discipline.** Spellings that are designed but not yet shipped are documented *as contract, not surface*, explicitly marked as not in the registered inventory and not dispatchable today, each with its shipped equivalent. Invoking one answers `unknown command`. Never write a designed spelling into a procedure as if it works. +- **Decision records for settled semantics.** A change to claim/park/resume semantics, supervision or stop authority, cap policy, or attribution/logging requires a fleet decision record (FDR, in repository-root `doc/decisions/`, indexed by `doc/decisions/README.md`) in the same body of work — the same pull request, or the same run for non-PR work. +- **A machine check enforces the inventory half.** The test `pmo_operator_docs_match_registered_help_inventory` in `crates/fleet-registry/tests/pmo_operator_docs.rs` ties the README's operator contract to the registered help inventory: a verb added to the registry without its contract docs, or vice versa, fails the workspace test suite. See [Testing](testing.md). + +## The extension: the book is part of the same change + +This book is now one of the surfaces DOC-01 covers. The rule: + +**Any change to a command, a flag, a default, a capability, a surface, or an operational procedure updates the matching chapter of this book in the same pull request.** + +Concretely, in the same change as the code: + +1. A new or changed verb or flag → its command-reference chapter, plus [Add a subcommand](add-a-subcommand.md) or [Add a flag](add-a-flag.md) if the change alters the pattern those chapters teach, plus `pkgs/fleet/docs/verbs.md` per DOC-01. +2. A new domain or capability → [Register a domain or capability](register-a-domain.md) and [Repository layout](layout.md). +3. A changed default → every chapter that states the old default. Search the book for the value; defaults are stated in more places than you remember. +4. A changed operational procedure (ports, profile names, heal order, rollout order) → the matching operations chapter: [Running the brokers as services](../operations/services.md), [Health checks and the heal stack](../operations/health-and-healing.md), or [Release and rollout](release-and-rollout.md). +5. A changed deployment of the book itself → [Deploying this book](../operations/deploying-this-book.md). + +"Same change" means same pull request. A follow-up issue promising to update the book later does not satisfy the rule — that is exactly how the pre-book docs drifted into the disagreements the research for this book catalogued (a README package count that no longer matched `default.nix`, usage strings that disagreed with each other, help text describing an earlier epic step as current). If you find such a disagreement while writing, fix the stale side if it is in your change's scope; otherwise file an issue in the owning repository in the same pass and note it in your change. + +## The two build gates + +Two mechanical gates keep the book honest: + +1. **`create-missing = false`.** The book's `book.toml` sets `create-missing = false`, with the standing rule inherited from the mcpx exemplar: every chapter in `SUMMARY.md` must exist on disk; never invent stubs. Adding a `SUMMARY.md` entry without the file fails the build instead of silently publishing an empty page. +2. **The Nix build.** The book builds as the `.#fleet-docs` package (see [Deploying this book](../operations/deploying-this-book.md)). The build-only workflow `fleet-docs.yml` runs that build on `main`, and the combined Pages deploy rebuilds it again. A chapter that breaks mdBook — a bad link target, a missing file — fails the build by name rather than shipping broken. + +Internal links in this book are relative `.md` links only, and every file starts with its exact chapter title as its single `# ` heading. Both are part of the contract: relative links keep the book readable in the repository as well as on the rendered site, and the title rule keeps `SUMMARY.md`, the file, and the rendered page in agreement. + +## Where the rule is recorded + +The rule lives in three places, which must agree: + +1. `pkgs/fleet/README.md` — the DOC-01 contract itself, the source of truth for the registry and `verbs.md` halves. +2. `pkgs/fleet/doc/agents/documentation.md` — the agent-facing documentation rules inside the package, which carry the book rule for sessions working in this tree. +3. This chapter — the book stating its own maintenance rule, so a reader who arrived here first can find the whole contract. + +If the three disagree, the README's DOC-01 text wins for command-contract questions and this chapter wins for book-scope questions — and the disagreement itself gets fixed in the same pass it is noticed. + +## Build and preview the book locally + +1. From `pkgs/fleet/`, with mdBook available, build in place: + + ```sh + mdbook build + ``` + + The rendered site lands in the build directory named by `book.toml`. Open its `index.html` to preview. +2. Or build the packaged form, exactly as CI does, from the repository root: + + ```sh + nix build .#fleet-docs + ``` + + The result is the rendered site; serve or open `result/index.html` to check links, search, and chapter order before merging. + +Either route is a valid pre-merge check. The Nix route is the stronger one: it is the same derivation the deploy uses, with the same mdBook version. diff --git a/pkgs/fleet/book/development/layout.md b/pkgs/fleet/book/development/layout.md new file mode 100644 index 0000000000..67bf4b92ee --- /dev/null +++ b/pkgs/fleet/book/development/layout.md @@ -0,0 +1,55 @@ +# Repository layout + +Fleet lives in `pkgs/fleet/` in the `developing-today/code` repository. It is a self-contained Cargo workspace on the `pkgs/atlas-search` pattern: its own `Cargo.toml`, `Cargo.lock`, and `rust-toolchain.toml`, with no workspace relationship to the repository root. The design of record is epic `developing-today/code#5412`. + +This chapter is the map. For how the pieces are built, see [Building fleet](building.md). For how they are tested, see [Testing](testing.md). + +## The 13-crate workspace + +`pkgs/fleet/Cargo.toml` declares 13 members, `resolver = "2"`, workspace version `0.1.0`, edition 2024, rust-version 1.85, licence `MIT OR Apache-2.0`. Shared external dependencies are pinned once in `[workspace.dependencies]` (`serde 1` with derive, `serde_json 1`, `sha2 0.11`, `toml 1.2`); the 12 library crates are path dependencies of the binary crate. + +| Crate | What lives there | +|---|---| +| `crates/fleet` | The binary crate. `[[bin]] name = "fleet"`, entry point `src/main.rs`. It has no `lib.rs`. It also holds the bin-crate-only domains: `src/secrets.rs`, and the `gh` domain in `src/gh.rs` with `src/gh_cache.rs`, `src/gh_closure.rs`, `src/gh_guard.rs`, `src/gh_metadata.rs`, plus `src/session_state.rs`, `src/invocation_ledger.rs`, `src/derived_version.rs`, and `build.rs`. | +| `crates/fleet-registry` | The full domain registry: names, one-line descriptions, argv0 aliases, capabilities, and variant profiles. Standard-library only, strings and tables only, no I/O. Compiled into every variant so `--help` is always complete. Single file: `src/lib.rs`. | +| `crates/fleet-config` | Configuration: `~/.config/fleet/fleet.toml` plus environment resolution, the `[domains]` enable/disable table, and state-directory paths. Single large `src/lib.rs`. | +| `crates/fleet-secrets` | The one secrets-by-name path: secrets-broker protocol first, `bws` CLI fallback, `op` CLI where a vault is named. Values are never stored, never logged, and redacted in `Debug`. Single `src/lib.rs`. | +| `crates/fleet-proxy-proto` | The session-proxy wire contract: length-prefixed JSON framing (an 8-byte big-endian length prefix plus JSON) and the hello/capability frame types. The contract lives here and nowhere else. | +| `crates/fleet-queue` | The queue domain: the repo-queue client surface plus the queue-broker and secrets-broker server roles. By far the largest crate. Key files: `src/client.rs` and its submodules under `src/client/` (`commands_lifecycle.rs`, `commands_query.rs`, `fallback_stack.rs`, `mode_report.rs`, `support.rs`, `transport.rs`, `verify_disposition.rs`), `src/fallback.rs`, `src/placement.rs`, `src/validate.rs`, `src/turso_queue.rs` and `src/turso_queue/`, `src/queue_broker.rs`, `src/secrets_broker.rs`. Standalone binaries in `src/bin/`: `repo-queue`, `queue-broker`, `secrets-broker`. | +| `crates/fleet-dispatch` | The dispatch domain: a thin client over the pm-stack `pm-dispatch` service — status, launch, and enqueue verbs. Exactly three routes: `GET /health`, `POST /v1/sessions`, `POST /v1/tasks`. Single `src/lib.rs`. | +| `crates/fleet-dispatch-test` | The dispatch-test domain: scan fleet repositories for free GitHub Actions capacity, submit a job to the Turso-backed jobs store, dispatch the pilot workflow, and track the stored status. Single `src/lib.rs`. | +| `crates/fleet-proxy` | The session proxy domain: `proxy serve` (the broker) and `proxy connect` / `proxy init` (the client). Files include `src/serve.rs`, `src/client.rs`, `src/http.rs`, `src/tunnel.rs`, `src/connect_udp.rs`, `src/files.rs`, plus extra binaries `fleet-connect-udp` and `fleet-udp-forward`. | +| `crates/fleet-laptop-agent` | The laptop-agent domain: the transport ladder (broker, Cloudflare, Tailscale, SSH) and the verbs over the laptop-agent daemon. Files: `src/lib.rs`, `src/cli.rs`, `src/client.rs`, `src/guard.rs`, `src/ladder.rs`, `src/legs.rs`. | +| `crates/fleet-search` | The search domain: the atlas-search client surface over the live Atlas service, and the `serve search` role — the Atlas service itself, rehomed from the atlas-search bin crate. Files include `src/cli.rs`, `src/client.rs`, `src/proto.rs`, `src/serve.rs`, `src/server.rs`. Feature-split into `client` and `serve`. It is the one member that consumes crates outside the workspace (`atlas-core`, `atlas-embed`, `atlas-proto` by relative path under `../atlas-search/crates/`). | +| `crates/fleet-bridge` | The bridge domain: send and receive through the message bridge's fleet mailboxes. Single `src/lib.rs` plus `src/tests.rs`. | +| `crates/fleet-agent` | The agent domain: enrol a named agent of any kind, check what a seat can reach (`doctor`), ask for the next piece of work down the intake ladder (`next`), and open a shell where builds belong. Files: `src/lib.rs`, `src/enroll.rs`, `src/kinds.rs`, `src/next.rs`, `src/shell.rs`, `src/shortlist.rs`, `src/tests.rs`. The `shell` domain is served by this crate's `run_shell` entry point. | + +Where each domain lives, in one rule: a domain's client surface, parser, and usage strings live in its owning crate (or, for `secrets` and `gh`, in the binary crate); the registry entry that names it lives in `fleet-registry`; the dispatch arm that reaches it lives in `crates/fleet/src/main.rs`. See [Register a domain or capability](register-a-domain.md) for what a new domain must add in each of those places. + +## Supporting files at `pkgs/fleet/` + +- `default.nix` — the Nix builder for all fleet packages. See [Building fleet](building.md). +- `fleet-surfaces.json` — the placement registry: the execution surfaces placement may choose between, the owners they draw capacity from, and the laptop saturation flag. It is compiled into the binary (`include_str!`) and rendered by `fleet queue surfaces`. Add a surface by adding a registry entry and a compatible workflow. +- `migrations/` — the fleet database migrations, numbered SQL files from `0001_agent.sql` through `0026_ainventory_interpretation.sql`, including their test, check, and rollback companions. +- `repo-task-v1.schema.json` — the task packet schema that `fleet queue validate` checks a task packet against. +- `smoke.sh` — the hermetic, per-variant, post-build smoke suite. See [Testing](testing.md). +- `fleet-build-lock` — the bash helper that serialises heavy builds fleet-wide to a small number of slots. See [Building fleet](building.md). +- `rust-toolchain.toml` — the pinned toolchain. See [Building fleet](building.md). +- `README.md` — the package's own long-form document, including the operator and contributor contract (DOC-01). See [Keeping this book current](keeping-this-book-current.md). +- Helper scripts: `fleet-fetch.py` (deterministic repository snapshot fetcher writing into the fleet-queue database), `lane-claim.sh` and `lane-handoff.sh` (pilot lane claim one-shots), `enqueue-when-green.sh` (enqueue a pull request into the merge queue the moment its required check goes green), `turso-exec.py`, and the Python predecessors and peers of the Rust laptop-agent surface, `laptop-agent.py` and `laptop-agent-broker.py`. +- Subtrees that are not part of the Rust workspace: `archer-slack/` (Python Slack collector/puller), `hosted-worker/` (the TypeScript/Cloudflare Worker edition of the queue and `gh` surfaces), `placement/` (a small Go module: `policy.go`, `evaluate.go`, `cmd/placement-record/` — a proof of concept, not the live placement engine, which is the Rust code in `fleet-queue`), and `runtime-db-export/` (Python export/load tooling). + +## The `doc/` versus `docs/` split + +Fleet's documentation predates this book and is split three ways. Do not merge the directories; each has a distinct job. + +1. `pkgs/fleet/docs/` — long-form operator documents that ship with the package. Exactly two files today: + - `docs/verbs.md` — the canonical command reference. The repository-root `AGENTS.md` points contributors at it, and the DOC-01 contract requires it to change with every command change. + - `docs/fleet-gh-credentials.md` — the `fleet gh` credential lifecycle. +2. `pkgs/fleet/doc/` — agent-facing runbooks inside the package. Exactly one file today: `doc/agents/remote-build-and-test.md` (dispatch builds and tests remotely; do not compile on the sandbox or the laptop). +3. Repository-root `doc/` — the fleet-wide record that lives outside the package: `doc/agents/` runbooks (including `fleet-command-channel.md` and `onboarding-an-agent.md`, which the fleet README cites by paths that look fleet-local) and `doc/decisions/`, the fleet decision records (FDR-0001 onwards, with an index in `doc/decisions/README.md`). + +Two consequences to know before you go looking: + +- Source files cite a design of record at `doc/2026-11-04T11-45-48Z_design_fleet_multicall_binary/`. That directory is **not** under `pkgs/fleet/doc/`; a reader who starts there will not find it. +- This book is a fourth home, and it does not replace the other three. `docs/verbs.md` remains the canonical verb reference, the FDRs remain the decision record, and this book is the narrative and procedural layer over both. The rule that keeps all of them in step is in [Keeping this book current](keeping-this-book-current.md). diff --git a/pkgs/fleet/book/development/register-a-domain.md b/pkgs/fleet/book/development/register-a-domain.md new file mode 100644 index 0000000000..f319821309 --- /dev/null +++ b/pkgs/fleet/book/development/register-a-domain.md @@ -0,0 +1,95 @@ +# Register a domain or capability + +A domain exists in fleet because three things agree: the registry names it, a Cargo feature compiles it in, and the runtime reconstructs the same fact from the compiled binary. This chapter explains that machinery and lists everything a new domain must add. For the crate map, see [Repository layout](layout.md); for the build attributes that select feature sets, see [Building fleet](building.md). + +## The registry: `crates/fleet-registry/src/lib.rs` + +`fleet-registry` is a dependency-free crate of strings and tables — no I/O — compiled into every variant, including `fleet-connect`, so that `--help` is always complete. It owns three things. + +### Domains + +`pub const DOMAINS: &[Domain]` is the full registry, in help order, with 12 entries: `queue`, `serve`, `proxy`, `dispatch`, `dispatch-test`, `secrets`, `gh`, `bridge`, `agent`, `shell`, `search`, `laptop-agent`. `pub fn domain(name)` is a linear find over it. + +`struct Domain` is the unit that help lists, stubs name, and config disables: + +| Field | Meaning | +|---|---| +| `name: &'static str` | The domain's invocation name. | +| `summary: &'static str` | The one-line description help renders. | +| `capabilities: &'static [Capability]` | Every capability the domain spans. | +| `primary: Capability` | The headline capability availability keys on. Example: on `fleet-serve` the `search` domain is marked absent because its headline is the client, even though the `search-serve` capability exists under `serve`. | +| `aliases: &'static [&str]` | The domain's argv0 aliases. | +| `subcommands: &'static [&str]` | The top-level verb inventory, rendered by domain help and checked by the DOC-01 machine test. | + +`struct AliasRoute { domain, implied_arg }` and `pub fn alias_route(argv0)` define the argv0 map. The shipped aliases are: `repo-queue` → `queue`; `queue-broker` → `serve` with implied arg `queue-broker`; `secrets-broker` → `serve` with implied arg `secrets-broker`; `laptop-agent-broker` → `proxy` with implied arg `serve`; `atlas-search` → `search`; `laptop-agent` → `laptop-agent`. An argv0 that is none of {`fleet`, a variant name, an alias} is a usage error at exit 2 naming the expected names. `is_known_invocation_name(name)` is `fleet` ∨ variant name ∨ alias. + +### Capabilities: the 15 atoms + +`enum Capability` has 15 variants with stable string ids (`Capability::id`, `Capability::ALL`): + +`proxy-connect`, `proxy-serve`, `proxy-raw-splice`, `queue`, `queue-broker`, `secrets-broker`, `search`, `search-serve`, `dispatch`, `dispatch-test`, `laptop-agent`, `secrets`, `gh`, `bridge`, `agent`. + +Note there is no `shell` capability atom: the `shell` domain rides on the `agent` capability. + +`CapabilitySet` is a `BTreeSet`, built with `capability_set(&[…])`. Named sets: `full_capabilities()` (all 15), `serve_capabilities()` = {ProxyConnect, ProxyServe, ProxyRawSplice, QueueBroker, SecretsBroker, SearchServe, Secrets}, and `connect_capabilities()` = {ProxyConnect, ProxyRawSplice}. + +### `CapState`: the four availability states + +At dispatch, `Surface::cap_state(cap, domain_name)` checks in order and yields `enum CapState`: + +| State | Meaning | +|---|---| +| `Available` | Compiled in, in profile, not config-disabled. The domain handler runs. | +| `NotInBuild` | The Cargo feature was not compiled into this build. | +| `NarrowedByName` | Compiled in, but the argv0 profile (below) narrowed it out. | +| `DisabledByConfig` | The `[domains]` table in `fleet.toml` disabled it on this host. | + +Any non-`Available` state falls through to the stub (exit 69 — see the stub wordings below). `Surface` itself is the invocation's whole effective surface: `compiled` (from Cargo features), `profile` (from the hyphenated invocation name), `effective` (= `compiled ∩ profile.capabilities()`, or `compiled` when there is no profile), and the loaded `fleet_config::Config`. + +The registry's own tests are invariant oracles: `capability_ids_are_unique_and_stable`, `variant_profiles_nest` (connect ⊂ serve ⊂ full, and full == ALL), `every_domain_primary_is_in_its_surface`, `aliases_route_to_real_domains`, `domain_aliases_match_the_argv0_map`. + +## How capabilities are compiled in: `compiled_capabilities()` and bin-crate features + +Two layers, and both must agree. + +**Layer 1 — Cargo features on the binary crate** (`crates/fleet/Cargo.toml`, `[features]`): + +- `default = ["full"]`. +- `full = [proxy-serve, queue, queue-broker, secrets-broker, search, search-serve, dispatch, dispatch-test, laptop-agent, secrets, gh, bridge, agent, opencode-probe]`. +- `serve = [proxy-serve, queue-broker, secrets-broker, search-serve, secrets, opencode-probe]` — the broker-side subset, shipped as one feature for the Nix build. +- The connect build is `--no-default-features` with nothing optional on. +- `proxy-connect` is **not** a feature: it is compiled into every variant. +- Each feature wires optional dependencies, for example `queue = ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/client"]` and `search-serve = ["dep:fleet-search", "fleet-search/serve"]`. `fleet-proxy` is a non-optional dependency with `default-features = false`: the proxy client is in every variant, only the broker half (`fleet-proxy/serve`) is gated. +- Two things are kept out of connect on purpose: `opencode-probe` (its `ureq` + rustls stack would break the D7 2 MiB gate — see [Building fleet](building.md)) and `fleet-secrets` (the connect variant carries nothing else). + +Domain crates mirror the discipline one level down. In `fleet-queue`, the features are `client`, `queue-broker`, and `secrets-broker`, and `src/lib.rs` gates modules on them: `client`, `fallback`, `needs_drew`, `placement` under `client`; `queue_broker`, `turso_queue`, `validate` under `queue-broker`; `secrets_broker` under `secrets-broker`; `uds_http` under either broker. In `fleet-search`, `client` and `serve` split the client surface from the Atlas service role. + +**Layer 2 — runtime reconstruction.** `fn compiled_capabilities()` in `crates/fleet/src/main.rs` starts from `{ProxyConnect, ProxyRawSplice}` unconditionally and inserts one `Capability` per `cfg!(feature = "…")`. `build_variant(compiled)` then re-derives which shipped `Variant` the set equals — Full, Serve, or Connect; an unrecognised set reports its build name as `fleet-custom`. The binary *reports* its variant from its feature set; it does not trust a baked-in name. `fleet capabilities` prints both lists: `capabilities` (what this invocation can use) and `compiled_capabilities` (what the binary was built with) — their difference is exactly the profile and config narrowing. + +## argv0 profiles narrow only + +`enum Variant { Full, Serve, Connect }` is a property of the artefact whose names double as invocation profiles: `Variant::name()` is `fleet` / `fleet-serve` / `fleet-connect`. `Variant::from_invocation_name()` recognises only the two hyphenated names; plain `fleet` selects no profile. + +The rule is **narrowing only**: a profile is a capability ceiling (`compiled ∩ profile.capabilities()`), never a widening. Invoking the full binary as `fleet-connect` gives you the connect surface; invoking the connect binary as `fleet` gives you nothing extra, because the capabilities were never compiled in (`NotInBuild`, not `NarrowedByName`). An alias route, by contrast, constructs the surface with no profile at all and prepends its implied argument. + +## The stub wordings + +When a domain is not `Available`, `fn stub(...)` in `main.rs` prints to stderr and returns exit 69 (`EXIT_UNAVAILABLE`, `EX_UNAVAILABLE` from sysexits.h). The first line names the domain and the reason class; the second line lists what this invocation *can* do (`Enabled capabilities: .`); the third names the build. One form per `CapState`: + +- `NotInBuild`: `fleet: this build does not include ''.` plus `This is the build ().`, and ` The full build is 'fleet'.` when the build is not full. +- `NarrowedByName`: `fleet: invoked as '', this build does not include ''.` plus the explanation that the invocation is name-scoped to the profile and that invoked as `fleet` it carries the full surface. +- `DisabledByConfig`: `fleet: '' is disabled by config on this host.` plus the instruction to re-enable the domain under `[domains]` in the named `fleet.toml` path. +- `Available` (the step-1 form, for a surface compiled in with nothing behind it): `fleet: '' is included in this build but not implemented yet.` plus the step-1 skeleton wording of epic #5412. + +Help renders the same states without stubbing: domain help is registry data and is always available, even where the domain is not. Help marks each domain `included in this build`, `not in this build — invoking it prints the capability stub (exit 69)`, `narrowed out by this invocation name — … (exit 69)`, or `disabled by config on this host (exit 69 if invoked)`, and top-level help closes with: "A domain this invocation cannot use answers with a stub and exit code 69." + +## Step by step: what a new domain must add + +1. **Registry entry.** A `Domain` in `DOMAINS` in `crates/fleet-registry/src/lib.rs`, in help order, with `name`, `summary`, `capabilities`, `primary` (which must be a member of its own `capabilities` — the registry tests enforce this), `aliases`, and `subcommands`. If the domain needs a new capability atom, add the `Capability` variant with a stable string id and place it in `ALL` and in the named sets it belongs to. +2. **Crate.** A new library crate under `pkgs/fleet/crates/`, added to the workspace `members` in `pkgs/fleet/Cargo.toml` and to `[workspace.dependencies]` by path, exposing a `run` entry point with the domain's argument and config shape. Follow the existing crates' feature discipline: gate server roles and heavy dependencies behind features so the connect build stays clean. +3. **Bin-crate wiring.** An optional dependency plus a feature in `crates/fleet/Cargo.toml`; the feature added to `full` (and to `serve` if the domain has a broker-side role); one `cfg!(feature = "…")` insertion in `compiled_capabilities()` in `main.rs`. +4. **Dispatch arm.** In `run_domain` in `main.rs`, a `#[cfg(feature = …)]` arm under the `CapState::Available` path calling the crate's `run`. Subcommand-sensitive capability requirements (the way `serve` maps its role token to `QueueBroker` / `SecretsBroker` / `SearchServe` / `ProxyServe`) go in `required_capability(...)`. An argv0 alias, if the domain needs one, goes in `alias_route()` in the registry — and the registry test `domain_aliases_match_the_argv0_map` must still pass. +5. **Help.** The registry entry *is* the top-level help. The domain's own `--help`, per-verb usage strings, and parser live in the domain crate, hand-rolled — see [Add a subcommand](add-a-subcommand.md). +6. **Capabilities JSON.** Nothing extra to write: `fleet capabilities` is generated from the registry plus `compiled_capabilities()`, so a correctly registered domain appears in it automatically, with its per-domain `state` one of `available`, `not-in-build`, `narrowed-by-name`, `disabled-by-config`. Verify it does, on both a full build and a narrowed build. +7. **Build and smoke coverage.** A Nix attribute only if the domain needs a new variant (rare — variants are profiles, not domains). Smoke coverage in `pkgs/fleet/smoke.sh` that the domain renders in help on every variant and stubs at 69 where it is unavailable. +8. **Docs in the same change (DOC-01).** `pkgs/fleet/docs/verbs.md` and this book in the same change — see [Keeping this book current](keeping-this-book-current.md). The DOC-01 machine test (`pmo_operator_docs_match_registered_help_inventory`) ties the README's operator contract to the registered inventory, so a registry entry without its contract docs fails the workspace suite. diff --git a/pkgs/fleet/book/development/release-and-rollout.md b/pkgs/fleet/book/development/release-and-rollout.md new file mode 100644 index 0000000000..72512066ea --- /dev/null +++ b/pkgs/fleet/book/development/release-and-rollout.md @@ -0,0 +1,126 @@ +# Release and rollout + +Fleet has three distinct release motions, and confusing them is the classic rollout mistake: + +1. **Publish** — build the static binary and upload it as a GitHub release asset (`scripts/muse/publish-fleet.sh`). +2. **Bootstrap pin** — point fresh-seat provisioning at that asset (`scripts/muse/bootstrap.sh`). +3. **Deploy** — roll broker services on the laptop through generation-based profiles (`pkgs/deploy/deploy.py`), and update the two live installs of the binary itself. + +The governing rule, from the fleet README's Deploy section: **a verb is not shipped when it merges — it is shipped when both live installs report it.** That rule exists because of a real failure (#6728): `fleet queue fallback` was merged as source and docs while the installed binaries answered `repo-queue: unknown command "fallback"` for a full day. + +## 1. Publish: `scripts/muse/publish-fleet.sh` + +The script builds the static fleet binary and uploads it as a GitHub release asset on `developing-today/code`, then prints the tag and sha256 to pin in `bootstrap.sh`. + +Contract: at most one positional argument, `REV` (default `origin/main`); no flags; `-h` / `--help` prints the header; anything else exits 2 before any subprocess runs (the operator-script argument contract: a script declares its whole command line and parses strictly against that declaration before any subprocess, network, file write, lock, or deploy step). + +Steps: + +1. Fetch `origin main` and resolve the revision. The tag is derived from it: `short` is the 7-character revision prefix and `tag = "fleet-static-$short"`. +2. Create a throwaway detached git worktree at that revision (removed by an exit trap) and build inside it: + + ```sh + nix build "$work/src#fleet-static" + ``` + + Building in a detached worktree, not the primary clone, keeps the primary on `main` and clean. +3. Gate the artefact, twice: + - **Static-linkage gate** — `file -L` on the binary must report `statically linked` or `static-pie`. A non-static build is refused. + - **Bridge-capability gate** — the binary's `capabilities` output, checked programmatically, must show a domain named `bridge` with `available` true. The Muse seat's bootstrap requires the bridge-capable full profile; a build without it is fatal. +4. Copy the binary to the asset name `fleet-x86_64-linux-musl` and write its checksum file `fleet-x86_64-linux-musl.sha256` (` `). +5. Publish idempotently: if the release `fleet-static-` already exists, download its existing `.sha256` and re-upload with `--clobber` only when the checksum differs; otherwise create the release as a prerelease targeted at the revision, with notes naming the build command and the bootstrap consumer. +6. Read the two output lines — they are the pin values for the next step: + + ```text + tag=fleet-static- + sha256= + ``` + +## 2. The bootstrap pin: `scripts/muse/bootstrap.sh` + +`bootstrap.sh` rebuilds a Muse sandbox seat from nothing — tools, config, laptop link — with every phase idempotent and skipping work already done. It runs in **8 phases**: `tools token restore tailnet fleet persist init check`, selectable with `--only ` / `--skip `; `--all` also restores `~/git` and `~/agents`. Exit 0 means ok, exit 1 names the failed phase, exit 2 is a usage error. + +The fleet pin is a pair of lines near the top of the script, under the comment "pinned artifacts (update together; sha256 of the downloaded file)": + +```sh +FLEET_URL="${FLEET_URL:-https://github.com/developing-today/code/releases/download/fleet-static-/fleet-x86_64-linux-musl}" +FLEET_SHA256="${FLEET_SHA256:-}" +``` + +Both are environment-overridable. The URL is exactly the publish step's tag scheme plus the asset name. To move the pin: + +1. Run `publish-fleet.sh` for the revision you intend to ship and note its `tag=` and `sha256=` lines. +2. Edit both `FLEET_URL` (the tag segment) and `FLEET_SHA256` in `bootstrap.sh`, together, in the same change. Updating one without the other makes every fresh bootstrap fail its checksum. +3. Commit and merge through the normal worktree-and-pull-request flow. + +How the pin is consumed: in the `tools` phase, a sha256-verifying `fetch` downloads the pinned binary into `$HOME/.local/share/muse-bootstrap/fleet/fleet` — kept under the plain name `fleet` in its own off-PATH directory, because fleet picks its verb set from argv0 — and only when the existing copy is missing or fails the same `has_bridge` capability probe publish used. `fetch` dies on a sha256 mismatch. In the `fleet` phase, that download becomes the seat's install at `~/tools/fleet`: if the existing file is not writable it is moved aside to `~/tools/fleet.old`; the new binary is installed atomically (`install -m 755` to `~/tools/fleet.tmp`, then `mv -f` over `~/tools/fleet`) and only when the bytes differ; then `~/tools/bin/fleet` and `~/tools/bin/repo-queue` are symlinked to `~/tools/fleet` — the `repo-queue` link is the argv0 alias doing the work, not a second binary. + +The other phases, briefly: `token` obtains the seat's Bitwarden Secrets Manager access token; `restore` restores the seat's files and provisions the shared broker token files by name from Bitwarden Secrets Manager; `tailnet` joins the tailnet and writes the `[host]` config into `~/.config/fleet/fleet.toml`; `persist` saves a boot hook that re-runs `--only tailnet,fleet` after a sandbox recycle; `init` brings up the seat's init stack (see [Running the brokers as services](../operations/services.md)); `check` verifies the install — `fleet version` and `capabilities` including the bridge capability, laptop-link reachability the way fleet dials it, secret resolution by name, and a bridge hello/inbox probe as the seat's agent. + +## 3. Deploy the brokers: `deploy.py` profiles and generations + +Broker services on the laptop are deployed with `pkgs/deploy/deploy.py` — a registry-validating deployment CLI (stdlib-only Python). Service definitions live in `pkgs/deploy/services.nix`; the registry the CLI consumes is baked into its package at build time. A valid definition carries exactly the fields `package, entryPoint, args, environment, secrets, user, ports, restart, healthCheck, targets` (plus optional `healthTimeoutSeconds` and `timer`), and a `class` — for the laptop brokers, `systemd`. Secrets in a definition are **names only**, resolved by the secrets broker at activation time; a definition never carries a value. + +The three fleet profiles: + +| Profile | Package / entry point | Args | Port | Health check | +|---|---|---|---|---| +| `queue-broker` | `fleet`, `bin/fleet` | `serve queue-broker` | 4801 (`PORT=4801`, `QUEUE_BROKER_BACKEND=turso`) | `GET /healthz` on the laptop tailnet address, port 4801 | +| `secrets-broker` | `fleet`, `bin/fleet` | `serve secrets-broker` | 4800 (`PORT=4800`) | `GET /health` on the laptop tailnet address, port 4800 | +| `laptop-agent` | `laptopAgent`, `bin/laptop-agent` | none | 4799 (`LAPTOP_AGENT_PORT=4799`) | none — `/health` requires the daemon token, so health is verified through the authenticated client after activation | + +`queue-broker` names one secret by name (the Turso fleet-queue read-write token); `secrets-broker` names none, because it *is* the resolver. `laptop-agent` restarts `always` rather than `on-failure`: a clean SIGTERM/success exit does not restart under `on-failure`, and a past daemon-death episode showed that gap is real. + +### Profiles, generations, and the generation log + +Each target owns a per-service Nix profile. The system-scope default base is `/nix/var/nix/profiles/per-service`; sandbox targets default to `~/.local/share/deploy/profiles` (home survives a sandbox recycle; `/etc` does not). `--profile-base` / `$DEPLOY_PROFILE_BASE` relocates the base. + +The rendered systemd unit's `ExecStart` points at the profile's **`current`** link (`//current/`), never at a bare store path — so a generation flip is a profile repoint, not a unit rewrite, and the unit file itself does not change between generations. A flip is one atomic symlink repoint at the generation directory (`/.generations///`). + +Every deploy and rollback appends to an **append-only JSONL generation log**, one file per target at `/generations/.jsonl` (state dir via `--state-dir` / `$DEPLOY_STATE_DIR`). Each event records the generation id, source revision, artefact, timestamp, and actor. The log is never truncated; the current and previous generations are derived by *folding* it in order — a `deploy` event makes its generation current, a `rollback` event makes the generation it repointed to current, and previous is the last distinct generation before current. + +### Activation and rollback + +1. Preview with no side effects: + + ```sh + deploy --dry-run + ``` + + This prints the ordered activation plan, which is the oracle for what a real activation will do. +2. Activate. The real run, in plan order: build → install the next generation into the profile → write the unit → daemon-reload → restart **only that unit** → health-check (the definition's `healthCheck` URL, within `healthTimeoutSeconds`). On any failure, the profile flips back to the previous generation and the unit restarts on it. +3. Roll back when a generation is bad. **Rollback is a repoint, never a rebuild:** repoint the profile at the previous distinct generation → restart → health-check → on failure, flip back to the generation you came from → append a `rollback` event to the log. Rollback refuses when no generations are recorded or only one is ("rollback needs a previous generation"). `deploy status` folds the log and reports current and previous with their source revisions plus health. + +## 4. The two live installs of the binary + +Separate from `deploy.py`, the fleet binary itself has two live installs, and both must move for a change to count as shipped: + +1. Build **one** artefact from current `main` and record its version: + + ```sh + nix build .#fleet + ./result/bin/fleet version + ``` + + Both installs must match that build's source revision. +2. **Laptop install** — a plain binary copy over the laptop's `~/.local/bin/fleet`. Verify in place. +3. **Sandbox install** — `~/tools/fleet`, reached through the `~/tools/bin/fleet` and `~/tools/bin/repo-queue` symlinks. This install is root-owned provisioning, read-only to lanes: a lane that cannot redeploy it files or updates the tracking issue instead of working around it. In practice it moves through the bootstrap path of section 2. + +One warning from the same README section: a vendor-step failure naming an atlas crate means `pkgs/fleet/Cargo.lock` has drifted from the atlas-search path dependencies. `bash .github/scripts/check-fleet-lock.sh` names the drift in seconds; regenerate with `(cd pkgs/fleet && cargo update --workspace)` before building. The same check runs in CI — see [Testing](testing.md). + +## 5. Seat rollout order and verification + +Roll a new binary out to seats in this order: + +1. Publish the static artefact and move the bootstrap pin (sections 1–2), so any seat rebuilt from scratch lands on the new build. +2. Deploy the laptop brokers through `deploy.py` if the change touches a broker role, and verify each profile's health check. +3. Update the laptop install (`~/.local/bin/fleet`), then the sandbox install (`~/tools/fleet`). +4. Verify **per seat**, by surface, not by version string alone: + + ```sh + fleet version + fleet capabilities + fleet queue --help + ``` + + `fleet version` on each seat must report the same source revision as the artefact you built, and the verb surface you shipped must be present — for a new verb, run the verb's own `--help` on each seat. A seat still answering `unknown command` for a merged verb is not rolled out, whatever its version line says. diff --git a/pkgs/fleet/book/development/testing.md b/pkgs/fleet/book/development/testing.md new file mode 100644 index 0000000000..69c490acdb --- /dev/null +++ b/pkgs/fleet/book/development/testing.md @@ -0,0 +1,82 @@ +# Testing + +Fleet's testing doctrine comes from the repository's standing rules: property-based tests where code has meaningful invariants, model-based tests where a spec or model exists, and **every automated test names its oracle** — in practice, test names and comments carry the issue number and the invariant they check (`Oracle (#7598): …`, `#12777 oracle: the unblock marker is audit-only…`). `proptest 1.12` is a dev-dependency of the binary crate (for the `gh` read classifier) and of `fleet-queue` (for the client parser invariants). + +Run the whole suite from `pkgs/fleet/`: + +```sh +cargo test --workspace +``` + +## Inline, oracle-named tests per crate + +Tests are overwhelmingly inline `#[cfg(test)] mod tests` in the file they test. The shape per crate: + +| Crate | Where the tests live | +|---|---| +| `fleet` (bin) | Inline tests in `src/main.rs` (serve-list parsing, proxy-ssh argv building, help-flag positions, broker-role argument rejection) plus integration targets in `tests/`: `invocation_ledger.rs`, `proxy_ssh.rs`, `search_serve.rs`. | +| `fleet-registry` | In-file invariant tests (`capability_ids_are_unique_and_stable`, `variant_profiles_nest`, `every_domain_primary_is_in_its_surface`, `aliases_route_to_real_domains`, `domain_aliases_match_the_argv0_map`) plus the integration target `tests/pmo_operator_docs.rs` — the DOC-01 machine check described in [Keeping this book current](keeping-this-book-current.md). | +| `fleet-queue` | A very large inline test module in `src/client.rs` (parser invariants, the usage↔parser parity test below, timeline rendering), marker-fold oracles in `src/fallback.rs`, tests in the `src/client/` command modules, and integration targets gated by feature (next section). Two Python SQL regressions ship as test data: `implementation_repo_sql.py` and `quarantine_atomic_sql.py`. | +| `fleet-config` | A large inline suite (around fifty tests) plus proptest. | +| `fleet-secrets` | A large inline suite (around thirty-five tests). | +| `fleet-search` | `tests/serve_contract.rs` for the serve-role contract. The server is a parity-guarded copy of the atlas-search service, also guarded by the `fleet-search-parity-guard` workflow. | +| `fleet-agent` | Inline `src/tests.rs`; proptest regression seeds are checked in at `proptest-regressions/tests.txt`. | +| `fleet-dispatch`, `fleet-laptop-agent`, `fleet-bridge` | Inline tests in `src/lib.rs` / `src/tests.rs` and module tests. | + +## Feature-gated integration tests: `[[test]] required-features` + +Because the workspace is feature-split (see [Register a domain or capability](register-a-domain.md)), a test target declares the features it needs, and Cargo only builds it when that surface is compiled. In `fleet-queue`'s `Cargo.toml`: + +- `tests/broker_bin_args.rs` — `required-features = ["queue-broker", "secrets-broker"]` +- `tests/chunked_list.rs` — `required-features = ["client"]` +- `tests/person_wait_cli.rs` — `required-features = ["client"]` + +The consequence to remember: the fallback module sits behind the `client` feature (`#[cfg(feature = "client")] pub mod fallback;` in `crates/fleet-queue/src/lib.rs`), so **a broker-only test run does not compile the fallback tests at all**. The fallback oracles run only under a client-carrying feature set. The Nix `fleet-brokers` test flags and the full-variant check phase both carry `client`; a local `cargo test --features queue-broker` run silently skips them. When you change fallback behaviour, run a client-carrying test set explicitly. + +## `pkgs/fleet/tests/` — the one Python test + +`pkgs/fleet/tests/` contains exactly one file, and it is not a Cargo integration test: `test_tailnet_proxy_env.py`, a Python test of the tailnet proxy environment contract for the Python-side tooling that shares the tree. + +Other test-bearing corners outside the crates: `pkgs/fleet/archer-slack/` Python tests, `pkgs/fleet/hosted-worker/test/` TypeScript tests for the hosted Worker edition (including `stamp-sig.test.ts`, the golden-vector conformance surface the Rust `gh` domain's Ed25519 signing must reproduce byte-exact), `pkgs/fleet/placement/evaluate_test.go` for the Go placement proof of concept, and `pkgs/fleet/migrations/*_test.sql`. + +## `smoke.sh` — the hermetic post-build suite + +`pkgs/fleet/smoke.sh` is the per-variant, post-build smoke suite. It is hermetic by contract: no network, no installs, no state outside a `mktemp` directory, and it exits non-zero if any check fails. + +1. Build the four outputs (see [Building fleet](building.md)). +2. Invoke it with the four Nix package output paths; each argument's `bin/fleet` is the artefact under test: + + ```sh + ./pkgs/fleet/smoke.sh ./result ./result-1 ./result-2 ./result-3 + ``` + +What it covers: + +- **Variants** — for each of full, serve, connect, and static: `--help` renders the full registry with unavailable domains marked, and `version` lists exactly that variant's capability set. +- **Stubs** — a missing domain stubs with exit 69 and the right wording, reached three ways: `fleet `, an argv0 alias symlink, and a hyphenated variant name (which narrows). A config-disabled domain stubs at 69 with the config wording. +- **Connect hygiene** — both connect flavours run under `env -i` and are within the D7 size gate (≤ 2 MiB). +- **Search serve role** — reaches the real role rather than a stub; hermetically it stops at config load (exit 2) before any token is needed. +- **Proxy domain end to end** — broker auto-start, round-trips, shim materialisation and stale-shim removal on a services-map change, init no-op, location-aware init cases (an unknown location reports and exits 69 with no broker spawned), legacy proto-0 interop, idle exit, pool default rendering, a 32-concurrent burst, and the identity stamp. +- **Queue domain** — the secrets-broker role binds and `/health` answers (in the hermetic world, 503 with `serving=false` is the *pass* shape); the queue-broker `/healthz` answers; client-to-broker wiring (a credential failure surfaces as exit 3 with broker wording); the fallback switch (one JSON object, exit 6) and the operator escape hatch underneath it; client `--help` / `--version` through the argv0 route. +- **Dispatch domain** — the thin client against a stub pm-dispatch and a stub `bws` on `PATH`: the token is resolved by name, presented as `Authorization: Bearer`, the service JSON is printed verbatim, and a deliberate 409 is passed through. +- **Secrets domain** — the broker-first chain against a stub session broker speaking the framed protocol, with the `bws` fallback behind it. + +## CI: main only + +Repository policy: CI runs only on `main`. There are no pull-request runs, required status checks are disabled, and formatting is not a merge gate (it is auto-fixed on `main`). The fleet-relevant workflows: + +| Workflow | Trigger | What it runs | +|---|---|---| +| `fleet-rust-tests.yml` | Nightly cron (`17 7 * * *`) plus `workflow_dispatch` only | A contract check (`check-fleet-rust-tests.sh`, plus that script's own test), installs toolchain 1.99.1 via rustup (the `rust-toolchain.toml` pin), then `cargo +1.99.1 test --manifest-path pkgs/fleet/Cargo.toml --workspace --all-targets --locked`. Its header records why it exists: before it, the workspace's tests ran in no CI venue at all, and the baseline run found a stale dep-wiring oracle and a parallel-spawn flake in `fleet-queue`. | +| `fleet-smoke.yml` | Push to `main` with paths under `pkgs/fleet/**`, the atlas-search manifests/crates, the workflow, and its check scripts; plus `workflow_dispatch` | Contract checks, the **fleet `Cargo.lock` versus atlas manifests check** (`check-fleet-lock.sh` — it fails by name instead of deep inside a derivation when the lockfile has drifted from the atlas-search path dependencies), Nix-builds the four outputs `.#fleet .#fleet-serve .#fleet-connect .#fleet-connect-static`, runs `pkgs/fleet/smoke.sh` on them, and greps the log for `^smoke: [1-9][0-9]* passed, 0 failed$` so a silently skipped suite cannot report green. Timeout 150 minutes (a cold cache compiles ONNX Runtime from source; warm is roughly 40 minutes). | +| `fleet-search-parity-guard.yml` | Per its own triggers | Guards the "verbatim copy" claim of `fleet-search`'s `server.rs` against the atlas-search service. | + +Each fleet workflow carries a contract step — a shell check script *and that script's own test* run before the real work — so a workflow edited out of sync with the test-suite registry fails by name. + +> Discrepancy note (workflow text): `fleet-rust-tests.yml`'s concurrency comment speaks of push-to-main runs, but the workflow has no push trigger at all — nightly plus dispatch only, by a deliberate ruling. The header's nightly note is the true statement; the comment is leftover boilerplate. + +## The usage↔parser parity test — and what it does not check + +Queue usage text is hand-maintained in two strings per verb, both in `crates/fleet-queue/src/client/support.rs`: the one-line synopsis in `TOP_USAGE` and the long text returned by `usage(verb)`. The parser is hand-rolled (`parse_verb_args` / `parse_args_inner` in the same file). The machine check that keeps them honest is `every_verb_usage_matches_its_parser` in the `client.rs` test module: it asserts that every verb's usage names *exactly* the flags its parser accepts. Companion tests are `usage_covers_the_acceptance_verbs` and `usage_never_prints_nothing` (an unknown verb falls back to `TOP_USAGE`). + +**What it does not cross-check: `TOP_USAGE`.** The parity test checks each verb's own `usage()` text against its parser; it does not check the `TOP_USAGE` synopsis lines against either. That drift is real today: for `release`, `heartbeat`, `checkpoint`, `fail`, and `complete`, the per-verb `usage()` text carries `[--lane ]` while the `TOP_USAGE` synopsis omits `--lane`. The parser is the authority on which spelling is right for each verb. Until a cross-check exists, anyone editing a verb's flags must update both strings by hand — the procedure in [Add a flag](add-a-flag.md) says exactly that. diff --git a/pkgs/fleet/book/getting-started/installation.md b/pkgs/fleet/book/getting-started/installation.md new file mode 100644 index 0000000000..03fca11bf5 --- /dev/null +++ b/pkgs/fleet/book/getting-started/installation.md @@ -0,0 +1,169 @@ +# Installation and bootstrap + +There are two ways to get fleet onto a machine: + +1. **The static release** — a single statically linked musl binary published + as a GitHub release asset. This is what a fresh sandbox seat installs, + through `scripts/muse/bootstrap.sh`. It needs no Nix and no shared + libraries, which is the point: a glibc-dynamic build names Nix store paths + that a non-Nix host does not have. +2. **A Nix build** — one of the variant packages from the repo flake, for + machines that are part of the Nix fleet (the laptop, NixOS hosts). + +## The static musl release + +The release is produced by `scripts/muse/publish-fleet.sh`: + +- It builds the `fleet-static` package (the full capability profile on the + musl `pkgsStatic` Rust platform) in a throwaway detached git worktree at the + requested revision (default `origin/main`). +- It refuses to publish an artifact that is not statically linked, and it + probes the artifact's `capabilities` output: a build whose `bridge` domain + is not available is fatal, because a Muse seat's bootstrap requires the + bridge-capable full profile. +- The release tag is `fleet-static-`, where `` is the first 7 + characters of the commit SHA. The asset name is + `fleet-x86_64-linux-musl`, published alongside + `fleet-x86_64-linux-musl.sha256` containing the asset's SHA-256 sum. +- The script prints exactly two lines for the operator to pin in the + bootstrap script: `tag=fleet-static-` and `sha256=`. + Re-publishing an existing tag only re-uploads when the sum differs. + +Source: https://github.com/developing-today/code/blob/main/scripts/muse/publish-fleet.sh + +## Bootstrap: `scripts/muse/bootstrap.sh` + +A Muse sandbox seat is rebuilt from scratch whenever the sandbox is recycled: +no fleet binary, no laptop link. `bootstrap.sh` rebuilds the seat. Every phase +is idempotent and skips work already done. Exit codes: 0 success, 1 a phase +failed (the message names it), 2 usage. Phases are selectable with +`--only ` / `--skip `; `--all` additionally restores `~/git` and +`~/agents`. + +**The pin.** Two lines near the top of the script, both overridable from the +environment, pin the release: + +```sh +FLEET_URL="${FLEET_URL:-https://github.com/developing-today/code/releases/download/fleet-static-b8bbcc0/fleet-x86_64-linux-musl}" +FLEET_SHA256="${FLEET_SHA256:-}" +``` + +The URL is exactly the publish tag scheme (`fleet-static-<7-char short sha>`) +plus the asset name. `FLEET_AGENT` (default `muse`) and `FLEET_AGENT_GROUPS` +select the seat identity; groups are never hardcoded for another agent kind. + +**The phases**, in the order `PHASES="tools token restore tailnet fleet persist init check"`: + +1. **tools** — downloads the pinned fleet binary, verifying its SHA-256, into + `$HOME/.local/share/muse-bootstrap/fleet/fleet`. It is kept under the name + `fleet` in its own off-PATH directory because fleet picks its verb set from + argv0 (the name it is invoked under). The download is skipped when the + existing copy is present and passes the bridge-capability probe. The phase + also installs `bws`, `restic`, and `tailscale` into the seat's bin + directory; a tailscale failure only skips the tailnet phase. +2. **token** — obtains the Bitwarden Secrets Manager access token for the + seat. +3. **restore** — restores the seat's files with restic, and provisions the + three shared broker token files from Bitwarden Secrets Manager, each with + owner-only (0600) permissions: + `fleet.secrets-broker-token` → `~/tools/secrets-broker-token`, + `fleet.queue-broker-token` → `~/tools/queue-broker-token`, and + `fleet.laptop-agent-token` → `~/tools/laptop-agent-token`. Bitwarden is the + source of truth for these three names. A missing name is not fatal: the + enrolment continues and the check phase names the gap. See + [Secrets and the secrets broker](../concepts/secrets.md) for why these + files matter. +4. **tailnet** — joins the tailnet and points fleet's laptop link at it. In + kernel mode the seat dials the laptop directly; in userspace mode traffic + goes through tailscaled's CONNECT proxy, which fleet expects on port 3130, + and the phase writes `fleet-proxy.env` with + `HTTPS_PROXY=http://127.0.0.1:3130`. The phase also writes the `[host]` + config into `~/.config/fleet/fleet.toml`. +5. **fleet** — installs the binary at **`~/tools/fleet`**. If the existing + file is not writable it is moved aside to `~/tools/fleet.old` (with sudo + when available). The install is atomic — `install -m 755` to + `~/tools/fleet.tmp`, then `mv -f` over `~/tools/fleet` — and happens only + when the bytes differ. The phase then creates two symlinks: + `~/tools/bin/fleet` → `~/tools/fleet` and `~/tools/bin/repo-queue` → + `~/tools/fleet`. The `repo-queue` link is the argv0 alias doing the work; + there is no second binary. +6. **persist** — writes `~/tools/muse-bootstrap.sh` plus a boot hook that, + after a sandbox recycle, re-runs `--only tailnet,fleet` under + `flock -n $HOME/tools/.muse-boot.lock` with a 300 s timeout. Only + `/home/hatch` survives a recycle, so persistence lives there. +7. **init** — brings up the seat's init stack (brokers, the `gh` shim, the + laptop channel) from the restored tools. This is the same work + `fleet init` does; see [Proxy, sessions and recovery](../concepts/proxy.md). +8. **check** — verifies the seat: `fleet version` and `fleet capabilities` + run and the bridge capability is present; the laptop link is reachable the + way fleet dials it; `fleet secrets get tailscale.auth-key` (a secret name) + resolves; `fleet secrets list` answers (the session broker answering is + the expected path; the `bws` fallback is noted as acceptable); and a + bridge hello/inbox probe succeeds as the seat's agent. + +Source: https://github.com/developing-today/code/blob/main/scripts/muse/bootstrap.sh + +## Nix build variants + +From the repo root, the flake exposes the fleet packages: + +```sh +nix build .#fleet .#fleet-serve .#fleet-connect .#fleet-connect-static +``` + +`pkgs/fleet/default.nix` returns six attributes: + +| Attribute | Cargo features | Platform | Installed alias link | Size gate | +|---|---|---|---|---| +| `fleet` | default (= full) | glibc | — | no | +| `fleet-serve` | `serve` | glibc | `fleet-serve` | no | +| `fleet-connect` | none (`--no-default-features`) | glibc | `fleet-connect` | yes | +| `fleet-brokers` | `fleet-queue` with `client,queue-broker,secrets-broker`, `--bins` | glibc | — | no | +| `fleet-static` | default (= full) | musl (`pkgsStatic`) | — | no | +| `fleet-connect-static` | none | musl (`pkgsStatic`) | `fleet-connect` | yes | + +Facts that matter when choosing one: + +- The installed binary is always named `fleet`. A hyphenated name + (`fleet-serve`, `fleet-connect`) is installed as a *symlink to the same + binary*; the name narrows the capability surface at invocation time. See + [The shape of the binary](shape.md). +- The size gate is the connect variant's budget: the stripped binary must be + at most 2 MiB (2,097,152 bytes) or the build fails. +- `fleet-brokers` builds the three standalone broker artifacts `repo-queue`, + `queue-broker`, and `secrets-broker` from the `fleet-queue` crate. They are + the migration's rollback inventory and retire only at the close of the + multicall epic. +- The static builds carry no ONNX Runtime library path: the search-serve role + in a static binary needs `ATLAS_ORT_LIB` supplied at runtime. The glibc + non-connect builds bake the path in. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/default.nix + +## Verifying an install + +Two built-in commands verify any install. Both take no arguments — a trailing +argument, including `--help`, is a usage error (exit 2). + +```sh +fleet version +fleet capabilities +``` + +`fleet version` prints five lines: the version (`fleet 0.1.0`), the build +name (`fleet`, `fleet-serve`, or `fleet-connect`, derived by matching the +compiled capability set against the variant sets — with an annotation when +the invocation name narrowed the surface), the derived version (of the form +`0.1.0-dev+g`), the source revision (the full commit SHA the build was +cut from), and the enabled capabilities — the *usable* set for this +invocation, in registry order, or `none`. + +`fleet capabilities` prints the same facts as JSON, plus the full domain +registry with, for each domain, its summary, aliases, required capabilities, +and a `state` of `available`, `not-in-build`, `narrowed-by-name`, or +`disabled-by-config`. It prints two distinct lists: `capabilities` (what this +invocation can use) and `compiled_capabilities` (what the binary was built +with). Their difference is exactly the narrowing applied by the invocation +name and the host config. On a full build both lists are the same 15 +capabilities and every domain is `available`. The Quickstart chapter, +[Quickstart](quickstart.md), walks through what to do with this output. diff --git a/pkgs/fleet/book/getting-started/quickstart.md b/pkgs/fleet/book/getting-started/quickstart.md new file mode 100644 index 0000000000..b1607754a6 --- /dev/null +++ b/pkgs/fleet/book/getting-started/quickstart.md @@ -0,0 +1,140 @@ +# Quickstart + +The five-minute path. It assumes fleet is installed (see +[Installation and bootstrap](installation.md)) and runs five commands, in an +order that checks each layer before the next one depends on it: the binary, +the seat, a secret, the queue, and finally taking work. Every command here is +read-only except the last, which claims a task only when work is available. + +## 1. `fleet version` and `fleet capabilities` — the binary + +```sh +fleet version +fleet capabilities +``` + +`fleet version` prints five lines: version, build name, derived version, +source revision, and enabled capabilities. What you are checking: the build +name is `fleet` (the full build) and the enabled-capabilities line is not +`none`. The short form `fleet --version` prints only the first two lines. + +`fleet capabilities` prints the registry as JSON. What you are checking: the +`capabilities` and `compiled_capabilities` lists match (both are the full 15 +on an unnarrowed full build), and every entry in `domains` has +`"available": true`. If a domain shows `"state": "narrowed-by-name"`, you +invoked the binary under a variant name such as `fleet-connect`; invoke it as +`fleet`. If it shows `"disabled-by-config"`, the host's `fleet.toml` disables +that domain under `[domains]`. If it shows `"not-in-build"`, the binary is a +narrowed build. Invoking an unavailable domain prints a stub and exits 69; +see [The shape of the binary](shape.md). + +## 2. `fleet agent doctor` — the seat + +```sh +fleet agent doctor +``` + +Doctor probes the seat's four *legs* — a leg is one route the seat needs — +in parallel, each by running a real fleet verb as this seat, and prints one +JSON object: + +| Leg | Probe | What "up" needs | +|---|---|---| +| `bridge` | `bridge inbox --agent --limit 1` (with a known agent name) | HTTPS to the message bridge, and the fleet token resolved by name through fleet secrets | +| `queue` | `queue health` | The queue broker: its socket on the laptop, or the laptop transport from elsewhere | +| `github` | `gh api rate_limit` through `fleet gh` (falling back to a plain signed-in `gh`) | A working `gh` token, by fleet rotation or by sign-in | +| `shell` | `laptop-agent health` | A route to the laptop: its broker, the Cloudflare tunnel, the tailnet, or SSH | + +The bridge probe is deliberately a read made *as* an agent: service health +alone proves nothing about whether this seat holds the fleet token, so with +no agent name known the bridge leg is reported not ok even when the service +answers. + +From the legs, doctor derives the *rungs* map — which rungs of the intake +ladder (see step 5) this seat still has: `push` follows the bridge leg, +`queue` follows the queue leg, `shortlist` is always true (it is a local +file), and `priority` follows the github leg. It also reports `builds`: +whether `fleet shell` reaches the laptop from here. + +Exit codes: 0 when any intake rung is live (bridge, queue, or github), 3 +when none is, 2 for a usage error. A seat with only HTTPS still has rungs 1 +and 4 of the ladder; doctor tells you exactly which world you are in. The +full treatment is in +[Agents: enrolment, doctor and the intake ladder](../concepts/agents.md). + +## 3. `fleet secrets get ` — a secret, by name + +```sh +fleet secrets get tailscale.auth-key +``` + +(Any secret name your seat is entitled to works; `tailscale.auth-key` is the +name the bootstrap check phase uses.) + +This resolves the secret *by name*: the secrets broker first, Bitwarden +(`bws`) as fallback. The value goes to stdout and nowhere else — not to a +log, not to an error message. Resolution order and cache semantics are in +[Secrets and the secrets broker](../concepts/secrets.md); the short version +is that a broker cache hit answers immediately and carries the value's age, +and a miss on a loaded cache reads through to Bitwarden so a freshly minted +secret is visible at once. + +Exit codes: 0 ok, 2 usage (for example, no name, or more than one name), 3 +unresolved / broker unavailable and the fallback also failed. The companion +verb `fleet secrets list` prints the names in the broker's cache, one per +line, never values; unlike `get`, `list` has **no** `bws` fallback — a broker +failure is exit 3, because a vault listing is not the same thing as a cache +listing. + +## 4. `fleet queue health` — the queue + +```sh +fleet queue health +``` + +This asks the queue broker for its health table. The first output line is +`project: (resolved via )`; the table that follows carries +per-queue counts by task status, or `(no queues have tasks)` when empty. +Exit 0 means the broker answered. Exit 3 means the transport path to the +broker failed. Exit 6 is special: it is the *fallback switch* — the primary +queue store failed and this work has been switched to the GitHub fallback +queue; the output is one JSON object saying so, with a hint naming the +`fleet queue fallback …` verbs to continue with. See +[The queue: tasks, lanes and leases](../concepts/queue.md). + +Note that `queue health` (this verb, an authenticated broker call) is a +different thing from the broker's unauthenticated `GET /healthz` probe. + +## 5. `fleet agent next` — take work + +```sh +fleet agent next +``` + +`next` walks the *intake ladder* — four rungs, in order — and returns the +first piece of work it finds, as one JSON object +`{agent, rung, task, then, tried}`: + +1. **Push** — a command addressed to this agent on the bridge. Work a person + or central already chose outranks everything. +2. **Queue** — a claim on the fleet queue, taken with a 4-hour lease + (14,400 s — the queue's own default lease is 45 minutes, which lapses + mid-task). The `then` lines in the answer name the lease deadline and the + `queue checkpoint` / `queue complete` commands for the claimed task. +3. **Shortlist** — the top of this host's local shortlist, re-checked against + GitHub before hand-out. If the list is at or below its low-water mark + (default 3 entries) with nobody refilling it, `next` returns a `refill` + task instead of handing out a stale remnant. +4. **Priority** — the highest-priority open issue straight from GitHub, + reserved into the shortlist file as it is handed out so two seats on one + host do not take the same issue. + +`tried` is the per-rung log: each rung is recorded as `skipped`, `empty`, +`down`, or `rejected`, with a reason. A rung that is *down* is skipped, not +fatal — that is what doctor's rung map predicted. Exit codes: 0 when work +was handed out, 5 when no rung had work, 3 when a needed leg is down in a +way that leaves nothing to try, 2 for a usage error. + +That is the whole loop. An agent's working cycle is: `next`, do the task, +run the `then` lines (checkpoint as you go, complete at the end), and call +`next` again while the run has budget. diff --git a/pkgs/fleet/book/getting-started/shape.md b/pkgs/fleet/book/getting-started/shape.md new file mode 100644 index 0000000000..1e00ca053c --- /dev/null +++ b/pkgs/fleet/book/getting-started/shape.md @@ -0,0 +1,170 @@ +# The shape of the binary + +Fleet is a *multicall binary*: one executable whose behaviour is selected +first by the name it is invoked under (argv0, the zeroth argument — the name +the operating system was asked to run), and then by its first real argument. +This chapter describes that shape: the personalities, the domain registry, +the capability system, the build variants, and what happens when an +invocation asks for something it cannot do. + +## argv0 personalities and aliases + +There are three classes of invocation name: + +1. **`fleet`** — the full root dispatch: domains, plus the built-in commands. +2. **Variant names** — `fleet-serve` and `fleet-connect`. These select an + invocation *profile*: a capability ceiling. A profile can only narrow the + surface, never widen it. Invoking a serve build as `fleet` does not give + it client capabilities it was not compiled with; invoking a full build as + `fleet-connect` restricts it to the connect profile for that invocation. +3. **Alias names** — each routes straight into one domain, some with an + implied argument prepended: + +| argv0 | Routes to | Implied argument | +|---|---|---| +| `repo-queue` | domain `queue` | — | +| `queue-broker` | domain `serve` | `queue-broker` | +| `secrets-broker` | domain `serve` | `secrets-broker` | +| `laptop-agent-broker` | domain `proxy` | `serve` | +| `atlas-search` | domain `search` | — | +| `laptop-agent` | domain `laptop-agent` | — | + +An argv0 that is none of {`fleet`, a variant name, an alias} is a usage +error: the binary prints the expected names and exits 2. Aliases are how the +install works in practice — `~/tools/bin/repo-queue` is a symlink to the +fleet binary, not a second program (see +[Installation and bootstrap](installation.md)). + +Dispatch order, exactly: argv0 alias → domain route; argv0 variant name → +root dispatch with that profile as the ceiling; argv0 `fleet` → root +dispatch; then, for a domain, the capability checks below decide between the +domain handler and the stub; an unknown name is a usage error, exit 2. The +dispatch is hand-rolled — deliberately not a command-line parsing library — +so that it behaves identically in every variant, including the tiny connect +build where the registry and the stub machinery are the product. + +## The domain registry + +The registry is compiled into *every* build, including `fleet-connect`: every +build knows every domain's name, summary, aliases, and required capabilities, +whether or not it can run it. That is why `fleet --help` prints "the full +registry — every build knows every domain" on every variant, and why domain +help never stubs — help is registry data and renders identically everywhere, +with unavailable domains marked inline. + +The twelve domains, in registry (help) order, are `queue`, `serve`, `proxy`, +`dispatch`, `dispatch-test`, `secrets`, `gh`, `bridge`, `agent`, `shell`, +`search`, and `laptop-agent`. Their purposes are tabulated in the +[introduction](../index.md#the-domain-map). + +Each domain declares a *primary capability* — the capability its headline +availability keys on. One consequence worth knowing: on the serve build the +`search` domain is marked absent, because its primary capability is the +search *client*, even though the `search-serve` capability exists in that +build under the `serve` domain. + +## Capabilities: the 15 + +A *capability* is an atom of function that a build can include or omit. +There are 15, in registry order: + +``` +proxy-connect, proxy-serve, proxy-raw-splice, queue, queue-broker, +secrets-broker, search, search-serve, dispatch, dispatch-test, +laptop-agent, secrets, gh, bridge, agent +``` + +Notes: + +- `proxy-connect` is unconditional: it is compiled into every variant, and is + not even a Cargo feature. `proxy-raw-splice` joins it in the runtime's + always-present set. +- There is no `shell` capability atom: the `shell` domain rides on the + `agent` capability. +- A domain can require several capabilities. `serve` requires four + (`queue-broker`, `secrets-broker`, `search-serve`, `proxy-serve`) — one per + role — and the capability checked for a `serve` invocation is the one for + the role named. `proxy` requires three (`proxy-serve`, `proxy-connect`, + `proxy-raw-splice`), checked per verb. + +Three sets decide whether a domain runs for a given invocation: the +*compiled* set (from the build's Cargo features), the *profile* set (from a +variant invocation name, if any), and the host config's `[domains]` table, +which can disable a domain on one host. The *effective* set is the compiled +set intersected with the profile; the *usable* set further removes every +capability of every config-disabled domain. `fleet version` reports the +usable set; `fleet capabilities` reports both the usable set +(`capabilities`) and the compiled set (`compiled_capabilities`). + +## Build variants + +The variant is a property of the artifact. The same names double as the +invocation profiles above. + +| Variant | Installed name | Compiled capabilities | +|---|---|---| +| Full | `fleet` | all 15 | +| Serve | `fleet-serve` | `proxy-connect`, `proxy-serve`, `proxy-raw-splice`, `queue-broker`, `secrets-broker`, `search-serve`, `secrets` (7) — daemon roles plus proxy, no working-seat clients | +| Connect | `fleet-connect` | `proxy-connect`, `proxy-raw-splice` (2) | + +The profiles nest: connect ⊂ serve ⊂ full. The binary *reports* its variant +by matching its compiled capability set against the variant sets; an +unrecognised compiled set is reported as a custom build. + +Alongside the three variants, the Nix package set builds `fleet-brokers` — +the three standalone artifacts `repo-queue`, `queue-broker`, and +`secrets-broker` — and the two musl statics, `fleet-static` (full profile) +and `fleet-connect-static` (connect profile, size-gated at 2 MiB). See +[Installation and bootstrap](installation.md#nix-build-variants). + +## The stub and exit 69 + +A domain this invocation cannot use answers with a *stub*: a block on stderr, +always exit code **69** (`EX_UNAVAILABLE`). There are four wordings, one per +reason: + +1. **Not in build** — "this build does not include '<domain>'", followed by + the enabled capabilities and the build name, plus "The full build is + 'fleet'" when the build is not the full one. +2. **Narrowed by name** — invoked as `fleet-serve` or `fleet-connect`, the + name scoped the surface away: the stub says the invocation is name-scoped + to that profile, and that invoked as `fleet` it carries the full surface. +3. **Disabled by config** — the `[domains]` table in this host's fleet config + set the domain to `false`; the stub names the config file to re-enable it + in. This is the per-host shaping / incident lever: one host's fleet can + have a domain switched off without a rebuild. +4. **Available but not implemented** — the step-1 skeleton form: "included in + this build but not implemented yet", with wording from the multicall + epic's first step. (The wording is stale step-1 text; the form remains in + the source. Where this book's research found help text claiming a domain + "lands in a later step" for a domain that is in fact fully implemented — + `gh` and `laptop-agent` are the two cases — the source behaviour is what + this book documents.) + +Every stub's second line is `Enabled capabilities: ` (`none` +when empty), so a stub always tells you what the invocation *can* do. + +## Built-in commands overview + +Five root built-ins are handled before domain dispatch. They take no +arguments: a trailing argument is a usage error naming it, exit 2 — and that +includes `--help`, so `fleet version --help` is an error, not help. + +| Built-in | Behaviour | +|---|---| +| `init` | Autostart this host's roles per the `[host]` manifest; a no-op when they are already running. Byte-identical to `fleet proxy init` — one implementation, two spellings. With an unknown location it reports state, starts nothing, and exits 69: it never guess-starts a role. | +| `session bind` | Validate and persist an explicit or inherited session identity (an OpenCode session id, `ses_` followed by ASCII letters/digits). The identity is stored in a `.fleet-session-id` marker at the git worktree root, and is used only when the session is verified live. | +| `version` | Five lines: version, build, derived version, source rev, enabled capabilities. `fleet --version` / `-V` print only the first two lines. | +| `capabilities` | The registry and this build's capabilities as JSON (see the Quickstart for how to read it). | +| `help [domain]` | `fleet help` ≡ `fleet --help`: the full registry, exit 0. `fleet help ` prints one domain's help and rejects any second argument. An unknown name is a usage error, exit 2. | + +Bare `fleet` with no arguments is a missing-subcommand error: the message +and the full help go to stderr, exit 2. + +Two more root-level facts: every domain invocation first runs session +initialisation (the `session bind` machinery with no explicit id), and every +invocation — whatever its outcome — appends a payload-free record (invoked +as, arguments, exit code, elapsed milliseconds) to an invocation ledger; +failing to write the ledger never alters the result. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet/src/main.rs and https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-registry/src/lib.rs diff --git a/pkgs/fleet/book/index.md b/pkgs/fleet/book/index.md new file mode 100644 index 0000000000..a29d0fa265 --- /dev/null +++ b/pkgs/fleet/book/index.md @@ -0,0 +1,131 @@ +# fleet + +`fleet` is one multicall binary for the fleet's tools. A *multicall binary* is a +single executable that behaves as many different programs depending on the name +it is invoked under and the first argument it is given. The fleet binary is +version `0.1.0`. Invoked as `fleet`, it dispatches to one of twelve *domains* — +a domain is a named tool area, such as the work queue or the secrets resolver — +and invoked under one of its alias names (`repo-queue`, `queue-broker`, +`secrets-broker`, `laptop-agent-broker`, `atlas-search`, `laptop-agent`) it +routes straight into the corresponding domain. There is one binary to build, +one binary to install, and one binary to keep current on every machine the +fleet runs on. + +Source: https://github.com/developing-today/code/blob/main/pkgs/fleet/Cargo.toml + +## Why fleet exists + +Before fleet, each fleet tool was its own script or program, installed its own +way, and each one re-solved the same four problems. Fleet solves them once, +inside one binary: + +1. **A shared work queue.** Agents on different machines need one place where + work is filed, claimed by exactly one worker at a time under a *lease* (a + time-limited claim that expires if the holder stops reporting in), and + completed with evidence. The queue domain and its resident queue broker + provide that queue, backed by a dedicated Turso database. See + [The queue: tasks, lanes and leases](concepts/queue.md). +2. **Secrets without vault sprawl.** Resolving a secret by shelling out to the + Bitwarden Secrets Manager command-line tool (`bws`) on every call cost + 10–40 seconds per invocation. Fleet instead runs a *secrets broker*: a + resident cache of the vault that answers by name in milliseconds, refreshes + itself on a timer, and falls back to `bws` only when it must. Callers name a + secret; they never hold a vault credential of their own. See + [Secrets and the secrets broker](concepts/secrets.md). +3. **Remote build placement.** A limited sandbox is the wrong place to compile. + Fleet decides, from live capacity data, which GitHub Actions copy of the + fleet repositories should run a build — a personal copy, an organisation + copy, a forks copy, a Blacksmith runner, or a codespace — and dispatches the + job there. See [Placement and remote dispatch](concepts/placement.md). +4. **Agent coordination.** Agents need a mailbox, a way to prove what their + seat can reach, and one rule for what work to take next. The bridge domain + provides the mailbox, the agent domain provides enrolment, a four-leg + health check called *doctor*, and the *intake ladder* that decides what an + agent works on next. See [The bridge: fleet messaging](concepts/bridge.md) + and [Agents: enrolment, doctor and the intake ladder](concepts/agents.md). + +## Who it serves + +- **Agents on seats.** A *seat* is one running agent instance in one place: a + Muse session in a sandbox, an OpenCode session on the laptop, a chat + assistant connected over HTTPS. An agent uses fleet to enrol, check its + seat, take work, resolve secrets, message other agents, and run builds where + builds belong. +- **Operators.** A human (or a supervising agent) running the fleet uses fleet + to inspect queue health, read the message log, check which token sources + still have GitHub rate-limit headroom, and run the daemon roles in the + foreground under a supervisor. +- **Developers.** A developer changing fleet itself uses the same binary's + registry and capability output to see exactly what a given build contains, + and uses the Nix build variants described in + [Installation and bootstrap](getting-started/installation.md). + +## The domain map + +Every build of fleet knows every domain. Whether a given invocation can *use* +a domain depends on the capabilities compiled into that build, on the name it +was invoked under, and on the host's configuration; a domain it cannot use +answers with a stub message and exit code 69. The full mechanics are in +[The shape of the binary](getting-started/shape.md). + +| Domain | Purpose | +|---|---| +| `queue` | The repo work queue: enqueue, claim, and complete tasks through the queue broker. Alias: `repo-queue`. | +| `serve` | Run a fleet daemon role (queue-broker, secrets-broker, search, proxy) in the foreground. Aliases: `queue-broker`, `secrets-broker`. | +| `proxy` | The session proxy: serve the broker socket, connect or init through it, run recovery SSH, splice raw TCP streams, or transfer files (`get`/`put`). Alias: `laptop-agent-broker`. | +| `dispatch` | Thin client over pm-stack dispatch: status, launch, and enqueue verbs. | +| `dispatch-test` | Explicit-dispatch CI test: scan fleet repos for free Actions capacity, submit a job, track its stored status. | +| `secrets` | Resolve secrets by name: the secrets broker first, Bitwarden as fallback. | +| `gh` | The real `gh` CLI, passed through under a rotating fleet token (personal, then the fleet's GitHub Apps); rate-limit and permission failures fail over to the next token. | +| `bridge` | Fleet messaging through the message bridge: central sends messages or commands to an agent, a group, or all; agents read their mailbox, answer, and ack. | +| `agent` | The agent's front door: enrol an agent of any kind, check what this seat reaches, and take the next piece of work down the intake ladder. | +| `shell` | Run a command, or open a shell, where builds belong: the laptop, a codespace, or here. | +| `search` | Atlas corpus search over the session history (hybrid full-text plus vector search). Alias: `atlas-search`. | +| `laptop-agent` | Client for the laptop-agent daemon: run and manage jobs on the laptop. Alias: `laptop-agent`. | + +Alongside the domains there are five built-in commands that are not domains: +`init` (autostart this host's roles per the host manifest), `session bind` +(validate and persist a session identity), `version`, `capabilities`, and +`help`. + +## How to read this book + +- **New seat, first hour:** [Installation and bootstrap](getting-started/installation.md), + then [Quickstart](getting-started/quickstart.md). You will have a working + binary and will have run the five commands that prove the seat works. +- **Agent or operator who wants to understand the system:** + [The shape of the binary](getting-started/shape.md), then + [Architecture](concepts/architecture.md), then the concept chapter for the + domain you are working in. +- **Someone debugging a specific behaviour:** go straight to that domain's + concept chapter. Every concept chapter is self-contained: it defines its + terms, states its defaults and exit codes, and does not require reading the + others first. +- **Someone changing fleet:** the concept chapters state the behaviour your + change must preserve; the development part of this book covers how changes + are built, tested, and shipped. + +## Conventions used in this book + +- **Commands** are shown as they are typed, for example `fleet agent doctor`. + Inside the queue domain, the binary's own usage strings spell the program + `repo-queue` (the argv0 alias), so queue examples may show either + `fleet queue claim` or `repo-queue claim`; they are the same code path. +- **Flags and defaults.** When a flag has a default, the default is stated as a + number or a literal value, for example "lease default 2700 s (45 minutes)". + Where the help text and the source disagree, this book states the *source* + behaviour and says so. +- **Exit codes.** Fleet uses a small shared vocabulary: 0 success, 2 usage + error, 3 transport down / unresolved / a needed leg down, 69 capability + unavailable (the stub). Individual domains add codes — 1, 4, 5, 6 appear in + the queue, bridge, agent, and dispatch chapters — and each chapter lists its + own codes in full. +- **Secrets are named, never valued.** This book gives secret *names* (for + example `fleet.secrets-broker-token`) and token *file paths*. It never + prints a secret value, and neither does the binary: values go to the one + place each command defines (standard output for `fleet secrets get`, a + single header for an authenticated request) and nowhere else. +- **Source references** are provenance only. Each chapter names the source + files it was written from, as absolute URLs under + https://github.com/developing-today/code/blob/main/pkgs/fleet/. The chapter + text itself is complete without following them. diff --git a/pkgs/fleet/book/library/crates.md b/pkgs/fleet/book/library/crates.md new file mode 100644 index 0000000000..2c6b4bfba5 --- /dev/null +++ b/pkgs/fleet/book/library/crates.md @@ -0,0 +1,252 @@ +# The crates + +The fleet binary is one Rust workspace, `pkgs/fleet/`, with 13 crates: +12 library crates and the one binary crate that assembles them. The +workspace is self-contained — its own `Cargo.toml`, `Cargo.lock` and +`rust-toolchain.toml`, no workspace relationship to the repository root +— at version `0.1.0`, edition 2024, rust-version 1.85, licensed +`MIT OR Apache-2.0`. Shared externals are pinned once at the workspace +level (`serde 1` with derive, `serde_json 1`, `sha2 0.11`, `toml 1.2`); +the fleet crates depend on each other by path only. The release profile +is a size contract, not a speed profile: `opt-level = "z"`, `lto = +true`, `codegen-units = 1`, `strip = true`, sized for the connect +variant's budget (target ≤ 1.5 MiB, hard ≤ 2 MiB, stripped). + +This chapter names every crate by its exact package name, gives its +purpose in the crate's own words (the `description` line of its +`Cargo.toml`, quoted verbatim), and maps which crate owns which domain. +The chapters after this one go deep on the three library surfaces an +embedder touches most: [The queue client](queue-client.md), +[Placement and surfaces as data](placement.md), and +[Registry, config and capabilities](registry-and-config.md). + +## The 13 crates + +### `fleet` + +> "One multicall binary for the fleet's tools: search, queue, dispatch, proxy — with compile-time capability-selected variants (epic developing-today/code#5412)." + +The bin crate: `[[bin]] name = "fleet"`, and **no `lib.rs`**. Its +`src/main.rs` is the multicall entrypoint — argv0 routing, the +capability surface, the stub machinery, root built-ins — and it also +carries two domains as bin-crate modules rather than library crates: +`secrets` (the `fleet secrets` verbs, over `fleet-secrets`) and `gh` +(the `fleet gh` passthrough, with its `gh_cache`, `gh_closure`, +`gh_guard` and `gh_metadata` modules). Unconditional modules include +`invocation_ledger`, `session_state` and `derived_version` (the last +also included by path from `build.rs`, which bakes the source revision +and the derived version into the binary). + +### `fleet-agent` + +> "The fleet agent domain: one front door for any agent. Enrol a named agent of any kind, check what this seat can reach, ask for the next piece of work down the intake ladder (pushed command, queue claim, local shortlist, highest priority), and open a shell where builds belong." + +Owns the `agent` domain (`kinds`, `enroll`, `doctor`, `next`, +`shortlist`) and the `shell` domain (`run_shell` entry): one crate, two +registry domains, both riding the single `agent` capability. It links +only `fleet-config` among the fleet crates: it runs the other domains' +verbs through the same binary rather than linking their crates. + +### `fleet-bridge` + +> "The fleet bridge domain: send and receive through the message bridge's fleet mailboxes — central commands one agent, a group or all; agents read, answer and ack." + +Owns the `bridge` domain. Essentially a single `src/lib.rs` plus its +tests: the mailbox client for the bridge service, with the two token +classes (owner token for central verbs, fleet token for agent verbs) +resolved by name through `fleet-secrets`. + +### `fleet-config` + +> "fleet configuration: ~/.config/fleet/fleet.toml + env resolution, the [domains] enable/disable table, and state-dir paths." + +A platform crate, not a domain: the one place configuration resolves. +Environment overrides, then the config file +(`${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml` unless `$FLEET_CONFIG` +names another), then compiled-in defaults. A missing file is not an +error; a malformed file — including unknown sections or keys — is a loud +error on every path, never a silent fallback. It also owns the fleet's +path, port and socket constants. Covered in depth in +[Registry, config and capabilities](registry-and-config.md). + +### `fleet-dispatch` + +> "The fleet dispatch domain: a thin client over pm-stack's pm-dispatch service — status, launch, and enqueue verbs (epic developing-today/code#5412, step 4 #5432)." + +Owns the `dispatch` domain: a single-file client over pm-dispatch's +existing HTTP routes — exactly three (`GET /health`, +`POST /v1/sessions`, `POST /v1/tasks`). pm-stack itself is a working +TypeScript/Bun service suite that is deliberately not rewritten; per-task +status is not here, because that state is the repo queue itself. + +### `fleet-dispatch-test` + +> "The fleet dispatch-test domain: explicit-dispatch CI test — scan fleet repos for free GitHub Actions capacity, submit a job to the Turso-backed jobs store, dispatch the pilot workflow, and track the job's stored status." + +Owns the `dispatch-test` domain (`scan`, `submit`, `status`). Nothing in +it is trigger-driven: every verb runs only when a caller invokes it, and +`submit` dispatches a `workflow_dispatch` run explicitly. + +### `fleet-laptop-agent` + +> "The fleet laptop-agent domain: the transport ladder (broker, Cloudflare, Tailscale, SSH) and the verbs over the laptop-agent daemon (epic developing-today/code#5412, issue #10796)." + +Owns the `laptop-agent` domain (`health`, `jobs`, `kill`, `exec`, +`run`, `poll`, `fetch`): the client for the laptop-agent daemon on port +4799, with a four-leg transport ladder — broker, Cloudflare, Tailscale, +and an SSH leg that exists in the ordering as a stub and never carries +traffic in this build. + +### `fleet-proxy` + +> "The fleet session proxy domain: `proxy serve` (the broker) and `proxy connect`/`init` (the client) — design note §4, epic developing-today/code#5412." + +Owns the `proxy` domain: the session broker (`proxy serve`), the client +verbs (`connect`, `init`, `ssh`, `splice`, `get`, `put`), warm tunnel +pools to the laptop's services, and file transfer over the agent +channel. The crate is a non-optional dependency of the bin crate with +its own features split: the client is in every variant; only the broker +half (`serve`) is feature-gated. It also carries two extra binaries +(`fleet-connect-udp`, `fleet-udp-forward`). + +### `fleet-proxy-proto` + +> "The fleet proxy wire contract: length-prefixed JSON framing plus the hello/capability frame types. The contract lives here and nowhere else." + +A platform crate: the session-broker wire protocol and nothing else — +8-byte big-endian length-prefixed JSON frames, the hello/capability +handshake, and the major-version window (N / N−1, plus the legacy proto +0 dialect). (The design note's "4-byte" framing was a census error; the +live wire is 8-byte, and the crate README records the erratum.) + +### `fleet-queue` + +> "The fleet queue domain: the repo-queue client surface plus the queue-broker and secrets-broker server roles (epic developing-today/code#5412, step 2 #5430)." + +By far the largest crate, and the owner of three registry surfaces at +once: the `queue` domain (the client, including the GitHub fallback +queue and the placement module), and — under the `serve` domain — the +`queue-broker` and `secrets-broker` roles. It also builds three +standalone binaries from `src/bin/` (`repo-queue`, `queue-broker`, +`secrets-broker`), the migration's rollback inventory: they retire only +at the epic's close, not before. Its internal split — client surface, +broker surface, and the feature gates between them — is the subject of +[The queue client](queue-client.md) and +[Placement and surfaces as data](placement.md). + +### `fleet-registry` + +> "The full fleet domain registry: names, one-line descriptions, argv0 aliases, capabilities and variant profiles. Std-only; compiled into every fleet variant." + +A platform crate with a hard constraint: **dependency-free** (std only, +strings and tables, no I/O), so it can be compiled into *every* variant +— including the size-gated connect build — and `--help` is always +complete. It owns the 15 capability atoms, the 12 domains, the three +build variants and the argv0 alias map. Covered in depth in +[Registry, config and capabilities](registry-and-config.md). + +### `fleet-search` + +> "The fleet search domain: the atlas-search client surface over the live Atlas service (job protocol), with the Q3 host defaults — via-service with loud standalone fallback on the sandbox seat, standalone on the laptop seat (epic developing-today/code#5412, step 5 #5433) — and the `serve search` role, the Atlas service itself rehomed from the atlas-search bin crate (#5604)." + +Owns the `search` domain (the Atlas client) and the `search` serve role +(the Atlas service itself, behind the crate's `serve` feature). It is +the one workspace member that consumes crates **outside** the workspace: +`atlas-core` / `atlas-embed` / `atlas-proto` by relative path from +`pkgs/atlas-search`. The serve role's engine is a verbatim copy of +atlas-search's service, held byte-for-byte by a parity-guard workflow. + +### `fleet-secrets` + +> "The one secrets-by-name path for fleet: secrets-broker protocol first, bws CLI fallback. Values are never stored, never logged, and redacted in Debug." + +A platform crate, not a domain: the resolver every domain uses to turn a +secret *name* into a value. The resolution chain is broker first (direct +socket where the broker is local, framed through the session broker +elsewhere), then the `bws` CLI fallback, then a 1Password source where a +vault is named. Resolved values live in a type whose `Debug` is +redacted; chain errors count failed sources without ever carrying a +value. + +## Dependency shape + +Three rules describe the whole graph: + +1. **`fleet-registry` depends on nothing** — not even on the workspace's + shared externals. That is what lets every variant, however small, + know every domain name, summary, alias and required capability, + whether or not it can run it. +2. **Platform crates sit at the bottom**: `fleet-registry`, + `fleet-config`, `fleet-secrets` and `fleet-proxy-proto` own the + contracts (registry, configuration, secret resolution, wire framing) + that domain crates consume. Domain crates do not shell out around + them — no domain resolves its own config file, fetches its own + Bitwarden secret, or invents its own framing. +3. **The bin crate assembles.** `crates/fleet` wires the domain crates + behind Cargo features, reconstructs its compiled capability set from + those features at runtime (see + [Registry, config and capabilities](registry-and-config.md)), and + routes argv0 → domain → capability check → handler or stub. Domain + crates generally do not depend on each other; where one domain needs + another's verbs (`fleet-agent` running queue or bridge verbs), it + goes through the assembled binary, not a crate edge. + +Feature wiring mirrors the capability set one level down. On the bin +crate, for example, `queue = ["dep:fleet-secrets", "dep:fleet-queue", +"fleet-queue/client"]` and `queue-broker = ["dep:fleet-secrets", +"dep:fleet-queue", "fleet-queue/queue-broker"]`: enabling a capability +enables exactly the matching feature surface of the owning crate. +`proxy-connect` is not a feature at all — it is compiled into every +variant unconditionally. + +## Which crate owns which domain + +| Registry domain | Primary capability | Owning crate | Entry point | +|---|---|---|---| +| `queue` | `queue` | `fleet-queue` | `fleet_queue::client::run` | +| `serve` (roles `queue-broker`, `secrets-broker`) | `queue-broker` | `fleet-queue` (bin-crate glue routes the roles) | `fleet_queue::queue_broker::run`, `fleet_queue::secrets_broker::run` | +| `serve` (role `search`) | `search-serve` | `fleet-search` | `fleet_search::serve::run` | +| `serve` (role `proxy`) | `proxy-serve` | `fleet-proxy` | the proxy serve loop, via bin-crate glue | +| `proxy` | `proxy-connect` | `fleet-proxy` (+ `fleet-proxy-proto`) | bin-crate glue over `fleet-proxy` client/serve | +| `dispatch` | `dispatch` | `fleet-dispatch` | `fleet_dispatch::run` | +| `dispatch-test` | `dispatch-test` | `fleet-dispatch-test` | `fleet_dispatch_test::run` | +| `secrets` | `secrets` | bin crate, over `fleet-secrets` | `crates/fleet/src/secrets.rs` | +| `gh` | `gh` | bin crate | `crates/fleet/src/gh.rs` and siblings | +| `bridge` | `bridge` | `fleet-bridge` | `fleet_bridge::run` | +| `agent` | `agent` | `fleet-agent` | `fleet_agent::run` | +| `shell` | `agent` | `fleet-agent` | `fleet_agent::run_shell` | +| `search` | `search` | `fleet-search` | `fleet_search::run` | +| `laptop-agent` | `laptop-agent` | `fleet-laptop-agent` | `fleet_laptop_agent::cli::run` | + +Note the two irregular rows, because embedders trip on both: `shell` +has **no capability atom of its own** — it rides the `agent` capability +— and `secrets` and `gh` are domains without library crates, living as +modules in the bin crate (over `fleet-secrets`, in the `secrets` case). + +## Example: depending on the platform layer + +The smallest useful embedding is the dependency-free registry: any +crate, tool or test can ask what the fleet's surface *is* without +linking a single domain. This example is illustrative — it follows the +researched API (`fleet_registry::DOMAINS`, `fleet_registry::domain`) +but the exact return type of the lookup helper was not verified against +the source signature in this pass. + +```toml +# Cargo.toml +[dependencies] +fleet-registry = { path = "../fleet-registry" } +``` + +```rust +// Print the registered summary for the queue domain, if it exists. +fn main() { + for d in fleet_registry::DOMAINS { + println!("{} — {}", d.name, d.summary); + } + // fleet_registry::domain(name: &str) -> Option<&'static Domain> + if let Some(d) = fleet_registry::domain("queue") { + println!("queue aliases: {:?}", d.aliases); + } +} +``` diff --git a/pkgs/fleet/book/library/placement.md b/pkgs/fleet/book/library/placement.md new file mode 100644 index 0000000000..89f4b8ed26 --- /dev/null +++ b/pkgs/fleet/book/library/placement.md @@ -0,0 +1,358 @@ +# Placement and surfaces as data + +Placement — deciding *where* a build job runs — is data, not code. The +surface registry is a JSON file; adding a location is adding an entry; +no surface is hardcoded in the engine. This chapter documents that file +field by field, how the registry is resolved and extended, the decision +types the engine works with, the local session store format, and how +another crate uses placement. + +The live engine is Rust: the `placement` module of `fleet-queue` +(gated behind the crate's `client` feature), exposed as the +`fleet queue dispatch`, `fleet queue session` and `fleet queue surfaces` +verbs. It is the absorption of the `fleet-place` reference implementation +into the queue client. The operator's walkthrough is +[Tutorial: dispatch a build remotely](../tutorials/dispatch-a-build.md). + +> Do not confuse this engine with `pkgs/fleet/placement/`. That +> directory is a different, unrelated Go proof-of-concept (a +> placement-*record* package for a policy framework) that is +> deliberately not wired into the live queue client or any dispatcher. +> Two placement systems share one name; only the Rust module over +> `fleet-surfaces.json` dispatches anything. + +## The surface registry: `fleet-surfaces.json` + +The registry lives at `pkgs/fleet/fleet-surfaces.json` and is **compiled +into the binary** (`include_str!`). Resolution at runtime, in order: + +1. An explicit override — the `--registry PATH` flag or the + `FLEET_PLACE_REGISTRY` environment variable — is **strict**: a bad + path is a fatal error, never a silent fallback. The file must parse + as JSON and contain a `surfaces` array, or the error is + `registry {path} has no surfaces array`. +2. Without an override, `$HOME/git/code/pkgs/fleet/fleet-surfaces.json` + wins if it exists (a live checkout can carry a newer registry). +3. Then the cwd-relative `pkgs/fleet/fleet-surfaces.json`, if it exists. +4. Finally, the embedded copy. + +Top-level shape: + +```json +{ + "comment": "Fleet placement registry. …", + "version": 2, + "laptop": { "busy": false, "busy_source": "manual-flag", "note": "…" }, + "owners": { "": { "…": "…" } }, + "surfaces": [ { "…": "…" } ] +} +``` + +- `comment`: human documentation of the format; never read by code. +- `version`: `2` in the shipped registry. +- `laptop.busy` (bool), `laptop.busy_source` (string, shipped value + `"manual-flag"`), `laptop.note` (string): the saturation signal for + the codespace tier. It is set from queue depth where a caller can read + it, else flipped by hand or overridden per-dispatch with + `--laptop-busy`. Deliberately not scraped telemetry. +- `owners`: per-owner caps, below. +- `surfaces`: the surface entries, below. `fleet queue surfaces` prints + the resolved registry verbatim as pretty JSON — that output *is* this + file, which is the quickest way to read the registry a given binary + will use. + +### Every field of a surface entry + +The union of fields across the shipped entries, with the code that +consumes each: + +| Field | Type | Consumed by / meaning | +|---|---|---| +| `id` | string | Surface identity: the `--surface ID` pin, the session record's `surface`, and the sort tie-break | +| `kind` | string | Adapter selector: `github-actions`, `blacksmith`, `codespace` or `laptop`. Any other value gets **no adapter** — the surface is invisible to the cascade and cannot be pinned either | +| `status` | string | Eligibility requires exactly `"active"` for `github-actions`/`blacksmith` surfaces. Shipped values: `active`, `standby` (`org-run`), `pending-scope` (`codespace-overflow`), `handoff-only` (`laptop`). The codespace and laptop adapters do not apply this check | +| `owner` | string | The account whose cap, load and budget the surface draws on; load is aggregated per owner, not per surface | +| `repo` | string or null | The *runner-host* repo the workflow is dispatched in (not the target repo). `null` for `codespace-overflow` and `laptop`. Used for token minting, load counting, run correlation, and the session record's `runner_repo` / `portable_id` | +| `workflow` | string or null | The workflow file dispatched; `"fleet-command.yml"` for all Actions/Blacksmith surfaces, `null` for codespace/laptop | +| `targets` | string array | Target-repo patterns: exact `owner/repo`, `owner/*`, or `*` (see matching rules below) | +| `notes` | string | Human documentation only; never read by code | +| `app_installation` | integer or null | GitHub App installation id for that host repo. Documentation/record only in the Rust code — nothing in the engine reads it; token minting goes through a separate helper | +| `dispatch_as` | string, optional | `"user"` dispatches with the signed-in user's token; absent or `"app"` uses an App installation token. Any other value fails eligibility | +| `dispatch_id_input` | bool | The workflow declares a `dispatch_id` input. When true, dispatch mints a fresh `fp_…` handle (separate from the session handle) and sends it as that input; the workflow puts it in the run title, enabling exact run correlation. When absent/false, correlation falls back to pre-dispatch snapshot exclusion | +| `platform_input` | bool | The workflow declares a `platform` input. Gates macOS: a `platform=macos` job is ineligible on a surface where this is not `true` | +| `previous_run_id_input` | bool | The workflow accepts `previous_run_id` / `previous_run_repo` inputs (follow-up output download) | +| `container_input` | bool | The workflow accepts `container_image`; a `--container` value is only sent when this is `true` | +| `sticky_queue_threshold` | integer | Follow-up stickiness threshold. Code default if absent: `2`, clamped to at least 1. All shipped surfaces: `2` | +| `selection_priority` | integer | Tier-1 sort key (third position). Code default if absent: `50`. Shipped: `10` everywhere except `org-run` at `20`. Lower sorts first | +| `public_targets_only` | bool, optional | Only `fleet-forks` (`true`). Eligibility does a live `GET /repos/{target}` and requires `"private": false` | +| `host_surface` | string, optional | Only `fleet-org-blacksmith` (`"fleet-org"`): records which github-actions surface hosts this Blacksmith variant. Documentation-level linkage; the Blacksmith adapter dispatches its own surface's repo/workflow directly | +| `budget` | object, optional | Blacksmith: `{free_minutes_monthly, paid_cap_minutes, rate_note}`. Codespace: `{core_hours_monthly, note}` | +| `max_live` | integer, optional | Only `codespace-overflow` (`3`). Printed in the capacity summary only; **never enforced** | + +### The seven shipped surfaces + +| `id` | `kind` | `status` | Owner / host repo | `dispatch_as` | Notable | +|---|---|---|---|---|---| +| `fleet-personal` | github-actions | active | dezren39 / dezren39/fleet | (app) | Its repo secrets include `GHCR_ORG_PAT` and `NIX_CACHE_*` (names only) for private checkouts, cross-run artifacts and Nix cache pushes | +| `fleet-org` | github-actions | active | developing-today / developing-today/fleet | user | Canonical org runner; also the Blacksmith host | +| `fleet-forks` | github-actions | active | developing-today-forks / developing-today-forks/fleet | user | `public_targets_only: true` — private targets are rejected because this host has no `GHCR_ORG_PAT` secret | +| `org-run` | github-actions | standby | developing-today / developing-today/code | (app) | `platform_input`, `previous_run_id_input`, `container_input` all false; priority 20. Because eligibility requires `"active"`, it can never be selected or pinned — retained for manual workflow use | +| `fleet-org-blacksmith` | blacksmith | active | developing-today / developing-today/fleet | user | `host_surface: fleet-org`; budget below | +| `codespace-overflow` | codespace | pending-scope | dezren39 / no repo | — | Budget 180 core-hours/month; `max_live: 3`; never creates codespaces | +| `laptop` | laptop | handoff-only | dezren39 / no repo | — | Targets `["*"]`; a placement record only — this adapter never runs shell commands on the laptop | + +All Actions/Blacksmith surfaces target +`["dezren39/*", "developing-today/*", "developing-today-forks/*"]` except +`org-run`, which targets only `["developing-today/*"]`. + +### Per-owner caps + +From the shipped `owners` object: + +| Owner | `concurrent_jobs_cap` | `concurrent_macos_cap` | `plan` | `private_minutes_monthly` | +|---|---|---|---|---| +| `developing-today` | 20 | 5 | `free-org` | 2000 | +| `developing-today-forks` | 20 | 5 | `free-org (assumed - confirm)` | 2000 | +| `dezren39` | 40 | 5 | `pro` | 3000 | + +Only `concurrent_jobs_cap` is read as the cap: an owner missing from +`owners`, or a missing field, yields cap **0** — zero free slots, so the +surface is unusable in Tier 1. `plan` and `private_minutes_monthly` are +never read by the placement code; they are registry documentation. +For a macOS job the effective cap is +`min(concurrent_jobs_cap, concurrent_macos_cap)` — 5 for every shipped +owner — and the adapter deliberately counts *all* of the owner's active +host runs against that minimum, so macOS headroom is +`max(0, 5 − (running + queued on that owner's hosts))`. + +### Target matching + +A repo string is valid (`valid_owner_repo`) when it has exactly one `/`, +both parts non-empty and not `.`/`..`, with characters +`[A-Za-z0-9._-]` only; a `--repo` failing this is a fatal usage error +(exit `2`). A pattern matches a repo when: `"*"` matches any valid +`owner/name`; `"owner/*"` matches when the owner is exactly equal and +the name is a single non-empty segment; anything else is exact string +equality. A surface targets a job iff any of its `targets` matches the +job's repo. + +### Budgets that are, and are not, enforced + +Blacksmith's registry budget is real: `free_minutes_monthly: 3000`, +`paid_cap_minutes: 0`, with a `rate_note` recording that Blacksmith is +orgs-only, free for 3,000 minutes a month, then paid per minute — and +that `paid_cap_minutes` is the knob to raise. Eligibility computes +`remaining = free + paid_cap + this job's --allow-paid-blacksmith − +used`, where `used` is reconciled from the local store's ledger of +Blacksmith dispatch durations for the current UTC month. The +`--allow-paid-blacksmith MINUTES` value (a float, default `0.0`) is an +eligibility allowance for this one decision only — not a per-run +spending cap, not a workflow input, not persisted. + +By contrast, the codespace budget numbers (`core_hours_monthly: 180`, +`max_live: 3`) appear only in a capacity *summary string*. Neither is +measured or enforced anywhere; dispatch does not count live codespaces. + +## Reading and extending the registry + +Read the registry the way the binary does: + +```bash +fleet queue surfaces +``` + +That prints the resolved registry as pretty JSON (a `--registry PATH` +flag reads a different file). To extend placement: + +1. Add a surface entry to `fleet-surfaces.json` with a unique `id`, a + `kind` that has an adapter, the `owner` whose caps it draws on (add + the owner to `owners` first if it is new — a missing owner means cap + 0), its host `repo` and `workflow`, and its `targets`. +2. Add a compatible workflow to the host repo: the entry's capability + flags (`dispatch_id_input`, `platform_input`, + `previous_run_id_input`, `container_input`) are promises about that + workflow's declared inputs. Declaring a flag the workflow does not + implement sends inputs into the void; omitting one the workflow + supports disables the feature silently. +3. Set `status: "active"` only when the surface should really be picked. + `standby` is a supported, deliberate state: registered, documented, + and unpickable. + +No code change is needed for a new surface of an existing `kind`. A new +`kind` is a code change: one adapter implementing the trait below. + +## Placement decision types + +The engine's vocabulary, as researched from the module: + +- **The job**: `{repo, command, ref, runner, platform, container, + surface_pin, preferred_surface, previous_run_id, previous_run_repo, + push_nix_cache, actions_cache, actions_cache_restore_keys, + allow_paid_blacksmith}` — exactly the fields a session record stores + under `job` (below). `runner` is `auto | github | blacksmith`; + `platform` is `linux | macos`. A job pinning `runner=blacksmith` + makes every github-actions adapter ineligible, and vice versa for + `runner=github`. +- **The adapter trait**: each registry `kind` is served by one adapter + implementing `eligible(job, ctx, gh) -> (bool, reason)`, + `capacity(job, ctx) -> {summary, free_slots, remaining_total_minutes}`, + `dispatch(job, gh) -> DispatchResult`, and `status(session, gh)` + (defaulting to the stored state). `free_slots` and + `remaining_total_minutes` are both optional in a capacity report: a + summary-only adapter (codespace) reports neither. +- **`DispatchResult`**: `{run_id, run_url, note, codespace, + terminal_state}` — what a dispatch attempt hands back to be recorded + as a session. +- **The decision**: `decide(registry, job, ctx, gh)` returns the chosen + adapter (or none, for the all-tiers-exhausted case) together with the + `reasoning` array — one human string per skip, candidate and pick, + which is part of the dispatch verb's output, not a debug log. +- **The context (`ctx`)**: built per decision from the GitHub API and + the local store — per-owner load `(running, queued)` counted only over + that owner's fleet runner-host repos (two `total_count` reads per host + repo, `in_progress` and `queued`; failures are soft and recorded in + `load_read_errors`), per-owner and per-surface last-dispatch epochs + from the session store, the month's Blacksmith minutes used, and the + laptop-busy flag (`--laptop-busy` or the registry's `laptop.busy`). + +The cascade itself — hard pin, follow-up affinity (kept only while the +preferred surface is eligible, has capacity, and its owner's queued +count is strictly below its `sticky_queue_threshold`), Tier 1 free +Actions sorted by `(load, owner_last_dispatch, selection_priority, +surface_last_dispatch, surface_id)`, Tier 2 Blacksmith in registry +order, Tier 3 Codespaces, then exhaustion — is walked step by step in +[Tutorial: dispatch a build remotely](../tutorials/dispatch-a-build.md). + +## The session store format + +Placement sessions are a labelled **stopgap**: a local JSON store at +`$FLEET_PLACE_STATE/sessions.json`, defaulting to +`~/.local/state/fleet-place/sessions.json` — the same path and record +shape the reference implementation used, so records migrate rather than +being redesigned when the designed backend table lands. + +Store shape: + +```json +{ + "sessions": { "": { "…": "…" } }, + "blacksmith_dispatches": [ { "…": "…" } ] +} +``` + +A missing or unparseable store loads as +`{"sessions": {}, "blacksmith_dispatches": []}`. Writes are +pretty-printed JSON with recursively sorted keys, written to a +per-process temp file and renamed over the store, under a lock +directory (`sessions.lockdir` beside the store; waiters poll every +50 ms up to a 15-second deadline; a lock older than 120 seconds is +stale and is broken). New sessions are committed under the lock by +re-loading the on-disk store and merging, so concurrent processes do +not drop each other's records. + +A session record (dispatched case): + +```json +{ + "handle": "fp_…", + "job": { "repo": "…", "command": "…", "ref": "…", "runner": "…", + "platform": "…", "container": "…", "surface_pin": "…", + "preferred_surface": "…", "previous_run_id": "…", + "previous_run_repo": "…", "push_nix_cache": false, + "actions_cache": "…", "actions_cache_restore_keys": [], + "allow_paid_blacksmith": 0.0 }, + "surface": "fleet-org", + "surface_kind": "github-actions", + "runner_repo": "developing-today/fleet", + "portable_id": "developing-today/fleet#45146933211", + "decision_reasoning": ["…"], + "run_id": 45146933211, + "run_url": "https://github.com/developing-today/fleet/actions/runs/45146933211", + "state": "queued|dispatched|running|succeeded|failed|cancelled", + "submitted_by": "@", + "actor": "developing-today[bot] (GitHub App dispatch)", + "created_at": "YYYY-MM-DDTHH:MM:SSZ", + "updated_at": "YYYY-MM-DDTHH:MM:SSZ", + "note": "…", + "codespace": "…" +} +``` + +Field notes an embedder must know: + +- `handle` is `fp_` plus 16 random bytes from `/dev/urandom`, + hex-encoded — 35 characters total, 128 bits. +- `surface_kind` is omitted in the all-tiers-exhausted record, which has + `surface` / `run_id` / `run_url` null, `state: "queued"`, and no + `runner_repo` / `portable_id`. `runner_repo` appears only when the + surface has a repo; `portable_id` only when a run id is known; + `note` only when the adapter supplied one; `codespace` only on + codespace dispatches. +- Initial state: the adapter's `terminal_state` if set (codespace + dispatches are created already-terminal), else `queued` if a run was + correlated, else `dispatched`. +- `actor` is hardcoded to the App string even for `dispatch_as: "user"` + surfaces — a known inaccuracy in the record for the majority of + shipped surfaces. Do not build attribution on it. +- `blacksmith_dispatches` entries are `{handle, month, minutes, + run_id, note, reconciled}`: appended with `minutes: 0.0` at dispatch, + then reconciled to the run's real duration (rounded to 2 dp) when the + session reaches a terminal state, or before the next real dispatch + decision. +- Refresh: `session status` / `session result` (and follow-up + resolution, and Blacksmith reconciliation) re-read the GitHub run and + update `state` + `updated_at` on change. `session list` does **not** + refresh — it prints stored state as-is. A portable reference + `OWNER/REPO#RUN_ID` bypasses the store entirely and resolves live, as + described in the tutorial. + +## Using placement from another crate + +Placement is a module of `fleet-queue` behind the `client` feature, and +its researched public surface is the verb entry points the queue client +dispatches to: `cmd_dispatch`, `cmd_session` and `cmd_surfaces` in +`fleet_queue::placement`. The supported embedding today is therefore +the same one the binary uses — depend on `fleet-queue` with the +`client` feature and drive the verbs, either through +`fleet_queue::client::run` with a dispatch-shaped argument vector, or +through the placement entry points directly. + +This example is illustrative: the `client::run` route uses the verified +entry point from [The queue client](queue-client.md); the exact +signatures of the individual `cmd_*` placement functions were not +verified in this pass, so they are not presented as checked signatures +here. + +```toml +# Cargo.toml +[dependencies] +fleet-queue = { path = "../fleet-queue", features = ["client"] } +``` + +```rust +// Ask placement for a dry-run decision (no --dispatch flag) and let +// the placement module print its decision + reasoning, exactly as +// `fleet queue dispatch` would. +fn dry_run_decision() -> i32 { + let args: Vec = [ + "dispatch", + "--repo", "developing-today/code", + "--command", "cargo test --workspace", + "--json", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + fleet_queue::client::run(&args) +} +``` + +The verb entry points share the standard signature, verified against +the source: `placement::cmd_dispatch(args: &[String]) -> i32`, and +likewise `cmd_session` and `cmd_surfaces`. The engine itself is +`pub fn decide(registry: &serde_json::Value, job: &Job, ctx: &Ctx, gh: &dyn Gh) -> R<(Option>, Vec)>` — +it returns the chosen adapter (or `None` when the job stays queued) +plus the reasoning lines. `Job` is a public struct, and the adapter +types (`Adapter`, `Capacity`, `DispatchResult`, and the concrete +adapters) are re-exported publicly from `fleet_queue::placement` +(`pub use adapters::{...}`), so embedders can name them. diff --git a/pkgs/fleet/book/library/queue-client.md b/pkgs/fleet/book/library/queue-client.md new file mode 100644 index 0000000000..0e18ae319d --- /dev/null +++ b/pkgs/fleet/book/library/queue-client.md @@ -0,0 +1,278 @@ +# The queue client + +`fleet-queue` is three surfaces in one crate — a client, a queue broker +and a secrets broker — and Cargo features are the walls between them. +This chapter is about embedding the **client** surface: what the +`client` feature turns on, how a verb call travels to the broker (the +`call()` path), the argument-parsing helpers every verb is built on, the +fallback module's feature gate, the two transport routes, and how token +files are handled on each side. + +For the crate's place in the workspace, see [The crates](crates.md). +For the verbs themselves, the tutorials +[Tutorial: claim and complete a queue task](../tutorials/claim-and-complete.md) +and [Tutorial: run the brokers](../tutorials/run-the-brokers.md) cover +the operator's view. + +## The feature gates + +`fleet-queue`'s features, and the modules each one gates in `lib.rs`: + +| Feature | Dependencies it adds | Modules it gates | +|---|---|---| +| `client` | `fleet-config`, `ureq` | `client`, `fallback`, `needs_drew`, `placement` | +| `queue-broker` | `client`, plus `tiny_http`, `ureq`, `fleet-config`, `libc`, `rusqlite` | `queue_broker`, `turso_queue`, `validate` | +| `secrets-broker` | `tiny_http`, `fleet-config`, `libc` | `secrets_broker` | + +Either broker also gates `uds_http`; `disposition` is gated on +`client` **or** `queue-broker` (the completion gate is needed on both +sides). Unconditional modules include `backoff`, `bin_args`, +`creation_outbox`, `log`, `merge_intent`, `token_file`, `work` and +`person_wait`. + +Two consequences an embedder must internalise: + +- **`queue-broker` includes `client`.** A broker build carries the whole + client surface with it; there is no broker-only build of this crate + without the client. +- **The fallback module sits behind the `client` feature** — + `#[cfg(feature = "client")] pub mod fallback;`. The GitHub-issues + fallback transport is client surface, not broker surface. A test run + under `--features queue-broker` alone would not even compile the + fallback's tests; they run only under a client-carrying feature set + (the Nix `fleet-brokers` build and the full-variant check phase both + carry it). + +The bin crate maps capabilities onto these features exactly: +`queue = […, "fleet-queue/client"]`, `queue-broker = […, +"fleet-queue/queue-broker"]`, and the standalone `fleet-brokers` +package builds `-p fleet-queue --features +client,queue-broker,secrets-broker --bins`, producing `repo-queue`, +`queue-broker` and `secrets-broker` as separate artifacts. + +## The entry point + +The client's single public entry is the same function the multicall +binary and the standalone `repo-queue` binary both call: + +```rust +pub fn run(args: &[String]) -> i32 // fleet_queue::client::run +``` + +`args` is the argument vector *after* the domain name (`fleet queue +` / `repo-queue `), and the return is the process exit +code. Inside, `run` is one match over 32 verb names — the same 32 names +the registry lists as the queue domain's subcommands — dispatching to a +`cmd_` handler in the client modules (`commands_lifecycle.rs` for +lifecycle verbs, `commands_query.rs` for query verbs, `fallback_stack.rs` +for the outbox/stack groups), with `fallback` routed to +`crate::fallback::run` and `dispatch` / `session` / `surfaces` routed to +the placement module (see [Placement and surfaces as data](placement.md)). + +Bare invocation and help follow the client's own contract: no args +prints the top usage and returns `2`; a single `--help` / `-h` / `help` +returns `0`; an unknown verb prints `repo-queue: unknown command …` plus +the top usage and returns `2`. + +## The `call()` path + +Every broker-backed verb handler is the same five moves: + +1. Declare its flags and parse (next section). +2. Validate positionals and build a JSON request body. +3. POST the body to the verb's broker route via the transport's `call` + helper — `call("/unblock", &body)` for the `unblock` verb, and so on. + Every client verb is one POST route on the broker (`/validate`, + `/enqueue`, `/list`, `/claim`, `/claim-flow`, `/heartbeat`, + `/checkpoint`, `/complete`, `/unblock`, … plus the event, outbox and + stack families). +4. Unwrap the broker envelope: success is `{ok: true, …}`; failure is + `{ok: false, exit, error}` — the client prints `error` and exits with + `exit` (defaulting to `4` when the envelope carries no `exit` of its + own). +5. Print the returned row (most verbs) as JSON and return `0`. + +Two transport behaviours sit inside step 3 and are part of the client's +contract, not accidents: + +- **Retry on transient store errors.** A broker envelope whose error + carries PostgREST code `57014` (statement timeout) or `PGRST002` + (schema cache) is retried with exponential backoff and jitter — base + 500 ms, doubling, capped at 20 s, at most 6 attempts. This is safe for + writes because a `57014` means the statement rolled back. +- **The fallback switch.** For the work verbs — `claim`, `heartbeat`, + `checkpoint`, `complete`, `health` — *any* primary-store failure + (broker unreachable, or an `{ok: false}` envelope) switches the caller + to the GitHub fallback for that work instead of dying: a diagnostic on + stderr, one JSON object on stdout naming the switch + (`{"ok": false, "fallback": true, "switch_to": "github-fallback", …}` + with a `mode_line` of mode `db-degraded`, route `github-markers`), and + exit **6**. The environment variable `REPO_QUEUE_NO_FALLBACK_SWITCH=1` + is the escape hatch that restores plain die-on-error. + +The client's exit-code vocabulary follows from this: `0` success, `1` +gate/not-found failures on specific verbs, `2` usage, `3` transport or +broker-path failure (unreachable, HTTP 401, HTTP ≥ 400, malformed reply), +`4` a broker envelope failure with no exit of its own, `5` "the verb ran +but there is no matching claimed row / no claimable task", `6` the +fallback switch. + +## Verb argument parsing helpers + +All queue verbs parse through one hand-rolled parser in +`client/support.rs` — there is no `clap` anywhere in the workspace, by +design. The pure core is `parse_args_inner`; `parse_verb_args` is the +wrapper handlers call: + +```rust +// Shape of a handler's first moves (from cmd_unblock): +let args = parse_verb_args("unblock", rest, &["worker", "reason", "drop-dep"], &[]); +reject_extra_pos("unblock", &args, 1); +``` + +The signature pattern is `parse_verb_args(verb, rest, value_flags, +bool_flags)`: the handler declares exactly the flags it accepts, value +flags in the first slice and booleans in the second. The result is an +`Args` value — `{ pos: Vec, opts: Map }` — with +accessors `get`, `has`, `get_i64` and `pos_i64`. + +The parser's rules are the client's usage contract, and they are strict: + +- A help token anywhere in a verb's args prints that verb's exact usage + and exits `0` — help wins over every other argument, *except* when the + help-looking token is the value of a value-flag (`fail 5 --error help` + records the error text "help"). +- Unknown flags, duplicate value flags (never silent last-wins), a + boolean given an inline value (`--dry-run=false`), a value flag with + no value, a value flag followed by another `--flag` token, extra + positionals past the verb's arity, and non-numeric values for numeric + flags are **all** usage errors: message plus the verb's usage on + stderr, exit `2` — and for the arity and flag-shape errors, all of + this happens before any broker contact. +- Durations and limits are **rejected, never clamped**, identically at + client and broker: claim lease `1..=86400` (default 2700), heartbeat + extend `1..=86400` (default 900), park delay `1..=604800`, list limit + `1..=500` (default 20). + +Two hand-maintained usage strings per verb live beside the parser (the +one-line synopsis in `TOP_USAGE` and the long form in `usage(verb)`), +and a machine test — `every_verb_usage_matches_its_parser` — asserts +every verb's usage names *exactly* the flags its parser accepts. An +embedder adding a verb gets that test as a free oracle; see the worked +example in the crates' contributor documentation. + +Shared resolution helpers sit on top of `Args`: `opt_worker` (flag, else +the default worker `repo-worker-code`), `opt_queue` (flag, else +`REPO_QUEUE_DEFAULT_QUEUE`, else the shadow default +`repo-health-code-shadow` — with `claim` and `list` deliberately +*unscoped* when neither flag nor env is present, and `enqueue` having no +default at all), and the lane resolution for holder verbs (flag, else +`REPO_QUEUE_LANE`, else null, in which case the broker checks the worker +alone). These helpers are crate-internal (`pub(super)` / `pub(crate)`): +an embedder outside the crate uses `client::run`, not the helpers. + +## Transport routes + +The client never touches the database and never fetches from Bitwarden. +It POSTs JSON to the queue broker, which is the only process that talks +to the Turso store. Route selection, in order: + +### 1. The direct route (on-laptop) + +Chosen when a broker URL is configured: the environment variable +`REPO_QUEUE_BROKER_URL`, else the file `~/.config/repo-queue/broker-url`. +A `unix://` value selects the broker's Unix socket; anything else +is read as `http://host:port` TCP. With no configured URL, fleet-config's +probe-based choice for the `queue-broker` role applies: a live role +socket selects the Unix socket, otherwise the client falls through to +route 2 — and a failed Unix-socket attempt falls back to the +session-proxy route *within the same call*. + +On the wire this is raw HTTP/1.1: `POST `, header +`X-Agent-Token: `, `Content-Type: application/json`, +`Connection: close`. Read timeout 300 s, write timeout 60 s. Chunked and +Content-Length responses are both decoded strictly; HTTP 401 and +HTTP ≥ 400 die with exit `3` (a ≥ 400 surfaces the body's `error` +field). + +### 2. The session-proxy route (sandbox default) + +The client connects to the laptop-agent session proxy's Unix socket — +fleet-config's `broker_socket()` when it loads, else +`$HOME/.cache/laptop-agent/broker.sock` (environment beats config file +beats that compiled-in default). Framing is the proxy protocol: an +8-byte big-endian length prefix plus one JSON envelope: + +```json +{"method": "POST", "path": "/claim", "body": { }, "port": 4801, "token_file": "/tools/queue-broker-token"} +``` + +The proxy, on the laptop, reads the named token file *there* and +forwards to the broker on port `4801`. Read timeout 660 s. On a failed +first attempt the client auto-spawns the proxy/broker program — a +sibling `fleet` binary (`fleet proxy serve`) always wins; the Python +`~/tools/laptop-agent-broker.py` is the fallback for standalone rollback +builds — waits up to about 5 seconds for the socket, and retries once. + +Broker-unavailable on either route is exit `3`, or the fallback switch +(exit `6`) for the work verbs. + +## Token file handling + +One loader serves every side: `token_file::load_token_file` reads the +file and trims it, and a missing, unreadable, empty or whitespace-only +file is a **hard error naming the file** — a broker refuses to start and +a client refuses to send. (Before this rule, an empty token file +authenticated *any* empty-token client, including to the secrets +broker.) + +Which file, on which route (names and paths only — values are never +read by the client code that names them, and never printed): + +| Side | Source | +|---|---| +| Session-proxy envelope | Names the file `/tools/queue-broker-token`; the proxy reads it on the laptop, per request | +| Direct route, client token | `REPO_QUEUE_TOKEN_FILE`, else `~/.config/queue-broker/token` | +| Broker's own token | `QUEUE_BROKER_TOKEN_FILE`, default `~/.config/queue-broker/token` — compared against the request's `X-Agent-Token` header | +| Broker's Turso credential | `QUEUE_BROKER_TURSO_TOKEN_FILE`, else resolved through the secrets broker by the secret name `turso.fleet-queue-rw-token` | + +The broker side mirrors the client's strictness: its pre-body gate +refuses from headers alone — wrong or missing token gets +`401 {"error":"unauthorized"}`, a `Content-Length` over the 16 MiB cap +gets `413` — before any body byte is read. The only unauthenticated +route is `GET /healthz`. + +## Example: embedding the client + +This example is illustrative: it uses the verified entry point +(`fleet_queue::client::run`, taking the post-domain argument vector and +returning the exit code) to run one verb from an embedding binary. + +```toml +# Cargo.toml — the client surface only; no broker code is compiled. +[dependencies] +fleet-queue = { path = "../fleet-queue", features = ["client"] } +``` + +```rust +// Run `fleet queue health` from inside another binary and propagate +// its exit code (0 ok, 3 broker path down, 6 fallback switch, ...). +fn main() -> std::process::ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let code = fleet_queue::client::run(&args); + std::process::ExitCode::from(code as u8) +} +``` + +With the `queue-broker` feature instead, the same crate additionally +exposes `fleet_queue::queue_broker::run()` and +`fleet_queue::secrets_broker::run()` — both argument-free serve loops +(the standalone broker binaries accept no arguments at all: `-h` / +`--help` prints usage with exit `0`, anything else is a usage error at +exit `2`, classified by the crate's `bin_args` helper). + +There is no public transport-level helper for embedders: the `call()` +family in `client/transport.rs` (`call`, `call_result`, `call_fb`) is +`pub(super)` — visible only inside the client module. `client::run` is +the only public entry point, which is why the example above goes +through it. diff --git a/pkgs/fleet/book/library/registry-and-config.md b/pkgs/fleet/book/library/registry-and-config.md new file mode 100644 index 0000000000..4e014456a0 --- /dev/null +++ b/pkgs/fleet/book/library/registry-and-config.md @@ -0,0 +1,291 @@ +# Registry, config and capabilities + +Two platform crates decide what a given `fleet` invocation *is*: +`fleet-registry` says what exists — every domain, capability and build +variant, in every build — and `fleet-config` says what this host allows +and where everything lives. On top of them, the binary computes an +invocation **surface**: compiled capabilities, narrowed by the name it +was invoked under and by the host's config, with every unusable domain +answering through the same stub. This chapter covers all three layers +and the gating rules an embedder must respect. + +For the crate map, see [The crates](crates.md). + +## `fleet-registry`: the inventory is the registry + +`fleet-registry` is dependency-free — std only, strings and tables, no +I/O — and is compiled into **every** variant, including the size-gated +connect build, so `--help` is always complete. It owns four things. + +### The 15 capabilities + +`enum Capability`, with stable string ids in `Capability::ALL`, in +registry order: + +```text +proxy-connect, proxy-serve, proxy-raw-splice, queue, queue-broker, +secrets-broker, search, search-serve, dispatch, dispatch-test, +laptop-agent, secrets, gh, bridge, agent +``` + +`CapabilitySet` is a `BTreeSet`, built with +`capability_set(&[…])`; the crate provides `full_capabilities()`, +`serve_capabilities()` and `connect_capabilities()` for the three +variant sets below. + +### The 12 domains + +`pub const DOMAINS: &[Domain]` — the full registry in help order: +`queue`, `serve`, `proxy`, `dispatch`, `dispatch-test`, `secrets`, +`gh`, `bridge`, `agent`, `shell`, `search`, `laptop-agent`. + +`struct Domain` is the unit that help lists, stubs name, and config +disables: + +| Field | Meaning | +|---|---| +| `name: &'static str` | The domain's invocation name | +| `summary: &'static str` | The one-line description help prints | +| `capabilities: &'static [Capability]` | Every capability the domain spans | +| `primary: Capability` | The capability headline availability keys on | +| `aliases: &'static [&str]` | Its argv0 aliases | +| `subcommands: &'static [&str]` | The top-level verb inventory rendered by domain help | + +The `primary` rule has a visible consequence: on the `fleet-serve` +build, the `search` domain is marked absent because its headline +capability is the `search` *client*, even though the `search-serve` +role exists under `serve`. And `shell`'s capability list is `["agent"]` +— there is no `shell` capability atom; shell rides on the agent +capability. + +`pub fn domain(name)` looks a domain up by name (a linear find over +`DOMAINS`). + +### The 3 variants + +`enum Variant { Full, Serve, Connect }` — a property of the artifact, +whose names double as invocation profiles: + +| Variant | Installed name | Compiled capabilities | +|---|---|---| +| `Full` | `fleet` | All 15 | +| `Serve` | `fleet-serve` | `proxy-connect`, `proxy-serve`, `proxy-raw-splice`, `queue-broker`, `secrets-broker`, `search-serve`, `secrets` (7) — daemon roles plus proxy, no working-seat clients | +| `Connect` | `fleet-connect` | `proxy-connect`, `proxy-raw-splice` (2) | + +`Variant::name()` gives the installed side-by-side name; wherever a +variant is actually used, the binary is renamed plain `fleet` and the +hyphenated names survive as argv0 personalities (symlinks to the one +binary, created at install time). `Variant::capabilities()` is the +profile ceiling. `Variant::from_invocation_name()` recognises only +`fleet-serve` / `fleet-connect`; plain `fleet` selects no profile. +The profiles nest — connect ⊂ serve ⊂ full, and full equals +`Capability::ALL` — an invariant the crate's own tests assert, along +with unique/stable capability ids, every domain's primary being in its +own surface, aliases routing to real domains, and the domain alias +table matching the argv0 map. + +### The argv0 alias map + +`struct AliasRoute { domain, implied_arg }` and `pub fn alias_route(argv0)` +give the multicall names; anything not listed is not a multicall name: + +| argv0 | Routes to domain | Implied argument | +|---|---|---| +| `repo-queue` | `queue` | — | +| `queue-broker` | `serve` | `queue-broker` | +| `secrets-broker` | `serve` | `secrets-broker` | +| `laptop-agent-broker` | `proxy` | `serve` | +| `atlas-search` | `search` | — | +| `laptop-agent` | `laptop-agent` | — | + +An alias route constructs the surface with **no profile** (aliases do +not narrow), prepends the implied argument, and dispatches straight to +the domain. `is_known_invocation_name(name)` is true for `fleet`, a +variant name, or an alias; any other invocation name is a usage error +(exit `2`) naming the expected names. + +## `CapState`: the four answers a domain can give + +The binary's `Surface` (in the bin crate) holds the invocation's whole +effective surface: the compiled set, the optional profile, their +intersection as the effective set, and the loaded config. +`Surface::cap_state(cap, domain_name)` checks in order and yields +`enum CapState`: + +| `CapState` | Meaning | Stub wording (first line) | +|---|---|---| +| `Available` | Compiled in, in profile, not config-disabled | — (the domain runs; the fourth form below is its skeleton variant) | +| `NotInBuild` | This build was compiled without it | `fleet: this build does not include ''.` | +| `NarrowedByName` | The invocation name (`fleet-serve` / `fleet-connect`) scoped it away | `fleet: invoked as '', this build does not include ''.` | +| `DisabledByConfig` | The `[domains]` table in this host's fleet config set the domain to `false` | `fleet: '' is disabled by config on this host.` | + +Every stub goes to stderr and returns exit **69** (`EX_UNAVAILABLE`). +Its second line is always `Enabled capabilities: ` — the +*usable* set: the effective set minus every capability of every +config-disabled domain — and its third line names the build. There is +also a step-1 skeleton form for a capability that is `Available` but has +nothing behind it yet: "included in this build but not implemented +yet", in frozen epic-#5412 wording. Help renders the same four states +inline (`[not in this build]`, `[narrowed out by this name]`, +`[disabled by config]`), and renders them on *every* variant — help +never stubs. + +`fleet capabilities` prints the whole picture as JSON: the build block +(name, version, derived version, source revision, invoked-as, profile), +**two** capability lists — `capabilities` (what this *invocation* can +use) and `compiled_capabilities` (what the *binary* was built with); +their difference is exactly the profile/config narrowing — and one +entry per domain with its `state` (`available`, `not-in-build`, +`narrowed-by-name`, `disabled-by-config`) and `available` boolean. + +## `compiled_capabilities()`: the binary reports its own variant + +Capabilities are compiled in through Cargo features on the bin crate, +and reconstructed at runtime — the binary *derives* its variant from +its feature set; it does not trust a baked-in name. + +- The feature sets: `default = ["full"]`, where `full` enables every + domain feature; `serve` enables the serve set as one feature for the + Nix build; the connect build is `--no-default-features` with nothing + optional on. Each feature wires its optional dependencies and the + owning crate's matching feature (for example `queue = + ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/client"]`). +- `proxy-connect` is **not a feature**: it is compiled into every + variant unconditionally. `fleet-proxy` itself is a non-optional + dependency with default features off — the client is in every + variant; only the broker half (`fleet-proxy/serve`) is gated. + `fleet-secrets` is optional for the same reason in reverse: the + connect variant must not carry it. +- `fn compiled_capabilities()` starts from `{ProxyConnect, + ProxyRawSplice}` unconditionally and inserts one `Capability` per + `cfg!(feature = "…")`. `build_variant(compiled)` then matches the set + against the three variant sets — `Full`, `Serve`, `Connect`, or + `None`, which renders as the build name `fleet-custom` in + `fleet version`. + +Dispatch order, end to end: argv0 alias → domain route; argv0 variant +name → root dispatch with that profile as a ceiling; argv0 `fleet` → +root dispatch; then per domain — capability compiled in? in profile? +not config-disabled? → the domain handler, else the stub; an unknown +name is a usage error, exit `2`. The dispatch is hand-rolled, +explicitly not `clap`, because it must behave identically in every +variant — including the tiny connect build, where the full registry and +the stub machinery are the product. + +## `fleet-config`: one place config resolves + +`Config::load()` / `Config::file_path()` resolve, in order: environment +overrides (`FLEET_CONFIG`, `FLEET_BROKER_SOCKET`, …), then the config +file (`$FLEET_CONFIG`, else `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`), +then compiled-in defaults. The crate owns the `[domains]` +enable/disable table (`domain_enabled(name)` — the per-host shaping and +incident lever behind `DisabledByConfig`), the `[proxy]`, `[secrets]`, +`[queue-broker]`, `[secrets-broker]` and `[dispatch]` sections, and the +fleet's constants: ports (4799 laptop-agent, 4800 secrets-broker, 4801 +queue-broker, 4802 gh cache, 4879 pm-dispatch, 3130 egress proxy) and +role sockets (environment beats `[] socket` in the file beats the +runtime-dir/home defaults). + +### The `[host]` manifest: `FLEET_HOST_CONFIG` and `FLEET_LOCATION` + +`fleet init` — autostart this host's roles per the manifest — resolves +the manifest in this order: + +1. **`FLEET_HOST_CONFIG`**: a complete inline `[host]` manifest. It wins + outright. A manifest with no location is a loud error. +2. **`FLEET_LOCATION`**: names the location; roles come from the config + file's `[host]` section only if the file's location matches, else + from the built-in map. +3. **The config file's `[host]` section**: `location`, `init_mode`, and + `[host.roles]` — the role set is exactly the key set of the roles + table, and an unknown role name is a loud parse error, never silently + ignored. + +The built-in location map has two locations today (a future lab node +provisions its own `[host]` section instead of growing the table): + +| Location | `init_mode` | Roles | +|---|---|---| +| `sandbox` | `spawn` | `proxy`, `secrets-broker` | +| `laptop` | `systemd` | `laptop-agent`, `queue-broker`, `search`, `secrets-broker` | + +The full `[host]` role vocabulary is five names — `proxy`, +`queue-broker`, `secrets-broker`, `search`, `laptop-agent` — a superset +of the serve roles (it includes `laptop-agent`, which is not a serve +role). Behaviour that follows from the manifest rules: + +- An **unknown location** (no manifest from any source, or a location + with no roles) makes `init` report state — every source consulted, + plus detected hostname/OS/systemd for the report only, since detection + never selects roles — start nothing, and exit `69`. Never guess-start + a role. +- Roles the manifest itself disables (`enabled = false`) are reported as + skipped with their reason; then the `[domains]` gate is applied and + **wins over the manifest**. +- In `spawn` mode (sandbox), v1 spawn semantics exist for exactly the + two sandbox roles; any other role in a spawn manifest is reported and + skipped, never spawned. In `systemd` mode (laptop), init never + detached-spawns a daemon systemd owns: it reports each unit's state, + starts an inactive-but-existing unit, and reports a missing unit as + skipped. + +## Capability gating rules for embedders + +These are the rules the narrowing-only design imposes on anyone +embedding or wrapping the binary: + +1. **Profiles only narrow, never widen.** Invoking under `fleet-serve` + or `fleet-connect` sets a capability *ceiling*: the effective surface + is `compiled ∩ profile`. No invocation name, config file or + environment variable can give an invocation a capability its binary + was not compiled with. +2. **Config only disables.** The `[domains]` table can remove a domain + on a host (the incident lever), and that gate wins even over the + `[host]` manifest's role list — but it cannot enable what the build + or profile lacks. +3. **Aliases do not narrow.** An argv0 alias (`repo-queue`, + `queue-broker`, …) routes straight to its domain with no profile. + Only the two hyphenated *variant* names narrow. +4. **Check state, don't assume.** An embedder that depends on a domain + must handle all four `CapState` outcomes — or, from outside the + process, exit `69` with the stub's wording — and should read + `fleet capabilities` (the JSON census) rather than hardcoding which + build it hopes it is running. The two lists in that output exist + precisely so a wrapper can tell "this binary can't" (compiled set) + from "this invocation can't" (usable set). +5. **Help is not evidence of availability.** The full registry renders + on every variant by design. Availability is the domain's `state` in + the capabilities census, or the stub you get when you invoke it. + +## Example: reading the registry and the config + +This example is illustrative — it follows the researched API shapes +(`fleet_registry::DOMAINS`, `Capability::ALL`, +`fleet_config::Config::load`) but the exact signatures were not all +verified against source in this pass, and two spots are marked for the +coordinator rather than presented as checked signatures. + +```rust +// List every registered domain with its primary capability, then ask +// the loaded config whether the queue domain is enabled on this host. +fn main() { + for cap in fleet_registry::Capability::ALL { + println!("capability: {}", cap.id()); + } + for d in fleet_registry::DOMAINS { + println!("domain {} (primary: {})", d.name, d.primary.id()); + } + + // Config::load() -> Result; a malformed + // file is a loud error on every path, never a silent default. + let config = fleet_config::Config::load().expect("fleet config must load"); + println!("queue enabled: {}", config.domain_enabled("queue")); +} +``` + +Signatures verified against the source: `Capability::id(self) -> &'static str` +is the accessor for the stable string ids used above, and +`fleet_registry::domain(name: &str) -> Option<&'static Domain>` is the +by-name lookup. `fleet_config` also offers +`Config::load_from(path: &Path) -> Result` for an +explicit manifest path. diff --git a/pkgs/fleet/book/operations/deploying-this-book.md b/pkgs/fleet/book/operations/deploying-this-book.md new file mode 100644 index 0000000000..571c8205c7 --- /dev/null +++ b/pkgs/fleet/book/operations/deploying-this-book.md @@ -0,0 +1,72 @@ +# Deploying this book + +This book is an mdBook that lives with the code it documents: sources in `pkgs/fleet/book/`, configuration in `pkgs/fleet/book.toml`, build definition in `pkgs/fleet/docs.nix`, published to the `developing-today/code` GitHub Pages site under `/fleet/`. This chapter describes exactly how that works — and, just as explicitly, the custom-domain step that is **not** wired yet. + +For the rule that keeps the book's content current, see [Keeping this book current](../development/keeping-this-book-current.md). + +## The pieces + +- `pkgs/fleet/book.toml` — mirrors the mcpx book's configuration: title "fleet", `src = "book"` (a dedicated folder; mcpx's `src` is its pre-existing `docs/` because that book grew out of an existing docs tree), build directory `book`, and `create-missing = false` — every chapter in `SUMMARY.md` must exist on disk; the build never invents stubs. The fleet book is plain mdBook: mcpx's book uses a custom Go preprocessor and an agent-twin emitter, and fleet has no equivalent tools. That is a deliberate difference, not an omission. +- `pkgs/fleet/book/` — `SUMMARY.md` plus the chapters. `index.md` is the introduction. +- `pkgs/fleet/docs.nix` — mirrors `pkgs/mcpx/docs.nix` minus the Go preprocessors. It takes a `siteUrl` argument (default `"/"`) that is baked into the rendered book as mdBook's `output.html.site-url`, injected at build time via the `MDBOOK_OUTPUT__HTML__SITE_URL` environment variable rather than stored in `book.toml`. +- `lib/default.nix` — exposes the package next to its mcpx sibling: `fleetDocs = pkgs.callPackage ../pkgs/fleet/docs.nix { };` and `fleet-docs = fleetDocs;` in the packages set, so the build is: + + ```sh + nix build .#fleet-docs + ``` + +## The two workflows + +Repository CI runs on `main` only, and the book follows the same policy. + +### `fleet-docs.yml` — build only + +`.github/workflows/fleet-docs.yml` mirrors the mcpx build job: on push to `main` and on `workflow_dispatch`, it builds `.#fleet-docs`, stages the result, and verifies the rendered site (the index page exists). It **never deploys**. Its job is to fail by name on `main` when a chapter breaks the build — a missing `SUMMARY.md` target under `create-missing = false`, a bad link, a broken derivation — before the deploy path is involved. + +### `mcpx-docs.yml` — the combined Pages deploy + +The deploy lives inside the existing `.github/workflows/mcpx-docs.yml`, whose deploy staging gains the fleet book. The reason is a hard constraint of GitHub Pages: + +**One repository has one Pages site, and a Pages deploy replaces the whole site.** + +The mcpx book already occupies `https://developing-today.github.io/code/`. A fleet-only deploy would publish an artifact containing only the fleet book — and wipe the mcpx book off the site. So the deploy job builds both books and stages one combined site: + +```text +site/ ← the mcpx book, built with siteUrl "/code/" +site/fleet/ ← the fleet book, built with siteUrl "/code/fleet/" +``` + +The fleet book is therefore reached at `https://developing-today.github.io/code/fleet/`, and its `siteUrl` is `/code/fleet/` — the `/code/` project-site prefix plus the `fleet/` staging directory. The combined artifact then goes through the same publish shape as before: a staging job (`configure-pages` + `upload-pages-artifact`) and a separate publish job with the `pages` concurrency group and one retry, the job boundary existing so the Pages artifact metadata has time to propagate before `deploy-pages` fetches it. + +GitHub Pages for `developing-today/code` is **already enabled** with `build_type = "workflow"` (source: GitHub Actions). There is no manual enable step, no `gh-pages` branch, and no generated HTML is ever committed. + +## Preview the book locally + +1. Build the packaged form from the repository root: + + ```sh + nix build .#fleet-docs + ``` + +2. Open or serve `result/index.html` and check the chapter order, internal links, and search. +3. Or, for a faster edit loop, build in place from `pkgs/fleet/`: + + ```sh + mdbook build + ``` + + and preview the output directory named by `book.toml`. The Nix build is the authoritative check — it is the same derivation, mdBook version, and `siteUrl` handling the deploy uses. + +Note the local default `siteUrl` is `"/"`. Links inside the book are relative `.md` links, so local preview navigation works regardless; only absolute site URLs differ between the local build and the deployed one. + +## The future custom-domain step — not wired yet + +Per Drew's steer, the book will eventually be served from a custom domain instead of the `github.io` path. That step is **planned, not wired**: there is no CNAME file anywhere in the repository today, no custom domain is set on the Pages site (`cname: null`), and the `siteUrl` values above still point at `/code/` and `/code/fleet/`. Do not present the custom domain as live, and do not "fix" URLs in anticipation of it. + +When the step is taken, it has exactly three parts, done together: + +1. **CNAME file** — add the CNAME file naming the chosen domain to the deployed site artifact (it must ride in the combined staging of `mcpx-docs.yml`, alongside both books, or the next deploy removes it — whole-site replacement cuts both ways). +2. **DNS record** — create the DNS record for the domain pointing at GitHub Pages, in the account that owns the domain's zone. +3. **Pages custom domain setting** — set the custom domain on the repository's Pages configuration so GitHub provisions the certificate and redirects the `github.io` address. + +The same change must also move both books' deploy `siteUrl` values from the `/code/…` paths to the domain-rooted paths, and update [Keeping this book current](../development/keeping-this-book-current.md) and this chapter to describe the wired state. Until that change lands, this section stands as the record of intent. diff --git a/pkgs/fleet/book/operations/faq.md b/pkgs/fleet/book/operations/faq.md new file mode 100644 index 0000000000..13a6c509e1 --- /dev/null +++ b/pkgs/fleet/book/operations/faq.md @@ -0,0 +1,55 @@ +# FAQ + +Short answers, each pointing at the chapter that owns the long one. For symptom-driven diagnosis, see [Troubleshooting](troubleshooting.md); for definitions, see [Glossary](glossary.md). + +**Why is fleet one binary instead of a tool per job?** + +One multicall binary means one artefact to build, pin, publish, and roll out to every seat, and one registry that every build knows in full — so `--help` and `fleet capabilities` are complete even on a narrowed build, and an unavailable domain answers with an informative stub instead of "command not found". Domains are compiled in per variant by Cargo features; hyphenated names (`fleet-serve`, `fleet-connect`) and aliases (`repo-queue`) are argv0 personalities of the same binary. See [Register a domain or capability](../development/register-a-domain.md). + +**Why did my command print a stub and exit 69?** + +The domain is not usable in that invocation: not compiled into the build, narrowed out by the invocation name, or disabled by config on that host. The stub's first line says which; `fleet capabilities` says it in JSON. Exit 69 is `EX_UNAVAILABLE` — the binary working as designed. See the stub entry in [Troubleshooting](troubleshooting.md). + +**The broker is down — what do I do?** + +First, find out *which* broker and *which layer*: `fleet agent doctor` for the seat, `fleet queue health` for the queue, `GET /health` for the secrets-broker. On a sandbox seat, the heal chain rebuilds the stack in order (tailscaled → relay → session broker → secrets broker → gh) on a roughly five-minute cycle. On the laptop, systemd owns the brokers — check the unit, and redeploy through the profile if the generation is bad. If the *queue*-broker is unreachable for a work verb, the client switches to the GitHub fallback with exit 6 rather than failing outright. See [Health checks and the heal stack](health-and-healing.md). + +**Where do secrets come from?** + +By name, never by value in files or commands. The resolution path is the secrets-broker protocol first (a Bitwarden Secrets Manager cache that refreshes on a TTL), then the `bws` CLI as fallback, then `op` where a vault is named. Deploy definitions, bootstrap scripts, and this book name secrets; they never carry values. A secret minted moments ago is visible immediately: a cache miss reads through to Bitwarden for that one name. + +**Why did placement pick Blacksmith?** + +Placement is a tiered cascade over the surfaces in `fleet-surfaces.json`: free GitHub-hosted Actions capacity first (Tier 1, least-loaded owner first), then Blacksmith (Tier 2) within its monthly budget — Blacksmith is a budgeted fallback, not a default, and a dispatch can require explicit allowance for paid capacity. A `--followup` dispatch sticks to the previous session's surface when that surface still has capacity and its owner's queued count is below the sticky threshold (2 on every shipped surface). See also: why did placement pick *anything* — it picks from live capacity and local session history, per owner, not per repository whim. + +**What is an `fp_` handle?** + +The handle of a placement dispatch session: `fp_` plus a 128-bit random value, printed when `fleet queue dispatch` records the session. It names the dispatch session record (whose local records live in `~/.local/state/fleet-place/sessions.json`) and is what `fleet queue session status ` and `fleet queue session result ` take. It is distinct from the workflow's `dispatch_id` input, which is a separate fresh correlation id generated per dispatch when the surface's workflow declares one. A portable alternative form for run correlation is `OWNER/REPO#RUN_ID`. + +**Can I use fleet as a library?** + +The workspace's library crates (`fleet-registry`, `fleet-config`, `fleet-secrets`, `fleet-queue`, and the rest) are real crates with real APIs, and fleet's own domains consume them that way. But they are an internal workspace on the atlas-search pattern — versioned together at 0.1.0, consumed by path, with no published-crate compatibility promise. Inside the repository, write against them freely; outside it, shell out to the binary, whose command contract is the stable surface. + +**How do I add a verb?** + +Follow [Add a subcommand](../development/add-a-subcommand.md): registry entry, both usage strings, dispatch arm, handler, broker verb if it mutates state, fallback twin if it must work broker-down, oracle-named tests, and `docs/verbs.md` plus this book in the same change. For a flag on an existing verb, see [Add a flag](../development/add-a-flag.md). + +**Which queue am I on?** + +There is one fleet queue; the `--queue` flag scopes within it, it does not select a different system. The subtleties: `claim` and `list` are *unscoped* when neither flag nor the `REPO_QUEUE_DEFAULT_QUEUE` environment variable is set (the broker works across the one queue); `enqueue` has no default queue at all and must name one; most other verbs default to `repo-health-code-shadow` via `--queue`'s default. If a verb behaved as if it could not see your task, check which of those three cases you were in before suspecting the broker. + +**Why exit 5?** + +Exit 5 is the queue client's "the verb ran, but there is no matching claimed row / no claimable task" code. It covers: `claim` finding nothing claimable (`{"task": null}`), the no-double-serve guard holding a fresh claim (`fallback_held`), and every holder verb (`heartbeat`, `checkpoint`, `park`, `release`, `block`, `fail`, `complete`) whose worker/lane does not match the claimed row or whose row is already terminal. `fleet agent next` also exits 5 when no intake rung had work. See the lane/worker mismatch and lease-expiry entries in [Troubleshooting](troubleshooting.md). + +**Why did `complete` reject me?** + +Because completion of a fix-class task is evidence-gated: it must carry a verified disposition record from `fleet queue verify-disposition`, read back live from GitHub, and the broker's gate found a defect — a stale record, a verdict the readback does not support, a linked PR missing from the readback, or a follow-up that fails its checks. The rejection leaves the task claimed, deliberately. Iterate with `verify-disposition --json` standalone (exit 0 means the record would pass) and complete promptly with a fresh record. See [Troubleshooting](troubleshooting.md). + +**Where is this book's source?** + +In the repository, at `pkgs/fleet/book/` (chapters) with `pkgs/fleet/book.toml` beside it and the build in `pkgs/fleet/docs.nix`, published as the `.#fleet-docs` package and deployed under `/fleet/` on the combined Pages site. Build or preview it with the steps in [Deploying this book](deploying-this-book.md). The book's maintenance rule — it changes in the same pull request as the behaviour it describes — is [Keeping this book current](../development/keeping-this-book-current.md). + +**Why does the same secret name resolve differently on the laptop and the sandbox?** + +Because "the secrets-broker" is location-relative: on the laptop it is the tailnet-bound broker; on a sandbox seat, `fleet init` runs a local loopback copy on the same port. Both are caches of the same Bitwarden Secrets Manager source, resolved by the same name — what differs is which cache answers, and therefore the value's age (`age_seconds` on a cache hit tells you). Check `/health`'s `oldest_secret_age_seconds` before assuming a rotation did not propagate. diff --git a/pkgs/fleet/book/operations/glossary.md b/pkgs/fleet/book/operations/glossary.md new file mode 100644 index 0000000000..df6827aca0 --- /dev/null +++ b/pkgs/fleet/book/operations/glossary.md @@ -0,0 +1,44 @@ +# Glossary + +One-to-three sentence definitions, alphabetised. Chapters use these terms in these senses. + +**broker** — A resident fleet service that other components ask over a socket or HTTP: the queue-broker owns queue state, the secrets-broker owns the secrets cache, and the session broker (the session proxy's server half) owns laptop-channel connections. Brokers are the stateful centre; clients are replaceable. + +**capability** — One of the 15 compile-time atoms in `fleet-registry` (`queue`, `proxy-connect`, `search-serve`, and so on) that decide what a build can do. A domain's availability is derived from its capabilities, the invocation's profile, and config, as one of four `CapState` values. + +**disposition** — The verified account of what actually happened to a task's issue and its linked pull requests, read back live from GitHub by `verify-disposition`. A completion that requires one must carry the record, and the broker's gate checks it before the task may close. + +**envelope** — The broker's reply shape: `{ok: true, …}` carrying a `row` (or `rows`), or `{ok: false, exit, error}` carrying the exit code the client exits with and the message it prints. Clients do not invent errors; they relay envelopes. + +**fallback** — Two senses, both load-bearing. (1) *Transport fallback*: the GitHub-issues transport of the queue in `fleet-queue/src/fallback.rs`, used when the broker path fails; a work verb switches to it with exit 6. (2) *Resolution fallback*: the next source in a chain, as in the secrets path falling back from the secrets-broker protocol to the `bws` CLI. + +**follow-up** — A recorded successor that owns the remainder of unfinished work: a task, an issue, or a pull request named on a completion (with a `--reason`, always) so a task may close while linked work is still open. The disposition gate verifies it exists and is in the state claimed. + +**lane** — A named work stream within a queue worker family, recorded on a claim so the broker can tell whose claim a holder verb acts on. All scheduled lanes share one worker id, so the lane — resolved from `--lane`, else the `REPO_QUEUE_LANE` environment variable, else null — is the discriminator. + +**leg** — One of `fleet agent doctor`'s four independent probes: bridge, queue, github, shell. There is no secrets leg; secrets is folded into the bridge leg's stated need. From the legs, doctor derives the rungs map. + +**outbox** — The creation outbox: the broker-side queue for GitHub object creation (issues, pull requests, comments) that must survive crashes and rate limits. Producers enqueue; a single drainer claims, creates, verifies by read-back, and resolves, pacing creates and backing off on rate limits. + +**placement** — The component that chooses where a dispatched job runs, from the surfaces registry, by live capacity and session history: a tiered cascade (free GitHub-hosted Actions, then budgeted Blacksmith, then the remaining surface kinds) with a hard-pin override and follow-up stickiness. + +**rung** — One step of the `fleet agent next` intake ladder, tried in order: push (a bridge command addressed to the agent), queue (a queue claim), shortlist (the local file), priority (GitHub). A rung that is *down* is skipped and recorded; a rung that is *empty* is a different fact. + +**seat** — One enrolled agent installation: a sandbox, a laptop, or another host running a fleet binary with its own identity, config, and token files. Rollout is verified per seat, because seats run whatever binary they were last given. + +**shortlist** — The local file of candidate work an agent seat keeps for itself, managed by `fleet agent shortlist`. It is the one intake rung that is always available, because it needs no network, broker, or token. + +**stack** — Merge-intent sense: a recorded, ordered set of merge intents (finished branches with their authoring lane, worker, and session) in the broker's `merge_intents` table, managed by `fleet queue stack`. Not a call stack and not the pm stack. + +**stub** — The three-line stderr block a domain answers with when it is not usable in an invocation, always exit 69 (`EX_UNAVAILABLE`). Its wording names the reason class: not in this build, narrowed out by the invocation name, disabled by config, or included but not implemented. + +**surface** — Two related senses. (1) *Execution surface*: an entry in `fleet-surfaces.json` naming a place fleet work can run (a GitHub Actions pool, Blacksmith, a codespace pool, the laptop), with its owner, targets, status, and capacity facts. (2) *Invocation surface*: the set of capabilities a single fleet invocation can use, after build, profile, and config narrowing. + +**session proxy** — The fleet proxy domain's broker-and-client pair that carries a sandbox seat's traffic to the laptop's brokers over one channel, with a length-prefixed JSON wire protocol and a hello/capability handshake. `proxy serve` is the broker; `proxy connect` and `proxy init` are the client side. + +**tombstone** — A terminal marker that records a task, claim, or session as deliberately dead, so later folds and replays skip it instead of resurrecting it. A tombstone is a record, not a deletion: the history stays readable. + +**variant** — One of the three shipped capability profiles of the one binary — Full (`fleet`), Serve (`fleet-serve`), Connect (`fleet-connect`) — selected at build time by Cargo features and re-derivable at runtime from the compiled capability set. Hyphenated variant names double as argv0 profiles that narrow, never widen, an invocation's surface. + +**worker** — The identity that claims and holds queue tasks (`--worker`, default `repo-worker-code`, with named exceptions such as `cancel`'s `fleet-monitor`). Holder verbs are checked against the claiming worker and lane; a mismatch is exit 5. + diff --git a/pkgs/fleet/book/operations/health-and-healing.md b/pkgs/fleet/book/operations/health-and-healing.md new file mode 100644 index 0000000000..1a7ab22312 --- /dev/null +++ b/pkgs/fleet/book/operations/health-and-healing.md @@ -0,0 +1,61 @@ +# Health checks and the heal stack + +Fleet has no single health endpoint; it has a health *surface* per layer, and the right check depends on which layer you doubt. This chapter lists every surface, then describes the self-healing chain that keeps a sandbox seat's broker stack alive. For symptom-driven diagnosis, see [Troubleshooting](troubleshooting.md). For how the services are run, see [Running the brokers as services](services.md). + +## Every health surface + +| Surface | Command / route | What it proves | +|---|---|---| +| Queue as a client sees it | `fleet queue health [--queue ] [--worker ]` | The queue client can reach the broker (`POST /health`) and the broker's health rows come back. `--worker` scopes the answer to that worker's view. Distinct from the broker's own unauthenticated probe, below. | +| Queue-broker liveness | `GET /healthz` on the queue-broker (port 4801 on the laptop) | The broker process answers. Unauthenticated — the only unauthenticated queue-broker route. It answers before the Turso backend is up (the backend starts on a separate thread), so it proves liveness, not readiness. | +| Secrets-broker readiness | `GET /health` on the secrets-broker (port 4800) | Returns `{ok, serving, secrets, last_refresh_unix, refreshing, oldest_secret_age_seconds}`. **503 while `serving` is false** — `serving` becomes true only once at least one refresh has succeeded. Before that, the body carries `refresh_error` when a refresh has failed. A live process whose `bws` cannot run is *not* serving, and this endpoint says so. | +| Session-broker (proxy) liveness | `fleet proxy` broker hello via `fleet init`'s probe; the broker also self-checks its peers | The session proxy answers on its socket and speaks the hello/capability handshake. `fleet init` reporting the proxy role as live is the practical check. | +| Bridge health | `fleet bridge health` | The message bridge's `/healthz` answers. No token needed. Proves the bridge service, not your seat's mailbox access — for that, read a mailbox (`fleet bridge inbox --agent --limit 1`). | +| Seat health, all legs | `fleet agent doctor [--agent ]` | Four independent probes issued together — the **legs**: **bridge** (`bridge inbox --agent A --limit 1` with a name, else `bridge health`), **queue** (`queue health`), **github** (`gh api rate_limit` via `fleet gh`, falling back to plain signed-in `gh`), **shell** (`laptop-agent health`). There is no secrets leg: secrets is folded into the bridge leg's stated need. From the legs, doctor derives the **rungs** map (which intake rungs this seat still has: push = bridge leg, queue = queue leg, shortlist = always true, priority = github leg) and the `builds` line. Exit 0 when any intake rung is live, else 3. | +| `gh` cache daemon | `fleet gh cache-status` | Probes the `gh` cache daemon: whether it is running, where it is bound, and its cache state. No daemon is a transport-down answer (exit 3), not a crash. | +| Laptop-agent daemon | `fleet laptop-agent health` | Prints the daemon's health JSON verbatim (its `GET /health`, token-authenticated); exit 0 on an answer. This is the shell leg of `doctor` and the post-activation check for the `laptop-agent` deploy profile, which has no unauthenticated health endpoint. | +| Dispatch service | `fleet dispatch status` | The pm-dispatch service's `GET /health` body, printed verbatim. | +| The binary itself | `fleet version` / `fleet capabilities` | Build name, derived version, source revision, and the usable capability set. The first thing to collect when a seat behaves as if a verb or domain were missing — see the stub entry in [Troubleshooting](troubleshooting.md). | + +Two reading rules: + +- **Liveness is not readiness.** `/healthz` answering, a process existing, and a port listening are each weaker than the check one layer up. Always confirm with the highest surface that matches the complaint: a queue complaint gets `fleet queue health`, a seat complaint gets `fleet agent doctor`. +- **503 from the secrets-broker is information, not failure.** It distinguishes "not loaded yet" from "no such secret" (404) and from "the source failed" (502). Clients key on it; so should you. + +## The heal stack (sandbox seat) + +A sandbox seat's broker stack has several moving parts between a fleet command and the laptop, and any of them can die with the seat's runtime. The heal chain rebuilds them **in dependency order**: + +```text +tailscaled → relay :3130 → session broker → secrets broker → gh +``` + +1. **tailscaled** — the tailnet itself. Nothing downstream works without it. +2. **The relay on port 3130** — a local relay that carries the seat's session-proxy traffic to the tailnet proxy. Userspace-networking seats route the session proxy through a CONNECT proxy fleet expects on port 3130; the relay is what makes that port answer. +3. **The session broker** — the session proxy broker process (`fleet serve proxy`), spawned via `fleet init` when its socket does not answer (see [Running the brokers as services](services.md)). +4. **The secrets broker** — the seat's loopback secrets-broker, spawned the same way when its socket does not answer. +5. **gh** — the `gh` command shim and the pristine `gh` binary it routes to; the chain verifies both exist and answer, because a shim whose target is missing fails every `gh` call at once. + +Order matters: starting the session broker before the relay is up produces a broker that cannot reach anything; starting the secrets broker before the session broker leaves secret consumers with nowhere to ask. The chain is therefore run whole, in this order, never piecemeal by hand. + +### The 5-minute heal cron + +A cron job on the seat runs the heal check roughly every five minutes. Each run verifies channel health (the chain above), secrets health (the secrets-broker answering and serving), and `gh`. A healthy run is silent. An unhealthy leg is rebuilt by the same chain the bootstrap uses — the heal is a re-run of the bring-up for the dead leg and everything downstream of it, not a separate repair implementation. + +### `init-ensure` + +`init-ensure` is the bring-up the heal cron and the bootstrap share. It: + +1. Test-executes fleet binary candidates before trusting one (a file can list as executable and still fail to execute, for example when its interpreter is absent), and points the seat's `gh` entry point at a working binary. +2. Delegates the channel to the heal chain above (tailscaled, relay, session broker). +3. Fetches the secrets-broker token by name from Bitwarden Secrets Manager when the local token file is missing, so the secrets broker can start authenticated. +4. Ensures the secrets broker and the `gh` route, completing the five legs. + +The bootstrap's boot hook re-runs the tailnet and fleet phases after a sandbox recycle under a lock with a timeout, because only the home directory survives a recycle. Between recycles, the 5-minute heal cron is what keeps the stack honest. + +### What to do when healing does not converge + +1. Run `fleet agent doctor` and note which legs are down — the heal chain fixes legs in order, so the *first* down leg is the one to look at. +2. Check the leg's own surface from the table above (for example `fleet gh cache-status` for the `gh` leg, `/health` for the secrets-broker). +3. Do not restart-loop a broker that is up but not serving; see the secrets-refresh entry in [Troubleshooting](troubleshooting.md). +4. If the channel itself (tailscaled / relay) is the first down leg and healing does not restore it, the seat cannot reach the laptop at all: queue and broker work will fail with transport errors (exit 3) while purely local work (the shortlist rung) still functions. That state is a channel outage, not a fleet bug — report it as such, with the doctor output attached. diff --git a/pkgs/fleet/book/operations/services.md b/pkgs/fleet/book/operations/services.md new file mode 100644 index 0000000000..5d0a985a67 --- /dev/null +++ b/pkgs/fleet/book/operations/services.md @@ -0,0 +1,52 @@ +# Running the brokers as services + +Fleet's long-running roles are broker services. Where they run depends on the seat: on the laptop they are systemd services owned by the deployment machinery; on a sandbox seat they are detached processes spawned by `fleet init`. This chapter covers both models. For deploying new generations of the laptop services, see [Release and rollout](../development/release-and-rollout.md). For checking them, see [Health checks and the heal stack](health-and-healing.md). + +## The laptop model: `deploy.py` profiles + +On the laptop, services are defined in `pkgs/deploy/services.nix` and deployed by `pkgs/deploy/deploy.py` (see [Release and rollout](../development/release-and-rollout.md) for the full profile, generation, and rollback mechanics). The properties that matter day to day: + +- Each service gets a per-service Nix profile under the profile base (system scope: `/nix/var/nix/profiles/per-service`). +- `deploy.py` renders a systemd unit per service whose `ExecStart` points at the profile's **`current`** link — `//current/` — never at a bare store path. A generation flip is therefore a profile repoint plus a restart of that one unit; the unit file does not change. +- Activation restarts **only that unit**, health-checks it, and flips the profile back to the previous generation on failure. +- The generation history is the append-only JSONL log per target; `deploy status` folds it to report current and previous generations. + +### The four laptop services + +Three of the laptop's services are fleet's own; the fourth group is the pm stack that shares the same deployment machinery and the same host. + +| Service | Runs | Port | Restart | Health | +|---|---|---|---|---| +| `queue-broker` | `fleet serve queue-broker`, backend `turso` | 4801 | `on-failure` | Unauthenticated `GET /healthz` | +| `secrets-broker` | `fleet serve secrets-broker` | 4800 | `on-failure` | `GET /health` (503 until the first successful refresh — that is a state, not a crash; see [Troubleshooting](troubleshooting.md)) | +| `laptop-agent` | `bin/laptop-agent` (its own package, not the fleet binary) | 4799 | `always` | No unauthenticated endpoint; verified through the authenticated client | +| pm stack neighbours | `pm-aggregator`, `pm-projector`, `pm-tunnel`, and the other Cloudflare/pm-stack targets declared in the same `services.nix` registry | per definition | per definition | per definition | + +Operational notes: + +- The queue-broker binds its HTTP surface with the agent token required on every route except `GET /healthz`. Its Turso backend comes up on a startup thread, so `/healthz` and `/validate` answer before the backend is ready; a broker that answers `/healthz` but fails verbs with transport errors is still starting, or its backend token is wrong. +- The secrets-broker binds the laptop tailnet address only on the laptop. Sandbox consumers reach it through the session proxy — except on the sandbox itself, where `fleet init` runs a local loopback copy (next section). +- `laptop-agent` restarts `always` on purpose: under `on-failure`, a clean SIGTERM or success exit leaves the daemon down. Do not "fix" that back. +- `fleet serve` can also run several roles in one process: `fleet serve queue-broker secrets-broker …` parses a multi-role list, capability-checks the **whole list before anything binds** (a role this invocation cannot run stubs the entire list at exit 69, with no partial start), and spawns one thread per role. A role thread's failure fails the process — the supervisor (systemd) restarts the unit. The deployed profiles nonetheless spell one role per unit, so each broker restarts and health-checks independently. + +### `fleet init` in systemd mode (laptop) + +`fleet init` never detached-spawns a daemon systemd owns. For each role in the host manifest it reports the `fleet-.service` state via `systemctl --user is-active`: an active unit is a no-op; an inactive but existing unit is started with `systemctl --user start`; a missing unit is reported and skipped, not an error; unavailable `systemctl` is a report, not a spawn. Roles the manifest disables are reported as skipped with their reason, and the `[domains]` config gate wins over the manifest. + +## The sandbox model: roles spawned by `fleet init` + +A sandbox seat has no systemd ownership of fleet roles. There, `fleet init` uses **spawn mode**, which exists for exactly two roles; any other role in a spawn manifest is reported and skipped, never spawned. `fleet init` also runs session initialisation first; a session error exits 2 before any role work. A build whose usable surface lacks `proxy-serve` can only stub `init` (exit 69). + +1. **proxy (the session proxy / session broker)** — init probes the broker socket and says hello. A live broker, in either protocol dialect, means status plus PATH-shim sync, and nothing more: a strict no-op. Init never spawns over, restarts, or fights an incumbent broker. Only an unanswered socket spawns `fleet serve proxy`, detached, after which init syncs shims from the new broker's services map. +2. **secrets-broker** — init probes its Unix socket; a live answer means status and out. Otherwise it spawns `fleet serve secrets-broker` detached (setsid, output appended to `secrets-broker.log` beside the socket) with `SECRETS_BROKER_BIND=127.0.0.1:4800` set explicitly — and the broker forces loopback itself when the seat's location is the sandbox, so the sandbox broker is loopback-only twice over. Init then waits (50 × 100 ms probes) for the socket to answer before reporting success. + +Two more init behaviours to know: + +- **Report mode.** Given no roles to start, init reports state — every source consulted, plus detected hostname/OS/systemd for the report only (detection never selects roles) — starts nothing, and exits 69. "Never guess-start a role" is the rule. +- **Provision before the binary flip.** `fleet init` resolves location and roles from the `[host]` section of `fleet.toml`. When rolling out a binary that understands a new config shape, write the `[host]` config first, pin the init call site, and only then deploy the binary. Rollback warning: pre-location-aware binaries parse-error on a `fleet.toml` containing `[host]` (strict unknown-field rejection), so config and binary roll back **together**. + +## Restart and health expectations + +- A broker that is down is restarted by its supervisor: systemd on the laptop (per the profile's restart policy), the heal stack on a sandbox seat (see [Health checks and the heal stack](health-and-healing.md)). +- Do not restart-loop a broker that is *up but not serving*. The canonical case is the secrets-broker before its first successful refresh: the process is alive, `/health` answers 503 with `serving=false`, and restarting it only restarts the refresh clock. Diagnose the refresh instead — see [Troubleshooting](troubleshooting.md). +- After any restart, verify with the health surfaces, not with process existence: `/healthz` for the queue-broker, `/health` for the secrets-broker, `fleet queue health` for the queue as a client sees it, and `fleet agent doctor` for the seat as a whole. diff --git a/pkgs/fleet/book/operations/troubleshooting.md b/pkgs/fleet/book/operations/troubleshooting.md new file mode 100644 index 0000000000..49a55c5ac7 --- /dev/null +++ b/pkgs/fleet/book/operations/troubleshooting.md @@ -0,0 +1,70 @@ +# Troubleshooting + +Symptom → cause → fix. Each entry names the check that confirms the cause before you apply the fix. For the health surfaces referenced throughout, see [Health checks and the heal stack](health-and-healing.md); for how the services are run, see [Running the brokers as services](services.md). + +## Session proxy down / "proxy closed during CONNECT" + +- **Symptom:** Fleet commands that need the laptop fail with transport errors (exit 3); proxy connections die during the CONNECT handshake. +- **Cause:** One of the first legs of the heal chain is down: tailscaled, the local relay on port 3130, or the session broker itself. The session proxy is how a sandbox seat reaches the laptop's brokers, so its failure looks like every broker failing at once. +- **Confirm:** `fleet agent doctor` — the queue and shell legs are down while the github leg may still answer. +- **Fix:** Let the heal chain rebuild in order (tailscaled → relay :3130 → session broker → secrets broker → gh); it runs on a roughly 5-minute cron, or re-run the seat's init bring-up. Do not start the session broker by hand ahead of the relay — a broker started before its relay answers but reaches nothing. + +## Secrets broker stuck refreshing (503, very many `bws` fetches) + +- **Symptom:** `fleet secrets get ` fails or reports the broker not serving; `GET /health` on the secrets-broker answers 503 with `serving=false` for a long time; the broker's refresh appears to run constantly (the shape recorded as issue #13081 involves on the order of 220 `bws` fetches in a refresh cycle). +- **Cause:** The broker's full-vault refresh has not yet *succeeded*. `serving` only becomes true once a refresh completes (`last_refresh_unix` is set); a refresh that keeps failing or being restarted keeps the broker in the not-serving state, and `/health` reports `refresh_error` when a refresh has failed. +- **Confirm:** `GET /health` — check `refreshing`, `last_refresh_unix`, and `refresh_error`. A cached read that succeeds carries `source: "cache"` and an `age_seconds`; that tells you the broker once served and how stale the value is. +- **Fix:** Fix the refresh's cause (the `bws` route and its token, by name — never by pasting a value anywhere), then let **one** refresh complete. **Do not restart-loop the broker:** every restart discards refresh progress and restarts the clock, converting a slow recovery into a permanent 503. A process that is alive and returning 503-with-`serving=false` is in a known state, not crashed. + +## Queue double-serve: a parked, completed, or cancelled task is served again (#13091) + +- **Symptom:** A task whose issue record shows it parked, completed, or cancelled is handed out by `fleet queue claim` as if it were live work. +- **Cause:** The broker-side state and the GitHub issue record have diverged; the broker re-served a task whose terminal or parked disposition lives in the issue record. Recorded as issue #13091. +- **Confirm:** Read the task (`fleet queue show `) and the GitHub issue. Treat **the issue record as the source of truth** for disposition. +- **Fix (workaround):** Re-park the task (`fleet queue park `) so the broker state matches the record, and note the double-serve on the issue. Do not work the task a second time, and do not complete it "again" — a duplicate completion corrupts the lane ledger. The no-double-serve guard (the client checking a fresh claim against the GitHub fallback and holding it with reason-class `fallback_held`, exit 5) covers the claim path it can see; a re-serve that bypasses it is the bug, not operator error. + +## Stub: exit 69 + +- **Symptom:** A command prints a three-line block to stderr and exits 69, without doing any work. +- **Cause:** The domain is not usable in this invocation. Exit 69 is `EX_UNAVAILABLE`: the stub is the binary working as designed, not a crash. The first line decodes which of the four wordings you got: + 1. *"this build does not include '<domain>'"* — **NotInBuild**: the capability was never compiled into this variant (for example, asking `fleet-connect` for the queue). + 2. *"invoked as '<name>', this build does not include '<domain>'"* — **NarrowedByName**: the binary has the domain, but the hyphenated argv0 profile narrowed it out. Re-invoke as plain `fleet`. + 3. *"'<domain>' is disabled by config on this host"* — **DisabledByConfig**: the `[domains]` table in this host's `fleet.toml` disables it. The stub names the config file; re-enable it there if the disable is not a deliberate incident lever. + 4. *"'<domain>' is included in this build but not implemented yet"* — **Available-form**: compiled in, nothing behind it. +- **Confirm:** `fleet capabilities` — the domain's `state` field says the same thing in JSON (`not-in-build`, `narrowed-by-name`, `disabled-by-config`, `available`), and the second stub line lists the capabilities this invocation *can* use. +- **Fix:** Match the wording: use the full build, invoke as `fleet`, or re-enable in config. Never "fix" a stub by reinstalling — the install is telling you the truth about itself. + +## GitHub rate limits: user token versus the App route + +- **Symptom:** `gh` calls (direct or via `fleet gh`) fail with rate-limit errors — `rate limit`, `rate_limit`, `too many requests`, HTTP 429. +- **Cause:** The token that made the call exhausted its bucket. The user (personal) token and the GitHub App installation tokens are separate buckets with separate limits. +- **How `fleet gh` handles it:** `fleet gh` rotates credentials in a fixed order — the personal token first, then the fleet App's installations, then the developing.today App's, then the backup App's — and a rate-limit (or permission) failure is one of the two classes that may be retried under the next token, because the limiter refuses the request *before* it is processed, so replaying a write is safe. Other failure classes are retried under a fresh token only for read-only calls. +- **Fix:** Prefer `fleet gh` over plain `gh` for fleet work so rotation applies. If you hit a limit on plain `gh`, switch routes rather than retrying in a loop — a rate-limited write that cannot go through the CLI route belongs in the creation outbox, which paces creates and backs off on consecutive rate limits (300 s, up to its attempt budget) instead of hammering. Check which route you are on with `fleet agent doctor` (the github leg reports `route: "fleet"` or `"plain"`). + +## Claim rejected: lane/worker mismatch (#6853 shape) + +- **Symptom:** Holder verbs (`heartbeat`, `checkpoint`, `park`, `release`, `block`, `fail`, `complete`) fail with exit 5 and a "no matching claimed row" error, although the task is visibly claimed. +- **Cause:** The broker checks the holder by worker **and lane**: all scheduled lanes share one worker id, so the lane is what tells the broker whose claim a verb acts on. A verb issued with the wrong `--lane` (or a lane from a different registered lane/worker family — the `registered_lane_worker` families of issue #6853) does not match the claimed row. +- **Confirm:** Compare the claim's lane and worker (`fleet queue show `, the claim output) with what your command resolved: `--lane` flag, else the `REPO_QUEUE_LANE` environment variable, else null (broker checks the worker alone). Also confirm the row is non-terminal — the same exit 5 covers "already terminal". +- **Fix:** Re-issue with the claiming lane (`--lane `) and the claiming worker. Do not release and re-claim to work around it; that churns the lease and the timeline. + +## TLS `UnknownIssuer` from sandbox seats (#13122) + +- **Symptom:** HTTPS calls from a sandbox seat fail certificate validation with an `UnknownIssuer` error, while `gh` itself works. +- **Cause:** The sandbox's egress proxy intercepts TLS. A client validating against the webpki root store alone does not trust the interception chain; the platform root store does. (This is why `fleet gh`'s App legs validate against the platform root store rather than webpki roots alone.) +- **Confirm:** The same call succeeds through `gh` or through a platform-store client, and fails only from the webpki-only client. Recorded as issue #13122. +- **Fix:** Use the route that validates against the platform store (`fleet gh` for GitHub API work). Do not disable certificate verification anywhere as a workaround — an unverified channel for fleet credentials is worse than the outage. + +## Lease expiry mid-work + +- **Symptom:** Work you are holding is claimed by someone else, or your next `heartbeat` / `complete` fails with exit 5 ("no matching claimed row"). +- **Cause:** A claim is a lease, not a lock. Every claim first runs lease expiry opportunistically: abandoned claims whose lease lapsed become claimable at the moment anyone looks. If your heartbeats stopped (a stalled session, a long silent build), the lease lapsed and the task returned to the pool. +- **Confirm:** `fleet queue timeline ` shows the expiry and any re-claim. Check the lease length you claimed with against the gap in your heartbeats. +- **Fix:** Prevention, not recovery: heartbeat on a cadence well inside the lease, and checkpoint before long silent operations. If the task was re-claimed, coordinate through the issue record before touching it again — two workers on one task is the failure this system exists to prevent. If nobody re-claimed it, claim it again and continue. + +## `verify-disposition` gate rejections at `complete` + +- **Symptom:** `fleet queue complete` rejects the completion and **leaves the task claimed**, with a message naming a defect in the disposition record. +- **Cause:** Completion of a fix-class task requires a verified disposition: the readback record produced by `fleet queue verify-disposition --repo `, which reads the issue and its linked PRs back from GitHub live. The broker's gate is pure (no network) and checks: the record's freshness (≤ 1800 s old by default; more than 300 s in the future is unreadable clock skew), that it describes *this* task's issue, that the verdict matches the readback (for example `merged_verified` requires at least one merged pull in the readback), that every PR the completion links appears in the readback, and any follow-up (a follow-up issue must be open, not the issue being completed, and must link the completed issue and every unfinished PR; a successor PR must be in the readback and merged; a follow-up task is checked broker-side for a live status naming the same issue). +- **Confirm:** Run the verb standalone — `fleet queue verify-disposition --repo --json` exits 0 when its record would pass the gate and 1 when the gate would reject it, so you can iterate without touching the claim. +- **Fix:** Address the named defect — most often a stale record (re-run `verify-disposition` and complete promptly), a verdict the readback does not support (the work is not actually in the state claimed; finish or follow up the work first), or a missing follow-up for the `open_draft_with_followup` / `open_draft_superseded` verdicts (record the follow-up with `--reason`, which any follow-up target requires). The gate leaving the task claimed is deliberate: a rejected completion loses no work. diff --git a/pkgs/fleet/book/reference/agent.md b/pkgs/fleet/book/reference/agent.md new file mode 100644 index 0000000000..73e87b330c --- /dev/null +++ b/pkgs/fleet/book/reference/agent.md @@ -0,0 +1,310 @@ +# fleet agent + +`fleet agent` is the agent's front door: enrol an agent of any kind, check what this seat reaches, and take the next piece of work down the intake ladder. The fleet already has the legs — bridge mailboxes, the queue, the laptop transport, GitHub, secrets by name; what a new kind of agent lacked was one place to enroll, check its seat, and take work. `fleet agent` is that place. Its sibling domain [fleet shell](shell.md) rides on the same `agent` capability — there is no separate `shell` capability atom. + +Every verb prints **one JSON object**. Exit codes for the domain: `0` ok · `2` usage · `3` a needed leg is down · `5` no work on any rung (`next` only). + +See also [Agents: enrolment, doctor and the intake ladder](../concepts/agents.md) and [fleet bridge](bridge.md). + +Known discrepancy: every per-verb help invocation returns **one shared USAGE text** for the whole domain — there is no per-verb help in source. The per-verb sections below are written from source semantics. + +## fleet agent kinds + +``` +fleet agent kinds +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments and no flags. | + +### Behaviour + +Prints the kind table as JSON: for each kind its name, summary, bridge groups, seat, and enrolment note, plus the three seat definitions. A kind says three things: which bridge groups it joins, how it reaches the fleet from where it runs, and what to tell it at enrolment. Adding a kind is adding a row; no verb changes. The 16 kinds: + +| Kind | Groups | Seat | Note (abridged) | +|---|---|---|---| +| `muse` | muse | binary | Fresh Muse gets a bridge-capable static build from `scripts/muse/bootstrap.sh`; older installs run the same commands on the laptop install via `~/tools/laptop-ssh.sh` | +| `opencode` | opencode | binary | Runs on the laptop seat, so every leg is local | +| `openchamber` | opencode, openchamber | binary | Joins `opencode` too, so `group:opencode` reaches both pipelines | +| `openclaw` | openclaw | binary | — | +| `claude-code` | claude-code | binary | A cloud session has no tailnet: messaging and the priority rung work over HTTPS; builds go through `fleet shell` | +| `codex` | codex | binary | — | +| `gemini` | gemini | binary | — | +| `antigravity` | antigravity | binary | — | +| `grok` | grok | binary | A bot with no shell enrolls as kind `http` under the same name and groups | +| `dot` | dot | http | `pkgs/dot-bridge` carries its Slack and ChatGPT transports; the mailbox is the same store | +| `duet` | duet | http | — | +| `claude` | (none) | connector | Fixed bridge address `claude`; set a wake hook for channel:claude so a send starts a session | +| `chatgpt` | (none) | connector | Fixed address `chatgpt`; woken by its MCP Events subscription | +| `laptop` | laptop | binary | A job or service on the fleet laptop | +| `http` | (none) | http | Anything that can make an HTTPS request and nothing else | +| `generic` | (none) | binary | Any other agent with a shell — the fallback `enroll` names in its unknown-kind error | + +Seats: **binary** = has a shell and runs the fleet binary itself (`enroll`, then `next`); **http** = no shell of its own, speaks the bridge's fleet routes over HTTPS (`scripts/fleet/bridge-mailbox.py` is the reference client) and gets work from its mailbox; **connector** = a chat assistant with the Message Bridge connector attached — it has a channel address, not a mailbox. + +### Exit codes + +`0` ok · `2` usage. + +### Example + +```console +$ fleet agent kinds +``` + +Prints all 16 kinds with their groups, seats, and enrolment notes as one JSON object. + +## fleet agent enroll + +``` +fleet agent enroll --kind K --name N [--groups a,b] [--dry-run] [--profile PATH] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--kind` | `K` | required | One of the 16 kinds (see `kinds`). An unknown kind is a usage error listing all kinds, with "use generic for anything with a shell". | +| `--name` | `N` | required | The agent's name (its bridge mailbox name). The shared USAGE spells this `--name`; the domain help line abbreviates it as the enroll line's second value. | +| `--groups` | `a,b` | kind's built-in groups | Additional bridge groups; adds to the kind's groups, never replaces them. | +| `--dry-run` | — | off | Probe nothing and register nothing. | +| `--profile` | `PATH` | default profile path | Where to save the profile. | + +### Behaviour + +Registers an agent and saves its profile. Flow: the kind is validated; `--groups` adds to the kind's built-in groups; for a binary/http seat the bridge leg is probed in **Register** mode — `bridge hello` with the name and groups, which is what actually registers the mailbox; connector kinds instead get the "attach the connector" instruction and a fixed channel address. The four legs are probed (see `doctor`) and the saved profile records agent, kind, groups, and leg state. + +The JSON answer carries: the profile, `registered` (true only when not a dry run *and* the bridge leg answered), the legs, the **rungs** map, and seat-specific next-step lines — for a binary seat the run loop (`fleet agent next --agent `, do the task, run its `then` lines, repeat while the run has budget) and the `fleet shell` line ("runs where builds belong; never build in a limited sandbox"); for an http seat the token-by-name note and the reference-client commands; for central, the `fleet bridge send --to

[--command]` lines. + +### Exit codes + +`0` — a dry run, or any intake rung is live. `2` — usage (including an unknown kind). `3` — no intake rung is live. + +### Example + +```console +$ fleet agent enroll --kind generic --name worker-1 +``` + +Registers `worker-1`, probes its four legs, and saves its profile with the run-loop instructions. + +## fleet agent doctor + +``` +fleet agent doctor [--agent N] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--agent` | `N` | profile / `$FLEET_AGENT` | Agent name to probe the bridge leg as. With no name known, the bridge leg is reported not ok even when the service answers. | + +### Behaviour + +Checks which legs answer from this seat. **The four legs are `bridge`, `queue`, `github`, `shell`** — there is no secrets leg; secrets is folded into the bridge leg's stated need ("HTTPS to the message bridge, and the fleet token by name through fleet secrets"). The four probes are independent and are issued **together** (one parallel call), each a real fleet verb run as this seat: + +| Leg | Probe | "Up" detail | What it needs | +|---|---|---|---| +| bridge | `bridge hello` (enroll) / `bridge inbox --agent A --limit 1` (doctor with a name) / `bridge health` (no name known) | "registered" / "the mailbox answers" | HTTPS to the bridge + the fleet token by name through fleet secrets | +| queue | `queue health` | "answers" | The queue broker: its socket on the laptop, or the laptop transport from elsewhere | +| github | `gh api rate_limit` via `fleet gh`; if that fails, plain signed-in `gh api rate_limit` | "answers", with `route: "fleet"` or `"plain"` recorded | `gh` with a token: fleet gh's rotation, or a signed-in gh | +| shell | `laptop-agent health` | "the laptop answers" | A route to the laptop: its broker, the Cloudflare tunnel, the tailnet or ssh | + +Doctor's bridge probe with a known agent is a **read that takes nothing** (`inbox --limit 1`): service health alone proves nothing about whether this seat holds the fleet token, so only a call made *as* an agent counts. With no agent name, the bridge leg is reported **not ok** even when the service answers ("the service answers, but no agent name is known to read a mailbox with: enrol, or pass --agent"). + +From the legs, doctor derives the **rungs** map — which intake rungs this seat still has: `push` = bridge leg, `queue` = queue leg, `shortlist` = **always true** (it is a local file), `priority` = github leg. The answer also reports `builds`: "fleet shell reaches the laptop" when the shell leg answers, else "fleet shell has no laptop route from here; it will try a codespace, then run here". + +### Exit codes + +`0` — any intake rung is live (bridge, queue or github). `2` — usage. `3` — no intake rung is live. + +### Example + +```console +$ fleet agent doctor --agent archer +``` + +Probes all four legs in parallel and prints the legs, the rungs map, and the builds line as one JSON object. + +## fleet agent next + +``` +fleet agent next [--agent N] [--lane L] [--repo OWNER/NAME] [--low-water N] [--shortlist PATH] [--platform P] [--pool P] [--remaining-budget-minutes N] [--filter EXPR] [--queue Q] [--no-push] [--no-queue] [--no-shortlist] [--no-priority] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--agent` | `N` | profile / `$FLEET_AGENT` | Agent taking the work. | +| `--lane` | `L` | derived from the agent name | Queue lane for the queue rung's claim. | +| `--repo` | `OWNER/NAME` | `developing-today/code` | Repo the priority/shortlist rungs draw from. | +| `--low-water` | `N` | `3` | Shortlist low-water mark for this call. | +| `--shortlist` | `PATH` | profile/state default | Shortlist file path. | +| `--platform` | `P` | — | Carried into the queue claim. | +| `--pool` | `P` | — | Carried into the queue claim. | +| `--remaining-budget-minutes` | `N` | — | Carried into the queue claim. | +| `--filter` | `EXPR` | — | Carried into the queue claim. | +| `--queue` | `Q` | — | Queue name for the queue rung's claim. | +| `--no-push` | — | off | Skip rung 1 (recorded as `skipped` in `tried`). | +| `--no-queue` | — | off | Skip rung 2. | +| `--no-shortlist` | — | off | Skip rung 3. | +| `--no-priority` | — | off | Skip rung 4. | + +### Behaviour + +Tries four rungs **in order** and returns the first that yields work. A rung that is *down* (bridge unreachable, broker not answering) is not the same as a rung that is *empty*: down rungs are recorded and skipped, so a seat with only HTTPS still gets work from rungs 1 and 4. Every answer is `{agent, rung, task, then, tried}` — `tried` is the per-rung log (`skipped`/`empty`/`down`/`rejected` with a why), and `then` is the list of follow-up commands the runner should execute for the handed-out task. + +1. **Push** — a command addressed to this agent on the bridge (`bridge inbox --commands --take`). This rung outranks everything: a command a person (or central) pushed is work already chosen. +2. **Queue** — a claim on the one fleet queue (`queue claim` with the agent's lane; the lane defaults from the agent name — known lane families are validated by the queue, and a lane registered to a shared queue worker is honoured). `next` claims with a **4-hour lease** (14400 s, overriding the queue's 45-minute default, which lapses mid-task) and the task's `then` lines name the lease deadline plus the `queue checkpoint` / `queue complete` commands with the claimed worker/lane. A broker refusal that is really a lane verdict (lane bound to another queue, registration did not land) is reported as rung `rejected`, distinct from `down`. +3. **Shortlist** — the top of this host's local shortlist: entries are re-checked against GitHub before hand-out (an issue closed, assigned or owner-parked since listing is dropped with a named why), then handed out in rank order. **Refill switch:** if the list is at or below low-water with nobody refilling, `next` does not hand out a stale remnant — it returns rung **`refill`** instead, a purpose-switch task (`purpose: "refill-shortlist"`, target 8) whose instructions and `then` lines are the `shortlist fill` / `shortlist add` commands. One run refills; the marker it leaves keeps the rest working. +4. **Priority** — the highest-priority open issue straight from GitHub. Label queries run soonest-first over the priority label family (`priority/critical`, then `priority/high`, … — the same ordering as the shortlist ranks); candidates are filtered (owner-parked labels — `user/owned`, `user/review`, `user/escalated` class — are kept out), and the winner is **reserved into the shortlist file** as it is handed out, so two seats on one host do not take the same issue. + +### Exit codes + +`0` — a rung yielded work. `2` — usage. `3` — a needed leg is down (domain-level). `5` — **no work on any rung**. + +### Example + +```console +$ fleet agent next --agent archer +{"agent": "archer", "rung": "queue", "task": {…}, "then": […], "tried": […]} +``` + +Returns the first available work down the ladder, with the follow-up commands in `then`. + +## fleet agent shortlist status + +``` +fleet agent shortlist status [--low-water N] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--low-water` | `N` | `3` | Low-water mark for the `low` computation. | +| `--shortlist` | `PATH` | profile/state default | Shortlist file path (shared shortlist flag). | + +### Behaviour + +Reports the local list `next` draws on: a JSON file on this host, guarded by a lock file (stale after 30 s). Entries are `{repo, issue, title, rank, why, added_at}` plus handed-out records and an optional refill marker. `status` prints the list, its count, `low` (count ≤ low-water — so a list of exactly 3 is already low), and the refill state. Defaults: low-water **3**, target **8**. + +Ranks (lower is sooner): `expedite` → 0, `priority/critical` → 1, `now` → 2, `priority/high` → 3, `next` → 4, `priority/normal` → 5, anything else **unranked = 6**. Hand-out order is lowest rank, then oldest `added_at`, then lowest issue number. + +### Exit codes + +`0` ok · `2` usage · `3` a needed leg is down. + +### Example + +```console +$ fleet agent shortlist status +``` + +Prints the entries, the count, whether the list is low, and the refill state. + +## fleet agent shortlist take + +``` +fleet agent shortlist take +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--shortlist` | `PATH` | profile/state default | Shortlist file path (shared shortlist flag). This verb takes no verb-specific flags. | + +### Behaviour + +Hands out the soonest entry to this agent — the same selection `next` rung 3 uses (lowest rank, then oldest, then lowest issue number). A handed-out issue is kept from being handed out again on this host for **2 h** (7200 s); pruning drops expired handed records and expired refill markers. + +### Exit codes + +`0` ok · `2` usage · `3` a needed leg is down · `5` no work (empty list) by the domain's `next`-family convention. + +### Example + +```console +$ fleet agent shortlist take +``` + +Hands out the soonest shortlist entry as one JSON object. + +## fleet agent shortlist clear + +``` +fleet agent shortlist clear +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--shortlist` | `PATH` | profile/state default | Shortlist file path (shared shortlist flag). This verb takes no verb-specific flags. | + +### Behaviour + +Empties the list and clears the refill marker. + +### Exit codes + +`0` ok · `2` usage. + +### Example + +```console +$ fleet agent shortlist clear +``` + +Empties the local shortlist and clears any live refill marker. + +## fleet agent shortlist add + +``` +fleet agent shortlist add --issue N --title T [--repo R] [--rank N] [--why TEXT] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--issue` | `N` | required | Issue number to add. | +| `--title` | `T` | required | Issue title recorded on the entry. | +| `--repo` | `R` | `developing-today/code` | Repository the issue belongs to. | +| `--rank` | `N` | `6` (unranked) | Rank for hand-out order (see `status` for the rank table). | +| `--why` | `TEXT` | — | Why this entry was listed. | +| `--shortlist` | `PATH` | profile/state default | Shortlist file path (shared shortlist flag). | + +### Behaviour + +Adds one entry `{repo, issue, title, rank, why, added_at}`. Duplicates (same repo+issue already listed) are refused — the add returns false rather than listing the issue twice. + +### Exit codes + +`0` ok · `2` usage. + +### Example + +```console +$ fleet agent shortlist add --issue 13165 --title "Write the fleet book" --rank 1 +``` + +Adds issue 13165 at rank 1 (`priority/critical` rank). + +## fleet agent shortlist fill + +``` +fleet agent shortlist fill [--repo R] [--target N] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--repo` | `R` | `developing-today/code` | Repository to draw candidates from. | +| `--target` | `N` | `8` (clamped 1–50) | Top the list up to this many entries. | +| `--shortlist` | `PATH` | profile/state default | Shortlist file path (shared shortlist flag). | + +### Behaviour + +Tops the list up to target from the priority candidates: it fetches **2× target** candidates from GitHub (the same candidate scan as `next` rung 4), adds them in rank order until the target is met, records the fill (so a just-filled list suppresses an immediate second refill), and clears the refill marker. Refill bookkeeping: a refill marker `(by, at)` lasts **30 min** (1800 s); a list needs refill when it is low, no marker is live, and no fill finished within the window. + +### Exit codes + +`0` ok · `2` usage · `3` a needed leg is down (GitHub unreachable). + +### Example + +```console +$ fleet agent shortlist fill +``` + +Tops the local shortlist up to 8 entries from the priority candidates. diff --git a/pkgs/fleet/book/reference/bridge.md b/pkgs/fleet/book/reference/bridge.md new file mode 100644 index 0000000000..fd7fca4a5a --- /dev/null +++ b/pkgs/fleet/book/reference/bridge.md @@ -0,0 +1,258 @@ +# fleet bridge + +`fleet bridge` is the mailbox client for the message bridge (at `https://bridge.security.cab`). Every fleet agent has a **mailbox** on the bridge named after it, and registers with optional **groups** (`muse`, `code-lanes`, …). Central sends a message or a command to one agent, a group, or all; the agent reads its mailbox, does the work, and posts its answer back, which marks the command handled. + +See also [The bridge: fleet messaging](../concepts/bridge.md). + +Known discrepancy: every per-verb help invocation returns **one shared USAGE text** for the whole domain — there is no per-verb help in source, despite the domain status line "(options: fleet bridge <command> --help)". The per-verb sections below are written from source semantics. + +## Tokens, URLs, and defaults (all verbs) + +Two token families, both resolved **by name** through fleet-secrets; values are never printed, logged, or put in argv: + +| Family | Secret name | Opens | URL shape | +|---|---|---|---| +| Owner token (central verbs) | `message-bridge.access-token` (renamable via `[bridge] owner_token_name`) | `send`, `agents`, `log` | `/api//fleet/…` | +| Fleet token (agent verbs) | `message-bridge.fleet-token` | `hello`, `inbox`, `post`, `ack` — agent routes only; it cannot send commands | `/fleet//…` | + +Tokens travel **in the URL path**, so every error string is scrubbed of token values (``) before it is printed, and a 404 is reported as "a wrong token, an old bridge without fleet mailboxes, or a wrong URL". Plain `http` URLs are accepted only to this machine; anything else must be `https`, because tokens ride the path. + +Derivation fallback: when the fleet token's secret is missing but the owner token resolves (the laptop seat), the fleet token is **derived from the owner token exactly as the bridge derives it**: `base64url(HMAC-SHA256(key = owner token bytes, message = "message-bridge/fleet-token/v1"))`. The derived value is used in-process only; it is never written anywhere. + +Defaults: the agent name defaults to `$FLEET_AGENT`, then `[bridge] agent`; groups to `$FLEET_AGENT_GROUPS`, then `[bridge] groups`; the bridge URL to `$FLEET_BRIDGE_URL`, then `[bridge] url`, then `https://bridge.security.cab` (env beats file throughout). Output is the bridge's JSON, passed through. + +Exit codes for every verb unless noted: `0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request (its JSON error goes to stderr). + +## fleet bridge send + +``` +fleet bridge send --to [--command] [--sender NAME] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--to` | `` | required | Targets: `agent:` (or a bare name), `group:`, `all`. Repeat `--to` or comma-separate. | +| `--command` | — | off (plain message) | Mark the send as a command. | +| `--sender` | `NAME` | — | Sender name recorded on the message. | +| `` (positional) | text | required | Message text; `-` reads it from stdin. | + +### Behaviour + +Central verb (owner token). Sends a message — or, with `--command`, a command — to one agent, a group, or all agents. Route: `POST /api//fleet/send`. A command sits in the target mailboxes until an agent takes it (see `inbox --take`) and posts an answer back, which marks it handled. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge send --to group:muse --command "run the nightly triage" +``` + +Sends a command to every agent in the `muse` group. + +## fleet bridge agents + +``` +fleet bridge agents +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments and no flags. | + +### Behaviour + +Central verb (owner token). Lists the registered agents, their groups, and unread counts. Route: `GET /api//fleet/agents`. The bridge's agent registry is exactly the set of agents that have said `hello` (name, groups, last-seen, unread counts). + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge agents +``` + +Prints the registered agents, groups, and unread counts as the bridge's JSON. + +## fleet bridge log + +``` +fleet bridge log [--agent A] [--direction inbound|outbound] [--kind message|command] [--since-id N] [--before-id N] [--limit N] [--order asc|desc] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--agent` | `A` | — | Filter to one agent. | +| `--direction` | `inbound\|outbound` | — | Filter by direction. | +| `--kind` | `message\|command` | — | Filter by kind. | +| `--since-id` | `N` | — | Only rows after this id. | +| `--before-id` | `N` | — | Only rows before this id. | +| `--limit` | `N` | bridge default | Maximum rows. | +| `--order` | `asc\|desc` | bridge default | Row order. | + +### Behaviour + +Central verb (owner token). Reads the central message log. Route: `GET /api//fleet/messages?…` with the filters as query parameters. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge log --kind command --limit 5 +``` + +Shows the five most recent commands in the central log. + +## fleet bridge hello + +``` +fleet bridge hello [--agent A] [--groups g1,g2] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--agent` | `A` | `$FLEET_AGENT`, then `[bridge] agent` | Agent name to register. | +| `--groups` | `g1,g2` | `$FLEET_AGENT_GROUPS`, then `[bridge] groups` | Comma-separated groups to join. | + +### Behaviour + +Agent verb (fleet token). Registers / refreshes this agent and its groups — this is the registry write: the bridge's agent registry is exactly the set of agents that have said hello. Route: `POST /fleet//hello` with `{agent, groups}`. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge hello --agent archer --groups muse +``` + +Registers `archer` in the `muse` group (or refreshes an existing registration). + +## fleet bridge inbox + +``` +fleet bridge inbox [--agent A] [--groups g1,g2] [--commands | --messages] [--all] [--since-id N] [--limit N] [--take] [--wait SECS] [--interval SECS] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--agent` | `A` | `$FLEET_AGENT`, then `[bridge] agent` | Mailbox to read. | +| `--groups` | `g1,g2` | `$FLEET_AGENT_GROUPS`, then `[bridge] groups` | Groups whose mail is included. | +| `--commands` | — | off | Only commands. Mutually exclusive in effect with `--messages`. | +| `--messages` | — | off | Only plain messages. | +| `--all` | — | off (unread only) | Include read messages as well as unread. | +| `--since-id` | `N` | — | Only rows after this id. | +| `--limit` | `N` | bridge default | Maximum rows. | +| `--take` | — | off | Mark what this call returns as read. | +| `--wait` | `SECS` | off | Poll until something arrives or SECS pass (capped at 24 h in source). | +| `--interval` | `SECS` | `15` | Poll interval while waiting. | + +### Behaviour + +Agent verb (fleet token). Reads this agent's mailbox: unread by default; `--all` includes read ones; `--take` marks what it returns as read; `--wait` polls (default interval 15 s) until something arrives or SECS pass. Route: `GET /fleet//inbox?…`. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge inbox --agent archer --commands --take +``` + +Takes this agent's unread commands, marking them read as they are returned. + +## fleet bridge post + +``` +fleet bridge post [--agent A] [--reply-to ID] [--to ADDR] [--instruction | --kind K] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--agent` | `A` | `$FLEET_AGENT`, then `[bridge] agent` | Posting agent. | +| `--reply-to` | `ID` | — | Answer that row (and mark it read). | +| `--to` | `ADDR` | central | Send to any address instead: `drew`, `claude`, `chatgpt`, `connectors`, `agent:` (or a bare name), `group:`, `agents`, `all`. Repeat or comma-separate. | +| `--instruction` | — | off | Make it an instruction. Requires `--to`. | +| `--kind` | `K` | — | Kind override; `--kind instruction` is equivalent to `--instruction`. | +| `` (positional) | text | required | Message text; `-` reads it from stdin. | + +### Behaviour + +Agent verb (fleet token). Posts a message to central by default; with `--reply-to` it answers that row (and marks it read) — posting an answer back is what marks a command handled. Route: `POST /fleet//send`. + +### Exit codes + +`0` ok · `2` usage (including `--instruction` without `--to`) · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge post --agent archer --reply-to 412 "nightly triage done: 3 issues filed" +``` + +Answers message 412 and marks it read. + +## fleet bridge ack + +``` +fleet bridge ack [--agent A] (--up-to ID | ID...) +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--agent` | `A` | `$FLEET_AGENT`, then `[bridge] agent` | Agent whose mailbox to ack in. | +| `--up-to` | `ID` | — | Mark every message up to this id read. Alternative to listing ids. | +| `ID...` (positional) | ids | — | Mark exactly these messages read. | + +### Behaviour + +Agent verb (fleet token). Marks messages read without posting an answer. Route: `POST /fleet//ack`. + +### Exit codes + +`0` ok · `2` usage (neither `--up-to` nor any id) · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge ack --agent archer --up-to 412 +``` + +Marks all of `archer`'s messages up to id 412 as read. + +## fleet bridge health + +``` +fleet bridge health +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments and no flags, and **no token**. | + +### Behaviour + +Reads the bridge's `/healthz`, **unauthenticated** — the only bridge verb that needs no token. It proves the service answers; it proves nothing about whether this seat holds a usable token (that is what `fleet agent doctor`'s bridge leg checks, with a real mailbox read). + +### Exit codes + +`0` ok · `2` usage · `3` transport · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge health +``` + +Prints the bridge's health JSON. diff --git a/pkgs/fleet/book/reference/builtins.md b/pkgs/fleet/book/reference/builtins.md new file mode 100644 index 0000000000..e25c0d2a4e --- /dev/null +++ b/pkgs/fleet/book/reference/builtins.md @@ -0,0 +1,196 @@ +# Built-in commands + +The `fleet` binary has five root built-in commands that belong to no domain: `init`, `session bind`, `version`, `capabilities`, and `help`. They are available in every build variant (`fleet`, `fleet-serve`, `fleet-connect`) because they describe the binary and its registry rather than any domain's work. + +Two rules govern all five, without exception: + +- **Built-ins take no arguments.** A trailing argument is a usage error naming it, exit 2 — never silently discarded. That rule includes `--help`: `fleet version --help` and `fleet capabilities --help` are errors, not help, and `fleet help --help` answers `error: no domain named '--help'`. This is the opposite of the leaf-verb convention elsewhere in the binary, where ` --help` prints that verb's usage and exits 0. +- **Bare `fleet` is an error.** With no subcommand at all, the binary prints a missing-subcommand message and the full help to stderr and exits 2. `fleet --help`, `fleet -h`, and `fleet help` (exactly one word) print the registry help and exit 0. `fleet --version` and `fleet -V` print the short version form (see `version` below). + +A domain an invocation cannot use answers with a stub on stderr and exit 69 (`EX_UNAVAILABLE`). There are four stub wordings, one per reason class: the domain is not in this build, the invocation name (`fleet-serve` / `fleet-connect`) narrowed the surface away, the `[domains]` table in fleet config disabled the domain on this host, or the domain is included but not yet implemented. Every stub's second line is `Enabled capabilities: ` (`none` when empty). Help marks unavailable domains inline — `[not in this build]`, `[narrowed out by this name]`, `[disabled by config]` — but prints the full registry on every variant: every build knows every domain. + +Config resolution lives in one place (`fleet-config`): environment overrides (`FLEET_CONFIG`, `FLEET_BROKER_SOCKET`) beat the config file (`$FLEET_CONFIG`, else `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`), which beats compiled-in defaults. A missing file is not an error; a malformed file — including unknown sections or keys — is a loud error on every path, never a silent fallback. + +Sources: [fleet main.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet/src/main.rs), [fleet-registry](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-registry/src/lib.rs), [fleet-config](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-config/src/lib.rs), [fleet-proxy client](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-proxy/src/client.rs), [session state](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet/src/session_state.rs). + +## fleet init + +```text +Usage: fleet init +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| _(none)_ | — | — | `init` takes no arguments and no flags. Any trailing argument is a usage error, exit 2. The identical command is also spelled `fleet proxy init`; both spellings resolve to one implementation. | + +**Behaviour.** `fleet init` autostarts this host's fleet roles if they are not running, per the `[host]` manifest. It first runs session initialisation (see `session bind` below); a session error is exit 2 before any role work. The capability ladder applies before anything else: a build whose usable surface lacks `proxy-serve` can only stub `init`, exit 69. + +The manifest resolution order is: + +1. **`FLEET_HOST_CONFIG`** — a complete inline `[host]` manifest; wins outright. A manifest with no location is a loud error. +2. **`FLEET_LOCATION`** — names the location; roles come from the config file's `[host]` section only if the file's location matches, else from the built-in map. +3. **The config file's `[host]` section** — `location`, `init_mode`, and `[host.roles]`; the role set is exactly the key set of the roles table, and an unknown role name is a loud parse error, never silently ignored. + +Only two built-in locations exist today; a future lab node provisions its own `[host]` section instead of growing the table: + +| Location | init_mode | Roles | +|---|---|---| +| `sandbox` | spawn | `proxy`, `secrets-broker` | +| `laptop` | systemd | `laptop-agent`, `queue-broker`, `search`, `secrets-broker` | + +The full `[host]` role vocabulary is five names — `proxy`, `queue-broker`, `secrets-broker`, `search`, `laptop-agent` — a superset of the serve roles (it includes `laptop-agent`, which is not a serve role). + +- **Unknown location** (no manifest from any source, or a location with no roles): init reports state — every source consulted, plus detected hostname/OS/systemd for the report only (detection never selects roles) — starts nothing, and exits 69. It never guess-starts a role. +- **Manifest skips and the kill switch:** roles the manifest itself disables (`enabled = false`) are reported as skipped with their reason; then the `[domains]` gate is applied and wins over the manifest (the proxy role keys on the `proxy` domain, the daemon roles on `serve`). +- **`spawn` mode (sandbox):** spawn semantics exist for exactly two roles; any other role in a spawn manifest is reported and skipped, never spawned. + - *proxy:* probe the broker socket and say hello. A live broker (either protocol dialect) means status plus PATH-shim sync and out — a strict no-op: never a spawn, never a restart; init never fights an incumbent broker. Only an unanswered socket spawns `fleet serve proxy` detached, then reports what it started and syncs shims from the new broker's services map. + - *secrets-broker:* probe its Unix socket; a live answer means status and out. Otherwise spawn `fleet serve secrets-broker` detached (output appended to `secrets-broker.log` beside the socket) with `SECRETS_BROKER_BIND=127.0.0.1:4800` set explicitly — and the broker forces loopback itself when `FLEET_LOCATION=sandbox`, so the sandbox broker is loopback-only twice over. Init then waits (50 × 100 ms probes) for the socket to answer before reporting success. +- **`systemd` mode (laptop):** init never detached-spawns a daemon systemd owns. For each role it reports `fleet-.service` state via `systemctl --user is-active`; an active unit is a no-op; an inactive but existing unit is started via `systemctl --user start`; a missing unit is reported and skipped, not an error; unavailable systemctl is a report, not a spawn. + +Exit codes: 0 ok (including the all-roles-already-running no-op) · 2 usage error or session-initialisation error · 69 capability stub, or unknown location (starts nothing). + +```text +$ fleet init +proxy: running (broker socket answers; shims synced) +secrets-broker: running (socket answers) +$ echo $? +0 +``` + +## fleet session bind + +```text +Usage: fleet session bind [--session-id ID] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--session-id` | session id | resolved (see Behaviour) | The explicit session identity to validate and persist. Both `--session-id ID` and `--session-id=ID` spellings are accepted; at most one value — a second value is the usage error shown in the help dump. | + +**Behaviour.** `fleet session bind` validates and persists this worktree's session identity. The identity is an OpenCode session id of the form `ses_` followed by ASCII letters and digits — anything else fails closed. + +Resolution precedence: the explicit `--session-id` → `$FLEET_SESSION_ID` → the OpenCode environment → the worktree's marker file. The marker is a plain one-line file `.fleet-session-id` at the git worktree root, so each worktree retains its own active session association. A marker is used only when the session is **live** — checked against the OpenCode server's session endpoint; a stale marker (ended or unverifiable session) is an explicit error naming the file and the id, never a silent fall-through, and an unavailable server is not proof a recorded session is live. + +A successful bind sets `FLEET_SESSION_ID` for fleet's child processes and persists the identity to the marker, so a later bare invocation in the same worktree resolves the same session. Every domain invocation runs this initialisation (with no explicit id) before dispatch; `fleet init` runs it explicitly. + +Exit codes: 0 ok · 2 usage error, malformed session id, or stale/unverifiable marker. + +```text +$ fleet session bind --session-id ses_01J9EXAMPLE0000000000000 +session bound: ses_01J9EXAMPLE0000000000000 (worktree marker .fleet-session-id) +$ fleet session bind --session-id not-a-session +fleet session: invalid session id 'not-a-session' (expected ses_ followed by letters/digits) +``` + +## fleet version + +```text +Usage: fleet version +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| _(none)_ | — | — | `version` takes no arguments. `fleet version --help` is a usage error, exit 2. The short form is spelled `fleet --version` or `fleet -V`. | + +**Behaviour.** `fleet version` prints five lines; the short `--version` / `-V` form prints only the first two: + +```text +fleet 0.1.0 +Build: fleet [(invoked as ; surface narrowed to the profile)] +Derived version: 0.1.0-dev+gb8bbcc0 +Source rev: b8bbcc0c49564ab31db8d58b026b67532db9491e +Enabled capabilities: proxy-connect, proxy-serve, … (usable set, registry order) +``` + +The fields are: the workspace **version**; the **build** name — `fleet`, `fleet-serve`, or `fleet-connect`, derived by matching the *compiled* capability set against the variant sets (an unrecognised compiled set falls back to the plain build name) — with the profile annotation when the invocation name narrowed the surface; the **derived version** (the `0.1.0-dev+g` form); the **source rev** (the full commit SHA the build was cut from); and the **enabled capabilities** — the *usable* set (compiled ∩ profile ∩ `[domains]` enables), comma-joined in registry order, or `none`. The values above are the reference build's, as captured in the capabilities dump. + +There are 15 capability atoms, in registry order: `proxy-connect, proxy-serve, proxy-raw-splice, queue, queue-broker, secrets-broker, search, search-serve, dispatch, dispatch-test, laptop-agent, secrets, gh, bridge, agent`. `proxy-connect` is unconditional — present in every variant. The three build variants are: Full (`fleet`, all 15), Serve (`fleet-serve`: `proxy-connect, proxy-serve, proxy-raw-splice, queue-broker, secrets-broker, search-serve, secrets` — daemon roles plus proxy, no working-seat clients), and Connect (`fleet-connect`: `proxy-connect, proxy-raw-splice` only). Invoking the binary under a hyphenated name selects that profile as a ceiling; profiles can only narrow, never widen. An unknown invocation name is a usage error, exit 2, naming the expected names. + +Exit codes: 0 ok · 2 usage error (any argument, including `--help`). + +```text +$ fleet version +fleet 0.1.0 +Build: fleet +Derived version: 0.1.0-dev+gb8bbcc0 +Source rev: b8bbcc0c49564ab31db8d58b026b67532db9491e +Enabled capabilities: proxy-connect, proxy-serve, proxy-raw-splice, queue, queue-broker, secrets-broker, search, search-serve, dispatch, dispatch-test, laptop-agent, secrets, gh, bridge, agent +``` + +## fleet capabilities + +```text +Usage: fleet capabilities +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| _(none)_ | — | — | `capabilities` takes no arguments. `fleet capabilities --help` is a usage error, exit 2. | + +**Behaviour.** `fleet capabilities` prints the registry for agents as pretty-printed JSON: + +```json +{ + "build": { + "name": "fleet", "version": "0.1.0", + "derived_version": "0.1.0-dev+gb8bbcc0", + "source_rev": "b8bbcc0c49564ab31db8d58b026b67532db9491e", + "invoked_as": "fleet", "profile": null + }, + "capabilities": [ "…" ], + "compiled_capabilities": [ "…" ], + "domains": [ + { "name": "queue", "summary": "…", "aliases": ["repo-queue"], + "capabilities": ["queue"], "available": true, "state": "available" } + ] +} +``` + +Per-domain `state` is one of `available`, `not-in-build`, `narrowed-by-name`, `disabled-by-config` (the four reason classes behind the exit-69 stub), and `available` is exactly `state == "available"`. Note the two distinct capability lists: `capabilities` is what this *invocation* can use; `compiled_capabilities` is what the *binary* was built with — their difference is the profile/config narrowing. In the reference build both are the full 15 and every domain is `available`. One registry quirk: the `shell` domain's capability list is `["agent"]` — there is no `shell` capability atom; shell rides on the agent capability. + +Exit codes: 0 ok · 2 usage error (any argument, including `--help`). + +```text +$ fleet capabilities | head -20 +{ + "build": { + "name": "fleet", + "version": "0.1.0", + "derived_version": "0.1.0-dev+gb8bbcc0", + "source_rev": "b8bbcc0c49564ab31db8d58b026b67532db9491e", + "invoked_as": "fleet", + "profile": null + }, + "capabilities": [ + "proxy-connect", + "proxy-serve", + "proxy-raw-splice", + "queue", + … +``` + +## fleet help + +```text +Usage: fleet help [domain] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | domain name | full registry | With no argument, prints the full registry help (identical to `fleet --help`). With one domain name, prints that domain's help. A second argument is rejected. `fleet help --help` is an error: there is no domain named `--help`. | + +**Behaviour.** `fleet help` with no argument prints the full registry: `fleet 0.1.0 — one multicall binary for the fleet's tools`, the usage lines, all 12 domains with summaries and argv0 aliases, the five built-in commands, and the note that a domain this invocation cannot use answers with a stub and exit code 69. `fleet help ` prints the domain's registry help: summary line, `Usage: fleet [args...]`, argv0 aliases, the command list, and a status line whose wording is per-domain and capability-aware. An unknown name is a usage error: `error: no domain named '' — run 'fleet --help' for the registry`, exit 2. Domain help is registry data and renders identically on every build, with unavailable domains marked — help never stubs. + +Exit codes: 0 ok · 2 unknown domain name or extra argument. + +```text +$ fleet help queue +fleet queue — Repo work queue: enqueue, claim, and complete tasks through the queue broker. + +Usage: fleet queue [args...] +Aliases (argv0): repo-queue +Commands: validate, enqueue, list, claim, release, lane, bind, heartbeat, checkpoint, park, wake, block, unblock, dep-recheck, quarantine-recheck, cancel, revive, fail, complete, verify-disposition, timeline, history, show, models, health, signal, fallback, dispatch, session, surfaces, outbox, stack +Status: included in this build +``` + +Next: the queue domain itself, starting with [fleet queue: core verbs](queue-core.md). diff --git a/pkgs/fleet/book/reference/dispatch-test.md b/pkgs/fleet/book/reference/dispatch-test.md new file mode 100644 index 0000000000..283627874b --- /dev/null +++ b/pkgs/fleet/book/reference/dispatch-test.md @@ -0,0 +1,130 @@ +# fleet dispatch-test + +`fleet dispatch-test` is an explicit-dispatch CI test harness: scan fleet repos for free Actions capacity, submit a job, and track its stored status. Nothing here is trigger-driven: every verb runs only when a caller invokes it, and `submit` dispatches a `workflow_dispatch` run explicitly. + +See also [fleet dispatch](dispatch.md) and [Dispatch and dispatch-test](../concepts/dispatch.md). + +## Shared machinery + +- **Execution homes:** ONE repo — the fleet repo, config `[dispatch-test] fleet_repo`, default **`dezren39/fleet`** — holds the other fleet repos as git submodules and carries the generic workflow `fleet-dispatch-test.yml`. Eligible homes are its *copies*: the source repo plus its fork network, discovered per invocation by breadth-first traversal of `GET /repos/{r}/forks`, **depth-capped at 8 levels**, deduplicated, source first, then copies in API order — unless `[dispatch-test] scopes` pins an explicit list (pin wins; scan output reports `scopes_source: "config"` vs `"fork-network"`). +- **Capacity counting:** for each scope, ACTIVE = (jobs with status `in_progress` or `queued` across all `in_progress` runs — fetched paginated, page size 100, max 100 pages) + (number of `queued` runs, from `total_count`, counted as **1 active unit each** — a queued run has not started and exposes no jobs, so it counts once regardless of its eventual fan-out). +- **Workflow presence:** the repo's workflows list (paginated) contains a workflow whose `path` ends with `fleet-dispatch-test.yml` and whose `state` is `active` (a missing state counts as active). +- **Eligible** = `workflow_present && active < threshold`. +- **Threshold:** `--threshold N`, else `[dispatch-test] threshold`, else **40**. `--threshold 0` is a usage error ("can never be satisfied"). +- **Pagination contract:** paged reads are complete, bounded, or say so; truncation is never silent. +- **Auth, by name through fleet-secrets only:** GitHub token name `[dispatch-test] token_name`, default `github.ghcr-classic-pat`; Turso token name `[dispatch-test] turso_token_name`, default `turso.fleet-dispatch-jobs-token`. Each value enters exactly one `Authorization` header per request. GitHub calls use `User-Agent: fleet-dispatch-test` against `https://api.github.com`. +- **Turso jobs store:** endpoint `[dispatch-test] turso_url`, default `https://fleet-dispatch-jobs-dezren39.aws-us-east-1.turso.io`; requests are `POST {url}/v2/pipeline`. Table `jobs`, columns: `id, created_at, name, target_repo, target_ref, script, status, run_id, run_url, exit_code, output_tail, updated_at, submodule, commands`. The phase-2 migration (`ALTER TABLE jobs ADD COLUMN submodule TEXT`, `… ADD COLUMN commands TEXT`) is applied idempotently by submit and status; a "duplicate column" error means already-migrated and is ignored. + +Known discrepancy: the help text understates three source behaviours — scan's human output has a leading `scopes source: …` line the help omits; `--threshold 0` is a usage error the help does not mention; and submit's forced `--repo` also skips the eligibility checks (below). + +## fleet dispatch-test scan + +``` +fleet dispatch-test scan [--threshold N] [--json] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--threshold` | `N` | config, else `40` | Eligibility threshold: a scope is eligible when `active < threshold` and the workflow is present. `0` is a usage error. | +| `--json` | — | off | Print the facts as JSON instead of lines. | + +### Behaviour + +Scans every scope in order. Human output: a first line `scopes source: {config|fork-network} (fleet repo {repo})`, then one line per scope ` active= workflow= eligible=`, then `chosen: ` (the first eligible scope). `--json` prints: + +```json +{"threshold": 40, "fleet_repo": "dezren39/fleet", "scopes_source": "fork-network", + "scopes": [{"repo": "dezren39/fleet", "active": 3, "workflow": true, "eligible": true}], + "chosen": "dezren39/fleet"} +``` + +### Exit codes + +- `0` — ok (including `chosen: none`). +- `2` — usage (including `--threshold 0`). +- `3` — transport down / credentials unresolved / no eligible scope class failures on the scan path. +- `4` — an HTTP error status from GitHub or Turso. + +### Example + +```console +$ fleet dispatch-test scan +scopes source: fork-network (fleet repo dezren39/fleet) +dezren39/fleet active=3 workflow=yes eligible=yes +chosen: dezren39/fleet +``` + +## fleet dispatch-test submit + +``` +fleet dispatch-test submit --submodule NAME [--threshold N] [--repo owner/name] [--ref REF] [--name TEXT] [--commands TEXT | --commands-file PATH] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--submodule` | `NAME` | required | Fleet-repo submodule to run in — a single path segment: alphanumerics, `-`, `_`, `.`; never empty, `.` or `..`, never a slash. Examples: `code, opencode, openchamber, nix, hatch`. | +| `--threshold` | `N` | config, else `40` | Capacity threshold for the scan rule. `0` is a usage error. | +| `--repo` | `owner/name` | — | Force this execution-home copy. Forcing **bypasses the eligibility rule**: the code scans the forced repo only to report `active_at_scan`; it does not check `active < threshold` or workflow presence. | +| `--ref` | `REF` | empty | Ref **inside the submodule repo**; empty = the submodule stays at the umbrella's recorded SHA. Stored in the row's `target_ref`. | +| `--name` | `TEXT` | — | Free-text job name recorded on the row. | +| `--commands` | `TEXT` | trivial smoke set | Shell commands run inside the submodule. Mutually exclusive with `--commands-file`. Default: `set -eux; echo dispatch-test smoke; git rev-parse HEAD; uname -a`. | +| `--commands-file` | `PATH` | — | Read the commands from a file. Mutually exclusive with `--commands`. | + +### Behaviour + +The job id is generated client-side (time-based base36 + random hex suffix). The sequence order is load-bearing: + +1. Connect to GitHub and to the Turso jobs store; run the idempotent schema migration. +2. INSERT the job row with `status='queued'`, `target_repo=NULL`, `target_ref=`, `script=`, `submodule=`, `commands=`, `run_id/run_url/exit_code/output_tail=NULL`, `created_at`/`updated_at` = now (RFC 3339 UTC). (`script` mirrors `commands` so MVP-era readers still see the payload.) +3. Pick the home: forced `--repo`, else the scan rule over discovered/pinned scopes. No eligible scope is a transport-class error (exit 3): "no eligible scope: no execution-home copy has active < {threshold} with the generic workflow present (job {id} remains queued in the store)". +4. Dispatch sequence: (a) `UPDATE jobs SET target_repo=?` — (b) dispatch `POST /repos/{repo}/actions/workflows/fleet-dispatch-test.yml/dispatches` with `{"ref": , "inputs": {"job_id": id}}` — **the job id is the workflow's only input** — (c) only then `UPDATE jobs SET status='dispatched'`. Any failure stops the sequence: a failed dispatch leaves the row `queued` (with its target repo recorded). +5. Prints JSON: `{job_id, repo, submodule, ref (null when empty), active_at_scan, threshold, status: "dispatched"}`. + +Row lifecycle: `queued` (insert) → `dispatched` (client, after the workflow POST) → `running` (the workflow itself writes this, with `run_id`/`run_url`, when it fetches the job) → terminal status + `exit_code`/`output_tail` written back by the workflow, always, even on failure (a cancelled run is the best-effort exception — its row stays `running`, which `status` reports honestly). + +### Exit codes + +- `0` — ok, row dispatched. +- `2` — usage (bad submodule, `--commands` with `--commands-file`, `--threshold 0`). +- `3` — transport down / credentials unresolved / no eligible scope. +- `4` — an HTTP error status from GitHub or Turso. + +### Example + +```console +$ fleet dispatch-test submit --submodule code --name "smoke the code submodule" +{"job_id": "…", "repo": "dezren39/fleet", "submodule": "code", "ref": null, "active_at_scan": 3, "threshold": 40, "status": "dispatched"} +``` + +## fleet dispatch-test status + +``` +fleet dispatch-test status +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | job id | required | Exactly one positional; anything else is a usage error. This verb takes no flags. | + +### Behaviour + +Prints the stored row as pretty JSON with **all columns** (`id, created_at, name, target_repo, target_ref, submodule, commands, script, status, run_id, run_url, exit_code, output_tail, updated_at`), values typed from the Turso cells. This reads the store only — it never queries GitHub for live run state. + +### Exit codes + +- `0` — ok. +- `2` — usage (not exactly one positional). +- `3` — transport down / credentials unresolved. +- `4` — an HTTP error status, including an **unknown job id**: "job {id} not found in the jobs store" exits 4. + +### Example + +```console +$ fleet dispatch-test status +{ + "id": "…", + "status": "dispatched", + "submodule": "code", + "target_repo": "dezren39/fleet" +} +``` diff --git a/pkgs/fleet/book/reference/dispatch.md b/pkgs/fleet/book/reference/dispatch.md new file mode 100644 index 0000000000..d568ee780c --- /dev/null +++ b/pkgs/fleet/book/reference/dispatch.md @@ -0,0 +1,129 @@ +# fleet dispatch + +`fleet dispatch` is a thin client over pm-dispatch, the pm-stack dispatch service. The service is a working TypeScript/Bun suite that is not rewritten; this domain is verbs over its existing HTTP routes — and those routes are exactly three. Per-task status is **not** here: a task's state is the repo queue itself, so per-task status reads ride the queue domain (`fleet queue list`). + +| Verb | Route | Auth | +|---|---|---| +| `status` | `GET /health` | unauthenticated | +| `launch` | `POST /v1/sessions` | Bearer | +| `enqueue` | `POST /v1/tasks` | Bearer | + +See also [fleet dispatch-test](dispatch-test.md) and [Dispatch and dispatch-test](../concepts/dispatch.md). + +## Connection ladder and auth (all verbs) + +Transport selection, in order: + +1. **Direct URL:** env `FLEET_DISPATCH_URL` or fleet.toml `[dispatch] url`. It must be `http://host[:port]` with **no path** — a path is a usage error; a missing port gets the configured port appended. +2. **Loopback probe:** probe `127.0.0.1:{port}` with a 750 ms connect timeout; if it answers, go direct to loopback. Port: `[dispatch] port`, default **4879**. +3. If config `proxy_direct()` is set: direct to `{target_host}:{port}`. +4. **Proxy-egress CONNECT:** a CONNECT tunnel through the fleet proxy egress to the target host's dispatch port (the sandbox route). The client opens its own tunnel on the egress because the framed session-broker shape forwards only an `X-Agent-Token` header, which pm-dispatch does not accept. + +Auth is `Authorization: Bearer `, the token resolved **by name** through fleet-secrets: default name `pm-dispatch.api-token`, overridable with `[dispatch] token_name`. The value enters exactly one header per request and is never printed, logged, or stored. HTTP 401 is reported as a transport-class error naming the mismatch with the service's own token env (name only). + +Success bodies print to stdout as pretty JSON exactly as the service sent them; errors go to stderr, prefixed `fleet dispatch: `. For HTTP error bodies the `error` string is used, and if the body has more fields the whole body is appended in brackets (a failed launch's 502 names its cancelled `task_id`); messages are truncated at 600 chars. + +The argument parser is shared by `launch` and `enqueue`: `--flag value` and `--flag=value` are both accepted; duplicate value flags, unknown options, values on boolean flags, and stray positionals are all usage errors. + +## fleet dispatch status + +``` +fleet dispatch status +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments. Any argument is a usage error. `--help`/`-h` prints usage and succeeds without contacting the service. | + +### Behaviour + +Issues `GET /health` on pm-dispatch: is the service up, and which build. Prints the service's health body as a JSON object **plus** an added `"transport"` field describing the route taken, for example `"direct http://127.0.0.1:4879"` or `"tunnel via proxy egress to {host}:4879"`. A non-object health body is wrapped as `{"health": , "transport": …}`. + +### Exit codes + +- `0` — ok. +- `2` — usage. +- `3` — transport down / credentials unresolved or rejected. +- `4` — the service answered with an HTTP error status. + +### Example + +```console +$ fleet dispatch status +{"ok": true, "transport": "direct http://127.0.0.1:4879"} +``` + +## fleet dispatch launch + +``` +fleet dispatch launch --repo --prompt [options] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--repo` | `` | required | An allowlisted fleet repo (allowlist checked service-side). | +| `--prompt` | `` | required (or `--prompt-file`) | The session prompt. | +| `--prompt-file` | `` | — | Read the prompt from a file. Together with `--prompt` is a usage error. | +| `--title` | `` | service default: the prompt's first line | Tracking-issue title. | +| `--model` | `` | — | Model hint for the session. | +| `--directory` | `` | — | Must be the repo's laptop primary or inside it. | +| `--priority` | `

` | — | Integer 10–90, or `critical\|high\|normal\|low`. Sent as a JSON number when it parses as an integer, otherwise as the raw string; range validation is the service's job. | +| `--issue` / `--no-issue` | — | service default: issue | Create the tracking issue. Both together, in either order, is a usage error. Sent only when given. | +| `--wait` / `--no-wait` | — | service default: wait | Wait for the launch to complete. Both together is a usage error. Sent only when given. | + +### Behaviour + +POSTs `/v1/sessions` — creates the tracking issue and queue task, starts the session, and assigns the task to it (all service-side). The client sends **only the fields the caller set**: `repo` and `prompt` always; `title`, `model`, `directory`, `priority` when given; `issue: bool` only when `--issue`/`--no-issue` was given; `wait: bool` only when `--wait`/`--no-wait` was given. The defaults named in the help (title = first prompt line, issue on, wait on) are the **service's** defaults, applied because the client omits the fields. + +### Exit codes + +- `0` — ok. +- `2` — usage. +- `3` — transport down / credentials unresolved or rejected. +- `4` — the service answered with an HTTP error status. + +### Example + +```console +$ fleet dispatch launch --repo developing-today/code --prompt "Fix the failing smoke test" --no-wait +``` + +Creates the tracking issue and queue task, starts a session on the laptop, and returns without waiting for the launch to complete. + +## fleet dispatch enqueue + +``` +fleet dispatch enqueue --repo --title --prompt [options] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--repo` | `` | required | An allowlisted fleet repo (allowlist checked service-side). | +| `--title` | `` | required | Task title. | +| `--prompt` | `` | required (or `--prompt-file`) | The task prompt. | +| `--prompt-file` | `` | — | Read the prompt from a file. Together with `--prompt` is a usage error. | +| `--kind` | `` | service default: `triage` | One of `triage\|small_fix\|pr_shepherd\|ci_investigation`. Validated client-side; an unknown kind is a usage error listing the four. Sent only when given. | +| `--priority` | `

` | — | Integer 10–90, or `critical\|high\|normal\|low` (same wire rule as launch). | +| `--model` | `` | — | Stored as the payload's model hint only. | +| `--issue` | — | service default: no issue | Create a tracking issue first. One-way boolean — there is no `--no-issue`; omitting it sends nothing. The opposite default from launch. | +| `--issue-number` | `` | — | Attach to this existing issue instead. Must parse as an integer; sent as `issue_number`. | +| `--dedupe-key` | `` | service default: canonical key from the issue, else unique | Sent as `dedupe_key`. | + +### Behaviour + +POSTs `/v1/tasks`: enqueue only, no session. Wire names are snake_case (`issue_number`, `dedupe_key`); launch's are single words. + +### Exit codes + +- `0` — ok. +- `2` — usage (including an unknown `--kind`). +- `3` — transport down / credentials unresolved or rejected. +- `4` — the service answered with an HTTP error status. + +### Example + +```console +$ fleet dispatch enqueue --repo developing-today/code --title "Triage the red nightly" --prompt "Find why the nightly failed" --kind ci_investigation +``` + +Enqueues a CI-investigation task without launching a session. diff --git a/pkgs/fleet/book/reference/gh.md b/pkgs/fleet/book/reference/gh.md new file mode 100644 index 0000000000..4d68d61cd9 --- /dev/null +++ b/pkgs/fleet/book/reference/gh.md @@ -0,0 +1,187 @@ +# fleet gh + +`fleet gh` is the real `gh` CLI, passed through under a rotating fleet token. Four argument vectors are **shadow subcommands** (`tiers`, `cache-serve`, `cache-status`, `closures`); every other argument vector passes through to the real `gh` unchanged. + +See also [The gh passthrough](../concepts/gh.md). + +Known discrepancy: the domain help's status line still says "implementation lands in a later step of epic #5412". The source is a complete implementation (rotation, cache, close guard, closures, metadata stamping). This chapter documents the source. + +## The passthrough (any other arguments) + +``` +fleet gh +fleet gh --raw +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--raw` | — | off (also `FLEET_GH_RAW=1`) | First-class bypass: exec the real `gh` directly with the caller's ambient credentials; no token resolved or injected, no rotation or failover. | +| *(all other args)* | — | — | Passed to the real `gh` binary unchanged. `FLEET_GH_BIN` selects the binary, default `gh`. | + +### Behaviour + +Before each attempt, one token is resolved by name through the fleet secrets chain and exported as `GH_TOKEN` **for that attempt only**. Attempts are *captured* (piped), not streamed, because the failure text is what classifies a failover; the caller sees the final attempt's stdout, stderr, and exit code **byte-exact** as `gh` produced them. Attempts are silent by default; `FLEET_GH_TRACE=1` names each attempt's token *source* (never a value) on stderr. Tokens are never printed, logged, or written to a file; provider errors name source and stage only. The audit log redacts secret-carrying arguments (`gh secret set` bodies, `Authorization` headers) in its copy only. + +**Rotation order** (source behaviour): + +1. **Personal** — the `gh` OAuth token, parsed out of the broker secret named `github-cli.hosts-yml` (the hosts.yml file itself, stored by name; the parser extracts its `oauth_token`). +2. **Fleet App installations** — "developing.today fleet", App ID **5612056** (`FLEET_GH_APP_ID` may override). Private key by secret name `github-app.developing-today-fleet.private-key`. Default owners, in order: `developing-today`, `developing-today-forks`, `dezren39`. +3. **developing.today App installations** — App ID and key both by name (`kaneo.github-app-id`, `kaneo.github-app-private-key`). Default owners: `developing-today`, `dezren39`. +4. **developing-today-backup App installations** — by name (`github-app.backup-app-id`, `github-app.backup-private-key`). Default owner: `developing-today`. + +Known discrepancy: the help summary's "personal, then the developing.today App's installations" understates the source — there are **three** Apps in a fixed order (fleet → developing.today → backup), each expanded over its owners. + +Mechanics per App leg: the private key is resolved by name; an RS256 JWT is signed with the system `openssl`, the key passed over an inherited fd — never written to disk, never in argv; the owner's installation is resolved live from `GET /app/installations`, paginated at 100/page. **Hint-first:** when the call names a repo or org, that owner's installation moves to the front of *each* App leg, because an installation token only sees its own installation's scope. Controls: `FLEET_GH_ORDER` (comma list fixing the rotation exactly: `personal`, `app:`, `devtoday:`, `backup:`), `FLEET_GH_APP_OWNERS` / `FLEET_GH_DEVTODAY_OWNERS` / `FLEET_GH_BACKUP_OWNERS` (comma lists replacing an App's default owners). + +**Failover triggers.** A failed attempt's combined stdout+stderr is classified: + +| Class | Trigger strings (case-insensitive) | Retry? | +|---|---|---| +| RateLimit | `rate limit`, `rate_limit`, `too many requests`, `http 429` | Yes — any call | +| Permission | `missing required scopes`, `insufficient_scopes`, `resource not accessible`, `not accessible by integration`, `not accessible by personal access token`, `this endpoint requires you to be authenticated`, `bad credentials`, `http 401` | Yes — any call | +| NodeResolution | `could not resolve to a node` | Read-only calls only | +| Other | anything else | Read-only calls only | + +The rule: a **write is only repeated under a fresh token when the failure proves GitHub refused the request before processing it** — rate-limit and permission/scope rejections are both pre-execution refusals. Node-resolution is explicitly not one: GraphQL executes mutation fields serially, so a batched mutation may already have run an earlier field before a later field's node fails to resolve; replaying would duplicate the part that landed. Any other write failure is returned as-is. Reads repeat on any failure class. A token *provider* failure skips that source silently (named under trace) and the rotation continues; if no attempt produced output, the caller gets the provider errors and exit 3. If the last failover has no successor, the caller is shown the real `gh` failure, not a summary. + +Two wrappers sit in front of the rotation: + +- **Close guard:** `issue close` and `issue edit --add-label status:done` are refused (exit 2, never reaching the rotation) when the queue broker has a claimed or parked task bound to that repo#issue, unless the bound task's completion record (a `fleet-closure/v1` record carrying its task id) is presented with the wrapper-only flag `--completion-record `, stripped before `gh` runs. The queue query **fails open** — a broker outage must not block every close. +- **Metadata create path:** `issue create` / `pr create` bodies are stamped with the fleet Metadata block before the rotation runs, and the full record is inserted into the metadata store after a successful create; a malformed caller block refuses the create before any write; a failed insert never loses the item (reported on stderr, ingestion heals it). Controls: `FLEET_METADATA_DB`, `FLEET_GH_STAMP_KEY_ID` (key material by name from the secrets broker). + +### Exit codes + +- The final attempt's `gh` exit code, byte-exact. +- `2` — close-guard refusal, or a malformed metadata block on a create. +- `3` — no token source produced an attempt (provider errors reported). + +### Example + +```console +$ fleet gh api rate_limit --jq '.rate.remaining' +``` + +Runs the real `gh` under the first rotation token that succeeds, failing over on a rate-limit or permission refusal. + +## fleet gh tiers + +``` +fleet gh tiers +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no flags. | + +### Behaviour + +Probes *every* rotation source and prints its core and GraphQL rate-limit headroom — labels and numbers only; token values never leave the provider. + +Known discrepancy: `tiers` takes no `--help`: `fleet gh tiers --help` errors with `error: unexpected argument '--help' for 'fleet gh tiers'`. This verb is documented only in source. + +### Exit codes + +- `0` — every source answers. +- `3` — any source is down. + +### Example + +```console +$ fleet gh tiers +``` + +Prints per-source core and GraphQL headroom for the personal token and all three Apps' installations. + +## fleet gh cache-serve + +``` +fleet gh cache-serve [--bind ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--bind` | `` | `FLEET_GH_CACHE_BIND`, else `127.0.0.1:4802` | Daemon bind address. `--bind` beats the env, which beats the default; a bind without a port gets 4802. | + +### Behaviour + +Runs the credential/token cache daemon in the foreground (port **4802** — the next port after the queue broker's 4801). It caches four things, **memory-only, single-flight minting** (concurrent requests for one key block on the in-flight mint): + +| Entry kind | TTL | +|---|---| +| Secret resolutions | 60 s | +| App JWTs | within their expiry, minus a 60 s skew | +| Installation tokens | until shortly before `expires_at`, minus the same 60 s skew, floored at 1 s | +| Per-App installation lists | 300 s | + +Nothing is written to disk; a restart is a cold cache, never a stale one. The wire is newline-delimited JSON over TCP, protocol version 1 — a daemon that does not know a request's version answers `{ok: false, …}` rather than guessing. Every normal `fleet gh` call resolves through the localhost daemon first, then the laptop daemon (the proxy's reach target at the same port; `[gh] cache_local` / `cache_laptop` in config, `FLEET_GH_CACHE` env beats both); with no daemon answering it resolves in-process over the *same* cache implementation and says so on stderr ("resolving in-process"). + +### Exit codes + +- `0` — clean exit. +- `2` — usage. +- `69` — capability unavailable. + +### Example + +```console +$ fleet gh cache-serve +``` + +Runs the cache daemon in the foreground on 127.0.0.1:4802. + +## fleet gh cache-status + +``` +fleet gh cache-status +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments and no flags. | + +### Behaviour + +Probes the configured cache daemons and prints each one's snapshot — entry counts by kind, hit/miss counters, soonest expiry. Key names and values never leave the daemon; counts only. + +### Exit codes + +- `0` — at least one daemon answered. +- `2` — usage (trailing argument). +- `3` — **no daemon answered**. + +### Example + +```console +$ fleet gh cache-status +``` + +Prints counts-only snapshots for each configured cache daemon. + +## fleet gh closures + +``` +fleet gh closures [] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional, optional) | item reference | — | Filter the closure log to one item. This verb takes no flags. | + +### Behaviour + +Reads back the closure log. The policy layer behind it: `issue|pr close|reopen` through the rotation must carry a `--reason` from the taxonomy — `implemented`, `superseded`, `cancelled`, `started-incorrectly` — enforced with the policy error "Please give a reason. This is required by policy." The reason is written into the close comment, and every successful close or reopen appends one `fleet-closure/v1` JSON-line record to `closure-records.jsonl` in the fleet state directory (backed up with it); `closures` prints the log, optionally filtered to one item. + +Known discrepancy: this verb has **no help output at all** — its help-dump file is empty because the `--help` invocation produced nothing. Its behaviour is documented only in source (this section). + +### Exit codes + +- `0` — ok. +- `2` — usage. + +### Example + +```console +$ fleet gh closures +``` + +Prints the full `fleet-closure/v1` closure log, one JSON record per line. diff --git a/pkgs/fleet/book/reference/laptop-agent.md b/pkgs/fleet/book/reference/laptop-agent.md new file mode 100644 index 0000000000..b77c7a38ef --- /dev/null +++ b/pkgs/fleet/book/reference/laptop-agent.md @@ -0,0 +1,244 @@ +# fleet laptop-agent + +`fleet laptop-agent` is the client for the laptop-agent daemon — the Python service on the laptop at `100.99.113.103:4799`. The client speaks HTTP JSON to it; the token is the laptop-agent token file (`~/tools/laptop-agent-token`), read per request and sent as `X-Agent-Token` on the direct legs; on the broker leg the token rides in the framed request's named token file instead. The domain's argv0 alias is `laptop-agent` itself. + +See also [fleet proxy](proxy.md) and [fleet shell](shell.md). + +Known discrepancy: there is **no `--help` handling anywhere in this domain**. The shared USAGE text is printed only as part of error messages, and a `--help` argument is treated as data — `laptop-agent jobs --help` errors `unknown command "jobs"` (because `jobs` accepts no trailing arguments), `poll --help` actually polls a job named `--help` and prints its real `HTTP 404: no such job`, and `kill --help` prints nothing. This chapter is written from source. A second stale-help note: the domain status line still claims "implementation lands in a later step of epic #5412"; the source is a full client mirroring the Python daemon client verb for verb. + +## Shared behaviour (all verbs) + +Strict parsing: anything unaccounted for is a usage error (exit 2) before any transport is touched. Job ids are restricted to the characters the daemon mints (`[A-Za-z0-9_-]`), because a job id goes into a URL path. + +Each call gets a fresh **trip id** (sent as the `X-Trip-Id` header on HTTP legs / the `trip` field on the broker leg, and used for exec cancellation and log correlation). The default call deadline is **660 s**, overridable via `LAPTOP_AGENT_DEADLINE_S`. Failures print `laptop-agent: ` and exit 1, except the timeout and usage cases noted per verb. + +### The transport ladder + +Every verb's call goes down a four-leg **ladder**, in order; the first leg that answers wins, and when an earlier leg failed the client prints one line: `laptop-agent: note: answered by after failed`. + +1. **Broker** — the warm session-broker socket (default `~/.cache/laptop-agent/broker.sock`): the framed protocol (8-byte big-endian length + JSON `{method, path, body, trip}`; reply framed the same way, `{status, body}`). Absent when no socket file exists. +2. **Cloudflare** — TLS through the egress proxy to the tunnel hostname, with the Access service token resolved by name (secret name `cloudflare.access-laptop-agent`) *only when this leg is tried*, so a healthy broker never pays for the resolution; a resolution failure is cached 60 s. +3. **Tailscale** — HTTP CONNECT through the egress proxy at port **3130** to `100.99.113.103:4799`. +4. **SSH** — a named **stub**: always absent ("ssh leg not implemented"). The ladder's fourth leg exists in the ordering but never carries traffic in this build. + +**Replay rules:** each leg classifies its failures as **absent** (not configured here), **unsent** (failed before the request was written), or **sent** (failed after). A request may fall through to the next leg freely when absent/unsent, but a *sent* failure replays only for idempotent calls — non-idempotent calls (`exec`, `run` submits) are never replayed on a leg that may already have sent them, so a submitted job or an exec is never duplicated by the ladder. + +The USAGE block (printed only inside error messages) is: + +``` +usage: fleet laptop-agent + health + jobs + kill JOB + exec [--cwd DIR] [--timeout SECS] [--shell] -- CMD... + run [--cwd DIR] [--shell] -- CMD... + poll JOB [--wait SECS] + fetch REMOTE_PATH LOCAL_PATH +``` + +## fleet laptop-agent health + +``` +fleet laptop-agent health +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments. Any trailing argument is a usage error, exit 2. | + +### Behaviour + +Issues `GET /health` to the daemon (via the ladder) and prints the daemon's health JSON verbatim. + +### Exit codes + +- `0` — the daemon answered. +- `1` — no leg answered. +- `2` — usage. + +### Example + +```console +$ fleet laptop-agent health +``` + +Prints the daemon's health JSON. + +## fleet laptop-agent exec + +``` +fleet laptop-agent exec [--cwd DIR] [--timeout SECS] [--shell] -- CMD... +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--cwd` | `DIR` | daemon default | Working directory for the command (sent as the spec's `cwd`). | +| `--timeout` | `SECS` | `120` | Daemon-side timeout in seconds. The client deadline is timeout + 15 s transport grace. | +| `--shell` | — | off | Run the joined command string as a shell command (`{cwd, shell: "cmd string"}`) instead of an argv spec (`{cwd, argv}`). | +| `--` | — | required | Separator; everything after it is the command. No command is a usage error ("no command given (use -- cmd...)"). | + +### Behaviour + +**Synchronous** run: `POST /exec` with body `{cmds: [spec], timeout_s}`. Prints the first result's stdout to stdout and stderr to stderr, and returns the command's own exit code. Output capture is capped at **1 MiB per stream** (tail kept) with a truncation warning on stderr. On client-deadline expiry it best-effort cancels by trip (`POST /exec//cancel`, 3 s budget) and exits **124**; a daemon-reported timeout also exits 124. `exec` is non-idempotent for the ladder: it is never replayed after a sent failure. + +### Exit codes + +- The command's own exit code. +- `1` — transport failure. +- `2` — usage. +- `124` — timeout (client deadline or daemon-reported). + +### Example + +```console +$ fleet laptop-agent exec --timeout 300 -- cargo build +``` + +Runs `cargo build` synchronously on the laptop with a 300 s timeout and returns its exit code. + +## fleet laptop-agent run + +``` +fleet laptop-agent run [--cwd DIR] [--shell] -- CMD... +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--cwd` | `DIR` | daemon default | Working directory for the job. | +| `--shell` | — | off | Run the joined command string as a shell command instead of an argv spec. | +| `--` | — | required | Separator; everything after it is the command. | +| `--timeout` | — | — | **Not accepted** — passing it is an unknown-option error. Detached jobs have no client-side timeout; use `poll --wait` to bound waiting. | + +### Behaviour + +**Detached** submit: `POST /jobs`. Prints the returned `job_id` and exits 0. Follow up with `poll`. `run` is non-idempotent for the ladder: it is never replayed after a sent failure. + +### Exit codes + +- `0` — job submitted, `job_id` printed. +- `1` — transport failure. +- `2` — usage (including `--timeout`). + +### Example + +```console +$ fleet laptop-agent run -- ./long-build.sh +job_… +``` + +Submits a detached job and prints its job id. + +## fleet laptop-agent poll + +``` +fleet laptop-agent poll JOB [--wait SECS] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `JOB` (positional) | job id | required | Job id (`[A-Za-z0-9_-]` only). | +| `--wait` | `SECS` | — | How long to keep polling before reporting still-running. | + +### Behaviour + +Incremental output streaming: `GET /jobs/?out_off=N&err_off=M`. The client persists per-job output offsets in a local offsets file (`.json` in the laptop-agent state dir), sends them on each poll, appends only the new stdout/stderr, and saves the returned `out_next`/`err_next`. It polls every ≤3 s until the job's state is `done` — then prints `[laptop-agent] job done exit= duration_ms=` on stderr and returns the job's exit code — or until the wait deadline passes, printing `still running` and returning **0** (still-running is not a failure). A reply without offsets is an error, exit 1. + +### Exit codes + +- The job's exit code, once the job is done. +- `0` — still running at the wait deadline. +- `1` — transport failure, or a reply without offsets. +- `2` — usage. + +### Example + +```console +$ fleet laptop-agent poll job_… --wait 600 +``` + +Streams new output every ≤3 s for up to 600 s, then returns the job's exit code (or 0 with "still running"). + +## fleet laptop-agent jobs + +``` +fleet laptop-agent jobs +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments. Any trailing argument is an unknown-command error, exit 2. | + +### Behaviour + +Issues `GET /jobs` and prints the job list pretty-printed. + +### Exit codes + +- `0` — ok. +- `1` — transport failure. +- `2` — usage. + +### Example + +```console +$ fleet laptop-agent jobs +``` + +Prints the daemon's job list as pretty JSON. + +## fleet laptop-agent kill + +``` +fleet laptop-agent kill JOB +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `JOB` (positional) | job id | required | Exactly one job id (`[A-Za-z0-9_-]` only). | + +### Behaviour + +Issues `POST /jobs//kill` with `{}` and prints the reply. + +### Exit codes + +- `0` — ok. +- `1` — transport failure. +- `2` — usage. + +### Example + +```console +$ fleet laptop-agent kill job_… +``` + +Kills the named job and prints the daemon's reply. + +## fleet laptop-agent fetch + +``` +fleet laptop-agent fetch REMOTE_PATH LOCAL_PATH +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `REMOTE_PATH` (positional) | path | required | File path on the laptop. | +| `LOCAL_PATH` (positional) | path | required | Destination path on this host. This verb takes no flags. | + +### Behaviour + +Hash-checked copy. First it hashes the remote file *on the laptop* by running `shasum -a 256` through `/exec`, then pulls the file in **1 MiB** raw ranges via `GET /file?path=…&off=…&len=1048576` until an empty chunk, verifies the assembled bytes' SHA-256 against the remote hash, and only then writes the destination — a mismatch writes nothing and exits 1. + +### Exit codes + +- `0` — ok, hash verified and destination written. +- `1` — transport failure, or a SHA-256 mismatch (nothing written). +- `2` — usage. + +### Example + +```console +$ fleet laptop-agent fetch /home/user/build/result.tar ./result.tar +``` + +Copies the file in 1 MiB ranges and writes it locally only after its SHA-256 matches the remote hash. diff --git a/pkgs/fleet/book/reference/proxy.md b/pkgs/fleet/book/reference/proxy.md new file mode 100644 index 0000000000..93aa23c9a7 --- /dev/null +++ b/pkgs/fleet/book/reference/proxy.md @@ -0,0 +1,245 @@ +# fleet proxy + +The session proxy is the broker every sandbox seat talks through to reach the laptop's services. The wire is 8-byte big-endian length-prefixed JSON frames. The broker persists nothing: the routing table comes from config, tunnels live in memory, and token files are read per request and never stored or logged. + +The broker's services map (port → service) is built in: 4799 laptop-agent, 4800 secrets-broker, 4801 queue-broker, 21118 rustdesk. The session broker socket defaults to `~/.cache/laptop-agent/broker.sock` (`FLEET_BROKER_SOCKET` / `[proxy] broker_socket`). + +The domain's argv0 alias is `laptop-agent-broker`. Capabilities: `proxy-serve` (serve), `proxy-connect` (connect/init/get/put/ssh — present in every build), `proxy-raw-splice` (splice). + +See also [fleet serve](serve.md) and [Proxy, sessions and recovery](../concepts/proxy.md). + +## fleet proxy serve + +``` +fleet proxy serve +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments. `--help` prints the usage, exit 0; any other trailing argument is a usage error naming it, exit 2. | + +### Behaviour + +Binds the session broker Unix socket and serves in the foreground. If a live broker already owns the socket, it exits quietly; if the socket file is stale, it unlinks and binds. + +- **Warm tunnel pools:** per-port pools of warm CONNECT tunnels to the laptop's services; pool size from `LAPTOP_AGENT_POOL`, compiled default **50**. A request takes a pooled connection and on any failure retries **once on a fresh one**. Pool overflow policy: idle → grow (below the live ceiling) → wait briefly for a returned tunnel → grow anyway; a request never fails because of the pool. +- **Two reaches to the laptop:** the **Cloudflare leg is primary** for the laptop-agent daemon port *when its Access file exists* (`~/tools/laptop-agent-cf-access.json`, a JSON `{client_id, client_secret}` file, mode 600, read per request, sent only as `CF-Access-*` headers, never stored or logged; no file, no leg) — TLS through the platform egress proxy to the tunnel hostname `sandbox-link.security.cab`, whose ingress lands on the daemon's own listener laptop-side, token auth preserved end to end. The **tailnet leg** (CONNECT through the host egress proxy to the tailnet target host `100.99.113.103`) is the automatic fallback, on connection failure *and* on a Cloudflare edge error status (502/503/530) alike. Pools and recovery gates key on `(port, transport)` so the legs never share a bucket. +- **Hello negotiation:** sessions speak the legacy dialect (**proto 0**: request frames from the first frame) or negotiate a hello first (**proto 1**, fleet clients), decided per connection by peeking at the first frame, never by configuration. The hello response carries the services map (port → `{name, version}`) and the broker's capability list. A too-old peer gets the proto-too-old frame and exit 69 on the client side. +- **Keepalive and idle exit:** a keepalive thread pings the laptop-agent's `/health` every **180 s**. The broker exits once *client requests* have been idle for `idle_exit_secs` (`[proxy] idle_exit_secs`, default **3600** s; 0 is rejected at config load) — keepalive traffic does **not** count as use. In a multi-role serve list the idle exit is disabled (co-hosted mode). +- **Colocated brokers:** for the queue/secrets broker ports, the broker first tries the role's own Unix socket with a bounded dial (the dial *is* the probe; a socket that answers within the deadline is used, any other outcome selects TCP within the same attempt) before tunnelling. + +Port 3130 note: port **3130** is the host **egress proxy** port — the CONNECT proxy named by the session's `HTTPS_PROXY` environment. It is not a fleet listener. The tailnet leg's shape is: fleet → HTTP CONNECT to the egress proxy at `:3130` → tailnet target `100.99.113.103:`. Fleet contains no 3130 listener to restart; 3130 belongs to the session/host layer. + +### Exit codes + +- `0` — clean exit, including "a live broker already owns the socket". +- `2` — usage (trailing argument). +- `69` — capability unavailable in this invocation. + +### Example + +```console +$ fleet proxy serve +``` + +Binds the broker socket and serves until client requests have been idle for 3600 s. + +## fleet proxy connect + +``` +fleet proxy connect [--print-path] [--stdio [--host H] [--port N]] [--request METHOD PATH [--service-port N] [--token-file F] [--body JSON]] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--print-path` | — | off | Print the PATH shim directory and exit. Mutually exclusive with `--request` and `--stdio`. | +| `--stdio` | — | off | Raw relay spelling (SSH's ProxyCommand shape): relay stdin/stdout over one tunnel. Mutually exclusive with `--request` and `--print-path`. | +| `--host` | `H` | config target host | Tunnel destination host. Requires `--stdio`. | +| `--port` | `N` | `22` | Tunnel destination port. Requires `--stdio`. | +| `--request` | `METHOD PATH` | — | Issue exactly one framed request on the negotiated stream and print `{"status": …, "body": …}` as JSON. | +| `--service-port` | `N` | the request's implied route (4799) | Select the laptop service port. Must follow `--request`. | +| `--token-file` | `F` | — | Name the token file the broker should read for this request. Must follow `--request`. | +| `--body` | `JSON` | — | Request body; must be valid JSON. Must follow `--request`. | + +Each flag may be given at most once; a repeat is a usage error. + +### Behaviour + +Connect to the session proxy: **ensure a broker answers (starting one when none does)**, sync the PATH shims from its services map, and optionally issue one request over the negotiated stream. The ensure step spawns `fleet serve proxy` detached when the socket does not answer, then waits for the hello. A legacy (proto 0) answer still counts as running; its services map is the built-in table. The negotiated services map regenerates the PATH shim directory; `--print-path` prints that directory and exits (the shell-integration spelling). + +### Exit codes + +- `0` — ok. +- `2` — usage (repeated flag, bad combination, invalid `--body` JSON). +- `3` — transport failure. +- `69` — protocol / capability unavailable (including a proto-too-old peer). + +### Example + +```console +$ fleet proxy connect --request GET /health --service-port 4799 +{"status": 200, "body": {"ok": true}} +``` + +Ensures a broker, then issues one health request to the laptop-agent service. + +## fleet proxy init + +``` +fleet proxy init +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments. | + +### Behaviour + +Byte-identical to the `fleet init` built-in — one implementation lives in the proxy client and both spellings resolve identically. It autostarts this host's fleet roles per the `[host]` manifest: on the sandbox, probe the broker socket and sync PATH shims when a broker answers (a strict no-op when one is already running — init never fights an incumbent broker), start one when none does, and probe/start the standing loopback secrets broker. An unknown location reports state, starts nothing, and exits 69. + +### Exit codes + +- `0` — roles running or correctly reported. +- `2` — session initialisation error, before any role work. +- `69` — unknown location, or this build cannot run `init`. + +### Example + +```console +$ fleet proxy init +``` + +Autostarts the sandbox roles (proxy + secrets-broker) if they are not running. + +## fleet proxy ssh + +``` +fleet proxy ssh -- [ssh args...] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--` | — | required, first | Literal separator. Everything after it is SSH arguments. A second `--` inside the SSH arguments is an error: "the SSH destination is fixed; do not pass a second '--'". | + +### Behaviour + +Runs system OpenSSH through the fleet proxy **as a recovery path** — the route you use when the normal laptop channel is what is broken. Everything that decides where the connection lands is pinned by fleet; the caller supplies only extra SSH options and an optional remote command. Option parsing walks clusters character-by-character so clustered forms like `-vL` split correctly. + +The pinned argv shape: + +- Destination `user@` with `HostName=` (default `100.99.113.103`), `User=user`. +- Identity `~/.ssh/id_ed25519` with `IdentitiesOnly=yes`. +- `UserKnownHostsFile=~/.ssh/known_hosts_laptop`, `StrictHostKeyChecking=yes`. +- `ConnectTimeout=60`, `ConnectionAttempts=3`, `ServerAliveInterval=15`, `ServerAliveCountMax=8`. +- `ControlMaster=auto` with `ControlPath=~/.ssh/cm-%r@%h:%p` and `ControlPersist=3600`. +- `ProxyCommand= proxy connect --stdio --host --port %p`. + +The fleet proxy credential stays in the environment and is sent only by the CONNECT relay, never in the SSH argv. The command `exec`s the system `ssh` (Unix only; elsewhere exit 69). Its exit code is ssh's own. + +### Exit codes + +- ssh's own exit code on success of the exec. +- `2` — usage (missing `--`, or a second `--` in the SSH arguments). +- `69` — non-Unix platform. + +### Example + +```console +$ fleet proxy ssh -- hostname +amd +``` + +Opens the pinned recovery SSH connection and runs `hostname` on the laptop. + +## fleet proxy get + +``` +fleet proxy get [--mode OCTAL] [--no-resume] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--mode` | `OCTAL` | destination default | File mode for the downloaded file. | +| `--no-resume` | — | off (resume on) | Do not resume from an existing deterministic temp; start over. | +| `-` (as destination) | — | — | Stream to stdout instead of a local path. | + +### Behaviour + +Downloads a file from the laptop over the agent channel, through the broker to the laptop-agent daemon's file routes. Chunks are **2 MiB raw chunks, base64-encoded**, carried in JSON envelopes (`stat`, `begin`, `commit`, `abort`, `read`). Chunks land in a deterministic local temp — `..fleet-part-` beside the destination — so an interrupted transfer resumes by re-issuing `begin` and continuing from the temp's size. The whole-file **SHA-256** from the daemon's `stat` must match before the temp is renamed over the destination. `-` streams to stdout (the hash is still verified at the end; a mismatch fails the command *after* the bytes were emitted — check stderr). **Recursive get is deferred in v1**: the daemon protocol has no directory-listing route. + +### Exit codes + +- `0` — ok, hash verified. +- `2` — usage. +- `3` — transport. +- `69` — capability unavailable. + +### Example + +```console +$ fleet proxy get /home/user/build/result.tar ./result.tar +``` + +Downloads the file with resume support and verifies its SHA-256 before renaming it into place. + +## fleet proxy put + +``` +fleet proxy put [--mode OCTAL] [--no-resume] +fleet proxy put -r [--mode OCTAL] [--no-resume] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--mode` | `OCTAL` | `0644` for stdin; otherwise the local file's mode | File mode on the laptop. | +| `--no-resume` | — | off (resume on) | Do not resume from an existing deterministic temp; start over. | +| `-r` | — | off | Recursive: upload a directory tree. | +| `-` (as source) | — | — | Read stdin (spooled locally first). | + +### Behaviour + +Uploads a file to the laptop over the agent channel. The file is hashed (SHA-256), uploaded in **2 MiB chunks** to a deterministic temp on the laptop — `..fleet-part-` beside the destination — and **atomically renamed over the destination only after the daemon verifies the hash**. An interrupted put resumes from the temp unless `--no-resume` is given. Progress and the final sha256 go to stderr. + +### Exit codes + +- `0` — ok, hash verified by the daemon and rename committed. +- `2` — usage. +- `3` — transport. +- `69` — capability unavailable. + +### Example + +```console +$ fleet proxy put ./result.tar /home/user/build/result.tar +``` + +Uploads the file in 2 MiB chunks; the destination only appears once its hash verifies. + +## fleet proxy splice + +``` +fleet proxy splice +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments. | + +### Behaviour + +Listens on **`127.0.0.1:21118`** (loopback only, a pinned constant) and relays each accepted TCP stream through the fleet broker to the laptop's RustDesk direct-access service (port 21118 laptop-side). Requires the broker to advertise raw-splice support in its hello (the `proxy-raw-splice` capability plus the service flag); a legacy or non-advertising broker is a transport error, not a silent fallback. This is the RustDesk direct-access path that avoids the relayed session. + +### Exit codes + +- `0` — clean exit. +- `2` — usage (trailing argument). +- `3` — transport (broker does not advertise raw-splice). +- `69` — capability unavailable. + +### Example + +```console +$ fleet proxy splice +``` + +Starts the loopback splice listener on 127.0.0.1:21118 until stopped. diff --git a/pkgs/fleet/book/reference/queue-admin.md b/pkgs/fleet/book/reference/queue-admin.md new file mode 100644 index 0000000000..aa936a3d4b --- /dev/null +++ b/pkgs/fleet/book/reference/queue-admin.md @@ -0,0 +1,366 @@ +# fleet queue: inspection and admin + +The inspection and admin verbs read the queue's history and operate its side systems: `timeline` / `history` (one task's event timeline), `signal` (the wake-up signal file), `models` (serving-model rollup), `outbox` (the creation outbox for GitHub objects), and `stack` (merge-intent stacks). + +Shared context — the global exit-code vocabulary (0 ok, 1 gate/not-found, 2 usage, 3 transport/401, 4 broker store failure, 5 no-claim/no-row, 6 fallback switch) — is stated in [fleet queue: core verbs](queue-core.md). + +Sources: [commands_query.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/commands_query.rs), [commands_lifecycle.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs), [fallback_stack.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/fallback_stack.rs), [creation_outbox.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/creation_outbox.rs), [merge_intent.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs). + +## fleet queue timeline + +```text +usage: repo-queue timeline [--worker ] [--json] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The task whose timeline to render. | +| `--worker` | worker id | `repo-worker-code` | Attribution; the events queries don't use it beyond the shared envelope. | +| `--json` | boolean | off | Print `{"task_id": n, "events": […], "served": […]}` instead of the rendered timeline. | + +**Behaviour.** For each of 14 event kinds — `claimed, session_bound, lane_session_bound, model_stamp, session_unbound, session_binding_cleared, completed, lease_expired, lease_expired_at_cap, claim_refused, released, parked, failed, cancelled` — it calls `/events-list {task_id, kind, limit:1000}`, merges, sorts by event id, and collapses duplicates (same kind/session/leaf/trigger within 120 s = one record written by two surfaces). If the broker doesn't serve `/events-list`, it prints the interim direct-DB SQL to stderr and exits **3**. Output: a rendered timeline (binding windows with the exact resolved models per window, joined from the route ledger). With `--json`: `{"task_id": n, "events": […], "served": [{"session_id", "start", "end", "segments": […]}]}`; an empty timeline prints `task : no timeline records` (or the empty JSON shape), exit 0. + +Exit codes: 0 ok (including empty timeline) · 2 usage · 3 broker does not serve `/events-list` / transport · 4 broker store failure. + +```text +$ fleet queue timeline 19479 +task 19479 timeline: + claimed 2026-11-23T04:05:00Z worker=repo-worker-code lane=code-a + session_bound 2026-11-23T04:05:01Z session=ses_01J9EXAMPLE0000000000000 + checkpoint 2026-11-23T04:20:00Z stage=drafting + served: ses_01J9EXAMPLE0000000000000 04:05:00Z–… (1 segment) +``` + +## fleet queue history + +```text +usage: repo-queue history [--worker ] [--json] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The task whose timeline to render. | +| `--worker` | worker id | `repo-worker-code` | Attribution (as `timeline`). | +| `--json` | boolean | off | JSON output (as `timeline`). | + +**Behaviour.** `history` is a pure alias of `timeline`: same function, same output, same exit codes. See `timeline` above for the full behaviour. + +Exit codes: 0 ok · 2 usage · 3 broker does not serve `/events-list` / transport · 4 broker store failure. + +```text +$ fleet queue history 19479 --json +{"task_id": 19479, "events": [{"kind": "claimed", "created_at": "2026-11-23T04:05:00Z"}], "served": []} +``` + +## fleet queue signal + +```text +usage: repo-queue signal [--queue ] [--reason ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--queue` | queue name | `repo-health-code-shadow` | The ordinary queue resolution — flag → env `REPO_QUEUE_DEFAULT_QUEUE` → the shadow default. (Unlike `claim`/`list`, signal is NOT unscoped; unlike `enqueue`, it does have a default.) | +| `--reason` | text | `manual_signal` | Reason recorded in the signal object. | + +**Behaviour.** Asks the broker `/signal-count {queue}` for `queued_count` + `oldest_queued_at`, then writes a wake-up signal file for the queue's consumers: a JSON object `{"queue", "generation", "queued_count", "oldest_queued_at", "updated_at", "reason"}` where `generation` is one more than the max generation found in the existing signal/state files for that queue. Signal file path: env `REPO_QUEUE_SIGNAL_PATH`, else `$HOME/workspace/goals/keep-the-four-repos-healthy/hidden_files/repo-queue-signal.json`, with a sibling `repo-queue-signal-state.json` carrying `{queue, generation, updated_at}`. Both writes are atomic (tmp + rename); a write failure dies exit 3. The printed output is the signal object itself, exit 0. + +Exit codes: 0 ok · 2 usage · 3 transport / unwritable signal file · 4 broker store failure. + +```text +$ fleet queue signal --queue repo-health-code --reason "manual wake for the book build" +{"queue": "repo-health-code", "generation": 42, "queued_count": 12, "oldest_queued_at": "2026-11-23T03:58:00Z", "updated_at": "2026-11-23T04:30:00Z", "reason": "manual wake for the book build"} +``` + +## fleet queue models + +```text +usage: repo-queue models [--days ] [--json] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--days` | integer days | 7 | Rollup window. **Clamped** to 1..=30 (note: clamped, unlike the reject-don't-clamp duration/limit flags elsewhere). | +| `--json` | boolean | off | Print an object including `"days"` and the per-model rows instead of the human table. | + +**Behaviour.** Rolls up serving-model stamps across tasks: which models worked which tasks, joined from claim stamps + timeline binding windows + the route ledger. Output: human table headed `model rollup — last d (since )`, or with `--json` an object including `"days"` and the per-model rows. If the broker's `/events-list` doesn't serve the cross-task kinds, it prints `repo-queue models: this broker does not serve cross-task …` and a 50000-row scan cap produces a warning line rather than silent truncation. + +Exit codes: 0 ok · 2 usage · 3 transport / cross-task events not served · 4 broker store failure. + +```text +$ fleet queue models --days 7 +model rollup — last 7d (since 2026-11-16T04:30:00Z) +model tasks completed +claude-sonnet (example) 41 38 +``` + +## fleet queue outbox + +```text +usage: repo-queue outbox ... +``` + +The creation outbox is the queue for **GitHub object creation** (issues, PRs, comments) that must survive crashes and rate limits: producers enqueue, a single serial drainer creates through `gh`, verifies by read-back, and resolves. Pilot producer: `new-issue-creator-code-a`. There is no dual-write and no automatic fallback to direct creation — a broker failure stops the drain visibly. + +State machine: kinds `issue | pull_request | issue_comment | pr_comment`; states `pending | leased | uncertain | done | blocked`. Constants: claim lease **120 s**, min gap between creates **2 s**, hourly create budget **300**, retry backoff base **30 s** cap **3600 s**, circuit breaker opens after **3** consecutive rate limits for **300 s**, default max attempts **8**. Entries carry a `fleet-outbox:` marker in the created object's body so the drainer can reconcile by search/read-back. + +Each subverb below follows the reference format. All outbox subverbs print the full broker envelope JSON unless noted. + +### fleet queue outbox enqueue + +```text +usage: repo-queue outbox enqueue [--repo ] [--kind ] [--dedup-key ] [--producer

] [--payload | --payload-file ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--repo` | repo | unset | Target repo for the object to create. | +| `--kind` | `issue\|pull_request\|issue_comment\|pr_comment` | unset | Object kind. | +| `--dedup-key` | key | unset | Dedupe key; the broker table has a unique index on `(repo, dedup_key)`. | +| `--producer` | producer name | unset | Producing identity (pilot: `new-issue-creator-code-a`). | +| `--payload` | JSON | **required (one of the two)** | Creation payload inline. Neither `--payload` nor `--payload-file` → exit 2. | +| `--payload-file` | file path | **required (one of the two)** | Creation payload from a file. | + +**Behaviour.** POST `/outbox-enqueue`; prints the full broker envelope JSON. The entry lands in state `pending`. + +Exit codes: 0 ok · 2 usage / missing payload · 3 transport · 4 broker store failure. + +```text +$ fleet queue outbox enqueue --repo developing-today/code --kind issue --dedup-key book-13165 --producer new-issue-creator-code-a --payload '{"title":"Fleet book: queue chapters","body":"… fleet-outbox:pending"}' +{"ok": true, "row": {"id": 77, "state": "pending", "kind": "issue", "repo": "developing-today/code"}} +``` + +### fleet queue outbox list + +```text +usage: repo-queue outbox list [--repo ] [--state ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--repo` | repo | unset | Filter by repo. | +| `--state` | `pending\|leased\|uncertain\|done\|blocked` | unset | Filter by state. | + +**Behaviour.** POST `/outbox-list`; prints the envelope. + +Exit codes: 0 ok · 2 usage · 3 transport · 4 broker store failure. + +```text +$ fleet queue outbox list --state pending +{"ok": true, "rows": [{"id": 77, "state": "pending", "kind": "issue", "repo": "developing-today/code"}]} +``` + +### fleet queue outbox metrics + +```text +usage: repo-queue outbox metrics +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| _(none)_ | — | — | Takes no flags. | + +**Behaviour.** POST `/outbox-metrics` with `{}`; prints the envelope (counts by state/kind plus circuit-breaker state). + +Exit codes: 0 ok · 2 usage · 3 transport · 4 broker store failure. + +```text +$ fleet queue outbox metrics +{"ok": true, "pending": 1, "leased": 0, "uncertain": 0, "done": 128, "blocked": 0, "circuit_open": false} +``` + +### fleet queue outbox claim + +```text +usage: repo-queue outbox claim [--owner ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--owner` | owner name | `outbox-drainer` | Claiming drainer identity. Claim lease is 120 s. | + +**Behaviour.** Claims the oldest due entry; prints the envelope (its `row` is null when idle). + +Exit codes: 0 ok (including idle, `row: null`) · 2 usage · 3 transport · 4 broker store failure. + +```text +$ fleet queue outbox claim +{"ok": true, "row": {"id": 77, "state": "leased", "kind": "issue", "repo": "developing-today/code"}} +``` + +### fleet queue outbox resolve + +```text +usage: repo-queue outbox resolve [--outcome done|rate_limited|uncertain|failed] [--github-number ] [--github-url ] [--retry-after ] [--error ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | entry id | required | The leased entry to resolve. Missing `` → exit 2 with the usage line. | +| `--outcome` | `done\|rate_limited\|uncertain\|failed` | **none (see note)** | Resolution outcome. | +| `--github-number` | integer | unset | Created object's number, for `done`. | +| `--github-url` | URL | unset | Created object's URL, for `done`. | +| `--retry-after` | seconds | unset | Backoff hint for `rate_limited`. | +| `--error` | text | unset | Error text for `failed`/`uncertain`. | + +**Behaviour.** POST `/outbox-resolve` for the leased entry, recording the outcome and (for `done`) the created object's identity for read-back reconciliation. + +Known discrepancy: `--outcome` has **no client-side default or validation** — omitted, it sends the empty string and the broker decides. The usage line presents it as a normal optional flag with a closed value set; the closed set is enforced, if at all, broker-side only. This chapter documents the source behaviour. + +Exit codes: 0 ok · 2 usage / missing `` · 3 transport · 4 broker store failure. + +```text +$ fleet queue outbox resolve 77 --outcome done --github-number 13170 --github-url https://github.com/developing-today/code/issues/13170 +{"ok": true, "row": {"id": 77, "state": "done", "github_number": 13170}} +``` + +### fleet queue outbox drain + +```text +usage: repo-queue outbox drain [--owner ] [--max ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--owner` | owner name | `outbox-drainer` | Drainer identity used for claims. | +| `--max` | integer | 20 | Max items to drain this run, floored at 1. | + +**Behaviour.** The pilot drainer itself. Loop: claim → if the entry is `uncertain`, reconcile by marker first (search + strongly-consistent list scan; a lookup that *could not check* keeps the entry uncertain with the error class recorded and **never re-creates**) → create via `gh` (pacing: ≥2 s between creates; the broker enforces circuit + hourly budget at claim) → verify by read-back → resolve. Per-item output lines are JSON: `{"id","outcome":"done"|"uncertain"|"rate_limited"|"failed"|"reconciled"|"lookup_unchecked", …}`; when the claim comes back empty it prints `{"drained": k, "idle": true, "claim": }` and exits 0; after `--max` items, `{"drained": k, "idle": false}`. Create outcomes map: created+verified → `done`; created but read-back failed or ambiguous output → `uncertain`; 403/429/rate-limit → `rate_limited`; other failure → `failed`. + +Exit codes: 0 drained / idle · 2 usage · 3 transport (a broker failure stops the drain visibly) · 4 broker store failure. + +```text +$ fleet queue outbox drain --max 5 +{"id": 77, "outcome": "done", "github_number": 13170} +{"drained": 1, "idle": true, "claim": {"ok": true, "row": null}} +``` + +## fleet queue stack + +```text +usage: repo-queue stack ... +``` + +A stack is a recorded, ordered set of **merge intents** — finished branches with their authoring lane/worker/session — stored in the broker's `merge_intents` table (unique on `(stack_id, position)` and `(repo, branch)`). Intent states: `intended → replaying → landed`, plus `conflicted` and `abandoned` — five states in total; legality of every move is decided by the pure core's transition table, never in SQL. A conflicted intent returns only through its recorded authoring lane. + +Each subverb below follows the reference format. + +### fleet queue stack record + +```text +usage: repo-queue stack record --stack --repo --branch [--base-branch ] [--head-sha ] [--issue ] [--pr ] --lane [--worker ] [--session-id ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--stack` | stack id | **required** | Stack to append to. Missing → exit 2. | +| `--repo` | repo | **required** | The intent's repo. Missing → exit 2. | +| `--branch` | branch name | **required** | The finished branch. Missing → exit 2. | +| `--base-branch` | branch name | unset | Base the branch was authored against. | +| `--head-sha` | commit SHA | unset | Recorded head SHA. | +| `--issue` | issue number | unset | Linked issue. | +| `--pr` | PR number | unset | Linked PR. | +| `--lane` | lane id | **required** | Authoring lane (the owner lane for conflict routing). Missing → exit 2. | +| `--worker` | worker id | caller's worker (`repo-worker-code`) | Authoring worker. | +| `--session-id` | session id | unset | Authoring session. | + +**Behaviour.** The append is fail-fast validated client-side with the *same* pure-core rules the broker applies, and the broker additionally validates the (lane, worker) pair against the lane registry — an unregistered owner lane is refused. POST `/stack-record`; prints the row. + +Exit codes: 0 ok · 2 usage / missing required flag / validation failure · 3 transport · 4 broker store failure / broker refusal. + +```text +$ fleet queue stack record --stack book-13165 --repo developing-today/code --branch writer/w2-queue --lane code-a +{"stack_id": "book-13165", "position": 0, "repo": "developing-today/code", "branch": "writer/w2-queue", "state": "intended"} +``` + +### fleet queue stack list + +```text +usage: repo-queue stack list [--stack ] [--worker ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | stack id | one of positional / `--stack` required | The stack to list. | +| `--stack` | stack id | unset | Alternative spelling of the positional. If both are given and disagree → exit 2. | +| `--worker` | worker id | `repo-worker-code` | Caller identity. | + +**Behaviour.** POST `/stack-list`; prints the derived stack state (the full state is answered from the database alone). + +Exit codes: 0 ok · 2 usage / disagreeing ids · 3 transport · 4 broker store failure. + +```text +$ fleet queue stack list book-13165 +{"stack_id": "book-13165", "intents": [{"position": 0, "branch": "writer/w2-queue", "state": "intended"}]} +``` + +### fleet queue stack transition + +```text +usage: repo-queue stack transition --stack --position --to [--pr ] [--conflict-detail ] [--worker ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--stack` | stack id | **required** | The stack. Missing → exit 2. | +| `--position` | integer | **required** | The intent's position. Missing → exit 2. | +| `--to` | intent state | **required** | Target state; must parse as an intent state (`intended`, `replaying`, `landed`, `conflicted`, `abandoned`). Missing/unparseable → exit 2. | +| `--pr` | PR number | unset | PR associated with the move. | +| `--conflict-detail` | text | **required when `--to conflicted`** | What the authoring lane must resolve. A move to `conflicted` without it → exit 2. | +| `--worker` | worker id | `repo-worker-code` | Caller identity. | + +**Behaviour.** An illegal move is a broker refusal, not a write. POST `/stack-transition`. + +Exit codes: 0 ok · 2 usage / missing required flag / conflicted without detail · 3 transport · 4 broker store failure / illegal move refused. + +```text +$ fleet queue stack transition --stack book-13165 --position 0 --to replaying +{"stack_id": "book-13165", "position": 0, "state": "replaying"} +``` + +### fleet queue stack restack + +```text +usage: repo-queue stack restack --stack --position --base [--head-sha ] [--worker ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--stack` | stack id | **required** | The stack. Missing → exit 2. | +| `--position` | integer | **required** | The intent's position. Missing → exit 2. | +| `--base` | branch name | **required** | The new base branch. Missing → exit 2. | +| `--head-sha` | commit SHA | unset | New head SHA after the restack. | +| `--worker` | worker id | `repo-worker-code` | Caller identity. | + +**Behaviour.** Acknowledges that an intent's author restacked its branch off a withdrawn base; the broker re-plans with the core's `plan_restack` (taint rules bind there) and refreshes the recorded `base_branch`. POST `/stack-restack`. + +Exit codes: 0 ok · 2 usage / missing required flag · 3 transport · 4 broker store failure. + +```text +$ fleet queue stack restack --stack book-13165 --position 0 --base main +{"stack_id": "book-13165", "position": 0, "base_branch": "main", "state": "intended"} +``` + +### fleet queue stack replay + +```text +usage: repo-queue stack replay [--stack ] [--worker ] [--repo-dir

] [--dry-run] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--stack` | stack id | **required in practice** | The stack to replay. The usage line brackets it optional, but missing → exit 2. | +| `--worker` | worker id | `repo-worker-code` | Caller identity. | +| `--repo-dir` | directory | `.` | Checkout to replay in. | +| `--dry-run` | boolean | off | Print the plan JSON — exactly what a live pass would do — and change nothing. | + +**Behaviour.** The replay executor: walks the stack's recorded merge order bottom-up and lands it — rebase onto new main, push (force-with-lease pinned to the verified pre-rebase tip), open PR, merge, mark landed, post the outcome note — one intent at a time. `--dry-run` prints `{"stack_id","dry_run":true,"plan":[{"position","branch","action"}]}`. Refuses a checkout with somebody else's rebase already in progress. Replay never resolves a conflict itself. + +Exit codes: 0 landed/idle (an empty plan prints a `note` explaining the stack is empty, finished, or blocked at a conflicted head) · 2 usage / missing `--stack` · **3** any other step failure — the intent is left `replaying` and a later `stack replay` resumes it (including the case where the conflict itself could not be recorded) · **4** a rebase/merge conflict was recorded `conflicted` and routed to its authoring lane (the JSON carries `conflict {position, detail, route {owner_lane, owner_worker, owner_session, repo, branch, base_branch, issue_number}}`). + +```text +$ fleet queue stack replay --stack book-13165 --dry-run +{"stack_id": "book-13165", "dry_run": true, "plan": [{"position": 0, "branch": "writer/w2-queue", "action": "rebase+merge"}]} +$ fleet queue stack replay --stack book-13165 +{"stack_id": "book-13165", "landed": [0], "state": "landed"} +``` diff --git a/pkgs/fleet/book/reference/queue-core.md b/pkgs/fleet/book/reference/queue-core.md new file mode 100644 index 0000000000..23098532a1 --- /dev/null +++ b/pkgs/fleet/book/reference/queue-core.md @@ -0,0 +1,258 @@ +# fleet queue: core verbs + +`fleet queue` is the repo work queue: enqueue, claim, and complete tasks through the queue broker. Inside the binary the same surface is the standalone `repo-queue` program, and every per-verb usage string says `repo-queue`, not `fleet queue`; the two spellings are identical. The full command list is: `validate, enqueue, list, claim, release, lane, bind, heartbeat, checkpoint, park, wake, block, unblock, dep-recheck, quarantine-recheck, cancel, revive, fail, complete, verify-disposition, timeline, history, show, models, health, signal, fallback, dispatch, session, surfaces, outbox, stack`. + +Task states are `queued`, `claimed`, `parked`, `blocked`, `needs_review` (live) and `done`, `failed`, `cancelled` (terminal). + +This chapter covers the core verbs — `validate`, `enqueue`, `list`, `claim`, `release`, `show`, `health`. The lifecycle verbs are in [fleet queue: lifecycle verbs](queue-lifecycle.md), the GitHub fallback in [fleet queue: the fallback queue](queue-fallback.md), dispatch and sessions in [fleet queue: dispatch and sessions](queue-dispatch.md), and inspection/admin in [fleet queue: inspection and admin](queue-admin.md). + +## How the client reaches the broker + +The client never touches the database and never fetches from Bitwarden; it POSTs JSON to the **queue-broker**, which is the only process that talks to the Turso store (database `fleet-queue`). There are two routes, in selection order: + +1. **Direct route (on-laptop)**, chosen when a broker URL is configured: environment `REPO_QUEUE_BROKER_URL`, else the file `~/.config/repo-queue/broker-url`. A `unix://` value selects the broker's Unix socket; anything else is read as `http://host:port` TCP (the broker dual-binds TCP + UDS; default TCP bind is the laptop tailnet address, port 4801). The direct-route token comes from env `REPO_QUEUE_TOKEN_FILE`, else `~/.config/queue-broker/token`, sent as header `X-Agent-Token`. Wire: raw HTTP/1.1, read timeout 300 s, write timeout 60 s. With no configured URL, fleet-config's probe-based choice for the `queue-broker` role applies: a live role socket selects UDS; a failed UDS attempt falls back to the session-proxy route within the same call. +2. **Session-proxy route (sandbox default):** the client connects to the laptop-agent session proxy's Unix socket — `$HOME/.cache/laptop-agent/broker.sock` (fleet-config's `broker_socket()` wins when it loads; env beats config file beats that compiled-in default). Framing: 8-byte big-endian length prefix + one JSON envelope `{method:"POST", path, body, port:4801, token_file:"/tools/queue-broker-token"}`. The proxy, on the laptop, reads the named token file there and forwards to the broker on port 4801. Read timeout 660 s. On a failed first attempt the client auto-spawns the proxy/broker program — a sibling `fleet` binary (`fleet proxy serve`) always wins; the Python `~/tools/laptop-agent-broker.py` is the fallback for standalone rollback builds — waits up to ~5 s for the socket, and retries once. + +Broker-unavailable on either route is exit 3, or the fallback switch (exit 6) for the work verbs — see [fleet queue: the fallback queue](queue-fallback.md). + +Broker envelopes are `{ok:true, ...}` or `{ok:false, exit, error}`; the client prints `error` and exits with `exit`. A broker envelope whose error carries PostgREST code `57014` (statement timeout) or `PGRST002` (schema cache) is retried with exponential backoff + jitter — base 500 ms, ×2, cap 20 s, max 6 attempts. Safe for writes because a 57014 means the statement rolled back. + +Broker server facts that shape client behaviour: the pre-body gate refuses from headers alone — wrong/missing token → `401 {"error":"unauthorized"}`; `Content-Length` over the 16 MiB cap → `413 {"error":"request body too large"}`. The only unauthenticated route is `GET /healthz` → `{"service":"queue-broker"}`. Non-POST → 405. Token files are read + trimmed; a missing, unreadable, empty, or whitespace-only file is a hard error naming the file. Before dispatch, the broker re-validates durations and `not_before` with the same ranges as the client; violations answer `{ok:false, exit:2, …}`. `/validate` and `/healthz` are served without the Turso backend; everything else answers exit 3 `queue backend not ready: …` until the backend connects. + +## Global parsing rules and defaults + +- **Help:** `repo-queue` with no args prints the top usage and exits 2; a single `--help`/`-h`/`help` exits 0. ` --help` anywhere in the verb's args prints that verb's exact usage and exits 0 — help wins over every other argument, *except* when the help-looking token is the value of a value-flag (`fail 5 --error help` records the error text "help"; `park 5 --reason -h` parks with reason "-h"). +- **Parsing errors are exit 2:** unknown flag, duplicate flag, a boolean given an inline value (`--dry-run=false`), a value flag with no value, a value flag followed by another `--flag` token, extra positionals past a verb's arity (rejected before any broker contact), and non-numeric values for numeric flags (the message names the flag). Message + the verb's usage go to stderr. +- **`--worker` default:** `repo-worker-code`. Exceptions: `cancel` defaults its worker to `fleet-monitor` (see [lifecycle verbs](queue-lifecycle.md)); `stack record`'s owner worker and the outbox owner defaults differ (see [inspection and admin](queue-admin.md)). +- **`--queue` default — the divergence.** The nominal default is `repo-health-code-shadow`, overridable by env `REPO_QUEUE_DEFAULT_QUEUE` — **but** `claim` and `list` are *unscoped* when neither flag nor env is present (one-queue model: the broker works across the one fleet queue), and `enqueue` has **no** default at all. Every other verb keeps the shadow default. The help surface presents all three behaviours identically (`[--queue ]` everywhere), so the divergence is invisible from help alone. Known discrepancy: this divergence is deliberate in source (#7016, #8097) but undocumented in help. +- **`--lane`** on the holder-checked verbs (heartbeat, checkpoint, park, release, block, fail, complete): flag, else env `REPO_QUEUE_LANE`, else null — the broker then checks the worker alone. All scheduled lanes share one worker id, so the lane is what tells the broker whose claim a verb acts on. +- **`--progress` / `--progress-file`** are mutually exclusive (both → exit 2). The file form reads the file's text as the progress value. +- **`--execution `** (park, fail, complete) is parsed into an execution record `{lane, lane_id?, session_id, fallback_reason?}`; a lane-looking value (e.g. `opencode-a`, `any-n`) is split into mode (`opencode`/`direct`) + `lane_id`; the mode-only values `direct`/`opencode` pass through unchanged. +- **Durations are rejected, never clamped**, identically at client and broker: lease 1..=86400 (default 2700), heartbeat extend 1..=86400 (default 900), park delay 1..=604800 (no default), list limit 1..=500 (default 20). `not_before` must be a non-empty RFC 3339 timestamp no more than 366 days in the future. +- **Mode line:** claim, heartbeat, checkpoint, complete (and the fallback-switch envelope) carry a `mode_line` object `{verb, mode, route}` selected by the routing contract from observed legs (database / replica / github-write / github-read). Modes: `normal` (route `cloud`), `gh-read-degraded`, `gh-write-degraded`, `db-degraded` (route `github-markers`). + +## Exit codes (the whole queue client) + +Stated once here and referenced by every other queue chapter: + +- **0** — success. +- **1** — gate / not-found: `verify-disposition` gate failure or unreadable GitHub readback; `show` task not found; fallback `complete` disposition rejection. +- **2** — usage error (message + usage on stderr). +- **3** — transport / broker-path failure: broker unreachable, HTTP 401 (token rejected), HTTP ≥400 broker error, malformed broker reply, unwritable signal file, `/events-list` not served by the broker (timeline/show), home unresolvable. +- **4** — broker store failure: the default when a broker envelope `{ok:false}` carries no `exit` of its own; broker-side store/transport failures are emitted as exit 4. Also `stack replay`'s routed-conflict exit. +- **5** — no-claim / no-row: the verb ran but there is no matching claimed row / no claimable task (`require_row` failure: "no matching claimed row (task not claimed by this worker, or already terminal)"). +- **6** — fallback switch: a work verb's primary-store failure switched the work to the GitHub fallback (see [the fallback queue](queue-fallback.md)). + +Sources: [fleet-queue client](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client.rs), [client support](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/support.rs), [client transport](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/transport.rs), [queue broker](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs), [Turso queue store](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs). + +## fleet queue validate + +```text +usage: repo-queue validate +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | file path | required | The packet JSON file to validate. | +| _(no flags)_ | — | — | `validate` has no flags at all — not even `--json`; output is always the JSON object below. | + +**Behaviour.** Loads the packet and validates it *through the broker* (`/validate`). An unreadable file dies exit 2 `cannot read packet file: …`; invalid JSON dies exit 2 `packet file is not valid JSON: …`. Validation failure dies with the broker's exit code and the joined error list. On success it prints, on stdout, `{"valid": true, "dedupe_key": , "kind": , "title": }`. + +The validator checks, among other things: `priority` on the design scale [10, 20, 30, 40, 50, 70, 90]; `max_attempts` 1..=1000 (design default 1000); payload size hard ceiling 16384 bytes (warn above 4096); the payload `schema` const `"repo-task/v1"`; `kind` one of six values the validator allows (`pr_shepherd, triage, small_fix, ci_investigation, second_pass, feature_slice`); `repo` on the validator's 9-repo allowlist; and the identity rule — a packet must carry at least one of `issue`, `prs` (non-empty), `set`, or `source`. + +Known discrepancy: the published packet schema (`repo-task-v1.schema.json`) allows only 4 kinds and 8 repos; the validator allows 6 kinds (adding `second_pass`, `feature_slice`) and 9 repos (adding legacy `dezren39/nix`, kept for in-flight dedupe keys after the rename to `dezren39/darwin-nix`). A packet valid to the broker can be invalid against the published schema, and vice versa. This chapter documents the validator (source) behaviour. + +Exit codes: 0 valid · 2 unreadable file / invalid JSON / usage · broker's exit code on validation failure. + +```text +$ fleet queue validate ./task.json +{"valid": true, "dedupe_key": "fix: repo-health:v1:fix:developing-today/code:issue:13165", "kind": "small_fix", "title": "Write the fleet book queue chapters"} +``` + +## fleet queue enqueue + +```text +usage: repo-queue enqueue [--queue ] [--platform

] [--dry-run] [--shadow-intent] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | file path | required | The packet JSON file to enqueue. | +| `--queue` | queue name | **none — required in effect** | Target queue stream. Resolution: `--queue` flag → the packet's own `"queue"` field → env `REPO_QUEUE_DEFAULT_QUEUE`. With none of the three: exit 2 (see Behaviour). | +| `--platform` | platform family | unset | Restricts the item to a platform family; validated client-side. Absent = unset, claimable anywhere. | +| `--dry-run` | boolean | off | Validate + ask the broker to build the row, print it, file nothing. | +| `--shadow-intent` | boolean | off | Required to enqueue into a queue whose name ends in `-shadow`; without it, exit 2. | + +**Behaviour.** Flow: read packet (exit 2 shapes as in `validate`) → broker `/validate` (a dry run still validates, with `dry_run` noted) → shadow guard → POST `/enqueue` `{packet, queue, dry_run, shadow_intent, platform}`. + +Queue resolution deliberately differs from every other verb: with no flag, no packet `"queue"` field, and no env, enqueue dies exit 2 with `enqueue: no queue resolved — … (enqueue has no default queue; the old shadow default silently misrouted work)`. + +Outputs: + +- **Dry run:** the would-be task row as JSON, with two extra keys: `"_dry_run": true` and `"_rpc": "agent.enqueue_repo_task"`. Exit 0. +- **Real run:** one human line, any `warning: …` lines, then the task row as JSON. Exit 0. The line is one of: + - `enqueued new task (queue , status )` — row created within 10 s skew of the call; + - `dedupe hit: existing task (queue , status , created )` — the dedupe key already has a live row; nothing was filed. Warnings are added when the holding row is in a different queue than requested, or in a terminal state; + - `revived: existing task (…)` — dedupe hit on a `queued` row whose `updated_at` is fresh (broker revived it in place); + - `revived: new task (…), predecessor task ()` — the envelope carried `revived_from`: the key's prior task was terminal, a fresh task was created linked to it; + - `work already queued: existing task (queue , status ) holds ; nothing filed (set payload.dedupe_override to file a deliberate parallel)` — the envelope carried `work_identity_collision`: a *live* task already holds this work identity (repo, issue, kind family), regardless of dedupe key. + +Dedupe semantics: dedupe is by `(queue, dedupe_key)` among **live** rows (the Turso backend does a read-then-insert check — its `(queue, dedupe_key)` index is deliberately NOT unique). A key held only by terminal rows accepts a new row. A *cancelled* row is revived in place by enqueue (fields reset, attempts 0, lease deleted, `enqueued` event flagged `revived_from_cancelled`); a *failed* row deliberately does not revive — re-enqueue of a failed identity files a new row or is an explicit operator action (the `revive` verb). + +At enqueue the broker also: enriches a packet that names an issue but carries no `labels` array from the GitHub mirror in the same store; selects the stored priority from label bands (`expedite` → 15, `next-up` → 25 — stored values deliberately not on the packet priority scale); and normalizes `max_attempts` / `required_budget_minutes` from the packet copy into the payload mirror. + +Exit codes: 0 enqueued / dedupe hit / revived / dry run · 2 unreadable packet, invalid JSON, no queue resolved, shadow queue without `--shadow-intent`, usage · 3 transport · 4 broker store failure. + +```text +$ fleet queue enqueue ./task.json --queue repo-health-code +enqueued new task 19479 (queue repo-health-code, status queued) +{"id": 19479, "queue": "repo-health-code", "status": "queued", "dedupe_key": "fix: repo-health:v1:fix:developing-today/code:issue:13165", "payload": {"schema": "repo-task/v1", "kind": "small_fix", "…": "…"}} +``` + +## fleet queue list + +```text +usage: repo-queue list [--queue ] [--status ] [--limit ] [--not-before ] [--lane ] [--worker ] [--task ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--queue` | queue name | unscoped | Flag → env `REPO_QUEUE_DEFAULT_QUEUE` → **no scope** (all queues). Never the shadow default. | +| `--status` | status string | unset | Filter by status. Help names `queued\|parked\|claimed\|blocked` as the actionable set; any status string is forwarded. | +| `--limit` | integer | 20 | Range 1..=500, rejected (never clamped) outside it, exit 2 naming `--limit`. | +| `--not-before` | RFC 3339 timestamp | unset | Filter; validated client-side with the park/revive rule, exit 2 on garbage. | +| `--lane` | lane id | unset | Filter forwarded to the broker. | +| `--worker` | worker id | unset | Filter forwarded to the broker. | +| `--task` | task id | unset | Narrow to one task regardless of status ordering — the recovery path for verifying a just-completed task. | + +**Behaviour.** A bare `list` prints a scope note to **stderr**: it shows one queue (or every queue when unscoped) in the broker's default ordering — *newest terminal rows first* — "not the actionable set", with pointers to `--status`, `--queue`, `--limit`. Fetching is paged at 100 rows/page with broker offsets, because a single oversized `/list` reply used to render as a silent "(no tasks)". A reply with no `rows` array is an error (exit 3), never an empty list. + +Output is a table with columns `task, priority, status, age, dedupe_key, title` (title truncated to 72 chars); `(no tasks)` when empty. When the broker reports a total: `(N matching tasks)`, or `(truncated: showing X of N matching tasks — raise --limit to see more)`. There is **no `--json` flag** on list. + +Exit codes: 0 ok · 2 usage (including out-of-range `--limit`, bad `--not-before`) · 3 transport / malformed reply · 4 broker store failure. + +```text +$ fleet queue list --status queued --limit 3 +task priority status age dedupe_key title +19479 20 queued 4m fix: repo-health:v1:fix:developing-today/code:issue:13165 Write the fleet book queue chapters +19480 30 queued 2m triage: repo-health:v1:triage:developing-today/code:issue:13170 Triage the failing nightly +(2 matching tasks) +``` + +## fleet queue claim + +```text +usage: repo-queue claim [--queue ] [--worker ] [--lease-seconds ] [--lane ] [--task ] [--count ] [--from-session ] [--platform

] [--session-id ] [--model-provider

] [--model-id ] [--model-variant ] [--filter ] [--pool

] [--launched-by ] [--remaining-budget-minutes ] [--handoff] [--bind] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--queue` | queue name | unscoped | Flag → env → unscoped across the one fleet queue, priority order. | +| `--worker` | worker id | `repo-worker-code` | Claiming worker identity, stamped on the row + `leases` table. Passing it explicitly counts as claim intent even though it equals the default (see bare-claim refusal). | +| `--lease-seconds` | integer seconds | 2700 (45 min) | Lease length. Range 1..=86400, rejected outside, exit 2. A 0/negative lease is "born expired". | +| `--lane` | lane id | unset | Lane identity for this claim; validated broker-side against the lane registry (unknown lane / worker mismatch / disabled lane / queue mismatch each refuse and claim nothing). Canonical lane universe: 6 families (`code, any, not-code, opencode, openchamber, nix`) × `a..=z` = 156 lanes, all enabled. | +| `--task` | task id | unset | By-id claim: take exactly that row when the by-id predicate allows (a queued row under the ordinary predicate, or a sink/handed-off row). | +| `--count` | integer | 1 | Batch claim: the broker runs the same atomic pick n times. Range 1..=5, enforced client- and broker-side; outside → exit 2. | +| `--from-session` | session id | unset | With `--task`: session-to-session **transfer**. The named session must be the task's current holder (its session mark is the capability); a mismatch refuses and leaves the claim untouched. The task never passes through queued/parked. | +| `--platform` | platform family | unset | A *mark*, not a filter: stamped on the row and the claimed event; a mismatched or undeclared claim claims items all the same. | +| `--session-id` | session id | unset | The claiming session's own id, recorded as a mark on the claimed event; also enables model-stamp derivation and `--bind`. Session ids have the shape `ses_` + alphanumerics. | +| `--model-provider` | provider name | unset | The claiming session's serving model provider, stamped by the broker as the row's `claim_provider`. | +| `--model-id` | model id | unset | Stamped as the row's `claim_model`. | +| `--model-variant` | variant name | unset | Stamped as the row's `claim_variant`. If all model flags are absent and `--session-id` is given, the stamp is *derived* from the session's own record; derivation failure never fails the claim. | +| `--filter` | filter expression | unset | Claimer-side boolean filter expression over task metadata (repo, queue, pool, platform, label, kind, priority, lane, model), evaluated by the broker inside the claim. | +| `--pool` | pool identity | unset | The claimer's declared pool identity; recorded like the other marks and used only to satisfy a task's own `requires.pool`. | +| `--launched-by` | who | `opencode-claimant` (only sent with `--bind`) | Who launched the bound session. | +| `--remaining-budget-minutes` | integer minutes | unset | The claimer's remaining shift budget. The broker only matches requirement-bearing tasks whose `required_budget_minutes` fits; omitting it leaves requirement-bearing tasks unclaimed. Skips are reported (see no-claim output). | +| `--handoff` | boolean | off | Pick = the next recorded opencode handoff (status `handed_off`) from the sink; the broker picks the row, the caller names no task. | +| `--bind` | boolean | off | Claim + lane-assign + session-bind in ONE broker round trip via `/claim-flow`. Requires `--session-id`, a single (non-batch) claim, and no `--from-session`; violations die exit 2 before broker contact. A post-claim lane/bind failure inside the flow is answered as a partial SUCCESS envelope carrying `claim_flow_partial` (never a retryable error) — the client prints the note on stderr and stamps `claim_flow_partial` onto the printed row. | + +**Behaviour — bare-claim refusal.** A claim with no task, no filter, no queue scope, no count, no handoff/bind, and no identity marks (worker, lane, session-id, pool, platform, from-session) is refused *before any broker contact*, exit 2: "a bare claim is never a meaningful intent and has repeatedly stolen the queue's top task during CLI probing". + +**Behaviour — the pick.** One atomic conditional update (libSQL is single-writer, so the claim is one conditional UPDATE whose WHERE re-checks claimability against the picked row; a competing claim after the first lands matches no row and returns no claim, exit 5). Eligible: `queued` rows with `attempts < max_attempts` and `not_before` null or due, plus `parked` rows whose `not_before` is due. Order: `priority ASC, created_at ASC` (lowest number = highest priority). Claiming sets status `claimed`, `worker_id`, `claimed_at`, `lease_until = now + lease_seconds`, upserts the `leases` row, writes a `claimed` event — and increments `attempts` by 1 for a fresh (queued) claim but **0 for a parked resume** (park/resume must not consume attempts; the event carries `resumed_from_park`). Every claim first runs lease expiry opportunistically: abandoned claims whose lease lapsed become claimable at the moment anyone looks. + +**Behaviour — no-double-serve guard.** After a successful primary claim, the client checks the task's issue against the GitHub fallback (see [the fallback queue](queue-fallback.md)). If the issue is `live` or `contested` in the fallback under a *different* worker, the client immediately blocks the task back with reason-class `fallback_held` and prints `{"task": null, "guard": "fallback_held", "held_by": , "repo": …, "issue": …}`, exit 5. If the GitHub check itself fails, the claim is served with a `guard_warning` key added (the guard fails open; a GitHub outage must not stall every claim). Batch claims run the same guard per row; held rows land in `guard_held`. + +**Behaviour — timeline mirroring.** On a pre-#9046 broker the client appends `session_bound` / `model_stamp` events after a claim (and a `session_unbound` for the from-session on a transfer); a post-#9046 broker stamps in-op and its rows carry `claim_session_id`, making the appends a no-op. Timeline appends are fail-soft — they warn, never fail the claim. + +**Output.** Success: the task row **verbatim** as JSON (the row is the contract: `{id, queue, status, dedupe_key, payload, …}`), exit 0, plus a `mode_line`. A row that arrives with a null or empty-object `payload` is treated as payload-less and reported as *no claim*. Batch output: `{"tasks": […rows…], "claimed": k, "requested": n, "guard_held": […]}`, exit 0 when k ≥ 1. No-claim output: `{"task": null}` — deliberately carrying no id/queue/status a caller could mistake for a task — plus any of `budget_skipped`, `max_required_budget_minutes`, `queued`, `at_cap_queued`, `queued_not_yet_due`, `parked_due` the broker supplied; stderr gets the diagnostic `no claimable task — Q queued (A at the attempt cap, D not yet due), P parked due` (with `; every queued task is at the attempt cap` when that is the whole story). Exit 5. + +Exit codes: 0 claimed · 2 usage / bare-claim refusal / out-of-range lease or count / `--bind` precondition failure · 3 transport · 4 broker store failure · 5 no claimable task, or claim held by the no-double-serve guard · 6 fallback switch on primary-store failure. + +```text +$ fleet queue claim --worker repo-worker-code --lane code-a --session-id ses_01J9EXAMPLE0000000000000 +{"id": 19479, "queue": "repo-health-code", "status": "claimed", "worker_id": "repo-worker-code", "lane_id": "code-a", "lease_until": "2026-11-23T04:50:00Z", "dedupe_key": "fix: repo-health:v1:fix:developing-today/code:issue:13165", "payload": {"schema": "repo-task/v1", "kind": "small_fix"}, "mode_line": {"verb": "claim", "mode": "normal", "route": "cloud"}} +$ fleet queue claim --worker repo-worker-code --lane code-a +{"task": null, "queued": 0, "parked_due": 0} +no claimable task — 0 queued (0 at the attempt cap, 0 not yet due), 0 parked due +(exit 5) +``` + +## fleet queue release + +```text +usage: repo-queue release [--worker ] [--lane ] [--reason ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to release. | +| `--worker` | worker id | `repo-worker-code` | Holder identity; the row must be claimed by this worker (and lane, when supplied). | +| `--lane` | lane id | env `REPO_QUEUE_LANE`, else null | Holder lane check; null means the broker checks the worker alone. | +| `--reason` | text | **required** | Why this task goes back to the pool; recorded on a `released` event. Must be non-empty. | + +**Behaviour.** Returns the task to `queued`, immediately claimable; the reason is recorded on a `released` event. Used by dispatch for an item whose sub-task failed to launch/bind — back to the pool in the same touch instead of sitting claimed until lease expiry. Release also closes the session binding window on the timeline (`session_unbound`, trigger `release`). On success it prints the broker's returned task row as JSON and exits 0. When no matching claimed row exists, it dies exit 5 with `release: no matching claimed row (task not claimed by this worker, or already terminal)`. + +Known discrepancy: help brackets `--reason` as optional (`[--reason ]`); source makes it **required and non-empty** — missing → exit 2 `release requires --reason "" (#8217)`. This chapter documents the source behaviour. (The top-level usage line additionally omits `[--lane ]`, which the per-verb usage, the help dump, and the implementation all have.) + +Exit codes: 0 released · 2 usage / missing or empty `--reason` · 3 transport · 4 broker store failure · 5 no matching claimed row. + +```text +$ fleet queue release 19479 --worker repo-worker-code --lane code-a --reason "sub-task failed to launch; returning to pool" +{"id": 19479, "queue": "repo-health-code", "status": "queued", "worker_id": null, "lease_until": null} +``` + +## fleet queue show + +```text +usage: repo-queue show [--limit ] [--json] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The task to show. | +| `--limit` | integer | 10 | History tail length; validated with the list-limit rule (1..=500), rejected outside, exit 2. | +| `--json` | boolean | off | Print the details + history as JSON instead of the rendered form. | + +**Behaviour.** Shows one task's current details + recent history: the rich `/list` row for the task is the source of truth for mutable state, plus the tail of the same 14-kind event timeline `timeline` reads (see [inspection and admin](queue-admin.md)). Task not found: stderr `repo-queue show: task not found`, exit 1. A broker without `/events-list`: exit 3. + +Exit codes: 0 ok · 1 task not found · 2 usage · 3 transport / broker does not serve `/events-list` · 4 broker store failure. + +```text +$ fleet queue show 19479 +task 19479 — repo-health-code — claimed by repo-worker-code (lane code-a) +title: Write the fleet book queue chapters +lease_until: 2026-11-23T04:50:00Z +recent events: claimed, session_bound, checkpoint +``` + +## fleet queue health + +```text +usage: repo-queue health [--queue ] [--worker ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--queue` | queue name | unset | Scopes the request body when given. Health uses the plain flag only — no env/shadow-default resolution is applied to the body. | +| `--worker` | worker id | `repo-worker-code` | **Attribution only** — accepted because the claimant packet mandates `--worker` on every verb; it changes neither the request body nor the printed table. | + +**Behaviour.** POSTs `/health` through the fallback-switch path: a dead primary switches the work to the GitHub fallback, exit 6 (see [the fallback queue](queue-fallback.md)). Output: first line `project: (resolved via )` (source defaults to `bitwarden`), then a table whose columns are whatever keys the broker's health rows carry (per-queue counts by status); `(no queues have tasks)` when empty. This verb is distinct from the broker's unauthenticated `GET /healthz`. + +Exit codes: 0 ok · 2 usage · 3 transport · 4 broker store failure · 6 fallback switch on primary-store failure. + +```text +$ fleet queue health +project: db.dezren39.turso.io (resolved via bitwarden) +queue queued claimed parked blocked done +repo-health-code 12 3 1 0 481 +``` diff --git a/pkgs/fleet/book/reference/queue-dispatch.md b/pkgs/fleet/book/reference/queue-dispatch.md new file mode 100644 index 0000000000..e9289c77f0 --- /dev/null +++ b/pkgs/fleet/book/reference/queue-dispatch.md @@ -0,0 +1,147 @@ +# fleet queue: dispatch and sessions + +`dispatch`, `session`, and `surfaces` are *not* broker verbs: they are the absorbed `fleet-place` reference implementation, deciding **where a build job runs** across the fleet's GitHub Actions copies and runner providers, and dispatching it there as the developing-today GitHub App. The surface registry is data (`fleet-surfaces.json`); no surface is hardcoded. Errors in this family print `repo-queue: ` and exit **2**. This `dispatch` is unrelated to `fleet dispatch` / `dispatch-test` at the top level of the binary (separate domains). + +Shared context is in [fleet queue: core verbs](queue-core.md). + +Sources: [placement.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/placement.rs), [fleet-surfaces.json](https://github.com/developing-today/code/blob/main/pkgs/fleet/fleet-surfaces.json). + +## fleet queue dispatch + +```text +usage: repo-queue dispatch --repo --command '' [--ref REF] [--runner auto|github|blacksmith] [--platform linux|macos] [--container IMAGE] [--surface ID] [--followup HANDLE|OWNER/REPO#RUN_ID] [--push-nix-cache] [--actions-cache KEY:PATH] [--actions-cache-restore-key PREFIX]... [--allow-paid-blacksmith MINUTES] [--laptop-busy] [--dispatch] [--json] [--registry PATH] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--repo` | `owner/name` | **required** | Target repo; must match a surface's targets. Missing → exit 2. | +| `--command` | command string | **required** | The command the surface's `fleet-command.yml` workflow runs. Missing → exit 2. | +| `--ref` | git ref | empty (workflow default) | Git ref to run at. | +| `--runner` | `auto\|github\|blacksmith` | `auto` | Provider preference; other values die exit 2. | +| `--platform` | `linux\|macos` | `linux` | Other values die exit 2. An undocumented alias `--macos` exists in source. | +| `--container` | image name | unset | Container image for surfaces with `container_input`; empty value dies exit 2. | +| `--surface` | surface id | unset | Pin one surface; an unknown id dies (`--surface : no such surface in the registry`), exit 2. | +| `--followup` | `HANDLE` or `OWNER/REPO#RUN_ID` | unset | Chain this dispatch after a previous run (portable run reference). | +| `--push-nix-cache` | boolean | off | Ask the workflow to push the Nix cache (needs the surface's cache secrets). | +| `--actions-cache` | `KEY:PATH` | unset | One Actions cache binding; must be non-empty `KEY:PATH`, else exit 2. (Single value in source despite the plural name.) | +| `--actions-cache-restore-key` | prefix | unset | Restore-key prefixes. **Repeatable.** | +| `--allow-paid-blacksmith` | minutes (number) | `0` | Raise the Blacksmith paid cap for this dispatch only; must parse as a number, else exit 2. | +| `--laptop-busy` | boolean | off | Manually mark the laptop busy (the registry's saturation signal for the codespace tier is deliberately a manual flag, "not scraped telemetry"). | +| `--dispatch` | boolean | off | **Actually dispatch.** Without it the verb is a dry run (the default). | +| `--json` | boolean | off | Machine-readable decision/session output. | +| `--registry` | file path | resolution order (see `surfaces`) | Placement registry file. | +| `--assume-owner-load` | `owner=N[,owner=N…]` | unset | Testing override, labeled as simulation in the output: pretend owner load. | +| `--assume-blacksmith-used` | minutes | unset | Testing override, labeled as simulation in the output: pretend Blacksmith minutes already used. | + +**Behaviour.** Loads the registry, computes live capacity per surface (owner concurrency caps, macOS caps, Blacksmith free-minute budget, codespace liveness, local session history/stickiness), picks a surface + provider, and prints the placement decision. **Dry-run is the default**: without `--dispatch` nothing is dispatched. With `--dispatch` it workflow-dispatches `fleet-command.yml` on the chosen surface's repo (as the GitHub App installation token when the registry says `dispatch_as` app, else the signed-in user's token), writes a **session record**, and prints its handle: `fp_` + 128-bit random. + +Known discrepancy: the help line says `[--ref REF]`; the placement module's frozen-v1 interface comment says `[--ref SHA]`. Cosmetic only; the flag itself is identical. This chapter documents `--ref REF`. + +Exit codes: 0 decision printed (dry run) or dispatched · 2 usage / unknown surface / bad flag value (this family's errors are exit 2). + +```text +$ fleet queue dispatch --repo developing-today/code --command 'nix build .#fleet' --json +{"surface": "fleet-org", "provider": "github", "platform": "linux", "dry_run": true, "reason": "owner capacity available; sticky threshold not reached"} +$ fleet queue dispatch --repo developing-today/code --command 'nix build .#fleet' --dispatch +fp_9f2c41aa07b34d5e8c01aa22334455 +``` + +## fleet queue session status + +```text +usage: repo-queue session [HANDLE|OWNER/REPO#RUN_ID] [--mine] [--json] [--registry PATH] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | session handle `fp_…` or portable ref `OWNER/REPO#RUN_ID` | **required** | The session to inspect. A portable reference is resolved directly against GitHub without the local store. | +| `--mine` | boolean | off | Accepted on the session group (used by `list`; see below). | +| `--json` | boolean | off | Print the record as JSON instead of the one-line text form. | +| `--registry` | file path | resolution order (see `surfaces`) | Placement registry file. | + +**Behaviour.** Session records are a labeled **STOPGAP**: a local JSON store at `~/.local/state/fleet-place/sessions.json` (same path/shape as the reference implementation, so records migrate when the designed placement-sessions table lands). The store is lock-guarded on write. `session status ` refreshes the record from GitHub and prints `: state= surface= run=` (or the record as JSON with `--json`). + +Known discrepancy: `--help` is **not** treated as help here. The token after the subcommand is taken as the HANDLE, so `session status --help` looks up a session literally named `--help` and fails with `repo-queue: no session with handle --help in …/sessions.json`. Only a bare `session --help` (no subcommand) prints usage. The flags documented here come from source. This chapter documents the source behaviour. + +Exit codes: 0 ok · 2 usage / no such handle / missing handle (`session status needs a HANDLE`). + +```text +$ fleet queue session status fp_d0a842c9bd33aa2999f5a12393397ab9 +fp_d0a842c9bd33aa2999f5a12393397ab9: state=running surface="fleet-org" run=https://github.com/developing-today/fleet/actions/runs/45146933211 +``` + +## fleet queue session result + +```text +usage: repo-queue session [HANDLE|OWNER/REPO#RUN_ID] [--mine] [--json] [--registry PATH] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | session handle `fp_…` or portable ref `OWNER/REPO#RUN_ID` | **required** | The session to inspect. | +| `--mine` | boolean | off | Accepted on the session group (used by `list`). | +| `--json` | boolean | off | Print the record as JSON instead of the one-line text form. | +| `--registry` | file path | resolution order (see `surfaces`) | Placement registry file. | + +**Behaviour.** Same refresh as `status`; the output adds `terminal: bool` (`succeeded|failed|cancelled` are terminal) and, when not terminal, the note `not terminal yet — reconnect with the same handle`. Text form: `: (terminal=) run=`. + +Known discrepancy: as with `status`, `--help` after the subcommand is treated as a handle, not as help (see `session status`). Flags are documented from source. + +Exit codes: 0 ok · 2 usage / no such handle / missing handle. + +```text +$ fleet queue session result fp_d0a842c9bd33aa2999f5a12393397ab9 +fp_d0a842c9bd33aa2999f5a12393397ab9: running (terminal=false) run=https://github.com/developing-today/fleet/actions/runs/45146933211 +not terminal yet — reconnect with the same handle +``` + +## fleet queue session list + +```text +usage: repo-queue session [HANDLE|OWNER/REPO#RUN_ID] [--mine] [--json] [--registry PATH] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--mine` | boolean | off | Filter to records whose `submitted_by` is the current user. | +| `--json` | boolean | off | Print `{"sessions": […]}` instead of one status line per session. | +| `--registry` | file path | resolution order (see `surfaces`) | Placement registry file. | + +**Behaviour.** Lists all session records in the local store, newest first. Text form is one status line per session, or `no sessions`; `--json` gives `{"sessions": […]}`. Group-level behaviour: `session` with no subcommand prints the usage and returns 2; `session --help` prints usage and returns 0; an unknown subcommand dies exit 2. + +Exit codes: 0 ok · 2 usage / unknown subcommand. + +```text +$ fleet queue session list +fp_d0a842c9bd33aa2999f5a12393397ab9: state=running surface="fleet-org" run=https://github.com/developing-today/fleet/actions/runs/45146933211 +``` + +## fleet queue surfaces + +```text +usage: repo-queue surfaces [--registry PATH] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--registry` | file path | resolution order (see Behaviour) | Registry file to print. | + +**Behaviour.** Prints the resolved placement registry verbatim as pretty JSON, exit 0. (The help-dump `queue_surfaces.txt` is exactly this output, not help text.) Registry resolution order: `--registry ` or env `FLEET_PLACE_REGISTRY` → a home copy → the source-tree relative path → the registry **embedded in the binary**. Registry shape (version 2): `{comment, version, laptop: {busy, busy_source, note}, owners: {: {concurrent_jobs_cap, concurrent_macos_cap, plan, private_minutes_monthly}}, surfaces: […]}`. + +The shipped surfaces: `fleet-personal` (github-actions, dezren39/fleet, App installation, active), `fleet-org` (github-actions, developing-today/fleet, user-token dispatch, active; also the Blacksmith host), `fleet-forks` (github-actions, developing-today-forks/fleet, **public targets only**, active), `org-run` (standby, retained for manual use; placement prefers fleet-org), `fleet-org-blacksmith` (kind `blacksmith`, Linux-only fallback; budget 3000 free min/mo, paid cap 0 — paid overage disabled unless a dispatch explicitly supplies `--allow-paid-blacksmith`), `codespace-overflow` (kind `codespace`, status `pending-scope`, max 3 live, 180 core-hours/mo budget; uses existing codespaces only, never creates them), `laptop` (kind `laptop`, `handoff-only` — a placement record only; this adapter never runs shell commands on the laptop). Targets accept exact `owner/repo`, `owner/*`, or `*`. `sticky_queue_threshold: 2` and `selection_priority` (10 for the active runners, 20 for org-run) drive the cascade. + +Exit codes: 0 ok · 2 usage / unreadable registry. + +```text +$ fleet queue surfaces | head -30 +{ + "comment": "Fleet placement registry. Targets accept exact owner/repo names, owner/* patterns, or * for all valid owner/repo paths. …", + "version": 2, + "laptop": { "busy": false, "busy_source": "manual-flag", "note": "…" }, + "owners": { + "developing-today": { "concurrent_jobs_cap": 20, "concurrent_macos_cap": 5, "plan": "free-org", "private_minutes_monthly": 2000 }, + … + }, + "surfaces": [ … ] +} +``` diff --git a/pkgs/fleet/book/reference/queue-fallback.md b/pkgs/fleet/book/reference/queue-fallback.md new file mode 100644 index 0000000000..8ead10a25b --- /dev/null +++ b/pkgs/fleet/book/reference/queue-fallback.md @@ -0,0 +1,224 @@ +# fleet queue: the fallback queue + +The fallback queue is the GitHub-issue-comment queue: the queue used when the primary broker/store is down — and, via the permanent fallback switch, whenever a work verb's primary call fails. **All state lives in issue comments; there is no database and nothing to reconcile when the backend returns** — the broker system re-derives queue state from labels and its own tables as it already does after any drift. + +Group usage: + +```text +usage: repo-queue fallback ... +``` + +- **Work items** are open issues carrying the fleet's existing labels `queue/queued` (waiting), `queue/claimed` (held), `queue/blocked` (blocked) — the same labels the broker-backed system maintains; no parallel taxonomy. Blocked items sit outside the scan sweep and cannot be claimed. +- **Repos:** the sweep covers five, in pilot order — `developing-today/code`, `developing-today-forks/opencode`, `developing-today-forks/openchamber`, `dezren39/darwin-nix`, `dezren39/fleet`. Shortcuts: `code`, `opencode`, `openchamber`, `nix`, `fleet`. Full names are `developing-today/code`, `developing-today-forks/opencode`, `developing-today-forks/openchamber`, `dezren39/darwin-nix`, `dezren39/fleet`. +- **Worker identity:** every fleet worker posts to GitHub as the same account, so comment authorship cannot tell workers apart — the marker's worker id is the only identity the lease can be keyed on. Therefore `--worker` is **required, never defaulted** (or env `FLEET_FALLBACK_WORKER`); ids must match `[A-Za-z0-9._-]`, max 64 chars. Plain (unmarked) comments do NOT renew a claim. +- **Exit codes** mirror the primary client (see [core verbs](queue-core.md)): 0 ok, **2** usage, **3** the GitHub transport itself failed (gh missing/erroring), **5** the verb ran but the claim state forbids the action, **1** a `complete` whose disposition the gate rejected or whose record could not be read. +- All fallback verbs print JSON except where noted; every verb's JSON carries `"mode": "fallback"` on scan/status. + +Sources: [fallback.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/fallback.rs), [client transport](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/transport.rs), [disposition.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/disposition.rs). + +## The marker grammar + +The claim is the *first line* of a comment, exactly (the `fleet-claim v1` grammar): + +```text + + + + +``` + +A human-readable line sits under the marker. The marker's embedded `ts` is authoritative. Marker reads paginate comments at 100/page, max 10 pages; a read that ends on a full 10th page **errors** rather than returning a truncated marker set. + +## The lease and the claim-state fold + +**The lease:** a claim stays live while the holder posts heartbeat markers. Default window **30 minutes**, overridable per-verb with `--lease-min` or globally with env `FLEET_QUEUE_FALLBACK_LEASE_MIN`. (30, not 20: worker checkpoints land at most ~15 min apart and the fix timebox is 45 min, so a 20-minute lease would let a live claim look dead between checkpoints.) + +**Claim state fold** (a fold over the issue's marker events in comment order): + +- `free` — no claim events. Claimable. +- `released {worker, outcome, ts}` — the holder released. Claimable. +- `live {worker, last_activity, age_seconds}` — last marker inside the lease. Not claimable by others. +- `stale {…}` — older than the lease; any worker may claim, superseding. Claimable. +- `contested {holder, challenger, ts}` — a claim posted while another's claim is live **contests** the issue: hands-off for everyone while the contest is younger than the lease. A contest ages out once every challenger has been silent a full lease window (a repeat claim refreshes that challenger's contest); a release from a challenger clears their contest at once. The holder may heartbeat throughout. Not claimable. + +Claimable = free | released | stale. + +## The permanent fallback switch (exit 6) + +The GitHub fallback is **not** an outage-only mode anymore. For the work verbs — **claim, heartbeat, checkpoint, complete, health** — *any* primary-store failure (broker unreachable, or an `{ok:false}` envelope from the broker) switches the caller to the GitHub fallback for that work instead of dying: + +- stderr: `repo-queue: primary queue store failed on (exit ): ; switching this work to the GitHub fallback` +- stdout: one JSON object `{"ok": false, "fallback": true, "switch_to": "github-fallback", "verb": , "mode_line": {"verb": …, "mode": "db-degraded", "route": "github-markers"}, "broker_exit": , "error": , "hint": "continue this work with: fleet queue fallback scan|claim|heartbeat|release|unblock"}` +- **exit 6**, so a worker loop can branch on it without parsing prose. +- Escape hatch: env `REPO_QUEUE_NO_FALLBACK_SWITCH=1` restores plain die-on-error. + +The primary claim path also guards in the other direction — the no-double-serve guard: after a successful primary claim, if the issue is `live` or `contested` in the fallback under a different worker, the primary task is blocked back with reason-class `fallback_held` and the claim answers exit 5 (see [core verbs](queue-core.md)). + +## fleet queue fallback scan + +```text +usage: repo-queue fallback scan [--repo ] [--limit <1..100>] [--lease-min ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--repo` | repo or shortcut | all five sweep repos | Restrict the sweep to one repo (shortcut names resolve: `code`, `opencode`, `openchamber`, `nix`, `fleet`). | +| `--limit` | integer | 15 | Max items; range 1..=100 (outside → usage error). | +| `--lease-min` | integer minutes | 30 (or env `FLEET_QUEUE_FALLBACK_LEASE_MIN`) | Lease window used to fold claim states. | +| _(positionals)_ | — | **none accepted** | `scan` takes **no positional arguments** — see discrepancy note. | + +**Behaviour.** Sweeps the fallback repos' labelled issues (`queue/queued`, `queue/claimed`, `queue/blocked`) and folds each issue's claim state. Output JSON: `{"mode":"fallback", "generated_at", "lease_seconds", "items": [{"repo","number","title","url","labels","blocked","claim": }], "summary": {"total", "claimable"}, "notes": […]}`. Items are ranked claimable first (free/released/stale), then live, then contested/blocked; a blocked item never ranks claimable even if its marker fold reads free — the label is the block. Per-issue comment-read failures land in `notes` and the issue is folded with no markers rather than failing the sweep. + +Known discrepancy: the group usage line in `queue_fallback.txt` (and source `GROUP_USAGE`) summarizes `scan `, but `fallback scan` takes **no positionals at all** (they are a usage error) — its repo filter is the `--repo` flag. The same top-level usage additionally **omits `complete`** from the fallback subcommand list while the fallback group usage and the implementation both include it. This chapter documents the implementation behaviour. + +Exit codes: 0 ok · 2 usage (including positionals, out-of-range `--limit`) · 3 GitHub transport failed. + +```text +$ fleet queue fallback scan --repo code --limit 5 +{"mode": "fallback", "generated_at": "2026-11-23T04:30:00Z", "lease_seconds": 1800, "items": [{"repo": "developing-today/code", "number": 13165, "title": "Write the fleet book", "url": "https://github.com/developing-today/code/issues/13165", "labels": ["queue/queued"], "blocked": false, "claim": {"state": "free", "claimable": true}}], "summary": {"total": 1, "claimable": 1}, "notes": []} +``` + +## fleet queue fallback status + +```text +usage: repo-queue fallback status [--lease-min ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | repo or shortcut | required | The issue's repo. | +| `` (positional) | integer | required | The issue number. | +| `--lease-min` | integer minutes | 30 (or env `FLEET_QUEUE_FALLBACK_LEASE_MIN`) | Lease window used to fold the claim state. | + +**Behaviour.** Shows the folded claim state for one fallback issue. Output JSON: `{"mode":"fallback", "repo", "number", "url", "lease_seconds", "blocked": bool, "last_unblock": {"worker","ts"}|null, "claim": }` where state JSON is one of `{"state":"free","claimable":true}`, `{"state":"released","claimable":true,"worker","outcome","released_at"}`, `{"state":"live"|"stale","claimable":bool,"worker","last_activity","age_seconds"}`, `{"state":"contested","claimable":false,"worker"(holder),"challenger","contested_at"}`. + +Exit codes: 0 ok · 2 usage · 3 GitHub transport failed. + +```text +$ fleet queue fallback status code 13165 +{"mode": "fallback", "repo": "developing-today/code", "number": 13165, "url": "https://github.com/developing-today/code/issues/13165", "lease_seconds": 1800, "blocked": false, "last_unblock": null, "claim": {"state": "live", "claimable": false, "worker": "repo-worker-code", "last_activity": "2026-11-23T04:28:00Z", "age_seconds": 120}} +``` + +## fleet queue fallback claim + +```text +usage: repo-queue fallback claim --worker [--lease-min ] [--note ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | repo or shortcut | required | The issue's repo. | +| `` (positional) | integer | required | The issue number. | +| `--worker` | worker id | **required** (or env `FLEET_FALLBACK_WORKER`) | Claiming worker identity — the marker's worker id is the lease key. Must match `[A-Za-z0-9._-]`, max 64 chars. Never defaulted. | +| `--lease-min` | integer minutes | 30 (or env `FLEET_QUEUE_FALLBACK_LEASE_MIN`) | Lease window. | +| `--note` | text | unset | Human-readable note placed under the claim marker. | + +**Behaviour.** Refuses (exit 5) when the issue is blocked (label), closed, or under a live/contested claim by another worker. Otherwise posts the claim marker comment ("Picked up by `` — working this now. … after <lease> minutes of silence any other worker may pick this up."), then **re-reads the markers**: races are detected on read-back (if the fold now shows a contest or another holder, the claim did not take). On success it sets labels `queue/claimed` + `work/assigned`, removing `queue/queued`. + +No-double-serve note: this is the fallback side of the guard described in [core verbs](queue-core.md) — a fallback claim on an issue the primary queue currently holds does not merge the two claims; workers must resolve the contest through the fold (the primary claim path blocks its own task back when it detects a live fallback hold by a different worker). + +Exit codes: 0 claimed · 2 usage / missing or malformed `--worker` · 3 GitHub transport failed · 5 issue blocked, closed, or live/contested under another worker; or the read-back shows the claim did not take. + +```text +$ fleet queue fallback claim code 13165 --worker repo-worker-code +{"mode": "fallback", "repo": "developing-today/code", "number": 13165, "claim": {"state": "live", "claimable": false, "worker": "repo-worker-code", "last_activity": "2026-11-23T04:30:00Z", "age_seconds": 0}} +``` + +## fleet queue fallback heartbeat + +```text +usage: repo-queue fallback heartbeat --worker [--lease-min ] [--note ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | repo or shortcut | required | The issue's repo. | +| `` (positional) | integer | required | The issue number. | +| `--worker` | worker id | **required** (or env `FLEET_FALLBACK_WORKER`) | Holder identity. Never defaulted. | +| `--lease-min` | integer minutes | 30 (or env `FLEET_QUEUE_FALLBACK_LEASE_MIN`) | Lease window the renewed claim is folded under. | +| `--note` | text | unset | Human-readable progress note under the heartbeat marker. | + +**Behaviour.** Posts a heartbeat marker, renewing *your* lease. Only the current holder's markers renew; heartbeating someone else's live claim does not take it over (the fold keeps the holder; your marker at most contests if it were a claim — a heartbeat is not). + +Exit codes: 0 heartbeat posted · 2 usage / missing or malformed `--worker` · 3 GitHub transport failed · 5 the claim state forbids the action. + +```text +$ fleet queue fallback heartbeat code 13165 --worker repo-worker-code --note "chapters 2 of 6 drafted" +{"mode": "fallback", "repo": "developing-today/code", "number": 13165, "claim": {"state": "live", "claimable": false, "worker": "repo-worker-code", "last_activity": "2026-11-23T04:45:00Z", "age_seconds": 0}} +``` + +## fleet queue fallback release + +```text +usage: repo-queue fallback release --worker [--lease-min ] [--outcome done|free] [--summary ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | repo or shortcut | required | The issue's repo. | +| `` (positional) | integer | required | The issue number. | +| `--worker` | worker id | **required** (or env `FLEET_FALLBACK_WORKER`) | Holder identity. Never defaulted. | +| `--lease-min` | integer minutes | 30 (or env `FLEET_QUEUE_FALLBACK_LEASE_MIN`) | Lease window. | +| `--outcome` | `done\|free` | unset | `done` keeps the terminal state; `free` hands the work back unworked. | +| `--summary` | text | unset | Human-readable summary under the release marker. | + +**Behaviour.** Posts a release marker with the outcome. `done` keeps the terminal state (labels: `queue/claimed`/`work/assigned` removed, nothing restored); `free` hands the work back unworked and restores `queue/queued`. Plain `release --outcome done` remains the way to hand back work that carries no disposition (contrast `complete` below). A release from a challenger clears their contest at once. + +Exit codes: 0 released · 2 usage / missing or malformed `--worker` / bad `--outcome` · 3 GitHub transport failed · 5 the claim state forbids the action. + +```text +$ fleet queue fallback release code 13165 --worker repo-worker-code --outcome free --summary "cannot take this now; back to the pool" +{"mode": "fallback", "repo": "developing-today/code", "number": 13165, "claim": {"state": "released", "claimable": true, "worker": "repo-worker-code", "outcome": "free", "released_at": "2026-11-23T04:50:00Z"}} +``` + +## fleet queue fallback complete + +```text +usage: repo-queue fallback complete --worker --summary --result [--pr ] [--lease-min ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | repo or shortcut | required | The issue's repo. | +| `` (positional) | integer | required | The issue number. | +| `--worker` | worker id | **required** (or env `FLEET_FALLBACK_WORKER`) | Holder identity. Never defaulted. | +| `--summary` | text | **required** | Completion summary posted with the release-done marker. | +| `--result` | file path | **required** | A disposition record file — the output of `fleet queue verify-disposition --repo --json` (see [lifecycle verbs](queue-lifecycle.md)). | +| `--pr` | comma-separated PR numbers | unset | The completion's linked PRs, for the gate's coverage check. | +| `--lease-min` | integer minutes | 30 (or env `FLEET_QUEUE_FALLBACK_LEASE_MIN`) | Lease window. | + +**Behaviour — offline gate parity.** Broker parity: `--result` must pass the broker's **offline** disposition gate (`disposition::check` — the same pure gate the broker applies, including the 1800 s freshness rule and the five-verdict rules in [lifecycle verbs](queue-lifecycle.md)) for this issue *before anything is posted*; a rejection posts nothing, the claim stays live, and the verb exits **1**. + +On a pass it posts the release-done marker with the summary and the **full record** in a ` ```fleet-disposition ` fenced block, so the record stays consumable from the marker stream when the broker returns. + +**UNCHECKED follow-ups.** The one broker-only check — a `follow_up`'s `task_id` against the live queue — cannot run from a fallback seat: such a record is completed with that check flagged **UNCHECKED** in the comment and the verb output, never silently treated as checked. + +Exit codes: 0 completed · 1 disposition gate rejection or unreadable record (nothing posted; claim stays live) · 2 usage / missing required flag / malformed `--worker` · 3 GitHub transport failed · 5 the claim state forbids the action. + +```text +$ fleet queue verify-disposition 13165 --repo developing-today/code --json > /tmp/disp.json +$ fleet queue fallback complete code 13165 --worker repo-worker-code --summary "Book chapters merged" --result /tmp/disp.json +{"mode": "fallback", "repo": "developing-today/code", "number": 13165, "completed": true, "verdict": "merged_verified", "follow_up_task_check": "n/a"} +``` + +## fleet queue fallback unblock + +```text +usage: repo-queue fallback unblock --worker --reason +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | repo or shortcut | required | The issue's repo. | +| `` (positional) | integer | required | The issue number. | +| `--worker` | worker id | **required** (or env `FLEET_FALLBACK_WORKER`) | Overriding worker identity — the override is worker-scoped and recorded. Never defaulted. | +| `--reason` | text | **required** | Why the block is overridden; recorded in the unblock marker. Missing → exit 2. | + +**Behaviour.** The fallback form of the broker's manual override: posts an unblock marker recording the override + reason, clears the `queue/blocked` label and restores `queue/queued`, then verifies the label transition landed. **Refusals (exit 5):** an issue that is closed, not blocked, or under a live or contested claim. + +Exit codes: 0 unblocked · 2 usage / missing `--worker` or `--reason` · 3 GitHub transport failed · 5 closed, not blocked, or live/contested claim. + +```text +$ fleet queue fallback unblock code 13165 --worker repo-worker-code --reason "blocking PR merged; override the stale block" +{"mode": "fallback", "repo": "developing-today/code", "number": 13165, "blocked": false, "last_unblock": {"worker": "repo-worker-code", "ts": "2026-11-23T04:55:00Z"}, "claim": {"state": "free", "claimable": true}} +``` diff --git a/pkgs/fleet/book/reference/queue-lifecycle.md b/pkgs/fleet/book/reference/queue-lifecycle.md new file mode 100644 index 0000000000..e87130c1ea --- /dev/null +++ b/pkgs/fleet/book/reference/queue-lifecycle.md @@ -0,0 +1,442 @@ +# fleet queue: lifecycle verbs + +The lifecycle verbs move a claimed task through its life: attribution (`lane`, `bind`), lease care (`heartbeat`, `checkpoint`), waiting (`park`, `wake`, `block`, `unblock`, `dep-recheck`, `quarantine-recheck`), and the terminal/revival verbs (`cancel`, `revive`, `fail`, `complete`, `verify-disposition`). + +Shared rules, stated in [fleet queue: core verbs](queue-core.md) and not repeated in full here: the global exit-code vocabulary (0 ok, 1 gate/not-found, 2 usage, 3 transport/401, 4 broker store failure, 5 no-claim/no-row, 6 fallback switch); the `--worker` default `repo-worker-code`; the `--lane` resolution (flag → env `REPO_QUEUE_LANE` → null, broker checks worker alone); and `--progress` / `--progress-file` mutual exclusion. + +**Holder-checked verbs.** `lane`, `bind`, `heartbeat`, `checkpoint`, `park`, `release`, `block`, `fail`, `complete` are holder-checked broker-side: the row must be claimed by this worker (and lane, when one is supplied) and non-terminal, else the envelope has no row and the client dies **exit 5** with `: no matching claimed row (task not claimed by this worker, or already terminal)`. On success they print the broker's returned task row as JSON and exit 0. Several lifecycle verbs answer `{task, lane_ledger}` (and sometimes `follow_on_task_id`) instead of the bare row when the broker includes a ledger. + +**The person-wait guard (FDR-0013)** applies to `park` and `block` and is described once under `block` below; `park` references it. + +Sources: [commands_lifecycle.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs), [commands_query.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/commands_query.rs), [verify_disposition.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/client/verify_disposition.rs), [disposition.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/disposition.rs), [person_wait.rs](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/person_wait.rs), [turso_queue lifecycle](https://github.com/developing-today/code/blob/main/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs). + +## fleet queue lane + +```text +usage: repo-queue lane [--worker ] [--exclusion-reason ] [--opencode-reason ] [--limit-platform

] [--limit-reason ] [--clear-platform-limit] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to report lane progress on. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--exclusion-reason` | text | unset | Recorded on the lane ledger as `exclusion_reason`. | +| `--opencode-reason` | text | unset | Recorded on the lane ledger as `opencode_reason`. | +| `--limit-platform` | platform family | unset | Record a platform limitation (`platform_limit`). Requires `--limit-reason` (see Behaviour). | +| `--limit-reason` | text | unset | The reason for the platform limitation (`platform_limit_reason`). | +| `--clear-platform-limit` | boolean | off | Clear a recorded platform limitation. | + +**Behaviour.** Reports lane progress on a task. Broker route `/lane`; writes the `repo_task_lane_ledger` row for the task: `assigned_lane` (the caller's lane context), `exclusion_reason`, `opencode_reason`, `platform_limit`, `platform_limit_reason`. A platform limitation exists only with its recorded reason: the broker refuses a `--limit-platform` with no `--limit-reason`. `--clear-platform-limit` clears a recorded limitation. Prints the returned task row as JSON. + +Exit codes: 0 ok · 2 usage / platform limit without a reason · 3 transport · 4 broker store failure · 5 no matching claimed row. + +```text +$ fleet queue lane 19479 --worker repo-worker-code --limit-platform macos --limit-reason "needs the macOS runner pool" +{"id": 19479, "status": "claimed", "lane_ledger": {"assigned_lane": "code-a", "platform_limit": "macos", "platform_limit_reason": "needs the macOS runner pool"}} +``` + +## fleet queue bind + +```text +usage: repo-queue bind [--worker ] --session-id [--launched-by ] [--model-provider

] [--model-id ] [--model-variant ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to bind a session to. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--session-id` | session id | **required** | The session to bind. Missing → exit 2. | +| `--launched-by` | who | `opencode-claimant` | Who launched the bound session; recorded on the lane ledger. | +| `--model-provider` | provider name | unset | Serving model provider for the model stamp. | +| `--model-id` | model id | unset | Serving model id for the model stamp. | +| `--model-variant` | variant name | unset | Serving model variant for the model stamp. Explicit `--model-*` wins; else the stamp is derived from the session's own record. | + +**Behaviour.** Binds a session to a claimed task (`/bind`): records `session_id` + `launched_by` on the lane ledger. The model stamp works exactly as on `claim` (see [core verbs](queue-core.md)). The client also appends `session_bound` (and `model_stamp` when a stamp exists) timeline events, trigger `bind`. Prints the returned task row as JSON. + +Exit codes: 0 ok · 2 usage / missing `--session-id` · 3 transport · 4 broker store failure · 5 no matching claimed row. + +```text +$ fleet queue bind 19479 --worker repo-worker-code --session-id ses_01J9EXAMPLE0000000000000 +{"id": 19479, "status": "claimed", "lane_ledger": {"assigned_lane": "code-a", "session_id": "ses_01J9EXAMPLE0000000000000", "launched_by": "opencode-claimant"}} +``` + +## fleet queue heartbeat + +```text +usage: repo-queue heartbeat [--worker ] [--lane ] [--extend-seconds ] [--progress

] [--progress-file ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task whose lease to refresh. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--lane` | lane id | env `REPO_QUEUE_LANE`, else null | Holder lane check. | +| `--extend-seconds` | integer seconds | 900 (15 min) | New lease length from now. Range 1..=86400, exit 2 outside (a 0/negative extend "lapses the holder's own claim"). | +| `--progress` | text/JSON | unset | Progress value merged into the row. Mutually exclusive with `--progress-file`. | +| `--progress-file` | file path | unset | File whose text is read as the progress value. Mutually exclusive with `--progress`. | + +**Behaviour.** Refreshes the claim lease: `lease_until = now + extend_seconds` on both the task row and the `leases` row (`heartbeat_at` updated). Note the asymmetry: claim's default lease is 2700 s but a heartbeat only adds 900 s unless told otherwise. `--progress`/`--progress-file` optionally merge a progress value into the row. Heartbeat goes through the fallback-switch path: a primary-store failure switches the work to the GitHub fallback, exit 6 (see [the fallback queue](queue-fallback.md)). Prints the row + `mode_line`. + +Exit codes: 0 ok · 2 usage / out-of-range `--extend-seconds` / both progress flags · 3 transport · 4 broker store failure · 5 no matching claimed row · 6 fallback switch. + +```text +$ fleet queue heartbeat 19479 --worker repo-worker-code --lane code-a +{"id": 19479, "status": "claimed", "lease_until": "2026-11-23T04:35:00Z", "mode_line": {"verb": "heartbeat", "mode": "normal", "route": "cloud"}} +``` + +## fleet queue checkpoint + +```text +usage: repo-queue checkpoint [--worker ] [--lane ] [--stage ] [--progress

] [--progress-file ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to checkpoint. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--lane` | lane id | env `REPO_QUEUE_LANE`, else null | Holder lane check. | +| `--stage` | stage name | **required** | The checkpoint stage. Missing → exit 2. | +| `--progress` | text/JSON | unset | Progress value merged into the row. Mutually exclusive with `--progress-file`. | +| `--progress-file` | file path | unset | File whose text is read as the progress value. Mutually exclusive with `--progress`. | + +**Behaviour.** Records progress + stage without touching the lease. The broker (`/checkpoint`) merges the progress (default `{}`) into the task row with `progress.last_checkpoint = {stage, at}` stamped in; upserts the per-worker KV row `checkpoints(worker_id, 'task:') = {stage, progress, at}`; writes a `checkpoint` event. Fallback-switch path, like heartbeat: a primary-store failure switches, exit 6. Prints row + `mode_line`. + +Known discrepancy: help brackets `--stage` as optional (`[--stage ]`); source makes it **required** — missing → exit 2 `checkpoint: --stage is required`. This chapter documents the source behaviour. + +Exit codes: 0 ok · 2 usage / missing `--stage` / both progress flags · 3 transport · 4 broker store failure · 5 no matching claimed row · 6 fallback switch. + +```text +$ fleet queue checkpoint 19479 --worker repo-worker-code --lane code-a --stage drafting --progress '{"chapters": 2}' +{"id": 19479, "status": "claimed", "progress": {"last_checkpoint": {"stage": "drafting", "at": "2026-11-23T04:20:00Z"}}, "mode_line": {"verb": "checkpoint", "mode": "normal", "route": "cloud"}} +``` + +## fleet queue park + +```text +usage: repo-queue park [--worker ] [--lane ] --reason [--delay-seconds ] [--not-before ] [--progress

] [--progress-file ] [--ready-condition ] [--execution ] [--required-budget-minutes ] [--hands --action ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to park. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--lane` | lane id | env `REPO_QUEUE_LANE`, else null | Holder lane check. | +| `--reason` | text | **required** | Why the task is parked. Missing → exit 2. | +| `--delay-seconds` | integer seconds | broker default 1200 when neither delay nor not-before is given | Relative wait. Range 1..=604800 (7 days); 0 is rejected by design — "a park that waits zero seconds is a requeue, and a requeue already has its own verb (`release`)". Mutually exclusive with `--not-before`. | +| `--not-before` | RFC 3339 timestamp | unset | Absolute wake time; must be non-empty and ≤366 days in the future. Mutually exclusive with `--delay-seconds`. | +| `--progress` | text/JSON | unset | Progress merged into the row; may carry `ready_condition` (see Behaviour). Mutually exclusive with `--progress-file`. | +| `--progress-file` | file path | unset | File whose text is read as the progress value. | +| `--ready-condition` | JSON object | derived (see Behaviour) | What "done waiting" means. Non-JSON → exit 2; non-object JSON → exit 2. | +| `--execution` | execution id | unset | Folded into an execution record `{lane, lane_id?, session_id, fallback_reason?}`. | +| `--required-budget-minutes` | integer minutes | broker-derived for capacity waits (see Behaviour) | The minimum remaining shift budget a future claimer must declare. Non-positive values record no requirement. | +| `--hands` | `physical\|interactive-login\|payment\|signature` | unset | Hands kind for a valid person-wait (FDR-0013); must come with `--action`. | +| `--action` | text | unset | One sentence a person can do in five minutes; required with `--hands` on a person-wait. | + +**Behaviour.** Parks a claimed task: status becomes `parked`, out of the claimable pool until its `not_before` is due, its ready-condition is released by the revalidation sweeper, or `wake` short-circuits the wait. + +- **Ready-condition kinds** the revalidation sweeper can verify from DB state: `task_terminal {task_id}`, `task_status {task_id, status}`, `event_seen {task_id?, event_kind}`, `time {until}`. External kinds (`ci`, `pr_merged`, `issue_closed`, `person_answer`, `review`, …) are recorded faithfully but a DB sweeper cannot verify them. With no explicit condition the broker derives one from `progress.ready_condition`, else `{"kind":"time","until":}`. +- **wait_kind** is derived from the condition kind at park time: `time`→`timer`; `triage`→`triage`; `ci|ci_green|pr_merged|issue_closed|upstream_pr`→`ci`; `review|codex_review|pr_review|person_answer`→`review`; `capacity|quota_reset`→`capacity`; anything else→`external`. `park_kind` records `relative` vs `absolute`. +- **Broker wait floors:** whatever delay a lane asks for, a `triage` wait is held at least **6 h (21600 s)** and a `ci` or `capacity` wait at least **1 h (3600 s)** — a requested wake earlier than the floor is bumped to the floor; timer/review/external waits keep the caller's delay. (Lanes re-discovering an unchanged wait every 20–25 min was the park churn this kills.) A park whose recorded stage is `awaiting_triage` is a triage wait whatever condition the caller attached. +- **Handoff parks / the sink:** a non-triage park that is a *handoff* (the condition defaulted, per the broker's rule) is routed `to_sink` — parked into the handed-off sink where `claim --handoff` / by-id claims collect it, rather than sitting as an ordinary timed park. +- **`--required-budget-minutes`:** for a `capacity` wait the broker defaults it from the packet's `timebox_minutes` when the flag is absent. +- **Person-wait guard (FDR-0013):** a park whose ready-condition kind is `person_answer`, or whose reason text names the owner as the release, is refused client-side (exit 2, before broker contact) unless it is a valid hands item; a valid hands item is stamped into `progress.hands = {kind, action}`. See the full guard under `block` below. +- Park stamps `last_checked_at = now`, resets `check_outcome`, and the **park revalidation sweeper** later records `check_outcome` ∈ `confirmed` (condition unmet; park untouched), `released` (condition met → status `queued`, `not_before` null, `park_released` event), or `stale` (cannot verify). +- Output: row (or `{task, lane_ledger[, follow_on_task_id]}`); a park closes the session binding window on the timeline. + +Exit codes: 0 parked · 2 usage / missing `--reason` / both delay flags / bad ready-condition / person-wait refusal · 3 transport · 4 broker store failure · 5 no matching claimed row. + +```text +$ fleet queue park 19479 --worker repo-worker-code --lane code-a --reason "waiting on CI for the linked PR" --ready-condition '{"kind":"ci","repo":"developing-today/code"}' --delay-seconds 600 +{"id": 19479, "status": "parked", "wait_kind": "ci", "not_before": "2026-11-23T05:20:00Z"} +``` + +## fleet queue wake + +```text +usage: repo-queue wake [--worker ] [--reason ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The parked task to wake. | +| `--worker` | worker id | `repo-worker-code` | Caller identity. | +| `--reason` | text | empty string | Why the wait is over; recorded with the wake. | + +**Behaviour.** Releases a broker-held parked wait *now* that its condition is satisfied: the broker flips the row back to `queued`. Canonical caller: the triage step waking an item it just triaged. Prints the row. + +Exit codes: 0 woken · 2 usage · 3 transport · 4 broker store failure · 5 no parked row the broker can wake. + +```text +$ fleet queue wake 19479 --reason "triaged; ready to work" +{"id": 19479, "status": "queued", "not_before": null} +``` + +## fleet queue block + +```text +usage: repo-queue block [--worker ] [--lane ] --reason-class --blocker [--progress

] [--progress-file ] [--ledger-id ] [--question ] [--context ] [--options-json ] [--links-json ] [--blocked-by-pr ] [--blocked-by-issue ] [--blocked-by-task ] [--blocked-by-ci ] [--dep-recheck-seconds ] [--dep-max-ttl-seconds ] [--hands --action ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to block. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--lane` | lane id | env `REPO_QUEUE_LANE`, else null | Holder lane check. | +| `--reason-class` | class name | **required** | Free-form block class (contrast `fail`, whose `--reason-class` is a closed enum). Missing → exit 2. | +| `--blocker` | text | **required** | What blocks the task. Missing → exit 2. | +| `--progress` | text/JSON | unset | Progress merged into the row. Mutually exclusive with `--progress-file`. | +| `--progress-file` | file path | unset | File whose text is read as the progress value. | +| `--ledger-id` | id | unset | Needs-drew payload: the PM ledger id (see Behaviour). | +| `--question` | text | unset | Needs-drew payload: the question for the owner. A hands item's `--action` serves as the question when none is given. | +| `--context` | text | unset | Needs-drew payload: optional context. | +| `--options-json` | JSON array | unset | Needs-drew payload: array of `{"id","label"}` objects; bad shape → exit 2. | +| `--links-json` | JSON array | unset | Needs-drew payload: array of strings; bad shape → exit 2. | +| `--blocked-by-pr` | comma-separated `owner/repo#N` refs | unset | Typed dependency: PRs that must land. Bad refs die client-side, exit 2. | +| `--blocked-by-issue` | comma-separated `owner/repo#N` refs | unset | Typed dependency: issues that must close/resolve. Bad refs die client-side, exit 2. | +| `--blocked-by-task` | comma-separated bare task ids | unset | Typed dependency: queue tasks that must reach a terminal state. | +| `--blocked-by-ci` | comma-separated `owner/repo#N` refs | unset | Typed dependency: CI runs; here `N` is an Actions **run id**. | +| `--dep-recheck-seconds` | integer seconds | 900 | How often the broker re-checks the deps. Clamped broker-side to 300..=3600. | +| `--dep-max-ttl-seconds` | integer seconds | 259200 (3 days) | Max lifetime of a dep block before TTL expiry releases it. Broker floor 60 s, ceiling 7 days (604800 s). | +| `--hands` | `physical\|interactive-login\|payment\|signature` | unset | Hands kind for a valid person-wait (FDR-0013); must come with `--action`. | +| `--action` | text | unset | One sentence a person can do in five minutes: a single line of ≤200 chars that must not itself ask for a decision. | + +**Behaviour.** Sets status `blocked`; the row keeps its claim identity in progress/ledger terms but is out of the claimable pool until unblocked, dep-cleared, or TTL-expired. Output: the row, exit 0. (The claim path also uses `/block` internally with reason-class `fallback_held` for the double-serve guard — see [core verbs](queue-core.md).) After a `/block`, the broker fire-and-forget raises the needs-drew alert for an escalated block, mirroring the client's own raise. + +**Typed dependency blocks.** The parsed deps array sent to the broker is `[{kind:"pr"|"issue", repo, number} | {kind:"ci", repo, run_id} | {kind:"task", task_id}]` — never a prose block the broker cannot watch. The deps are stored on the task row in the **`blocked_deps`** column (TEXT, JSON) — the state the task calls `dep_blocked` when `blocked_deps` is non-empty — alongside `dep_recheck_seconds`, `dep_next_recheck_at`, and `dep_blocked_until`. The broker watches these deps and releases the task itself when they clear, or when the max TTL expires. Production cadence: the broker's sweep fires the dep recheck every minute; the `dep-recheck` verb is the manual trigger. + +**Person-wait guard (FDR-0013).** A block whose reason class is one of `escalated-to-user`, `drew_decision`, `person-answer`, or whose blocker text contains an owner-wait phrase ("awaiting drew", "needs the owner", "owner decision", "waiting for the owner", … — an 18-phrase list), waits on a person and is **refused** (exit 2, before broker contact) unless it is a hands item: `--hands physical|interactive-login|payment|signature` **and** `--action ""`. The refusal text tells the worker a choice is theirs to make. Passing `--hands`/`--action` on a block that does *not* wait on a person is also an error. A valid hands item is stamped `progress.hands`. The same guard applies to `park`. + +**Needs-drew payload.** Only for `--reason-class escalated-to-user` **with** `--ledger-id` and `--question`. Then the client stamps `progress.needs_drew.ledger_id`, sends a `needs_drew {ledger_id, question, context?, options, links}` object in the `/block` body, and *after the block lands* posts the alert to the PM aggregator's alerts-intake (token resolved by name through fleet-secrets; value never printed). A failed alert post only warns on stderr — the block already succeeded and the verb still exits 0. Without ledger-id + question, an escalated block behaves exactly as before. + +Exit codes: 0 blocked · 2 usage / missing `--reason-class` or `--blocker` / bad dep ref / bad options/links shape / person-wait refusal / hands flags on a non-person block · 3 transport · 4 broker store failure · 5 no matching claimed row. + +```text +$ fleet queue block 19479 --worker repo-worker-code --lane code-a --reason-class dependency --blocker "waiting on PR developing-today/code#13100" --blocked-by-pr developing-today/code#13100 +{"id": 19479, "status": "blocked", "blocked_deps": [{"kind": "pr", "repo": "developing-today/code", "number": 13100}], "dep_recheck_seconds": 900, "dep_blocked_until": "2026-11-26T04:20:00Z"} +``` + +## fleet queue unblock + +```text +usage: repo-queue unblock [--worker ] [--reason ] [--drop-dep ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The blocked task to release. | +| `--worker` | worker id | `repo-worker-code` | Caller identity; the broker audits who overrode. | +| `--reason` | text | empty string | Why the block is overridden; audited. | +| `--drop-dep` | comma-separated `kind:ref` list | unset | Surgical dep drop: `issue:owner/repo#N`, `pr:owner/repo#N`, `ci:owner/repo#RUN`, `task:ID`. Bad refs die client-side, exit 2; the broker re-validates every spec. | + +**Behaviour.** The manual override: releases a blocked task now, dep-blocked or classic. The broker audits who overrode and what dep record was discarded. + +- **Without `--drop-dep`:** clears the task's blocked state entirely (deps discarded). +- **With `--drop-dep `:** surgical. Only the named entries are dropped from the task's `blocked_deps` record. **The task stays blocked on the remaining deps; dropping the last one releases it.** + +Output: the row, exit 0. + +Exit codes: 0 unblocked (or last dep dropped) · 2 usage / bad `--drop-dep` ref · 3 transport · 4 broker store failure · 5 no blocked row matches. + +```text +$ fleet queue unblock 19479 --reason "PR merged manually; dep record is stale" --drop-dep pr:developing-today/code#13100 +{"id": 19479, "status": "queued", "blocked_deps": []} +``` + +## fleet queue dep-recheck + +```text +usage: repo-queue dep-recheck [--task ] [--limit ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--task` | task id | unset | Force one task's recheck instead of a full pass. | +| `--limit` | integer | no documented default | Pass size limit; forwarded verbatim to the broker (no default is documented in help or client source). | + +**Behaviour.** Runs the broker's dependency recheck pass now, or forces one task's recheck with `--task`. The pass re-reads each dep-blocked task's deps (issue/PR state, CI run state, task terminality) and releases the ones that cleared; TTL-expired dep blocks are released by the same machinery. Output: the pass result row as JSON. + +Exit codes: 0 ok · 2 usage · 3 transport · 4 broker store failure. + +```text +$ fleet queue dep-recheck --task 19479 +{"task": 19479, "checked": 1, "released": 1, "still_blocked": 0} +``` + +## fleet queue quarantine-recheck + +```text +usage: repo-queue quarantine-recheck [--task ] [--limit ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--task` | task id | unset | Force one task's recheck instead of a full pass. | +| `--limit` | integer | no documented default | Pass size limit; forwarded verbatim to the broker. | + +**Behaviour.** Runs the broker's quarantine recheck pass: re-validates **blocked, dep-free** rows whose recorded error is a claim-path quarantine (e.g. a stored packet that fails claim-time validation) and requeues the ones whose error no longer reproduces. Production cadence is the broker sweep's; this is the manual trigger. Output: the pass result row as JSON. + +Exit codes: 0 ok · 2 usage · 3 transport · 4 broker store failure. + +```text +$ fleet queue quarantine-recheck +{"checked": 3, "requeued": 1, "still_quarantined": 2} +``` + +## fleet queue cancel + +```text +usage: repo-queue cancel [--worker ] [--reason ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The task to cancel. | +| `--worker` | worker id | **`fleet-monitor`** | Caller identity. Note: cancel is a monitor close-out verb — its worker default is NOT the global `repo-worker-code`. | +| `--reason` | text | **required** | Why the task will never be worked. Missing → exit 2. Recorded as `result.cancel_reason`. | + +**Behaviour.** For a task that will never be worked (issue closed, self-assigned elsewhere, superseded). Sets status `cancelled`, clears worker/lease, deletes the lease row, records `result.reason_class = "cancelled"` + `result.cancel_reason`, writes a `cancelled` event. The original function only accepted `queued` or `parked` rows. Output: the row; cancel closes the timeline binding window. + +Known discrepancy: help brackets `--reason` as optional (`[--reason ]`); source makes it **required** (exit 2 without it). Source-only fact: cancel's `--worker` default is `fleet-monitor`, not `repo-worker-code`. This chapter documents the source behaviour. + +Exit codes: 0 cancelled · 2 usage / missing `--reason` · 3 transport · 4 broker store failure · 5 no matching row. + +```text +$ fleet queue cancel 19481 --reason "issue closed as duplicate; superseded by task 19482" +{"id": 19481, "status": "cancelled", "result": {"reason_class": "cancelled", "cancel_reason": "issue closed as duplicate; superseded by task 19482"}} +``` + +## fleet queue revive + +```text +usage: repo-queue revive [--worker ] [--reason ] [--not-before ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The terminal or dead-at-cap task to revive. | +| `--worker` | worker id | `repo-worker-code` | Caller identity. | +| `--reason` | text | empty string | Why the task is revived; recorded with the revive. | +| `--not-before` | RFC 3339 timestamp | unset | Fresh `not_before` for the revived row; validated as: non-empty, ≤366 days in the future, else exit 2. | + +**Behaviour.** Revives a terminal task **in place**: a failed task, or a queued task dead at cap (attempts exhausted), gets `attempts = 0` and a fresh `not_before` through the broker's `/revive` — the supported replacement for direct-SQL resets. Output: the row. + +Exit codes: 0 revived · 2 usage / bad `--not-before` · 3 transport · 4 broker store failure · 5 no matching row. + +```text +$ fleet queue revive 19483 --reason "transient infra failure fixed; retry the work" +{"id": 19483, "status": "queued", "attempts": 0} +``` + +## fleet queue fail + +```text +usage: repo-queue fail [--worker ] [--lane ] [--error ] [--reason-class ] [--execution ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to fail. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--lane` | lane id | env `REPO_QUEUE_LANE`, else null | Holder lane check. | +| `--error` | text | **required** | The failure error text. Missing → exit 2. Note: `--error help` records the literal text "help" (value-flag exception to the help rule). | +| `--reason-class` | `transient\|deterministic\|blocked` | `transient` | Closed enum — anything else dies exit 2 `argument --reason-class: invalid choice: '…'`. (Contrast `block`, whose `--reason-class` is free-form.) | +| `--execution` | execution id | unset | Folded into an execution record `{lane, lane_id?, session_id, fallback_reason?}`. | + +**Behaviour.** Terminal `failed`. Broker route `/fail`. Output: row or `{task, lane_ledger}`; fail closes the timeline binding window. + +Known discrepancy: help brackets `--error` as optional; source makes it **required** (exit 2 without it), and `--reason-class` is a closed enum (default `transient`) that help never mentions. This chapter documents the source behaviour. + +Exit codes: 0 failed · 2 usage / missing `--error` / invalid `--reason-class` · 3 transport · 4 broker store failure · 5 no matching claimed row. + +```text +$ fleet queue fail 19479 --worker repo-worker-code --lane code-a --error "packet payload fails validation on retry" --reason-class deterministic +{"id": 19479, "status": "failed", "last_error": "packet payload fails validation on retry", "result": {"reason_class": "deterministic"}} +``` + +## fleet queue complete + +```text +usage: repo-queue complete [--worker ] [--lane ] [--result ] [--result-file ] [--telemetry ] [--execution ] [--queue ] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | task id | required | The claimed task to complete. | +| `--worker` | worker id | `repo-worker-code` | Holder identity. | +| `--lane` | lane id | env `REPO_QUEUE_LANE`, else null | Holder lane check. | +| `--result` | JSON object | `{}` when neither result flag is given | The completion result object. Must parse as a JSON **object** (non-JSON or non-object → exit 2). | +| `--result-file` | file path | unset | File containing the result object. When both are given, `--result-file` is read after and **wins** over `--result`. | +| `--telemetry` | JSON object | unset | Telemetry whose keys must be a subset of the four fields `pool, model, effort, cost_usd` — unknown fields die exit 2 listing the allowed set. Values are merged into the result only for fields the result doesn't already carry. | +| `--execution` | execution id | unset | Folded into `result.execution = {lane, session_id, fallback: bool, fallback_reason?, assigned?}` when the result doesn't already carry an `execution` key, and also sent as the body's `execution`. | +| `--queue` | queue name | parsed, **never used** | Dead flag — see discrepancy note. | + +**Behaviour.** Terminal `done`, via POST `/complete` on the fallback-switch path (a primary-store failure switches, exit 6). Output: row or `{task, lane_ledger[, follow_on_task_id]}` — a triage completion can spawn a follow-on task whose id rides the envelope. Completion closes the timeline binding window. + +Client-side completion dressing (all fail-soft, explicit caller values win): + +- `result.dominant_model`: the bound session's dominant serving model over the task's claim window (route_attempt call count), when derivable. +- Telemetry defaulting: `pool`/`model`/`effort` are filled from the claim stamp, else the completing session's serving leaf / declared route pool; `cost_usd` stays null (no cost readout is sourceable). `effort` is recorded only from resolved session messages, never inferred from route names. + +**The evidence gate.** Shape validation alone used to let a fix-class row complete `done` on any non-empty evidence string while its issue was open and a draft PR still carried the work. Now, a completion that requires a disposition must carry `result.disposition` — the verified readback record produced by `verify-disposition` (next section): + +```json +{"checked_at": "…", "source": "…", "issue": {"number": 0, "state": "…", "state_reason": "…", "closed_at": "…", "closed_by": "…"}, "pulls": [{"number": 0, "state": "…", "is_draft": false, "merged_at": "…"}], "verdict": "…", "follow_up": "…"} +``` + +The gate is pure (no network): it parses the record, checks freshness (≤ **1800 s** old by default; >300 s in the future is unreadable clock skew), checks it describes the task's issue, checks the verdict against the readback, checks every PR the completion result links (`pr`/`pr_url`/`merged_pr` fields) appears in the readback, and checks any follow-up. **Every rejection leaves the task claimed** and names the defect ("…; the task remains claimed"). The five verdicts and their per-verdict rules are specified under `verify-disposition` below. + +Known discrepancy: `--queue` is present in help and in the client's flag list, but the source **never reads it** — it reaches no request body field. A dead flag. This chapter documents the source behaviour. + +Exit codes: 0 completed · 1 disposition gate rejection (task remains claimed) · 2 usage / non-object result / unknown telemetry field · 3 transport · 4 broker store failure · 5 no matching claimed row · 6 fallback switch. + +```text +$ fleet queue verify-disposition 13165 --repo developing-today/code --json > /tmp/disp.json +$ fleet queue complete 19479 --worker repo-worker-code --lane code-a --result-file /tmp/disp-result.json +{"id": 19479, "status": "done", "completed_at": "2026-11-23T04:25:00Z"} +``` + +## fleet queue verify-disposition + +```text +usage: repo-queue verify-disposition --repo [--pr ] [--follow-up-task | --follow-up-issue | --follow-up-pr ] [--reason ] [--staleness-seconds ] [--json] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | issue number | required | The issue to read back from GitHub. | +| `--repo` | `owner/name` | **required** | The issue's repo. Missing → exit 2. | +| `--pr` | comma-separated PR numbers | unset | Explicitly linked PRs to include in the readback. | +| `--follow-up-task` | task id | unset | Follow-up target: a queue task (checked by the *broker* at completion — only the queue knows if it is live). Mutually exclusive with the other follow-up flags. | +| `--follow-up-issue` | issue number or URL | unset | Follow-up target: a same-repo issue; its own readback (state + explicit links) is embedded. | +| `--follow-up-pr` | PR number | unset | Follow-up target: a successor PR. | +| `--reason` | text | **required when any follow-up target is given** | Why the follow-up owns the remainder. Any follow-up target without `--reason` → exit 2. | +| `--staleness-seconds` | integer seconds | 1800 (30 min) | Freshness window for the record; must be positive (exit 2 otherwise). | +| `--json` | boolean | off | Print the raw record object. Without it, a human summary. | + +**Behaviour.** Reads the issue and its linked PRs **back from GitHub, live** (never from a remembered claim) and prints the disposition a terminal completion must carry. Readback assembly: `gh api repos//issues/` (the REST form, because it carries `closed_by`); `gh pr list --state all --limit 300 --json number,state,isDraft,mergedAt,body`; a search union (`" in:body"`, limit 100) because the 300 newest PRs are not the whole history; then an individual `gh pr view` for any explicitly linked/successor PR the union lacks. A PR counts as *linked* when it is named by queue provenance / `--pr`, or its body carries an explicit marker — `Refs #n`, `Fixes #n`, `Related program: #n`. A bare prose `#n` is not a link (except that the `Related program:` prose marker *is* honored — it is the only link the draft PR in the motivating case had to its issue). + +Either way (`--json` or human summary) the verb then runs the offline gate on its own record: **exit 0 when the record would pass, exit 1 when the broker's gate would reject it**, and exit 1 when the issue or PR list cannot be read from GitHub at all. Usage errors exit 2. + +**The five verdicts** (exactly five; derivation and gate rules): + +| Verdict | Derived when | Gate requires | +|---|---|---| +| `merged_verified` | some pull in the readback is merged | ≥1 merged pull in the readback | +| `closed_verified` | issue closed and no unfinished pulls | issue state actually `closed` (a close timestamp on an open issue is a superseded close, not evidence) | +| `open_draft_with_followup` | unfinished pulls exist, nothing merged, issue not cleanly closed | a recorded `follow_up`; while the issue is OPEN, unfinished pulls are allowed *only* under this or the next verdict, with the follow-up on record | +| `open_draft_superseded` | (operator-asserted; same derivation family) | a recorded `follow_up` | +| `invalid_no_work` | none of the above (no merged pull, issue open, no unfinished pull) | rejected if any linked pull still carries work | + +A pull is *unfinished* when it is not merged (`merged_at` null) and not closed. + +**Follow-up checks:** reason required; target must be one of `task_id`, `issue_url`, `successor_pr`. A follow-up *issue* must not be the issue being completed, must be **open**, must link the completed issue with an explicit marker, and must link every unfinished PR. A *successor PR* must be in the readback and must be **merged**. A *task* target is checked broker-side: the task must exist, not be the completing task, be in a **live** (non-terminal) status, and name the same issue. + +**Intentional-close exception:** a closed issue may leave related work open only when the close was a deliberate act by a person (the readback's `closed_by` is checked against automation) *and* a verified follow-up owns the remainder. + +Exit codes: 0 record would pass the gate · 1 gate would reject it, or GitHub readback unreadable · 2 usage (including missing `--repo`, follow-up without `--reason`, non-positive `--staleness-seconds`). + +```text +$ fleet queue verify-disposition 13165 --repo developing-today/code --json +{"checked_at": "2026-11-23T04:24:00Z", "source": "github-readback", "issue": {"number": 13165, "state": "open", "state_reason": null, "closed_at": null, "closed_by": null}, "pulls": [], "verdict": "invalid_no_work", "follow_up": null} +(exit 1 — no merged pull and no follow-up on record; a completion carrying this record would be rejected) +``` diff --git a/pkgs/fleet/book/reference/search.md b/pkgs/fleet/book/reference/search.md new file mode 100644 index 0000000000..266e57eb4a --- /dev/null +++ b/pkgs/fleet/book/reference/search.md @@ -0,0 +1,113 @@ +# fleet search + +`fleet search` is the atlas-search client surface over the live Atlas service contract: **hybrid FTS+vector search over the Atlas corpus**, with classification filters. Search "joins unchanged" after the service cutover; the service role itself is `fleet serve search` (see [fleet serve](serve.md)). Two verbs: `search` (the default) and `get-chunk`. `init` and `fetch-model` are usage errors naming the standalone artifact — they stay on the standalone atlas-search artifact. + +See also [Search: the Atlas corpus](../concepts/search.md). + +Invocation shapes: + +``` +fleet search [options] +fleet search search [options] (atlas-search's own shape — the leading `search` token is stripped) +fleet search get-chunk [options] +``` + +## Routing (both verbs) + +- **Via-service route:** an in-process client speaking the Atlas service's **loopback HTTP job protocol** to the service at `--service-url` (default `http://127.0.0.1:18760`): submit a search job, wait for it (unless `--no-wait`, which prints the job handle), render the result so output matches atlas-search in shape. The backend behind the service is a read-only Turso corpus store with one shared Snowflake embedder. +- **Standalone route:** there is no second embedder/backend in the fleet workspace — the client **delegates to the kept standalone `atlas-search` binary on PATH**, passing the caller's arguments in atlas-search's own shape (with `--via-service`/`--standalone` stripped, and `ATLAS_SEARCH_VIA` removed from the child's environment so an ambient value can't silently re-route it), inheriting its stdout byte-for-byte. A missing artifact is exit 3 with a message naming it as "the search domain's kept standalone". +- **Precedence:** explicit `--via-service` / `--standalone` first; then env `ATLAS_SEARCH_VIA=service|standalone`; then fleet.toml `[search] via`; then the seat default: + - **Sandbox seat → via-service**, with a **loud** standalone fallback (stderr: "fleet search: warning: --via-service: {detail}; falling back to standalone"). The via-service client reaches the laptop's loopback service through the loopback forward on the shared laptop-ssh control connection. + - **Laptop seat → standalone.** The seat signal is the *service's own config file* `~/.local/state/atlas-search/service.json`: only the serving host has one. +- **Provisioning / sensitivity ceilings:** the via-service client presents a per-seat bearer token — env `ATLAS_SEARCH_TOKEN`, else the JSON file at **`~/.config/atlas-search/client.json`** (a JSON object with one token string field, file mode 0600). Identities are named in the service config; the **server** clamps `--max-sensitivity` to the identity's ceiling: identity `drew-cli` → `secret-bearing`, identity `sandbox-scripts` → `personal`. The fleet verb adds no ceiling logic of its own. A seat with no client.json cannot use the service route and falls back to standalone. + +## fleet search search + +``` +fleet search [options] +fleet search search [options] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | text | required | The search query (a single positional). | +| `--k` | `N` | `10` | Final result count. | +| `--pool` | `N` | `100` | Per-branch candidates, validated `1..=400`. | +| `--mode` | `MODE` | `hybrid` | `hybrid \| fts \| vector`. | +| `--kind` | `CSV` | — | Classification kind filter. | +| `--topic` | `CSV` | — | Topic filter. | +| `--project` | `CSV` | — | Project filter. | +| `--client` | `CSV` | — | Client filter. | +| `--since` | `YYYY-MM-DD` | — | Sessions created on/after (inclusive). | +| `--until` | `YYYY-MM-DD` | — | Sessions created on/before (inclusive). | +| `--max-sensitivity` | `LV` | `personal` | `shareable \| personal \| local-only \| secret-bearing`. A *request*; the server clamps it to the client identity's ceiling. | +| `--group-by-session` | — | off | Roll chunk hits up to sessions. | +| `--expand` | `N` | `0` | Include N neighbouring chunks around each hit. | +| `--with-message` | — | off | Include the parent message text. | +| `--no-cache` | — | off | Bypass service cache *reads*; the fresh result still lands in the cache. | +| `--no-wait` | — | off | Do not block: print the service job handle and return. (The one-shot default waits for the job.) | +| `--hydrate` | `N` | `0` | Hydrate the top N results to full content. | +| `--raw-rows[=branches]` | optional `=branches` | — | Ungrouped rows: bare = flat fused rows; `=branches` = pre-fusion branch rows. | +| `--text` | — | off | Human-readable output instead of JSON (default output is JSON). | +| `--model` | `NAME` | `Snowflake/snowflake-arctic-embed-m-v2.0` | Embedding model. | +| `--embedder` | `NAME` | `auto` | `auto \| fastembed \| st`. | +| `--trunc` | `N` | `0` | Truncate vectors to N dims (0 = full). | +| `--vector-backend` | `B` | `scan` | `scan \| index-fill \| index-fixed`. | +| `--via-service` | — | seat default | Prefer the Atlas service (job protocol). Mutually exclusive with `--standalone` (usage error). | +| `--standalone` | — | seat default | Run standalone (delegate to the atlas-search artifact). Mutually exclusive with `--via-service`. | +| `--service-url` | `URL` | `http://127.0.0.1:18760` | Service base URL; env `ATLAS_SEARCH_URL`, then fleet.toml `[search] url`, override it. | + +Standalone-only engine knobs (`--backend`, `--db`) are deliberately not part of this surface. + +Known discrepancy: the help text spells the default model "Snowflake arctic-embed-m-v2.0", dropping the slash; the source constant is `Snowflake/snowflake-arctic-embed-m-v2.0`, and the help spelling is not a valid model id as written. This chapter documents the source value. + +### Behaviour + +The search is hybrid FTS+vector over the Atlas corpus with the classification filters above, mirroring `atlas-search search`'s flags one-for-one where they translate to the wire request. Default output is JSON; `--text` renders human-readable output. With `--no-wait` on the service route, the command prints the service job handle and returns instead of blocking for the result. + +### Exit codes + +- `0` — ok. +- `1` — service-job/backend failure surfaced without a fallback. +- `2` — usage/validation (including `--via-service` with `--standalone`, or `--pool` outside `1..=400`). +- `3` — routing unavailable (no service and no standalone artifact). + +### Example + +```console +$ fleet search 'queue broker lease' --k 5 --text +``` + +Runs a hybrid search for "queue broker lease" and prints the top 5 hits as text. + +## fleet search get-chunk + +``` +fleet search get-chunk [--neighbors N] [--text] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | chunk id | required | The chunk to fetch. | +| `--neighbors` | `N` | `0` | Include N chunks either side **in the same message**. | +| `--text` | — | off | Human-readable output instead of JSON. | +| `-h`, `--help` | — | — | Print this verb's own usage. | + +### Behaviour + +Fetches one chunk with its provenance (session, client, sensitivity). **`get-chunk` always runs standalone** — it is job-scoped in the service protocol, so it cannot ride the service route; when via-service was *requested* (flag/env/config — the seat default doesn't count) it prints the loud fallback note first, then delegates to the standalone artifact. + +### Exit codes + +- `0` — ok. +- `1` — backend failure surfaced without a fallback. +- `2` — usage/validation. +- `3` — routing unavailable (no standalone artifact). + +### Example + +```console +$ fleet search get-chunk 112081 --neighbors 2 --text +``` + +Fetches chunk 112081 with two neighbouring chunks on each side, rendered as text. diff --git a/pkgs/fleet/book/reference/secrets.md b/pkgs/fleet/book/reference/secrets.md new file mode 100644 index 0000000000..40034ffc08 --- /dev/null +++ b/pkgs/fleet/book/reference/secrets.md @@ -0,0 +1,83 @@ +# fleet secrets + +`fleet secrets` resolves secrets **by name**: the secrets broker first, Bitwarden (`bws`) as fallback. Secret values are never printed anywhere except `get`'s stdout, never logged, and never written to a file by this domain. For the broker itself — its cache, refresh, and serving gate — see [Secrets and the secrets broker](../concepts/secrets.md) and the `secrets-broker` role in [fleet serve](serve.md). + +The platform rule is that secrets are resolved by name through the fleet-secrets chain only; no domain shells out to `bws` or reads a token file on its own. + +## The resolution chain (shared context) + +`get` walks this chain in order: + +1. **Broker leg(s) first.** Where the secrets broker's own socket answers (the laptop), a direct source speaks `GET /secret/` over that Unix socket directly. Elsewhere (the sandbox), a broker source makes a **framed exchange through the session broker** to port 4800: the request names the token *file* (`[secrets] token_file`, default `~/tools/secrets-broker-token`); the session broker reads the file per request and sends its contents as `X-Agent-Token` — fleet only ever names the file; the value never transits fleet's own memory on this leg. +2. **`bws` CLI fallback** — `bws secret list` + `get`, the same shape the broker itself uses to fill its cache. The fallback carries its own credential: the `BWS_ACCESS_TOKEN` env var when non-empty, else the on-disk machine-account token file, handed to the `bws` child via its environment. +3. (Library-level, not in this domain's headline chain) a 1Password source for seats that keep secrets there — the same names resolve without a broker or a Bitwarden token. + +Retry semantics: a broker leg that cannot answer is retried before the chain moves on — the budget is sized to real restart windows (a full switch restarts broker + tunnel together; the broker is back in ~16 s) without making a genuinely dead broker a hang: the first pause doubles per attempt up to a cap, with a per-attempt ceiling on a single exchange. Exactly one broker leg owns the retry budget; when a direct leg exists, the session-broker leg behind it gets no retries. A broker **404 is definitive** about the name and is not retried. If the session-broker socket file does not exist at all, the leg does not burn the retry budget. Resolved values live in a type whose `Debug` is redacted; chain errors count failed sources without ever carrying a value. + +Known discrepancy: "the laptop secrets-broker" in the domain summary is **location-relative**. On the sandbox the first leg is a *local* loopback broker spawned by `fleet init`; on the laptop it is a direct Unix-socket leg; only from the sandbox-through-proxy path is it the laptop's broker. + +The three broker service tokens are published in Bitwarden Secrets Manager under the names `fleet.secrets-broker-token`, `fleet.queue-broker-token`, and `fleet.laptop-agent-token`, and live on a seat as mode-0600 files `~/tools/secrets-broker-token`, `~/tools/queue-broker-token`, and `~/tools/laptop-agent-token`. Do not conflate these client-side files with the daemon-side token files in each broker's own config dir (`~/.config/secrets-broker/token`, `~/.config/queue-broker/token`). + +## fleet secrets get + +``` +fleet secrets get +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `` (positional) | secret name | required | Exactly one name, not starting with `-`. This verb takes no flags. Help flags are answered before arity checks, so `--help` is never mistaken for a secret name. | + +### Behaviour + +Resolves one secret by name through the chain above. The value goes **to stdout and nowhere else**; errors are value-free shapes on stderr. A broken pipe on stdout is a quiet success (the Unix-filter rule), so `fleet secrets get NAME | head` does not fail. + +Broker response shapes this verb consumes: a cache hit answers `{"key", "value", "fetched_at_unix", "age_seconds", "source": "cache"}`; a read-through hit answers the same shape with `"source": "bitwarden-read-through"` and `"age_seconds": 0`; a not-loaded broker answers 503 `{"error": "secrets not loaded yet"}`; an absent name answers 404 `{"error": "no such secret"}`; a Bitwarden read-through failure answers a loud 502, never a silent 404-as-if-absent. + +### Exit codes + +- `0` — ok, value on stdout (including the broken-pipe case). +- `2` — usage (missing/extra name, or a name starting with `-`). +- `3` — unresolved / broker unavailable and the fallback could not resolve the name either. + +### Example + +```console +$ fleet secrets get fleet.secrets-broker-token > /dev/null && echo resolved +resolved +``` + +(The value itself is deliberately not shown; in real use it is piped or captured, never displayed.) + +## fleet secrets list + +``` +fleet secrets list +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments and no flags. | + +### Behaviour + +Lists the names in the broker's cache, one per line — names only, never values. Source selection mirrors `get`'s first leg only: the direct broker source when the broker's own socket is configured/live, else the session-broker source over the session broker socket plus the configured secrets token file. + +Known discrepancy: `list` has **no `bws` fallback**, contradicting the symmetry the domain summary ("broker first, Bitwarden as fallback") suggests. A broker failure is loud — stderr plus exit 3 — because a `bws` listing has different semantics: it enumerates the vault, not the broker's cache, so it is never silently substituted. + +### Exit codes + +- `0` — ok, names on stdout. +- `2` — usage (trailing argument). +- `3` — broker unavailable. There is no fallback for this verb. + +### Example + +```console +$ fleet secrets list +fleet.laptop-agent-token +fleet.queue-broker-token +fleet.secrets-broker-token +``` + +Names only; the listing is the broker's cache, not the vault. diff --git a/pkgs/fleet/book/reference/serve.md b/pkgs/fleet/book/reference/serve.md new file mode 100644 index 0000000000..643637e765 --- /dev/null +++ b/pkgs/fleet/book/reference/serve.md @@ -0,0 +1,186 @@ +# fleet serve + +`fleet serve` runs one or more fleet daemon roles in the foreground. Each role is a blocking serve loop that also exists as a leaf elsewhere in the binary; `serve` is the composition point a service manager (systemd) supervises. + +Roles: + +| Role token | Capability | Runs | Same leaf as | +|---|---|---|---| +| `queue-broker` | `queue-broker` | the repo work queue as a resident service | argv0 `queue-broker` | +| `secrets-broker` | `secrets-broker` | the Bitwarden-backed secrets cache | argv0 `secrets-broker` | +| `search` | `search-serve` | the Atlas search service | `fleet search serve`, argv0 `atlas-search serve` | +| `proxy` | `proxy-serve` | the session proxy broker | `fleet proxy serve` | + +See also [fleet proxy](proxy.md), [fleet secrets](secrets.md), [fleet search](search.md), and [Secrets and the secrets broker](../concepts/secrets.md). + +## Role-list semantics + +``` +fleet serve +fleet serve [ ...] +``` + +- **One role:** `fleet serve ` runs that role in the foreground. +- **Two or more roles:** `fleet serve [ ...]` with two or more *distinct* role tokens and nothing else runs all of them in one process. The parser only engages as a list when at least the first two tokens are both role tokens; it then validates the whole tail. +- A duplicate is a hard error: `error: duplicate role 'queue-broker' in 'fleet serve' list`. +- Any non-role token is a hard error, for example: `error: unexpected argument '--help' in 'fleet serve' list: a serve list is role tokens only (queue-broker, secrets-broker, search, proxy)`. +- **All roles are capability-checked before anything binds.** If any role is not available in this invocation, the whole list stubs with exit 69 and `fleet serve: role '' cannot run in this invocation` — there is no partial start. +- Each role's blocking loop runs on **its own thread** in the one process. Startup prints `fleet serve: starting N roles in one process: `. +- Supervision is fail-fast: the supervisor polls the threads on a 100 ms tick; **the first role thread to return or panic takes the whole process down** (the external supervisor restarts the unit). The process exit code is the role's own code, except that a role exiting cleanly (code 0) is converted to exit **1** — a daemon role returning at all is abnormal — and a panic is also exit 1. The role is named on stderr either way. +- One composition subtlety: the `proxy` role inside a list runs co-hosted, which **disables the proxy's idle-exit**, so an idle proxy cannot exit the shared process and kill its siblings. + +Known discrepancy: a serve list has **no `--help` form at all** — appending `--help` to a two-role list is the hard error above, not help. Single-role `--help` works, but for the two brokers it returns only the generic serve domain help (see below). + +If the invocation cannot use a role at all (not in this build, narrowed out by the invocation name, or disabled by config), `serve` answers with the capability stub on stderr, always **exit 69**. + +### argv0 aliases + +Invoking the binary as `queue-broker` or `secrets-broker` routes straight into the serve domain with that role prepended. Help, stub, and argument-rejection behaviour are identical to the spelled-out form. + +## fleet serve queue-broker + +``` +fleet serve queue-broker +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | This role takes no flags and no arguments. | + +### Behaviour + +Runs the repo work queue as a resident service. Any trailing argument is rejected before the daemon starts with `unexpected argument '' for 'fleet serve queue-broker'`, exit 2 — through the serve spelling and through the argv0 alias alike. A help flag in the flag position (`fleet serve queue-broker --help`) is answered first with the *generic serve domain help*, exit 0. + +- **Bind:** TCP `QUEUE_BROKER_BIND`, default `100.99.113.103:4801` (the laptop tailnet address), **plus a Unix-socket dual-bind**: `QUEUE_BROKER_SOCKET`, default `~/.config/queue-broker/broker.sock`. Routes and auth are identical on both transports. A Unix-socket bind failure degrades to "TCP only" with a log line. +- **Token:** `QUEUE_BROKER_TOKEN_FILE`, default `~/.config/queue-broker/token`; an unreadable token file is a startup error, exit 3. Requests carry `X-Agent-Token`; a pre-body gate refuses unauthenticated or oversized requests from headers alone (401 / 413) before any body byte is read. The only unauthenticated route is the health probe. +- **Protocol:** `POST /` with a JSON args object; response envelope `{"ok": true, ...}` or `{"ok": false, "exit": N, "error": "..."}` where `exit` mirrors the queue client's codes (2 validation, 3 config, 4 HTTP, 5 no row). +- **Health:** `GET /healthz` returns `{"service": "queue-broker"}`, unauthenticated. +- **Backend:** Turso only, on the dedicated `fleet-queue` database at `QUEUE_BROKER_TURSO_URL`, token from `QUEUE_BROKER_TURSO_TOKEN_FILE` or resolved from the secrets broker. `QUEUE_BROKER_BACKEND` unset, empty, or `turso` is accepted; anything else is a startup config error, exit 3. +- **Secrets dependency:** `QUEUE_BROKER_SECRETS_URL` (default `http://100.99.113.103:4800`, or `unix://` for the secrets broker's socket) and `QUEUE_BROKER_SECRETS_TOKEN_FILE` (default `~/.config/secrets-broker/token`). +- **Startup ordering:** the listener binds *first*, then the Turso backend comes up on a startup thread, so `/healthz` answers immediately and queue verbs answer exit 3 with a `turso_pending` reason until the backend is ready. A backend that cannot come up within its retry budget still exits the broker with 3 so the supervisor restarts it. + +Known discrepancy: there is no role-specific help for this role; `fleet serve queue-broker --help` prints the generic serve domain help. + +### Exit codes + +- `0` — only via `--help`; a running broker returning 0 in a serve list is converted to 1 by the supervisor. +- `2` — unexpected argument. +- `3` — token-file or backend startup failure. +- `69` — role not available in this invocation. + +### Example + +```console +$ fleet serve queue-broker +``` + +Runs the queue broker in the foreground on TCP port 4801 and its Unix socket until stopped. + +## fleet serve secrets-broker + +``` +fleet serve secrets-broker +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | This role takes no flags and no arguments. | + +### Behaviour + +Runs the secrets broker in the foreground, dual-bound on TCP and a Unix socket. Any trailing argument is rejected before the daemon starts with `unexpected argument '' for 'fleet serve secrets-broker'`, exit 2. A help flag in the flag position is answered first with the generic serve domain help, exit 0. + +The broker's full semantics — the serving gate, cache-first reads, read-through on miss, refresh, and per-secret install — are covered in [Secrets and the secrets broker](../concepts/secrets.md). The client side is [fleet secrets](secrets.md). Its configuration: + +| Env var | Default | Meaning | +|---|---|---| +| `SECRETS_BROKER_BIND` | `100.99.113.103:4800` | TCP bind. On the sandbox (`FLEET_LOCATION=sandbox`) the bind is forced to `127.0.0.1:4800` at the bind itself, whatever the env says. | +| `SECRETS_BROKER_SOCKET` | `~/.config/secrets-broker/broker.sock` | Unix-socket dual-bind; a bind failure degrades to TCP-only with a log line. | +| `SECRETS_BROKER_TOKEN_FILE` | `~/.config/secrets-broker/token` | Daemon token file; unreadable means startup exit 3. | +| `SECRETS_BROKER_TTL_S` | `900` (minimum `30`) | Refresh interval in seconds. Unparseable falls back to 900 with a warning; parsed but below 30 refuses to start, exit 2. | + +Endpoints (header `X-Agent-Token` required on everything except `/health`; identical over TCP and the Unix socket): `GET /health`, `GET /secrets` (names only, sorted), `GET /secret/`, `POST /refresh`. + +Known discrepancy: there is no role-specific help for this role; `fleet serve secrets-broker --help` prints the generic serve domain help. + +### Exit codes + +- `0` — only via `--help`. +- `2` — unexpected argument, bad home, or a refused TTL. +- `3` — token-file or bind failure. +- `69` — role not available in this invocation. + +### Example + +```console +$ fleet serve secrets-broker +``` + +Runs the secrets broker in the foreground on TCP port 4800 and its Unix socket until stopped. + +## fleet serve search + +``` +usage: fleet serve search [options] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--config` | `PATH` | `~/.local/state/atlas-search/service.json` (env `ATLAS_SEARCH_SERVICE_CONFIG`) | Service config file. | +| `--listen` | `ADDR` | from config | Listen address override (loopback only). | +| `--job-ttl-ms` | `N` | `600000` | Completed-job TTL override, milliseconds. | +| `--hard-ttl-ms` | `N` | `3600000` | Submit hard-cap override, milliseconds. | +| `-h`, `--help` | — | — | Print this role's usage and exit 0. | + +### Behaviour + +This is the only flag-bearing serve role. It runs the Atlas search service in the foreground: the loopback HTTP job protocol over one shared Snowflake embedder and a read-only Turso backend — the atlas-search service rehomed into fleet, same config, same wire. The role is also reachable as `fleet search serve`; both spellings require the `search-serve` capability. See [fleet search](search.md) for the client. + +- The embedder is the Snowflake `snowflake-arctic-embed-m-v2.0` model at a pinned snapshot revision, loaded lazily on the first vector query only — FTS-only jobs and a cold service work without it. The model directory resolves from `ATLAS_MODEL_DIR` / the Nix closure. +- The backend is a read-only Turso backend; its token comes only from the service config chain, never the environment. +- The job protocol is a bounded async queue with in-memory temp state; `/health` reports the embedder load state. +- `init` (client table) and `fetch-model` deliberately stay on the standalone atlas-search artifact. Rollback is pointing the unit's ExecStart back at `atlas-search serve`. + +### Exit codes + +- `0` — only via `--help`; a running service never exits 0. +- `1` — runtime failure. +- `2` — usage / config error. +- `69` — role not available in this invocation. + +### Example + +```console +$ fleet serve search --job-ttl-ms 300000 +``` + +Runs the search service with a five-minute completed-job TTL. + +## fleet serve proxy + +``` +fleet serve proxy +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | This role takes no flags and no arguments. | + +### Behaviour + +Runs the session proxy (the broker) in the foreground, binding the broker socket from fleet config (`FLEET_BROKER_SOCKET` / `[proxy] broker_socket`, default `~/.cache/laptop-agent/broker.sock`). It is the same leaf as `fleet proxy serve`; see [fleet proxy](proxy.md) for the full broker semantics — warm pools, the hello negotiation, keepalive, and idle exit. Inside a multi-role serve list the proxy runs co-hosted and its idle-exit is disabled (see Role-list semantics above). Unlike the two broker roles, this role has its own usage text: `fleet serve proxy --help` prints the proxy-role usage, exit 0. + +### Exit codes + +- `0` — clean exit (for example `--help`, or a live broker already owning the socket); in a serve list a clean role exit is converted to 1. +- `2` — unexpected argument. +- `69` — role not available in this invocation. + +### Example + +```console +$ fleet serve queue-broker secrets-broker proxy +fleet serve: starting 3 roles in one process: queue-broker secrets-broker proxy +``` + +Runs all three roles in one supervised process; the first role to exit takes the process down. diff --git a/pkgs/fleet/book/reference/shell.md b/pkgs/fleet/book/reference/shell.md new file mode 100644 index 0000000000..029870c898 --- /dev/null +++ b/pkgs/fleet/book/reference/shell.md @@ -0,0 +1,112 @@ +# fleet shell + +`fleet shell` runs a command, or opens a shell, where builds belong: the laptop, a codespace, or here. A limited sandbox is the wrong place to compile. It adds no transport; it builds the argv for the verb that already knows how to get there. The domain rides on the `agent` capability. + +Known discrepancy: the top-level help for this domain lists only `targets` and hides every flag below. The flags are documented here from source (they appear only in the domain's `--help` text). A second discrepancy: the `--detach` usage error for local/codespace says "it needs --target laptop", but the actions target also accepts `--detach` with different semantics — the error string predates the actions target. + +See also [fleet agent](agent.md) and [fleet laptop-agent](laptop-agent.md). + +## fleet shell + +``` +fleet shell [options] [-- COMMAND...] +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| `--target` | `auto\|laptop\|codespace\|actions\|local` | `auto` | Where to run. An explicit target is used as given and **never falls back** — a caller that asked for the laptop does not silently build in a sandbox. | +| `--codespace` | `NAME` | the first available | Which codespace (codespace target). | +| `--repo` | `OWNER/NAME` | this checkout's `origin` | The repository an actions run executes in. | +| `--cwd` | `DIR` | — | Directory to run in (the Cargo workspace for the shared target lane). A usage error on the actions target ("the command runs in the runner's checkout of the repository"). | +| `--build` | — | off | A heavy build: take a fleet-build-lock slot; Cargo workspaces use a shared target lane (see Behaviour). A usage error on the actions target ("dispatches through placement instead — drop --build"). Requires a command after `--`. | +| `--timeout` | `SECS` | laptop non-build `120`; laptop build `3600`; actions wait `3600` | How long a laptop command may run; on the actions target, how long to wait for the run. Must be a `u64`. Requires a command after `--`. | +| `--detach` | — | off | Laptop: start it as a laptop job and return its id (follow with `fleet laptop-agent poll JOB --wait N`). Actions: dispatch and return the session handle instead of waiting. A usage error on local/codespace. Requires a command after `--`. | +| `--print` | — | off | Print the plan as JSON instead of running it: `{target, codespace (name\|null), repo (actions repo\|null), program, args, because}`. | +| `-h`, `--help` | — | — | Print the full usage (the only place the flags are listed). | + +Positionals before `--`: only the single word `targets` is allowed; anything else is a usage error "unexpected argument '{x}': put the command after `--`". `--build`, `--detach`, and `--timeout` all require a command after `--`; with no command they are a usage error. + +### Behaviour + +**Targets:** `auto` (default), `laptop`, `codespace`, `actions`, `local`. + +**Auto resolution, in order:** + +1. Env **`FLEET_SHELL_TARGET`** (parsed with the same validator; an invalid value is a usage error) — only when `--target` was left at `auto`; an explicit `--target X` beats the env. +2. **Here, if this seat is the laptop:** seat signal = env `FLEET_LOCATION` or fleet.toml host location, trimmed, equal to `"laptop"`. +3. **The laptop, if it answers:** probe = running `fleet laptop-agent health` successfully. +4. **A codespace, if one exists:** the first codespace from `gh codespace list --json name,repository,state`. +5. **Here** (`local`), with because-string "neither the laptop nor a codespace answered; running here". + +**Auto never picks actions.** Actions is reachable only by explicit `--target actions` (or `FLEET_SHELL_TARGET=actions`). + +**Per-target execution plan:** + +- **local:** interactive (no command) → `sh -l`. With a command → `sh -lc ` where the line is the command, prefixed `cd {cwd} && ` when `--cwd` was given, or the build line when `--build`. `--detach` on local is a usage error. +- **laptop:** interactive → `fleet proxy ssh --` (the pinned ssh leaf). With a command → `fleet laptop-agent exec --shell -- `, with `--cwd DIR` when given and `--timeout N`. With `--detach` → `fleet laptop-agent run --shell -- ` instead (no `--timeout` is passed in detach mode), returning the laptop job id. +- **codespace:** `gh codespace ssh -c NAME [-- ]`; NAME from `--codespace`, else the first available (preferring `state == "Available"`, else the first listed). Interactive = no `--` part. `--detach` on codespace is a usage error. +- **actions:** the plan *is* a placement dispatch: `fleet queue dispatch --repo {repo} --command {command} --dispatch --json`. `--repo` defaults to this checkout's `origin` remote parsed for `github.com/` / `github.com:` shapes; with neither a flag nor a GitHub origin it errors "the actions target needs a repository". Interactive use is a usage error ("it cannot open a shell"). + +Command quoting: the words after `--` are joined by shell-string rules — a single word is taken as shell text verbatim; multiple words are POSIX-quoted word by word (left bare only if `[A-Za-z0-9_\-./:=,+@%]`, else single-quoted). + +**`--build`: the build lock and the Cargo target broker.** On laptop/local/codespace, a `--build` command is wrapped by the build lock: `~/tools/fleet-build-lock ` (one slot). If the host has no executable lock, local/codespace fall back with a stderr note "fleet shell: this host has no build lock; running without one". If the command may invoke Cargo (a `cargo` invocation followed — after skipping toolchain/flag words — by a compiling subcommand `build|check|test|bench|clippy|run|install|doc|rustc|nextest|fix|package|publish`, and conservatively **any** `just` or `make` invocation), the locked command is instead a broker-aware shell script that: locates the Cargo workspace (honouring `--manifest-path`/`--path`), derives a repo key (the path segment after `pkgs/`, else the workspace root basename, sanitised), and leases a shared target dir from `~/tools/cargo-target-broker checkout --repo {key} --profile {dev|test|release} --wait 900 --json` (profile: `test` if the command mentions test/bench, `release` for `--release` or a non-`--debug` `install`, else `dev`; `--workspace-cwd` added when the caller's cwd is outside the workspace). It exports the leased `CARGO_TARGET_DIR`, runs the command in its own process group with signal-forwarding traps, and checks the lease in on exit. If the broker/lease fails, it falls back to `CARGO_TARGET_DIR=$HOME/build-cache/{repo}` with the stderr note "fleet shell: broker unavailable; using shared fallback …". Non-Cargo builds under the lock run as `fleet-build-lock sh -c ''`. + +**Detach behaviour, per target:** + +- **laptop + `--detach`:** runs `fleet laptop-agent run …` and returns its job id immediately; follow up with `fleet laptop-agent poll JOB --wait N`. No timeout is forwarded. +- **actions + `--detach`:** dispatches through placement (a "patient" call — dispatch is not cut short, "cutting it short would orphan the run"), extracts `handle` from the JSON (missing handle or non-JSON is a Down error), prints `{target: "actions", repo, handle, state, run_url, because, note: "dispatched, not waited on; reconnect with: fleet queue session result {handle}"}` and exits 0. +- **actions without `--detach`:** polls `fleet queue session result {handle} --json` every **15 s** until `terminal` is true or the budget (default 3600 s, or `--timeout`) expires. On terminal it prints `{target, repo, handle, state, run_url, because}` and exits **0 iff state == "succeeded", else 1** (failed *and* cancelled both give 1). On budget expiry it errors "run {handle} still {state} after {budget}s; reconnect with: fleet queue session result {handle}". The run's own output is **not** streamed: "the run's own output lives on that page (gh run view --log)". +- **local / codespace + `--detach`:** usage error — "--detach starts a laptop job; it needs --target laptop". + +### Exit codes + +- The executed command's / leaf verb's exit code, in general. +- Actions target: `0` iff the run succeeded, else `1` (and `0` for a successful `--detach` dispatch). +- `2` — usage (bad target, missing command for `--build`/`--detach`/`--timeout`, detach on local/codespace, interactive/`--build`/`--cwd` on actions, invalid `FLEET_SHELL_TARGET`). + +### Example + +```console +$ fleet shell --target laptop --build -- cargo test +``` + +Takes a build-lock slot on the laptop, leases a shared Cargo target dir, and runs `cargo test` there with the 3600 s build timeout. + +## fleet shell targets + +``` +fleet shell targets +``` + +| Flag | Argument | Default | Meaning | +|---|---|---|---| +| — | — | — | Takes no arguments; anything after `--` with `targets` is a usage error. | + +### Behaviour + +Prints a JSON reachability report: + +```json +{"targets": [{"target": "laptop", "reachable": true, "how": "…"}, + {"target": "codespace", "reachable": false, "codespace": null}, + {"target": "actions", "reachable": true, "how": "…"}, + {"target": "local", "reachable": true, "how": "this machine"}], + "auto_would_pick": {"target": "laptop", "because": "…"}} +``` + +The `how` strings: laptop = "this seat is the laptop" or "fleet laptop-agent (broker, Cloudflare tunnel, tailnet, ssh)"; codespace = "gh codespace ssh"; actions = "fleet queue dispatch (placement over the registered Actions surfaces)"; actions reachability = `fleet queue surfaces` parses and contains at least one `github-actions` or `blacksmith` surface (of any status). + +Known discrepancy: because reachability ignores surface `status`, a registry whose only Actions surface were a standby surface would still report actions reachable even though placement could never pick it. + +### Exit codes + +- `0` — report printed. +- `2` — usage. + +### Example + +```console +$ fleet shell targets +``` + +Prints which targets answer from this seat and which one `auto` would pick, with the reason. diff --git a/pkgs/fleet/book/tutorials/bridge-messaging.md b/pkgs/fleet/book/tutorials/bridge-messaging.md new file mode 100644 index 0000000000..8454d4d0df --- /dev/null +++ b/pkgs/fleet/book/tutorials/bridge-messaging.md @@ -0,0 +1,255 @@ +# Tutorial: bridge messaging + +This tutorial exercises the whole bridge loop: an agent says hello and +registers its mailbox, central sends it a message and a command, the +agent reads its inbox, posts a reply, and acknowledges what it has +handled — and central reads the log to confirm the exchange. + +It assumes the `fleet` binary is installed (see +[Installation and bootstrap](../getting-started/installation.md)). + +The model in one paragraph: every fleet agent has a **mailbox** on the +message bridge (live at `https://bridge.security.cab`) named after it, +and registers with optional **groups**. Central sends a message or a +command to one agent, a group, or all; the agent reads its mailbox, does +the work, and posts its answer back, which marks the command handled. +The bridge's agent registry is exactly the set of agents that have said +hello. + +There are two credential classes, both resolved **by name** through +fleet secrets — never typed or printed: + +- **Central verbs** (`send`, `agents`, `log`) use the owner token, + secret name `message-bridge.access-token`. +- **Agent verbs** (`hello`, `inbox`, `post`, `ack`) use the fleet token, + secret name `message-bridge.fleet-token`, which opens only the agent + routes and cannot send commands. + +Every verb's output is the bridge's JSON, passed through. Exits for the +whole domain: `0` ok, `2` usage, `3` transport or credentials, `4` the +bridge refused the request (its JSON error goes to stderr). One help +quirk: `fleet bridge` has a **single shared usage text** for the whole +domain — every per-verb `--help` prints the same block, so read the line +for the verb you are running. + +The agent name defaults to `$FLEET_AGENT`, then `[bridge] agent` in the +fleet config; groups default to `$FLEET_AGENT_GROUPS`, then +`[bridge] groups`; the bridge URL to `$FLEET_BRIDGE_URL`, then +`[bridge] url`, then the default above. The steps below pass `--agent` +explicitly so the flow is unambiguous. + +## Step 1: Say hello — register the mailbox + +```bash +fleet bridge hello --agent --groups muse,code-lanes +``` + +What the output means: the bridge's JSON answer to the registration. +Your agent now appears in the registry with the groups you named and a +last-seen time from this call. `hello` is both the first registration +and the refresh: re-running it updates groups and last-seen. This is +also the call `fleet agent enroll` makes for its bridge leg (see +[Tutorial: enrol a new seat](enrol-a-seat.md)). + +What can go wrong, and the fix: + +- Exit `3`: the fleet token could not be resolved by name, or the bridge + is unreachable. Verify secret resolution with + [Tutorial: resolve a secret](resolve-a-secret.md). One special case: + on a seat where the fleet token's secret is missing but the owner + token resolves (the laptop seat), the fleet token is derived from the + owner token in-process, exactly as the bridge derives it — it is never + written anywhere. If hello works on the laptop without the fleet-token + secret present, that derivation is why. +- Exit `4` with a `404` shape: reported as a wrong token, an old bridge + without fleet mailboxes, or a wrong URL. Check the URL resolution + order above before suspecting the token. + +## Step 2: Send to an agent, a group, and all (as central) + +Central sends with `--to`. Targets are `agent:` (or a bare name), +`group:`, or `all`; repeat `--to` or comma-separate several. + +A plain message to one agent: + +```bash +fleet bridge send --to agent: "standup notes are in the shared doc" +``` + +The same message to a whole group: + +```bash +fleet bridge send --to group:muse "standup notes are in the shared doc" +``` + +And to every registered agent: + +```bash +fleet bridge send --to all "standup notes are in the shared doc" +``` + +A **command** — work the agent is expected to do and answer — adds +`--command` (without it, the default is a plain message): + +```bash +fleet bridge send --to agent: --command "run the queue health check and report back" +``` + +Long text can come from stdin by passing `-` as the text argument. +`--sender NAME` overrides the recorded sender name. + +What the output means: the bridge's JSON answer for the send. The +message is now in each target mailbox as an unread row; for a command, +it will sit as an unhandled command until the agent posts its answer +(Step 4). + +What can go wrong, and the fix: + +- Exit `3` as central: the owner token (secret name + `message-bridge.access-token`) did not resolve. Central verbs cannot + use the fleet token, and the fleet token cannot send commands — using + the wrong class is a credentials failure, not a partial send. +- Exit `4`: the bridge refused — read its JSON error on stderr; a + mistyped target is refused here rather than silently dropped. + +## Step 3: Read the inbox (as the agent) + +```bash +fleet bridge inbox --agent +``` + +What the output means: your **unread** rows as JSON. Useful filters, +all from the shared usage: + +- `--commands` or `--messages`: only that kind. The intake ladder's push + rung reads with `--commands --take`, because a pushed command outranks + every other source of work. +- `--all`: include rows already read. +- `--take`: mark what this call returns as read, as it returns it. +- `--since-id N`, `--limit N`: page the mailbox. +- `--wait SECS` (with `--interval SECS`, default interval 15 s): poll + until something arrives or the seconds pass. The wait is capped at + 24 hours in the client. +- `--groups g1,g2`: also read group mailboxes for those groups. + +Note the id of the command row from Step 2 — Step 4 replies to it, and +Step 5 acknowledges up to it. + +What can go wrong, and the fix: + +- An empty inbox right after a send: check the target spelling (a bare + name and `agent:` are the same target; a group send lands in the + group mailbox, which you read by passing `--groups`), and whether a + previous `--take` read already marked the rows read — re-read with + `--all` to see them. +- Exit `3` / exit `4`: same credential and refusal shapes as Step 1. + +## Step 4: Post a reply + +A bare `post` sends a message to central. With `--reply-to`, it answers +that specific row **and marks it read** — for a command, that answer is +what marks the command handled. + +```bash +fleet bridge post --agent --reply-to "queue health: all queues answering; details in the log" +``` + +As with `send`, `-` reads the text from stdin. + +`post` can also address others directly with `--to`: `drew`, `claude`, +`chatgpt`, `connectors`, `agent:` (or a bare name), +`group:`, `agents`, or `all`, repeated or comma-separated: + +```bash +fleet bridge post --agent --to group:muse "health check done — summary posted to central" +``` + +Adding `--instruction` (or `--kind instruction`) makes the post an +instruction, which **requires** `--to`. + +What can go wrong, and the fix: + +- Replying without `--reply-to` when you meant to answer a command: the + post lands as a new message to central, and the command stays + unhandled. Re-post with the row's id. +- Exit `2`: an instruction without `--to`, or other flag misuse — the + shared usage text is the reference. + +## Step 5: Acknowledge what you have handled + +Reading with `--take` marks rows read as they are returned; `ack` is the +explicit form, for rows you read earlier or handled out of band. It +takes either explicit ids or one `--up-to` boundary: + +```bash +fleet bridge ack --agent --up-to +``` + +```bash +fleet bridge ack --agent +``` + +What the output means: the bridge's JSON answer; the named rows (or +every row up to the boundary) are now read, so they no longer count in +your unread total and no longer appear in a default `inbox` read. + +What can go wrong, and the fix: + +- Acking rows you have not actually handled: `ack` is a state change, + not a receipt you can retract. Prefer `--take` on the read that does + the handling, and use explicit `ack` only for rows you can name. + +## Step 6: Read the log as central + +Central's view of the whole exchange is the log: + +```bash +fleet bridge log +``` + +What the output means: the central message log as JSON — both +directions, messages and commands. Filters: `--agent A`, +`--direction inbound|outbound`, `--kind message|command`, +`--since-id N`, `--before-id N`, `--limit N`, `--order asc|desc`. The +send from Step 2, the reply from Step 4 and the resulting handled state +are all visible here; this is the audit view the mailbox verbs do not +give you. + +The companion central verb is the registry view: + +```bash +fleet bridge agents +``` + +It prints the registered agents, their groups and unread counts — the +quick check that a Step 1 hello landed and that Step 5's ack drained +the unread count. + +Finally, the token-free health probe, useful before blaming credentials +for a failure in any step: + +```bash +fleet bridge health +``` + +It answers the bridge's `/healthz` with no token at all. + +What can go wrong, and the fix: + +- `log` and `agents` are central verbs: they need the owner token. An + exit `3` here with working agent verbs means the owner token's name + (`message-bridge.access-token`) is the one that does not resolve on + this seat — the two token classes fail independently. + +## You are done when + +- `fleet bridge agents` (as central) lists your agent with the groups + from Step 1. +- A command sent in Step 2 appears in the agent's Step 3 inbox, is + answered by a Step 4 `post --reply-to`, and shows as handled in the + Step 6 log. +- The agent's unread count in `fleet bridge agents` is back to zero + after Step 5's ack. +- You can state which token class each verb you ran used — owner token + for `send`/`agents`/`log`, fleet token for `hello`/`inbox`/`post`/ + `ack` — and neither value was ever printed. diff --git a/pkgs/fleet/book/tutorials/claim-and-complete.md b/pkgs/fleet/book/tutorials/claim-and-complete.md new file mode 100644 index 0000000000..809508b1f6 --- /dev/null +++ b/pkgs/fleet/book/tutorials/claim-and-complete.md @@ -0,0 +1,295 @@ +# Tutorial: claim and complete a queue task + +This tutorial works one queue task from claim to a verified completion: +claim it (through `fleet agent next`), keep the lease alive with +heartbeats, record progress with checkpoints, build the completion's +evidence with `verify-disposition`, and complete — including what the +evidence gate's rejection looks like and how to recover from it. + +It assumes the `fleet` binary is installed (see +[Installation and bootstrap](../getting-started/installation.md)) and the +seat is enrolled (see [Tutorial: enrol a new seat](enrol-a-seat.md)). + +One warning before Step 1, because it decides whether Step 6 works at +all: **a claim taken through `fleet agent next` may be registered under +the worker and lane `agent-next-05`, not under your agent name and not +under the queue client's defaults.** Every holder verb after the claim — +heartbeat, checkpoint and complete — is checked by the broker against +the worker (and the lane, when you supply one). Completing with the +wrong worker or lane does not complete the wrong task; it finds no +matching claimed row at all. Step 2 shows how to read the real worker +and lane out of the claim, and Step 6 uses them exactly: +`--worker agent-next-05 --lane agent-next-05`. + +## Step 1: Claim through `fleet agent next` + +```bash +fleet agent next --agent +``` + +What the output means: one JSON object, `{agent, rung, task, then, +tried}`. For queue work, `rung` is `"queue"` and `task` is the claimed +task row. The claim behind this rung is an ordinary queue claim with a +four-hour lease (`14400` seconds, overriding the queue client's +45-minute default). The `then` lines are part of the contract: they name +the lease deadline and the exact checkpoint and complete commands for +this claim, with the right task id, worker and lane already filled in. +Prefer those lines over retyping flags from memory. + +Exit `5` from `next` means no rung had work — there is nothing to claim +right now, and this tutorial ends there until work exists. Exit `2` is a +usage error; exit `3` is a leg down (run +`fleet agent doctor --agent ` and fix the leg). + +You can also claim directly with the queue client: + +```bash +fleet queue claim --worker --lane +``` + +A direct claim prints the task row verbatim as JSON — `{id, queue, +status, dedupe_key, payload, …}` — and exits `0`. Two direct-claim rules +surprise people: + +- A **bare claim is refused before any broker contact**, exit `2`: a + claim with no task, no filter, no queue scope, no count, no + handoff/bind and no identity marks (worker, lane, session-id, pool, + platform, from-session) "is never a meaningful intent". Passing + `--worker` explicitly counts as intent even when it equals the + default. +- **No claimable task** prints `{"task": null}` — deliberately carrying + no id, queue or status a caller could mistake for a task — plus a + diagnostic on stderr of the form `no claimable task — Q queued (A at + the attempt cap, D not yet due), P parked due`, and exits **5**. + +Keep the claimed row. Everything below needs its `id`, and Steps 2–6 +need the worker and lane the claim was stamped with. + +## Step 2: Read the claim's worker and lane + +```bash +fleet queue show +``` + +What the output means: the task's current details, sourced from the +broker's rich row for the task, plus the tail of its event timeline. +Confirm the row is `claimed`, and note the worker and lane recorded on +it. When the claim came from `fleet agent next`, expect the worker/lane +pair `agent-next-05` / `agent-next-05` — the shared identity the agent +ladder claims under. All scheduled lanes share related worker ids, which +is exactly why the lane matters: it is what tells the broker whose claim +a later verb acts on. + +What can go wrong, and the fix: + +- `repo-queue show: task not found`, exit `1`: the id is wrong, or + it never was a broker task id. Go back to the claim output from Step 1 + and copy the `id` from the row itself. +- Exit `3`: the broker path failed (unreachable, token rejected, or a + broker that does not serve the event routes). The claim itself is + unaffected; fix the transport and retry the read. + +From here on, this tutorial writes the holder flags as +`--worker agent-next-05 --lane agent-next-05`. If your Step 1 claim was +a direct claim under a different worker/lane, substitute the pair your +claim actually used, everywhere, unchanged. + +## Step 3: Heartbeat to keep the lease + +A claim is a lease. If it lapses, the task returns to the pool and +another worker may take it. A heartbeat sets the lease to *now plus the +extend* on both the task row and the lease record. + +```bash +fleet queue heartbeat --worker agent-next-05 --lane agent-next-05 +``` + +What the output means: the broker's updated task row as JSON, plus a +`mode_line` describing the route the verb took. The default extend is +**900 seconds (15 minutes)** — note the asymmetry: a claim's default +lease is 2700 seconds, but a heartbeat only adds 900 unless told +otherwise. For a long stretch of work, say so: + +```bash +fleet queue heartbeat --worker agent-next-05 --lane agent-next-05 --extend-seconds 3600 --progress "halfway through the fix" +``` + +`--extend-seconds` must be in `1..=86400`; values are rejected, never +clamped, and `0` or a negative value would lapse your own claim, so it +dies with exit `2`. `--progress

` (or `--progress-file ` — the two +are mutually exclusive, both together is exit `2`) merges a progress +value into the row. + +What can go wrong, and the fix: + +- Exit `5` with `heartbeat: no matching claimed row (task not claimed by + this worker, or already terminal)`: the broker does not believe you + hold this task. The usual causes are a wrong `--worker`/`--lane` pair + (re-read Step 2), a lease that already lapsed and was re-claimed by + someone else, or a task that is already terminal. Do not retry blindly + — check `fleet queue show ` first. +- Exit `6`: the primary queue store failed and the verb switched this + work to the GitHub fallback. The output is one JSON object naming the + switch, with a hint of the form `continue this work with: fleet queue + fallback scan|claim|heartbeat|release|unblock`. Follow it: from here + the task is worked through the fallback verbs until the primary store + returns. Setting `REPO_QUEUE_NO_FALLBACK_SWITCH=1` disables the switch + and restores plain die-on-error, if you ever need the raw failure. + +## Step 4: Checkpoint progress + +A checkpoint records where the work has got to, without touching the +lease. The broker merges the progress into the task row, stamps +`progress.last_checkpoint = {stage, at}`, stores a per-worker checkpoint +record, and writes a `checkpoint` event. + +```bash +fleet queue checkpoint --worker agent-next-05 --lane agent-next-05 --stage implementing --progress "fix written; tests running" +``` + +`--stage` is **required**. The help line brackets it as optional; the +client does not — omitting it dies with `checkpoint: --stage is +required`, exit `2`. The output is the updated row plus a `mode_line`, +exit `0`. + +What can go wrong, and the fix: + +- Exit `5`: the same no-matching-claimed-row shape as the heartbeat. + Same diagnosis: worker/lane pair, lapsed lease, or terminal task. +- Exit `6`: the fallback switch, exactly as in Step 3. + +Checkpoint at meaningful boundaries — claim taken, fix written, tests +green, PR opened — not on a timer. A later reader (or a later you, after +a crash) reconstructs the work from these stages. + +## Step 5: Build the completion evidence with `verify-disposition` + +A completion whose work is verifiable on GitHub must carry a +**disposition**: a fresh, live readback of the issue and its linked PRs, +produced by `verify-disposition`. It reads GitHub live — never a +remembered claim — and prints the record the completion gate will check. + +```bash +fleet queue verify-disposition --repo --json +``` + +`--repo` is required (exit `2` without it). Save the `--json` output to +a file; Step 6 feeds it to `complete` as the result's `disposition`. + +What the output means: a record of the form `{"checked_at", "source", +"issue": {number, state, state_reason, closed_at, closed_by}, "pulls": +[{number, state, is_draft, merged_at}], "verdict", "follow_up"}`. The +verb then runs the offline gate on its own record before returning: + +- Exit `0`: the record would pass the broker's gate. +- Exit `1`: the gate would reject it, or the issue/PR list could not be + read from GitHub at all. +- Exit `2`: a usage error. + +The verdict is one of exactly five: + +| Verdict | Means | +|---|---| +| `merged_verified` | Some pull in the readback is merged | +| `closed_verified` | The issue is closed and no unfinished pulls remain | +| `open_draft_with_followup` | Unfinished pulls exist, nothing merged, and a follow-up is on record | +| `open_draft_superseded` | Operator-asserted variant of the above, also requiring a follow-up | +| `invalid_no_work` | No merged pull, issue open, no unfinished pull | + +When the honest verdict needs a follow-up — typically +`open_draft_with_followup`, because a draft PR still carries work — +name exactly one follow-up target and give a reason (any follow-up +target **requires** `--reason`, exit `2` without it): + +```bash +fleet queue verify-disposition --repo --follow-up-pr --reason "the remaining work moved to the successor PR" --json +``` + +The alternatives are `--follow-up-task ` (checked by the broker at +completion time — only the queue knows whether that task is live) and +`--follow-up-issue ` (same repo only; its own readback is embedded +and checked: it must be open, must not be the issue being completed, and +must link the completed issue and every unfinished PR with an explicit +marker such as `Refs #n`). A successor PR must be in the readback and +must be merged. + +Two freshness facts to plan around: the record goes stale after **1800 +seconds (30 minutes)** by default (`--staleness-seconds` changes it for +this verb), and a record more than 300 seconds in the future is +unreadable clock skew. Run this step immediately before completing, not +at the start of the work. + +## Step 6: Complete — with the evidence gate + +```bash +fleet queue complete --worker agent-next-05 --lane agent-next-05 --result-file result.json +``` + +where `result.json` is a JSON **object** carrying, for a verifiable +completion, the disposition record from Step 5 under the key +`disposition`, plus any `pr` / `pr_url` / `merged_pr` fields naming the +PRs the completion claims. (`--result ` passes the object inline +instead; when both are given, `--result-file` wins. A result that is not +a JSON object dies with exit `2`.) + +What the output means on success: the task row — or +`{task, lane_ledger}`, and for a triage completion possibly a +`follow_on_task_id` — with the task now in the terminal status `done`. +Exit `0`. + +The evidence gate is pure (no network): before accepting the completion, +the broker parses the disposition record and checks its freshness, that +it describes this task's issue, that the verdict matches the readback, +that **every PR the result links appears in the readback**, and any +follow-up. A completion that requires a disposition and does not carry +one is rejected the same way. + +### What a gate rejection looks like, and how to recover + +A rejection names the defect and ends with the sentence that matters: +**"…; the task remains claimed"**. The completion did not land, nothing +terminal was written, and your claim — worker, lane and lease — is +exactly where it was. Recovery is therefore always the same shape: + +1. Read the named defect literally. The common ones: the record is + stale (older than 1800 s); the verdict does not match the readback + (for example claiming `merged_verified` with no merged pull in it); + a linked PR is missing from the readback; unfinished pulls remain + with no follow-up on record; a follow-up issue does not link the + completed issue or is itself closed. +2. Fix the underlying fact, not the wording. Merge the PR, close the + issue properly, file and link the follow-up, or correct the result's + PR fields so they name only PRs the readback contains. +3. Re-run Step 5 to mint a **fresh** disposition against the corrected + reality — never edit a stale record by hand; its `checked_at` is part + of what the gate checks. +4. Re-run this step's `complete` with the same worker and lane. Keep + heartbeating (Step 3) while you work through a rejection, so the + lease does not lapse mid-recovery. + +What else can go wrong here: + +- Exit `5`, no matching claimed row: wrong worker/lane (see Step 2) or + the lease lapsed during a long recovery. If the task was re-claimed + by another worker, it is theirs now — do not complete over them. +- Exit `6`: the fallback switch. In the fallback, completion is + `fleet queue fallback complete --worker + --summary --result `, where `--result` is the same + `verify-disposition --json` record; it must pass the same offline gate + **before anything is posted**, and a rejection there also posts + nothing, leaves the claim live, and exits `1`. +- `--telemetry `, if you pass it, may only carry the keys `pool`, + `model`, `effort`, `cost_usd`; an unknown field dies with exit `2` + listing the allowed set. + +## You are done when + +- `fleet queue show ` reports the task with status `done`. +- The completion you submitted carried a disposition record that + `fleet queue verify-disposition --repo ` + itself exited `0` on, minted within the staleness window before the + completion. +- No gate rejection is outstanding: if `complete` ever answered "…; the + task remains claimed", you fixed the named defect, re-minted the + disposition, and completed again — under the same `--worker` and + `--lane` the claim was taken with. diff --git a/pkgs/fleet/book/tutorials/dispatch-a-build.md b/pkgs/fleet/book/tutorials/dispatch-a-build.md new file mode 100644 index 0000000000..54f668fcd2 --- /dev/null +++ b/pkgs/fleet/book/tutorials/dispatch-a-build.md @@ -0,0 +1,313 @@ +# Tutorial: dispatch a build remotely + +This tutorial runs a build (or any command) in a target repository on a +fleet runner instead of on your own machine: first as a dry run, so you +read the placement decision before anything runs; then for real, so you +get a session handle; then polling that handle to a terminal result. It +also covers chaining a follow-up run onto the same host, pushing the Nix +cache, and the raw `gh` fallback for when no fleet binary is available. + +It assumes the `fleet` binary is installed (see +[Installation and bootstrap](../getting-started/installation.md)). The +placement model behind this tutorial — surfaces, tiers and the registry +as data — is covered in [Placement and surfaces as data](../library/placement.md). + +The verb is `fleet queue dispatch`. Despite living under `queue`, it is +not a broker verb: it is the placement engine absorbed into the queue +client. It decides **where** a job runs across the fleet's GitHub Actions +copies and runner providers, and dispatches the `fleet-command.yml` +workflow there. It is unrelated to the top-level `fleet dispatch` domain. + +## Step 1: Dry-run first, and read the placement decision + +Without `--dispatch`, the verb is a dry run: it loads the surface +registry, computes live capacity, picks a surface, prints the decision — +and writes nothing, dispatches nothing. + +```bash +fleet queue dispatch --repo --command '' +``` + +For example, a test run in this repository: + +```bash +fleet queue dispatch --repo developing-today/code --command 'cargo test --workspace' +``` + +`--repo` and `--command` are both required, and `--repo` must be a valid +`owner/name` (exactly one `/`, characters `[A-Za-z0-9._-]`); anything +else is a fatal usage error, exit `2`. Every error in this verb family +prints `repo-queue: ` on stderr and exits `2`. + +What the output means (human form): + +```text +decision: + - + - … +dry-run (no session written; pass --dispatch to submit) +``` + +Read the reasoning lines — they are the decision, not decoration. The +cascade that produced them, in order: + +0. A hard pin (`--surface ID`), if you gave one: that surface or a fatal + error, never a fall-through. +1. Follow-up affinity, if you gave `--followup` (Step 5). +2. **Tier 1 — free GitHub-hosted Actions**: every `github-actions` + surface that is eligible and has free slots, sorted least-loaded + owner first, then least-recently-used owner, then the registry's + `selection_priority`, then per-surface recency, then surface id. +3. **Tier 2 — Blacksmith**, in registry order, within its minute budget. +4. **Tier 3 — Codespaces**, only when the laptop is marked busy or the + surface was explicitly selected. + +If every tier is exhausted, the decision is `queued` with the reasoning +"all tiers exhausted — job stays queued (recorded, never dropped; +repo-queue remains its system of record)". + +For machine-readable output, add `--json`. A dry run's object carries +`job`, `decision`, `reasoning` and `"mode": "dry-run (no session written; +pass --dispatch to submit)"`, plus a `note` when a testing override was +used and `load_read_errors` when an owner's load could not be read (load +failures are soft: that owner's load counts as 0 and the error is +reported, not hidden). + +What can go wrong, and the fix: + +- `pinned surface is ineligible: `, exit `2`: a `--surface` pin + is a placement choice, not an override of eligibility. Read the + `` — a common one is pinning the `org-run` surface, whose registry + status is `standby`, not `active`, so it can never be selected or + pinned. Drop the pin or pick an eligible surface. +- `--surface : no such surface in the registry`: the id is not in + the registry (including surfaces whose `kind` has no adapter). List + the registry with `fleet queue surfaces` and copy an `id` exactly. +- A macOS job (`--platform macos`) is ineligible on surfaces without + `platform_input: true`, and counts against the owner's macOS sub-cap + (5 for every shipped owner). If the decision surprises you, the + reasoning lines name the surface that failed and why. + +## Step 2: Dispatch for real, and read the `fp_` handle + +Add `--dispatch` (and `--json`, so the handle is unambiguous): + +```bash +fleet queue dispatch --repo developing-today/code --command 'cargo test --workspace' --dispatch --json +``` + +What the output means: the job object, the `decision`, the full +`reasoning` array, and then the session fields — `handle`, `run_id`, +`run_url`, and (when known) `runner_repo` and `portable_id`. The handle +has the form `fp_` followed by 32 lowercase hex characters, for example: + +```text +fp_d0a842c9bd33aa2999f5a12393397ab9 +``` + +Keep it. The handle is how you poll (Step 3), how a follow-up finds this +run (Step 5), and how the session is recorded in the local store at +`~/.local/state/fleet-place/sessions.json` (override the store directory +with `$FLEET_PLACE_STATE`). That store is a labelled stopgap with the +reference implementation's record shape, kept so records migrate when +the designed backend table lands. + +How dispatch actually happens, so the output makes sense: for the chosen +surface's host repo, the client snapshots existing workflow runs, POSTs +the workflow dispatch (anything but HTTP `204` is fatal), then polls the +run list for up to about 40 seconds to correlate the new run — exactly, +when the surface declares a `dispatch_id` input, by matching a fresh +`fp_…` dispatch id placed in the run title. + +What can go wrong, and the fix: + +- The dispatch succeeds but no run correlates in time: the session is + still written, with `run_id: null`, state `dispatched`, and the note + "dispatch accepted (HTTP 204) but the run did not appear within ~40s; + resolve it from the workflow's run list". This is not a failed + dispatch — do not re-dispatch. Resolve the run from the host repo's + workflow run list, then refer to it by its portable reference + `/#` (Step 4). +- The all-tiers-exhausted case **with** `--dispatch`: a session record is + still written — `surface`, `run_id` and `run_url` all null, state + `queued` — and its handle is printed (the JSON gains `handle` and + `state`, but no `run_id`/`run_url` keys). The job is recorded, never + dropped; nothing is running yet. + +## Step 3: Poll the session to a terminal result + +```bash +fleet queue session status +``` + +What the output means: the stored record is refreshed from GitHub first +(if it has a run and a registered host surface), then printed in the +form: + +```text +: state= surface= run= +``` + +States are `queued`, `dispatched`, `running`, `succeeded`, `failed` and +`cancelled`, mapped from the GitHub run's status and conclusion. Add +`--json` to print the whole refreshed record instead of the one line. + +When you need the verdict rather than the state: + +```bash +fleet queue session result +``` + +That prints `: (terminal=) run=`, where +`terminal` is true exactly when the state is `succeeded`, `failed` or +`cancelled`. While it is not terminal, the record carries the note +"not terminal yet — reconnect with the same handle". Poll `result` on +your own cadence; there is no streaming form, and the run's own output +is not streamed either — it lives on the run page (`gh run view --log`). + +Two neighbouring forms worth knowing: + +```bash +fleet queue session list +fleet queue session list --mine +``` + +`list` prints every record in the local store, newest first — from the +stored state, **without** refreshing. `--mine` keeps only records whose +`submitted_by` is the current user on this host. + +What can go wrong, and the fix: + +- `repo-queue: no session with handle in `, exit `2`: + the handle is not in this seat's local store. Handles are local — + another seat's store does not have your record. Use the portable + reference instead (Step 4), which resolves live without the store. +- Do not pass `--help` to `session status` or `session result`: those + subcommands do not special-case it, so the token after the subcommand + is taken as the handle and you get exactly the "no session with handle + --help" error above. Only a bare `fleet queue session --help` prints + the usage. + +## Step 4: Refer to a run portably + +Anywhere a handle is accepted, a portable reference +`OWNER/REPO#RUN_ID` is accepted too — where `OWNER/REPO` is the +**runner-host** repo of a registered `github-actions` or `blacksmith` +surface (for example `developing-today/fleet`), not the target repo: + +```bash +fleet queue session result developing-today/fleet#45146933211 +``` + +What the output means: the reference is resolved directly against the +GitHub API with that surface's token, producing a synthetic record with +the same state mapping as Step 3. This is the form that survives moving +between seats and workspaces, and the form a follow-up takes when you do +not have the original handle. + +## Step 5: Chain a follow-up that sticks to the host + +A follow-up downloads the previous run's `fleet-output` artifact and, by +preference, stays on the same host surface — which also keeps it in the +same Actions cache scope, since caches are per host repo. + +```bash +fleet queue dispatch --repo developing-today/code --command '' --followup --dispatch +``` + +Dry-run it first (drop `--dispatch`) and read the affinity line in the +reasoning. The preferred surface is kept only while **all** of these +hold: its adapter exists and is eligible; it has capacity; and the +owner's queued count is strictly below the surface's +`sticky_queue_threshold` — `2` on every shipped surface. With two or +more runs already queued on that owner, stickiness is released, and the +reasoning records exactly why: `followup affinity released from : +eligible=<…>, capacity=<…>, queued= (threshold 2); …`. On a keep, the +line reads `followup affinity keeps : `. + +What can go wrong, and the fix: + +- With `--dispatch`, a previous run that is not yet terminal is fatal: + "previous run is still <state>; wait for a terminal result before + downloading its output". Wait for Step 3's `result` to report + `terminal=true` first. +- A previous dispatch with no correlated run yet is likewise fatal: + "previous dispatch has no correlated run yet; resolve its status + before continuing". Resolve it via Step 4, then chain from the + portable reference. +- In dry-run mode neither guard fires, and a local previous record is + read without refreshing — so a dry run can show an affinity a real + dispatch would refuse. Treat the dry run as a placement preview, not a + promise. + +## Step 6: The `--push-nix-cache` variant + +```bash +fleet queue dispatch --repo --command 'nix build' --push-nix-cache --dispatch +``` + +What changes: placement sends the workflow input `push_nix_cache: true`. +On success, the workflow's action signs `./result` and copies it to the +shared Fleet R2 cache — resolving `./result`, signing with the key from +the host repo's secret named `NIX_CACHE_SIGNING_KEY`, and uploading to +the URL in the secret named `NIX_CACHE_UPLOAD_URL` (names only; the +endpoint is secret-configured, not hardcoded). + +What can go wrong, and the fix: + +- "cache push requested but signing/upload secrets are not configured; + skipping": the run still succeeds; only the push is skipped. The host + surface you landed on does not carry the `NIX_CACHE_*` secrets — the + `fleet-personal` registry note names them for that surface. Pin or + follow up onto a surface whose host repo has them, or accept the skip. +- No `./result` in the target checkout: also a notice-and-skip. Build + something that leaves a `./result` link, or drop the flag. +- A related variant: `--actions-cache KEY:PATH` binds one extra Actions + cache path under the key prefix `KEY` (default namespace prefix + `fleet-deps-v1`), with `--actions-cache-restore-key PREFIX` (repeatable, + and it requires `--actions-cache`) adding restore prefixes. + +## Step 7: The raw `gh workflow run` fallback + +When no fleet binary is available — a foreign host, a broken install — +the same workflow can be dispatched directly. You give up placement (you +choose the host repo yourself), session records, and correlation; you +keep the identical workflow contract. + +```bash +gh workflow run fleet-command.yml --repo developing-today/fleet --field repo=developing-today/code --field command='cargo test --workspace' +``` + +The workflow is `fleet-command.yml` in a fleet host repo +(`dezren39/fleet`, `developing-today/fleet` or +`developing-today-forks/fleet`). Its inputs include `repo` and `command` +(both required), plus optional `ref`, `runner` (`github` or +`blacksmith`), `platform` (`linux` or `macos`), `container_image`, +`actions_cache_key` (default `fleet-deps-v1`), `actions_cache_path`, +`actions_cache_restore_keys`, `previous_run_id`, `previous_run_repo`, +`push_nix_cache` and `timeout_minutes` (5–120, default 60 — an input +placement itself never sends, so placement dispatches always get the +60-minute default). Follow the run with `gh run list --repo +--workflow fleet-command.yml` and `gh run view --log`. + +What can go wrong, and the fix: + +- Dispatching in the target repo instead of a host repo: there is no + `fleet-command.yml` in `developing-today/code` — it lives only in the + fleet host repos. Re-run against a host repo, with the target named in + the `repo` field. +- `runner=blacksmith` from any host repo other than + `developing-today/fleet`, or with `platform=macos`: the workflow's + normalize job rejects both. Use the `developing-today/fleet` host for + Blacksmith, on Linux. + +## You are done when + +- A dry run printed a `decision` whose reasoning lines you can explain: + which tier picked the surface, or why the pin/affinity held or was + released. +- The real dispatch printed an `fp_…` handle (or a portable + `OWNER/REPO#RUN_ID` reference you resolved from the run list). +- `fleet queue session result ` reports `terminal=true` with + the state you expected — `succeeded` for a good build — and you know + the run's own log lives on its run page, not in the session record. diff --git a/pkgs/fleet/book/tutorials/enrol-a-seat.md b/pkgs/fleet/book/tutorials/enrol-a-seat.md new file mode 100644 index 0000000000..92d77376cf --- /dev/null +++ b/pkgs/fleet/book/tutorials/enrol-a-seat.md @@ -0,0 +1,272 @@ +# Tutorial: enrol a new seat + +This tutorial takes a fresh seat — a new agent instance on a new sandbox or +machine — from nothing to taking work. It assumes the `fleet` binary is +already installed on the seat. If it is not, install it first by following +[Installation and bootstrap](../getting-started/installation.md), then come +back here. + +By the end, the seat will have its three broker token files, a registered +bridge mailbox, a saved agent profile, and a checked answer from every leg +of `fleet agent doctor`. Names, kinds and groups in the examples are +illustrative: pick your own agent name, and use a kind from Step 4. + +Secrets in this tutorial are handled **by name only**. You never type, +print or paste a secret value; the bootstrap fetches token files for you, +and every later command resolves the values it needs by name. + +## Step 1: Run the seat bootstrap + +On a Muse sandbox seat, the bootstrap script rebuilds the whole seat — +tools, tokens, the tailnet link, the binary, and the local init stack — +from the pinned release. It is idempotent: re-running it skips work that +is already done. + +```bash +bash scripts/muse/bootstrap.sh +``` + +What the output means: the script runs named phases in order — +`tools token restore tailnet fleet persist init check`. Each phase either +reports that its work was already present or does it and moves on. The +final `check` phase verifies the binary (including that the `bridge` +domain is available), the laptop link, secret resolution by name, and a +bridge hello/inbox probe as your agent. + +What can go wrong, and the fix: + +- A phase fails and the script stops, naming the phase. Exit `1` means "a + phase failed"; exit `2` means the command line itself was wrong. Fix the + named phase's cause (usually a missing download or a tailnet join that + needs attention) and re-run the whole script — completed phases skip + themselves. +- The check phase reports a missing token name. That is not fatal to + enrolment itself, but the affected legs will fail in Step 5. Note which + name is missing and continue to Step 2 to check the token files + directly. + +Seats that are not Muse sandboxes do not run this script. If your seat +was provisioned another way, continue at Step 2 and make sure the token +files and the binary are in place by your provisioning route instead. + +## Step 2: Confirm the three token files appeared + +The bootstrap's token phase fetches three Bitwarden Secrets Manager +secrets — by the names `fleet.secrets-broker-token`, +`fleet.queue-broker-token` and `fleet.laptop-agent-token` — into three +files under `~/tools/`. These are client-side files the seat's commands +name when they talk to the brokers; the brokers read the files per +request and never store or log their contents. + +```bash +ls -l ~/tools/secrets-broker-token ~/tools/queue-broker-token ~/tools/laptop-agent-token +``` + +What the output means: three regular files, each with owner-only +permissions (`-rw-------`, mode `0600`). Their contents are secret values +— do not open, print or copy them anywhere. Only their presence, names +and permissions matter here. + +What can go wrong, and the fix: + +- A file is missing. The seat can still enrol (the bridge leg works over + HTTPS with a by-name secret), but the queue, secrets and shell legs + will fail with synthesised transport errors, because those legs read + these shared files. Re-run the bootstrap's token provisioning; if the + missing Bitwarden name itself does not resolve, that is a provisioning + problem to raise with whoever stood the seat up — do not substitute + another secret's value, and do not reuse the older, different name + `secrets-broker.token`, which is a different value. +- Permissions are wider than `0600`. Tighten them: + +```bash +chmod 600 ~/tools/secrets-broker-token ~/tools/queue-broker-token ~/tools/laptop-agent-token +``` + +Do not confuse these client-side `~/tools/*-token` files with the +daemon-side token files under `~/.config/secrets-broker/token` and +`~/.config/queue-broker/token`. The daemon-side files belong to the +brokers themselves (see [Tutorial: run the brokers](run-the-brokers.md)); +a working seat needs its own `~/tools/` set. + +## Step 3: Say hello on the bridge + +Registering on the bridge is a single command. The bridge's agent +registry is exactly the set of agents that have said hello: name, groups +and last-seen time all come from this call. + +```bash +fleet bridge hello --agent --groups muse +``` + +Replace `` with the name you will enrol under in Step 4, +and the groups with the groups your kind carries (Step 4 shows where +groups come from; `--groups` here takes a comma-separated list). The +command prints the bridge's JSON answer. + +What the output means: your mailbox now exists on the bridge at +`https://bridge.security.cab`, and central can address you as +`agent:` or through any group you named. Re-running +`hello` refreshes the registration and its groups; it is safe to repeat. + +What can go wrong, and the fix: + +- Exit `3` — transport or credentials. The fleet token (secret name + `message-bridge.fleet-token`) could not be resolved by name, or the + bridge could not be reached. Check that secret resolution works at all + by following [Tutorial: resolve a secret](resolve-a-secret.md), then + retry. +- Exit `4` — the bridge refused the request; its JSON error is printed on + stderr. A `404` here is reported as a wrong token, an old bridge + without fleet mailboxes, or a wrong URL — check the bridge URL + resolution (`$FLEET_BRIDGE_URL`, then `[bridge] url` in the fleet + config, then the default above). +- Exit `2` — a usage error; fix the flags and retry. Note that `fleet + bridge` has one shared usage text for the whole domain, so read the + `hello` line in it carefully. + +If you omit `--agent`, the name defaults to `$FLEET_AGENT`, then +`[bridge] agent` in the fleet config; groups default the same way via +`$FLEET_AGENT_GROUPS` and `[bridge] groups`. For a first enrolment, pass +both explicitly so the registration is the one you intend. + +## Step 4: Enrol the agent + +Enrolment validates the kind, adds any extra groups, probes the bridge in +register mode (the `hello` from Step 3 is what actually registers the +mailbox), probes the remaining legs, and saves a profile recording the +agent, kind, groups and leg state. + +```bash +fleet agent enroll --kind muse --name --groups muse +``` + +`--kind` and `--name` are required. `--groups a,b` adds to the kind's +built-in groups. If you do not know which kind fits, list the table +first: + +```bash +fleet agent kinds +``` + +That prints one JSON object describing every kind: its name, summary, +bridge groups, seat type (`binary`, `http` or `connector`) and enrolment +note. Sixteen kinds are registered, including `muse`, `opencode`, +`openchamber`, `openclaw`, `claude-code`, `codex`, `gemini`, +`antigravity`, `grok` and the fallback kind `generic` for any other agent +with a shell. Adding a kind is adding a row to that table; no verb +changes. + +What the output means: one JSON object carrying the saved profile, +`registered` (true only when this was not a dry run **and** the bridge +leg answered), the four legs, the intake rungs this seat still has, and +seat-specific next-step lines — for a binary seat, the run loop +(`fleet agent next --agent `, do the task, run its `then` lines, +repeat) and the `fleet shell` line. Exit `0` means a dry run, or that at +least one intake rung is live; exit `3` means no intake rung is live. + +What can go wrong, and the fix: + +- Unknown kind: a usage error (exit `2`) listing all kinds. Pick one from + the list, or use `generic` for anything with a shell. +- `registered` is false even though enrolment exited `0`: the bridge leg + did not answer, so the mailbox was not registered by this call. Re-run + Step 3, fix what it reports, then enrol again. +- You only want to preview: add `--dry-run`. A dry run probes nothing and + registers nothing, and always exits `0`. +- To save the profile somewhere other than the default path, pass + `--profile PATH`. + +## Step 5: Read all four legs with doctor + +Doctor probes four legs **in parallel**, each with a real fleet verb run +as this seat. The four legs are `bridge`, `queue`, `github` and `shell`. +There is no separate secrets leg: secret resolution is folded into the +bridge leg's stated need. + +```bash +fleet agent doctor --agent +``` + +Read the answer leg by leg: + +| Leg | Probe | "Up" means | It needs | +|---|---|---|---| +| `bridge` | `bridge inbox --agent --limit 1` | "the mailbox answers" | HTTPS to the bridge, and the fleet token by name through fleet secrets | +| `queue` | `queue health` | "answers" | The queue broker: its socket on the laptop, or the laptop transport from elsewhere | +| `github` | `gh api rate_limit` via `fleet gh`, falling back to a signed-in plain `gh` | "answers", with `route: "fleet"` or `"plain"` recorded | A `gh` token: the fleet rotation, or a signed-in `gh` | +| `shell` | `laptop-agent health` | "the laptop answers" | A route to the laptop: its broker, the Cloudflare tunnel, the tailnet, or ssh | + +Two details matter when reading the result: + +- Doctor's bridge probe with a known agent is a read that takes nothing + (`inbox --limit 1`). Service health alone proves nothing about whether + this seat holds the fleet token, so only a call made *as* an agent + counts. With no agent name known, the bridge leg is reported **not ok** + even when the service answers — enrol, or pass `--agent`. +- From the legs, doctor derives the **rungs** map: `push` follows the + bridge leg, `queue` follows the queue leg, `priority` follows the + github leg, and `shortlist` is always true because it is a local file. + The answer also reports `builds`: whether `fleet shell` reaches the + laptop from here, or will try a codespace and then run locally. + +Exit `0` means at least one intake rung (bridge, queue or github) is +live; exit `3` means none is. + +What can go wrong, and the fix: + +- `queue` down while `bridge` is up: the classic missing-token-file + shape. Go back to Step 2 — a seat whose bootstrap skipped the token + phase enrols fine and then fails exactly here. +- `github` down: neither the fleet rotation nor a signed-in `gh` + answered. Sign `gh` in on the seat, or check secret resolution by name + as in [Tutorial: resolve a secret](resolve-a-secret.md). +- `shell` down but the other legs up: the seat can still take work; + builds will fall back as the `builds` line describes. Fix the laptop + route when you need laptop builds. + +## Step 6: Take the first piece of work + +`fleet agent next` walks the intake ladder in order — a pushed bridge +command, a queue claim, the local shortlist, then the highest-priority +open issue from GitHub — and returns the first rung that yields work. A +rung that is *down* is recorded and skipped; a rung that is *empty* is +different, and the answer's `tried` log says which was which. + +```bash +fleet agent next --agent +``` + +What the output means: one JSON object, `{agent, rung, task, then, +tried}`. Do the task, then run the commands in `then` — for a queue task +those lines name the lease deadline and the exact `fleet queue +checkpoint` / `fleet queue complete` commands for the claim. The queue +rung claims with a four-hour lease, overriding the queue's 45-minute +default, which would lapse mid-task. The full claim-and-complete flow is +[Tutorial: claim and complete a queue task](claim-and-complete.md). + +What can go wrong, and the fix: + +- Exit `5`: no rung had work. This is a normal, healthy answer for an + idle fleet — the seat is enrolled and reachable, there is simply + nothing to hand out right now. Read `tried` to confirm each rung was + `empty` or `skipped` rather than `down`; a `down` rung points back at + the matching doctor leg in Step 5. +- Exit `3`: a needed leg is down before the ladder could run. Fix it via + Step 5. +- Exit `2`: a usage error in the flags. + +## You are done when + +All of the following hold: + +- `ls -l ~/tools/*-token` shows the three token files, each mode `0600`. +- `fleet bridge hello --agent ` exits `0`. +- `fleet agent enroll --kind --name ` printed a + profile with `registered: true`. +- `fleet agent doctor --agent ` exits `0`, and you have + read all four legs — `bridge`, `queue`, `github`, `shell` — and know + which rungs they give you. +- `fleet agent next --agent ` either handed you a task + with its `then` lines, or exited `5` with every rung `empty` or + `skipped` in `tried` — never `down` for a reason you have not fixed. diff --git a/pkgs/fleet/book/tutorials/resolve-a-secret.md b/pkgs/fleet/book/tutorials/resolve-a-secret.md new file mode 100644 index 0000000000..39def69842 --- /dev/null +++ b/pkgs/fleet/book/tutorials/resolve-a-secret.md @@ -0,0 +1,224 @@ +# Tutorial: resolve a secret + +This tutorial resolves a secret **by name** through `fleet secrets`: +first through the secrets broker, then by observing the Bitwarden +fallback, then listing what the broker holds — and finally reading the +three failure shapes (`502`, `404`, exit `3`) correctly and checking the +broker's health when resolution fails. + +It assumes the `fleet` binary is installed (see +[Installation and bootstrap](../getting-started/installation.md)). + +The standing rule for this whole surface: **secrets are resolved by name +through `fleet secrets` only.** No fleet domain shells out to `bws` +itself or reads a token file on its own, and no command in this tutorial +ever prints a secret value anywhere except the one place `get` is +specified to put it — its own stdout. The examples below use the +placeholder name `example.api-token`; substitute a real secret *name* +(never a value) from your own vault. + +## Step 1: Resolve a name through the broker path + +```bash +fleet secrets get example.api-token +``` + +What the output means: the secret's value, on **stdout and nowhere +else**, and exit `0`. Nothing else is printed — no source label, no age, +no log line. That silence is deliberate: the command is built to sit in +a pipeline, and a broken pipe on stdout (for example piping into `head`) +is a quiet success, not an error. + +The resolution chain behind that one line (`Resolver::default_chain` in +the `fleet-secrets` crate): + +1. **Broker leg first.** Where the secrets broker's own socket answers + (the laptop), the client speaks `GET /secret/` over that Unix + socket directly. Elsewhere (a sandbox seat), it makes a framed + exchange through the session broker to port `4800`. On that leg the + request names the token *file* (config `[secrets] token_file`, + default `~/tools/secrets-broker-token`); the session broker reads the + file per request and sends its contents as the auth header — the + client only ever names the file, and the value never transits the + client's own memory on this leg. +2. **`bws` CLI fallback** (Step 3), only when the broker leg cannot + answer. +3. At library level there is also a 1Password source for seats that keep + secrets there; the `fleet secrets` default chain's headline shape is + broker, then `bws`. + +What the broker does with the request: a cache hit answers immediately +with the cached value. A miss on a *loaded* cache is not final — the +broker reads through to Bitwarden for that one name and serves what it +finds, so a secret minted moments ago is visible immediately instead of +at the next refresh tick. The broker refreshes its whole cache from +Bitwarden at startup and then on a TTL (default 900 seconds), serving +stale values while a refresh runs. + +What can go wrong, and the fix: + +- Exit `2`: a usage error — `get` takes exactly one name, and the name + must not start with `-`. +- Exit `3`: unresolved — no source in the chain could produce the value. + Work through Steps 4 and 5 before concluding the name is wrong. +- The value looks stale after a rotation: the broker serves cached + values with their fetch time, and a rotation lands within one TTL of + the edit. Wait out the TTL, or ask for a broker refresh (Step 5); do + not "fix" it by reading Bitwarden directly in your own scripts — the + by-name chain is the platform rule. + +## Step 2: Know which names exist — `list` + +```bash +fleet secrets list +``` + +What the output means: the names in the **broker's cache**, one per +line, names only, never values. Exit `0`. + +What can go wrong, and the fix — one deliberate asymmetry to memorise: +**`list` has no `bws` fallback.** A broker failure here is loud (an +error on stderr, exit `3`), because a `bws` listing has different +semantics — it enumerates the vault, not the broker's cache — so it is +never silently substituted. If `list` fails but `get` works, you are +seeing exactly that asymmetry, not an inconsistency: `get` fell back, +`list` refused to. Fix the broker (Step 5) rather than working around +the listing. + +## Step 3: Force and observe the `bws` fallback + +There is no `--force-bws` flag. The fallback is a property of the chain: +when the broker leg reports itself *unavailable*, the leg is retried +first — the retry budget is sized to real restart windows (a full switch +restarts broker and tunnel together, and the broker is back in about +16 seconds), with pauses doubling per attempt up to a cap — and only +then does the chain move on to `bws`. One exception: if the +session-broker socket file does not exist at all, the leg does not burn +its retry budget — no broker on this box is not a broker mid-restart. + +To force the fallback in a test, make the broker leg genuinely +unavailable on a seat where that is safe — for example on a sandbox seat, +before `fleet init` has started the local loopback secrets broker (see +[Tutorial: run the brokers](run-the-brokers.md) for what `init` starts), +or while the laptop broker is stopped for maintenance — then run Step 1 +again: + +```bash +fleet secrets get example.api-token +``` + +What the output means: the same contract as the broker path — the value +on stdout, exit `0`, nothing else. The fallback runs `bws secret list` +plus `bws secret get`, the same shape the broker itself uses to fill its +cache, with the `bws` credential resolved the way the broker resolves +its own (the `BWS_ACCESS_TOKEN` environment variable when non-empty, +else the on-disk machine-account token file, handed to the `bws` child +through its environment). + +How you observe which path answered, since the output deliberately does +not say: by the broker's state, not by the value. Check the broker's +health (Step 5) at the same moment — if it was not serving, the value +came from `bws`; if it was serving, it came from the broker. Latency is +a secondary hint only: the per-call `bws` fetch the broker exists to +replace cost 10–40 seconds per invocation, against an immediate cache +hit. Never treat latency alone as proof. + +What can go wrong, and the fix: + +- The fallback also fails, exit `3`: `bws` is missing, its credential + does not resolve, or the name is absent from the vault as well as + unreachable through the broker. Distinguish "absent" from + "unreachable" with Step 4. +- A broker **404 is definitive and is not retried, and does not fall + back**: the broker has a loaded cache and read-through, and the name + is not in Bitwarden. That is Step 4's `404`, not a fallback trigger. + +## Step 4: Read the failure shapes — `502` vs `404` vs exit `3` + +These three answers mean three different things. Confusing them sends +you fixing the wrong layer. + +**`404` — the name does not exist.** From the broker: +`{"error": "no such secret"}`. The broker's cache was loaded, the +read-through to Bitwarden ran, and Bitwarden definitely does not hold +that name. Fix the *name*: check spelling against Step 2's list. Do not +retry, and do not restart anything — nothing is down. + +**`502` — the source behind the broker failed.** From the broker: +`{"error": "bitwarden read-through failed"}`. The name was a cache miss, +the broker tried to read through, and Bitwarden itself failed (the `bws` +call behind the broker errored). This is loud precisely so it is never +mistaken for a `404`: the secret may well exist; the broker could not +check. Fix the broker's Bitwarden leg (Step 5), then retry. + +**`503` — the broker is up but not serving yet.** Before its first +successful refresh, the broker answers `GET /secret/` with +`{"error": "secrets not loaded yet"}`, and its health endpoint answers +503 too. A live process whose `bws` cannot run is *not* serving, and +health says so. This is a wait-or-fix-the-refresh state, not a missing +secret. + +**Exit `3` — the client could not resolve the name at all.** The +`fleet secrets` client-side shape: the broker leg was unavailable (after +its retries), and the fallback also failed or the name was unresolved +through it. Exit `3` is about the *path*, where `404`/`502`/`503` are +answers *from* a broker that was reached. (For completeness: the +client's other exits are `0` for success and `2` for usage.) + +## Step 5: Check the broker's health when it fails + +The broker's health endpoint is unauthenticated and reports the serving +gate directly. On the laptop, where the broker binds its tailnet address +on port `4800`: + +```bash +curl -s http://100.99.113.103:4800/health +``` + +Read the answer field by field: `{ok, serving, secrets, +last_refresh_unix, refreshing, oldest_secret_age_seconds}`. + +- `serving: true` with a recent `last_refresh_unix`: the broker is + healthy; `secrets` is the cached name count and + `oldest_secret_age_seconds` tells you the stalest value it can serve. + A resolution failure against a serving broker is a `404` problem + (Step 4), not a health problem. +- HTTP `503` with `serving: false`: no refresh has succeeded yet. If the + body carries `refresh_error`, that is the diagnosis — the refresh's + `bws` leg is failing (credential, missing `bws`, malformed vault + entry). Fix that leg; the broker keeps answering health honestly + while it cannot serve. +- No answer at all: the broker process is not running, or this seat + cannot reach it. On a sandbox seat, run `fleet init` (it starts the + local loopback broker copy the sandbox uses) or see + [Tutorial: run the brokers](run-the-brokers.md) to run one in the + foreground and watch it start. On the laptop, check the service that + runs `fleet serve secrets-broker`. + +To kick a refresh on a running broker without restarting it, POST to +`/refresh` on the same address. Unlike `/health`, that endpoint requires +the broker's `X-Agent-Token` header — supply the token through your +normal operator tooling for the daemon-side token file +(`~/.config/secrets-broker/token` on the laptop), without printing its +contents or placing them in a command line. It answers +`202 {"ok": true, "refresh": "started"}`; a refresh requested while one +is already in progress is refused with "refresh already in progress". +Then re-read `/health`: a successful refresh sets `last_refresh_unix` +and clears the recorded refresh error. + +Note the sandbox shape: on a sandbox seat (`FLEET_LOCATION=sandbox`) the +local broker's bind is forced to `127.0.0.1:4800` at the bind itself, +whatever its environment says — the same health checks apply against +loopback there. + +## You are done when + +- `fleet secrets get example.api-token` (with a real name substituted) + exits `0` and prints the value on stdout only. +- `fleet secrets list` exits `0` and lists names — proving the broker + leg, since `list` never falls back. +- You can state, for a failure you induced or observed, which of `404` + (name absent), `502` (Bitwarden read-through failed), `503` (broker + not serving yet) or exit `3` (client could not resolve at all) it was, + and which layer you fixed. +- The broker's `/health` reports `serving: true`. diff --git a/pkgs/fleet/book/tutorials/run-the-brokers.md b/pkgs/fleet/book/tutorials/run-the-brokers.md new file mode 100644 index 0000000000..2f9dc99d1b --- /dev/null +++ b/pkgs/fleet/book/tutorials/run-the-brokers.md @@ -0,0 +1,253 @@ +# Tutorial: run the brokers + +This tutorial runs the queue broker in the foreground, proves it healthy +two different ways, adds the secrets broker beside it in the same +process, and stops everything cleanly. It is the manual form of what a +service manager runs in production — useful on a new host, in a test +environment, and whenever you want a broker's startup output in front of +you instead of in a log. + +It assumes the `fleet` binary is installed (see +[Installation and bootstrap](../getting-started/installation.md)). + +Two facts frame everything below: + +- The broker roles take **no arguments**. Through `fleet serve`, any + trailing argument to `queue-broker` or `secrets-broker` is rejected + before the daemon starts (`unexpected argument '' for 'fleet + serve '`, exit `2`) — through the spelled-out form and through + the `queue-broker` / `secrets-broker` argv0 aliases alike. There is no + per-role help for the two brokers either: `fleet serve queue-broker + --help` answers with the generic serve domain help, exit `0`. +- In production these roles are supervised (systemd on the laptop), and + the supervisor restarts them. In this tutorial **you** are the + supervisor: the process runs until you stop it. + +## Step 1: Run the queue broker in the foreground + +```bash +fleet serve queue-broker +``` + +(The argv0 spelling `queue-broker`, invoked as its own program name, +lands in exactly the same place.) + +What happens, in order: + +1. The broker loads its token from its token file — + `QUEUE_BROKER_TOKEN_FILE`, default `~/.config/queue-broker/token`. + Requests carry that token in the `X-Agent-Token` header; an + unreadable token file is a startup error, exit `3`. Token files are + loaded by reading and trimming the file; a missing, unreadable, empty + or whitespace-only file is a hard error naming the file, and the + broker refuses to start. +2. It binds **two** listeners with identical routes and auth: TCP on + `QUEUE_BROKER_BIND` (default `100.99.113.103:4801`, the laptop's + tailnet address; port `4801` is the queue broker's fleet-wide port), + and a Unix socket on `QUEUE_BROKER_SOCKET` (default + `~/.config/queue-broker/broker.sock`). If the socket bind fails, the + broker degrades to TCP-only with a log line rather than dying. +3. The listener comes up **before** the backend: the Turso backend + connects on a startup thread, so the health probe and validation + answer immediately while queue verbs answer exit `3` with a + `turso_pending` reason until the backend is ready. A backend that + cannot come up within its retry budget exits the broker with `3`, so + a supervisor restarts it. + +The process now blocks in the foreground. Leave it running and work from +a second terminal for the next steps. + +What can go wrong, and the fix: + +- Exit `3` at startup: the token file, the bind, or the backend config. + The backend accepts only Turso: `QUEUE_BROKER_BACKEND` unset, empty or + `turso` is fine; anything else is a startup config error, exit `3`. + The backend's credential comes from `QUEUE_BROKER_TURSO_TOKEN_FILE`, + or is resolved through the secrets broker by the secret **name** + `turso.fleet-queue-rw-token`; its URL is `QUEUE_BROKER_TURSO_URL`, + defaulting to the dedicated `fleet-queue` database. +- The broker also needs the secrets broker for some resolutions: it + reads `QUEUE_BROKER_SECRETS_URL` (default `http://100.99.113.103:4800`, + or `unix://` for the secrets broker's socket) and + `QUEUE_BROKER_SECRETS_TOKEN_FILE` (default + `~/.config/secrets-broker/token`). Step 3 runs that broker too. +- Sandbox clients never reach this process directly: they reach it + through the session proxy, which forwards to port `4801`. A broker + that is healthy locally (Step 2) but unreachable from a sandbox has a + proxy problem, not a broker problem. + +## Step 2: Health-check the queue broker — two different checks + +These two commands answer different questions. Do not substitute one for +the other. + +The unauthenticated probe, which any monitor can call: + +```bash +curl -s http://100.99.113.103:4801/healthz +``` + +It answers `{"service":"queue-broker"}`. `/healthz` is the broker's only +unauthenticated route, and it is served without the Turso backend — so +it proves the process is up and listening, **not** that the backend is +ready. (Everything else on the broker is a `POST` with the token header; +a non-POST request gets `405 {"error":"POST only"}`, a wrong or missing +token `401 {"error":"unauthorized"}`, and an oversized body `413` — the +pre-body gate refuses from headers alone, before any body byte is read. +The body cap is 16 MiB.) + +The queue-level health verb, which goes through the broker's real +request path: + +```bash +fleet queue health +``` + +What the output means: a first line `project: (resolved via +)`, then a table of per-queue task counts by status, built from +whatever keys the broker's health rows carry — or `(no queues have +tasks)` when the store is empty. Exit `0` means the broker **and** its +backend answered a real queue request. If `/healthz` answers but this +verb exits `3` in the first moments after startup, the backend is still +connecting (`turso_pending`); give it its retry window before treating +it as a failure. Note that `fleet queue health` is itself on the +fallback-switch path: a dead primary store switches the verb to the +GitHub fallback with exit `6` rather than a plain failure. + +## Step 3: Add the secrets broker + +Stop the Step 1 process (Step 5 shows the clean way) and start both +roles in one process, as a serve list: + +```bash +fleet serve queue-broker secrets-broker +``` + +What the output means: `fleet serve: starting 2 roles in one process: +queue-broker secrets-broker`. A serve list is **role tokens only, two or +more distinct ones, and nothing else**: + +- A duplicate is a hard error: `error: duplicate role 'queue-broker' in + 'fleet serve' list`. +- Any non-role token is a hard error — including `--help`. A serve list + has **no `--help` form at all**. +- **All roles are capability-checked before anything binds.** If any + role cannot run in this invocation, the whole list stubs with exit + `69` and no partial start. +- Each role's blocking loop runs on its own thread. Supervision is + fail-fast: the first role thread to return or panic takes the whole + process down, naming the role on stderr. A role exiting *cleanly* + (code `0`) is converted to process exit `1` — a daemon role returning + at all is abnormal — and a panic is also exit `1`. + +The secrets broker in this list behaves exactly as it does alone +(`fleet serve secrets-broker` in its own terminal works too, as does the +`secrets-broker` argv0 alias): + +- It binds TCP on `SECRETS_BROKER_BIND` (default + `100.99.113.103:4800`) plus its Unix socket + (`SECRETS_BROKER_SOCKET`, default `~/.config/secrets-broker/broker.sock`), + with its token from `SECRETS_BROKER_TOKEN_FILE` (default + `~/.config/secrets-broker/token`; unreadable is a startup exit `3`). + On a sandbox seat (`FLEET_LOCATION=sandbox`) the bind is **forced to + `127.0.0.1:4800`** at the bind itself, whatever the environment says. +- It is a resident Bitwarden Secrets Manager **cache**: at startup a + background thread runs a full refresh (`bws secret list`, then one + `bws secret get` per name, fetched 8-way parallel), then repeats on + the TTL — `SECRETS_BROKER_TTL_S`, default `900` seconds, minimum `30`. + An unparseable TTL falls back to 900 with a warning naming the value; + a parsed TTL below 30 makes startup **refuse to run**, exit `2`, + because one interval costs a full vault refresh and 0 would spin that + loop with no sleep at all. +- Until the first refresh *succeeds*, the broker is up but **not + serving**: its health endpoint answers `503`. That gate is the subject + of Step 4. + +What can go wrong, and the fix: + +- The whole list stubs at exit `69` naming a role: this invocation + cannot run that role (a narrowed build such as `fleet-connect`, or the + domain disabled in the fleet config). Nothing bound — fix the + invocation, not the roles. +- One role's startup failure (for example the secrets broker's token + file) takes the list down by design. Read the stderr line naming the + role, fix that role's cause, and start the list again. + +## Step 4: Health-check the secrets broker + +```bash +curl -s http://100.99.113.103:4800/health +``` + +What the output means: `{ok, serving, secrets, last_refresh_unix, +refreshing, oldest_secret_age_seconds}`. + +- `serving: true`: at least one refresh has succeeded. `secrets` is the + cached name count; `oldest_secret_age_seconds` is the stalest value + the broker can currently serve; reads are cache-first, with a + read-through to Bitwarden on a miss. +- HTTP `503` with `serving: false` (and `refresh_error` when a refresh + has failed): the process is alive and its `bws` leg is not — the + single most useful diagnosis this broker gives. Fix the refresh's + Bitwarden credential or `bws` availability, then watch + `last_refresh_unix` appear. +- The client-side cross-check is `fleet secrets list`, which lists the + broker cache's names and never falls back (see + [Tutorial: resolve a secret](resolve-a-secret.md)). + +## Step 5: Know where state lives, then stop cleanly + +Broker state is mostly **not** in local files, which is what makes +stopping and restarting these processes safe: + +- **Queue state** lives in the dedicated Turso database `fleet-queue` + (org `dezren39`, group `great-star-lord`) — the broker's only backend. + The broker process itself holds connections and in-flight requests, + not the queue. Tasks, leases, lanes, events, the creation outbox and + merge-intent stacks are all rows in that store. +- **Secrets state** is a cache, held in memory: the authoritative copy + is Bitwarden itself, and a restarted broker rebuilds its cache from + `bws` on its first refresh. Nothing is lost by stopping it — only + freshness, until the first refresh lands. +- **Local files** are configuration and credentials only: the token + files (`~/.config/queue-broker/token`, + `~/.config/secrets-broker/token`), the sockets + (`~/.config/queue-broker/broker.sock`, + `~/.config/secrets-broker/broker.sock`), and the fleet config that + resolved them. The placement session store + (`~/.local/state/fleet-place/sessions.json`) belongs to the dispatch + client, not to either broker. + +To stop: send the foreground process `Ctrl-C` (or `SIGTERM` to its +process group under your own supervisor). A clean stop is simply the +process exiting — there is no drain protocol to run, no state to flush, +and no shutdown verb. In a serve list, stopping the process stops every +role in it together; remember the fail-fast rule in reverse: if one role +dies on its own, the process exit you observe (the role's own code, or +`1` for a clean/panic exit) names that role on stderr, and the correct +response is to fix the named role and restart the list — exactly what +systemd does with the production units. + +What can go wrong, and the fix: + +- A restarted queue broker answers `/healthz` but queue verbs exit `3`: + the backend is still connecting. This is the designed startup + ordering, not a wedge — unless the backend's retry budget expires, at + which point the broker exits `3` and your supervisor (or you) restarts + it. +- A restarted secrets broker serves `503` longer than a refresh should + take: read `refresh_error` in the health body (Step 4) — the process + is honestly reporting a dead refresh leg, not hiding it. + +## You are done when + +- `curl -s http://100.99.113.103:4801/healthz` answers + `{"service":"queue-broker"}` **and** `fleet queue health` exits `0` + with a counts table — both checks, not just the probe. +- `fleet serve queue-broker secrets-broker` starts both roles in one + process, and the secrets broker's `/health` reports `serving: true` + with a set `last_refresh_unix`. +- You can name where each piece of state lives — queue rows in the + Turso `fleet-queue` database, secrets as an in-memory cache over + Bitwarden, only tokens/sockets/config as local files — and you have + stopped the foreground process cleanly with no state lost. diff --git a/pkgs/fleet/doc/agents/documentation.md b/pkgs/fleet/doc/agents/documentation.md new file mode 100644 index 0000000000..06328aede6 --- /dev/null +++ b/pkgs/fleet/doc/agents/documentation.md @@ -0,0 +1,44 @@ +# Documentation: the fleet book is part of the change + +`fleet` has a book: `pkgs/fleet/book/` (mdBook sources, `pkgs/fleet/book.toml`), +rendered by the flake output `.#fleet-docs` (`pkgs/fleet/docs.nix`) and +published inside the repository's GitHub Pages site at `/code/fleet/`. +The book is the complete, self-contained reference for the binary: every +domain, subcommand, flag, default, and operational procedure. + +## The rule (DOC-01, extended) + +The README's DOC-01 contract already requires the domain registry and +`pkgs/fleet/docs/verbs.md` to be updated in the same change as the code. +The book is part of that same contract: + +- Any change to a command, subcommand, flag, default, exit code, + capability, surface-registry entry, broker behaviour, or operational + procedure **updates the matching book chapter in the same PR**. +- A new subcommand or flag is not done until its reference section + exists in the book, following the worked traces in the book's + development guide ("Add a subcommand", "Add a flag"). +- Designed-but-unshipped spellings are never presented in the book as + shipped behaviour (the DOC-01 discipline); where help text and source + disagree, the book documents the source and calls out the discrepancy + until the help is fixed. + +## Gates + +- `book.toml` sets `create-missing = false`: a `SUMMARY.md` entry with + no file on disk fails the build instead of inventing a stub. +- `nix build .#fleet-docs` builds the whole book offline; the + `fleet-docs` workflow runs it on every push to main. +- The usage↔parser parity test still guards the help text; the book is + checked by review against the same sources. + +## Building and previewing + +```sh +cd pkgs/fleet +mdbook build # renders into pkgs/fleet/rendered/ +nix build .#fleet-docs # the exact CI build, from the repo root +``` + +Deployment is combined with the mcpx book's (one repository, one Pages +site, whole-site deploys): see the book's "Deploying this book" chapter. diff --git a/pkgs/fleet/docs.nix b/pkgs/fleet/docs.nix new file mode 100644 index 0000000000..ad23daf5dd --- /dev/null +++ b/pkgs/fleet/docs.nix @@ -0,0 +1,69 @@ +# The fleet book (#13165): render pkgs/fleet/book with mdBook into +# static HTML, sandboxed, with the flake-pinned mdbook from nixpkgs +# and no network access. Exposed as the .#fleet-docs flake output, so +# CI builds it through the ordinary flake-check path like every other +# output. Mirrors pkgs/mcpx/docs.nix (#1939, Approach C) minus the +# mcpx-specific Go preprocessors (docs-history / docs-twins), which +# the fleet book does not use. +# +# The base URL is a derivation argument (the #1941 pattern): `siteUrl` +# is baked into the rendered book as mdBook's output.html.site-url, so +# a local build, the CI build, and a deployed build differ only in +# that one value. The flake output uses the default "/"; the GitHub +# Pages deploy overrides it with "/code/fleet/" (the fleet book's +# path inside the repository's project site — mdBook needs the real +# hosting path or its generated 404 page points assets at the domain +# root), e.g. `fleetDocs.override { siteUrl = "/code/fleet/"; }`. +{ + lib, + runCommand, + mdbook, + siteUrl ? "/", +}: +let + # Only the book inputs enter the store: book.toml plus the book + # tree. The Rust sources next to them are not book content and stay + # out. + src = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./book.toml + ./book + ]; + }; +in +runCommand "fleet-docs" + { + nativeBuildInputs = [ + mdbook + ]; + meta = { + description = "fleet documentation book (mdBook rendering of pkgs/fleet/book)"; + homepage = "https://github.com/developing-today/code"; + license = with lib.licenses; [ + mit + asl20 + ]; + }; + } + '' + cp -r ${src} work + chmod -R u+w work + cd work + # Links that escape the book source tree would 404 in the rendered + # book: from book/, ../README.md means pkgs/fleet/README.md, which + # is not part of the artifact. Rewrite those links — in the copied + # pages only, the sources keep their relative links for GitHub — + # to the file's repository URL, at the depth where the link + # escapes: ../ from a top-level page, ../../ from a page one + # directory down. Links that stay inside book/ are left for + # mdBook to resolve. (Same treatment as pkgs/mcpx/docs.nix.) + repoURL="https://github.com/developing-today/code/blob/main/pkgs/fleet/" + find book -maxdepth 1 -name '*.md' -exec sed -i \ + "s|](\.\./|](''${repoURL}|g" {} + + find book -mindepth 2 -maxdepth 2 -name '*.md' -exec sed -i \ + "s|](\.\./\.\./|](''${repoURL}|g" {} + + # Bake the base URL into the book (see the siteUrl argument above). + export MDBOOK_OUTPUT__HTML__SITE_URL="${siteUrl}" + mdbook build --dest-dir $out + ''