---
name: slo-gen
description: Operate slo-gen, the sg CLI that hardens Ubuntu servers into LXD machines, forms LXD clusters and deploys applications from genesis/v1 YAML specs. Use when the user mentions sg, slo-gen, Slo Genesis, machine.yaml, cluster.yaml or application.yaml, or wants to provision LXD hosts, clusters, containers, VMs, PostgreSQL, ClickHouse or HAProxy with sg.
---

# Using slo-gen (`sg`)

slo-gen (Slo Genesis) is a Go CLI named `sg`. It turns plain Ubuntu LTS servers into hardened, managed LXD machines, forms LXD clusters over three or more of those machines, and deploys applications (containers, VMs, PostgreSQL or ClickHouse services, an HAProxy load balancer) onto a cluster. `sg panel` serves a local web UI and JSON API over the same services.

Docs: https://gen.slostack.io/docs. Version described here: `0.1.0-dev`. It is work in progress; treat every host it manages as one you can rebuild.

## How to behave when you operate sg for a user

1. **Never answer a confirmation for the user.** Mutating verbs print a plan and ask `... [y/N]:`. Show the user the plan and let them answer. Do not add `--yes` unless the user explicitly asked you to apply without a prompt, after they have read the same plan.
2. **Plan before you apply.** Run the read-only verb first (`sg machine plan`, `sg application plan`, `--dry-run` for scale and upgrade) and summarise what will change, the risk grades, and anything marked `high` or `data loss`.
3. **Never put secret values in a spec, a command line you echo, or a file you commit.** Specs name environment variables (`TS_AUTHKEY`, `admin_password_env: SG_PG_ADMIN_PASSWORD`). Ask the user to export them in their own shell.
4. **Never edit or delete `.sg/state.db`.** It is the ledger, the only proof of what sg owns. Don't run SQL against it.
5. **Never edit `~/.ssh/known_hosts` on the user's behalf** to get past a host-key error. Tell the user to verify and add the key themselves.
6. **Keep every spec for one estate in one directory.** The ledger is `<spec-dir>/.sg/state.db`; machines, cluster and applications must share it.
7. **Destroy is destructive.** `sg machine destroy` deletes instances and the ZFS pool file. `sg application destroy` deletes owned instances **and their volumes (data)**. Confirm intent in plain words before running either.
8. **Don't use the safety-override flags (`--force-volume-share`, `--confirm-root-data`, `--force`) to make an error go away.** Explain the refusal and let the user decide.
9. If a command exits 1 with a refusal, read the message: it names the rule. Fix the spec or the environment; don't retry blindly.

## The model: spec, plan, apply, ledger

- Every resource is a declarative YAML spec with `api_version: genesis/v1`. Unknown or wrongly typed fields are rejected. Names are lowercase DNS-safe labels.
- `plan` is read-only: it observes hosts over SSH and prints ordered changes, each with a risk grade (`none`, `low`, `medium`, `high`).
- Apply verbs (`create`, `deploy`, `rollback`, `destroy`, ...) build a **fresh** plan, print it, and ask `[y/N]`. Only an answer starting with `y`/`Y` continues. `--yes` skips only that question, never a safety or ownership check.
- Apply stops at the first failure and records it. Ctrl-C cancels cleanly: no new change starts, cleanup runs, the run is recorded as aborted.
- The ledger records every change sg makes. Rollback and destroy act only on what the ledger proves sg created; anything else is printed as `retained: ... is not owned by sg` and left alone.

Exit codes: `0` success, help, a completed read-only report (even one showing drift), or a declined confirmation. `1` runtime failure, safety refusal, configuration error (`sg <group> <verb>: <error>` on stderr). `2` usage error (bad flag, unknown group or verb).

## Prerequisites

