Aegis

Roadmap: Aegis Web Control Plane

Goal: Aegis runs on a VPS and serves a web dashboard on a configurable port. From that page, an operator can manage everything they can manage today from the CLI, plus live resource control: deploy, roll back, start/stop/restart apps, read logs, watch CPU/memory, and change each app’s CPU and memory limits with sliders.

Status: Phases 0–6 complete (several Phase 6 parts are experimental; the multi-node fleet is later) · Releases: v0.5.0 (web MVP), v0.6.0 (resource control), v0.7.0 (self-serve ops)


0. Where we are today (audit, 2026-09-28)

What works

Check Result
cargo build --workspace --all-targets ✅ passes
cargo fmt --all -- --check ✅ passes
cargo clippy --workspace --all-targets -- -D warnings ✅ passes
cargo test --workspace --all-targets ✅ all pass
CI smoke flow (daemon → init → deploy → status) ✅ passes after the fixes below

The foundation is sound and worth building on: the event store, event bus, projection engine, scheduler, detector pipeline, release switcher, and gRPC API all work and have tests.

Bugs fixed as part of this roadmap

Bug Impact Fix
The daemon wrote a daemon-only aegis.toml into its working directory on startup aegis init saw an “existing” config and skipped writing [project], so every aegis deploy invented a new random project ID. The CI smoke test hit this. The daemon no longer creates aegis.toml. init appends [project] to an existing file that lacks one. [daemon] is now optional in aegis.toml.
ProcessStarted always recorded "pid": 9000 Wrong PID in the audit trail and projections Records the real OS PID
The daemon reported a hardcoded version "0.1.0" Version drifts from the release Uses CARGO_PKG_VERSION

Simulated or stubbed behaviour found in the audit

These passed tests but didn’t do what the docs and CLI claimed. Phase 0 fixed them; each row says how.

