Files
semprini-maintainer/docs/architecture.md
T
2026-11-26 17:29:38 +13:00

15 KiB

Maintenance Agent (semprini-maintainer)

Autonomous, always-on agent that keeps the semprini.me stack healthy and current. Implementation: this repository — see 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.

Revised 2026-11-26: the daemon moved back to the core host, and from the local model to Claude through the Anthropic API, still on pydantic-ai. 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 run the probe on core No agent: nothing it could do 🚨, 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 🙋 / ⛔ / 📨 / ✅
Self-update Hourly Fast-forward this checkout, uv sync if needed, --check, re-exec 🔄 notice

Key decisions

  • Runs on the core host, on Claude (2026-11-26, the operator's decision; reverses "runs on the operator's workstation" and "one local model does everything", both 2026-09-26). WSL proved flaky, and while the workstation was off or asleep nothing maintained the stack; the core host is always on. The daemon runs there under systemd as ubuntu, checkout ~/semprini-maintainer, state in ~/.local/state/semprini-maintainer/. Without the workstation's GPU there is no local model, so one profile, claude (anthropic:claude-sonnet-5-5), does every kind of task, with no fallback. Consequences:
    • core is the only host, with no ssh, so commands run on it directly; the local (WSL) and windows (PowerShell) hosts are gone. The bot's git identity and GITEA_* are set in core's environment, and pull requests are opened from core.
    • The home cluster is reached through the WireGuard tunnel (kubectl as elz-operator, ssh sem-k8s-1..3, ssh sem-gw), only while the workstation hosting it is on. Hyper-V is out of reach: anything about the VMs goes to the operator.
    • Billing is per token with an API key (--set-api-key claude), and limits.cost_usd caps each run ($5, $15 for the upgrade); genai_prices prices Sonnet 5.5, so the cap applies. context_tokens is 200000, which caps what one long run re-sends per step. A Claude Code subscription token (claude setup-token) cannot drive pydantic-ai.
    • --hold on the core host writes the daemon's own hold file; remote_hold_file is empty, kept for a daemon run elsewhere.
    • install.sh runs on the core host. It retires a daemon on the repo host only when that host is reached over SSH; the WSL daemon had to be stopped by hand.
    • Watching from off the host, the reason for 2026-09-26's move, is lost again: when core dies, so does its maintainer (residual risks).
  • Runs on the operator's workstation (2026-09-26; reverses "runs on the stack host", 2026-09-15; superseded 2026-11-26). 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 in place, and commits and pushes there (over SSH while it ran on the workstation). The alternative, a checkout elsewhere 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; superseded 2026-11-26 by one Claude model). Operator messages, alert triage, health findings and the weekly upgrade all ran 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; retired 2026-11-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 ran on the Windows host, not in WSL: its models, its GPU driver and its app were there. The app's Expose Ollama to the network setting let WSL reach it (through WSL's gateway to Windows); it also opened 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; superseded 2026-11-26: Claude needs an API key, kept in config.json). A cloud profile needs 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.
  • One hold file (2026-11-26; there were two while the daemon ran on the workstation). A hold is a file so a shell can reach a running daemon. On the core host, sync-to-host.sh and the runbook's ssh … maintainer.py --hold write the daemon's own (--hold needs only python3), so nothing in semprini-core had to change for either move. A daemon run elsewhere reads the host's through remote_hold_file each minute and honours whichever ends later.
  • One daemon. Two would use the same Matrix bot and act on the same stack. install.sh stops and disables the repo host's service when it is reached over SSH; any other daemon is stopped by hand before installing.
  • Runs as ubuntu on core, not root. ubuntu 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 — Claude resists such text better than the small local model did, but the line stays.

Residual risks

  • When core dies, so does its maintainer, and the warning cannot get out. Off the host, the daemon noticed core going down, but Matrix lives on core, so the 🚨 waited in the outbox; back on the host, nothing notices at all. An external dead-man's switch (e.g. healthchecks.io) pinged by each health cycle, and a second channel that does not depend on core (ntfy, or mail through SES directly), would close it.
  • The home cluster is maintained only while the workstation is on. The tunnel ends there, and an asleep or powered-down workstation takes the cluster, and the agent's reach into it, with it. Its data is disposable (semprini-core's decision), so this matters less than the stack did.
  • One model, no fallback. Claude does every task; an Anthropic outage, a revoked key or an exhausted balance means no agent: tasks wait, and the operator is told once per kind of task. A second profile in routing is the lever.
  • Cost. Every run is metered. limits.cost_usd stops a run at its cap and reports it ⛔ blocked, but a burst of alerts is many runs: batching and the 12h cooldown per fingerprint are what keep the bill down.
  • 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.