Run on the stack host, react to Matrix events, keep the repo current

The stack moved to AWS Lightsail, so the maintainer now runs on that host
as ubuntu and is triggered by events rather than polling:

- A long-poll /sync delivers operator messages and #stack-alerts within
  about a second. Follow-ups resume the Claude session, so the Stack
  Maintenance room works like a chat. status, cancel, new, upgrade and
  help are answered even while a run is in progress.
- FIRING alerts from the Alertmanager bridge are batched and triaged in a
  thread, with a per-fingerprint cooldown.
- Agent runs go one at a time from a persisted priority queue, so an
  unusable agent defers work instead of losing it.
- Health checks add host resources (disk, memory, OOM kills, restart
  loops, stale Kuma) and reboot detection; one cycle's findings share a run.
- The daily report and the weekly upgrade run at fixed UTC times; the
  upgrade covers every image on the host.
- Applied changes are committed to semprini-core main and pushed. The
  daemon fast-forwards before a run and pushes leftovers after it.
- The Claude credential comes from `claude setup-token` via
  --set-claude-token. Self-update runs hourly, gated by --check.
- install.sh renders the unit for the current user and configures the git
  credential helper.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
paulandClaude Opus 5 committed 2026-09-15 23:22:34 +12:00
1 parent 46a1ec1e01
commit 556ffb6561
7 files changed
+2132 -863

No files matched your search