Area Before After Phase 0
Deploy saga starts the app Spawned echo Deploy success Runs build.start_command from the release’s aegis.toml, supervised, with PORT and [env] set
Health checks Never ran; the target was hardcoded to 127.0.0.1:8080 deploy.health_check_url (HTTP path, tcp://, or “stays up”) is polled until health_check_timeout_secs
Previous release / drain previous_release was always None The old process is stopped with SIGTERM and a drain timeout; if the new release is unhealthy, the old one is started again
Release versions Every deploy was v1.0.0 Unique, sortable versions (20260928-051203) or --release <name>; names are validated so they can’t escape the releases directory
Build stages Clone and Test only logged Git clone or git-aware copy; install/build/test commands with timeouts and a build log per deployment
Artifact store Hashed the path string and didn’t copy directories Hashes file contents; copies directory trees; checksum verification detects tampering
stop / restart / rollback Appended events nothing acted on Typed commands that the daemon executes, recording both the request and the outcome
Restart policy Restarted once, then gave up Exponential backoff (1 s → 30 s); crash-loop detection marks the process Failed
Process logs Only in the daemon’s tracing output Per-process log files (rotated at 10 MiB), aegis logs [-f]
Event ordering Replayed by created_at text Explicit seq column (migrated); the projection is updated synchronously in seq order
Daemon restart Apps were orphaned (SIGTERM wasn’t handled) and never restarted SIGTERM/SIGINT stop apps cleanly; on boot, apps the operator didn’t stop are restarted; interrupted deployments are marked failed
Runtime trait start/stop/health returned fake PIDs Reduced to runtime detection; the supervisor owns process lifecycle
CLI Required the daemon even for init/doctor; list, releases and timeline showed only event counts Offline commands work without the daemon; the list/query commands show real data

Still open after Phase 0 (tracked in later phases)


1. Target architecture

The web control plane lives inside the existing daemon as a second listener. It keeps the single-binary, no-external-dependencies promise.

                       Browser (operator)
                              │  HTTPS :8420  (cookie session + CSRF)
                              ▼
┌───────────────────────── aegis-daemon ─────────────────────────┐
│                                                                │
│  ┌───────────────┐   ┌────────────────┐   ┌─────────────────┐  │
│  │ gRPC :50051   │   │ HTTP :8420     │   │ Webhook         │  │
│  │ (CLI / TUI)   │   │ REST + SSE +   │   │ POST /hooks/*   │  │
│  │ localhost     │   │ embedded UI    │   │ (HMAC-verified) │  │
│  └──────┬────────┘   └───────┬────────┘   └────────┬────────┘  │
│         └────────────┬───────┴─────────────────────┘           │
│                      ▼                                         │
│          ┌──────────────────────┐   single command/query API,  │
│          │  ControlPlane core   │   shared by every transport  │
│          └───┬──────────┬───────┘                              │
│   commands   │          │ queries                              │
│              ▼          ▼                                      │
│      Event Store ──► Projection Engine                         │
│         │                                                      │
│         ▼                                                      │
│   Deployment saga ─► Process Supervisor ─► cgroup v2 / systemd │
│                          │                     (CPU, memory)   │
│                          ▼                                     │
│                  Log store + Metrics sampler                   │
└────────────────────────────────────────────────────────────────┘

Key decisions

Decision Choice Why
HTTP server axum inside the daemon (same Tokio runtime as tonic) Same ecosystem as tonic; no second process
Business logic Extract a ControlPlane service used by gRPC, HTTP and webhooks Today, logic sits in the gRPC handler and a 200-line saga closure in main.rs; a third transport would duplicate it
Live updates Server-Sent Events (SSE) for events, deploy progress, metrics and logs One-directional, works through proxies, auto-reconnects, simpler than WebSockets
Frontend A dependency-free vanilla JavaScript single-page app (core/web/ui/), embedded in the binary with include_str! and built on the same /api/v1 endpoints as the CLI (changed in Phase 3; the original plan was askama + htmx) Still no build step and no Node toolchain for source builds, so it stays a single binary. Talking to the JSON API directly means the dashboard can’t drift from it, live views use the existing SSE streams, and a strict content security policy (no inline code, same-origin only) is easy to keep. Node is only needed to run the Playwright browser tests.
Resource limits Linux cgroups: one cgroup per supervised process, with cpu.max, memory.max/memory.high (and pids.max) on v2, or the v1 equivalents. The child joins its cgroup between fork and exec. (Changed in Phase 4: per process rather than per app, and a cgroup v1 backend instead of the systemd-run fallback.) Limits can be changed live, without restarting the app, which is what the sliders need. A cgroup per process means both copies of an app during a graceful switch each get the full limit, instead of sharing one and risking an OOM mid-deploy. Delegation (Delegate=yes) covers systemd hosts; running as root covers the rest, including v1-only hosts that systemd-run wouldn’t help with.
Metrics sysinfo crate for the host; /proc/<pid> and cgroup cpu.stat / memory.current for each app; in-memory ring buffer plus 1-minute rollups in SQLite No Prometheus required. A /metrics Prometheus endpoint is optional later.
Config New [web] section in aegis.toml See §3

2. Phases

Each phase ends in a shippable, tested state. Acceptance criteria are what CI or a manual VPS test must show.

Phase 0 — Make the core real ✅ done

Delivered:

  1. Real app start: the saga reads build.start_command, the port, the health URL and [env] from the release’s own aegis.toml.
  2. Real health checks, with automatic rollback to the previous release when the new one isn’t healthy in time.
  3. Release lineage: unique versions, previous release tracked through ReleasePromoted, graceful drain, and retention pruning driven by release history.
  4. Daemon-executed commands: stop, start, restart and rollback are typed gRPC commands. Requests (Process*Requested, RollbackRequested) and outcomes (ProcessStopped, RollbackCompleted, …) are both recorded.
  5. Supervisor: process groups, backoff, crash-loop limit, SIGKILL escalation, and per-process rotating logs with live streaming.
  6. Builder: git clone or git-aware copy, install/build/test commands with timeouts and logs, and content-hashed artifacts.
  7. Event store: seq column with migration; ordered, synchronous projection updates.
  8. Read API: ListProjects, ListReleases, ListDeployments, GetDeployment, ListProcesses, GetLogs, StreamLogs and ListEvents. These back the CLI now and will back the web API later.
  9. Refactor: the saga moved to core/control (ControlPlane), which Phase 1 exposes over HTTP.

Evidence:

Phase 1 — HTTP API in the daemon ✅ done

Delivered:

Evidence: 7 HTTP API tests (guard rules, validation and errors, a full deploy → restart → stop/start → logs → rollback lifecycle against a real app, SSE filtering, shutdown ending streams, log follow) and new HTTP steps in scripts/e2e-smoke.sh (run in CI).

Phase 2 — Security and VPS hardening ✅ done

Delivered (details in security.md):

Independent security review. It found no authentication bypass, and it checked routing and path normalisation, CSRF, sessions, timing, webhook HMAC and config validation. It reported nine lower-severity issues, all fixed in this phase:

Deliberately not included in Phase 2: built-in ACME. (Added in Phase 5 with the built-in proxy; Caddy or certbot with [web.tls] still work.) Multiple users and roles remain Phase 6.

Evidence: 12 security tests in core/web/tests/auth.rs (route-by-route 401, cookie flags and CSRF, throttling, scopes, password change, streams closing on revocation, Host allowlist, signed webhooks deploying a real commit and ignoring replays, HTTPS over HTTP/1.1 and HTTP/2 with certificate renewal), 7 in core/auth (including 50 parallel sign-in attempts → exactly 5 allowed), config refusal tests, an independent security review of the diff, and new end-to-end steps (authentication, read-only token, unsafe-config refusals) in scripts/e2e-smoke.sh.

Phase 3 — Web dashboard MVP ✅ done → v0.5.0

Delivered: the daemon serves the dashboard at / when [web] enabled = true. It is a vanilla-JS SPA with no build step (see “Frontend” in the decisions table), with these additions to the API:

Playwright tests (ui-tests/, run in CI) drive a real daemon through the scenario below, on desktop and on a phone-sized screen. Every test also fails on any CSP violation or uncaught script error.

Planned scope (all delivered):

  1. Login
  2. Overview: host CPU, memory, disk and load; a card per app with status, current version, uptime, restart count and quick actions.
  3. App detail:
    • Deploy button (branch or commit, strategy) with live 7-stage pipeline progress over SSE.
    • Release history with one-click rollback.
    • Process controls: start, stop, restart.
    • Live log viewer: follow, pause, search, and download.
  4. Deployments timeline: all deploys across apps with status and duration; click through to stage logs.
  5. Events / audit log: filterable view of the event store (who did what, when).
  6. New app wizard: repo URL → auto-detect runtime (reusing DetectorPipeline) → edit build/start commands, port and health path → save.

UX: responsive (usable on a phone for incident response), light and dark themes, keyboard shortcuts, and confirmation dialogs for destructive actions.

Done when: everything in the Phase 0 “done” scenario can be done from the browser without SSH, with Playwright end-to-end tests in CI.

Phase 4 — Resource monitoring and control ✅ done → v0.6.0

Delivered:

The “done when” scenario is tested end to end in the browser (ui-tests/tests/resources.spec.js), against the real kernel:

  1. A memory-limit change reaches the running app within a second, with no restart.
  2. Dragging the CPU slider to 0.2 cores caps a busy loop at about 0.2 cores.
  3. Allocating past the limit gets the app OOM-killed and restarted, and the alert shows in the UI.

CI runs the kernel and HTTP tests on cgroup v2 both delegated (a transient systemd service with Delegate=yes, unprivileged) and as root, and the browser suite as root, with AEGIS_REQUIRE_CGROUPS=1 so that none of them can skip. Until then they skipped silently in CI: under sudo the tests inherited the runner service’s INVOCATION_ID, took that service’s cgroup for a delegated one, and found no controllers there. Detection now refuses a service cgroup that holds other processes and falls back to /sys/fs/cgroup/aegis as root. Locally they also passed on a cgroup v1 host.

Not done, deferred:

Original plan:

This is the “drag CPU and memory” feature.

Done when: on a VPS, dragging the memory slider on a running app changes memory.max within 1 s without a restart; a test app that exceeds it gets OOM-killed, restarted by the supervisor, and the event shows in the UI; the CPU limit visibly caps a busy-loop app’s CPU % on the chart.

Phase 5 — App configuration from the UI ✅ done → v0.7.0

Phase 6 — Operations polish (done; experimental parts marked)


3. Configuration additions

[daemon]
host = "127.0.0.1"
port = 50051                    # gRPC, localhost only (CLI/TUI)

[web]
enabled = true
host = "127.0.0.1"              # "0.0.0.0" requires tls or behind_proxy
port = 8420
behind_proxy = false            # trust X-Forwarded-* from 127.0.0.1 only
session_ttl_minutes = 720

[web.tls]
mode = "acme"                   # "off" | "files" | "acme"
domain = "aegis.example.com"
email = "ops@example.com"
# cert_path / key_path when mode = "files"

[resources.defaults]            # applied to new apps; per-app overrides in the UI
cpu_cores = 1.0
memory_mb = 512

4. New domain events

ProcessStopRequested, ProcessRestartRequested, RollbackRequested, ResourceLimitsChanged, ResourcePressureDetected, UserLoggedIn, UserLoginFailed, ApiTokenCreated, ApiTokenRevoked, SecretUpdated (the value is never stored in the event), DomainMapped / DomainUnmapped (done). Every event triggered from the web gains an actor field. Add each to docs/event_catalog.md when it is implemented.

5. Risks

Risk Mitigation
A public dashboard becomes a remote-code-execution vector Phase 2 is a hard gate before any public bind; safe defaults; the daemon refuses unsafe configurations
cgroup v2 delegation varies by distro and VPS provider Detect at startup and show capability status in the UI; systemd fallback; test matrix of Ubuntu 22.04/24.04 and Debian 12
Daemon restart kills managed apps Run apps in their own cgroup scopes so they survive a daemon restart; re-adopt them by PID and cgroup on boot
Metrics storage growth in SQLite Rollups plus retention pruning; metrics in a separate table/DB file from events
Scope creep Phases 0 → 3 are the MVP; Phases 4+ ship incrementally behind the MVP

6. Milestone summary

Milestone Phases Outcome
M-Core ✅ 0 Deploy/stop/restart/rollback do real work
M-API ✅ 1 + 2 Secure HTTP API reachable on the VPS
v0.5.0 — Web MVP ✅ 3 Manage all apps from the browser
v0.6.0 — Resource Control ✅ 4 Live CPU/memory monitoring and slider limits
v0.7.0 — Self-serve Ops ✅ 5 Env/secrets, domains + TLS, webhooks, schedules in the UI