diff --git a/.agents/skills/decide-and-proceed/SKILL.md b/.agents/skills/decide-and-proceed/SKILL.md index af42955fcd..8ea73d7bca 100644 --- a/.agents/skills/decide-and-proceed/SKILL.md +++ b/.agents/skills/decide-and-proceed/SKILL.md @@ -32,6 +32,14 @@ fleet queue block --reason-class escalated-to-user \ - If you cannot write the action as one sentence a person could do in five minutes, it is not a hands item. It is a decision, and rule 1 applies. - The queue refuses a person-wait block or park that has no `--hands` and `--action`. +On the GitHub issue, a hands item carries `user/escalated` and one marker line in its body, so every tool can tell it from a parked choice: + +```markdown + +``` + +`fleet agent next` never hands such an issue to an agent, and the dashboard lists it under "Needs a person's hands". An issue with `user/escalated` and no marker is shown as fleet work and is handed out to be decided. + ## Recording a decision One comment on the issue the decision belongs to: diff --git a/.agents/skills/next-work/SKILL.md b/.agents/skills/next-work/SKILL.md index 14bc35b48f..b1ff3c820f 100644 --- a/.agents/skills/next-work/SKILL.md +++ b/.agents/skills/next-work/SKILL.md @@ -11,7 +11,9 @@ A result is one of three things: a merged change that makes an unchecked accepta ## Choosing work -Read the plan's **Now** table first. Then take the first of these that exists: +The short way is `fleet agent next`: it returns one task from the highest intake rung that has one (a command pushed to you, the queue, the host's shortlist, GitHub priority) and the commands to run when the task is done. When it hands you an issue, do one slice of it. When it tells you the shortlist is low, filling the list is your task for that run. + +To choose by hand, read the plan's **Now** table first. Then take the first of these that exists: 1. **Breakage on main in an active track's code.** A red `id` suite outranks every feature slice, because every later verdict reads that signal. 2. **The next slice of an active track.** Follow [`feature-slice`](../feature-slice/SKILL.md). The track's row names its exit test and its open issues. diff --git a/doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md b/doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md new file mode 100644 index 0000000000..b7b7ce6403 --- /dev/null +++ b/doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md @@ -0,0 +1,273 @@ +# Fleet agent front door: one way in for every agent + +- **Date:** 2026-11-21 +- **Kind:** design, implemented in the same change +- **Code:** `pkgs/fleet/crates/fleet-agent` (`fleet agent`, `fleet shell`), + `pkgs/fleet/crates/fleet-queue/src/person_wait.rs`, `placement.rs`, + `pkgs/fleet/crates/fleet-secrets`, `pkgs/fleet/fleet-surfaces.json` +- **Rules it rests on:** [FDR-0013](../decisions/FDR-0013-no-owner-decision-gates.md) +- **Plan:** [`planning/plans/2026-11-21_results-first.md`](../../planning/plans/2026-11-21_results-first.md) + +## What was asked + +The owner asked on 2026-11-21 for one strategy that lets the fleet send and +receive messages as a whole, and that covers five things: + +1. Any persistent agent can be onboarded: Muse agents, Grok bots, Dot and + Duet, OpenClaw, Antigravity, and direct use from ChatGPT and Claude. +2. Those agents, and the OpenCode and OpenChamber pipeline, can be handed + tasks. +3. An agent talks to the `fleet` binary and nothing else. The binary handles + secrets and reaches Cloudflare. Tailscale is needed only for particular + parts. +4. Builds go to the fleet's GitHub Actions copies, a codespace or the laptop + as fits, and the binary has a subcommand that connects to a shell there, so + nothing builds inside a limited sandbox. +5. Tasks reach agents by a ladder of fallbacks: a central push, then queues + picked up on a schedule, then a local shortlist that a run refills when it + sees the list is low, then whatever has the highest priority. + +He also asked that the system not treat work as waiting on him because some +other session said so. That part is FDR-0013; this design is where it is +enforced. + +## What already existed + +Most of the transport was already built, as separate verbs that each agent had +to know and combine in the right order. + +| Need | Existing piece | +| ----------------------- | ---------------------------------------------------------------------------- | +| Messages and commands | `fleet bridge`: mailboxes on the Message Bridge worker, with wake hooks | +| Queue of small tasks | `fleet queue`: claim, checkpoint, complete | +| Run a command elsewhere | `fleet laptop-agent exec`, over broker, Cloudflare tunnel, tailnet, then ssh | +| Interactive shell | `fleet proxy ssh` | +| Build placement | `fleet queue dispatch` over the surface registry | +| Secrets by name | `fleet secrets`: the secrets broker, then `bws` | + +What was missing was the order of use, a place to say what kind of agent is +asking, the two lower rungs of the ladder, and a guard against owner waits. + +## What this adds + +### 1. `fleet agent`: enrol, check, take the next task + +```bash +fleet agent kinds # the kinds and how each enrols +fleet agent enroll --kind muse --name muse-7 # register, probe, save a profile +fleet agent doctor # what this seat reaches now +fleet agent next # one task, from the highest rung that has one +fleet agent shortlist status|add|take|fill|clear +``` + +An agent's whole loop is three lines: + +```bash +fleet agent next # exit 5: no work on any rung this run +# do the task in the answer, then run the answer's `then` lines +# repeat while the run has budget +``` + +Every answer is JSON on stdout. Exit codes are `0` done, `2` usage, `3` a leg +this verb needs is down, `5` no work. + +### 2. Kinds and seats + +A kind says what the agent is. A seat says how it reaches the fleet. + +| Seat | Kinds | How it enrols | +| ----------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `binary` | `muse`, `opencode`, `openchamber`, `openclaw`, `claude-code`, `codex`, `gemini`, `antigravity`, `grok`, `laptop`, `generic` | `fleet agent enroll --kind K --name N` from its own shell | +| `http` | `dot`, `duet`, `http` | Enrolled from any seat that has the binary; the agent then uses the mailbox's HTTPS calls | +| `connector` | `claude`, `chatgpt` | Nothing to enrol: the address is `claude` or `chatgpt`, reached through the Message Bridge connector | + +Enrolment registers the mailbox with the kind's groups, so `group:muse` or +`group:opencode` reaches every agent of that kind. `openchamber` joins +`opencode` too, so one send reaches the whole pipeline. A Grok bot with no +shell enrols as kind `http` under the same name and groups. + +Enrolment then probes four legs at once and reports which ladder rungs work +from this seat. A leg that is down says what it needs. Enrolment fails only +when no intake leg answers at all. + +### 3. What each part needs from the network + +| Part | Needs | Tailscale | +| ----------------------------- | ------------------------------------------------------------------------------ | ------------------------------ | +| Messages, and the push rung | HTTPS to the Message Bridge (Cloudflare), and the fleet token by name | No | +| Priority rung, shortlist fill | HTTPS to GitHub, and a `gh` token (the fleet's rotation, or a signed-in `gh`) | No | +| Shortlist | A local file | No | +| Queue rung | The queue broker: its socket on the laptop, else the laptop transport | Only as one fallback transport | +| `fleet shell`, builds | The laptop-agent ladder, a codespace through `gh`, or a GitHub Actions surface | Only as one fallback transport | +| Secrets | The secrets broker, then `bws`, then `op` where a vault is named | No | + +The laptop transport is the existing ladder: the broker, then the laptop's +Cloudflare tunnel, then the tailnet, then ssh. So a seat with HTTPS and nothing +else has messaging and three of the four rungs. Tailscale matters only for +reaching the laptop when its Cloudflare tunnel is down. + +### 4. The intake ladder + +`fleet agent next` walks four rungs and stops at the first that has a task. + +1. **Push.** A command sent to this agent, its group or everyone: + `fleet bridge inbox --agent N --commands --take --limit 1`. Wake hooks make + this immediate for agents that can be woken. +2. **Queue.** `fleet queue claim`, the shared queue that scheduled lane runs + already drain. +3. **Shortlist.** A ranked local file on the host, shared by every agent + there. If the list is below its low-water mark (3) and nobody has claimed + the refill in the last 30 minutes, this run's task **is** to refill it: the + answer is a `refill-shortlist` task with the ranked candidates, and the + run fills the list to its target (8) and then takes from it. +4. **Priority.** The highest-ranked open issue on GitHub that nobody is on. + +Rank order is `expedite`, `priority/critical`, `now`, `priority/high`, `next`, +`priority/normal`, then unranked, oldest first within a rank. An issue is left +out when it carries a hold label (`held`, `user/owned`, `do-not-auto-edit`) or +a label showing someone is on it. `user/escalated` and `status/blocked` are +**not** holds: such an issue is handed out with an instruction to decide what +was asked, record it, clear the labels and continue. + +A task from the shortlist or priority rung is a large-issue task, so it tells +the agent to land one slice (`.agents/skills/feature-slice`). This is how +large `id` work reaches agents while the queue still has only small-task +kinds. + +Every answer lists each rung tried and why it was passed over, so a down leg +is visible and is never mistaken for an empty one. Each call to another leg +has a time limit (45 seconds, `FLEET_AGENT_STEP_TIMEOUT`); a leg that does not +answer in time is down, and the ladder moves on. A queue claim gets four times +the limit, because cutting a claim short would orphan it. + +A pushed task is the command's body. The ladder does not pass along who sent +it, and nothing becomes the owner's instruction because a message says it is. + +### 5. `fleet shell`: run it where builds belong + +```bash +fleet shell -- cargo test -p id-core # a command, on the best target +fleet shell --build -- nix build .#id # takes a build slot, one-hour limit +fleet shell # an interactive shell +fleet shell --target codespace --codespace NAME -- make test +fleet shell targets # what this seat can reach +fleet shell --print -- # show the plan, run nothing +``` + +With `--target auto` the order is: here, if this is the laptop; the laptop, if +it answers; a running codespace; here as the last resort. A named target is +never swapped for another. On the laptop a command runs through +`fleet laptop-agent exec`, and `--build` runs it under the build lock. + +Jobs that should not hold a shell go to GitHub Actions through +`fleet queue dispatch`, which picks a surface from the registry. + +### 6. Three more build surfaces, by dispatching as the user + +The registry listed three surfaces as waiting for a GitHub App grant since +2026-11-04. The reason given was a rule that dispatch must use the App, which +no decision record backs. The fleet's GitHub user is an admin of all three +copies and can start a workflow there with the token it already has. + +A surface entry can now say `"dispatch_as": "user"`. Eligibility, dispatch, +status and load reads for that surface use the user's token: from the +environment, then the seat's `gh` login, then the `gh` hosts file by name +through fleet secrets. A surface without the field behaves as before, and +never falls back to the user's token. + +Each was proven with a real run on 2026-11-21 before the registry changed: + +| Surface | Host | Run | Result | +| ---------------------- | ------------------------------ | ----------- | --------------------------------------------------- | +| `fleet-org` | `developing-today/fleet` | 44900088840 | Success on `ubuntu-24.04` | +| `fleet-org-blacksmith` | `developing-today/fleet` | 44900255411 | Success on a `blacksmith-4vcpu-ubuntu-2404` runner | +| `fleet-forks` | `developing-today-forks/fleet` | 44900259404 | Success on `ubuntu-24.04`, after a sync to upstream | + +Five surfaces are now active. Concurrent GitHub-hosted jobs go from 60 to 80, +and Blacksmith's free minutes become reachable as a spill tier. Its paid cap +stays 0. + +### 7. No waits on a person + +`fleet queue park` and `fleet queue block` now refuse a wait on a person +unless it is a hands item. The check runs before the broker is contacted and +exits `2` with the rule and what to do instead. + +- A wait is a person wait when its reason class is one of the owner classes, + its ready condition is `person_answer`, or its text says the owner must + decide, approve, confirm or answer. +- A hands item names what only a person's hands can do: + `--hands physical|interactive-login|payment|signature`, with `--action`, one + sentence of at most 200 characters. +- A hands item blocks that step only. The agent takes the next task. + +On GitHub a hands item carries `user/escalated` and one marker line in its +body: ``. Three places +read it: + +- `fleet agent next` never hands such an issue to an agent, and it skips + `kind/tracker` issues, which index work without being work. +- The dashboard's census (`pm-stack/aggregator/src/needs-drew.ts`) splits the + items carrying `user/review` or `user/escalated` into three groups: needs a + person's hands, review requested, and parked on the owner by an agent. Only + the first two count as needing the owner. The third is listed as fleet work + whose count should fall to zero. +- The digest's "Needs Drew" section lists the first two groups only. + +### 8. Secrets: `op` beside `bws` + +The secrets chain gains an optional third source, the 1Password CLI. It joins +the chain only where `FLEET_OP_VAULT` names a vault, and reads +`op:////`, with `credential` as the default field +(`FLEET_OP_FIELD`). Seats without it keep the earlier chain exactly. Values +are never printed, logged or stored, as before. + +## Decisions + +Each is made, with how to undo it. + +| # | Decision | Why | Undo | +| --- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------- | +| A1 | Compose the existing verbs through the same binary. No new transport or service. | The transports work. What was missing was order and a single entry point. | Delete the crate; nothing else depends on it. | +| A2 | Surfaces may dispatch as the user. Three surfaces are active. | The user can already start those workflows; waiting for an App grant bought nothing for 17 days. | Remove `dispatch_as` and set the status back. | +| A3 | Large work arrives through rungs 1, 3 and 4. No new queue kind yet. | A queue kind touches the validator, dedupe, the store, dispatch, the schema and the PM stack. | None needed; a queue kind can be added later. | +| A4 | Connectors are addresses, not enrolled agents. | Claude and ChatGPT already have the bridge connector; a mailbox would be a second, unread inbox. | Add a `binary` kind row. | +| A5 | A slow leg is a down leg, after 45 seconds. | Measured: without a limit, one enrolment in a seat with no broker took more than two minutes. | Raise `FLEET_AGENT_STEP_TIMEOUT`. | +| A6 | `op` is off unless a vault is named, and is last in the chain. | Nothing changes for seats that use the broker or `bws`. | Unset `FLEET_OP_VAULT`. | +| A7 | `fleet-forks` targets public repos only. | That copy has no checkout secret, and only a public target was proven. | Add the secret, then add the target. | + +## How it was checked + +- The whole fleet workspace passes with the locked dependencies: 943 tests. The aggregator passes its 3,037 tests and its typecheck. +- `fleet-agent`: 45 tests, three of them property tests. The shortlist order + is checked against a sort, the file against a round trip, and shell quoting + against the real `/bin/sh`. Time limits are checked against real child + processes. The quoting property found a real fault before merge: a bare `~` + was sent unquoted, so the far shell replaced it with a home directory. +- The wait guard: 8 unit tests, and 5 tests that run the real `repo-queue` + binary against a fake broker that counts connections, so "refused before + the broker is asked" is observed. +- Placement: 7 new tests for `dispatch_as`. Secrets: 4 new tests for `op`. +- 34 hand-made faults were each caught by a test: 27 across the ladder, the + shortlist, the shell plan, the guard and its wiring, placement and the + secrets source, and 7 in the dashboard census. +- The built binary was run end to end: the park and block refusals exit `2`, + `fleet shell --print` plans the laptop build command, the serve variant + answers `fleet agent` and `fleet shell` with exit `69`, and + `fleet agent next` returned real ranked candidates from GitHub. +- The three surfaces were dispatched for real, as above. + +## Known gaps, in the order they should be closed + +1. The `fleet-org` copy's `fleet-run.yml` has diverged from upstream, so its + daily sync has failed since 2026-11-05. The copies need to converge: + upstream takes the cache options and the anonymous checkout, and the org + copy takes `dispatch_id` and `setup_runner`. +2. `codespace-overflow` needs the `codespace` scope on the `gh` login. That is + a hands item (an interactive login); nothing else waits on it. +3. A dry-run enrolment checks that the bridge answers, not that this seat + holds the fleet token, so it can report the push rung as working where a + real enrolment would not. +4. The PM stack does not yet show which rung fed each agent's task. It does + now separate hands items from choices an agent parked on the owner. +5. A `feature_slice` queue kind, so slices can also be scheduled centrally. diff --git a/doc/agents/fleet-command-channel.md b/doc/agents/fleet-command-channel.md index 7bf3f05f62..1e8c37f4cd 100644 --- a/doc/agents/fleet-command-channel.md +++ b/doc/agents/fleet-command-channel.md @@ -7,6 +7,14 @@ their mailbox, act on commands, and answer. Bridge side: `pkgs/message-bridge/worker/README.md` ("Fleet mailboxes"); client: `fleet bridge` (`pkgs/fleet/crates/fleet-bridge`). +## The short way + +`fleet agent next` does the mailbox check below and then tries the queue, +the host's shortlist and GitHub priority, in that order, and returns one +task. An agent that uses it does not need to run the steps in the next +section by hand. Enrolment and the full ladder: +[onboarding an agent](onboarding-an-agent.md). + ## Every lane run (Muse lanes and any other fleet agent) At the start of each run, before claiming queue work: diff --git a/doc/agents/onboarding-an-agent.md b/doc/agents/onboarding-an-agent.md new file mode 100644 index 0000000000..f184abf92b --- /dev/null +++ b/doc/agents/onboarding-an-agent.md @@ -0,0 +1,91 @@ +# Onboarding an agent to the fleet + +Any agent joins the fleet the same way, whatever it is: a Muse lane, an +OpenCode or OpenChamber session, an OpenClaw agent, a Grok bot, Dot, Duet, +Codex, Gemini, Antigravity, or a Claude Code session. Design: +[`doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/`](../2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md). + +## An agent with a shell + +```bash +fleet agent kinds # pick your kind +fleet agent enroll --kind --name # once per seat +fleet agent next # each time you want work +``` + +- `` is the agent's own stable name, the one the queue uses as worker + and lane: lowercase letters, digits, `.`, `_`, `-`. +- Enrolment registers your mailbox, tells you which intake rungs work from + your seat, and saves a profile so later verbs know who is asking. +- `fleet agent next` returns one task and the commands to run when it is + done. Exit `5` means no rung had work this run. +- `fleet agent doctor` repeats the reachability check at any time. + +## An agent that can only make HTTPS requests + +Enrol it from any seat that has the binary, then give the agent its name: + +```bash +fleet agent enroll --kind http --name --groups +``` + +The agent reads and answers its mailbox with the bridge's HTTPS calls +(`pkgs/message-bridge/worker/README.md`, "Fleet mailboxes"). `dot` and `duet` +are kinds of this seat. + +## Claude and ChatGPT + +Nothing to enrol. Their addresses are `claude` and `chatgpt`, reached through +the Message Bridge connector. Send to them like any other address. + +## Sending work to an agent + +```bash +fleet bridge send --to agent: --command "" # one agent +fleet bridge send --to group:muse --command "" # every agent of a kind +fleet bridge send --to group:opencode --command "" # OpenCode and OpenChamber +fleet bridge send --to claude "" # a connector +``` + +A command is a task and gets an answer. A plain message is information. + +## Where work comes from + +`fleet agent next` tries four places in order and takes the first task it +finds: a command pushed to you, the shared queue, the host's shortlist, then +the highest-priority open issue. If the shortlist is low and nobody is +refilling it, your task for that run is to refill it. You do not choose the +rung; the answer says which one fed you and why the others did not. + +## Builds + +Do not build inside a limited sandbox. Run the command where builds belong: + +```bash +fleet shell -- # the laptop, a codespace, or here +fleet shell --build -- # a long build: takes a build slot +fleet shell # an interactive shell +``` + +## What you need + +HTTPS is enough for messages and for three of the four rungs. The queue rung +and `fleet shell` need a route to the laptop, which the binary finds by +itself: the broker, the Cloudflare tunnel, the tailnet, then ssh. Secrets are +resolved by name through `fleet secrets`; never read a token file or call a +vault tool yourself. + +## Waiting on a person + +Do not. Decide, record the decision on the issue, and continue +(`.agents/skills/decide-and-proceed`, +[FDR-0013](../decisions/FDR-0013-no-owner-decision-gates.md)). The queue +refuses a park or block that waits on a person unless it is a hands item: + +```bash +fleet queue block --worker --lane --reason-class escalated-to-user \ + --hands interactive-login --action "" \ + --blocker "" +``` + +A hands item blocks that step only. Take the next task. diff --git a/doc/placement-intake/placement.md b/doc/placement-intake/placement.md index 02ea60a95d..f2bc7220ef 100644 --- a/doc/placement-intake/placement.md +++ b/doc/placement-intake/placement.md @@ -312,3 +312,39 @@ the org-run surface is `active` in the registry and the Blacksmith variant exists there too — a `fleet-org-blacksmith`-style registry entry on the code host is all that remains if Blacksmith legs are ever wanted on org-run itself. + +--- + +## 2026-11-21T11-50-00Z Update: surfaces may dispatch as the user + +The statement above that there is no user-token dispatch path no longer +holds. A surface entry may say `"dispatch_as": "user"`; that surface then +uses the fleet's own GitHub user token for eligibility, dispatch, status and +load reads. A surface without the field is App-only, as before. Reasons and +the decision record: +[`doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/`](../2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md) +and [FDR-0013](../decisions/FDR-0013-no-owner-decision-gates.md). + +Status on 2026-11-21, each proven by a real run: + +| Surface | Status | Dispatches as | Proof | +| ---------------------- | ------ | ------------- | ----------------------------------------------------------- | +| `fleet-personal` | active | the App | unchanged | +| `org-run` | active | the App | unchanged | +| `fleet-org` | active | the user | run 44900088840, success | +| `fleet-org-blacksmith` | active | the user | run 44900255411, success on a Blacksmith runner | +| `fleet-forks` | active | the user | run 44900259404, success after a sync to upstream `72049ac` | +| `codespace-overflow` | waits | | the `gh` login lacks the `codespace` scope | + +Two facts in the earlier text are out of date. The org copy has its repo +secrets. The forks copy needs no checkout secret for public targets, which +are the only targets its entry lists. + +Adding a location is now: copy the repo, register the entry, and either +install the App on the copy or set `dispatch_as` to `user` where the fleet's +GitHub user can start workflows there. + +The org copy's `fleet-run.yml` still differs from upstream in both +directions, so its daily sync fails on a merge conflict. Until the copies +converge, that entry declares no `dispatch_id` input and its runs are matched +by the snapshot fallback. diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 6a1153a437..ffb4fbc239 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -586,6 +586,7 @@ dependencies = [ name = "fleet" version = "0.1.0" dependencies = [ + "fleet-agent", "fleet-bridge", "fleet-config", "fleet-dispatch", @@ -603,6 +604,15 @@ dependencies = [ "ureq", ] +[[package]] +name = "fleet-agent" +version = "0.1.0" +dependencies = [ + "fleet-config", + "proptest", + "serde_json", +] + [[package]] name = "fleet-bridge" version = "0.1.0" diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml index 985b34e125..dd9fb4665c 100644 --- a/pkgs/fleet/Cargo.toml +++ b/pkgs/fleet/Cargo.toml @@ -27,6 +27,7 @@ members = [ "crates/fleet-laptop-agent", "crates/fleet-search", "crates/fleet-bridge", + "crates/fleet-agent", "crates/fleet", ] resolver = "2" @@ -49,6 +50,7 @@ fleet-proxy = { path = "crates/fleet-proxy" } fleet-laptop-agent = { path = "crates/fleet-laptop-agent" } fleet-search = { path = "crates/fleet-search", default-features = false } fleet-bridge = { path = "crates/fleet-bridge" } +fleet-agent = { path = "crates/fleet-agent" } serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.11" diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index ecdabebfd1..f1312853a4 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -62,6 +62,17 @@ crates/fleet-bridge/ the bridge domain: fleet mailboxes on the (fleet token, derived from the owner token when its own secret is missing). Runbook: doc/agents/fleet-command-channel.md. +crates/fleet-agent/ the agent domain and `fleet shell`: one + front door over the other verbs. `agent + enroll` registers any kind of agent and + reports which intake rungs its seat + reaches; `agent next` returns one task + from the highest rung that has one (a + pushed command, the queue, the host's + shortlist, GitHub priority); `shell` runs + a command or opens a shell on the laptop, + a codespace or here. Runbook: + doc/agents/onboarding-an-agent.md. crates/fleet-queue/ the queue domain (step 2): the repo-queue client, the queue-broker and secrets-broker roles, and packet validation — the broker @@ -251,9 +262,10 @@ behind them — lives in one place, and every build compiles it, so no build can know a domain another build forgot. The registered domains are `fleet queue`, `fleet serve`, `fleet proxy`, `fleet dispatch`, `fleet dispatch-test`, -`fleet secrets`, `fleet gh`, `fleet bridge`, `fleet search` and -`fleet laptop-agent`, plus the built-ins `fleet init`, -`fleet version`, `fleet capabilities` and `fleet help`. +`fleet secrets`, `fleet gh`, `fleet bridge`, `fleet agent`, +`fleet shell`, `fleet search` and `fleet laptop-agent`, plus the +built-ins `fleet init`, `fleet version`, `fleet capabilities` and +`fleet help`. One staleness, stated honestly: the registry's per-domain `subcommands` arrays are descriptive, and for the `queue` domain they diff --git a/pkgs/fleet/crates/fleet-agent/Cargo.toml b/pkgs/fleet/crates/fleet-agent/Cargo.toml new file mode 100644 index 0000000000..05e58de461 --- /dev/null +++ b/pkgs/fleet/crates/fleet-agent/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fleet-agent" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "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." + +[dependencies] +fleet-config = { workspace = true } +# preserve_order: every verb prints JSON, and the key order is the shape. +serde_json = { version = "1", features = ["preserve_order"] } + +[dev-dependencies] +# Property tests (AGENTS.md testing doctrine), the same proptest version +# the other fleet crates use. +proptest = "1.12" diff --git a/pkgs/fleet/crates/fleet-agent/proptest-regressions/tests.txt b/pkgs/fleet/crates/fleet-agent/proptest-regressions/tests.txt new file mode 100644 index 0000000000..50d0c090de --- /dev/null +++ b/pkgs/fleet/crates/fleet-agent/proptest-regressions/tests.txt @@ -0,0 +1,8 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 8ab280ccda55b49a7ae04ee5ca75326551661a22320b5eacd8ec7087c7595a2d # shrinks to specs = {1: (0, 0), 2: (0, 0)} +cc 267937dcd89ad2723dc8f8a9a4ccd6952378fdf435c0fcf6184182e8b298f9a6 # shrinks to word = "~" diff --git a/pkgs/fleet/crates/fleet-agent/src/enroll.rs b/pkgs/fleet/crates/fleet-agent/src/enroll.rs new file mode 100644 index 0000000000..5855effd13 --- /dev/null +++ b/pkgs/fleet/crates/fleet-agent/src/enroll.rs @@ -0,0 +1,398 @@ +//! `fleet agent enroll` and `fleet agent doctor`. +//! +//! Enrolment is three things, done in one command: register the agent's +//! mailbox on the bridge under its name and groups, find out which legs +//! answer from this seat, and save a small profile so later verbs know +//! who is asking without being told. +//! +//! It asks for nothing a seat does not have. The bridge is HTTPS on +//! Cloudflare, so messaging and pushed tasks work from anywhere the +//! fleet token resolves by name. The queue, the laptop shell and GitHub +//! are probed and reported; a leg that does not answer narrows the +//! intake ladder, it does not fail the enrolment. An agent is enrolled +//! when at least one rung can bring it work. + +use std::fs; +use std::path::PathBuf; + +use serde_json::{Value, json}; + +use crate::kinds::{self, Seat}; +use crate::{AgentError, EXIT_DOWN, EXIT_OK, Out, R, World, argv, check_name, parse, usage}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Profile { + pub name: String, + pub kind: String, + pub groups: Vec, + pub enrolled_at: u64, + /// The route that reached GitHub at enrolment (`fleet` or + /// `plain`), so later runs try the working one first. + pub gh: Option, +} + +/// `--profile`, else `$FLEET_AGENT_PROFILE`, else the XDG config path. +pub fn profile_path(world: &dyn World, flag: Option) -> Option { + if let Some(p) = flag.or_else(|| world.env("FLEET_AGENT_PROFILE")) { + return Some(PathBuf::from(p)); + } + if let Some(config) = world.env("XDG_CONFIG_HOME") { + return Some(PathBuf::from(config).join("fleet").join("agent.json")); + } + world.home().map(|h| h.join(".config/fleet/agent.json")) +} + +/// The saved profile, when there is one and it parses. +pub fn read_profile(world: &dyn World, flag: Option) -> Option { + let path = profile_path(world, flag)?; + let v: Value = serde_json::from_str(&fs::read_to_string(path).ok()?).ok()?; + Some(Profile { + name: v.get("name")?.as_str()?.to_string(), + kind: v.get("kind")?.as_str()?.to_string(), + groups: v + .get("groups") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|g| g.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(), + enrolled_at: v.get("enrolled_at").and_then(Value::as_u64).unwrap_or(0), + gh: v.get("gh").and_then(Value::as_str).map(str::to_string), + }) +} + +fn write_profile(path: &PathBuf, profile: &Profile) -> R<()> { + let down = |e: std::io::Error| { + AgentError::Down(format!("cannot save the profile {}: {e}", path.display())) + }; + if let Some(dir) = path.parent() { + if !dir.as_os_str().is_empty() { + fs::create_dir_all(dir).map_err(down)?; + } + } + let mut record = json!({ + "name": profile.name, + "kind": profile.kind, + "groups": profile.groups, + "enrolled_at": profile.enrolled_at, + }); + if let Some(gh) = &profile.gh { + record["gh"] = json!(gh); + } + let text = serde_json::to_string_pretty(&record).unwrap_or_default(); + fs::write(path, format!("{text}\n")).map_err(down) +} + +/// One leg's answer from this seat. +#[derive(Debug, Clone, PartialEq)] +pub struct Leg { + pub name: &'static str, + pub ok: bool, + pub detail: String, + /// What this leg needs, said once so a failed probe explains itself. + pub needs: &'static str, + /// For the github leg: which route answered (`fleet` or `plain`). + pub route: Option<&'static str>, +} + +impl Leg { + fn to_json(&self) -> Value { + let mut leg = + json!({"leg": self.name, "ok": self.ok, "detail": self.detail, "needs": self.needs}); + if let Some(route) = self.route { + leg["route"] = json!(route); + } + leg + } +} + +/// Probe the four legs. With `register`, the bridge probe is the +/// `hello` that registers the agent; without it, a health check. +pub fn probe(world: &dyn World, register: Option<(&str, &[String])>) -> Vec { + let bridge_call = match register { + Some((agent, groups)) => { + let mut hello = argv(&["bridge", "hello", "--agent", agent]); + if !groups.is_empty() { + hello.push("--groups".to_string()); + hello.push(groups.join(",")); + } + hello + } + None => argv(&["bridge", "health"]), + }; + // The four legs are independent, so they are asked together. + let mut outs = world + .fleet_many(&[ + bridge_call, + argv(&["queue", "health"]), + argv(&["gh", "api", "rate_limit"]), + argv(&["laptop-agent", "health"]), + ]) + .into_iter(); + let mut next_out = || { + outs.next().unwrap_or(Out { + code: EXIT_DOWN, + stdout: String::new(), + stderr: "the probe returned no result".to_string(), + }) + }; + let leg = |name: &'static str, out: &Out, up: &str, needs: &'static str| Leg { + name, + ok: out.ok(), + detail: if out.ok() { up.to_string() } else { out.why() }, + needs, + route: None, + }; + let bridge_out = next_out(); + let queue_out = next_out(); + let through_fleet = next_out(); + let shell_out = next_out(); + let (github_out, github_route) = if through_fleet.ok() { + (through_fleet, Some("fleet")) + } else { + let plain = world.program("gh", &argv(&["api", "rate_limit"])); + let route = plain.ok().then_some("plain"); + (plain, route) + }; + vec![ + leg( + "bridge", + &bridge_out, + if register.is_some() { + "registered" + } else { + "answers" + }, + "HTTPS to the message bridge, and the fleet token by name through fleet secrets", + ), + leg( + "queue", + &queue_out, + "answers", + "the queue broker: its socket on the laptop, or the laptop transport from elsewhere", + ), + Leg { + route: github_route, + ..leg( + "github", + &github_out, + "answers", + "gh with a token: fleet gh's rotation, or a signed-in gh", + ) + }, + leg( + "shell", + &shell_out, + "the laptop answers", + "a route to the laptop: its broker, the Cloudflare tunnel, the tailnet or ssh", + ), + ] +} + +fn leg_ok(legs: &[Leg], name: &str) -> bool { + legs.iter().any(|l| l.name == name && l.ok) +} + +/// Which intake rungs the answering legs leave this seat. +pub fn rungs(legs: &[Leg]) -> Value { + json!({ + "push": leg_ok(legs, "bridge"), + "queue": leg_ok(legs, "queue"), + "shortlist": true, + "priority": leg_ok(legs, "github"), + }) +} + +fn any_intake(legs: &[Leg]) -> bool { + leg_ok(legs, "bridge") || leg_ok(legs, "queue") || leg_ok(legs, "github") +} + +fn run_loop(agent: &str) -> Vec { + vec![ + format!("fleet agent next --agent {agent} # exit 5 means no work on any rung this run"), + "do the task it returns, then run its `then` lines".to_string(), + "repeat while the run has budget".to_string(), + ] +} + +fn central_lines(address: &str) -> Vec { + vec![ + format!( + "fleet bridge send --to {address} --command \"\" # a task to this one agent" + ), + format!( + "fleet bridge send --to {address} \"\" # information, no reply owed" + ), + ] +} + +/// `fleet agent enroll`. +pub fn enroll(world: &dyn World, args: &[String]) -> R<(Value, i32)> { + let a = parse( + args, + &["--dry-run"], + &["--kind", "--name", "--groups", "--profile"], + )?; + a.no_positional("enroll")?; + let kind_name = a.last("--kind").ok_or_else(|| { + usage(format!( + "enroll needs --kind: one of {}", + kinds::names().join(", ") + )) + })?; + let kind = kinds::kind(&kind_name).ok_or_else(|| { + usage(format!( + "unknown kind '{kind_name}': one of {} (use generic for anything with a shell)", + kinds::names().join(", ") + )) + })?; + let dry_run = a.has("--dry-run"); + + // A connector has a fixed channel address and no mailbox to register. + if kind.seat == Seat::Connector { + let address = kind.address.unwrap_or(kind.name); + return Ok(( + json!({ + "agent": address, + "kind": kind.name, + "seat": kind.seat.id(), + "address": address, + "registered": false, + "steps": [ + "Attach the Message Bridge connector to the assistant (the bridge page shows the URL).", + format!("Send to it at address `{address}`; it answers with send_message reply_to."), + kind.note, + ], + "central": central_lines(address), + }), + EXIT_OK, + )); + } + + let name = check_name( + "--name", + &a.last("--name") + .ok_or_else(|| usage("enroll needs --name "))?, + )?; + let mut groups: Vec = kind.groups.iter().map(|g| g.to_string()).collect(); + if let Some(extra) = a.last("--groups") { + for g in extra.split(',').map(str::trim).filter(|g| !g.is_empty()) { + let g = check_name("--groups entry", g)?; + if !groups.contains(&g) { + groups.push(g); + } + } + } + + let legs = if dry_run { + probe(world, None) + } else { + probe(world, Some((&name, &groups))) + }; + let registered = !dry_run && leg_ok(&legs, "bridge"); + + let profile_file = profile_path(world, a.last("--profile")); + // Only a seat that runs the binary keeps a profile: an http agent + // is enrolled from someone else's seat and must not take it over. + let saved = match (&profile_file, kind.seat, dry_run) { + (Some(path), Seat::Binary, false) => { + write_profile( + path, + &Profile { + name: name.clone(), + kind: kind.name.to_string(), + groups: groups.clone(), + enrolled_at: world.now(), + gh: legs + .iter() + .find(|l| l.name == "github") + .and_then(|l| l.route) + .map(str::to_string), + }, + )?; + Some(path.display().to_string()) + } + _ => None, + }; + + let address = format!("agent:{name}"); + let mut out = json!({ + "agent": name, + "kind": kind.name, + "seat": kind.seat.id(), + "address": address, + "groups": groups, + "registered": registered, + "dry_run": dry_run, + "profile": saved, + "legs": legs.iter().map(Leg::to_json).collect::>(), + "rungs": rungs(&legs), + "central": central_lines(&address), + "note": kind.note, + }); + match kind.seat { + Seat::Binary => { + out["run_loop"] = json!(run_loop(&name)); + out["builds"] = json!( + "fleet shell -- # runs where builds belong; never build in a limited sandbox" + ); + } + Seat::Http => { + out["http"] = json!({ + "token": "the fleet token, Bitwarden secret message-bridge.fleet-token, by name", + "reference_client": "python3 scripts/fleet/bridge-mailbox.py inbox --agent --commands --take", + "routes": [ + "POST /fleet//hello {agent, groups}", + "GET /fleet//inbox agent, kind=command, mark_read=true, limit=1", + "POST /fleet//send {agent, body, reply_to}", + "POST /fleet//ack {agent, up_to_id}", + ], + "work": "tasks arrive as commands in the mailbox; central or any enrolled agent sends them", + }); + } + Seat::Connector => {} + } + let code = if dry_run || any_intake(&legs) { + EXIT_OK + } else { + EXIT_DOWN + }; + Ok((out, code)) +} + +/// `fleet agent doctor`. +pub fn doctor(world: &dyn World, args: &[String]) -> R<(Value, i32)> { + let a = parse(args, &[], &["--agent", "--profile"])?; + a.no_positional("doctor")?; + let profile = read_profile(world, a.last("--profile")); + let agent = match a + .last("--agent") + .or_else(|| world.env("FLEET_AGENT")) + .or_else(|| profile.as_ref().map(|p| p.name.clone())) + { + Some(n) => Some(check_name("--agent", &n)?), + None => None, + }; + let legs = probe(world, None); + let code = if any_intake(&legs) { + EXIT_OK + } else { + EXIT_DOWN + }; + Ok(( + json!({ + "agent": agent, + "enrolled": profile.is_some(), + "legs": legs.iter().map(Leg::to_json).collect::>(), + "rungs": rungs(&legs), + "builds": if leg_ok(&legs, "shell") { + "fleet shell reaches the laptop" + } else { + "fleet shell has no laptop route from here; it will try a codespace, then run here" + }, + }), + code, + )) +} diff --git a/pkgs/fleet/crates/fleet-agent/src/kinds.rs b/pkgs/fleet/crates/fleet-agent/src/kinds.rs new file mode 100644 index 0000000000..a07575e72b --- /dev/null +++ b/pkgs/fleet/crates/fleet-agent/src/kinds.rs @@ -0,0 +1,212 @@ +//! The agent kinds this fleet knows how to enrol. +//! +//! A kind says three things about an agent: which bridge groups it +//! joins (so "all Muse lanes" is one address), how it reaches the fleet +//! from where it runs, and what to tell it at enrolment. Adding a kind +//! is adding a row here; no verb changes. + +use serde_json::{Value, json}; + +/// How an agent of this kind reaches the fleet. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Seat { + /// It has a shell and runs the fleet binary itself. + Binary, + /// It has no shell of its own: it speaks the bridge's fleet routes + /// over HTTPS (`scripts/fleet/bridge-mailbox.py` is the reference + /// client), and gets its work from its mailbox. + Http, + /// It is a chat assistant with the Message Bridge connector + /// attached. It has a channel address, not a mailbox. + Connector, +} + +impl Seat { + pub fn id(self) -> &'static str { + match self { + Seat::Binary => "binary", + Seat::Http => "http", + Seat::Connector => "connector", + } + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Kind { + pub name: &'static str, + pub summary: &'static str, + /// Bridge groups every agent of this kind joins. + pub groups: &'static [&'static str], + pub seat: Seat, + /// The fixed bridge address of a connector kind. + pub address: Option<&'static str>, + /// What is particular to enrolling this kind. + pub note: &'static str, +} + +pub const KINDS: &[Kind] = &[ + Kind { + name: "muse", + summary: "A Muse lane or a persistent Muse agent", + groups: &["muse"], + seat: Seat::Binary, + address: None, + note: "A fresh Muse gets a bridge-capable static build from scripts/muse/bootstrap.sh. \ + Where the installed binary predates `fleet agent`, run the same commands on the \ + laptop install: ~/tools/laptop-ssh.sh 'fleet agent next --agent '.", + }, + Kind { + name: "opencode", + summary: "An OpenCode lane", + groups: &["opencode"], + seat: Seat::Binary, + address: None, + note: "Runs on the laptop seat, so every leg is local.", + }, + Kind { + name: "openchamber", + summary: "An OpenChamber session or lane", + groups: &["opencode", "openchamber"], + seat: Seat::Binary, + address: None, + note: "Joins the opencode group too, so a send to group:opencode reaches both pipelines.", + }, + Kind { + name: "openclaw", + summary: "An OpenClaw agent", + groups: &["openclaw"], + seat: Seat::Binary, + address: None, + note: "", + }, + Kind { + name: "claude-code", + summary: "A Claude Code session with a shell, cloud or local", + groups: &["claude-code"], + seat: Seat::Binary, + address: None, + note: "A cloud session has no tailnet: messaging and the priority rung work over HTTPS; \ + builds go through `fleet shell`.", + }, + Kind { + name: "codex", + summary: "A Codex CLI or cloud agent", + groups: &["codex"], + seat: Seat::Binary, + address: None, + note: "", + }, + Kind { + name: "gemini", + summary: "A Gemini CLI agent", + groups: &["gemini"], + seat: Seat::Binary, + address: None, + note: "", + }, + Kind { + name: "antigravity", + summary: "An Antigravity agent", + groups: &["antigravity"], + seat: Seat::Binary, + address: None, + note: "", + }, + Kind { + name: "grok", + summary: "A Grok bot", + groups: &["grok"], + seat: Seat::Binary, + address: None, + note: "A bot with no shell enrols as kind `http` under the same name and groups.", + }, + Kind { + name: "dot", + summary: "The Dot assistant", + groups: &["dot"], + seat: Seat::Http, + address: None, + note: "pkgs/dot-bridge carries its Slack and ChatGPT transports; the mailbox is the \ + same store.", + }, + Kind { + name: "duet", + summary: "The Duet assistant", + groups: &["duet"], + seat: Seat::Http, + address: None, + note: "", + }, + Kind { + name: "claude", + summary: "Claude, through the Message Bridge connector", + groups: &[], + seat: Seat::Connector, + address: Some("claude"), + note: "Set a wake hook for channel:claude on the bridge page so a send starts a session.", + }, + Kind { + name: "chatgpt", + summary: "ChatGPT, through the Message Bridge connector", + groups: &[], + seat: Seat::Connector, + address: Some("chatgpt"), + note: "Woken by its MCP Events subscription.", + }, + Kind { + name: "laptop", + summary: "A job or service on the fleet laptop", + groups: &["laptop"], + seat: Seat::Binary, + address: None, + note: "", + }, + Kind { + name: "http", + summary: "Anything that can make an HTTPS request and nothing else", + groups: &[], + seat: Seat::Http, + address: None, + note: "", + }, + Kind { + name: "generic", + summary: "Any other agent with a shell", + groups: &[], + seat: Seat::Binary, + address: None, + note: "", + }, +]; + +pub fn kind(name: &str) -> Option<&'static Kind> { + KINDS.iter().find(|k| k.name == name) +} + +pub fn names() -> Vec<&'static str> { + KINDS.iter().map(|k| k.name).collect() +} + +/// `fleet agent kinds`: the table as JSON. +pub fn table() -> Value { + json!({ + "kinds": KINDS + .iter() + .map(|k| { + json!({ + "kind": k.name, + "summary": k.summary, + "groups": k.groups, + "seat": k.seat.id(), + "address": k.address, + "note": k.note, + }) + }) + .collect::>(), + "seats": { + "binary": "runs the fleet binary itself: fleet agent enroll, then fleet agent next", + "http": "no shell: speaks the bridge's fleet routes over HTTPS; work arrives in its mailbox", + "connector": "a chat assistant with the Message Bridge connector; addressed by channel", + }, + }) +} diff --git a/pkgs/fleet/crates/fleet-agent/src/lib.rs b/pkgs/fleet/crates/fleet-agent/src/lib.rs new file mode 100644 index 0000000000..e16224cdeb --- /dev/null +++ b/pkgs/fleet/crates/fleet-agent/src/lib.rs @@ -0,0 +1,558 @@ +//! fleet-agent — one front door for any agent (design: +//! `doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/`). +//! +//! The fleet already has the legs: mailboxes on the message bridge +//! (`fleet bridge`), the queue (`fleet queue`), the laptop transport +//! ladder (`fleet laptop-agent`, `fleet proxy ssh`), placement and +//! secrets by name. What an agent of a new kind lacked was one place to +//! start: who am I here, what can this seat reach, what do I work on +//! next, and where do I build. This crate is that place. It adds no +//! transport of its own: every verb is a sequence of the existing verbs, +//! run through the same binary, so their auth, retries and fallbacks +//! apply unchanged. +//! +//! Verbs (`fleet agent `): +//! +//! * `kinds` — the agent kinds this fleet knows how to enrol. +//! * `enroll` — register a named agent of a kind and save its profile. +//! * `doctor` — which legs answer from this seat, and which intake +//! rungs that leaves. +//! * `next` — the next piece of work, down the intake ladder: +//! a command pushed to this agent, a queue claim, the local +//! shortlist, then the highest-priority open issue. A rung that +//! cannot answer is skipped and named, never fatal. +//! * `shortlist` — the local list `next` draws on: `status`, `add`, +//! `take`, `fill`, `clear`. +//! +//! And one sibling domain, `fleet shell`: run a command or open a +//! shell where builds belong (the laptop, a codespace, or here). +//! +//! Nothing in this crate waits on a person. An issue parked "for the +//! owner" is handed out as ready work with a note saying so (FDR-0013). +//! +//! Exit codes, the workspace convention: 0 ok · 2 usage · 3 a leg +//! this verb needs is down · 5 no work on any rung (the queue's +//! no-claim code, so shift scripts need one check). + +use std::path::PathBuf; + +use fleet_config::Config; +use serde_json::Value; + +pub mod enroll; +pub mod kinds; +pub mod next; +pub mod shell; +pub mod shortlist; + +#[cfg(test)] +mod tests; + +pub const EXIT_OK: i32 = 0; +pub const EXIT_USAGE: i32 = 2; +pub const EXIT_DOWN: i32 = 3; +/// No rung had work. Equal to the queue client's no-claim exit. +pub const EXIT_NO_WORK: i32 = 5; + +pub const USAGE: &str = "\ +usage: fleet agent [options] + + kinds the agent kinds this fleet can enrol + enroll --kind K --name N register an agent and save its profile + [--groups a,b] [--dry-run] [--profile PATH] + doctor [--agent N] which legs answer from this seat + next [--agent N] the next piece of work, down the ladder: + [--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] + shortlist status|take|clear the local list `next` draws on + shortlist add --issue N --title T [--repo R] [--rank N] [--why TEXT] + shortlist fill [--repo R] [--target N] + +Every verb prints one JSON object. Exit: 0 ok, 2 usage, 3 a needed leg +is down, 5 no work on any rung."; + +/// A verb's failure: a usage error or a leg that is down. +#[derive(Debug, Clone, PartialEq)] +pub enum AgentError { + Usage(String), + Down(String), +} + +impl AgentError { + pub fn exit_code(&self) -> i32 { + match self { + AgentError::Usage(_) => EXIT_USAGE, + AgentError::Down(_) => EXIT_DOWN, + } + } +} + +impl std::fmt::Display for AgentError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AgentError::Usage(m) => write!(f, "fleet agent: {m}"), + AgentError::Down(m) => write!(f, "fleet agent: {m}"), + } + } +} + +pub type R = Result; + +pub fn usage(msg: impl Into) -> AgentError { + AgentError::Usage(msg.into()) +} + +// ---- the outside world ---- + +/// What one sub-invocation answered. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Out { + pub code: i32, + pub stdout: String, + pub stderr: String, +} + +impl Out { + pub fn ok(&self) -> bool { + self.code == 0 + } + /// The stdout parsed as JSON, when it is JSON. + pub fn json(&self) -> Option { + serde_json::from_str(self.stdout.trim()).ok() + } + /// One line saying why this call did not succeed, for a skip record. + pub fn why(&self) -> String { + let text = if self.stderr.trim().is_empty() { + self.stdout.trim() + } else { + self.stderr.trim() + }; + let line = text.lines().last().unwrap_or("").trim(); + let line: String = line.chars().take(200).collect(); + if line.is_empty() { + format!("exit {}", self.code) + } else { + format!("exit {}: {line}", self.code) + } + } +} + +/// Everything a verb needs from outside the process, so tests can +/// supply it. Production is [`RealWorld`]. +pub trait World { + /// Run this same fleet binary with `args`, capturing its output. + /// Production bounds the call ([`step_limit`]): a leg that gives + /// no answer in time is a leg that is down, never a hang. + fn fleet(&self, args: &[String]) -> Out; + /// Like [`World::fleet`], for the one kind of call that must not + /// be cut short: a call that changes state on the far side (a + /// queue claim), where stopping early would orphan the change. + fn fleet_patient(&self, args: &[String]) -> Out { + self.fleet(args) + } + /// Several independent fleet calls. Production runs them at the + /// same time, so probing every leg of a seat with nothing + /// reachable costs one limit, not one per leg. + fn fleet_many(&self, calls: &[Vec]) -> Vec { + calls.iter().map(|c| self.fleet(c)).collect() + } + /// Run another program, capturing its output. + fn program(&self, program: &str, args: &[String]) -> Out; + /// Run a program attached to this terminal; its exit code. + fn attach(&self, program: &str, args: &[String]) -> i32; + fn env(&self, key: &str) -> Option; + /// Seconds since the Unix epoch. + fn now(&self) -> u64; + fn home(&self) -> Option; +} + +pub struct RealWorld; + +/// Names the limit, in seconds, on one captured step. +pub const STEP_TIMEOUT_ENV: &str = "FLEET_AGENT_STEP_TIMEOUT"; +/// Long enough for a healthy leg over a slow link, short enough that +/// a seat with nothing reachable still answers in under a minute. +pub const DEFAULT_STEP_TIMEOUT_SECS: u64 = 45; +/// A patient call gets this many step limits: past the secrets +/// chain's two-minute broker retry window at the default. +pub const PATIENT_FACTOR: u64 = 4; + +/// The limit for one captured step from the variable's value: a +/// positive whole number of seconds, else the default. +pub fn step_limit(raw: Option<&str>) -> std::time::Duration { + let secs = raw + .and_then(|v| v.trim().parse::().ok()) + .filter(|n| *n > 0) + .unwrap_or(DEFAULT_STEP_TIMEOUT_SECS); + std::time::Duration::from_secs(secs) +} + +fn env_step_limit() -> std::time::Duration { + step_limit(std::env::var(STEP_TIMEOUT_ENV).ok().as_deref()) +} + +/// Run a command to completion or to `limit`, capturing its output. +/// A command still running at the limit is stopped and reported as +/// down (exit [`EXIT_DOWN`]) with a line saying how long it was given. +pub fn capture(mut cmd: std::process::Command, what: &str, limit: std::time::Duration) -> Out { + use std::io::Read; + use std::process::Stdio; + let mut child = match cmd + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + { + Ok(c) => c, + Err(e) => { + return Out { + code: 127, + stdout: String::new(), + stderr: format!("cannot run {what}: {e}"), + }; + } + }; + // Drain both pipes on threads so a chatty child never blocks on a + // full pipe while this thread waits for it. + fn drain(pipe: Option) -> std::sync::mpsc::Receiver { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut text = Vec::new(); + if let Some(mut pipe) = pipe { + let _ = pipe.read_to_end(&mut text); + } + let _ = tx.send(String::from_utf8_lossy(&text).into_owned()); + }); + rx + } + let stdout = drain(child.stdout.take()); + let stderr = drain(child.stderr.take()); + let started = std::time::Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) if started.elapsed() >= limit => break None, + Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)), + Err(_) => break None, + } + }; + match status { + Some(status) => { + // The child is gone; whatever it wrote is already in the + // pipes. A descendant that still holds a pipe open must + // not hold this call past the child's exit for long. + let grace = std::time::Duration::from_secs(2); + Out { + code: status.code().unwrap_or(1), + stdout: stdout.recv_timeout(grace).unwrap_or_default(), + stderr: stderr.recv_timeout(grace).unwrap_or_default(), + } + } + None => { + let _ = child.kill(); + let _ = child.wait(); + Out { + code: EXIT_DOWN, + stdout: String::new(), + stderr: format!("{what} gave no answer within {}s", limit.as_secs()), + } + } + } +} + +fn this_fleet(args: &[String], limit: std::time::Duration) -> Out { + let exe = match std::env::current_exe() { + Ok(p) => p, + Err(e) => { + return Out { + code: 127, + stdout: String::new(), + stderr: format!("cannot find this fleet binary: {e}"), + }; + } + }; + let mut cmd = std::process::Command::new(exe); + cmd.args(args); + let what = format!( + "fleet {}", + args.iter().take(2).cloned().collect::>().join(" ") + ); + capture(cmd, what.trim_end(), limit) +} + +impl World for RealWorld { + fn fleet(&self, args: &[String]) -> Out { + this_fleet(args, env_step_limit()) + } + fn fleet_patient(&self, args: &[String]) -> Out { + this_fleet(args, env_step_limit() * PATIENT_FACTOR as u32) + } + fn fleet_many(&self, calls: &[Vec]) -> Vec { + let limit = env_step_limit(); + std::thread::scope(|scope| { + let running: Vec<_> = calls + .iter() + .map(|call| scope.spawn(move || this_fleet(call, limit))) + .collect(); + running + .into_iter() + .map(|handle| { + handle.join().unwrap_or_else(|_| Out { + code: EXIT_DOWN, + stdout: String::new(), + stderr: "the probe did not finish".to_string(), + }) + }) + .collect() + }) + } + fn program(&self, program: &str, args: &[String]) -> Out { + let mut cmd = std::process::Command::new(program); + cmd.args(args); + capture(cmd, program, env_step_limit()) + } + fn attach(&self, program: &str, args: &[String]) -> i32 { + let target = if program == "fleet" { + match std::env::current_exe() { + Ok(p) => p, + Err(e) => { + eprintln!("fleet: cannot find this fleet binary: {e}"); + return 127; + } + } + } else { + PathBuf::from(program) + }; + match std::process::Command::new(target).args(args).status() { + Ok(s) => s.code().unwrap_or(1), + Err(e) => { + eprintln!("fleet: cannot run {program}: {e}"); + 127 + } + } + } + fn env(&self, key: &str) -> Option { + std::env::var(key).ok().filter(|v| !v.trim().is_empty()) + } + fn now(&self) -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) + } + fn home(&self) -> Option { + std::env::var_os("HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + } +} + +/// Build an argv from string slices. +pub fn argv(parts: &[&str]) -> Vec { + parts.iter().map(|s| s.to_string()).collect() +} + +// ---- argument parsing ---- + +/// Parsed options: `--name value`, `--name=value`, switches, and the +/// words after `--`. An unknown option is a usage error, never ignored. +#[derive(Debug, Default)] +pub struct Args { + flags: Vec<(String, Option)>, + pub positional: Vec, + /// The words after a `--` separator, verbatim. + pub tail: Vec, +} + +pub fn parse(args: &[String], switches: &[&str], values: &[&str]) -> R { + let mut out = Args::default(); + let mut it = args.iter(); + while let Some(a) = it.next() { + if a == "--" { + out.tail = it.cloned().collect(); + break; + } + if !a.starts_with("--") { + out.positional.push(a.clone()); + continue; + } + let (name, inline) = match a.split_once('=') { + Some((n, v)) => (n.to_string(), Some(v.to_string())), + None => (a.clone(), None), + }; + if values.contains(&name.as_str()) { + let v = match inline { + Some(v) => v, + None => it + .next() + .cloned() + .ok_or_else(|| usage(format!("{name} needs a value")))?, + }; + out.flags.push((name, Some(v))); + } else if switches.contains(&name.as_str()) { + if inline.is_some() { + return Err(usage(format!("{name} takes no value"))); + } + out.flags.push((name, None)); + } else { + return Err(usage(format!("unknown option {name}"))); + } + } + Ok(out) +} + +impl Args { + pub fn has(&self, name: &str) -> bool { + self.flags.iter().any(|(n, _)| n == name) + } + pub fn last(&self, name: &str) -> Option { + self.flags + .iter() + .rev() + .find(|(n, _)| n == name) + .and_then(|(_, v)| v.clone()) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + } + pub fn uint(&self, name: &str) -> R> { + match self.last(name) { + None => Ok(None), + Some(v) => v + .parse::() + .map(Some) + .map_err(|_| usage(format!("{name} must be a whole number"))), + } + } + pub fn no_positional(&self, verb: &str) -> R<()> { + if let Some(p) = self.positional.first() { + return Err(usage(format!("{verb} takes no argument '{p}'"))); + } + if !self.tail.is_empty() { + return Err(usage(format!("{verb} takes nothing after --"))); + } + Ok(()) + } +} + +/// An agent or lane name: what the bridge and the queue accept. +pub fn check_name(what: &str, name: &str) -> R { + let ok = !name.is_empty() + && name.len() <= 64 + && name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-')) + && name + .chars() + .next() + .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); + if ok { + Ok(name.to_string()) + } else { + Err(usage(format!( + "{what} '{name}' must be 1-64 of lowercase letters, digits, '.', '_' or '-', \ + starting with a letter or digit" + ))) + } +} + +/// `owner/name`, the only repository shape the fleet uses. +pub fn check_repo(repo: &str) -> R { + let ok = match repo.split_once('/') { + Some((owner, name)) => { + let part = |s: &str| { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) + }; + part(owner) && part(name) + } + None => false, + }; + if ok { + Ok(repo.to_string()) + } else { + Err(usage(format!("--repo '{repo}' must be owner/name"))) + } +} + +pub const DEFAULT_REPO: &str = "developing-today/code"; + +// ---- domain entry points ---- + +fn print(v: &Value) { + println!( + "{}", + serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string()) + ); +} + +fn wants_help(args: &[String]) -> bool { + args.iter() + .take_while(|a| a.as_str() != "--") + .any(|a| a == "--help" || a == "-h" || a == "help") +} + +/// Runs one `fleet agent` verb; Ok is the JSON to print and the exit code. +pub fn execute(world: &dyn World, args: &[String]) -> R<(Value, i32)> { + let Some((verb, rest)) = args.split_first() else { + return Err(usage("missing verb (try: fleet agent --help)")); + }; + match verb.as_str() { + "kinds" => { + parse(rest, &[], &[])?.no_positional("kinds")?; + Ok((kinds::table(), EXIT_OK)) + } + "enroll" => enroll::enroll(world, rest), + "doctor" => enroll::doctor(world, rest), + "next" => next::next(world, rest), + "shortlist" => shortlist::run(world, rest), + other => Err(usage(format!( + "unknown verb '{other}' (try: fleet agent --help)" + ))), + } +} + +/// The domain entry point: `fleet agent ...`. +pub fn run(config: &Config, args: &[String]) -> i32 { + if args.is_empty() || wants_help(args) { + println!("{USAGE}"); + return if args.is_empty() { EXIT_USAGE } else { EXIT_OK }; + } + // The sub-invocations load fleet config themselves; this domain + // has no settings of its own yet. + let _ = config; + match execute(&RealWorld, args) { + Ok((v, code)) => { + print(&v); + code + } + Err(e) => { + eprintln!("{e}"); + e.exit_code() + } + } +} + +/// The sibling domain's entry point: `fleet shell ...`. +pub fn run_shell(config: &Config, args: &[String]) -> i32 { + if wants_help(args) { + println!("{}", shell::USAGE); + return EXIT_OK; + } + match shell::run(config, &RealWorld, args) { + Ok(shell::Done::Printed(v)) => { + print(&v); + EXIT_OK + } + Ok(shell::Done::Ran(code)) => code, + Err(e) => { + eprintln!( + "{}", + e.to_string().replacen("fleet agent:", "fleet shell:", 1) + ); + e.exit_code() + } + } +} diff --git a/pkgs/fleet/crates/fleet-agent/src/next.rs b/pkgs/fleet/crates/fleet-agent/src/next.rs new file mode 100644 index 0000000000..4c945d8fb8 --- /dev/null +++ b/pkgs/fleet/crates/fleet-agent/src/next.rs @@ -0,0 +1,532 @@ +//! `fleet agent next` — the next piece of work, down the intake ladder. +//! +//! One verb for every agent, whatever started it (a wake hook, a cron +//! run, a person). It tries four rungs in order and returns the first +//! task it finds: +//! +//! 1. **push** — a command addressed to this agent on the bridge. This +//! is how central, a hook or another agent sends a task to one +//! specific place. +//! 2. **queue** — a claim on the one fleet queue. +//! 3. **shortlist** — the top of this host's local shortlist. A run +//! that finds the list low, with nobody refilling, is told to refill +//! it instead (rung `refill`): that run switches purpose. +//! 4. **priority** — the highest-priority open issue, straight from +//! GitHub labels. +//! +//! A rung that is down (the bridge unreachable, the broker not +//! answering, no `gh`) is recorded in `tried` and the ladder moves on. +//! Reaching nothing is never an error on its own: an agent on a seat +//! with only HTTPS still gets work from rungs 1 and 4. +//! +//! Nothing here treats a person as a gate. An issue labelled +//! `user/escalated` or blocked "for the owner" is handed out like any +//! other, with a note saying it was parked on the owner and that the +//! decision is the worker's to make (FDR-0013). Only the hold labels +//! of FDR-0012 keep an issue out. + +use serde_json::{Value, json}; + +use crate::shortlist::{self, Entry, rank_of}; +use crate::{ + DEFAULT_REPO, EXIT_NO_WORK, EXIT_OK, R, World, argv, check_name, check_repo, parse, usage, +}; + +/// Labels that hold an issue (FDR-0012): a person set them on purpose. +pub const HOLD_LABELS: [&str; 3] = ["held", "user/owned", "do-not-auto-edit"]; +/// Labels on an issue that indexes other work and is not itself a +/// piece of work to hand out. +pub const NOT_WORK_LABELS: [&str; 1] = ["kind/tracker"]; +/// How an issue body marks a hands item +/// (``). +pub const HANDS_MARKER: &str = ""); + let mut decided = issue(805, &["now", "user/escalated"]); + decided["body"] = json!("\nDecided: option B."); + fake.on( + "labels=now", + vec![ok(json!([ + hands, + issue(12238, &["now", "kind/tracker"]), + decided, + ]))], + ) + .on("gh api", vec![ok(json!([]))]); + let found = crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + // Positive control: the owner park with a decision record stays. + assert_eq!(found.iter().map(|e| e.issue).collect::>(), vec![805]); +} + +fn count_calls(fake: &Fake, prefix: &str) -> usize { + fake.calls() + .iter() + .filter(|c| c.starts_with(prefix)) + .count() +} + +#[test] +fn a_github_route_that_cannot_answer_is_paid_for_once_per_lookup() { + // Oracle: five ranked labels are asked. The route that fails is + // tried for the first only; the other four go straight to the + // route that answered. + let fake = Fake::new(); + fake.on( + "fleet gh api", + vec![fail(3, "fleet gh gave no answer within 45s")], + ) + .on("gh api", vec![ok(json!([]))]); + let found = crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + assert!(found.is_empty()); + assert_eq!(count_calls(&fake, "fleet gh api repos/"), 1); + assert_eq!(count_calls(&fake, "gh api repos/"), 5); +} + +#[test] +fn the_first_github_route_can_be_named_and_the_other_stays_the_fallback() { + // Named plain: the fleet's rotation is never asked while plain answers. + let fake = Fake::new(); + fake.set_env("FLEET_AGENT_GH", "plain"); + fake.on("gh api", vec![ok(json!([]))]); + crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + assert_eq!(count_calls(&fake, "fleet gh api"), 0); + assert_eq!(count_calls(&fake, "gh api repos/"), 5); + + // Named plain, but plain is down: the rotation still answers, and + // is then the route for the rest of the lookup. + let fake = Fake::new(); + fake.set_env("FLEET_AGENT_GH", "plain"); + fake.on("fleet gh api", vec![ok(json!([issue(557, &["now"])]))]) + .on("gh api", vec![fail(1, "gh: not signed in")]); + let found = crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + assert_eq!(found[0].issue, 557); + assert_eq!(count_calls(&fake, "gh api repos/"), 1); + assert_eq!(count_calls(&fake, "fleet gh api repos/"), 5); + + // A value that names no route changes nothing: rotation first. + let fake = Fake::new(); + fake.set_env("FLEET_AGENT_GH", "sideways"); + fake.on("fleet gh api", vec![ok(json!([]))]); + crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + assert_eq!(count_calls(&fake, "gh api repos/"), 0); +} + +#[test] +fn enrolment_records_the_github_route_that_answered_and_later_lookups_start_there() { + let fake = Fake::new(); + fake.on("fleet bridge hello", vec![ok(json!({"agent": "codex-2"}))]) + .on( + "fleet queue health", + vec![fail(3, "queue broker unreachable")], + ) + .on( + "fleet gh api", + vec![fail(3, "fleet gh gave no answer within 45s")], + ) + .on("gh api", vec![ok(json!([]))]) + .on( + "fleet laptop-agent health", + vec![fail(3, "no leg answered")], + ); + let (out, code) = run(&fake, &["enroll", "--kind", "codex", "--name", "codex-2"]); + assert_eq!(code, EXIT_OK); + assert_eq!(out["legs"][2]["leg"], "github"); + assert_eq!(out["legs"][2]["route"], "plain"); + let saved: Value = + serde_json::from_str(&std::fs::read_to_string(fake.profile_path()).unwrap()).unwrap(); + assert_eq!(saved["gh"], "plain"); + // One probe went through the rotation at enrolment; no lookup does. + assert_eq!(count_calls(&fake, "fleet gh api"), 1); + crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + assert_eq!(count_calls(&fake, "fleet gh api"), 1); + assert_eq!(count_calls(&fake, "gh api repos/"), 5); +} + +// ---- the shortlist ---- + +#[test] +fn shortlist_add_refuses_duplicates_and_recent_hand_outs() { + let mut list = Shortlist::default(); + assert!(list.add(entry(557, 2, 1))); + assert!(!list.add(entry(557, 0, 2)), "the same issue is listed once"); + let taken = list.take("muse-3", 100).unwrap(); + assert_eq!(taken.issue, 557); + assert!( + !list.add(entry(557, 2, 101)), + "handed out here inside the window" + ); + list.prune(100 + shortlist::HANDED_TTL_SECS); + assert!(list.add(entry(557, 2, 9000)), "the window has passed"); +} + +#[test] +fn a_shortlist_file_that_does_not_parse_is_an_error_and_is_left_alone() { + let fake = Fake::new(); + std::fs::write(fake.shortlist_path(), "{ not a shortlist").unwrap(); + let err = execute(&fake, &argv(&["shortlist", "status"])).unwrap_err(); + assert!( + matches!(&err, AgentError::Down(m) if m.contains("shortlist.json")), + "{err:?}" + ); + assert_eq!(err.exit_code(), EXIT_DOWN); + assert_eq!( + std::fs::read_to_string(fake.shortlist_path()).unwrap(), + "{ not a shortlist" + ); +} + +#[test] +fn shortlist_fill_tops_up_to_the_target_and_releases_the_filler() { + let fake = Fake::new(); + fake.on( + "labels=now", + vec![ok(json!([ + issue(1, &["now"]), + issue(2, &["now"]), + issue(3, &["now"]), + issue(4, &["now"]) + ]))], + ) + .on("gh api", vec![ok(json!([]))]); + fake.seed(vec![entry(2, 2, 1)]); + shortlist::update(&fake.shortlist_path(), fake.now.get(), |list| { + list.refill = Some(("muse-3".to_string(), fake.now.get())); + }) + .unwrap(); + let (out, code) = run( + &fake, + &["shortlist", "fill", "--target", "3", "--agent", "muse-3"], + ); + assert_eq!(code, EXIT_OK); + // One entry was there; #2 is already listed; #1 and #3 bring it to three; #4 is not needed. + assert_eq!(out["added"], 2); + assert_eq!(out["count"], 3); + let list = shortlist::load(&fake.shortlist_path()).unwrap(); + let mut issues: Vec = list.entries.iter().map(|e| e.issue).collect(); + issues.sort(); + assert_eq!(issues, vec![1, 2, 3]); + assert_eq!(list.refill, None); + assert!( + list.entries + .iter() + .filter(|e| e.issue != 2) + .all(|e| e.added_by == "muse-3") + ); +} + +#[test] +fn shortlist_take_on_an_empty_list_is_exit_five() { + let fake = Fake::new(); + let (out, code) = run(&fake, &["shortlist", "take", "--agent", "muse-3"]); + assert_eq!(code, EXIT_NO_WORK); + assert!(out["entry"].is_null()); +} + +proptest! { + /// Taking until empty yields the entries in (rank, added_at, issue) + /// order, each exactly once, and every take is remembered. + #[test] + fn take_order_matches_a_sort(specs in proptest::collection::btree_map(1u64..500, (0u64..7, 0u64..1000), 0..12)) { + let mut list = Shortlist::default(); + for (issue, (rank, added_at)) in &specs { + list.add(entry(*issue, *rank, *added_at)); + } + let mut expected: Vec<(u64, u64, u64)> = + specs.iter().map(|(issue, (rank, at))| (*rank, *at, *issue)).collect(); + expected.sort(); + let mut got = Vec::new(); + while let Some(e) = list.take("muse-3", 5000) { + got.push((e.rank, e.added_at, e.issue)); + } + prop_assert_eq!(&got, &expected); + prop_assert_eq!(list.handed.len(), specs.len()); + prop_assert!(list.entries.is_empty()); + } + + /// What is written is what is read back. + #[test] + fn the_file_round_trips(specs in proptest::collection::btree_map(1u64..500, (0u64..7, 0u64..1000), 0..8), marker in proptest::option::of(0u64..1000)) { + let fake = Fake::new(); + let mut list = Shortlist::default(); + for (issue, (rank, added_at)) in &specs { + list.add(entry(*issue, *rank, *added_at)); + } + list.refill = marker.map(|at| ("muse-3".to_string(), fake.now.get() - at)); + let want = list.clone(); + shortlist::update(&fake.shortlist_path(), fake.now.get(), |on_disk| *on_disk = list).unwrap(); + prop_assert_eq!(shortlist::load(&fake.shortlist_path()).unwrap(), want); + } +} + +// ---- enrolment ---- + +#[test] +fn enrolling_registers_the_mailbox_saves_the_profile_and_reports_the_rungs() { + let fake = Fake::new(); + fake.on( + "fleet bridge hello", + vec![ok(json!({"agent": "muse-7", "groups": ["muse", "night"]}))], + ) + .on( + "fleet queue health", + vec![fail(3, "queue broker unreachable")], + ) + .on( + "fleet gh api rate_limit", + vec![ok(json!({"rate": {"remaining": 4000}}))], + ) + .on( + "fleet laptop-agent health", + vec![fail(3, "no leg answered")], + ); + let (out, code) = run( + &fake, + &[ + "enroll", + "--kind", + "muse", + "--name", + "muse-7", + "--groups", + "night,muse", + ], + ); + // One answering intake leg is enough to be enrolled. + assert_eq!(code, EXIT_OK); + assert_eq!(out["registered"], true); + // The kind's group comes first; an extra group is added once. + assert_eq!(out["groups"], json!(["muse", "night"])); + assert!(fake.called("fleet bridge hello --agent muse-7 --groups muse,night")); + assert_eq!( + out["rungs"], + json!({"push": true, "queue": false, "shortlist": true, "priority": true}) + ); + assert_eq!(out["address"], "agent:muse-7"); + // A leg that is down says what it needs. + assert_eq!(out["legs"][1]["leg"], "queue"); + assert_eq!(out["legs"][1]["ok"], false); + assert!( + out["legs"][1]["needs"] + .as_str() + .unwrap() + .contains("queue broker") + ); + // The profile lets later verbs know who is asking. + let saved: Value = + serde_json::from_str(&std::fs::read_to_string(fake.profile_path()).unwrap()).unwrap(); + assert_eq!(saved["name"], "muse-7"); + assert_eq!(saved["kind"], "muse"); + + let fake_next = &fake; + fake_next + .on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on("gh api", vec![ok(json!([]))]); + let (next, _) = run(fake_next, &["next", "--no-shortlist"]); + assert_eq!(next["agent"], "muse-7", "next reads the saved profile"); +} + +#[test] +fn a_seat_where_no_intake_leg_answers_is_exit_three_and_still_explains_itself() { + let fake = Fake::new(); + fake.on("fleet ", vec![fail(3, "unreachable")]) + .on("gh ", vec![fail(1, "not signed in")]); + let (out, code) = run(&fake, &["enroll", "--kind", "generic", "--name", "box-1"]); + assert_eq!(code, EXIT_DOWN); + assert_eq!(out["registered"], false); + assert_eq!( + out["rungs"], + json!({"push": false, "queue": false, "shortlist": true, "priority": false}) + ); + assert_eq!(out["legs"].as_array().unwrap().len(), 4); +} + +#[test] +fn a_connector_has_an_address_and_no_mailbox() { + let fake = Fake::new(); + let (out, code) = run(&fake, &["enroll", "--kind", "claude"]); + assert_eq!(code, EXIT_OK); + assert_eq!(out["address"], "claude"); + assert_eq!(out["registered"], false); + assert!( + fake.calls().is_empty(), + "no hello for a connector: {:?}", + fake.calls() + ); + assert!(!fake.profile_path().exists()); +} + +#[test] +fn an_http_agent_is_registered_from_this_seat_without_taking_its_profile() { + let fake = Fake::new(); + fake.on("fleet bridge hello", vec![ok(json!({"agent": "dot"}))]) + .on("fleet ", vec![fail(3, "unreachable")]) + .on("gh ", vec![fail(1, "x")]); + let (out, code) = run(&fake, &["enroll", "--kind", "dot", "--name", "dot"]); + assert_eq!(code, EXIT_OK); + assert_eq!(out["seat"], "http"); + assert_eq!(out["registered"], true); + assert!( + out["http"]["routes"][0] + .as_str() + .unwrap() + .contains("/hello") + ); + assert!(out["profile"].is_null()); + assert!( + !fake.profile_path().exists(), + "this seat's own profile must not become dot's" + ); +} + +#[test] +fn a_dry_run_registers_nothing_and_saves_nothing() { + let fake = Fake::new(); + fake.on("fleet bridge health", vec![ok(json!({"ok": true}))]) + .on("fleet ", vec![fail(3, "unreachable")]) + .on("gh ", vec![fail(1, "x")]); + let (out, code) = run( + &fake, + &["enroll", "--kind", "muse", "--name", "muse-7", "--dry-run"], + ); + assert_eq!(code, EXIT_OK); + assert_eq!(out["registered"], false); + assert!(!fake.called("bridge hello")); + assert!(!fake.profile_path().exists()); +} + +#[test] +fn enrolment_refuses_an_unknown_kind_and_a_bad_name() { + let fake = Fake::new(); + let err = |words: &[&str]| execute(&fake, &argv(words)).unwrap_err(); + assert!( + matches!(err(&["enroll", "--kind", "robot", "--name", "r2"]), AgentError::Usage(m) if m.contains("generic")) + ); + assert!(matches!( + err(&["enroll", "--kind", "muse", "--name", "Muse_7!"]), + AgentError::Usage(_) + )); + assert!( + matches!(err(&["enroll", "--kind", "muse"]), AgentError::Usage(m) if m.contains("--name")) + ); + assert!(fake.calls().is_empty()); +} + +#[test] +fn every_kind_has_a_usable_row() { + let table = crate::kinds::table(); + let rows = table["kinds"].as_array().unwrap(); + assert!(rows.len() >= 10); + for kind in crate::kinds::KINDS { + assert!( + crate::check_name("kind", kind.name).is_ok(), + "{}", + kind.name + ); + for group in kind.groups { + assert!(crate::check_name("group", group).is_ok(), "{group}"); + } + // A connector is addressed by channel; nothing else has a fixed address. + assert_eq!( + kind.address.is_some(), + kind.seat == crate::kinds::Seat::Connector, + "{}", + kind.name + ); + } + // The kinds the fleet runs today are all enrolable by name. + for name in [ + "muse", + "opencode", + "openchamber", + "openclaw", + "grok", + "dot", + "duet", + "claude", + "chatgpt", + "antigravity", + ] { + assert!(crate::kinds::kind(name).is_some(), "{name}"); + } +} + +// ---- fleet shell ---- + +fn opts() -> Options { + Options { + cwd: None, + build: false, + timeout: None, + detach: false, + } +} + +fn words(list: &[&str]) -> Vec { + argv(list) +} + +#[test] +fn a_laptop_command_goes_through_the_laptop_agent_ladder() { + let plan = shell::plan( + Target::Laptop, + "test".into(), + &words(&["cargo", "test", "-p", "id-core"]), + &opts(), + ) + .unwrap(); + assert_eq!(plan.program, "fleet"); + assert_eq!( + plan.args, + argv(&[ + "laptop-agent", + "exec", + "--timeout", + "120", + "--shell", + "--", + "cargo test -p id-core" + ]) + ); +} + +#[test] +fn a_build_takes_a_lock_slot_and_an_hour() { + let plan = shell::plan( + Target::Laptop, + "test".into(), + &words(&["cargo", "test", "-p", "id-core"]), + &Options { + cwd: Some("/home/user/code/pkgs/id".into()), + build: true, + timeout: None, + detach: false, + }, + ) + .unwrap(); + assert_eq!( + plan.args, + argv(&[ + "laptop-agent", + "exec", + "--cwd", + "/home/user/code/pkgs/id", + "--timeout", + "3600", + "--shell", + "--", + "~/tools/fleet-build-lock cargo test -p id-core", + ]) + ); +} + +#[test] +fn detach_starts_a_job_and_only_on_the_laptop() { + let detached = Options { + cwd: None, + build: false, + timeout: None, + detach: true, + }; + let plan = shell::plan( + Target::Laptop, + "t".into(), + &words(&["nix", "build"]), + &detached, + ) + .unwrap(); + assert_eq!( + plan.args, + argv(&["laptop-agent", "run", "--shell", "--", "nix build"]) + ); + assert!(matches!( + shell::plan( + Target::Local, + "t".into(), + &words(&["nix", "build"]), + &detached + ), + Err(AgentError::Usage(_)) + )); +} + +#[test] +fn no_command_opens_a_shell_and_build_flags_then_make_no_sense() { + let plan = shell::plan(Target::Laptop, "t".into(), &[], &opts()).unwrap(); + assert_eq!( + (plan.program.as_str(), plan.args), + ("fleet", argv(&["proxy", "ssh", "--"])) + ); + let plan = shell::plan(Target::Codespace("cs-1".into()), "t".into(), &[], &opts()).unwrap(); + assert_eq!( + (plan.program.as_str(), plan.args), + ("gh", argv(&["codespace", "ssh", "-c", "cs-1"])) + ); + let build = Options { + cwd: None, + build: true, + timeout: None, + detach: false, + }; + assert!(matches!( + shell::plan(Target::Laptop, "t".into(), &[], &build), + Err(AgentError::Usage(_)) + )); +} + +#[test] +fn a_tilde_is_quoted_so_the_far_shell_does_not_expand_it() { + // Found by the property test below: a bare `~` came back as the + // home directory. Oracle: POSIX tilde expansion applies to an + // unquoted leading tilde only. + assert_eq!(shell::sh_quote("~"), "'~'"); + assert_eq!(shell::sh_quote("~/tools/x"), "'~/tools/x'"); + assert_eq!(shell::sh_quote("a~b"), "'a~b'"); + // Positive control: a word with none of it stays bare. + assert_eq!(shell::sh_quote("pkgs/id"), "pkgs/id"); +} + +#[test] +fn a_single_word_is_a_shell_string_and_several_words_are_quoted() { + assert_eq!( + shell::shell_string(&words(&["cd pkgs/id && cargo test"])), + "cd pkgs/id && cargo test" + ); + assert_eq!( + shell::shell_string(&words(&["echo", "two words", "it's"])), + "echo 'two words' 'it'\\''s'" + ); +} + +fn config() -> fleet_config::Config { + fleet_config::Config::default() +} + +#[test] +fn auto_on_the_laptop_runs_here_without_probing() { + let fake = Fake::new(); + fake.set_env("FLEET_LOCATION", "laptop"); + let (target, because) = shell::resolve(&config(), &fake, "auto", None).unwrap(); + assert_eq!(target, Target::Local); + assert!(because.contains("laptop")); + assert!(fake.calls().is_empty()); +} + +#[test] +fn auto_elsewhere_prefers_the_laptop_then_a_codespace_then_here() { + let fake = Fake::new(); + fake.on("fleet laptop-agent health", vec![ok(json!({"ok": true}))]); + assert_eq!( + shell::resolve(&config(), &fake, "auto", None).unwrap().0, + Target::Laptop + ); + + let fake = Fake::new(); + fake.on("fleet laptop-agent health", vec![fail(3, "no leg answered")]).on( + "gh codespace list", + vec![ok(json!([{"name": "sleepy", "state": "Shutdown"}, {"name": "awake", "state": "Available"}]))], + ); + assert_eq!( + shell::resolve(&config(), &fake, "auto", None).unwrap().0, + Target::Codespace("awake".to_string()), + "a running codespace is preferred over the first listed" + ); + + let fake = Fake::new(); + fake.on( + "fleet laptop-agent health", + vec![fail(3, "no leg answered")], + ) + .on("gh codespace list", vec![fail(1, "HTTP 403")]); + let (target, because) = shell::resolve(&config(), &fake, "auto", None).unwrap(); + assert_eq!(target, Target::Local); + assert!(because.contains("running here"), "{because}"); +} + +#[test] +fn an_explicit_target_is_never_swapped_for_another() { + let fake = Fake::new(); + fake.on( + "fleet laptop-agent health", + vec![fail(3, "no leg answered")], + ); + // Asked for the laptop while it is down: still the laptop, so the caller + // sees the failure instead of a build quietly running in a sandbox. + assert_eq!( + shell::resolve(&config(), &fake, "laptop", None).unwrap().0, + Target::Laptop + ); + assert!(fake.calls().is_empty(), "an explicit target is not probed"); + // Asked for a codespace when there is none: an error, not a fallback. + let fake = Fake::new(); + fake.on("gh codespace list", vec![ok(json!([]))]); + assert!(matches!( + shell::resolve(&config(), &fake, "codespace", None), + Err(AgentError::Down(_)) + )); +} + +#[test] +fn the_environment_can_pin_auto_and_a_bad_pin_is_refused() { + let fake = Fake::new(); + fake.set_env("FLEET_SHELL_TARGET", "local"); + assert_eq!( + shell::resolve(&config(), &fake, "auto", None).unwrap().0, + Target::Local + ); + fake.set_env("FLEET_SHELL_TARGET", "moon"); + assert!(matches!( + shell::resolve(&config(), &fake, "auto", None), + Err(AgentError::Usage(_)) + )); + // An explicit --target wins over the environment. + assert_eq!( + shell::resolve(&config(), &fake, "laptop", None).unwrap().0, + Target::Laptop + ); +} + +#[test] +fn shell_runs_the_plan_or_prints_it() { + let fake = Fake::new(); + fake.set_env("FLEET_LOCATION", "sandbox"); + fake.on("fleet laptop-agent health", vec![ok(json!({"ok": true}))]); + let printed = shell::run( + &config(), + &fake, + &argv(&["--print", "--build", "--", "cargo", "check"]), + ) + .unwrap(); + match printed { + shell::Done::Printed(plan) => { + assert_eq!(plan["target"], "laptop"); + assert_eq!(plan["args"][6], "~/tools/fleet-build-lock cargo check"); + } + shell::Done::Ran(_) => panic!("--print must not run"), + } + assert!(fake.attached.borrow().is_empty()); + let ran = shell::run(&config(), &fake, &argv(&["--", "uname", "-a"])).unwrap(); + assert!(matches!(ran, shell::Done::Ran(0))); + assert_eq!( + fake.attached.borrow().as_slice(), + ["fleet laptop-agent exec --timeout 120 --shell -- uname -a"] + ); + // A word before `--` is a mistake, not a command. + assert!(matches!( + shell::run(&config(), &fake, &argv(&["uname"])), + Err(AgentError::Usage(_)) + )); +} + +proptest! { + /// A quoted word, handed to a real shell, comes back unchanged. + #[test] + fn sh_quote_survives_a_real_shell(word in "[ -~]{0,24}") { + let line = format!("printf '%s' {}", shell::sh_quote(&word)); + let out = std::process::Command::new("sh").arg("-c").arg(&line).output().expect("sh runs"); + prop_assert!(out.status.success(), "sh rejected: {}", line); + prop_assert_eq!(String::from_utf8_lossy(&out.stdout).into_owned(), word); + } +} + +// ---- bounded steps ---- +// +// Oracle: the contract in `capture`'s doc comment, checked against +// the real /bin/sh: an answer in time is passed through whole; no +// answer in time is exit 3 (down) and a line saying how long. + +#[test] +fn a_step_that_answers_in_time_is_passed_through_whole() { + let mut cmd = std::process::Command::new("/bin/sh"); + cmd.args(["-c", "echo out; echo err >&2; exit 4"]); + let out = crate::capture(cmd, "probe", std::time::Duration::from_secs(20)); + assert_eq!(out.code, 4); + assert_eq!(out.stdout, "out\n"); + assert_eq!(out.stderr, "err\n"); +} + +#[test] +fn a_step_that_does_not_answer_in_time_is_down_not_a_hang() { + let mut cmd = std::process::Command::new("/bin/sh"); + cmd.args(["-c", "sleep 30"]); + let started = std::time::Instant::now(); + let out = crate::capture(cmd, "fleet queue health", std::time::Duration::from_secs(1)); + assert!( + started.elapsed() < std::time::Duration::from_secs(10), + "the limit must end the wait, not the child's own 30s" + ); + assert_eq!(out.code, crate::EXIT_DOWN); + assert!(!out.ok()); + assert_eq!(out.stderr, "fleet queue health gave no answer within 1s"); +} + +#[test] +fn a_step_that_cannot_start_says_so() { + let cmd = std::process::Command::new("/nonexistent/fleet-agent-test-binary"); + let out = crate::capture(cmd, "probe", std::time::Duration::from_secs(5)); + assert_eq!(out.code, 127); + assert!( + out.stderr.starts_with("cannot run probe: "), + "{}", + out.stderr + ); +} + +#[test] +fn a_large_output_does_not_block_the_step() { + // More than a pipe buffer: the step must still finish. + let mut cmd = std::process::Command::new("/bin/sh"); + cmd.args(["-c", "head -c 300000 /dev/zero | tr '\\0' 'a'"]); + let out = crate::capture(cmd, "probe", std::time::Duration::from_secs(20)); + assert_eq!(out.code, 0); + assert_eq!(out.stdout.len(), 300_000); +} + +#[test] +fn the_step_limit_is_a_positive_number_of_seconds_or_the_default() { + let default = std::time::Duration::from_secs(crate::DEFAULT_STEP_TIMEOUT_SECS); + assert_eq!(crate::step_limit(None), default); + for junk in ["", "0", "-5", "soon", "1.5"] { + assert_eq!(crate::step_limit(Some(junk)), default, "{junk:?}"); + } + assert_eq!( + crate::step_limit(Some(" 7 ")), + std::time::Duration::from_secs(7) + ); +} diff --git a/pkgs/fleet/crates/fleet-queue/Cargo.toml b/pkgs/fleet/crates/fleet-queue/Cargo.toml index 5aa7bd40f3..b7094def22 100644 --- a/pkgs/fleet/crates/fleet-queue/Cargo.toml +++ b/pkgs/fleet/crates/fleet-queue/Cargo.toml @@ -64,6 +64,11 @@ name = "chunked_list" path = "tests/chunked_list.rs" required-features = ["client"] +[[test]] +name = "person_wait_cli" +path = "tests/person_wait_cli.rs" +required-features = ["client"] + [dev-dependencies] # Property-based tests for the client parser invariants (#5939), diff --git a/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs b/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs index ad8c60d8f3..32936a78c8 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs @@ -825,6 +825,10 @@ pub(super) fn cmd_park(rest: &[String]) -> i32 { "ready-condition", "execution", "required-budget-minutes", + // FDR-0013: a park may wait on a person only as a hands + // item, named by these two flags. + "hands", + "action", ], &[], ); @@ -868,6 +872,28 @@ pub(super) fn cmd_park(rest: &[String]) -> i32 { } body["ready_condition"] = rc; } + // FDR-0013: no park waits on a person to decide. Checked before + // any broker contact; a hands item is stamped onto the progress so + // the row says what a person has to do. + let condition_kind = body["ready_condition"] + .get("kind") + .and_then(|k| k.as_str()) + .map(str::to_string); + let hands_flag = args.get("hands"); + let action_flag = args.get("action"); + match crate::person_wait::check(&crate::person_wait::Wait { + reason_class: None, + condition_kind: condition_kind.as_deref(), + text: &reason, + hands: hands_flag.as_deref(), + action: action_flag.as_deref(), + }) { + Ok(Some(hands)) => { + body["progress"]["hands"] = json!({"kind": hands.kind, "action": hands.action}); + } + Ok(None) => {} + Err(message) => die(2, &format!("park: {message}")), + } // --required-budget-minutes : the minimum remaining shift // budget a future claimer must declare to take this park // (#3418). For a capacity wait the broker defaults it from @@ -1004,6 +1030,10 @@ pub(super) fn cmd_block(rest: &[String]) -> i32 { "blocked-by-ci", "dep-recheck-seconds", "dep-max-ttl-seconds", + // FDR-0013: a block may wait on a person only as a hands + // item, named by these two flags. + "hands", + "action", ], &[], ); @@ -1014,11 +1044,30 @@ pub(super) fn cmd_block(rest: &[String]) -> i32 { let blocker = args .get("blocker") .unwrap_or_else(|| die(2, "block: --blocker is required")); + // FDR-0013: no block waits on a person to decide. Checked before + // any broker contact, so a refused block changes nothing. + let hands_flag = args.get("hands"); + let action_flag = args.get("action"); + let hands = match crate::person_wait::check(&crate::person_wait::Wait { + reason_class: Some(&rc), + condition_kind: None, + text: &blocker, + hands: hands_flag.as_deref(), + action: action_flag.as_deref(), + }) { + Ok(hands) => hands, + Err(message) => die(2, &format!("block: {message}")), + }; // #8568: the needs-drew payload is live only for an // escalated-to-user block that names its ledger item and its - // question; every other block keeps today's shape exactly. + // question; every other block keeps today's shape exactly. A + // hands item's action is the question when none was given, so the + // push says what to do. + let question = args + .get("question") + .or_else(|| hands.as_ref().map(|h| h.action.clone())); let needs_drew = if rc == "escalated-to-user" { - match (args.get("ledger-id"), args.get("question")) { + match (args.get("ledger-id"), question) { (Some(ledger_id), Some(question)) => Some(crate::needs_drew::BlockNeedsDrew { ledger_id, question, @@ -1033,6 +1082,9 @@ pub(super) fn cmd_block(rest: &[String]) -> i32 { None }; let mut progress = progress_arg(&args).unwrap_or(json!({})); + if let Some(hands) = &hands { + progress["hands"] = json!({"kind": hands.kind, "action": hands.action}); + } if let Some(nd) = &needs_drew { // Stamp the ledger id onto the task row through the // progress the CURRENT broker already persists — no diff --git a/pkgs/fleet/crates/fleet-queue/src/client/support.rs b/pkgs/fleet/crates/fleet-queue/src/client/support.rs index 7eaed3677f..a43e754023 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/support.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/support.rs @@ -196,9 +196,9 @@ Run `repo-queue --help` for flags:\n\ bind [--worker ] --session-id [--launched-by ] [--model-provider

] [--model-id ] [--model-variant ]\n\ heartbeat [--worker ] [--extend-seconds ] [--progress

] [--progress-file ]\n\ checkpoint [--worker ] [--stage ] [--progress

] [--progress-file ]\n\ - park [--worker ] --reason [--delay-seconds ] [--not-before ] [--progress

] [--progress-file ] [--ready-condition ] [--execution ] [--required-budget-minutes ]\n\ + park [--worker ] --reason [--delay-seconds ] [--not-before ] [--progress

] [--progress-file ] [--ready-condition ] [--execution ] [--required-budget-minutes ] [--hands --action ]\n\ wake [--worker ] [--reason ]\n\ - block [--worker ] --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 ]\n\ + block [--worker ] --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 ]\n\ unblock [--worker ] [--reason ]\n\ dep-recheck [--task ] [--limit ]\n\ quarantine-recheck [--task ] [--limit ]\n\ @@ -250,13 +250,13 @@ pub(crate) fn usage(verb: &str) -> &'static str { "usage: repo-queue checkpoint [--worker ] [--lane ] [--stage ] [--progress

] [--progress-file ]\n\nRecords a progress checkpoint." } "park" => { - "usage: repo-queue park [--worker ] [--lane ] --reason [--delay-seconds ] [--not-before ] [--progress

] [--progress-file ] [--ready-condition ] [--execution ] [--required-budget-minutes ]\n\nParks a task." + "usage: repo-queue park [--worker ] [--lane ] --reason [--delay-seconds ] [--not-before ] [--progress

] [--progress-file ] [--ready-condition ] [--execution ] [--required-budget-minutes ] [--hands --action ]\n\nParks a task. A park that waits on a person is refused unless it is a hands item (FDR-0013): --hands physical|interactive-login|payment|signature with --action, one sentence a person can do in five minutes." } "wake" => { "usage: repo-queue wake [--worker ] [--reason ]\n\nWakes a parked task." } "block" => { - "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 ]\n\nMarks a task blocked." + "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 ]\n\nMarks a task blocked. A block that waits on a person is refused unless it is a hands item (FDR-0013): --hands physical|interactive-login|payment|signature with --action, one sentence a person can do in five minutes." } "unblock" => { "usage: repo-queue unblock [--worker ] [--reason ]\n\nClears a task's blocked state." diff --git a/pkgs/fleet/crates/fleet-queue/src/lib.rs b/pkgs/fleet/crates/fleet-queue/src/lib.rs index ae14c46ba8..859dd70407 100644 --- a/pkgs/fleet/crates/fleet-queue/src/lib.rs +++ b/pkgs/fleet/crates/fleet-queue/src/lib.rs @@ -37,6 +37,7 @@ pub mod client; pub mod fallback; #[cfg(feature = "client")] pub mod needs_drew; +pub mod person_wait; #[cfg(feature = "client")] pub mod placement; #[cfg(feature = "queue-broker")] diff --git a/pkgs/fleet/crates/fleet-queue/src/person_wait.rs b/pkgs/fleet/crates/fleet-queue/src/person_wait.rs new file mode 100644 index 0000000000..c9c9fe0eb2 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/person_wait.rs @@ -0,0 +1,322 @@ +//! The person-wait guard (FDR-0013; settles FDR-0012 OQ-1). +//! +//! A block or park may wait on a person only as a **hands item**: a +//! step that needs a human body or a login only a person can finish, +//! written as one action. Anything else that would wait on a person is +//! a decision, and a decision is the worker's to make. This module is +//! the check `fleet queue block` and `fleet queue park` run before they +//! contact the broker. +//! +//! What counts as waiting on a person: +//! +//! * a block reason class in [`PERSON_WAIT_CLASSES`]; +//! * a park ready-condition kind in [`PERSON_WAIT_CONDITION_KINDS`]; +//! * a reason or blocker text that names the owner as the release +//! ([`names_owner_wait`]): the ownership handoff FDR-0012 removed, or +//! the owner decision FDR-0013 removes. +//! +//! The text match is deliberately a short list of phrases lanes have +//! actually written. It is not a classifier: a wait it misses is still +//! against the rule, and a real hands item it catches passes by saying +//! so with `--hands` and `--action`. + +/// Block reason classes whose release is a person. +pub const PERSON_WAIT_CLASSES: [&str; 3] = ["escalated-to-user", "drew_decision", "person-answer"]; + +/// Park ready-condition kinds whose release is a person. +pub const PERSON_WAIT_CONDITION_KINDS: [&str; 1] = ["person_answer"]; + +/// What a person's hands can be needed for. +pub const HANDS_KINDS: [&str; 4] = ["physical", "interactive-login", "payment", "signature"]; + +/// An action is one sentence, not a brief. +pub const MAX_ACTION_CHARS: usize = 200; + +/// Phrases that make the owner the release condition. Lowercase. +const OWNER_WAIT_PHRASES: [&str; 18] = [ + "ownership handoff", + "owner handoff", + "owner release", + "awaiting reassignment", + "awaiting owner", + "awaiting drew", + "waiting on drew", + "waiting for drew", + "waiting on the owner", + "waiting for the owner", + "needs drew", + "needs the owner", + "owner decides", + "owner decision", + "drew decides", + "drew decision", + "owner to re-scope", + "owner approval", +]; + +/// The phrase in `text` that names the owner as the release, if any. +pub fn names_owner_wait(text: &str) -> Option<&'static str> { + let lower = text.to_lowercase(); + OWNER_WAIT_PHRASES + .iter() + .find(|phrase| lower.contains(*phrase)) + .copied() +} + +/// One block or park, as far as this check cares. +#[derive(Debug, Clone, Copy, Default)] +pub struct Wait<'a> { + pub reason_class: Option<&'a str>, + pub condition_kind: Option<&'a str>, + /// The blocker or reason text. + pub text: &'a str, + pub hands: Option<&'a str>, + pub action: Option<&'a str>, +} + +/// A hands item that passed: its kind and its action. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Hands { + pub kind: String, + pub action: String, +} + +const WHAT_TO_DO: &str = "A choice is yours to make: decide it, record the decision on the issue, \ +and keep working (FDR-0013; .agents/skills/decide-and-proceed). Only a hands item may wait on a \ +person: add --hands and --action \"\". It blocks this step only; take the next task."; + +/// Check one block or park. +/// +/// `Ok(None)`: it does not wait on a person. `Ok(Some(hands))`: it +/// waits on a person's hands, validly. `Err(message)`: refused; the +/// message says what to do instead. +pub fn check(wait: &Wait) -> Result, String> { + let why = if let Some(class) = wait + .reason_class + .filter(|c| PERSON_WAIT_CLASSES.contains(c)) + { + Some(format!("reason class '{class}'")) + } else if let Some(kind) = wait + .condition_kind + .filter(|k| PERSON_WAIT_CONDITION_KINDS.contains(k)) + { + Some(format!("ready condition '{kind}'")) + } else { + names_owner_wait(wait.text).map(|phrase| format!("the text says \"{phrase}\"")) + }; + let hands = wait.hands.map(str::trim).filter(|h| !h.is_empty()); + let action = wait.action.map(str::trim).filter(|a| !a.is_empty()); + let Some(why) = why else { + return match (hands, action) { + (None, None) => Ok(None), + _ => Err( + "--hands and --action describe a wait on a person: use them with \ + --reason-class escalated-to-user (block) or a person_answer ready condition (park)" + .to_string(), + ), + }; + }; + let (Some(kind), Some(action)) = (hands, action) else { + return Err(format!( + "refusing to wait on a person ({why}). {WHAT_TO_DO}" + )); + }; + if !HANDS_KINDS.contains(&kind) { + return Err(format!( + "--hands '{kind}' is not a hands kind: one of {}", + HANDS_KINDS.join(", ") + )); + } + if action.contains('\n') || action.chars().count() > MAX_ACTION_CHARS { + return Err(format!( + "--action must be one sentence of at most {MAX_ACTION_CHARS} characters: the single \ + thing a person does. If it does not fit, it is a decision, not a hands item." + )); + } + if let Some(phrase) = names_owner_wait(action) { + return Err(format!( + "--action says \"{phrase}\": that asks a person to decide, which is not a hands item. \ + {WHAT_TO_DO}" + )); + } + Ok(Some(Hands { + kind: kind.to_string(), + action: action.to_string(), + })) +} + +#[cfg(test)] +mod tests { + //! Oracle: FDR-0013's decision, rule by rule. Each case states the + //! rule it stands for. + + use super::*; + + fn block<'a>(class: &'a str, text: &'a str) -> Wait<'a> { + Wait { + reason_class: Some(class), + text, + ..Wait::default() + } + } + + #[test] + fn an_ordinary_block_is_not_a_person_wait() { + // Positive control for every refusal below: the guard lets real blocks through. + for (class, text) in [ + ("dependency", "blocked by PR #12061 until it merges"), + ("ci-red", "main is red on id-test; fix is #12140"), + ("capacity", "needs a 90-minute window"), + ] { + assert_eq!(check(&block(class, text)), Ok(None), "{class}: {text}"); + } + } + + #[test] + fn every_person_wait_class_is_refused_without_hands() { + // Rule 2: nothing waits on Drew to decide, approve, confirm or re-scope. + for class in PERSON_WAIT_CLASSES { + let err = check(&block(class, "which encoding should F12.11 use?")).unwrap_err(); + assert!(err.contains("refusing to wait on a person"), "{err}"); + assert!(err.contains(class), "{err}"); + assert!( + err.contains("decide-and-proceed"), + "the refusal says what to do: {err}" + ); + assert!(err.contains("--hands"), "{err}"); + } + } + + #[test] + fn a_person_answer_park_is_refused_without_hands() { + let wait = Wait { + condition_kind: Some("person_answer"), + text: "planning-window confirmation", + ..Wait::default() + }; + assert!( + check(&wait) + .unwrap_err() + .contains("ready condition 'person_answer'") + ); + // A park waiting on something that is not a person is untouched. + let ci = Wait { + condition_kind: Some("ci_green"), + text: "waiting for the nightly", + ..Wait::default() + }; + assert_eq!(check(&ci), Ok(None)); + } + + #[test] + fn text_that_makes_the_owner_the_release_is_refused_whatever_the_class() { + // FDR-0012 OQ-1 and FDR-0013 rule 7: the phrases lanes actually wrote. + for text in [ + "Parked awaiting ownership handoff", + "blocked as packet_defect for the owner to re-scope", + "Next: owner decides whether the remaining items are still wanted", + "needs Drew to confirm the planning window", + "Waiting on Drew", + ] { + let err = check(&block("packet_defect", text)).unwrap_err(); + assert!(err.contains("the text says"), "{text}: {err}"); + } + // "owner" alone is not a wait: an upstream repo has an owner too. + assert_eq!( + check(&block( + "dependency", + "the upstream repo owner merged the fix; waiting for a release" + )), + Ok(None) + ); + } + + #[test] + fn a_hands_item_passes_with_its_kind_and_action() { + // Rule 6: a human body or a login only a person can finish. + let wait = Wait { + reason_class: Some("escalated-to-user"), + text: "codespace surface needs the codespace OAuth scope", + hands: Some("interactive-login"), + action: Some( + "Run `gh auth refresh -s codespace` on the laptop and approve the browser prompt.", + ), + ..Wait::default() + }; + assert_eq!( + check(&wait), + Ok(Some(Hands { + kind: "interactive-login".to_string(), + action: "Run `gh auth refresh -s codespace` on the laptop and approve the browser prompt." + .to_string(), + })) + ); + } + + #[test] + fn hands_must_be_a_known_kind_and_one_short_action() { + let base = |hands, action| Wait { + reason_class: Some("escalated-to-user"), + text: "x", + hands: Some(hands), + action: Some(action), + ..Wait::default() + }; + assert!( + check(&base("decision", "pick one")) + .unwrap_err() + .contains("not a hands kind") + ); + assert!( + check(&base("physical", "plug it in\nthen reboot")) + .unwrap_err() + .contains("one sentence") + ); + let long = "x".repeat(MAX_ACTION_CHARS + 1); + assert!( + check(&base("physical", &long)) + .unwrap_err() + .contains("one sentence") + ); + // Exactly at the limit is fine: the bound is "at most". + let at_limit = "x".repeat(MAX_ACTION_CHARS); + assert!(check(&base("physical", &at_limit)).is_ok()); + // One of the two alone is not a hands item. + let half = Wait { + reason_class: Some("escalated-to-user"), + text: "x", + hands: Some("physical"), + ..Wait::default() + }; + assert!( + check(&half) + .unwrap_err() + .contains("refusing to wait on a person") + ); + } + + #[test] + fn a_decision_cannot_be_dressed_as_a_hands_item() { + let wait = Wait { + reason_class: Some("escalated-to-user"), + text: "x", + hands: Some("interactive-login"), + action: Some("Owner decides which encoding to use"), + ..Wait::default() + }; + assert!(check(&wait).unwrap_err().contains("not a hands item")); + } + + #[test] + fn hands_flags_on_a_wait_that_is_not_a_person_wait_are_a_usage_error() { + let wait = Wait { + reason_class: Some("dependency"), + text: "blocked by PR #1", + hands: Some("physical"), + action: Some("plug it in"), + ..Wait::default() + }; + assert!(check(&wait).unwrap_err().contains("escalated-to-user")); + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/placement.rs b/pkgs/fleet/crates/fleet-queue/src/placement.rs index c80dc321c7..e4033c8e68 100644 --- a/pkgs/fleet/crates/fleet-queue/src/placement.rs +++ b/pkgs/fleet/crates/fleet-queue/src/placement.rs @@ -216,6 +216,14 @@ pub trait Gh { )) }) } + /// The signed-in user's own token, for a surface whose registry + /// entry says `"dispatch_as": "user"`. Dispatching a workflow with + /// a token the fleet already holds is a routine operation + /// (FDR-0013), so a surface the App is not installed on is still + /// usable. None where no user token is available. + fn user_token(&self) -> Option { + None + } fn api(&self, method: &str, path: &str, token: &str, body: Option<&Value>) -> R<(u16, Value)>; /// `gh codespace list --json name,repository,state`, parsed. fn codespace_list(&self) -> R>; @@ -237,6 +245,35 @@ pub trait Gh { struct RealGh { agent: ureq::Agent, tokens: RefCell>, + /// The user's token, looked up at most once per run: a miss is + /// remembered too, so a cascade over several `dispatch_as: user` + /// surfaces does not repeat a slow lookup. + user: RefCell>>, +} + +/// The fleet-secrets name of the `gh` hosts file (the personal leg +/// `fleet gh` uses). +const USER_HOSTS_SECRET: &str = "github-cli.hosts-yml"; + +/// The `oauth_token` value in gh's hosts.yml content. Line-shaped on +/// purpose, like `fleet gh`'s own reader: the file is a small +/// fixed-shape config. +fn hosts_yml_token(hosts_yml: &str) -> Option { + hosts_yml.lines().find_map(|line| { + let rest = line.trim().strip_prefix("oauth_token:")?; + let value = rest.trim().trim_matches('"').trim_matches('\''); + (!value.is_empty()).then(|| value.to_string()) + }) +} + +/// The first usable token out of an ordered list of lookups; a +/// lookup that yields only whitespace counts as a miss. +fn first_token(lookups: &[&dyn Fn() -> Option]) -> Option { + lookups + .iter() + .filter_map(|lookup| lookup()) + .map(|t| t.trim().to_string()) + .find(|t| !t.is_empty()) } impl RealGh { @@ -248,6 +285,7 @@ impl RealGh { .into(); RealGh { agent, + user: RefCell::new(None), tokens: RefCell::new(HashMap::new()), } } @@ -267,6 +305,42 @@ fn home_dir() -> String { } impl Gh for RealGh { + /// Where the user's token comes from, cheapest first: the + /// environment, the seat's own `gh` login, then the fleet secrets + /// chain by name (the same hosts file `fleet gh` reads). The + /// value goes into Authorization headers only. + fn user_token(&self) -> Option { + if let Some(known) = self.user.borrow().as_ref() { + return known.clone(); + } + let from_env = || { + ["GH_TOKEN", "GITHUB_TOKEN"] + .iter() + .filter_map(|k| std::env::var(k).ok()) + .find(|v| !v.trim().is_empty()) + }; + let from_gh = || { + let out = std::process::Command::new("gh") + .args(["auth", "token"]) + .stderr(std::process::Stdio::null()) + .output() + .ok()?; + out.status + .success() + .then(|| String::from_utf8_lossy(&out.stdout).to_string()) + }; + let from_secrets = || { + let config = fleet_config::Config::load().unwrap_or_default(); + let hosts = fleet_secrets::Resolver::default_chain(&config) + .resolve(USER_HOSTS_SECRET) + .ok()?; + hosts_yml_token(hosts.expose()) + }; + let found = first_token(&[&from_env, &from_gh, &from_secrets]); + *self.user.borrow_mut() = Some(found.clone()); + found + } + fn mint_token(&self, repo: &str) -> Option { if let Some(tok) = self.tokens.borrow().get(repo) { return Some(tok.clone()); @@ -370,6 +444,38 @@ fn surf_str<'a>(surface: &'a Value, key: &str) -> &'a str { surface.get(key).and_then(|v| v.as_str()).unwrap_or("") } +/// Whether a surface dispatches with the user's own token instead of +/// the App's installation token (registry field `dispatch_as`). +fn dispatches_as_user(surface: &Value) -> bool { + surf_str(surface, "dispatch_as") == "user" +} + +/// The token a surface's API calls use, when one is available: the +/// user's for a `dispatch_as: user` surface, else the App's. +fn surface_token(surface: &Value, gh: &dyn Gh) -> Option { + if dispatches_as_user(surface) { + gh.user_token() + } else { + gh.mint_token(surf_str(surface, "repo")) + } +} + +/// Why a surface has no token, for an eligibility reason or an error. +fn no_token_reason(surface: &Value) -> String { + let repo = surf_str(surface, "repo"); + if dispatches_as_user(surface) { + format!( + "{repo} dispatches as the user, and no user token is available here \ + (GH_TOKEN, GITHUB_TOKEN or `gh auth token`)" + ) + } else { + format!( + "app token cannot be minted for {repo} \u{2014} surface is \ + unreachable by the App" + ) + } +} + fn surf_targets(surface: &Value) -> Vec { surface .get("targets") @@ -655,6 +761,13 @@ fn base_eligible(surface: &Value, job: &Job) -> (bool, String) { if status != "active" { return (false, format!("surface status is '{status}', not 'active'")); } + let dispatch_as = surf_str(surface, "dispatch_as"); + if !matches!(dispatch_as, "" | "app" | "user") { + return ( + false, + format!("surface dispatch_as is '{dispatch_as}', not 'app' or 'user'"), + ); + } let targets = surf_targets(surface); if !targets.iter().any(|t| t == "*") && !targets.iter().any(|t| t == &job.repo) { return ( @@ -811,7 +924,7 @@ impl GithubActionsAdapter { let s = &self.surface; let repo = surf_str(s, "repo").to_string(); let workflow = surf_str(s, "workflow").to_string(); - let token = gh.app_token(&repo)?; + let token = surface_token(s, gh).ok_or_else(|| Die(no_token_reason(s)))?; let dispatch_id = dispatch_id_for(s); let inputs = self.workflow_inputs(job, dispatch_id.as_deref()); // Correlate the created run with THIS dispatch (Codex P1 @@ -914,7 +1027,7 @@ impl GithubActionsAdapter { } }; let repo = surf_str(&self.surface, "repo"); - let token = match gh.mint_token(repo) { + let token = match surface_token(&self.surface, gh) { Some(t) => t, None => { return session @@ -963,15 +1076,8 @@ impl Adapter for GithubActionsAdapter { // (Codex P2 on PR #8325): live token availability is part // of eligibility, so an inaccessible surface cannot win // the cascade and then abort at dispatch time. - let repo = surf_str(&self.surface, "repo"); - if gh.mint_token(repo).is_none() { - return ( - false, - format!( - "app token cannot be minted for {repo} \u{2014} surface is \ - unreachable by the App" - ), - ); + if surface_token(&self.surface, gh).is_none() { + return (false, no_token_reason(&self.surface)); } (true, "eligible".to_string()) } @@ -1059,15 +1165,8 @@ impl Adapter for BlacksmithAdapter { if job.runner == "github" { return (false, "job pins runner=github".to_string()); } - let repo = surf_str(&self.inner.surface, "repo"); - if gh.mint_token(repo).is_none() { - return ( - false, - format!( - "app token cannot be minted for {repo} \u{2014} surface is \ - unreachable by the App" - ), - ); + if surface_token(&self.inner.surface, gh).is_none() { + return (false, no_token_reason(&self.inner.surface)); } // The budget binds pinned surfaces too (Codex round-4 on // PR #8325): a --surface pin is a placement choice, not a @@ -1338,8 +1437,13 @@ pub fn build_ctx( ) -> Ctx { let owners = registry.get("owners").cloned().unwrap_or(json!({})); let mut hosts: HashMap> = HashMap::new(); + // Host repos whose every API call uses the user's token. + let mut user_repos: std::collections::HashSet = std::collections::HashSet::new(); for s in registry_surfaces(registry) { let kind = surf_str(&s, "kind"); + if dispatches_as_user(&s) { + user_repos.insert(surf_str(&s, "repo").to_string()); + } if (kind == "github-actions" || kind == "blacksmith") && !surf_str(&s, "repo").is_empty() { let repos = hosts.entry(surf_str(&s, "owner").to_string()).or_default(); let repo = surf_str(&s, "repo").to_string(); @@ -1362,11 +1466,16 @@ pub fn build_ctx( let mut running: i64 = 0; let mut queued: i64 = 0; for repo in repos { - let token = match gh.mint_token(repo) { + let minted = if user_repos.contains(repo) { + gh.user_token() + } else { + gh.mint_token(repo) + }; + let token = match minted { Some(t) => t, None => { read_errors.push(format!( - "{repo}: app token unavailable (not covered) — load counted as 0" + "{repo}: no token available (not covered) — load counted as 0" )); continue; } @@ -1593,7 +1702,7 @@ fn refresh_session(store: &mut Value, handle: &str, registry: &Value, gh: &dyn G && ["succeeded", "failed", "cancelled"].contains(&state.as_str()) { let repo = surf_str(surface, "repo").to_string(); - if let Some(token) = gh.mint_token(&repo) { + if let Some(token) = surface_token(surface, gh) { if let Ok((200, run)) = gh.api( "GET", &format!("/repos/{repo}/actions/runs/{}", run_id.unwrap()), @@ -2230,6 +2339,8 @@ mod tests { codespace_items: Vec, codespace_exit: i32, posts: RefCell>, + user_token: Option, + post_tokens: RefCell>, } impl Default for FakeGh { @@ -2244,6 +2355,8 @@ mod tests { codespace_items: Vec::new(), codespace_exit: 0, posts: RefCell::new(Vec::new()), + user_token: None, + post_tokens: RefCell::new(Vec::new()), } } } @@ -2256,14 +2369,18 @@ mod tests { None } } + fn user_token(&self) -> Option { + self.user_token.clone() + } fn api( &self, method: &str, path: &str, - _token: &str, + token: &str, body: Option<&Value>, ) -> R<(u16, Value)> { if method == "POST" { + self.post_tokens.borrow_mut().push(token.to_string()); self.posts .borrow_mut() .push((path.to_string(), body.cloned().unwrap_or(Value::Null))); @@ -3035,4 +3152,153 @@ mod tests { unsafe { std::env::remove_var("FLEET_PLACE_STATE") }; let _ = std::fs::remove_dir_all(&dir); } + + // ---- dispatch_as: user (FDR-0013) ---- + // + // Oracle: the registry field's contract. A surface that says + // `dispatch_as: user` uses the user's token for eligibility and + // dispatch; every other surface keeps the App-only behaviour. + + /// The personal fleet surface, re-declared as a fork the App is + /// not installed on, dispatching as the user. + fn user_surface() -> Value { + let reg = registry(); + let mut surface = find_surface(®, "fleet-personal").unwrap().clone(); + surface["id"] = json!("fleet-forks"); + surface["dispatch_as"] = json!("user"); + surface["app_installation"] = Value::Null; + surface + } + + #[test] + fn hosts_yml_token_reads_the_oauth_token_line() { + // Oracle: gh's hosts.yml shape (a user block carrying + // oauth_token), the same fixture shape `fleet gh` tests use. + let yml = "github.com:\n git_protocol: https\n users:\n someone:\n oauth_token: TOKEN_VALUE\n user: someone\n"; + assert_eq!(hosts_yml_token(yml).as_deref(), Some("TOKEN_VALUE")); + assert_eq!( + hosts_yml_token("oauth_token: \"QUOTED\"\n").as_deref(), + Some("QUOTED") + ); + // An empty value and a file without the line are misses. + assert_eq!(hosts_yml_token("oauth_token:\n"), None); + assert_eq!(hosts_yml_token("github.com:\n user: someone\n"), None); + } + + #[test] + fn first_token_takes_the_first_non_blank_lookup_in_order() { + let none = || None; + let blank = || Some(" \n".to_string()); + let a = || Some(" a-token\n".to_string()); + let b = || Some("b-token".to_string()); + assert_eq!( + first_token(&[&none, &blank, &a, &b]).as_deref(), + Some("a-token") + ); + assert_eq!(first_token(&[&b, &a]).as_deref(), Some("b-token")); + assert_eq!(first_token(&[&none, &blank]), None); + assert_eq!(first_token(&[]), None); + } + + #[test] + fn a_user_dispatch_surface_is_eligible_and_posts_with_the_user_token() { + let surface = user_surface(); + let ad = adapter_for(&surface).unwrap(); + let gh = FakeGh { + // The App cannot mint for this repo at all. + tokens_ok: false, + user_token: Some("user-token".to_string()), + post_runs: vec![json!({ + "id": 4242, + "html_url": "https://github.com/dezren39/fleet/actions/runs/4242", + "created_at": "2026-01-01T00:00:10Z" + })], + ..Default::default() + }; + let c = ctx(&[("dezren39", (0, 0))], 0.0, false); + assert_eq!(ad.eligible(&job(), &c, &gh), (true, "eligible".to_string())); + let result = ad.dispatch(&job(), &gh).unwrap(); + assert_eq!(result.run_id, Some(4242)); + assert_eq!(gh.post_tokens.borrow().as_slice(), ["user-token"]); + } + + #[test] + fn a_user_dispatch_surface_without_a_user_token_is_ineligible_and_says_why() { + let surface = user_surface(); + let ad = adapter_for(&surface).unwrap(); + let gh = FakeGh { + // An App token being available must not rescue it: the + // surface said which token it uses. + tokens_ok: true, + user_token: None, + ..Default::default() + }; + let c = ctx(&[("dezren39", (0, 0))], 0.0, false); + let (ok, why) = ad.eligible(&job(), &c, &gh); + assert!(!ok); + assert!(why.contains("dispatches as the user"), "{why}"); + let err = match ad.dispatch(&job(), &gh) { + Ok(_) => panic!("a surface with no token must not dispatch"), + Err(e) => e, + }; + assert!(err.0.contains("no user token"), "{}", err.0); + assert!(gh.posts.borrow().is_empty()); + } + + #[test] + fn an_app_surface_never_falls_back_to_the_user_token() { + // Positive control for the two tests above: without the + // registry field, a user token changes nothing. + let reg = registry(); + let surface = find_surface(®, "fleet-personal").unwrap().clone(); + let ad = adapter_for(&surface).unwrap(); + let gh = FakeGh { + tokens_ok: false, + user_token: Some("user-token".to_string()), + ..Default::default() + }; + let c = ctx(&[("dezren39", (0, 0))], 0.0, false); + let (ok, why) = ad.eligible(&job(), &c, &gh); + assert!(!ok); + assert!(why.contains("unreachable by the App"), "{why}"); + } + + #[test] + fn an_unknown_dispatch_as_value_is_refused() { + let mut surface = user_surface(); + surface["dispatch_as"] = json!("robot"); + let ad = adapter_for(&surface).unwrap(); + let gh = FakeGh { + user_token: Some("user-token".to_string()), + ..Default::default() + }; + let c = ctx(&[("dezren39", (0, 0))], 0.0, false); + let (ok, why) = ad.eligible(&job(), &c, &gh); + assert!(!ok); + assert!(why.contains("not 'app' or 'user'"), "{why}"); + } + + #[test] + fn load_for_a_user_dispatch_host_is_read_with_the_user_token() { + let mut reg = registry(); + reg["surfaces"] = json!([user_surface()]); + // No user token: the host's load cannot be read, and the + // context says so instead of counting it as zero silently. + let gh = FakeGh { + tokens_ok: true, + user_token: None, + ..Default::default() + }; + let c = build_ctx(®, &json!({}), false, "", None, &gh); + assert_eq!(c.load_read_errors.len(), 1, "{:?}", c.load_read_errors); + assert!(c.load_read_errors[0].contains("dezren39/fleet")); + // With one, the read goes through. + let gh = FakeGh { + tokens_ok: false, + user_token: Some("user-token".to_string()), + ..Default::default() + }; + let c = build_ctx(®, &json!({}), false, "", None, &gh); + assert!(c.load_read_errors.is_empty(), "{:?}", c.load_read_errors); + } } diff --git a/pkgs/fleet/crates/fleet-queue/tests/person_wait_cli.rs b/pkgs/fleet/crates/fleet-queue/tests/person_wait_cli.rs new file mode 100644 index 0000000000..6cf218cd1f --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/tests/person_wait_cli.rs @@ -0,0 +1,220 @@ +//! `repo-queue park` and `block` refuse a wait on a person before the +//! broker is asked (FDR-0013), and let a hands item and an ordinary +//! wait through. +//! +//! Oracle: the rule in `doc/decisions/FDR-0013-no-owner-decision-gates.md` +//! — only a hands item may wait on a person. The fake broker counts +//! connections, so "refused before the broker" is observed, not +//! inferred from the exit code alone. + +use std::io::{Read, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::process::{Command, Output}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::thread; +use std::time::{SystemTime, UNIX_EPOCH}; + +struct FakeBroker { + url: String, + connections: Arc, +} + +/// A broker that answers every request `400` and counts connections. +fn fake_broker() -> FakeBroker { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fake broker"); + let url = format!("http://{}", listener.local_addr().expect("local addr")); + let connections = Arc::new(AtomicUsize::new(0)); + let seen = connections.clone(); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + seen.fetch_add(1, Ordering::SeqCst); + let mut buffer = [0u8; 8192]; + let _ = stream.read(&mut buffer); + let body = br#"{"error":"fake broker"}"#; + let head = format!( + "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(body); + } + }); + FakeBroker { url, connections } +} + +fn isolated_home(tag: &str) -> PathBuf { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock") + .as_nanos(); + let home = std::env::temp_dir().join(format!( + "fleet-person-wait-{tag}-{}-{nanos}", + std::process::id() + )); + std::fs::create_dir_all(&home).expect("create isolated HOME"); + home +} + +fn run(tag: &str, broker: &FakeBroker, args: &[&str]) -> Output { + let home = isolated_home(tag); + let token_file = home.join("broker-token"); + std::fs::write(&token_file, "test-token\n").expect("write fake token"); + let output = Command::new(env!("CARGO_BIN_EXE_repo-queue")) + .args(args) + .env("HOME", &home) + .env("REPO_QUEUE_BROKER_URL", &broker.url) + .env("REPO_QUEUE_TOKEN_FILE", &token_file) + .output() + .expect("run repo-queue"); + let _ = std::fs::remove_dir_all(&home); + output +} + +fn stderr(output: &Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +#[test] +fn block_on_an_owner_class_is_refused_before_the_broker_is_asked() { + let broker = fake_broker(); + let output = run( + "block-refused", + &broker, + &[ + "block", + "42", + "--worker", + "w", + "--lane", + "l", + "--reason-class", + "escalated-to-user", + "--blocker", + "which encoding should this use?", + ], + ); + assert_eq!(output.status.code(), Some(2), "{}", stderr(&output)); + let text = stderr(&output); + assert!(text.contains("refusing to wait on a person"), "{text}"); + assert!(text.contains("FDR-0013"), "{text}"); + assert_eq!(broker.connections.load(Ordering::SeqCst), 0); +} + +#[test] +fn park_whose_reason_waits_on_the_owner_is_refused_before_the_broker_is_asked() { + let broker = fake_broker(); + let output = run( + "park-refused", + &broker, + &[ + "park", + "42", + "--worker", + "w", + "--lane", + "l", + "--reason", + "awaiting owner decision on scope", + "--delay-seconds", + "600", + ], + ); + assert_eq!(output.status.code(), Some(2), "{}", stderr(&output)); + assert!( + stderr(&output).contains("refusing to wait on a person"), + "{}", + stderr(&output) + ); + assert_eq!(broker.connections.load(Ordering::SeqCst), 0); +} + +#[test] +fn a_hands_item_is_let_through_to_the_broker() { + let broker = fake_broker(); + let output = run( + "hands", + &broker, + &[ + "block", + "42", + "--worker", + "w", + "--lane", + "l", + "--reason-class", + "escalated-to-user", + "--blocker", + "the gh login lacks the codespace scope", + "--hands", + "interactive-login", + "--action", + "Run gh auth refresh -s codespace on the laptop and approve the code.", + ], + ); + // The fake broker answers 400, so the verb fails — but for the + // broker's reason, not the guard's. + assert_ne!(output.status.code(), Some(2), "{}", stderr(&output)); + assert!( + !stderr(&output).contains("refusing to wait on a person"), + "{}", + stderr(&output) + ); + assert!(broker.connections.load(Ordering::SeqCst) >= 1); +} + +#[test] +fn a_hands_item_without_its_one_action_is_refused() { + let broker = fake_broker(); + let output = run( + "hands-no-action", + &broker, + &[ + "block", + "42", + "--worker", + "w", + "--lane", + "l", + "--reason-class", + "escalated-to-user", + "--blocker", + "needs a login", + "--hands", + "interactive-login", + ], + ); + assert_eq!(output.status.code(), Some(2), "{}", stderr(&output)); + assert_eq!(broker.connections.load(Ordering::SeqCst), 0); +} + +#[test] +fn an_ordinary_park_is_not_mistaken_for_a_person_wait() { + // Positive control for the refusals above: a wait on CI reaches + // the broker. + let broker = fake_broker(); + let output = run( + "ordinary-park", + &broker, + &[ + "park", + "42", + "--worker", + "w", + "--lane", + "l", + "--reason", + "waiting for CI on the open PR", + "--delay-seconds", + "600", + ], + ); + assert!( + !stderr(&output).contains("refusing to wait on a person"), + "{}", + stderr(&output) + ); + assert!(broker.connections.load(Ordering::SeqCst) >= 1); +} diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index 61b4953217..b2003f3957 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -60,6 +60,11 @@ pub enum Capability { /// fleet mailboxes: central commands one agent, a group or all; /// agents read, answer and ack. Bridge, + /// `fleet agent …` and `fleet shell …` — the agent's front door: + /// enrol an agent of any kind, check what this seat reaches, take + /// the next piece of work down the intake ladder, and run a command + /// where builds belong. Composes the other domains' verbs. + Agent, } impl Capability { @@ -81,6 +86,7 @@ impl Capability { Capability::Secrets => "secrets", Capability::Gh => "gh", Capability::Bridge => "bridge", + Capability::Agent => "agent", } } @@ -101,6 +107,7 @@ impl Capability { Capability::Secrets, Capability::Gh, Capability::Bridge, + Capability::Agent, ]; } @@ -310,6 +317,22 @@ pub const DOMAINS: &[Domain] = &[ "send", "agents", "log", "hello", "inbox", "post", "ack", "health", ], }, + Domain { + name: "agent", + summary: "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 (pushed command, queue, local shortlist, highest priority).", + capabilities: &[Capability::Agent], + primary: Capability::Agent, + aliases: &[], + subcommands: &["kinds", "enroll", "doctor", "next", "shortlist"], + }, + Domain { + name: "shell", + summary: "Run a command, or open a shell, where builds belong: the laptop, a codespace, or here.", + capabilities: &[Capability::Agent], + primary: Capability::Agent, + aliases: &[], + subcommands: &["targets"], + }, Domain { name: "search", summary: "Atlas corpus search over the session history (Snowflake hybrid, via atlas-search).", diff --git a/pkgs/fleet/crates/fleet-secrets/src/lib.rs b/pkgs/fleet/crates/fleet-secrets/src/lib.rs index 8c0dadd6c5..174e3c43a6 100644 --- a/pkgs/fleet/crates/fleet-secrets/src/lib.rs +++ b/pkgs/fleet/crates/fleet-secrets/src/lib.rs @@ -10,7 +10,11 @@ //! token *file* named in the request (the session broker reads it //! per request and sends `X-Agent-Token`; fleet never opens it); //! 2. the **`bws` CLI fallback** — `bws secret list` + `get`, the -//! same shape the secrets broker itself uses to fill its cache. +//! same shape the secrets broker itself uses to fill its cache; +//! 3. the **`op` CLI**, only where a vault is named +//! (`FLEET_OP_VAULT`): `op read op:////`. +//! A seat that keeps its secrets in 1Password resolves the same +//! names without a broker or a Bitwarden token ([`OpSource`]). //! //! Discipline, enforced by the types below: //! * a resolved value lives in [`SecretValue`], whose `Debug` is @@ -307,6 +311,9 @@ impl Resolver { .with_retry_policy(broker_retry), )); sources.push(Box::new(BwsSource::new())); + if let Some(op) = OpSource::from_environment() { + sources.push(Box::new(op)); + } Resolver::new(sources) } @@ -1002,6 +1009,96 @@ impl SecretSource for BwsSource { } } +/// Source 3, opt-in: the 1Password CLI. One read per name: +/// `op read --no-newline op:////`, so the item +/// title in the vault is the fleet secret name. It joins the default +/// chain only where a vault is named, so a seat without 1Password +/// keeps the historical chain exactly. +/// +/// Every `op` failure is `Unavailable`, never `NotFound`: the CLI +/// exits non-zero the same way for a missing item, a locked vault +/// and a signed-out session, and this crate does not read a child's +/// stderr (it could quote vault material) — so absence cannot be +/// told apart from a broken read here. +pub struct OpSource { + vault: String, + field: String, + runner: Box, +} + +impl OpSource { + /// Names the vault; setting it is what turns the source on. + pub const VAULT_ENV: &'static str = "FLEET_OP_VAULT"; + /// Names the item field that holds the value. + pub const FIELD_ENV: &'static str = "FLEET_OP_FIELD"; + /// 1Password's own default field for an API-credential item. + pub const DEFAULT_FIELD: &'static str = "credential"; + + /// The source for a vault and an optional field, or None where + /// no usable vault is named. A vault or field that could not be + /// one path segment of a secret reference turns the source off + /// rather than reading from somewhere unintended. + pub fn from_values( + vault: Option<&str>, + field: Option<&str>, + runner: Box, + ) -> Option { + let vault = vault.map(str::trim).filter(|v| Self::is_segment(v))?; + let field = match field.map(str::trim).filter(|f| !f.is_empty()) { + Some(f) if Self::is_segment(f) => f, + Some(_) => return None, + None => Self::DEFAULT_FIELD, + }; + Some(OpSource { + vault: vault.to_string(), + field: field.to_string(), + runner, + }) + } + + pub fn from_environment() -> Option { + let vault = std::env::var(Self::VAULT_ENV).ok(); + let field = std::env::var(Self::FIELD_ENV).ok(); + Self::from_values(vault.as_deref(), field.as_deref(), Box::new(ProcessRunner)) + } + + fn is_segment(s: &str) -> bool { + !s.is_empty() + && !s + .chars() + .any(|c| c == '/' || c == '?' || c == '#' || c.is_control()) + } + + /// The secret reference `op read` is given for a name. + pub fn reference(&self, name: &str) -> String { + format!("op://{}/{}/{}", self.vault, name, self.field) + } +} + +impl SecretSource for OpSource { + fn source_name(&self) -> &'static str { + "op" + } + + fn resolve(&self, name: &str) -> Result { + validate_name(name)?; + let unavailable = |detail: String| SecretError::Unavailable { + source: "op", + name: name.to_string(), + detail, + }; + let reference = self.reference(name); + let value = self + .runner + .run("op", &["read", "--no-newline", &reference]) + .map_err(|d| unavailable(format!("op read: {d}")))?; + if value.is_empty() { + return Err(unavailable("op read: empty value".to_string())); + } + Ok(SecretValue(value)) + } +} + #[cfg(test)] mod tests { use super::*; @@ -1871,4 +1968,120 @@ mod tests { ); assert_eq!(probe(&BwsTokenRunner::with_token(None)), "unset"); } + + // ---- op (1Password) source ---- + // + // Oracle: the 1Password secret-reference shape + // `op:////` and this crate's own rules + // (an empty value and a failed child are source failures). + + struct OpRunner { + answer: Result, + seen: std::rc::Rc>>>, + } + + impl CommandRunner for OpRunner { + fn run(&self, program: &str, args: &[&str]) -> Result { + assert_eq!(program, "op"); + self.seen + .borrow_mut() + .push(args.iter().map(|a| a.to_string()).collect()); + self.answer.clone() + } + } + + fn op_source( + vault: Option<&str>, + field: Option<&str>, + answer: Result, + ) -> ( + Option, + std::rc::Rc>>>, + ) { + let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let runner = OpRunner { + answer, + seen: seen.clone(), + }; + (OpSource::from_values(vault, field, Box::new(runner)), seen) + } + + #[test] + fn op_reads_one_reference_built_from_vault_name_and_field() { + let (source, seen) = op_source( + Some("fleet"), + None, + Ok("fixture-value-not-a-secret".to_string()), + ); + let source = source.expect("a named vault turns the source on"); + let v = source.resolve("message-bridge.fleet-token").unwrap(); + assert_eq!(v.expose(), "fixture-value-not-a-secret"); + assert_eq!( + seen.borrow().as_slice(), + [vec![ + "read".to_string(), + "--no-newline".to_string(), + "op://fleet/message-bridge.fleet-token/credential".to_string(), + ]] + ); + // A named field replaces the default one. + let (source, _) = op_source(Some("fleet"), Some("password"), Ok("x".to_string())); + assert_eq!(source.unwrap().reference("a.b"), "op://fleet/a.b/password"); + } + + #[test] + fn op_is_off_unless_a_usable_vault_is_named() { + for vault in [None, Some(""), Some(" "), Some("a/b"), Some("a?b")] { + let (source, _) = op_source(vault, None, Ok("x".to_string())); + assert!(source.is_none(), "vault {vault:?} must leave op off"); + } + // A field that is not one path segment turns it off too, + // rather than reading some other field. + let (source, _) = op_source(Some("fleet"), Some("a/b"), Ok("x".to_string())); + assert!(source.is_none()); + // Positive control: surrounding whitespace is not a reason. + let (source, _) = op_source(Some(" fleet "), Some(" "), Ok("x".to_string())); + assert_eq!(source.unwrap().reference("n"), "op://fleet/n/credential"); + } + + #[test] + fn op_failures_and_empty_values_are_unavailable_and_carry_no_value() { + let (source, _) = op_source(Some("fleet"), None, Err("exit status 1".to_string())); + match source.unwrap().resolve("wanted.name") { + Err(SecretError::Unavailable { source, detail, .. }) => { + assert_eq!(source, "op"); + assert_eq!(detail, "op read: exit status 1"); + } + other => panic!("expected Unavailable, got {other:?}"), + } + let (source, _) = op_source(Some("fleet"), None, Ok(String::new())); + match source.unwrap().resolve("wanted.name") { + Err(SecretError::Unavailable { source, .. }) => assert_eq!(source, "op"), + other => panic!("expected Unavailable, got {other:?}"), + } + // A name that is not a valid secret name never reaches op. + let (source, seen) = op_source(Some("fleet"), None, Ok("x".to_string())); + assert!(matches!( + source.unwrap().resolve("bad/name"), + Err(SecretError::InvalidName(_)) + )); + assert!(seen.borrow().is_empty()); + } + + #[test] + fn op_answers_when_the_sources_before_it_cannot() { + let (op, _) = op_source(Some("fleet"), None, Ok("from-op".to_string())); + let resolver = Resolver::new(vec![ + Box::new(FakeSource { + name: "bws", + result: Err(SecretError::Unavailable { + source: "bws", + name: "wanted.name".to_string(), + detail: "bws secret list: spawn failed: NotFound".to_string(), + }), + }), + Box::new(op.unwrap()), + ]); + assert_eq!(resolver.resolve("wanted.name").unwrap().expose(), "from-op"); + } } diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 512c2edcb5..b9d6ab564b 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -32,6 +32,10 @@ fleet-laptop-agent = { workspace = true, optional = true } # The bridge domain: fleet mailboxes on the message bridge (send/receive # for central and agents); a working-seat client, so full only. fleet-bridge = { workspace = true, optional = true } +# The agent domain: the front door that composes the other domains' +# verbs (enroll, doctor, next, shortlist) and `fleet shell`; a +# working-seat client, so full only. +fleet-agent = { workspace = true, optional = true } serde_json = { workspace = true } # The gh domain (code#8887) mints App installation tokens over the # GitHub API; same ureq pin as fleet-queue/fleet-search (rustls, no @@ -66,6 +70,7 @@ full = [ "secrets", "gh", "bridge", + "agent", ] # The serve variant's set, as one feature for the nix build. serve = [ @@ -107,6 +112,10 @@ laptop-agent = ["dep:fleet-secrets", "dep:fleet-laptop-agent"] # Fleet messaging through the message bridge: central sends messages or # commands; agents read, answer and ack. Full only (a client, not a role). bridge = ["dep:fleet-bridge"] +# The agent's front door: enrolment, the intake ladder and `fleet shell`. +# It runs the other domains' verbs through this same binary, so it links +# only fleet-config. Full only. +agent = ["dep:fleet-agent"] [dev-dependencies] # Property tests for the gh read classifier (AGENTS.md testing diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index ac1a884853..ebbf5518f2 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -111,6 +111,9 @@ fn compiled_capabilities() -> CapabilitySet { if cfg!(feature = "bridge") { caps.insert(Capability::Bridge); } + if cfg!(feature = "agent") { + caps.insert(Capability::Agent); + } caps } @@ -396,6 +399,8 @@ fn print_domain_help(surface: &Surface, d: &Domain) { "search" => "included in this build", "proxy" => "included in this build", "bridge" => "included in this build (options: fleet bridge --help)", + "agent" => "included in this build (options: fleet agent --help)", + "shell" => "included in this build (options: fleet shell --help)", "serve" => { "included in this build (queue-broker, secrets-broker, search and proxy roles)" } @@ -872,6 +877,17 @@ fn run_domain(surface: &Surface, d: &Domain, args: &[String], invoked_as: &str) if d.name == "bridge" { return fleet_bridge::run(&surface.config, args); } + // The agent's front door: enrolment, the intake ladder and + // `fleet shell`. Both domains compose the verbs above + // through this same binary. + #[cfg(feature = "agent")] + if d.name == "agent" { + return fleet_agent::run(&surface.config, args); + } + #[cfg(feature = "agent")] + if d.name == "shell" { + return fleet_agent::run_shell(&surface.config, args); + } // Step 5 (#5433): the search domain runs for real — // the atlas-search client surface over the live Atlas // service (full build only; the serve build carries diff --git a/pkgs/fleet/docs/verbs.md b/pkgs/fleet/docs/verbs.md index 0015a274b9..a550bf6771 100644 --- a/pkgs/fleet/docs/verbs.md +++ b/pkgs/fleet/docs/verbs.md @@ -26,51 +26,53 @@ domain is unavailable (capability stub). Client for the repo-queue broker (`crates/fleet-queue/src/client.rs`). -| Verb | Contract | -| --------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| `validate` | Validate a packet without writing it. | -| `enqueue` | Add a packet to the queue. | -| `list` | List items, with filters. | -| `claim` | Claim the highest-priority eligible item for a worker and lane. | -| `release` | Release a claim (requires `--reason`). | -| `lane` | Inspect or set lane state. | -| `bind` | Bind an item to a task reference. | -| `heartbeat` | Extend a claim's lease. | -| `checkpoint` | Record progress and the next action on a claimed item. | -| `park` | Park an item until its delay or a wake. | -| `wake` | Return a parked item to eligible. | -| `block`, `unblock` | Mark an item blocked with a reason class, or clear it. | -| `dep-recheck` | Re-evaluate dependency edges. | -| `quarantine-recheck` | Re-evaluate quarantined items. | -| `cancel` | Cancel an item. | -| `revive` | Reopen a failed or cancelled item. | -| `fail` | Mark a claimed item failed, with a reason class. | -| `complete` | Mark a claimed item done with a structured result. | -| `verify-disposition` | Verify a recorded disposition. | -| `timeline`, `history` | Event timeline for one item (same handler). | -| `models` | Model catalog and pool information. | -| `health` | Broker health and per-queue counts. | -| `signal` | Send a signal to a worker or item. | -| `fallback` | `scan`, `status`, `claim`, `heartbeat`, `release` (fallback mode). | -| `dispatch` | `status`, `launch`, `enqueue` (`placement.rs`). | -| `session` | Placement session commands. | -| `surfaces` | Print the placement surface registry (`pkgs/fleet/fleet-surfaces.json`) as JSON. Read-only; takes `[--registry PATH]`. | -| `outbox` | Creation outbox group. | -| `stack` | Stack group. | +| Verb | Contract | +| --------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `validate` | Validate a packet without writing it. | +| `enqueue` | Add a packet to the queue. | +| `list` | List items, with filters. | +| `claim` | Claim the highest-priority eligible item for a worker and lane. | +| `release` | Release a claim (requires `--reason`). | +| `lane` | Inspect or set lane state. | +| `bind` | Bind an item to a task reference. | +| `heartbeat` | Extend a claim's lease. | +| `checkpoint` | Record progress and the next action on a claimed item. | +| `park` | Park an item until its delay or a wake. A wait on a person is refused unless it is a hands item (`--hands`, `--action`). | +| `wake` | Return a parked item to eligible. | +| `block`, `unblock` | Mark an item blocked with a reason class, or clear it. The same hands rule as `park` applies to `block`. | +| `dep-recheck` | Re-evaluate dependency edges. | +| `quarantine-recheck` | Re-evaluate quarantined items. | +| `cancel` | Cancel an item. | +| `revive` | Reopen a failed or cancelled item. | +| `fail` | Mark a claimed item failed, with a reason class. | +| `complete` | Mark a claimed item done with a structured result. | +| `verify-disposition` | Verify a recorded disposition. | +| `timeline`, `history` | Event timeline for one item (same handler). | +| `models` | Model catalog and pool information. | +| `health` | Broker health and per-queue counts. | +| `signal` | Send a signal to a worker or item. | +| `fallback` | `scan`, `status`, `claim`, `heartbeat`, `release` (fallback mode). | +| `dispatch` | `status`, `launch`, `enqueue` (`placement.rs`). | +| `session` | Placement session commands. | +| `surfaces` | Print the placement surface registry (`pkgs/fleet/fleet-surfaces.json`) as JSON. Read-only; takes `[--registry PATH]`. | +| `outbox` | Creation outbox group. | +| `stack` | Stack group. | ## Other domains -| Domain and verb | Contract | -| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | -| `serve` | Serve role (`fleet-serve`). | -| `proxy serve`, `connect`, `init`, `ssh`, `splice`, `get`, `put` | Proxy leaves. `connect` takes connection flags; `put` takes mode and no-resume flags. | -| `dispatch status`, `launch`, `enqueue` | Dispatch status, launch a run, enqueue work (`crates/fleet-dispatch`). | -| `dispatch-test scan`, `submit`, `status` | Test-dispatch scan, submit and status (`crates/fleet-dispatch-test`). | -| `secrets get`, `list` | Secret lookup and listing. | -| `gh `, `tiers`, `cache-serve`, `cache-status`, `--raw` | Pass-through to `gh`; tier information; cache serve and status. | -| `bridge send`, `agents`, `log`, `hello`, `inbox`, `post`, `ack`, `health` | Fleet mailboxes on the message bridge: central sends; agents read, answer and ack. | -| `search search`, `get-chunk` | Search the index and fetch a chunk. The `serve` alias is also accepted. | -| `laptop-agent health`, `jobs`, `kill`, `exec`, `run`, `poll`, `fetch` | Laptop-agent broker operations. | +| Domain and verb | Contract | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `serve` | Serve role (`fleet-serve`). | +| `proxy serve`, `connect`, `init`, `ssh`, `splice`, `get`, `put` | Proxy leaves. `connect` takes connection flags; `put` takes mode and no-resume flags. | +| `dispatch status`, `launch`, `enqueue` | Dispatch status, launch a run, enqueue work (`crates/fleet-dispatch`). | +| `dispatch-test scan`, `submit`, `status` | Test-dispatch scan, submit and status (`crates/fleet-dispatch-test`). | +| `secrets get`, `list` | Secret lookup and listing. Chain: the broker, `bws`, then `op` where `FLEET_OP_VAULT` names a vault. | +| `gh `, `tiers`, `cache-serve`, `cache-status`, `--raw` | Pass-through to `gh`; tier information; cache serve and status. | +| `bridge send`, `agents`, `log`, `hello`, `inbox`, `post`, `ack`, `health` | Fleet mailboxes on the message bridge: central sends; agents read, answer and ack. | +| `search search`, `get-chunk` | Search the index and fetch a chunk. The `serve` alias is also accepted. | +| `laptop-agent health`, `jobs`, `kill`, `exec`, `run`, `poll`, `fetch` | Laptop-agent broker operations. | +| `agent kinds`, `enroll`, `doctor`, `next`, `shortlist` | The agent's front door: enrol any kind of agent, check what the seat reaches, take the next task down the intake ladder. | +| `shell [-- command]`, `shell targets` | Run a command or open a shell on the laptop, a codespace or here; `--build` takes a build slot. | Note: `scripts/fleet` is a directory of helper scripts, not the multicall binary. diff --git a/pkgs/fleet/fleet-surfaces.json b/pkgs/fleet/fleet-surfaces.json index 193d015082..52bef973fa 100644 --- a/pkgs/fleet/fleet-surfaces.json +++ b/pkgs/fleet/fleet-surfaces.json @@ -1,5 +1,5 @@ { - "comment": "Fleet placement surface registry (docs/placement.md). Adding a location = adding an entry here (+ app installation + a fleet copy). The dispatcher core (tools/fleet-place) reads ONLY this file for what exists; kinds map to adapters in the dispatcher. Limits source: GitHub Actions limits reference, https://docs.github.com/en/actions/reference/limits (verified 2026-11-04): concurrent GitHub-hosted jobs per account Free 20 / Pro 40 / Team 60 / Enterprise 500 (macOS subset 5 / 5 / 5 / 50); included private-repo minutes per month Free 2000 / Pro 3000 / Team 3000 / Enterprise 50000; public repositories: minutes unlimited on every plan, so for public targets the binding limit is the concurrency cap, not minutes.", + "comment": "Fleet placement surface registry (docs/placement.md). Adding a location = adding an entry here (+ a fleet copy, and either an app installation or \"dispatch_as\": \"user\" where the fleet's GitHub user can start workflows on the copy). The dispatcher core (tools/fleet-place) reads ONLY this file for what exists; kinds map to adapters in the dispatcher. Limits source: GitHub Actions limits reference, https://docs.github.com/en/actions/reference/limits (verified 2026-11-04): concurrent GitHub-hosted jobs per account Free 20 / Pro 40 / Team 60 / Enterprise 500 (macOS subset 5 / 5 / 5 / 50); included private-repo minutes per month Free 2000 / Pro 3000 / Team 3000 / Enterprise 50000; public repositories: minutes unlimited on every plan, so for public targets the binding limit is the concurrency cap, not minutes.", "laptop": { "busy": false, "busy_source": "manual-flag", @@ -46,12 +46,13 @@ }, { "app_installation": 174792676, + "dispatch_as": "user", "id": "fleet-org", "kind": "github-actions", - "notes": "Org fork of dezren39/fleet (created 2026-11-04). Actions are enabled at repo level, but the developing-today app installation is repository-selected and does not yet include this repo (API add refused 403; org-owner GUI grant filed under GRANTS NEEDED in the placement report). Ineligible for app dispatch until covered. Also needs repo secrets (GHCR_ORG_PAT for cross-repo checkout; NIX_CACHE_* for cache pushes) before non-trivial jobs.", + "notes": "Org fork of dezren39/fleet (created 2026-11-04). Dispatches with the user's own token (dispatch_as: user): the fleet's GitHub user is an admin of this repo, so no App installation is needed to start a workflow. Repo secrets are provisioned (GHCR_ORG_PAT, CACHIX_AUTH_TOKEN, NIX_CACHE_SIGNING_KEY, NIX_CACHE_UPLOAD_URL). Verified 2026-11-21 by a real dispatch: run 44900088840 succeeded on ubuntu-24.04. This copy's fleet-run.yml has diverged from upstream (it carries the cache options and the anonymous-checkout fallback; upstream carries dispatch_id and setup_runner), so its daily sync-upstream fails on a merge conflict and it declares no dispatch_id input here: runs are correlated by the snapshot fallback until the copies converge.", "owner": "developing-today", "repo": "developing-today/fleet", - "status": "pending-app-coverage", + "status": "active", "targets": [ "developing-today/code", "developing-today/opencode", @@ -63,17 +64,18 @@ }, { "app_installation": null, + "dispatch_as": "user", + "dispatch_id_input": true, "id": "fleet-forks", "kind": "github-actions", - "notes": "Third copy of the umbrella, in the forks org (stood up 2026-11-04; Drew is org admin). Absorbed as registry DATA only - no dispatcher change; the live extensibility proof. The developing-today app is NOT installed on developing-today-forks, so this surface is ineligible-app-missing until that grant lands (GRANTS NEEDED); no user-token fallback, per the app-only rule.", + "notes": "Third copy of the umbrella, in the forks org (stood up 2026-11-04). Dispatches with the user's own token (dispatch_as: user): the fleet's GitHub user is an admin of this repo. Synced to upstream head 72049ac on 2026-11-21 (sync-upstream run 44900085581), so it carries the dispatch_id input. Verified 2026-11-21 by a real dispatch: run 44900259404 succeeded on ubuntu-24.04 against developing-today/code. This copy has no GHCR_ORG_PAT secret, so its targets are public repos only; cache pushes need the NIX_CACHE_* secrets and are not available here.", "owner": "developing-today-forks", "repo": "developing-today-forks/fleet", - "status": "pending-app-installation", + "status": "active", "targets": [ "developing-today/code", "developing-today/opencode", "developing-today/openchamber", - "dezren39/darwin-nix", "dezren39/fleet" ], "workflow": "fleet-run.yml" @@ -104,13 +106,14 @@ "paid_cap_minutes": 0, "rate_note": "Blacksmith is orgs-only: 3,000 free min/mo, then PAID per-minute (it charges for public-repo minutes past the free tier). paid_cap_minutes is the registry knob Drew can raise; 0 = free tier only." }, + "dispatch_as": "user", "host_surface": "fleet-org", "id": "fleet-org-blacksmith", "kind": "blacksmith", - "notes": "Blacksmith variant of the org fork's fleet-run (runner input = blacksmith, label blacksmith-4vcpu-ubuntu-2404). Blacksmith app (blacksmith-sh, id 807020) VERIFIED installed on the developing-today org with repository_selection=all (2026-11-04). Org surfaces only \u2014 never the personal copy (provider is orgs-only). Inherits fleet-org's app-coverage blocker.", + "notes": "Blacksmith variant of the org fork's fleet-run (runner input = blacksmith, label blacksmith-4vcpu-ubuntu-2404). Blacksmith app (blacksmith-sh, id 807020) installed on the developing-today org with repository_selection=all. Org surfaces only \u2014 never the personal copy (provider is orgs-only). Dispatches with the user's own token, like its host surface fleet-org. Verified 2026-11-21 by a real dispatch: run 44900255411 ran its leg on a blacksmith-4vcpu-ubuntu-2404 runner and succeeded.", "owner": "developing-today", "repo": "developing-today/fleet", - "status": "pending-app-coverage", + "status": "active", "targets": [ "developing-today/code", "developing-today/opencode", diff --git a/pkgs/fleet/smoke.sh b/pkgs/fleet/smoke.sh index 28e1e9990c..319c6f085a 100755 --- a/pkgs/fleet/smoke.sh +++ b/pkgs/fleet/smoke.sh @@ -75,7 +75,7 @@ run() { ok "$name" } -FULL_CAPS="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" +FULL_CAPS="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" SERVE_CAPS="Enabled capabilities: proxy-connect, proxy-serve, proxy-raw-splice, queue-broker, secrets-broker, search-serve, secrets" CONNECT_CAPS="Enabled capabilities: proxy-connect" @@ -111,6 +111,10 @@ run "serve: fleet dispatch stubs" 69 "this build does not include 'dispatch'" \ "$SERVE_OUT/bin/fleet" dispatch run "serve: fleet laptop-agent stubs" 69 "this build does not include 'laptop-agent'" \ "$SERVE_OUT/bin/fleet" laptop-agent +run "serve: fleet agent stubs" 69 "this build does not include 'agent'" \ + "$SERVE_OUT/bin/fleet" agent +run "serve: fleet shell stubs" 69 "this build does not include 'shell'" \ + "$SERVE_OUT/bin/fleet" shell run "serve: fleet search (client) stubs — serve carries search-serve only" 69 \ "this build does not include 'search'" \ "$SERVE_OUT/bin/fleet" search @@ -868,6 +872,14 @@ run "full with queue=false: fleet queue stubs as disabled" 69 "disabled by confi run "full with queue=false: version drops queue capabilities" 0 "proxy-raw-splice, queue-broker" \ env FLEET_CONFIG="$TMP/fleet.toml" "$FULL_OUT/bin/fleet" version +echo "== agent domain and fleet shell: plans and refusals that need no network ==" +run "full: fleet agent kinds lists the kinds" 0 '"kind": "muse"' "$FULL_OUT/bin/fleet" agent kinds +run "full: fleet shell --print plans and runs nothing" 0 '"target": "local"' \ + env FLEET_SHELL_TARGET=local "$FULL_OUT/bin/fleet" shell --print -- true +run "full: fleet agent refuses an unknown verb" 2 "-" "$FULL_OUT/bin/fleet" agent frobnicate +run "full: a wait on a person is refused before the broker is asked" 2 "refusing to wait on a person" \ + "$FULL_OUT/bin/fleet" queue block 1 --worker w --lane l --reason-class escalated-to-user --blocker "which one?" + echo "== runs anywhere: env -i ==" run "connect dynamic under env -i" 0 "$CONNECT_CAPS" env -i "$CONNECT_OUT/bin/fleet" version run "connect static under env -i" 0 "$CONNECT_CAPS" env -i "$STATIC_OUT/bin/fleet" version diff --git a/planning/plans/2026-11-21_results-first.md b/planning/plans/2026-11-21_results-first.md index 086b68e023..1b1962da8d 100644 --- a/planning/plans/2026-11-21_results-first.md +++ b/planning/plans/2026-11-21_results-first.md @@ -36,33 +36,38 @@ Two `id` tracks, three fleet changes, one rule for decisions. ### Done (checked against GitHub on 2026-11-21) -| What | Evidence | -| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Path to Phase 12: all 14 ordered steps | #1235 closed 2026-11-08 | -| Validation audits, Phases 0–11 | #1075, #1076, #1077, #1078 closed 2026-10-27 | -| Phase 11 foundations | Every F11 issue in the [`id` roadmap's tracker table](../roadmaps/id.md) is closed | -| Phase 12: 14 of 18 items | Closed: F12.1 #807, F12.2 #556, F12.3 #835, F12.4 #1061, F12.6 #1063, F12.7 #1064, F12.8 #1065, F12.9 #1066, F12.13 #806, F12.14 #1068, F12.15 #558, F12.16 #559, F12.17 #1069, F12.18 #560 | -| Phase 13: 5 of 8 items | Closed: F13.1 #783, F13.2 #784, F13.3 #785, F13.7 #789, F13.8 #790 | -| `pkgs/id` split into 14 crates | #3447 closed 2026-11-13; `pkgs/id/crates/` holds 14 members | -| Phase 14 decided, first designs written | Plan of record #6312; v1 designs closed for hosted worlds #6283, discovery #6287, ecosystem #6291, shells #6296, creator tooling #6308 | -| #9106 summit design agreed | PR #9238 merged 2026-11-13; 384 statements mapped to 126 issue rows | -| #9106 first library code | `id-core`, `id-sync` and `id-store` PRs merged 2026-11-16 to 2026-11-19 (for example #11939, #11947, #11988) | -| One fleet queue, unfiltered claims | PR #8438 merged 2026-11-11; FDR-0001 to FDR-0012 in `doc/decisions/` | -| Self-mirroring of this repo's issues stopped | #11748 merged 2026-11-18, after 299 copies were filed in two days | -| Roadmap drift found in this review, fixed | This plan's PR: `ROADMAP.md`, `planning/roadmaps/id.md`, `planning/plans/README.md` | -| Scoreboard tool, three skills | This plan's PR: `scripts/fleet/flow-report/`, `.agents/skills/next-work`, `feature-slice`, `decide-and-proceed` | +| What | Evidence | +| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Path to Phase 12: all 14 ordered steps | #1235 closed 2026-11-08 | +| Validation audits, Phases 0–11 | #1075, #1076, #1077, #1078 closed 2026-10-27 | +| Phase 11 foundations | Every F11 issue in the [`id` roadmap's tracker table](../roadmaps/id.md) is closed | +| Phase 12: 14 of 18 items | Closed: F12.1 #807, F12.2 #556, F12.3 #835, F12.4 #1061, F12.6 #1063, F12.7 #1064, F12.8 #1065, F12.9 #1066, F12.13 #806, F12.14 #1068, F12.15 #558, F12.16 #559, F12.17 #1069, F12.18 #560 | +| Phase 13: 5 of 8 items | Closed: F13.1 #783, F13.2 #784, F13.3 #785, F13.7 #789, F13.8 #790 | +| `pkgs/id` split into 14 crates | #3447 closed 2026-11-13; `pkgs/id/crates/` holds 14 members | +| Phase 14 decided, first designs written | Plan of record #6312; v1 designs closed for hosted worlds #6283, discovery #6287, ecosystem #6291, shells #6296, creator tooling #6308 | +| #9106 summit design agreed | PR #9238 merged 2026-11-13; 384 statements mapped to 126 issue rows | +| #9106 first library code | `id-core`, `id-sync` and `id-store` PRs merged 2026-11-16 to 2026-11-19 (for example #11939, #11947, #11988) | +| One fleet queue, unfiltered claims | PR #8438 merged 2026-11-11; FDR-0001 to FDR-0012 in `doc/decisions/` | +| Self-mirroring of this repo's issues stopped | #11748 merged 2026-11-18, after 299 copies were filed in two days | +| Roadmap drift found in this review, fixed | This plan's PR: `ROADMAP.md`, `planning/roadmaps/id.md`, `planning/plans/README.md` | +| Scoreboard tool, three skills | This plan's PR: `scripts/fleet/flow-report/`, `.agents/skills/next-work`, `feature-slice`, `decide-and-proceed` | +| Agent front door: `fleet agent`, `fleet shell` | #12227: enrol any kind of agent; `fleet agent next` walks push, queue, shortlist, priority; `fleet shell` runs builds on the laptop or a codespace. [Design](../../doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md) | +| Queue refuses waits on a person | #12227: `fleet queue park` and `block` exit 2 unless the wait is a hands item; 13 tests, 5 of them against the real binary | +| Three more build surfaces in rotation | #12227: `fleet-org`, `fleet-org-blacksmith` and `fleet-forks` dispatch as the user; proven by runs 44900088840, 44900255411 and 44900259404 on 2026-11-21 | +| GitHub agrees with this plan (step 0) | Tracker #12238; ten issues filed (#12228 to #12237); `now` and `next` re-set to the order below; five duplicate door reports closed into #12228; #9112 closed with its decision | +| Dashboard separates hands items from agent parks | #12227: the attention page and the digest count only hands items and review requests as needing the owner; agent parks are listed as fleet work | "Closed" in this table means the issue is closed as completed. It does not mean the phase's exit test passes; see [Track A](#track-a-close-phase-12-and-tag-idv0120). ### Now -| Track or step | Exit test | State on 2026-11-21 | -| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| **F1** `id` gate before merge | `id` main-broken issues at 3 a week or fewer for two weeks | No gate. 43 `id` main-broken issues in the last 7 days. Design not written. | -| **F2** Feature slices in the queue; no repeat triage | A large issue triaged once is never triaged again without a change; a `feature_slice` packet is claimed and lands a PR | Not started. Skills `feature-slice` and `next-work` cover the worker side now. | -| **A** Close Phase 12, tag `id/v0.12.0` | All nine rows of the Phase 12 exit table recorded as met, each with a command and its output; release tagged | 4 items open: #1062, #1067, #805, #557. No exit audit. No `id` release has been tagged. | -| **B** One end-to-end slice of #9106 | A two-node test: signed record written by `id://` address on A, synced to B, a conflicting write reported; CLI shows it | Library modules merged; nothing under `crates/id-cli/src` or `pkgs/id/src` mentions `IdUri`. | -| **F4** No work waits on the owner | Open `user/escalated` issues that are not a hands item: 0 | 108 open. Rule and skill landed (FDR-0013, `decide-and-proceed`); the queue guard is in the fleet-agent PR. | +| Track or step | Exit test | State on 2026-11-21 | +| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **F1** `id` gate before merge (#12229, #12230) | `id` main-broken issues at 3 a week or fewer for two weeks | No gate. 43 `id` main-broken issues in the last 7 days. Design not written. | +| **F2** Feature slices in the queue; no repeat triage (#12233) | A large issue triaged once is never triaged again without a change; a `feature_slice` packet is claimed and lands a PR | Large issues now reach agents as slice tasks through the shortlist and priority rungs of `fleet agent next`. The queue kind and the repeat-triage fix are not started. | +| **A** Close Phase 12, tag `id/v0.12.0` (#12231) | All nine rows of the Phase 12 exit table recorded as met, each with a command and its output; release tagged | 4 items open: #1062, #1067, #805, #557. No exit audit. No `id` release has been tagged. | +| **B** One end-to-end slice of #9106 (#12232) | A two-node test: signed record written by `id://` address on A, synced to B, a conflicting write reported; CLI shows it | Library modules merged; nothing under `crates/id-cli/src` or `pkgs/id/src` mentions `IdUri`. | +| **F4** No work waits on the owner (#12234) | Open `user/escalated` issues that are not a hands item: 0 | 108 open on 2026-11-21. The rule, the skill and the queue guard have landed; the Now-track issues are cleared. The rest are worked through the priority rung, which hands them out as ready work. | ### Next (starts when a Now track passes its exit test) @@ -75,7 +80,7 @@ Two `id` tracks, three fleet changes, one rule for decisions. ### Later (kept, with the trigger that starts each) -Nothing here is dropped. In-flight PRs in these lines are shepherded to merge or closed with a salvage note; no new slice starts until the trigger fires or Drew moves the row. +Nothing here is dropped. In-flight PRs in these lines are shepherded to merge or closed with a salvage note; no new slice starts until the trigger fires or the row is moved in this plan. | Line | Trigger | Entry issues | | ----------------------------------------- | ----------------------------------------------------------- | ----------------------------------- | @@ -88,7 +93,7 @@ Nothing here is dropped. In-flight PRs in these lines are shepherded to merge or | Spill v2 | F12.12 target met | #7572, #7573, #7574 | | Android, ESP32, Bevy, native GUI and TUI | Phase 13 native shell (#788) landed | #7938, #5783, #5781, #1071, #1072 | | Phase 14 v2 to v4 outlines | The matching v1 is implemented | The open outlines under #6312 | -| Crate splits outside `pkgs/id` | Owner order | #8977, #8954 to #8969 | +| Crate splits outside `pkgs/id` | A Now or Next item needs the split | #8977, #8954 to #8969 | | New fleet and PM-stack features | Names the scoreboard row it moves (rule F6) | #1184, #1340, #1352 | ## Evidence @@ -188,7 +193,7 @@ Each step is one PR unless it says otherwise. ### Step 0: ratify and wire -0. **Make GitHub and the queue agree with this plan.** File one epic with the steps below as children; set `now`, `next` and `priority/*` labels in the order of the [Status board](#status-board); remove `user/escalated` and `status/blocked` from the Now rows' issues with the decision recorded on each. Queue bands follow from the labels at the next reconcile. Done when: every Now row links an open issue that carries `now` and no owner-wait label. +0. **Done 2026-11-21 (tracker #12238).** **Make GitHub and the queue agree with this plan.** File one epic with the steps below as children; set `now`, `next` and `priority/*` labels in the order of the [Status board](#status-board); remove `user/escalated` and `status/blocked` from the Now rows' issues with the decision recorded on each. Queue bands follow from the labels at the next reconcile. Done when: every Now row links an open issue that carries `now` and no owner-wait label. ### Fleet @@ -211,7 +216,7 @@ Each step is one PR unless it says otherwise. 14. **A2. F12.12 profile (#557).** Before any fix: where the 5.65 seconds go at 100 worlds and 20 events a second, as a committed profile and the command that produced it. Done when: the profile names the top three costs with their share of p99. 15. **A3. F12.12 fixes (#557).** One PR per cost from A2, each with a before and after number. Done when: the benchmark reports p99 under 50 ms, or the profile shows the target is wrong and the worker records a new one with that profile as its reason. 16. **A4. F12.10 fair scheduling (#1067).** The scheduler and per-account quotas, in slices; the `fuel_spin_isolation` workload already exists (PR #8322). Done when: a spinning world raises another world's p99 by no more than 10% in that benchmark. -17. **A5. F12.11 decisions, then delta frames (#805).** A decision request for each of the four choices (binary encoding, compression, resume tokens, bandwidth target) with defaults drawn from the F11.9 baseline; then the patch encoding and the parity test. Done when: a typical redraw is under 10% of the full frame and a patched client equals a full-frame client. +17. **A5. Delta frames, phase 3 on (#805).** Both open design questions were decided on 2026-11-21 as the design record recommends (D9). Next is the negotiated MessagePack representation with its parity test, then compression where the compressed frame is smaller. Done when: a typical redraw is under 10% of the full frame and a patched client equals a full-frame client. 18. **A6. F12.5 providers (#1062), inward-facing first.** `kv`, then `blob`; `http.fetch` and `notify` after, each off by default with a refusal test. Done when: each provider has bound, refusal and replay tests, and an unlisted host is refused. 19. **A7. Third guest language: Zig.** A Zig toolchain is already in the tree for the Roc host. Done when: the Zig SDK passes the conformance suite and ships a playable example. 20. **A8. Verification debt (#796).** Each inventory item gets a proving test or its own issue. Done when: #796's checklist is complete. @@ -240,16 +245,20 @@ Four, each needed by a Now step. No other design is asked for. Made on 2026-11-21 by the session that wrote this plan. None waits on anyone. Each is revisable by a later PR with evidence; none needs a confirmation. -| # | Decided | Why | Undo | -| --- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------- | -| D1 | Tracks A and B are the active `id` lines; the rest wait in Later with the triggers above | 14 of 18 Phase 12 items are closed, and the #9106 library code has nothing reaching it | Move a row | -| D2 | A `pkgs/id` change is tested before it merges, through a batched gate on the fleet's build host | `id` broke main 43 times in 7 days; batching answers the cost that made hosted PR checks unaffordable | Turn the gate off; nightly CI is unchanged | -| D3 | The third guest language for F12.8 is Zig | A Zig toolchain is already in the tree for the Roc host (`pkgs/id/examples/roc-world/host/build.zig`) | Add another SDK | -| D4 | F12.12 keeps its p99 target of 50 ms until the A2 profile shows where the time goes | A target changed before the measurement is a guess | Record a new target with the profile | -| D5 | #9112's delivered 39-component sequence and its dependencies stand as recorded | The sequence was delivered on 2026-11-19 and nothing in it was disputed | Re-order rows on #9112 | -| D6 | While `id` main-broken is above 3 a week, creator runs file hardening bugs only in active tracks' crates | 505 of 639 `id` bug issues came from the creator; they compete with the tracks for the same lanes | Drop the rule from the creator's instructions | -| D7 | An open large issue with a recorded verdict is covered by a parked task with a resume condition | Re-triaging it hourly produced four verdicts and no code on #1062 | Revert the reconciler change | -| D8 | The first release is `id/v0.12.0` | Matches `mcpx/v0.1.0` | Tag again | +| # | Decided | Why | Undo | +| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| D1 | Tracks A and B are the active `id` lines; the rest wait in Later with the triggers above | 14 of 18 Phase 12 items are closed, and the #9106 library code has nothing reaching it | Move a row | +| D2 | A `pkgs/id` change is tested before it merges, through a batched gate on the fleet's build host | `id` broke main 43 times in 7 days; batching answers the cost that made hosted PR checks unaffordable | Turn the gate off; nightly CI is unchanged | +| D3 | The third guest language for F12.8 is Zig | A Zig toolchain is already in the tree for the Roc host (`pkgs/id/examples/roc-world/host/build.zig`) | Add another SDK | +| D4 | F12.12 keeps its p99 target of 50 ms until the A2 profile shows where the time goes | A target changed before the measurement is a guess | Record a new target with the profile | +| D5 | #9112's delivered 39-component sequence and its dependencies stand as recorded | The sequence was delivered on 2026-11-19 and nothing in it was disputed | Re-order rows on #9112 | +| D6 | While `id` main-broken is above 3 a week, creator runs file hardening bugs only in active tracks' crates | 505 of 639 `id` bug issues came from the creator; they compete with the tracks for the same lanes | Drop the rule from the creator's instructions | +| D7 | An open large issue with a recorded verdict is covered by a parked task with a resume condition | Re-triaging it hourly produced four verdicts and no code on #1062 | Revert the reconciler change | +| D8 | The first release is `id/v0.12.0` | Matches `mcpx/v0.1.0` | Tag again | +| D9 | F12.11: the F11.12 gate covers journaled frame kinds only, so binary screen frames are a negotiated v2 of the ephemeral `View`; the under-10% target is measured on the logical `View` payload | Both are the recommendations in `doc/2026-11-01_design_id805.md` §7, unanswered since 2026-11-01 | Leave the binary path off; record another denominator with a measurement | +| D10 | Surfaces may dispatch with the fleet user's own token; `fleet-org`, `fleet-org-blacksmith` and `fleet-forks` are active | The user can already start those workflows; the App grant they waited on bought nothing in 17 days | Remove `dispatch_as` and set the status back | +| D11 | The five dead-door reports are one defect, tracked in #12228; `_antigravity` leaves the rotation until its account answers | A quota wall resets by itself; what the fleet controls is failover, which is code with a test | Reopen a report | +| D12 | On the dashboard and in the digest, only hands items and review requests count as needing the owner | An agent's parked choice is fleet work under FDR-0013 | Revert the census change | ## Scoreboard @@ -306,3 +315,5 @@ To undo: revert the plan's PR. The skills are additive and are loaded by descrip ## Progress - 2026-11-21: Plan written from a review of the roadmaps, plans, designs, 6,442 issues, 5,759 PRs and 30 days of mainline history at `48c34e12`. Same PR: flow report tool and tests; skills `next-work`, `feature-slice`, `decide-and-proceed`; drift fixed in `ROADMAP.md`, `planning/roadmaps/id.md` and `planning/plans/README.md`. Found on the way and fixed separately: `AGENTS.md` was 3 bytes over its rulebook budget (PR #12209). +- 2026-11-21: #12227 landed the agent front door (`fleet agent`, `fleet shell`), the queue guard for FDR-0013, user-token dispatch with three more build surfaces active, and an optional `op` secrets source. Checked by `cargo test --manifest-path pkgs/fleet/Cargo.toml --workspace --all-targets --locked` (942 passed) and three real dispatches. The forks copy of the fleet repo was synced to upstream the same day; the org copy still fails its sync on a merge conflict in `fleet-run.yml`. +- 2026-11-21: Step 0 done. Tracker #12238 and issues #12228 to #12237 filed; `now` holds the two `id` tracks, the gate and the fleet steps; `next` holds what follows. `fleet agent shortlist fill` against GitHub returned #4000, #12228, #7030, then the `now` set, in that order. #805 and #9112 decided; five door reports closed into #12228. One hands item exists: #12237. diff --git a/pm-stack/aggregator/src/digest.ts b/pm-stack/aggregator/src/digest.ts index 2d61946bf8..23cdc4c7bf 100644 --- a/pm-stack/aggregator/src/digest.ts +++ b/pm-stack/aggregator/src/digest.ts @@ -17,7 +17,7 @@ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import type { NeedsDrewCensus } from "./needs-drew.ts"; +import { needsDrewOwnerItems, type NeedsDrewCensus } from "./needs-drew.ts"; import type { ProjectPoolItem, ProvenanceDetail, QuotaPool, QuotaView } from "./model.ts"; import { poolState, windowPercent } from "./derive.ts"; @@ -226,13 +226,16 @@ export function buildDigest(inputs: DigestInputs): Digest { } else { const censusAgeMs = now.getTime() - Date.parse(inputs.needsDrew.fetchedAt); const censusStale = !inputs.needsDrew.complete || !Number.isFinite(censusAgeMs) || censusAgeMs > staleAgeMs; + // FDR-0013: only hands items and review requests are the owner's. + // A choice an agent parked on the owner is fleet work and is not + // listed here; the attention page counts those separately. const items = cap( - inputs.needsDrew.items.map( + needsDrewOwnerItems(inputs.needsDrew).map( (i): DigestItem => ({ ref: i.ref, title: i.title, url: i.url, - note: i.reason ?? `labelled ${i.needsLabels.join(", ")} — no reason recorded on the item`, + note: i.hands?.action ?? i.reason ?? `labelled ${i.needsLabels.join(", ")} — no reason recorded on the item`, }), ), ); diff --git a/pm-stack/aggregator/src/needs-drew.ts b/pm-stack/aggregator/src/needs-drew.ts index ecad184aec..1198467d6c 100644 --- a/pm-stack/aggregator/src/needs-drew.ts +++ b/pm-stack/aggregator/src/needs-drew.ts @@ -41,8 +41,30 @@ export interface NeedsDrewItem { * must show the honest fallback, not invent one. */ reason: string | null; updatedAt: string; + /** The hands marker in the item body, when it carries one + * (FDR-0013). Absent on items censused before the marker existed; + * read it through {@link needsDrewWait}. */ + hands?: NeedsDrewHands | null; } +/** What only a person's hands can do (FDR-0013). The same four kinds + * `fleet queue block --hands` accepts. */ +export const HANDS_KINDS = ["physical", "interactive-login", "payment", "signature"] as const; +export type HandsKind = (typeof HANDS_KINDS)[number]; + +export interface NeedsDrewHands { + kind: HandsKind; + /** The one action, when the marker states it. */ + action: string | null; +} + +/** How an item waits (FDR-0013, doc/decisions): + * - `hands`: something only a person's hands can do; it names one action. + * - `review`: a review was asked for (`user/review`). + * - `agent-decides`: an agent parked a choice on the owner. That is + * fleet work, not the owner's: an agent decides it and continues. */ +export type NeedsDrewWait = "hands" | "review" | "agent-decides"; + export interface NeedsDrewSourceStatus { repo: string; label: NeedsDrewLabel; @@ -125,6 +147,41 @@ export function extractNeedsDrewReason(body: unknown): string | null { return reason ? capUnits(reason, 240) : null; } +/** The hands marker an item body carries, if any: + * ``. + * A marker with an unknown kind is not a hands marker: the item then + * falls back to its labels rather than being trusted as a hands item. */ +export function extractNeedsDrewHands(body: unknown): NeedsDrewHands | null { + if (typeof body !== "string") return null; + const m = //.exec(body); + if (!m) return null; + const kind = (HANDS_KINDS as readonly string[]).includes(m[1]) ? (m[1] as HandsKind) : null; + if (!kind) return null; + const action = m[2]?.trim(); + return { kind, action: action ? capUnits(action, 240) : null }; +} + +/** How one census item waits. A hands marker wins; then a review + * request; everything else was parked on the owner by an agent. */ +export function needsDrewWait(item: Pick): NeedsDrewWait { + if (item.hands) return "hands"; + if (item.needsLabels.includes("user/review")) return "review"; + return "agent-decides"; +} + +/** The census items that are the owner's: hands items and review + * requests. Agent-parked choices are left out. */ +export function needsDrewOwnerItems(census: NeedsDrewCensus): NeedsDrewItem[] { + return census.items.filter((i) => needsDrewWait(i) !== "agent-decides"); +} + +/** Counts per kind of wait, for headings and scoreboards. */ +export function needsDrewWaitCounts(census: NeedsDrewCensus): Record { + const counts: Record = { hands: 0, review: 0, "agent-decides": 0 }; + for (const i of census.items) counts[needsDrewWait(i)]++; + return counts; +} + export interface NeedsDrewSweeperOptions { /** How long a completed sweep stays fresh. */ ttlMs?: number; @@ -235,6 +292,7 @@ export async function buildNeedsDrewCensus( ), reason: extractNeedsDrewReason(raw.body), updatedAt: typeof raw.updated_at === "string" ? raw.updated_at : fetchedAt, + hands: extractNeedsDrewHands(raw.body), }); } if (rawItems.length < PER_PAGE || status.count >= total) break; diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index fdea9551b0..02ecf2a241 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -63,7 +63,7 @@ import { scoreEdges, } from "./assets/aa-explorer-computations.js"; import { summarizeDns } from "./dns.ts"; -import type { NeedsDrewCensus } from "./needs-drew.ts"; +import { needsDrewWait, type NeedsDrewCensus, type NeedsDrewItem } from "./needs-drew.ts"; import type { Incident, IncidentEvent, PushSubscriptionRow } from "./alerts.ts"; import type { NotificationRollup } from "./notifications.ts"; import { NOTIFICATION_CLASS_DEFAULTS, NOTIFICATION_CLASSES } from "./notifications.ts"; @@ -3431,19 +3431,41 @@ export function needsDrewCensusHtml(census: NeedsDrewCensus | null | undefined): }) .join("; ")}. The list below may be missing items from those sources.` : ""; - const rows = census.items.length - ? `

    ${census.items - .map( - (i) => - `
  • ${esc(i.ref)} ${i.kind === "pr" ? "(PR) " : ""}${esc(i.title)} — ${i.needsLabels - .map((l) => `${esc(l)}`) - .join( - " ", - )} — ${i.reason ? esc(i.reason) : "no reason recorded on the item — open it for context"} (updated ${esc(i.updatedAt)})
  • `, + // FDR-0013: only hands items and review requests are the owner's. + // A choice an agent parked on the owner is fleet work, listed apart + // so the page never presents it as waiting on him. + const hands = census.items.filter((i) => needsDrewWait(i) === "hands"); + const review = census.items.filter((i) => needsDrewWait(i) === "review"); + const parked = census.items.filter((i) => needsDrewWait(i) === "agent-decides"); + const line = (i: NeedsDrewItem, note: string): string => + `
  • ${esc(i.ref)} ${i.kind === "pr" ? "(PR) " : ""}${esc(i.title)} — ${i.needsLabels + .map((l) => `${esc(l)}`) + .join(" ")} — ${note} (updated ${esc(i.updatedAt)})
  • `; + const reasonOf = (i: NeedsDrewItem): string => + i.reason ? esc(i.reason) : "no reason recorded on the item — open it for context"; + const answered = census.complete ? "" : " in the sources that answered"; + const handsRows = hands.length + ? `
      ${hands + .map((i) => + line( + i, + `${esc(i.hands?.kind ?? "hands")}: ${ + i.hands?.action ? esc(i.hands.action) : "the item states the one action" + }`, + ), ) .join("")}
    ` - : `

    No open items carry user/review or user/escalated right now${census.complete ? "" : " in the sources that answered"}.

    `; - return `

    Needs Drew — GitHub label census (${census.items.length})

    Every open issue and PR carrying user/review or user/escalated across the four repos (#1226). The labels are the system of record; this view reads them and never writes them. Census taken ${esc(census.fetchedAt)}${census.complete ? "" : " — incomplete, see below"}. Machine form: /api/needs-drew.json.

    ${failureNote}${rows}`; + : `

    No open item needs a person's hands right now${answered}.

    `; + const reviewRows = review.length + ? `
      ${review.map((i) => line(i, reasonOf(i))).join("")}
    ` + : `

    No open item carries user/review right now${answered}.

    `; + const parkedRows = parked.length + ? `

    An agent parked each of these on the owner without a hands action. They do not wait on him: an agent decides, records the decision on the item and continues (FDR-0013). This count should fall to zero.

      ${parked + .map((i) => line(i, reasonOf(i))) + .join("")}
    ` + : `

    Nothing is parked on the owner by an agent${answered}.

    `; + const rows = `

    Needs a person's hands (${hands.length})

    ${handsRows}

    Review requested (${review.length})

    ${reviewRows}

    Parked on the owner by an agent — fleet work (${parked.length})

    ${parkedRows}`; + return `

    Needs Drew — GitHub label census (${hands.length + review.length})

    Every open issue and PR carrying user/review or user/escalated across the four repos (#1226), split by how it waits. The count in the heading is hands items and review requests only. The labels are the system of record; this view reads them and never writes them. Census taken ${esc(census.fetchedAt)}${census.complete ? "" : " — incomplete, see below"}. Machine form: /api/needs-drew.json.

    ${failureNote}${rows}`; } /** diff --git a/pm-stack/aggregator/test/digest.test.ts b/pm-stack/aggregator/test/digest.test.ts index 8f8c603354..08931a184c 100644 --- a/pm-stack/aggregator/test/digest.test.ts +++ b/pm-stack/aggregator/test/digest.test.ts @@ -54,8 +54,8 @@ const census: NeedsDrewCensus = { kind: "issue", title: "decide the thing", url: "https://github.com/developing-today/code/issues/42", - labels: ["user/escalated"], - needsLabels: ["user/escalated"], + labels: ["user/review"], + needsLabels: ["user/review"], reason: "needs a budget call", updatedAt: "2026-11-02T09:00:00Z", }, @@ -130,6 +130,41 @@ describe("buildDigest", () => { expect(outlook.items[0].note).toContain("near wall"); }); + // FDR-0013: a choice an agent parked on the owner is fleet work. + // Oracle: the decision record's rule — only hands items and review + // requests are the owner's. + test("needs-drew lists hands items and reviews, not choices an agent parked on the owner", () => { + const withAll: NeedsDrewCensus = { + ...census, + items: [ + ...census.items, + { + ...census.items[0], + ref: "developing-today/code#43", + number: 43, + url: "https://github.com/developing-today/code/issues/43", + labels: ["user/escalated"], + needsLabels: ["user/escalated"], + reason: "which encoding should this use?", + }, + { + ...census.items[0], + ref: "developing-today/code#44", + number: 44, + url: "https://github.com/developing-today/code/issues/44", + labels: ["user/escalated"], + needsLabels: ["user/escalated"], + reason: null, + hands: { kind: "interactive-login", action: "Run gh auth refresh and approve the code." }, + }, + ], + }; + const needs = section(buildDigest(inputs({ needsDrew: withAll })), "needsDrew"); + expect(needs.items.map((i) => i.ref)).toEqual(["developing-today/code#42", "developing-today/code#44"]); + // A hands item's note is its one action. + expect(needs.items[1].note).toBe("Run gh auth refresh and approve the code."); + }); + test("weekly window reaches back seven days", () => { const d = buildDigest(inputs({ kind: "weekly" })); expect(d.windowHours).toBe(168); diff --git a/pm-stack/aggregator/test/needs-drew.test.ts b/pm-stack/aggregator/test/needs-drew.test.ts index 53957a6bf4..70f80a5fe1 100644 --- a/pm-stack/aggregator/test/needs-drew.test.ts +++ b/pm-stack/aggregator/test/needs-drew.test.ts @@ -2,7 +2,11 @@ import { describe, expect, test } from "bun:test"; import { buildNeedsDrewCensus, createNeedsDrewSweeper, + extractNeedsDrewHands, extractNeedsDrewReason, + needsDrewOwnerItems, + needsDrewWait, + needsDrewWaitCounts, needsDrewIncidentKey, needsDrewSearchUrl, type NeedsDrewFetchPage, @@ -237,6 +241,64 @@ describe("needs-drew census (#1226)", () => { }); }); +// FDR-0013 (doc/decisions): only a hands item may wait on a person. +// Oracle: the marker grammar documented on extractNeedsDrewHands and +// the four kinds `fleet queue block --hands` accepts. +describe("how an item waits", () => { + test("the hands marker gives a kind and an optional action", () => { + expect( + extractNeedsDrewHands('text\n\nmore'), + ).toEqual({ kind: "interactive-login", action: "Run gh auth refresh." }); + expect(extractNeedsDrewHands("")).toEqual({ kind: "payment", action: null }); + // An empty action is no action. + expect(extractNeedsDrewHands('')).toEqual({ + kind: "signature", + action: null, + }); + }); + + test("an unknown kind, another marker or no body is not a hands marker", () => { + expect(extractNeedsDrewHands("")).toBeNull(); + expect(extractNeedsDrewHands("")).toBeNull(); + expect(extractNeedsDrewHands("hands: please decide")).toBeNull(); + expect(extractNeedsDrewHands(null)).toBeNull(); + expect(extractNeedsDrewHands(42)).toBeNull(); + }); + + test("a hands marker wins, then a review request, else an agent parked it", () => { + const hands = { kind: "physical" as const, action: null }; + expect(needsDrewWait({ needsLabels: ["user/escalated"], hands })).toBe("hands"); + expect(needsDrewWait({ needsLabels: ["user/review"], hands })).toBe("hands"); + expect(needsDrewWait({ needsLabels: ["user/review", "user/escalated"], hands: null })).toBe("review"); + expect(needsDrewWait({ needsLabels: ["user/escalated"], hands: null })).toBe("agent-decides"); + // An item censused before the marker existed has no `hands` field. + expect(needsDrewWait({ needsLabels: ["user/escalated"] })).toBe("agent-decides"); + }); + + test("the census reads the marker from the item body and counts each kind of wait", async () => { + const fetchPage = fakeFetch((repo, label) => { + if (repo !== REPO) return { total: 0, items: [] }; + if (label === "user/review") return { total: 1, items: [item(1, ["user/review"])] }; + return { + total: 3, + items: [ + item(2, ["user/escalated"]), + item(3, ["user/escalated"], { body: '' }), + item(4, ["user/escalated"], { body: "Escalated: which encoding?" }), + ], + }; + }); + const census = await buildNeedsDrewCensus(fetchPage, { now: NOW }); + expect(census.items.find((i) => i.number === 3)?.hands).toEqual({ + kind: "physical", + action: "Plug in the rack PDU.", + }); + expect(census.items.find((i) => i.number === 2)?.hands).toBeNull(); + expect(needsDrewWaitCounts(census)).toEqual({ hands: 1, review: 1, "agent-decides": 2 }); + expect(needsDrewOwnerItems(census).map((i) => i.number)).toEqual([1, 3]); + }); +}); + describe("needs-drew census rendering", () => { const base = { fetchedAt: NOW.toISOString(), @@ -263,13 +325,57 @@ describe("needs-drew census rendering", () => { expect(needsDrewCensusHtml(null)).toContain("Unavailable"); }); - test("items render with the honest no-reason fallback and the API link", () => { + test("an agent-parked item renders as fleet work, not in the owner's count", () => { + // `base` holds one user/escalated item with no hands marker. const html = needsDrewCensusHtml(base); - expect(html).toContain("Needs Drew — GitHub label census (1)"); + expect(html).toContain("Needs Drew — GitHub label census (0)"); + expect(html).toContain("Parked on the owner by an agent — fleet work (1)"); + expect(html).toContain("Needs a person's hands (0)"); + expect(html).toContain("Review requested (0)"); expect(html).toContain(`${REPO}#7`); expect(html).toContain("no reason recorded on the item"); expect(html).toContain("/api/needs-drew.json"); expect(html).not.toContain("incomplete"); + // The parked item sits under the fleet-work heading, after it. + expect(html.indexOf(`${REPO}#7`)).toBeGreaterThan(html.indexOf('id="needs-drew-parked"')); + }); + + test("hands items and review requests are the owner's count, each under its own heading", () => { + const html = needsDrewCensusHtml({ + ...base, + items: [ + ...base.items, + { + ...base.items[0], + ref: `${REPO}#8`, + number: 8, + title: "sign in for the codespace surface", + url: `https://github.com/${REPO}/issues/8`, + hands: { kind: "interactive-login" as const, action: "Run gh auth refresh and approve." }, + }, + { + ...base.items[0], + ref: `${REPO}#9`, + number: 9, + title: "review the release notes", + url: `https://github.com/${REPO}/issues/9`, + labels: ["user/review"], + needsLabels: ["user/review" as const], + reason: "release notes are ready", + }, + ], + }); + expect(html).toContain("Needs Drew — GitHub label census (2)"); + expect(html).toContain("Needs a person's hands (1)"); + expect(html).toContain("Review requested (1)"); + expect(html).toContain("Parked on the owner by an agent — fleet work (1)"); + // The one action is shown, escaped, with its kind. + expect(html).toContain("interactive-login: Run gh auth refresh <now> and approve."); + const at = (needle: string) => html.indexOf(needle); + expect(at(`${REPO}#8`)).toBeGreaterThan(at('id="needs-drew-hands"')); + expect(at(`${REPO}#8`)).toBeLessThan(at('id="needs-drew-review"')); + expect(at(`${REPO}#9`)).toBeGreaterThan(at('id="needs-drew-review"')); + expect(at(`${REPO}#9`)).toBeLessThan(at('id="needs-drew-parked"')); }); test("failed sources render a banner naming repo and label", () => {