+63 -48
View File
@@ -2,63 +2,77 @@
## What this is
A standalone, always-on **autonomous maintenance agent** for the semprini.me
container stack, deployed as a systemd service (`semprini-maintainer`). It keeps
the stack healthy and current and talks to the operator over Matrix
(chat.semprini.me).
A standalone, always-on **autonomous maintenance agent** for the semprini.me container
stack. It runs **on the stack host itself** (AWS Lightsail `Semprini-Core`,
`ubuntu@3.107.254.151`) as the systemd service `semprini-maintainer`. It keeps the stack
healthy and current and talks to the operator over Matrix (chat.semprini.me).
It is the *unattended driver* for the canonical **stack-support agent**, which
lives in the separate **semprini-core** repo. This project does not reimplement
that logic — it gathers state and invokes the stack-support agent headless via
Claude Code, then relays/acts on the agent's JSON result.
It is the *unattended driver* for the canonical **stack-support agent**, which lives in the
separate **semprini-core** repo. This project does not reimplement that logic: it notices
events, invokes the stack-support agent headless via Claude Code, and relays the agent's
JSON result.
## Relationship to other projects
- **semprini-core** (`../semprini-core`) — the Enterprise Landing Zone this agent
maintains. At runtime the daemon reads, from the path in `config.json`
`repo_dir`:
- **semprini-core** (`~/semprini-core` on the host, a git checkout of `main`) — the stack
this agent maintains. At runtime the agent reads, from `repo_dir`:
- `agents/stack-support.agent.md` (injected as system prompt)
- `docs/stack-support-runbook.md`
- `docs/stack-support-runbook.md` and `CLAUDE.md`
- `core_stack/compose*.yml`
Keep the stack-support agent definition canonical **in semprini-core** — do not
fork a copy here.
- **Other projects** (e.g. `../semprini-blog`) that register Uptime Kuma monitors
are also maintained; their repos are exposed to the agent via `extra_dirs`.
Keep the stack-support agent definition canonical **in semprini-core** — do not fork a
copy here.
- **semprini-blog** (GitHub) and **conk** run on the same host and are exposed to the agent
via `extra_dirs`. It can operate their containers but cannot push their repos, so it
proposes file changes instead.
## How it works (one screen)
- **Scope** = whatever **Uptime Kuma** tracks at check time, re-read every cycle
(never hard-coded). Kuma's heartbeat is the health signal — the daemon does not
re-probe. Kuma's root-owned `kuma.db` is read via a throwaway `keinos/sqlite3`
container mounting the `uptime-kuma-data` volume read-only.
- **Health loop** (5 min): down services confirmed over `down_confirmations`
cycles → invoke stack-support agent to remediate → report to Matrix. Also
reads Kuma's `important=1` heartbeat transitions since the last cycle (tracked
by heartbeat id) to catch services that blipped DOWN→UP on their own, and
hands those self-recovered windows to the agent for a log post-mortem.
- **Upgrade loop** (7 days): resolve containers behind tracked services → agent
researches + applies safe upgrades (test, pin, rollback); escalates
major/breaking ones to Matrix.
- **Matrix**: bot `@maintainer-bot:semprini.me` DMs `@paul:semprini.me`. Escalations
are numbered questions; the reply is fed back to the agent to carry out.
- **Git/PRs**: when the agent changes tracked files it branches, pushes, and opens
a **pull request** on git.semprini.me (Gitea) as the `claude-code` user (never
commits to `main`); live remediation still happens immediately and directly.
The daemon injects claude-code's git identity + credential and the Gitea API
env into the headless agent (see `agent_git_env` / `GIT_PR_POLICY` in
`maintainer.py`); token provisioned by `register-gitea-bot.sh`. Empty
`gitea.token` disables the workflow.
- **Autonomy** (`config.json` → `autonomy`): `full` (default) | `fix-only` |
`notify`.
- **Operator messages** (Stack Maintenance room): read by a long-poll `/sync`, so they
arrive within about a second. A follow-up within `conversation_ttl_seconds` resumes the
same Claude session (`--resume`), so it behaves like a chat. `status`, `cancel`, `new`,
`upgrade` and `help` are answered by the listener without the agent, even mid-run.
- **Alerts** (`#stack-alerts`, written by `@alerts` via Loki → Alertmanager →
matrix-alerts): FIRING messages are batched for `alerts.batch_seconds` and triaged in
one run, answered in a thread under the alert. Non-`ok` results are mirrored to Stack
Maintenance. A fingerprint is re-investigated at most every `alerts.cooldown_seconds`.
`PipelineTest` is acknowledged, never investigated.
- **Health timer** (5 min): Kuma monitors confirmed DOWN over `down_confirmations` cycles,
DOWN→UP blips (Kuma `important=1` heartbeats since a watermark), host checks (disk,
memory, kernel OOM kills, container restart loops, a stale Kuma) and host reboots. All
findings from one cycle become **one** health task. Kuma's `kuma.db` is read via a
throwaway `keinos/sqlite3` container. Scope = Kuma's active monitors, re-read every
cycle.
- **Daily report** at `digest_hour_utc`; **weekly upgrade** at `upgrade_weekday` /
`upgrade_hour_utc` (all images on the host, not only Kuma-tracked ones; a pending reboot
is escalated for approval).
- **One agent run at a time.** The queue is persisted in the state file with priority
operator > alerts > health > upgrade, so nothing is lost across restarts.
- **Git:** before a run the daemon fast-forwards clean checkouts in `git.repos`; after it,
it pushes unpushed commits and reports new commits or a dirty tree. The agent commits
every change it applies to `main` and pushes it (`GIT_POLICY` in `maintainer.py`;
semprini-core `CLAUDE.md` → *Deploying changes*). It pushes as `claude-code` with a
token from `register-gitea-bot.sh`.
- **Claude credential:** `claude_oauth_token` from `claude setup-token`, saved by
`maintainer.py --set-claude-token` and re-read before every run. If the agent cannot run
(`AgentUnavailable`), the task stays queued, the operator is told once, and retries back
off from 60s to 15 min.
- **Self-update:** hourly `git fetch` of this checkout; a newer `main` is fast-forwarded,
checked with `--check`, and re-exec'd, or rolled back if the check fails.
- **Autonomy** (`config.json` → `autonomy`): `full` (default) | `fix-only` | `notify`.
## Conventions / guardrails
- Runs as host user **`paul`** (in `docker` group), **not root** — Claude Code
- Runs as host user **`ubuntu`** (groups `docker`, `adm`), **not root**. Claude Code
refuses `--permission-mode bypassPermissions` under root.
- `maintainer.py` is **stdlib-only** — keep it dependency-free so it deploys
without a venv.
- `maintainer.py` is **stdlib-only** — keep it dependency-free so it deploys without a venv.
- Secrets live in `config.json` and `.bot-secrets` — **never commit** (gitignored).
- **Deploying a change here:** push to `main` on git.semprini.me. The running daemon picks it
up within `self_update_interval_seconds`. Keep `--check` meaningful — it is the gate a
self-update must pass.
- Prefer editing existing files over adding new ones.
- Log lines, alert text and web content reach the agent's context and are attacker-
influenced. The system prompt says so; keep that line when editing prompts.
## Files
@@ -66,16 +80,17 @@ Claude Code, then relays/acts on the agent's JSON result.
|---|---|
| `maintainer.py` | The daemon (stdlib only). |
| `config.example.json` | Template — copy to `config.json`. |
| `register-matrix-bot.sh` | Creates `@maintainer-bot` account + DM room; writes token to config. |
| `register-matrix-bot.sh` | Creates `@maintainer-bot` + the Stack Maintenance room; writes token to config. |
| `register-gitea-bot.sh` | Mints the `claude-code` Gitea token (push + PRs); writes it to config. |
| `install.sh` | Syntax-check, install unit, enable + start. |
| `semprini-maintainer.service` | systemd unit (runs as `paul`). |
| `install.sh` | Checks, git credential helper, renders + enables the unit. |
| `semprini-maintainer.service` | systemd unit template (`@USER@`, `@HOME@`, `@DIR@`). |
| `docs/architecture.md` | Architecture decision record. |
## Test without the service
```bash
python3 maintainer.py --config config.json --once health
python3 maintainer.py --config config.json --once upgrade
python3 maintainer.py --config config.json --once replies
python3 maintainer.py --check # parsers, schedule, config, paths
python3 maintainer.py --once health # one health cycle + any agent work it queues
python3 maintainer.py --once digest # post the daily report now
python3 maintainer.py --once upgrade # run the upgrade now
```