# Architecture
How the code is put together, and how to extend it. The design and its rationale are in
[`design.md`](design.md).
## Overview
### Boxes
```mermaid
flowchart TB
subgraph vm["Agents' VM"]
slop["slop"]
end
others["slop on other boxes"]
subgraph box["Broker's box"]
broker["slop-broker serve"]
approve["slop-approve"]
end
subgraph builderbox["Builder's box (can be the broker's box)"]
builder["slop-broker builder
(its own user; only a read-only Git key)"]
end
browser["Web app in a browser"]
slop -- "vsock" --> broker
others -- "SSH, forced command" --> broker
approve -- "approve.sock, or SSH" --> broker
browser -- "HTTPS through a reverse proxy;
OIDC sign-in" --> broker
broker -- "Web Push" --> browser
broker -- "SSH, forced command" --> builder
builder -- "read-only key" --> git[("Git server")]
broker -- "SSH, deploy key" --> nodes["Boxes
(deploy-rs nodes)"]
broker -- "ssh-ng, cache key" --> cache[("Binary cache")]
```
- **`slop-broker serve`** holds every credential and runs every privileged step. Requesters reach it
over vsock, a Unix socket or SSH; approvers over `approve.sock`, SSH or the web app.
- **The builder** is a separate user with only a read-only Git key, on any box the broker can reach
over SSH; usually the broker's own, reached over SSH to localhost.
- It fetches commits itself, and evaluates and builds them (agent-written Nix).
- It reads the main branch for the deploy-rs nodes and for secrets.
- **Boxes and the cache** are reached over SSH with the broker's own keys, using options the broker
fixes.
### Inside the broker
The parts of `slop-broker serve`, and the module each is in. The builder is a separate process the
broker only talks to through `builder.rs`, over SSH; see [Inside the builder](#inside-the-builder).
```mermaid
flowchart TB
requesters["Requesters"] --> listeners
approvers["slop-approve"] --> approve
browser["Browsers"] --> web
subgraph serve["slop-broker serve"]
listeners["Listeners
server.rs, remote.rs"] --> handler["Request handler
server.rs"]
handler -- "names a node" --> targets["Targets
targets.rs"]
handler -- "plan, prepare, execute" --> ops["Operations
ops/"]
handler -- "authorize" --> policy["Policy
policy.rs"]
handler -- "ask" --> queue["Pending requests, leases, limits
queue.rs"]
approve["Approver connections
approve.rs"] -- "decide" --> queue
web["Web app
web/"] -- "decide" --> queue
targets --> client["Builder client
builder.rs"]
ops --> client
ops --> exec["Processes: ssh, nix copy
exec.rs, ops/ssh.rs"]
handler --> audit["Audit log
audit.rs"]
approve --> audit
end
client -- "SSH" --> builder["slop-broker builder"]
exec --> boxes["Boxes and the binary cache"]
web -. "Web Push" .-> browser
```
- **Listeners** turn a connection into a requester's name and hand it to the handler.
- **The handler** (`server::handle`) takes one request through the steps below, and is the only
part that sends the requester messages.
- **Operations** (`ops::plan`, `ops::prepare`, `ops::execute`) know what each kind of request means:
its scope, what approvers see, and how to carry it out.
- **The queue** holds what waits for an approver. Approvers answer through `approve::approve`,
whichever way they connect, and the handler waiting on that request carries on.
- **Targets** keep the main branch's deploy-rs nodes, from the builder.
### Inside the builder
`slop-broker builder` (`builder::worker`) is the forced command of the builder user's
`authorized_keys`, so every SSH connection from the broker runs it once: it reads one
`BuilderRequest` on stdin, answers on stdout, and exits. Its log goes to stderr, which the broker
passes on to the requester, if one is waiting. It holds nothing but a read-only Git key.
```mermaid
flowchart LR
broker["Broker
builder.rs"] -- "SSH: one request,
one answer" --> worker["slop-broker builder
builder::worker"]
subgraph home["Builder's home"]
mirror[("repository.git
(bare mirror)")]
caches[("deploy-nodes/, secret-rules/
per main-branch commit")]
end
worker -- "git fetch, log, diff, ls-tree" --> mirror
mirror -- "read-only key" --> git[("Git server")]
worker -- "nix eval, nix build" --> daemon["nix-daemon"]
worker --> caches
```
What each request runs, and whose code, decides whether it needs an approval first:
| Request | Runs | Whose code | Approval first |
|---|---|---|---|
| `Describe` | `git fetch` of every branch, then `log`, `diff --stat` and `diff` since the main branch | None: Git only | No |
| `Nodes` | `nix eval` of `deploy.nodes` on the main branch | The main branch's | No |
| `Secret` | `git ls-tree` of the main branch, and `nix eval` of its rules file | The main branch's | No |
| `Build` | `nix eval` of the targets' profiles, then `nix build` | The requester's commit | Yes: `builder` |
- The main branch is protected, so evaluating it runs reviewed Nix; a requester's commit only
runs in `Build`, after an approver has seen its diff.
- `Nodes` and `Secret` evaluate once per main-branch commit and keep the result in
`deploy-nodes/` and `secret-rules/`, only for the newest commit.
- Locks in the home directory keep one fetch (`fetch.lock`) and one build (`build.lock`) at a time;
a waiting request says so in its log.
- If the broker closes the connection (the requester went away), the builder stops.
## 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 detail), `execute`, quoting |
| `src/targets.rs` | SSH targets: the main branch's deploy-rs nodes from the builder, looked up again when stale or when a request names an unknown node |
| `src/detail.rs` | What approvers see of a request (`Detail`: fields, tables, lists, text) and its text rendering |
| `src/ops/ssh.rs`, `src/ops/query.rs`, `src/ops/deploy.rs`, `src/ops/build.rs` | Operations; `deploy.rs` also parses the comparison script, `src/ops/inspect.sh` |
| `src/ops/secret.rs`, `src/ops/secret/format.rs` | Age secrets: what approvers see, encryption, generated values; env and JSON fields |
| `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also reads secrets and deploy nodes on the main branch |
| `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/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`), each page's Server-Sent Events (`events.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, among them the page script (`assets/app.js`) and idiomorph, vendored (`assets/idiomorph.js`) |
| `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`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs, host side and repository template (`demo/`, `packages..demo` and `demo-box`, and `host.nix`, which `devenv.nix` imports) |
| `devenv.nix` | The development environment and its scripts, with the demo's host side (`devenv up`) from `nix/demo/host.nix`; `nix develop` gives a plainer shell from `flake.nix` without them |
| `.gitea/workflows/ci.yaml` | CI: `nix flake check` |
## Request lifecycle
Every request takes the same steps, in `server::handle`. Secrets, deploys and builds add a
**prepare** step before approval, because approvers should see what a request really does; the
sections after this one describe each kind on its own.
### Every request
1. **Connect.** A listener names the requester:
- vsock by the peer's CID;
- the Unix request socket by the peer's UID;
- the remote socket by the `Hello` that `slop-broker remote` (the forced command) writes.
Anything unknown is refused and audited.
2. **Read.** `server::handle` reads one `ClientMessage::Request`, within 10 seconds, and starts two
tasks:
- a reader, which forwards `Stdin` to a channel, closes it at `StdinEnd`, and cancels the
request's `CancellationToken` when the connection closes or sends anything else;
- a writer, which sends every `ServerMessage` from an `mpsc` channel in order, and stops after a
terminal one.
3. **Plan.**
- The protocol version is checked.
- `Targets::refresh` runs if the operation names a node (see
[Queries and SSH](#queries-and-ssh)).
- `ops::plan` checks the already-typed `Operation` against config and returns `Parsed`: the
operation's name, its scope, what approvers see, limits and whether it reads stdin.
- An error is sent back and audited as `invalid`; otherwise the request is audited.
4. **Prepare**, for secrets, deploys and builds only (below).
5. **Authorize.** `authorize` evaluates the requester's policy for the operation:
- `deny` refuses;
- `auto` takes a rate-limit slot;
- `ask` uses a matching lease if there is one. Otherwise it submits the request to the queue,
sends `Pending`, and waits for a decision, the timeout or a disconnect.
6. **Run.**
- The handler sends `Approved { by, stdin }`; the client sends stdin only then, and only if
`stdin` is set (`secret set`). `ssh` carries its stdin in the request instead.
- `ops::execute` runs the operation with `Io` (the stdin channel, the output sender and the
cancel token) and returns an exit status and an optional `OpResult`.
- If the requester leaves, most operations notice the cancel token and stop. Those
`ops::outlives_requester` names (deploys) ignore it: `see_through` logs `detached` and
keeps waiting, so the outcome is still audited.
7. **Finish.** One terminal message (`Finished`, `Denied`, `Expired` or `Error`), or none if the
requester went away, then the connection closes.
### Queries and SSH
`status`, `logs`, `failed` and `ssh`: no prepare step, since the command is the whole story.
1. **Plan.**
- **Targets:** `Targets::refresh` asks the builder for the main branch's nodes
(`BuilderRequest::Nodes`) when they're more than a minute old, or when the request names one
it doesn't know and the last lookup is more than 10 seconds old. A failed lookup is logged and
the last nodes are kept.
- `ssh::check` refuses a node that isn't one of them.
- The scope is the destination: `{ target }`, or `{ host, port }` for `--host`. The command is
only in the detail, so a lease covers any command to the same destination.
- `ssh::detail` shows the command and all of its stdin, refusing stdin that isn't UTF-8 and
requests too long to show whole.
2. **Run.**
- `ssh::command` builds the `ssh` command with the broker's fixed options (see
[Execution](#execution)). The queries build the remote command themselves from validated
fields; `ssh` passes the requester's words as they are, for `ssh` to join.
- stdout, stderr and the exit status go back to the requester; `ssh`'s stdin is the bytes its
request carried.
### Secrets
`secret keys|read|set|generate|rekey`.
1. **Plan.** `ops::secret::plan`:
- the scope is `{ action, path }`;
- `read` is marked sensitive, can never run as `auto` and is never leased.
2. **Prepare.**
- **Policy first:** a request policy would deny stops here, before anything is looked up.
- **Look up:** the builder reads the main branch (`BuilderRequest::Secret`): which paths hold
the requester's ciphertext (by its Git blob ID), and the rules file's recipients for the path.
- **Detail:** what the content really is, and how the recipients differ from the rules. A
mismatch marks the request sensitive. Audited as `prepared`.
3. **Run.** `ops::secret::execute` decrypts with the broker's age identity, then:
- `keys` returns the key names (`OpResult::SecretKeys`);
- `read` writes the plaintext to stdout;
- `set`, `generate` and `rekey` encrypt the new plaintext to the recipients, adding the
broker's own key, and return it (`OpResult::Secret`, with the public half of generated
keypairs).
### Deploys
```mermaid
sequenceDiagram
participant S as slop
participant B as Broker
participant G as Builder
participant A as Approver
participant N as Node
S->>B: Request { Deploy }
B->>G: Describe(commit), Git only
G-->>B: commits, diffstat, diff
B->>A: "builder" request: commits and diff
A-->>B: once / lease
B->>G: Build(targets)
G-->>S: build logs
G-->>B: built profiles
B->>N: copy closures, compare (read-only)
B->>A: "deploy" request: packages, units, files
A-->>B: once / lease
B-->>S: Approved
B->>N: activate as root (systemd-run)
B-->>S: output, then Finished { exit }
```
1. **Plan.** `ops::deploy::plan`:
- the targets' nodes are refreshed and checked as for SSH;
- the scope is `{ targets, mode, commit }`, and each target also gets a rule scope, so a rule
about one node applies to any deploy that includes it.
2. **Prepare.**
1. **Policy first**, as for secrets.
2. **Describe:** the builder fetches every branch and returns the commit's log, diffstat and
diff since the main branch (`BuilderRequest::Describe`). Only Git runs.
3. **Builder approval:** `ops::builder_gate` makes a separate request for operation `builder`
(its scope and rule fields are in [the design](design.md#deploys)), and `authorize` handles
it like any other. Audited as `approved` with `step: builder`.
4. **Build:** the builder evaluates and builds the targets' profiles
(`BuilderRequest::Build`); its log goes to the requester.
5. **Copy and compare**, on every node at once: `nix copy` the closures (substituting on the
node), then compare them with what the node runs, read-only
([`inspect.sh`](../src/ops/inspect.sh)).
6. **Detail:** the commits, then the package, unit and file changes per profile. Audited as
`prepared`.
3. **Run.** `ops::deploy::execute` activates every node at once, its profiles in order, as root
through `systemd-run`. Each line of output is prefixed with `[node.profile]`; the exit status is
the first failure's. Inside the unit, `activate-rs`'s output goes through a `cat` that, once
the connection is gone, gives way to one discarding it, so a lost connection can't stop it.
Each unit is `slop-deploy--`.
### Builds
`build`: like a deploy up to building, then the binary cache instead of nodes.
1. **Plan.** `ops::build::plan` needs a cache; the scope is `{ attrs, commit }`, with a rule scope
per attribute.
2. **Prepare.**
1. **Policy first**, **describe** and **builder approval**, as for deploys.
2. **Build:** the builder builds the attributes (`BuilderRequest::Build`).
3. **Detail:** the commits, and each output's path and closure size.
3. **Run.** `ops::build::execute` adds GC roots for the outputs in the cache, then pushes them over
`ssh-ng`, and prints their paths.
### `requests`
Built in: the requester's own pending requests and leases. Always allowed, and not audited.
### Audit events
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` (cancelled), `detached` (the requester left an operation
that carries on), plus `invalid` and `unknown` peers.
## Protocol
Every connection carries CBOR messages (`ciborium`; byte strings via `serde_bytes`), each framed
with a 4-byte big-endian length (`LengthDelimitedCodec`, 1 MiB maximum). The types are in
`src/proto.rs`; values such as `NodeName` are from `src/types.rs` and validate when decoded.
### Requester and broker
A requester sends one `Request`, then stdin only after an `Approved` that asks for it (`ssh`
carries its stdin in the request, so approvers see it). The broker
sends any number of progress messages and closes after a terminal one.
```rust
enum ClientMessage {
Request(Request),
Stdin(bytes),
StdinEnd,
}
struct Request {
version: u32, // PROTOCOL_VERSION; the broker refuses others
label: Option, // agent-supplied, shown as such
operation: Operation,
}
enum Operation {
Ssh { destination: Destination, command: Vec, stdin: Option },
Query { destination: Destination, query: Query },
Deploy { targets: Vec, commit: CommitId, boot: bool },
Build { attrs: Vec, commit: CommitId },
Secret(SecretOp),
Requests,
}
enum Destination {
Node(NodeName), // a target
Container { node: NodeName, name: ContainerName }, // `node.container-`
Host { user: UserName, host: HostName, port: u16 }, // `--host`
}
enum Query {
Status { unit: Option },
Logs { unit: UnitName, lines: Lines, since: Option },
Failed,
}
enum SecretOp {
Keys { file: SecretFile },
Read { file: SecretFile },
Set { path: SecretPath, base: Option, target: Target, recipients: Vec },
Generate { path: SecretPath, base: Option, target: Target, kind: GenKind,
recipients: Vec },
Rekey { file: SecretFile, recipients: Vec },
}
struct SecretFile { path: SecretPath, ciphertext: bytes }
enum Target { Whole, Field(SecretKey) }
enum GenKind { Password, Hex, Base64, Wireguard, SshEd25519, Age }
enum ServerMessage {
Pending { id: String, summary: String },
Approved { by: ApprovedBy, stdin: bool }, // ApprovedBy: Policy, Lease or Approver
Info(String),
Stdout(bytes),
Stderr(bytes),
// terminal:
Finished { exit: i32, result: Option },
Denied(String),
Expired,
Error(String),
}
enum OpResult {
Requests { pending: Vec, leases: Vec },
SecretKeys(Vec),
Secret { ciphertext: bytes, public: Option },
}
```
### Approvers
Any number of requests per connection, each answered by one response.
```rust
enum ApproveRequest {
List,
Decide { id: String, decision: Decision }, // Decision: Once, Lease(seconds) or Deny
Log { count: usize }, // at most 200 records
}
enum ApproveResponse {
Pending(Vec),
Recorded,
Log(Vec),
Error(String),
}
struct PendingInfo {
id: String,
requester: String,
op: String,
summary: String,
detail: Detail, // src/detail.rs
label: Option,
sensitive: bool,
passkey: bool, // only the web app can approve it
offers: Vec,
expires_in: u64,
}
```
### The remote socket and the builder
```rust
// Written once by `slop-broker remote`, as one length-prefixed frame without the codec, so
// nothing after it is read ahead; either protocol above follows.
struct Hello { role: Role, name: String } // Role: Requester or Approver
// One request on the builder's stdin, one answer on its stdout; logs on stderr.
enum BuilderRequest {
Describe(CommitId), // -> Description { log, stat, diff, on_branch }
Build(BuildRequest), // -> BuildResult { profiles, outputs }
Secret(SecretRequest), // -> SecretContext { branch, commit, paths, recipients }
Nodes, // -> Nodes { commit, nodes: { name: Node } }
}
```
### Rules
- 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.
- `slop` exits with the operation's status for `Finished` and 125 for anything else. `--json`
prints an `OpResult` as JSON.
## Policy, leases and limits
What a policy holds is in [the design](design.md#approvals-and-policy). The module writes
`services.slop-broker.policies` into the broker's TOML, for example:
```toml
[requesters.agent]
vsock_cid = 3626
policy = "agents"
[policies.agents]
max_pending = 4
auto_per_minute = 60
[policies.agents.ops.query]
action = "auto"
[policies.agents.ops.ssh]
action = "ask"
leases = ["5m", "1h"]
[[policies.agents.ops.ssh.rules]]
match = { target = "router*" }
action = "ask"
confirm = "passkey"
```
- `OpName` names the operations, and `OpName::fields` the scope fields their rules can match.
- serde refuses an unknown operation;
- `Config::validate` (called by `Broker::new`) refuses a rule matching an unknown field, and a
requester whose policy is missing;
- the module types both, and asserts the policy exists;
- `ops::plan` asserts, in debug builds, that the scopes it makes only use known fields.
### Deciding
`policy::evaluate` answers a request from its operation's entry and its scope:
1. No entry for the operation: deny.
2. The first rule whose `match` globs (`*`, `?`) all fit the scope wins. It replaces `action`, and
`leases` and `confirm` where it sets them.
3. The operation's `Limits` apply on top, whatever the policy says:
- `never_auto` turns `auto` into `ask`;
- `never_lease` removes leases.
`secret read` sets both.
### Leases
- A lease is keyed by the requester, the operation name and the scope's canonical JSON
(serde_json maps are sorted).
- The command is in the detail, not the scope, so an SSH lease covers any command to the same
target.
- An answer with a lease the policy doesn't offer is refused.
### Limits
- Pending requests, per requester (`max_pending` in the policy) and overall.
- `auto` requests per minute, per requester (`auto_per_minute`).
- A shared policy shares the numbers, not the counters or leases.
- Counters, leases and pending requests are only in memory.
## Execution
Every process the broker starts goes through `src/exec.rs`:
| Function | For | Input and output |
|---|---|---|
| `exec::run` | Operations the requester watches | The given stdin, or none; stdout and stderr as frames |
| `exec::capture` | The broker's own steps | Captured, none of the requester's stdio |
| `exec::run_prefixed` | Several nodes sharing the output (deploy copies and activations) | No stdin; each line prefixed with its node |
- Each process runs in its own process group. On cancellation the group gets `SIGTERM`, then
`SIGKILL` after five seconds.
- A spawn that fails with `ETXTBSY` is retried. It happens when another thread forks while an
executable is still open for writing (seen in parallel tests).
SSH always uses the options `ssh::command` fixes, which
[the design lists](design.md#box-queries-and-ssh). Arguments from the requester are validated so
none can be read as an option, and `--` comes before the hostname.
## Approvers
| Approver | Connects through | Recorded as |
|---|---|---|
| `slop-approve` on the broker's box | `approve.sock`, for the `slop-broker-approve` group | The user name |
| `slop-approve` on another box | SSH, a key in `sshApprovers` | ` (ssh)` |
| The web app | OpenID Connect | ` (web)`, or ` (web, passkey)` |
- A requester's UID is refused on `approve.sock` even if it's in the group.
- 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
| Module | On | Sets up |
|---|---|---|
| [`services.slop-broker`](../nix/modules/nixos/broker.nix) | The broker's box | The service and its config, and the `slop` user for requesters and approvers over SSH |
| [`services.slop-broker-builder`](../nix/modules/nixos/builder.nix) | The builder's box, which the broker reaches over SSH (to localhost when they share one) | The `slop-broker-build` user, its read-only Git key and its forced command |
| [`services.slop-broker-cache`](../nix/modules/nixos/cache.nix) | The cache's box | A forced command for the store's owner, and a timer that expires roots ([design](design.md#binary-cache)) |
| [`programs.slop`](../nix/modules/home-manager/slop.nix) (home-manager) | Requesters' and approvers' boxes | Both clients, their keys and the config pointing at them ([design](design.md#other-requesters-and-approvers)) |
### The broker's module
- **Config:** options become the TOML config (`pkgs.formats.toml`, nulls dropped).
- **Parts:** each operation group has its own section, and some need others:
- `ssh` and `deploy` need each other: SSH targets are the deploy-rs nodes on the main branch,
which the builder reads, so adding a box needs a commit there rather than a new broker config.
- `cache` (builds) and `secrets` need `deploy`, whose builder builds and looks secrets up.
- `web` needs a URL, an issuer and a client secret.
- **Credentials** arrive through `LoadCredential` under fixed names (`ssh-key`, `cache-key`,
`oidc-secret`, `age-identity`), which `config::credential` resolves in `$CREDENTIALS_DIRECTORY`.
- **Sandbox:** the service runs as `slop-broker` with a strict systemd sandbox. An operation that
needs more (address families, writable paths, helper users) adds it in the module; rerun the VM
test afterwards.
- **Remote keys** become `authorized_keys` entries for `slop`, each with a forced
`slop-broker remote `. The broker gets `slop`'s group to share the remote socket.
### Left 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.
- 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. Name it in `OpName` (`src/policy.rs`), which policies are keyed by, with the fields its rules
can match in `OpName::fields`; add both to the NixOS module's `opFields` and to the design's
policy table.
3. `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. `Parsed::new` defaults everything
else.
- Put anything shown but not part of the approval (commands, diffs) in `detail`: short facts
as fields, anything with rows as a table or list, and preformatted text as a text section.
Tone a field or row `Warn` when approvers must notice it, and mark the field `headline` if
notifications must keep it. Mark commands, paths and the like as code, and diffs with
`Section::diff`.
- Set `limits` and `sensitive` where the operation reveals or redistributes secrets.
- If approvers need something looked up first (as secrets do, on the main branch), list the
operation in `prepares`, and fill in `detail` and `prepared` in a `prepare` arm; it runs
before approval and only if policy wouldn't refuse.
4. Add the client subcommand in `src/bin/slop.rs` (clap parses validated types directly through
`FromStr`), and how to print its `OpResult`.
5. Tests: parsing in the module, behaviour in `tests/broker.rs` with fakes of what it calls.
6. Module options and sandbox changes; the deployment's policy entry follows in its own repo.
7. 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 copy from the builder's store to a node has one `NIX_SSHOPTS` for both connections.
The builder's store URL therefore carries its port and key (`ssh-ng://user@host:port?ssh-key=`):
Nix puts them after `NIX_SSHOPTS`, and for `-p` the last value wins (see
`DeployConfig::builder_store`).
- 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.
## Tests
How to run them is in [`AGENTS.md`](../AGENTS.md#commands).
| Tests | Cover |
|---|---|
| Unit tests, in each module | Parsing and validation, policy, leases, details, the web app's pieces |
| [`tests/broker.rs`](../tests/broker.rs) | Requests end to end, against a fake `ssh` and fakes of what operations call |
| [`tests/builder.rs`](../tests/builder.rs) | The builder against a local Git repository |
| [`nix/vm-test.nix`](../nix/vm-test.nix) | The broker through `services.slop-broker`, with its real service hardening, over vsock loopback, against a local `sshd` and a real builder; run it after changing the module, the service or the transport |
| [The demo](demo.md) | Not a test, but the quickest way to try the web app, passkey approvals, secrets and deploys by hand |
Gaps:
- The VM test needs KVM.
- It doesn't cover deploys or the web app; the demo covers the web app by hand.