From 1f834df3269fe4487fec13859d12b060de480be1 Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 22 Nov 2026 22:06:58 +0000 Subject: [PATCH] docs: Add the design, architecture and agent rules The design and architecture docs come from nixfiles' `docs/slop-broker.md` and its working notes, rewritten to describe the broker rather than one deployment: roles such as the agents' VM and the broker's box replace box names, and the rollout plan and deployment's agent setup stay in nixfiles. `AGENTS.md` carries over the general rules from nixfiles plus this repository's commands. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 100 ++++++++++ CLAUDE.md | 1 + README.md | 50 +++++ docs/architecture.md | 203 ++++++++++++++++++++ docs/design.md | 443 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 797 insertions(+) create mode 100644 AGENTS.md create mode 120000 CLAUDE.md create mode 100644 README.md create mode 100644 docs/architecture.md create mode 100644 docs/design.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e904266 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,100 @@ +# AGENTS.md + +This file provides guidance to coding agents working in this repository. `CLAUDE.md` is a symlink to +it — edit `AGENTS.md`, not the symlink. + +**Prefer this file over agent memory.** When you learn something durable about this repo — a +convention, a workflow gotcha, a design rationale — record it here or in the doc under `docs/` that +owns the topic, not in agent memory. This file is versioned and shared; memory is not. + +Keep this file lean: rules, workflows, safety constraints and sharp gotchas an agent needs before +starting work. Design and rationale belong in [`docs/design.md`](docs/design.md), and how the code is +put together in [`docs/architecture.md`](docs/architecture.md); link to them instead of repeating +them. + +## Overview + +`slop-broker` runs privileged operations (SSH commands, deploys, builds, and later secrets, DNS and +previews) for coding agents, under a policy and usually after a human approves each one. Agents use +the `slop` CLI; approvers use `slop-approve`, Home Assistant notifications or the web app. It's a +Rust crate (one library, the `slop-broker` and `slop` binaries) plus NixOS and home-manager modules, +all in this flake. + +Its reference deployment is [nixfiles](https://git.nul.ie/dev/nixfiles), which consumes this +flake as an input; box-specific configuration (which box runs the broker, its policies, firewall, +secrets and persistence) lives there, not here. + +## Commands + +The development environment is [devenv](https://devenv.sh) (`devenv.nix`): direnv with `.envrc`, +which takes the `devenv` CLI from the flake's nixpkgs, or `devenv shell` (without direnv, +`nix shell --inputs-from . nixpkgs#devenv` provides it). It has the Rust toolchain, the build's +native inputs and `git`, and lists its scripts on entry. The flake doesn't need devenv: it has the +package, modules, the demo's VMs and the checks. `nix develop` is a plainer alternative +(`devShells.default`): the same toolchain, with the native inputs taken from the package, but none +of devenv's scripts, `devenv test` or the demo's host side. + +- `cargo build`, `cargo test` — the unit and integration tests (`tests/`). `tests/builder.rs` needs + `git`, which the devenv shell provides. +- `cargo clippy --all-targets` — keep it free of warnings. `devenv test` runs clippy (warnings as + errors) and the tests. +- `cargo fmt` — the crate is formatted with `rustfmt` (`rustfmt.toml`); run it on code you change. +- `nix build` — the package, which also runs the tests. +- `vm-test` (or `nix build -L .#checks.x86_64-linux.vm`) — the NixOS VM test of the broker module + (needs KVM). +- The [demo](docs/demo.md): `devenv up -d` starts the host side (the broker from this checkout, its + web app, Pocket ID and the box VM); `devenv processes logs ` shows a process's output and + `devenv processes down` stops them. `demo` boots the agents' VM on the terminal and holds it until + `poweroff`, so an agent should run it in the background with stdin from a pipe it controls. + `slop-approve` in the devenv shell answers requests, and `demo-box` SSHes into the box VM. Stop + the agents' VM with `poweroff` on its console or by stopping that background task, not with + `pkill -f`, whose pattern also matches the shell running it. +- `nix fmt` — formats Nix with `nixpkgs-fmt`. **Ask before running it on a file you didn't write**: + some files aren't canonically formatted, and a whole-file reindent buries a logical change. + +Nix only sees files Git tracks, so a new file must be added (`jj` does this when it snapshots; +otherwise `git add -N`) before `nix build` can use it. + +## Conventions + +- Prefer `jj` for status, diffs, history, commits, rebases and remote operations; the repository is + colocated, so Git tooling works too. Inspect `jj status`, `jj diff` and `jj log` before editing, + preserve existing changes, and use explicit revisions when rewriting history. +- Separate logical steps in code with blank lines, in every language and inside function bodies: a + function that gathers its inputs, checks them, acts and reports should read as short paragraphs, + not one block. Keep closely related statements together, and leave a blank line before a comment + that introduces the next step. +- Comment where it genuinely aids understanding, not for trivial code; match the existing, fairly + sparse comment density. When adding something general, comment its general purpose, not the + specific change or one-off reason it was introduced for. +- Everything an approver sees comes from agents and must be treated as hostile: pass it through + `ops::printable` (the web app's templates do both that and HTML escaping; never mark a value + `|safe`). Never let request contents decide what runs + beyond what the operation's typed fields allow. +- Nix modules use plain `lib.mkOption`, options under `services.*` (NixOS) and `programs.*` + (home-manager), and never reference a particular deployment. Runtime secrets are paths outside + the Nix store, loaded with `LoadCredential`. +- Commit subjects follow `area: Capitalized summary` (e.g. `web: Show leases`, `nix: Add a cache + option`); aim for 50 characters and do not exceed 72. Hard-wrap commit bodies at 72 characters; + `-m` preserves unwrapped text, so include literal line breaks or use a file. Check + `jj log --no-graph -r -T description` and fix any line over 72 characters before + reporting a commit. A short body with the rationale is welcome when the subject isn't enough. + `Co-Authored-By` is the only trailer used here; don't add session or tooling trailers. +- Keep logically distinct (unrelated) changes in separate commits, but one piece of work stays in + one commit even when it touches code, modules and docs; split only when a reader would ask why two + things arrived together. + +## Writing + +- In prose and commit messages, quote code-like identifiers (commands, options, paths, crate and + attribute names) in backticks. +- Keep docs plain — avoid vague filler. Use "layout"/"structure" rather than "shape", and name things + directly instead of reaching for umbrella words. +- Use tables for lists of structured items, with the item's name as the link. Break up long prose: + a bullet running past about four lines over several distinct facts becomes a `###` subheading + with a lead sentence and nested bullets. +- Prefer durable concepts and named configuration identifiers over exact numbers that are tunable + and likely to drift; describe those by purpose and point at their source. +- Each fact has one home. Update the doc that owns a topic when the code changes it: the design and + its rationale in `docs/design.md`, the code's structure in `docs/architecture.md`, the agents' + guide in `slop-tools.md` (update it with each new operation). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..af3c4a3 --- /dev/null +++ b/README.md @@ -0,0 +1,50 @@ +# slop-broker + +An approval broker that runs privileged operations (SSH commands, deploys, builds, and later +secrets, DNS and previews) for coding agents, under a policy and usually after a human approves +each one. Agents use the `slop` CLI; approvers use `slop-approve`, a web app (sign-in with OpenID +Connect, passkeys, Web Push) or Home Assistant notifications. + +- [`docs/design.md`](docs/design.md) — the design and its rationale. +- [`docs/architecture.md`](docs/architecture.md) — how the code is put together and how to add an + operation. +- [`docs/demo.md`](docs/demo.md) — a setup to try it in. +- [`slop-tools.md`](slop-tools.md) — the guide for agents (`slop guide` prints it). + +## Trying it + +```sh +devenv up # the broker, its web app, Pocket ID and a box VM for the SSH targets +demo # in another terminal: the agents' VM, signed in as an agent that can send requests +``` + +See [`docs/demo.md`](docs/demo.md). + +## Using it + +The flake provides: + +| Output | What | +|---|---| +| `packages..default` | `slop`, `slop-broker` and `slop-approve` | +| `overlays.default` | `pkgs.slop-broker` | +| `nixosModules.slop-broker` | The broker (`services.slop-broker`) | +| `nixosModules.slop-broker-builder` | The builder for deploys and builds (`services.slop-broker-builder`) | +| `nixosModules.slop-broker-cache` | The binary cache side of builds (`services.slop-broker-cache`) | +| `homeModules.slop` | The clients on other boxes, over SSH (`programs.slop`) | + +`nixosModules.default` imports all three NixOS modules. The modules default their `package` to this +flake's build. Deployment-specific concerns (persisting state on an ephemeral root, the firewall in +front of the web app, SSH targets, policies) are left to the configuration that imports them; +[nixfiles](https://git.nul.ie/dev/nixfiles) is the reference deployment. + +## Developing + +The development environment is [devenv](https://devenv.sh): direnv with `.envrc`, which takes the +`devenv` CLI from the flake's nixpkgs so it needn't be installed, or `devenv shell`. `cargo test` +and `cargo clippy --all-targets` work there, `devenv test` runs both, and `vm-test` runs the NixOS +VM test (needs KVM). See [`AGENTS.md`](AGENTS.md) for conventions. + +## License + +MIT; see [`LICENSE`](LICENSE). diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..ce9b385 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,203 @@ +# Architecture + +How the code is put together, and how to extend it. The design and its rationale are in +[`design.md`](design.md). + +## Layout + +| File | Responsibility | +|---|---| +| `src/proto.rs` | Messages (`ClientMessage`, `ServerMessage`, `Operation`, `OpResult`, approver messages), framing and encoding | +| `src/types.rs` | Validated value types (`NodeName`, `UnitName`, `Since`, `Lines`, …) used inside messages | +| `src/config.rs` | TOML config from the NixOS module (durations as `"5m"`); credential path, user and group lookups | +| `src/policy.rs` | `auto` / `ask` / `deny` evaluation, rules with globs, per-operation `Limits` | +| `src/queue.rs` | Pending approvals, decisions, leases, per-requester limits and rate limits | +| `src/server.rs` | Listeners (vsock, Unix), the per-connection handler, `authorize` | +| `src/exec.rs` | Running processes on the requester's framed stdio; cancellation | +| `src/ops/mod.rs` | `plan` (request → `Parsed`: scope, approval text), `execute`, quoting | +| `src/ops/ssh.rs`, `src/ops/query.rs`, `src/ops/deploy.rs`, `src/ops/build.rs` | Operations; `deploy.rs` also has the `INSPECT` comparison script and its parser | +| `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client | +| `src/approve.rs` | Approver connections (many requests each), `slop-approve` client, `approve()` used by every approver | +| `src/remote.rs` | SSH transport: the `slop-broker remote` forced command, the remote socket, `connect` for both clients, and `address` (environment, then `~/.config/slop/config.toml`, then the default) | +| `src/ha.rs` | Home Assistant Companion notifications | +| `src/audit.rs` | Typed audit events: a text line to the journal, a JSON line to the file; `tail` for `slop-approve log` | +| `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name | +| `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` | +| `tests/broker.rs` | Handler tests over an in-memory duplex stream with a fake `ssh` | +| `src/web/` | The approvals web app: routes (`mod.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets | +| `templates/`, `askama.toml` | The web app's HTML, as [askama](https://askama.rs) templates compiled into the broker; `askama.toml` passes everything they show through `ops::printable` before escaping it | +| `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks..vm`) and the demo's VMs (`demo/`, `packages..demo` and `demo-box`) | +| `devenv.nix` | The development environment, its scripts and the demo's host side (`devenv up`); `nix develop` gives a plainer shell from `flake.nix` without them | + +## Request lifecycle + +1. A listener accepts a connection and maps it to a requester name: vsock by peer CID, the Unix + request socket by peer UID, the remote socket by the `Hello` its forced command sends. Anything + unknown is refused and logged. +2. `server::handle` reads one `ClientMessage::Request` (10-second limit), then starts a reader task + that forwards `Stdin` to a channel (closing it at `StdinEnd`) and cancels a `CancellationToken` + when the connection closes or misbehaves. A writer task sends every `ServerMessage` from an + `mpsc` channel, in order. +3. The protocol version is checked. `ops::plan` checks the already-typed `Operation` against config + (does the node exist?) and returns `Parsed`: the scope, what approvers are shown, limits, whether + stdin is used, and the operation. For operations that build (`ops::builds`), a policy pre-check + (deny stops here), then `ops::describe` (the builder's Git-only stage), then `authorize` of the + `ops::builder_gate` request (op `builder`, empty scope, audited as `approved` with + `step: builder`), then `ops::prepare`: build, copy, compare, and fill in the detail + (`Event::Prepared`). +4. `authorize` evaluates policy for the requester and operation. `deny` refuses. `auto` takes a + rate-limit slot. `ask` uses a matching lease if there is one, otherwise submits to the queue, + sends `Pending`, and waits for a decision, the timeout or a disconnect. +5. The handler sends `Approved { by, stdin }`. The client starts forwarding stdin only then, and + only if `stdin` is set. +6. `ops::execute` runs the operation with `Io` (stdin channel, output sender, cancel token) and + returns an exit status and an optional `OpResult`. +7. The handler sends one terminal message (`Finished`, `Denied`, `Expired`, `Error`), or nothing if + the requester went away, then closes. + +Every step is audited as an `audit::Event` carrying the request's ID (the same ID approvers see): +`request`, `prepared`, `approved` (with the approver's name), `decision`, `denied`, `expired`, +`finished`, `failed`, `disconnected`, plus `invalid` and `unknown` peers. Built-in operations (`requests`) aren't logged. + +## Protocol + +- Each message is a serde enum from `src/proto.rs`, encoded as CBOR (`ciborium`; byte strings via + `serde_bytes`) and framed by `LengthDelimitedCodec` (4-byte big-endian length, 1 MiB maximum). +- Requester → broker: `Request { version, label, operation }`, then `Stdin(bytes)` / `StdinEnd`. +- Broker → requester: `Pending`, `Approved { by, stdin }`, `Info`, `Stdout`, `Stderr`, then one of + `Finished { exit, result }`, `Denied`, `Expired` or `Error`. +- Every enum and struct has `deny_unknown_fields`, and value types validate in `TryFrom`, so a + request that decodes is well-formed. `plan` only checks it against config. +- Bump `PROTOCOL_VERSION` on any incompatible change: brokers and clients are deployed + separately. +- Approver connections use the same framing with `ApproveRequest` / `ApproveResponse`, any number + per connection. +- The remote socket starts with a `remote::Hello { role, name }`, written as one length-prefixed + frame without the codec so nothing after it is read ahead, then carries either protocol. +- The builder gets one `BuildRequest` frame on stdin and answers with one `BuildResult` frame on + stdout; build logs go to stderr, which the broker forwards to the requester. +- `slop` exits with the operation's status for `Finished` and 125 for anything else. `--json` + prints an `OpResult` as JSON. + +## Policy, leases and limits + +- Config: named `policies. = { max_pending, auto_per_minute, ops. = { action, leases, + rules } }`, and `requesters..policy` picks one, so requesters can share a policy. + `Config::validate` (called by `Broker::new`) refuses a requester whose policy is missing, and the + module asserts the same. A missing operation is denied. +- Rules match scope fields with globs (`*`, `?`); the first match wins and can replace `leases`. +- An operation's `Limits` override policy: `never_auto` turns `auto` into `ask`, and `never_lease` + removes leases (for example, `secret read`). +- The lease key is the operation name plus the scope's canonical JSON (serde_json maps are sorted), + per requester. The command is in the detail, not the scope, so a lease covers any command to the + same target. +- Approvers are offered `once`, each allowed lease (`5m`, `1h`, …) and `deny`. A lease that wasn't + offered is refused. +- Limits: pending requests per requester and overall, and `auto` requests per minute per + requester. A shared policy shares the numbers, not the counters or leases. Everything is in memory; a restart drops pending requests and leases. + +## Execution + +`exec::run` starts the process in its own process group, pumps stdout and stderr into frames, and +feeds stdin from the channel. On cancellation it sends `SIGTERM` to the group, then `SIGKILL` after +five seconds. It retries a spawn that fails with `ETXTBSY`, which happens when another thread forks +while an executable is still open for writing (seen in parallel tests). `exec::capture` runs a +process without the requester's stdio, for broker-internal steps. `exec::run_prefixed` runs one +without stdin and sends each output line with a prefix, so several nodes can share the output +(deploy copies and activations). + +SSH always uses options fixed in `ssh::command`: `-F none`, the credential key, no agent, +`BatchMode`, no forwarding, its own `known_hosts` (`accept-new`), and `--` before the hostname. +Arguments from the requester are validated so none can be read as an option. + +## Approvers + +- `approve.sock` is restricted to the `slop-broker-approve` group. A requester's UID is refused + even if it is in the group. The approver is recorded by user name. +- Over SSH, approvers are named in `sshApprovers` and recorded as ` (ssh)`. +- Home Assistant: an outbound WebSocket connection. Each pending request becomes a persistent, + sticky notification with random action IDs for Once, the shortest lease and Deny (Android shows + at most three). Replies must match a live action and the configured `device_id`, which is the + Companion app's own ID (the broker logs the ID of answers it ignores). It resyncs whenever the + queue changes (`Queue::subscribe`) and every five seconds, and logs why a connection failed. +- All of them call `approve::approve`, which records the decision and audits it; the approver's + name travels with the outcome into the `approved` event. + +## NixOS side + +- `nix/modules/nixos/broker.nix` (`services.slop-broker`) turns options into the TOML config + (`pkgs.formats.toml`, nulls dropped). Credentials arrive through `LoadCredential` under fixed + names (`ssh-key`, `cache-key`, `ha-token`, `oidc-secret`), which `config::credential` resolves in + `$CREDENTIALS_DIRECTORY`. +- The service runs as `slop-broker` with a strict systemd sandbox. Each operation that needs more + (address families, writable paths, helper users) adds it in the module, and the VM test should be + rerun. +- Remote keys become `authorized_keys` entries for the `slop` user with a forced + `slop-broker remote `; the broker gets `slop`'s group to share the remote socket. +- The `programs.slop` home-manager module installs both clients and sets up `request` and + `approve` keys: `Host` entries `slop-request` / `slop-approve` and `~/.config/slop/config.toml` + pointing at them. +- Deploys: `services.slop-broker.deploy` (broker side) and `services.slop-broker-builder` (the + `slop-broker-build` user, its read-only Git key and forced command). The broker can reach the + builder over SSH to localhost. +- Builds: `services.slop-broker.cache` (broker side) and `services.slop-broker-cache` on the cache's + box, whose forced command allows `nix-daemon --stdio` (exactly what `ssh-ng` sends) and + `root …`. The broker adds roots before copying, in case the store collects garbage often. +- Home Assistant: the broker's user there must be an admin, because non-admins can't subscribe to + notification actions. +- What the modules leave to the deployment: persisting `/var/lib/slop-broker` and the builder's + home on an ephemeral root, the firewall in front of the web app's port, which boxes are SSH + targets, and the policies. [nixfiles](https://git.nul.ie/dev/nixfiles) is the reference, and + [`nix/vm-test.nix`](../nix/vm-test.nix) a minimal example. + +## Adding an operation + +1. Add the `Operation` variant in `src/proto.rs`, using validated types from `src/types.rs` (add new + ones there), and an `OpResult` variant if it returns data. Bump `PROTOCOL_VERSION` if old clients + would misread anything. +2. `src/ops/.rs` and a `plan` arm in `src/ops/mod.rs`: the config checks, a scope that is + exactly what an approval should cover, and an `execute` arm. + - Put anything shown but not part of the approval (commands, diffs) in `detail`. + - Set `limits` and `sensitive` where the operation reveals or redistributes secrets. +3. Add the client subcommand in `src/bin/slop.rs` (clap parses validated types directly through + `FromStr`), and how to print its `OpResult`. +4. Tests: parsing in the module, behaviour in `tests/broker.rs` with fakes of what it calls. +5. Module options and sandbox changes; the deployment's policy entry follows in its own repo. +6. Agent guide (`slop-tools.md`) and [`design.md`](design.md). + +## Conventions and gotchas + +- Run `cargo fmt` (`rustfmt.toml`: width 120) and `cargo clippy --all-targets` in the devenv shell; + keep both clean (`devenv test` runs clippy and the tests). +- Report errors to requesters with `{error:#}` so the cause chain is included. +- Messages to requesters are read by agents. Make them say what to do instead (for example + "use --host for other boxes"). +- Remote login shells may be `fish`. Commands the broker builds are one `shell_quote`d string, + which both POSIX shells and `fish` read the same way as long as the words contain no `\\` or `\'`. +- Unix socket paths are limited to about 108 bytes, so deep scratch directories are too long for + manual tests; put sockets under `$XDG_RUNTIME_DIR`. +- The [demo](demo.md) is the easiest manual test of the web app. Against a real OpenID Connect + provider instead, run the broker with a `[web]` section and `url = "http://localhost:"`; the + provider's client needs that callback URL too. Remove it again afterwards. +- Claude Code's default Bash timeout is two minutes, shorter than the approval timeout; the agent + guide tells agents to use a longer timeout or run `slop` in the background. +- tokio's `Command::output()` captures stdout and stderr whatever they're set to; to let a child's + stderr through, `spawn()` and `wait_with_output()`. +- ssh keeps the first value of an option. `nix copy` to `ssh://` adds `PermitLocalCommand=yes` and + waits for `echo started`, so the broker's `PermitLocalCommand=no` would hang it forever (see + `copy_options`). +- A tokio program that reads stdin can't return from `main` while that read blocks; the builder + worker calls `std::process::exit` after writing its result. +- Session variables from home-manager only reach shells started after the next login + (`__HM_SESS_VARS_SOURCED` is inherited), which is why `programs.slop` writes a config file instead. +- Changes that touch several stack changes at once (such as spacing sweeps) can be made at the tip + and moved with `jj absorb`; it leaves lines whose neighbours come from different changes, which go + into the later of the two. + +## Known gaps + +- Home Assistant notifications can be swiped away on Android 14 and later; `persistent` no longer + prevents it. The possible fix (re-post on `mobile_app_notification_cleared`, on a quiet channel) + is described in [`design.md`](design.md) and left for now. +- `nix/vm-test.nix` needs KVM; run `vm-test` in the devenv shell. It doesn't cover deploys, Home + Assistant or the web app; the demo covers the web app by hand. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..a8ac858 --- /dev/null +++ b/docs/design.md @@ -0,0 +1,443 @@ +# slop-broker design + +`slop-broker` lets coding agents use credentials they must never hold: deploy and SSH keys, the +age identity for secrets, a binary cache and DNS API tokens. Agents send it requests through the +`slop` CLI, and it carries out each one under a policy, usually after a human approves it from a +terminal, the web app or the phone. + +The usual setup runs agents in a VM (the **agents' VM**) and the broker on the box that hosts it +(the **broker's box**), outside the agents' reach. Agents on other boxes can use it too (see +[Other requesters and approvers](#other-requesters-and-approvers)). The reference deployment is +[nixfiles](https://git.nul.ie/dev/nixfiles), whose `docs/slop-broker.md` describes how its boxes use +the broker. + +**Status:** the core, the box queries, `slop ssh`, the SSH transport, deploys, builds, Home +Assistant notifications and the approvals web app are implemented. The other operations here are +designed but not built yet (see [Planned operations](#planned-operations)). How the code is put +together is in [`architecture.md`](architecture.md); the NixOS and home-manager modules are in +[`nix/modules`](../nix/modules). + +## Trust model + +- Everything inside the agents' VM is agent-controlled, including root, and so is any other + requester. Anything a requester sends is untrusted: commands, file contents, commit IDs, + labels and its own descriptions of requests. +- The broker holds the credentials and runs every privileged step itself. A credential never + reaches a requester. The only exception is an explicit `slop secret read`. +- Each requester names a policy, and several requesters can share one. Leases and request + limits are still counted per requester. +- Each request has a **scope**, which is what an approval covers (for example: deploy `web` at + commit X). The broker builds both the scope and the text shown to the approver from validated + fields, never from text the agent wrote. +- Anything returned to a requester should be treated as published. It ends up in the agent's + context, so in the model provider's transcript and in the agent's session logs. +- The broker never evaluates agent-written Nix itself. A builder does, as a separate user that only + holds a read-only Git key. The broker's privileged half only copies, signs, encrypts or + activates the results. +- The broker's box should already be trusted with what the broker holds. With deploys, the deploy + key is root on every box it reaches, so also giving the broker access to secrets adds little. + +## Transport + +- The agents' VM gets a `vhost-vsock` device with a fixed CID. The broker listens on `AF_VSOCK` on + its box, and the kernel-reported peer CID identifies the requester. Nothing the guest sends can + change its CID. +- Messages are typed Rust enums shared by `slop` and the broker, encoded as CBOR and framed with + a length prefix (`tokio-util`'s `LengthDelimitedCodec`). Decoding validates every value (node and + unit names, ports and so on) and rejects unknown fields. The request carries a protocol version, + so a mismatched `slop` gets a clear error. +- One connection carries the request, then the operation's stdin (only after approval, and only + for operations that read it), its stdout and stderr, and a final message with the exit status + and any structured result. If the connection closes, the broker cancels the request or kills the + process it started. +- The VM never connects to the broker over the network, so the VM's network can stay isolated + from the broker's box. +- Local users on the broker's box can be requesters too, identified by UID on a Unix socket. + +### Other requesters and approvers + +Requesters and approvers on other boxes connect with SSH instead of vsock. That reuses `sshd` for +authentication and stream handling. + +- They log in as `slop` on the broker's box. Each key has a forced command, + `slop-broker remote `, set from + `services.slop-broker.requesters..sshKeys` or `services.slop-broker.sshApprovers.`. + It connects to the broker's remote socket, which only `slop` can use, and tells the broker whose + key it is. The broker trusts that the same way it trusts a CID. +- A key does one job. The module refuses the same key as both requester and approver, and the + client says which job it wants (`ssh … request` or `ssh … approve`), so a key used with the + wrong client fails with a clear error. +- A requester key only allows making requests, so it's fine for the agents on that box to be able + to read it. An approver key must be out of their reach. +- Each requester names a policy. The agents' VM is identified by its CID, the others by their + key. For example, workstations might share a policy that only allows `dns`, the box queries + and `requests`. +- `slop` connects to `$SLOP_BROKER`, else `broker` in `~/.config/slop/config.toml`, else vsock; + `slop-approve` likewise uses `$SLOP_APPROVE`, else `approve`, else `approve.sock` on the box. + An `ssh:` address goes to `ssh` as is, so a `Host` entry with `IdentitiesOnly` can + pick the right key when a box has both kinds. `SLOP_SSH` replaces the `ssh` command, like + `GIT_SSH_COMMAND`. +- The `programs.slop` home-manager module sets this up: `programs.slop.request` and + `programs.slop.approve` each take a key file, and get the `slop-request` and `slop-approve` + `Host` entries and the config file pointing at them. A config file rather than session + variables, because shells started before a switch don't see new variables. + +## The `slop` CLI + +There is one client command. Every subcommand blocks until the request is answered, +then streams the output. + +| Command | Purpose | Suggested policy | +|---|---|---| +| `slop status [unit]`, `slop logs `, `slop failed ` | Fixed read-only queries on boxes | auto | +| `slop ssh -- `, `slop ssh --host user@host[:port] -- ` | Any command over SSH | ask | +| `slop deploy … [--commit ] [--boot]` | Build a pushed commit and deploy it, to all targets at once | ask | +| `slop build … [--commit ]` | Build flake attributes of a pushed commit and push them to a binary cache | ask | +| `slop secret keys\|set\|generate\|rekey\|read …` (planned) | Work with age secrets | `keys` auto, `read` always ask, others ask | +| `slop dns list\|set\|delete …` (planned) | Change records in public DNS zones | `list` auto, others ask | +| `slop preview [--name n] [--public] [--auth basic\|sso] [--ttl 4h]` (planned) | Publish a dev server | ask | +| `slop requests` | Show this requester's pending requests and active leases | always allowed | + +Every request can carry `--label` (agent, repo and a one-line reason). The CLI fills it in +automatically where it can. Approvals show it marked as agent-supplied. + +## Approvals and policy + +- Each operation has a policy, configured in Nix: `auto`, `ask` or `deny`, plus the lease lengths + it allows (`"5m"`, `"1h"`). The module writes the broker's configuration as TOML. Narrower rules + override wider ones, for example per node, per DNS name or per secret path. +- Policies are named in `services.slop-broker.policies`, and each requester picks one with + `policy`, so several requesters, for example agents on different boxes, can share the same rules. +- An `ask` request waits for an answer (`services.slop-broker.timeout`) from the + [approvals web app](#approvals-web-app), `slop-approve` (on the broker's box, or over SSH from + another box) or a Home Assistant Companion notification. The answers are **once**, a **lease** + (the same scope is approved for a while, and only lengths the policy allows are offered) or + **deny**. +- An operation or rule can also set `confirm = "passkey"`: approving such a request needs a fresh + passkey in the web app, so `slop-approve` and Home Assistant can only deny it. Deploys to routers + are a typical use. +- `auto` operations are rate-limited per requester, so a looping agent can't hammer boxes or APIs. +- Pending requests are capped per requester and overall to limit notification spam. If the broker + restarts, pending requests and leases are dropped. + +### Home Assistant notifications + +The broker keeps an outbound connection to Home Assistant's +[WebSocket API](https://developers.home-assistant.io/docs/api/websocket/) and sends a +[Companion actionable notification](https://companion.home-assistant.io/docs/notifications/actionable-notifications/) +for each `ask` request. + +- The notification text is built from the scope, followed by the agent's label. Requests that + reveal a secret or change recipients are marked. +- Notifications are sticky and persistent: tapping one doesn't remove it, and before Android 14 it + can't be swiped away either. The broker clears each one once its request is answered, expires or + is cancelled. Since Android 14, users can dismiss even persistent notifications, and apps can't + prevent it. A dismissed request stays pending until it's answered elsewhere or expires. +- A possible fix: the Companion app fires `mobile_app_notification_cleared` when a notification is + dismissed. The broker could watch for it and re-post the notification while its request is still + pending, on a quiet notification channel so it doesn't alert again. Check first that the event + carries the notification's `tag`. The approvals web app (below) makes this matter less. +- Action IDs are random and never shown to the VM. A reply must match a live action and the + configured `device_id`: the Companion app's own ID, which differs from the device registry's. + The broker logs the ID of any answer it ignores, which is how to find it. Home Assistant, and + anyone who can fire events on it, is trusted to approve. +- If the connection fails, requests stay pending; a failure never approves anything. When the + broker reconnects, it reissues pending notifications with new action IDs. + +### Approvals web app + +Phone notifications are easy to lose, and a terminal isn't always at hand. The broker serves a web +app (`services.slop-broker.web`, code in [`src/web`](../src/web)) that makes approving reliable, and +on a desktop shows what `slop-approve` can only print. + +- **The page is the source of truth.** It lists what's pending with full detail and the active + leases, and updates itself, so a dismissed or missed notification costs nothing; a notification + only points at its request. Requests that need a passkey are marked, with a padlock on their + approve buttons. +- **Audit log.** The log page groups the audit file by request: who asked, what, the outcome and + who approved it, with filters by requester, operation and outcome and a search. Each request's + page shows its full timeline, including the detail approvers saw, so a notification for a + request that's since been answered still leads somewhere useful. +- **Front end.** Server-rendered HTML that works without JavaScript; a small script refreshes the + list and manages notifications, and a service worker shows them. Everything shown passes through + the same filter as `slop-approve` for control and bidirectional characters, and a strict content + security policy allows only the app's own scripts. + +#### Sign-in + +The web app listens on the broker's box (loopback by default, `web.address`) behind a reverse +proxy that terminates TLS; only the proxy should reach it. Approvers sign in through an OpenID +Connect provider. [Pocket ID](https://pocket-id.org), which only uses passkeys, is the one it's +tested with, and the [demo](demo.md) runs it. + +- **Signing in.** The broker is an OIDC client (`web.clientId`, the `openidconnect` crate, with + PKCE), checking the ID token itself rather than trusting a header from the proxy. Only members of + `web.group` may sign in: the provider should restrict the client to that group, and the broker + checks the token's `groups` claim too. +- **Sessions.** A sign-in gives a session cookie (`tower-sessions`) that lasts seven days without + use. Sessions are kept in an SQLite database in the broker's state directory, so a restart + doesn't sign phones out. + Answers are POSTs that need the browser's `Origin` to be the app and the session's token. The + audit log names web approvers like `alice (web)`. +- **Per-request passkeys, optional.** Approving a request whose policy says + `confirm = "passkey"` sends the approver back to the provider with `max_age=0`, which makes it ask + for the passkey again. The sign-in remembers the request, the answer and a hash of what was + shown; the broker accepts it only if the ID token is the same account's and its `auth_time` is no + older than the challenge, and the request hasn't changed. Pocket ID was tested to prompt and + return a fresh `auth_time` for both `max_age=0` and `prompt=login`; a provider that doesn't + can't confirm these requests. The audit log names these approvers like `alice (web, passkey)`. +- **What a session trusts.** Anything that can use the approver's session can answer requests that + don't need a fresh passkey, including agents running as that user on a workstation. That's + accepted when agents mostly run in the agents' VM; per-request passkeys cover operations where it + matters. + +#### Notifications + +The web app sends [Web Push](https://web.dev/articles/push-notifications-overview) notifications to +every device an approver turns them on for. Each links to its request; on desktop browsers and +Android it also has **Once** and **Deny** buttons (Android shows at most two), which the service +worker answers with the session like the page does. Requests that need a passkey only offer +**Deny**. The broker clears a notification once its request is answered or expires. + +- **Privacy.** Payloads are encrypted to the browser, so the push service (Google, Mozilla, Apple) + sees only timing and size. The broker signs pushes with a VAPID key it creates in its state + directory. +- **Where it works.** Desktop browsers deliver pushes while the browser is running, with or without + the tab. Android delivers them with everything closed. iOS (16.4 and later) only does once the + app is added to the Home Screen, and shows no buttons. +- **Endpoints.** The broker only accepts subscriptions at the major push services (Google's + `fcm.googleapis.com` and `jmt.google.com`, Mozilla, Apple, Microsoft), so a session can't make + it send requests elsewhere. + +| Channel | Arrives with the app closed | Action buttons | Who can read it on the way | Needs | +|---|---|---|---|---| +| Web Push to the web app | Android; desktop while the browser runs; iOS 16.4 and later once added to the Home Screen | Yes, except on iOS | Nobody: the payload is end-to-end encrypted to the browser | An OIDC provider and a reverse proxy | +| [Home Assistant Companion](#home-assistant-notifications) | Yes | Yes | Google: pushes go through Firebase Cloud Messaging, encrypted only in transit, except with Local Push while the app holds its own connection to Home Assistant | Home Assistant | + +### Audit log + +Each request, decision, approver, lease use and result is an event with the request's ID. The +broker writes it to the journal as a line of text and to `audit.jsonl` in its state directory as a +line of JSON. `slop-approve log [-n 50] [--json]` shows the recent events through the approve +socket, with each request's full detail. Secret operations will record the file and a hash of the +ciphertext before and after, never values. + +## Operations + +### Box queries and SSH + +- Targets are named in trusted config (`services.slop-broker.ssh.targets`), normally the + deployment's deploy-rs nodes. `--host` covers boxes outside them (OpenWrt, switches) with an + explicit `user@host` and port. +- SSH runs with options fixed by the broker: `-F none`, the key with `IdentitiesOnly`, no agent, + `BatchMode`, no forwarding or local commands, and the broker's own `known_hosts`. +- `ssh` joins its arguments into a string that the remote shell runs. Because of that, a + free-form command's text can't be judged as read-only, so `slop ssh` should always be `ask`. +- The fixed queries (`status`, `logs`, `failed`) validate their arguments (unit names, `--since`, + line counts), and the broker builds the quoted remote command. That makes them safe to run as + `auto`, which covers most of what agents need SSH for without prompting. + +### Deploys + +`slop deploy … [--commit ] [--boot]` deploys a pushed commit of a +[deploy-rs](https://github.com/serokell/deploy-rs) flake to one or more targets, each a node (all +its profiles, like `deploy .#node`) or `node.profile` (such as `host.container-web`). The client +resolves `--commit` (default `HEAD`) to a full ID in its checkout. + +1. **Describe, then approve use of the builder.** The broker runs the builder over SSH. The + builder is a user without keys, `slop-broker-build`, whose key's forced command is + `slop-broker builder` ([`services.slop-broker-builder`](../nix/modules/nixos/builder.nix)). + It fetches every branch from the Git server with a read-only key, so the agent never supplies + the source, and refuses commits that aren't on a branch. This first stage runs only Git: it + returns the commits since the main branch, their diffstat and their diff. Evaluation runs + agent-written Nix, so it waits for a separate `builder` request to be approved, which shows + those. Its scope is empty, so a lease lets the agent build any commit for a while; rules see + the `commit`, `on_branch` (whether it's already on the main branch) and `for` (`deploy` or + `build`). +2. **Build.** The builder evaluates the targets' deploy-rs profiles and builds them with the box's + Nix daemon. Only `git` gets the repository key, never the evaluator. Build logs stream to the + agent. One build runs at a time. +3. **Compare, before approval.** The broker copies the closures to each node, as deploy-rs does + (nodes substitute what the caches have; progress streams to the agent), and runs a fixed + read-only script on the node that compares each profile with the one installed. Nothing runs as + root, and no agent-written code runs. +4. **Approve.** One approval covers every target, the commit and the mode. Policy rules see one + scope per target (`node`, `profile`, `mode`, `commit`), and the strictest answer applies, so + for example a rule can allow routers only `boot`. +5. **Activate, once approved.** On every node at once, the broker runs deploy-rs's `activate-rs` + on each profile in deploy-rs's order, as root through the target's `sudo` command (`sudo -u` by + default), inside a transient unit (`systemd-run`). The activation therefore finishes even if the + connection drops, including when the broker deploys its own box and restarts. Output comes back + prefixed with the node. Deploys run in parallel; an agent that needs an order sends separate + requests. + +There is no magic rollback, unlike deploy-rs from a workstation. `--boot` makes the new +configuration the boot default without switching to it. Activation, including `dry-activate`, runs +the new system's own code as root, so none of it happens before approval. + +#### Approval contents + +Package versions come from `nix store diff-closures`. Configuration changes come from comparing +the two profiles' `etc` trees, whose entries are links into the store: changed, added and removed +systemd units (drop-ins count as their unit) and `/etc` files. That approximates what activation +will restart without running anything. A kernel or initrd change is called out because it needs a +reboot. The commit messages and diffstat are Git's, from the commits since the main branch. The +full view, in `slop-approve show ` or the web app, looks like this: + +```text +deploy hub (switch) at 3f9c2e1a8b0c +Commit 3f9c2e1a8b0c4d… +Commits: + 3f9c2e1 nixos/hub: Update Home Assistant + 8a1b7d0 nixos/hass: Add Zigbee coordinator + nixos/boxes/hub/containers/hass.nix | 14 +++++++++----- + 1 file changed, 9 insertions(+), 5 deletions(-) +hub.system (switch): + packages: no version changes + changed units: container@hass.service +hub.container-hass (switch): + packages: + home-assistant: 2026.11.1 → 2026.11.2, +3.4 MiB + python3.13-zha: 0.0.71 → 0.0.72 + changed units: home-assistant.service + changed files: /etc/hass/configuration.yaml +``` + +The phone notification carries only the first line and the label. It isn't the place to review a +large deploy. For those, approve from the web app or a terminal. + +### Binary cache + +Anything in a cache's store is signed and trusted by every box that uses it. A path built inside +the agents' VM proves nothing, because the agent could upload a different output under the hash of +a real derivation. So the cache is filled only from builds done by the builder (`slop build`): + +- `slop build … [--commit ]` works like a deploy up to approval: once use of the + builder is approved, it builds the flake attributes, and the `build` request shows the commits + and each output with its closure size. The `builder` approval is where a person reviews the + source; a policy can then let `build` push without asking again. +- Once approved, the broker pushes the outputs with `nix copy --to ssh-ng://` as the store's owner + (`services.slop-broker.cache`). That key's forced command + ([`services.slop-broker-cache`](../nix/modules/nixos/cache.nix)) allows only `nix-daemon --stdio` + on the cache's store and `root …`, which adds GC roots under `gcroots/slop-broker`. +- The broker adds the roots before copying, so a garbage collection in that store can't take the + paths mid-copy. A daily timer removes roots `keepDays` after their path was last pushed + (`services.slop-broker-cache`), and the store's next collection takes the paths: agent builds are + for sharing for a while, not for keeping. + +## Planned operations + +### Secrets + +The broker gets its own age identity, added as a recipient of the secrets it may handle (next to +the people's keys), so no person's key goes to the broker's box. Adding it to an existing +repository needs one full rekey. + +The agent sends the current `.age` file with each request, and the broker returns new ciphertext. +The broker never writes to a checkout. + +| Command | Result | Value enters VM? | +|---|---|---| +| `keys ` | Key names of an env, JSON or YAML secret | No | +| `set ` (value on stdin) | That field replaced, re-encrypted | Only what the agent sent | +| `set --whole` | Whole file replaced | Only what the agent sent | +| `generate --type password\|hex\|base64\|wireguard\|ssh-ed25519\|age` | Value created by the broker; keypair types return the public half | No | +| `rekey -r …` | Re-encrypted to the given recipients | No | +| `read ` | Plaintext | Yes, so always `ask`, never leased | + +- The requester lists the recipients. The broker names each one from a trusted list of known keys + (such as host keys and people's keys on the main branch), and shows changes from the file's + current recipients. An unknown key is flagged in the approval. This avoids evaluating + agent-written Nix just to get a recipient list. +- Encrypting to new recipients is done offline (`rage -r`) and needs no broker. +- The operations work for any repository that uses age files with the broker as a recipient. + +### DNS + +For public zones that are edited through a provider's API rather than from Nix config. Zones that +come from Nix config are changed with commits and deploys instead. Cloudflare is the first +provider. + +- `slop dns list [name]` shows the live records. `slop dns set … + [--ttl] [--proxied]` replaces the record set for that name and type, and `slop dns delete + ` removes it. +- The approval shows the record set before and after, read live from the provider. Leases are + scoped by name and type. +- The broker uses its own API token, limited to DNS edits in the allowed zones and separate from + any other automation's tokens. +- Policy denies zone apexes, `NS`, `MX` and `_acme-challenge` names by default. Records the broker + creates get a record comment, so the approval can say whether an agent is changing one of its own + records or an existing one. + +### Previews + +`slop preview 5173 [--name foo] [--public] [--auth basic|sso] [--ttl 4h]` publishes a dev server +in the agents' VM under a wildcard domain until its TTL expires. + +- A reverse proxy serves the wildcard domain with a wildcard certificate and proxies to the broker. + The broker looks up the host in its active previews and connects to the guest port over vsock. + The VM still accepts no inbound connections. + +#### Access + +The hostname and the authentication are chosen separately. + +- **Secret URL (default):** the hostname is an unguessable label, for example + `foo-<26 base32 characters>.`, which is 128 random bits after the optional name. + Because DNS and the certificate are wildcards, the name never appears in the zone or in + Certificate Transparency logs. Unknown hostnames get the same 404 as expired ones. Responses + carry `Referrer-Policy: no-referrer` and `X-Robots-Tag: noindex`. +- **`--public`:** the hostname is just the name (`foo.`). Without `--auth` this is a fully + public site. Public names are never leased, so each one needs its own approval. +- **`--auth basic`:** adds basic auth with a generated password. It's shown in the approval and + returned to the agent, which needs it to test the page and controls the content anyway. +- **`--auth sso`:** adds the proxy's existing single sign-on. +- The secret URL still leaks through browser history, shared links and resolver logs. Use an auth + option for anything that matters. +- If the preview domain is a subdomain of other services' domain, preview pages are same-site with + them: they can set cookies on the parent domain, and browsers send `SameSite=Lax` cookies + (including an SSO session) with their requests to those services. A separate registrable domain + avoids this. + +### TCP forwards and a cache for VM builds + +- **TCP forwards:** time-limited access from the VM to one internal `host:port` (for example a + database), approved per destination. +- **VM-built paths:** a separate store with its own signing key, trusted only by the agents' VM and + by boxes that opt in. Useful for sharing agent build artifacts or keeping them across VM + rebuilds. + +Both wait until a concrete need comes up. + +## Agent-facing docs + +- **Agent context:** the package ships [`slop-tools.md`](../slop-tools.md), which describes the + `slop` CLI and how requests behave (they block while waiting for approval, so no retrying in a + loop). `slop guide` prints it, and it's installed as `share/slop-broker/slop-tools.md` for + deployments to add to their agents' rules. Update the guide with each new operation. It asks + agents to suggest new operations when they would otherwise work around a missing one or keep + asking for the same `slop ssh` approval. +- **Agent permissions:** the broker is the gate, so an agent's own permission prompt for `slop` + would only ask twice; allow `slop` and keep denying direct use of deploy tools and keys. +- **Deployment docs:** deployment-specific notes (which nodes exist, their login shells, where the + Git server is) belong in the deployment's own agent rules. + +## Scope + +- **Out of scope for now:** secret tools other than age (such as `sops`), and a general + credential proxy for other APIs (forges, package registries). Agents keep using deploy keys of + their own for pushing. If more API operations are needed later, add them one at a time like + `dns`. + +## Tests + +- **Unit and integration tests** cover the protocol, policy, approvals, leases, SSH execution + against a fake `ssh`, the builder against a local Git repository, and the web app's pieces. They + run in the package build, or in the devenv shell with `cargo test` (`devenv test` adds clippy). +- **VM test** ([`vm-test.nix`](../nix/vm-test.nix)): a minimal system running the broker through + the `services.slop-broker` module, with its real service hardening, over vsock loopback, against + a local `sshd`. Run it after changing the module, the service or the transport (it needs KVM): + `vm-test` in the devenv shell, or `nix build -L .#checks.x86_64-linux.vm`. +- **Demo** ([`demo.md`](demo.md)): not a test, but the quickest way to try the web app and + passkey approvals by hand. +- New operations add tests against fakes of what they call (deploy-rs, the DNS provider's API).