Files
semprini-maintainer/docs/architecture.md
T
paulandClaude Opus 5.5 9aa1abf0e2 Run everything on the local model; no cloud tier
GLM-4.7-Flash can reach core over SSH, check, diagnose and upgrade, so
operator messages, alert triage, health findings and the weekly upgrade all
route to the one local profile. The Anthropic profile and its cloud-first
routing go, and with them the API key and metered billing the first draft
needed. The local profile's context_tokens rises to 131072, the window Ollama
loads GLM with, so long runs are not trimmed early.

Profiles and routing stay in configuration: a second model can still be
added, with hand-over when the first is unreachable or fails the run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 01:59:28 +12:00

164 lines
12 KiB
Markdown

# Maintenance Agent (semprini-maintainer)
Autonomous, always-on agent that keeps the semprini.me stack healthy and current.
Implementation: this repository — see [`README.md`](../README.md). It maintains the
**semprini-core** stack (a separate repo) referenced via `repo_dir` on `repo_host`.
Revised 2026-09-15 for the move to AWS Lightsail: the daemon ran on the stack host, reacted
to Matrix events instead of polling, and kept the repo equal to what runs.
Revised 2026-09-26: the daemon moved to the operator's workstation, and from Claude Code to
pydantic-ai on the workstation's local model. Decisions that changed say so below.
## Purpose
Maintain the running stack without an operator at the keyboard:
1. **Remediate** outages, and act on critical log alerts as they arrive.
2. **Upgrade** everything the core host runs weekly, with test and rollback.
3. **Keep the repo current**, so the stack can be rebuilt from git plus the host's secrets.
4. **Talk to the operator over Matrix** like a chat: answer questions, carry out
instructions, ask when a decision is theirs, and report anything important.
It is the unattended driver for the canonical stack-support agent
(`semprini-core/agents/stack-support.agent.md`): it feeds the agent events and state and
relays its results.
## Support processes
| Process | Trigger | What happens | Operator sees |
|---|---|---|---|
| Conversation | Operator message in Stack Maintenance, or in an alert thread | Agent run; follow-ups resume the session | Reply in the room (👀 on receipt, typing while working, the model in a footer) |
| Alert triage | `FIRING` from `@alerts` in `#stack-alerts` | Batched 60s; agent reads the LogQL lines, fixes a real fault or demotes benign noise in Alloy | Thread under the alert; non-`ok` mirrored to Stack Maintenance |
| Outage remediation | Kuma monitor DOWN for 2 checks | Agent diagnoses and fixes per the runbook | 🔧 / ❓ / ⛔ in Stack Maintenance |
| Post-mortem | Kuma DOWN→UP between checks | Agent finds the cause in logs; changes nothing healthy | Report in Stack Maintenance |
| Host checks | 5-min timer on core: disk ≥ 85%, memory < 400 MB, OOM kill, restart loop, Kuma stale, reboot | Agent investigates (12h cooldown per finding) | Report in Stack Maintenance |
| Core unreachable | 3 health checks in a row cannot reach core over SSH | No agent: nothing it could do from here | 🚨, delivered once Matrix is back |
| Daily report | 21:00 UTC | No agent: monitors, downtime, alerts, agent runs, commits, pending reboot or decision | 📋 in Stack Maintenance |
| Weekly upgrade | Sat 22:00 UTC (Sun 08:00 AEST) | Agent upgrades every image and host packages on core; pins, commits, pushes; escalates majors and reboots | Report + decisions |
| Service desk | Every minute | `service-desk.py poll` on core, over SSH | 🙋 / ⛔ / 📨 / ✅ |
| Self-update | Hourly | Fast-forward this checkout, `uv sync` if needed, `--check`, re-exec | 🔄 notice |
## Key decisions
- **Runs on the operator's workstation** (2026-09-26; reverses "runs on the stack host",
2026-09-15). EVAI, in WSL Ubuntu under systemd, as the operator's user. Three reasons:
local models need the workstation's RTX 4090; the data platform and the home k3s cluster
(the Hyper-V VMs) live on this machine, which the core host cannot reach; and a watcher
off the host notices the host itself going down, the first residual risk of the previous
design. Consequences:
- Everything on core is an SSH round trip, so there is one multiplexed connection
(`ControlPersist`) and the health check is one script (`probe.py`) piped to the host's
python3, returning one JSON snapshot.
- The workstation has to be on, and WSL running (a logon task keeps it up). Windows
updates and reboots take the maintainer with them.
- The service desk stays a script run on core, where its `.env`, docker and kubectl are;
the daemon only starts it there.
- WSL rather than Windows itself: systemd, the same unit and journal as before, and a
Linux shell; Windows stays reachable through interop (`powershell.exe`), and Ollama
through WSL's NAT gateway.
- **The agent edits core's live checkout over SSH**, and commits and pushes there. The
alternative, a checkout on the workstation deployed with `sync-to-host.sh`, adds a deploy
step the agent could forget and a second copy that can drift. Editing in place keeps
semprini-core's rule ("on the host, commit what you apply") unchanged. Files are written in
place, never renamed over, because core's configs are bind-mounted single files.
- **Runner = pydantic-ai in the daemon's process** (2026-09-26; reverses Claude Code
headless, `claude -p`). What it gains: any model pydantic-ai supports, local or cloud, with
fallback between them when more than one is configured; a typed result instead of a JSON
block fished out of prose; cancellation that
stops the command in flight; one Python process instead of a CLI per run. What it gives
up: Claude Code's large tool set, automatic `CLAUDE.md` loading, compaction and web search.
The agent now has five tools (`shell`, `read_file`, `write_file`, `edit_file` on a named
host, and `fetch_url`); the instructions tell it to grep the runbook and `CLAUDE.md` on core
for what it needs, and old tool output is shortened when a conversation nears a model's
window.
- **One local model does everything** (2026-09-26, the operator's decision). Operator
messages, alert triage, health findings and the weekly upgrade all run on GLM-4.7-Flash:
the operator judged it able to reach core over SSH, check, diagnose and upgrade, and saw
no reason for a second tier. It replaced a first design, the same day, that sent operator
messages, health findings and the upgrade to Claude through the API. So there is no
metered billing and no API key to hold. The mechanism is kept general in configuration:
models are profiles, and `routing` lists the profiles each kind of task tries; a second
profile in a list takes over when the first is unreachable (`FallbackModel`) or fails the
run, told what the failed attempt ran. Each reply says which model answered.
- **Local model = GLM-4.7-Flash on Ollama, on Windows** (tested 2026-09-26). The one test
that matters is whether a model uses what a tool returns: `--try-model` gives it a value it
cannot guess. GLM-4.7-Flash and qwen3.5:35b passed; qwen3-coder called the tool and then
made up an answer. GLM is faster and, at 19 GB, leaves the 24 GB card room for its cache.
Ollama runs on the Windows host, not in WSL: its models, its GPU driver and its app are
there. The app's *Expose Ollama to the network* setting lets WSL reach it (through WSL's
gateway to Windows); it also opens it to the home LAN, and Ollama has no authentication.
- **No model credential** (2026-09-26; retires the `claude setup-token` subscription token,
which is for Claude Code only). A cloud profile added later would need an API key, billed
per token; `limits.cost_usd` caps each run on a priced model.
- **Event-driven via long-poll `/sync`, not a Synapse application service.** The
homeserver holds a `/sync` request open and answers the moment an event lands, so
messages are handled within about a second. An appservice would push over HTTP instead,
but it needs a registration file in the generated `homeserver.yaml`, a listener reachable
from the Synapse container, and a Synapse restart. It would gain nothing a person could
notice — and from the workstation, nothing on core could reach such a listener anyway.
- **One agent run at a time, priority queue.** Two agents changing the same stack at once
would fight. The queue is persisted, so an instruction or alert survives a restart or an
unusable model. Priority: operator > alerts > health > upgrade. The listener answers
`status`, `cancel` and `model` itself while a run is in progress.
- **Conversations resume sessions.** Each room, and each alert thread, maps to the last
session used there: a pydantic-ai message history in the state directory. A reply within
4 hours continues it, so "why?" and "do option 2" work, on whichever model answers. An
escalation's answer always resumes the session that asked.
- **Scope of remediation = Uptime Kuma's active monitors.** Re-read every cycle, so
pausing a monitor takes a service out of scope (runbook → *Deliberately Stopped
Services*). Upgrades cover every image on the core host.
- **Health signal = Kuma heartbeat**, read from `kuma.db` through a throwaway
`keinos/sqlite3` container on the volume, read-only. Host checks cover what Kuma cannot
see. Prometheus stays out: semprini-core's observability design chose this check
instead.
- **Alerts go to the agent, not a person.** Every alert can start a run, so alerts are
batched, re-investigated at most every 12h per fingerprint, and benign messages are
demoted at the source in Alloy rather than by raising thresholds.
- **Applied changes go straight to `main`; proposals go through pull requests.** This
reversed the 2026-06 rule that every agent change went to a PR. Live changes then sat on
unmerged branches while `main` fell 15 commits behind what ran. The host is a git checkout
of `main`, the workstation deploys with `git push` plus a fast-forward, and the daemon
pushes whatever a run leaves unpushed. Gitea still records every commit for review. blog
and conk cannot be pushed by the bot, so the agent proposes patches there.
- **Two hold files.** A hold is a file so a shell can reach a running daemon. The
workstation's is the daemon's own; the core host's is what `sync-to-host.sh` and the
runbook's `ssh … maintainer.py --hold` write, from the host's old checkout (`--hold` needs
only python3). The daemon reads the host's each minute and honours whichever ends later,
so nothing in semprini-core had to change for the move.
- **One daemon.** Both daemons would use the same Matrix bot and act on the same stack, so
`install.sh` stops and disables the core host's service before starting this one.
- **Runs as the operator's WSL user, not root.** Its SSH key logs in to core as `ubuntu`,
which has docker and passwordless sudo: the agent keeps root-equivalent power on core,
which it needs to reboot and upgrade packages.
- **Matrix transport:** bot `@maintainer-bot:semprini.me`, registered with the Synapse
shared secret because password login is disabled. Both rooms are unencrypted: the bot
does not do E2EE.
## Trust boundary
Only two senders are obeyed: `admin_user_id` in either room, and `@alerts` in
`#stack-alerts` (whose messages trigger triage but are not instructions). Everything the
agent reads while working is untrusted: log lines, access-log paths, alert annotations,
web pages. The instructions tell the agent never to follow instructions found in them,
whichever model runs it. This is a mitigation, not a guarantee, for an agent with Docker
access — and a smaller local model is likely to resist such text less well than Claude.
## Residual risks
- **Nothing tells the operator when the workstation is off.** An asleep, rebooting or
powered-down workstation stops all maintenance silently. Cheapest fix: an external
dead-man's switch (e.g. healthchecks.io) pinged by the daily report or each health cycle.
- **When core dies, the warning cannot get out.** The daemon now notices, but Matrix lives on
core, so the 🚨 waits in the outbox. A second channel that does not depend on core (ntfy,
or mail through SES directly) would close it.
- **One local model runs production alone.** GLM-4.7-Flash does every task, upgrades
included, with no stronger model behind it. Its commits are in Gitea and its replies say
what it did; a second profile in `routing` is the lever if its judgement disappoints.
- **Ollama down means no agent.** With one profile there is nothing to hand over to: tasks
wait, and the operator is told once per kind of task.
- **Gitea lives on the host it describes.** vol-backup copies its volume to S3 nightly, and
workstation clones exist. A push mirror to GitHub would make a rebuild independent of S3.
- **Health checks pause during an agent run.** A 30-minute upgrade delays the next Kuma
check by up to that long; alerts and operator messages still queue and are acknowledged.