Files
semprini-maintainer/docs/architecture.md
T
paulandClaude Opus 5.5 61dca2c3ca Run on the workstation, on pydantic-ai with cloud and local models
The daemon moves from the Lightsail host to WSL on the workstation (EVAI),
where the RTX 4090 can run local models and the data platform and home
cluster live. It reaches the core host over one multiplexed SSH connection:
each health check pipes probe.py to the host's python3 and gets Kuma, disk,
memory, OOM kills, restarts and reboots back in one snapshot. The agent edits
and commits core's live checkout there, as semprini-core's rules expect, and
the service desk still runs on the host. Off the host, it now notices when
the host itself stops answering.

The agent runs in-process with pydantic-ai instead of Claude Code headless.
Model profiles (anthropic, ollama, any OpenAI-compatible server) are routed
per kind of task: an unreachable model hands over at once (FallbackModel), a
run that fails as a run restarts on the next profile. The result is a typed
envelope; conversations persist as message histories; cancel stops the
command in flight; each reply names the model and its cost. `model` in Matrix
pins a room to a profile; --try-model checks a model calls tools and uses
what they return (qwen3-coder does not; GLM-4.7-Flash, the local default, does).

Cloud runs now need an API key (--set-api-key) and are billed per token; the
subscription token was for Claude Code only. Back-off is per kind of task, so
a cloud-only upgrade waiting on a key does not stall work the local model
can do. A queued task held back by a hold no longer spins the main loop.

--hold and --resume stay stdlib-only, so sync-to-host.sh can still hold the
daemon from the host's checkout; the daemon reads the host's hold each minute.
install.sh sets up WSL and retires the host's service: one Matrix bot, one
daemon.

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

162 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 with configurable cloud and local models. 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, runs by model, cloud spend, 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, cloud or local, per kind of task, with
fallback; 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.
- **Models are profiles, routed per kind of task.** Defaults: operator messages and health
findings try the cloud first, alert triage tries the local model first, the weekly upgrade
is cloud only. Triage is the most frequent run and mostly reading, so it is the one worth
keeping local; the upgrade is the most consequential. An unreachable model hands over at
once (`FallbackModel`); a run that fails as a run restarts on the next profile, 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.
- **Credential = an API key per cloud profile** (2026-09-26; reverses the `claude
setup-token` subscription token). pydantic-ai calls the Anthropic API, which is billed per
token; the subscription token is for Claude Code only. Mitigations: the instructions, tool
list and conversation are prompt-cached; `limits.cost_usd` caps each run by kind; the
footer and the daily report show the spend; the most frequent work is routed local.
- **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.
- **A local model acts on production.** Alert triage runs local first by default. It can
change things (demote log lines, restart containers); a weaker model may judge worse.
Watch the footers, and move `alerts` to cloud first if its work disappoints.
- **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.
- **Cloud runs are metered.** A runaway run is capped by `limits`; a runaway *schedule* (an
alert storm past the cooldowns) is not, beyond the one-run-at-a-time queue.
- **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.