- The `sg` binary on the controller (the user's workstation): `curl -fsSL https://gen.slostack.io/install.sh | bash`, then `sg version`.
- Target hosts: Ubuntu `22.04` or `24.04` LTS, reachable over SSH as root with a key.
- A controller-local SSH **private** key (connects) and a separate **public** key file (installed for the deploy user).
- The host key already in `~/.ssh/known_hosts` (`ssh root@<host>` once and verify the fingerprint).
- A Tailscale auth key exported in an environment variable (default `TS_AUTHKEY`). The controller should be on the same tailnet: cluster addresses, the LXD API and application ports live there.

Environment settings read by `sg` (all optional):

| Variable | Default | Meaning |
|---|---|---|
| `SG_ENV` | `development` | Named environment, must not be empty |
| `SG_LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` |
| `SG_STATE_DIR` | `.sg` | Ledger directory. Relative values resolve against the spec file's directory (CLI) or the launch directory (`sg panel`) |

## Machines

```bash
sg machine init --name node-a --address 203.0.113.10 \
  --key-path ~/.ssh/id_ed25519 --deploy-public-key-path ~/.ssh/id_ed25519.pub \
  --distro ubuntu-24.04 --output machine.yaml   # writes the spec; local only
sg machine init --config machine.yaml            # validate + register; local only
sg machine plan --config machine.yaml            # read-only, connects over SSH
export TS_AUTHKEY=...                            # user does this, never you
sg machine create --config machine.yaml          # applies after [y/N]
sg machine status --config machine.yaml          # read-only drift report, never repairs
sg machine rollback --config machine.yaml [--all] [--force]   # undo last run's reversible changes
sg machine destroy --config machine.yaml [--with-packages]    # full sg-owned teardown
```

`create` applies up to eight changes, in this order: `install.packages`, `harden.ssh`, `create.deploy-user`, `install.tailscale`, `firewall.guard`, `storage.zfs`, `install.lxd`, `verify.isolation`. Each is verified after it runs. Rollback never removes `storage.zfs` or `install.lxd` (they hold data); only `destroy` does. sg never reboots a host; it warns when a reboot is pending.

Minimal `machine.yaml` (everything else has a default):

```yaml
api_version: genesis/v1
machine:
  name: node-a
  address: 203.0.113.10                  # what sg SSHes to
  ssh:
    key_path: ~/.ssh/id_ed25519          # controller-local PRIVATE key; user defaults to root
bootstrap:
  deploy_user:
    key_path: ~/.ssh/id_ed25519.pub      # controller-local PUBLIC key for the deploy user
```

Fields and defaults:

| Field | Default | Notes |
|---|---|---|
| `machine.distro` | `ubuntu-24.04` | `ubuntu-22.04` or `ubuntu-24.04` |
| `machine.ssh.user` | `root` | |
| `bootstrap.packages` | `[fail2ban, unattended-upgrades]` | |
| `bootstrap.ssh_hardening.password_root_login` | `false` | |
| `bootstrap.ssh_hardening.password_authentication` | `false` | |
| `bootstrap.deploy_user.name` | `deploy` | |
| `bootstrap.deploy_user.key_path` | ssh key path + `.pub` | Must be a public key file; validated before host contact |
| `bootstrap.firewall.guard` | `true` | nftables guard in front of LXD |
| `bootstrap.firewall.lxd_api_allow_from` | `[]` | Individual tailnet IPv4 addresses (inside `100.64.0.0/10`) allowed to reach the LXD API; no CIDRs |
| `bootstrap.firewall.lxd_api_allow_all_tailnet` | `false` | Let every tailnet client reach the LXD API/UI on `:8444`; conflicts with a non-empty allow list |
| `bootstrap.tailscale.enabled` | `true` | |
| `bootstrap.tailscale.auth_key_env` | `TS_AUTHKEY` | Name of the env var, never the key |
| `lxd.channel` | `5.21/stable` | |
| `lxd.api_address` | `tailnet:8444` | Never port 8443, never a wildcard or loopback |
| `lxd.storage.driver` | `zfs` | `zfs`, `btrfs` or `dir` |
| `lxd.storage.pool_file_size` | `150GiB` | `NGiB` or `NMiB` |
| `lxd.storage.arc_max` | `4GiB` | ZFS ARC cap |
| `lxd.network.bridge` | `lxdbr0` | |
| `lxd.network.subnet` | resolved once, before planning | CIDR like `10.81.0.1/24`; must avoid `172.16.0.0/12` and `100.64.0.0/10` |
| `lxd.network.nat` | `true` | |
| `lxd.network.ipv6` | `none` | Must be `none` while the guard is on |
| `lxd.profiles` | `default`, `task-vm` (2 CPU, 4GiB) | Unique, non-empty names |

## Clusters

Needs three or more machines created by sg **in the same ledger**, all on the same LXD channel. `members[0]` bootstraps. Membership grants shared root-level trust across all members.

```yaml
api_version: genesis/v1
cluster:
  name: lab
  members:
    - name: node-a                       # an sg-registered machine
      core_address: "100.64.0.11:8444"   # that member's tailnet IP and LXD port
    - name: node-b
      core_address: "100.64.0.12:8444"
    - name: node-c
      core_address: "100.64.0.13:8444"
```

`core_address` needs an explicit port, must not be a wildcard or port 8443, must be unique, and must match the member's own observed address and LXD binding.

```bash
sg cluster create --config cluster.yaml                     # shows plan, asks once
sg cluster destroy --config cluster.yaml --with-machines    # the only teardown that completes today
```

There is no `sg cluster init` or `sg cluster plan`; `create` shows its plan before it asks. Plain `sg cluster destroy` (without `--with-machines`) always refuses with `sg:cluster-teardown-unsupported`. A machine that is a recorded cluster member refuses `sg machine destroy`. Editing `cluster.yaml` never releases a member.

## Applications

```bash
sg application init --config application.yaml     # validate + register; local only
export SG_PG_ADMIN_PASSWORD=...                   # every admin_password_env must be set (user does this)
sg application plan --config application.yaml     # read-only; prints the plan and its hash
sg application deploy --config application.yaml   # fresh plan, [y/N], apply, health + exposure checks
sg application status --config application.yaml   # read-only: INSTANCE STATE HEALTH MEMBER DRIFT
sg application restart --config application.yaml [group|instance]        # no new generation
sg application scale --config application.yaml web --count 3 \
  --target web-0=node-a --target web-1=node-b --target web-2=node-c --dry-run
sg application upgrade --config application.yaml web --image ubuntu:24.04 --dry-run
sg application upgrade --config application.yaml db --service postgres --version <exact-version>
sg application rollback --config application.yaml  # redeploys generation N-1 as N+1
sg application destroy --config application.yaml   # deletes owned instances AND volumes
```

- Instances are named `<app>-<group>-<index>`; their keys in the spec are `<group>-<index>` starting at 0.
- **The application ships as an LXD image.** There is no build step or cloud-init field: `image` is passed to `lxc init` on the cluster. For custom apps, build on a member (`lxc launch ubuntu:24.04 build-x`, `lxc exec build-x -- cloud-init status --wait`, install, `lxc stop`, `lxc publish build-x --alias app-web-7`, `lxc delete build-x`) and use a new alias per build. Deploy fails if nothing answers on the exposed ports.
- **Container and VM images are different.** An image published from a container can't boot in a `type: vm` group (`Asked for a VM but image is of type container`). Build VM images from a VM: `lxc launch ubuntu:24.04 build-x --vm`, then wait for the agent (`until lxc exec build-x -- true; do sleep 3; done`) and `cloud-init status --wait`, install, run `cloud-init clean --logs`, stop and publish. A VM image in a container group silently becomes a VM, because sg only passes `--vm` for VM groups.
- **VM groups:** `type: vm`; `size.memory` is the VM's RAM; `size.root_disk` sizes its disk (default 10GiB on a stock pool). Block volumes appear inside as raw disks at `/dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_lxd_sg--volume--<name>` (dashes doubled); `mount` does not mount them, the guest must format and mount them. Filesystem volumes are mounted at `mount` automatically. sg sets up no SSH into instances; use `lxc exec <app>-<group>-<n> -- bash` on the member.
- **VM first-deploy gap:** the health gate runs once right after the VM reports Running, often before its LXD agent is up (`LXD VM agent is not currently running`). If the first deploy of a VM group fails at `app.health` that way, tell the user, wait a few seconds and suggest deploying again; the second deploy is a check-only run.
- Only a deploy that finishes OK with health verified becomes a **generation**. Failed or aborted runs never become rollback targets.
- `scale` and `upgrade` rewrite the group in `application.yaml`, then run the normal deploy. Always run them with `--dry-run` first. What happens to the edit when the user answers `N` is still being settled.
- `--target` on `scale` must list the full resulting placement, one `instance=member` per resulting instance.
- `upgrade` needs `--image` and/or `--service <name> --version <v>`. Versions are exact package versions, never `latest`.
- `destroy` keeps the registration, generations and data-volume safety markers in the ledger.

Full example:

```yaml
api_version: genesis/v1
application:
  name: shop
  cluster: lab                          # registered in this ledger
  groups:
    - name: web
      count: 2
      image: ubuntu:24.04
      target: {web-0: node-a, web-1: node-b}   # exactly count entries, keys from -0
      size: {cpu: 2, memory: 2GiB}
      env: {APP_MODE: production}
      refs: {DATABASE_HOST: db-0}       # an instance key or load balancer name
      expose:
        - port: 8080/tcp
      health: [/usr/bin/curl, -fsS, http://127.0.0.1:8080/healthz]
    - name: db
      count: 1
      type: vm                          # services and block volumes need vm
      image: ubuntu:24.04
      target: {db-0: node-c}
      size: {cpu: 2, memory: 4GiB, root_disk: 20GiB}
      volumes:
        - {name: pgdata, pool: default, size: 10GiB, content_type: block, attach: [db-0], mount: /srv/pgdata}
      services:
        - kind: postgres                # postgres | clickhouse
          version: "<exact-package-version>"
          admin_password_env: SG_PG_ADMIN_PASSWORD
  load_balancers:                       # at most one
    - name: web-edge
      kind: haproxy
      balances: [web]
      target: {web-edge-0: node-a}      # exactly one replica
      listen: 8088/tcp
      check: {type: http, path: /healthz, expect_status: 200}   # default type: tcp
```

Rules:

| Area | Rule |
|---|---|
| Group `type` | `container` (default) or `vm`. Container groups **must** declare `health` (an argv list run inside the instance). |
| `target` | Exactly `count` entries keyed `<group>-0` to `<group>-(count-1)`, each naming a cluster member. `count: 0` is valid. |
| `size` | Required: `cpu` (integer) and `memory`. Optional VM `root_disk`. Sizes are `NMiB` or `NGiB`. |
| Volumes | `content_type` `filesystem` (default) or `block`. Block volumes attach only to VM groups. A volume attached to more than one instance needs `security.shared: true`, must stay on one member, and plan/deploy/destroy need `--force-volume-share <volume>` (ask the user first). `mount` is an absolute path, not `/`. Volumes never shrink or change type. |
| Services | One per group; the group must be `type: vm` with `count: 1` and image `ubuntu:22.04` or `ubuntu:24.04`. `version` is never `latest`: PostgreSQL takes a major (`"17"`, newest release frozen at plan time) or an exact package version; ClickHouse needs an exact release like `"24.8.4.13"`. Default users: `postgres` / `default`. Default ports: PostgreSQL 5432, ClickHouse 9000. `data_volume` is required unless exactly one block volume is attached. Optional: `name`, `port`, `data_path`, `mount_device` (`/dev/disk/by-id/...`), `health`, `admin_user_env`, `tuning` (PostgreSQL `max_connections`, `shared_buffers`; ClickHouse `max_memory_usage`). |
| `env` / `refs` | Keys are env var names and must not overlap. A `refs` value names an instance key or a load balancer. In 0.1.0-dev `refs` is validated and (for service targets) opens that path in the guard, but is **not** set inside the instance: pass addresses through `env` too. |
| `expose` | `N/tcp`, unique per group, never the SSH or LXD control port. Published on the member's tailnet address; deploy checks it is reachable from the workstation. Exposing a service port (e.g. `5432/tcp`) is how you reach a database from the workstation. |
| Load balancer | `kind: haproxy`, `listen: N/tcp`, one replica `target: {<name>-0: <member>}`. Name must not collide with a group or instance key. |

## The panel

```bash
sg panel                        # http://127.0.0.1:7070, run from the project directory
sg panel --listen tailnet:7070  # this host's own verified tailnet address
```

Only loopback or this host's verified tailnet address is accepted. There is **no authentication**: it is a local operator console. Reads never open SSH; only Refresh and plan/apply actions contact hosts. Apply routes require the `plan_hash` from the matching plan route and refuse with `409 sg:plan-stale` if the fresh plan differs. Destroy routes also need `confirm_word` equal to the resource name. One run at a time (`409 sg:run-active`).

## What each teardown keeps

| Command | Removes | Keeps |
|---|---|---|
| `sg machine rollback` | Last run's reversible changes | ZFS pool, LXD, unowned state |
| `sg machine destroy` | Every recorded sg artifact, including instances and the pool file | Packages (unless `--with-packages`), unowned state |
| `sg cluster destroy --with-machines` | Cluster state and every member's machine teardown | Unowned state |
| `sg application destroy` | Owned instances and their volumes | Unowned artifacts, registration, generations, data-volume markers |

## Troubleshooting

| Message or code | Cause | Fix |
|---|---|---|
| `sg: loading configuration: ...` | Bad `SG_*` value | Fix the variable |
| `sg: unknown group "<x>"` (exit 2) | Typo or flag before the group | `sg <group> <verb> [flags]` |
| `--config requires ...` (exit 2) | Missing `--config` | Pass the spec path |
| Host-key or SSH failure in `plan` | Host not in known_hosts, or wrong private key | User verifies and adds the host key; sg never edits known_hosts |
| `bootstrap.deploy_user.key_path` names a private key | Deploy path must be a public key | Point it at the `.pub` file |
| `secret is unavailable: <VAR>` / `sg:secret-unavailable` | Named env var unset or empty | User exports it in the shell that runs sg |
| `sg:invalid-spec` / `sg:invalid-application-spec` | Validation failed | The message names the first broken rule |
| `sg:unknown-cluster` / `sg:cluster-not-ready` | Cluster not registered or not formed | `sg cluster create` in the same directory first |
| `sg:application-name-conflict` | Name bound to another spec path or cluster | Pick a new name; bindings never move silently |
| `sg:application-placement-invalid` | `target` names a non-member | Match `cluster.yaml` member names |
| `sg:plan-stale` (409) | State changed after approval | Re-plan and re-approve |
| `sg:cluster-teardown-unsupported` | Plain `sg cluster destroy` | Only `--with-machines` completes today |
| `sg:machine-in-cluster` | Destroying a cluster member directly | Destroy the cluster with machines instead |
| `sg:rollback-unavailable` | No generation N-1 | Nothing to roll back to |
| `sg:volume-share-unsafe` / `sg:service-data-on-root` | Safety refusal | Review the plan; override flags only if the user means it |
| `sg:exposure-conflict` / `sg:load-balancer-listen-conflict` | Port collision on a member | Choose another port |
| `sg:service-version-unavailable` | Version not resolvable | Use an exact available package version |

## Known limits (0.1.0-dev)

- Machine plan and create have been run by hand on one real Ubuntu 24.04 host. Clusters, applications and the panel are proven only against a scripted SSH/LXD runner so far.
- `machine destroy` skips a change whose verification failed, so a failed `install.lxd` is not torn down.
- Plain `cluster destroy` refuses; only `--with-machines` completes.
- Application status/drift reporting is incomplete. Peer-traffic policy for `refs` is undecided.
- Scale/upgrade decline semantics are being reconciled: prefer `--dry-run`.
- The first deploy of a VM group can fail its health gate before the VM's agent starts; a second deploy passes.
- The panel's upgrade takes `image` only; service version upgrades are CLI-only.
- Secret redaction across all output is deferred: review run output before sharing it.

<!-- Source: https://gen.slostack.io/docs/agents -->
