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:
1 parent
46a1ec1e01
commit
556ffb6561
7 files changed
+2132
-863
No files matched your search
@@ -1,165 +1,173 @@
|
||||
# semprini-maintainer — autonomous stack maintenance agent
|
||||
|
||||
A standalone systemd service that keeps the container stack healthy and current,
|
||||
and talks to the operator over Matrix (chat.semprini.me).
|
||||
A systemd service on the semprini.me stack host (AWS Lightsail `Semprini-Core`). It keeps
|
||||
the container stack healthy and current:
|
||||
- acts on critical log alerts the moment they are posted
|
||||
- upgrades everything the host runs, weekly
|
||||
- keeps the semprini-core repo equal to what runs
|
||||
- talks to the operator over Matrix (chat.semprini.me) like a chat
|
||||
|
||||
It is the *unattended driver* for the canonical stack-support agent that lives
|
||||
in the **semprini-core** repo (`agents/stack-support.agent.md`): the daemon
|
||||
gathers state and hands the judgement calls (diagnosis, remediation, upgrade
|
||||
planning) to that agent, run headless via Claude Code.
|
||||
It is the *unattended driver* for the canonical stack-support agent in the **semprini-core**
|
||||
repo (`agents/stack-support.agent.md`). The daemon notices events and hands the judgement
|
||||
calls to that agent, run headless via Claude Code. Design and decisions:
|
||||
[`docs/architecture.md`](docs/architecture.md).
|
||||
|
||||
## Relationship to semprini-core
|
||||
## Talking to it
|
||||
|
||||
This is a **separate project** from the stack it maintains. It does not bundle
|
||||
its own copy of the stack logic — at runtime it reads, from the semprini-core
|
||||
checkout pointed to by `repo_dir` in `config.json`:
|
||||
Two rooms on chat.semprini.me:
|
||||
|
||||
- `agents/stack-support.agent.md` — injected as the agent's system prompt
|
||||
- `docs/stack-support-runbook.md` — the remediation runbook
|
||||
- `core_stack/compose*.yml` — the compose files it operates on
|
||||
| Room | Written by | What happens |
|
||||
|---|---|---|
|
||||
| **Stack Maintenance** | you and `@maintainer-bot` | Your messages are instructions or questions: 👀 shows it arrived, typing shows it is working, and the reply lands in the room. A follow-up within 4 hours continues the same conversation. Decisions it needs arrive here as numbered options; answer with a number or in words. Reports and the daily summary go here too. |
|
||||
| **Stack alerts** (`#stack-alerts`) | `@alerts` (Alertmanager bridge) | Each FIRING alert is triaged and answered in a thread under it. Reply in the thread to discuss it. Anything that is not simply "ok" is repeated in Stack Maintenance. |
|
||||
|
||||
So **a semprini-core checkout and the running core stack must be present on the
|
||||
host** (they are what this agent maintains). The canonical stack-support agent
|
||||
definition stays in semprini-core to avoid drift. Other projects that register
|
||||
Uptime Kuma monitors (e.g. `semprini-blog`) are also maintained — their repos
|
||||
are made available to the agent via `extra_dirs`.
|
||||
Messages are read with a long-poll `/sync`: the homeserver answers as soon as something is
|
||||
posted, so there is no polling delay.
|
||||
|
||||
### Prerequisites
|
||||
A message that is exactly one of these words is handled at once, even mid-run:
|
||||
|
||||
- Docker (host user in the `docker` group)
|
||||
- Python 3 (stdlib only — no venv needed)
|
||||
- [Claude Code](https://claude.com/claude-code) CLI on `PATH`
|
||||
- A semprini-core checkout + the core stack running (incl. Uptime Kuma)
|
||||
| Command | Effect |
|
||||
|---|---|
|
||||
| `status` | What it is doing, the queue, health, host, next upgrade |
|
||||
| `cancel` / `stop` | Stop the agent run in progress |
|
||||
| `new` | Forget this room's conversation |
|
||||
| `upgrade` | Run the weekly upgrade now |
|
||||
| `help` | The list |
|
||||
|
||||
## What it does
|
||||
|
||||
| Cadence | Action |
|
||||
| Trigger | Action |
|
||||
|---|---|
|
||||
| **Every 5 min** (`health_interval_seconds`) | Read Uptime Kuma to learn which services are tracked **right now** and their up/down status. If a service is confirmed down across `down_confirmations` cycles, invoke the stack-support agent to diagnose + remediate, then report to Matrix. |
|
||||
| **Every 7 days** (`upgrade_interval_seconds`) | Resolve the containers behind tracked services, find the owning compose file, and have the agent research + apply upgrades (test, pin, rollback on failure). Breaking/major upgrades are escalated to Matrix for a decision. |
|
||||
| **Continuous** (`matrix_poll_seconds`) | Poll the Matrix room for the admin's replies — to answer escalations, or to take ad-hoc instructions. |
|
||||
| **Daily** (`heartbeat_interval_seconds`) | Quiet "N/M services up" heartbeat when all is well. |
|
||||
| Operator message | Agent run; the reply goes to the same room or thread |
|
||||
| FIRING alert in `#stack-alerts` | Batched for 60s, then one triage run: read the LogQL lines, fix a real fault, or demote benign noise in Alloy. Each fingerprint is re-investigated at most every 12h; `PipelineTest` is only acknowledged |
|
||||
| Every 5 min | Health check, below. Any findings become one agent run |
|
||||
| — Kuma monitor DOWN for 2 checks | Diagnose and remediate |
|
||||
| — Kuma monitor DOWN→UP between checks | Post-mortem from logs; changes nothing healthy |
|
||||
| — Disk ≥ 85%, memory < 400 MB, kernel OOM kill, restart loop, stale Kuma | Investigate and fix; 12h cooldown per finding |
|
||||
| — Host rebooted | Verify every stack came back |
|
||||
| Daily, 21:00 UTC | 📋 report: monitors, downtime, alerts, agent runs, commits, pending reboot or decision |
|
||||
| Weekly, Sat 22:00 UTC | Upgrade every image and host packages: test, pin, commit, push, roll back on failure. Majors and reboots are escalated |
|
||||
| Hourly | Self-update from this repo |
|
||||
|
||||
### Scope is dynamic
|
||||
|
||||
Scope is **whatever Uptime Kuma is tracking at the moment the check runs** — the
|
||||
monitor list is re-read every cycle, nothing is hard-coded. This deliberately
|
||||
covers services from *other* projects that register Kuma monitors (e.g.
|
||||
`semprini-blog`), not just `semprini-core`. Other project repos are made
|
||||
available to the agent via `extra_dirs`.
|
||||
|
||||
Kuma's own heartbeat result is the health signal, so the daemon never
|
||||
re-implements probes — it trusts the monitoring system already in the stack.
|
||||
|
||||
## Architecture
|
||||
Scope for remediation is **whatever Uptime Kuma tracks at check time**, re-read every
|
||||
cycle. Pausing a Kuma monitor is how a service is taken out of scope; see semprini-core
|
||||
`docs/stack-support-runbook.md` → *Deliberately Stopped Services*. Upgrades cover every
|
||||
image on the host.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ maintainer.py (daemon) │
|
||||
Uptime Kuma ──┤ read monitors+status (sqlite in volume) │
|
||||
(kuma.db) │ │
|
||||
│ on down / on schedule: │
|
||||
│ claude -p --append-system-prompt │──▶ stack-support
|
||||
│ (agents/stack-support.agent.md) │ agent does the
|
||||
│ │ diagnosis/fix
|
||||
│ parse JSON result envelope │◀── + returns JSON
|
||||
│ │
|
||||
Matrix ◀─────┤ send summaries / ask questions │
|
||||
(@paul) ─────┤ poll replies → resume escalations │
|
||||
└─────────────────────────────────────────┘
|
||||
Stack Maintenance ──┐ long-poll /sync ┌── Uptime Kuma (kuma.db via sqlite container)
|
||||
#stack-alerts ──────┤ ├── host: /proc, docker, kernel log
|
||||
▼ ▼
|
||||
┌──────────────────── maintainer.py ────────────────────┐
|
||||
│ listener thread: commands now, tasks → persisted queue │
|
||||
│ worker: one agent run at a time (operator > alerts > │
|
||||
│ health > upgrade); timers when idle │
|
||||
└───────────┬───────────────────────────────▲────────────┘
|
||||
│ claude -p [--resume] --output-format json
|
||||
▼ │ JSON envelope
|
||||
stack-support agent (semprini-core) ───────┘
|
||||
│ commits applied changes to main, pushes
|
||||
▼
|
||||
git.semprini.me/paul/semprini-core
|
||||
```
|
||||
|
||||
The agent returns a small JSON envelope the daemon relays:
|
||||
The agent ends each run with a JSON envelope the daemon relays:
|
||||
|
||||
```json
|
||||
{"status":"ok|action_taken|escalate|blocked","summary":"…","question":"…","options":["…"]}
|
||||
{"status":"ok|action_taken|escalate|blocked","summary":"…","details":"…","question":"…","options":["…"]}
|
||||
```
|
||||
|
||||
`escalate` posts the question (numbered options) to Matrix and pauses upgrades
|
||||
until the admin replies; the reply is fed back to the agent to carry out.
|
||||
## Git: the repo is what runs
|
||||
|
||||
## Autonomy
|
||||
`~/semprini-core` on the host is a git checkout of `main`. Before each run the daemon
|
||||
fast-forwards it if it is clean. The agent commits every change it applies to the live
|
||||
stack to `main` and pushes it as `claude-code`; a change it only proposes goes on a
|
||||
`maint/<topic>` branch with a pull request. After each run the daemon pushes anything left
|
||||
unpushed, retrying if Gitea is down. It reports new commits, with a link, and any
|
||||
uncommitted changes. From the laptop, deploy with semprini-core's `infra/sync-to-host.sh`
|
||||
(push, then fast-forward the host).
|
||||
|
||||
Set `autonomy` in `config.json`:
|
||||
semprini-blog (GitHub) and conk are readable by the agent but not pushable, so it proposes
|
||||
patches for them instead.
|
||||
|
||||
- `full` *(default)* — remediate **and** apply safe upgrades autonomously
|
||||
(test + auto-rollback); escalate only major/breaking upgrades.
|
||||
- `fix-only` — remediate health issues; report upgrades but never apply them.
|
||||
- `notify` — never change anything; only report to Matrix.
|
||||
## Setup on the host
|
||||
|
||||
## Why it runs as `paul`, not root
|
||||
|
||||
- Claude Code refuses `--permission-mode bypassPermissions` under root.
|
||||
- `paul` is in the `docker` group, so the agent can drive Docker/Compose.
|
||||
- Kuma's root-owned `kuma.db` is read via a throwaway `keinos/sqlite3`
|
||||
container mounting the named volume read-only — no host file access needed.
|
||||
|
||||
## Install
|
||||
Prerequisites:
|
||||
- the stack is running, including Synapse, Gitea, matrix-alerts and Uptime Kuma
|
||||
- `~/semprini-core` is a git checkout of `main`
|
||||
- the host user is in the `docker` group
|
||||
|
||||
```bash
|
||||
cd /home/paul/Dev/semprini-maintainer
|
||||
git clone https://git.semprini.me/paul/semprini-maintainer.git ~/semprini-maintainer
|
||||
cd ~/semprini-maintainer
|
||||
cp config.example.json config.json # paths assume user ubuntu
|
||||
|
||||
# 1. Config
|
||||
cp config.example.json config.json
|
||||
# set repo_dir to the semprini-core checkout; edit paths/intervals if needed
|
||||
# (defaults match this host)
|
||||
|
||||
# 2. Provision the Matrix bot + private room with the admin
|
||||
./register-matrix-bot.sh
|
||||
# then, one-time: accept the room invite in Element as @paul:semprini.me
|
||||
|
||||
# 3. Provision the Gitea token (lets the agent push + open PRs as claude-code)
|
||||
./register-gitea-bot.sh
|
||||
|
||||
# 4. Install + start the service
|
||||
./install.sh
|
||||
./register-matrix-bot.sh # @maintainer-bot + Stack Maintenance room → config.json
|
||||
./register-gitea-bot.sh # claude-code token for pushes and PRs → config.json
|
||||
( cd ~/semprini-core/core_stack && python3 scripts/setup-matrix-alerts.py ) # invites the bot to #stack-alerts
|
||||
./install.sh # checks, git credential helper, systemd unit, start
|
||||
```
|
||||
|
||||
`config.json` and `.bot-secrets` hold the bot token/password and are gitignored.
|
||||
|
||||
### Pushing code & pull requests
|
||||
|
||||
When the agent changes tracked files in a repo (compose files, configs, scripts,
|
||||
docs) it does **not** commit to `main` — it branches, commits, pushes, and opens
|
||||
a **pull request** on `git.semprini.me` (Gitea) for the operator to review, then
|
||||
reports the PR URL to Matrix. Live remediation that must restore service now
|
||||
(e.g. `docker compose up`) still happens immediately; only the git change is
|
||||
gated behind the PR.
|
||||
|
||||
It authenticates as the **`claude-code`** user (an OIDC account in
|
||||
auth.semprini.me that is already a push-capable collaborator). `register-gitea-bot.sh`
|
||||
mints a Gitea personal access token via the gitea admin CLI inside the
|
||||
`user-gitea` container — git.semprini.me has password login and HTTP basic auth
|
||||
disabled, but a PAT still works for git-over-HTTPS and the API, so no SSH
|
||||
exposure or core-stack change is needed. The daemon hands the headless agent
|
||||
claude-code's git identity + credential (via `GIT_CONFIG_*`, scoped to
|
||||
git.semprini.me) and the Gitea API coordinates (`$GITEA_TOKEN`, `$GITEA_API`,
|
||||
`$GITEA_REPO`) so it can open the PR itself. Leaving `gitea.token` empty disables
|
||||
the workflow — the agent then edits/redeploys live without committing.
|
||||
|
||||
## Operate
|
||||
Then, once: accept the Stack Maintenance invite in Element as `@paul`, and give the daemon a
|
||||
Claude credential. Run `claude setup-token` wherever you are signed in to Claude, then on the
|
||||
host:
|
||||
|
||||
```bash
|
||||
journalctl -u semprini-maintainer -f # logs
|
||||
systemctl status semprini-maintainer
|
||||
sudo systemctl restart semprini-maintainer
|
||||
|
||||
# One-off cycles without the service (for testing):
|
||||
python3 maintainer.py --config config.json --once health
|
||||
python3 maintainer.py --config config.json --once upgrade
|
||||
python3 maintainer.py --config config.json --once replies
|
||||
ssh -t ubuntu@3.107.254.151 ~/semprini-maintainer/maintainer.py --set-claude-token
|
||||
```
|
||||
|
||||
## Files
|
||||
It checks the token with a one-line request and saves it to `config.json`. The service
|
||||
uses it from its next run, with no restart. The token lasts a year.
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `maintainer.py` | The daemon. Stdlib only. |
|
||||
| `config.example.json` | Template — copy to `config.json`. |
|
||||
| `register-matrix-bot.sh` | Creates the `@maintainer` account + room, writes token to config. |
|
||||
| `register-gitea-bot.sh` | Mints the `claude-code` Gitea token for push + PRs, writes it to config. |
|
||||
| `semprini-maintainer.service` | systemd unit (runs as `paul`). |
|
||||
| `install.sh` | Syntax-check, install, enable, start. |
|
||||
**Moving to a new host:** bring `config.json` along. It holds both bot tokens, so the two
|
||||
register scripts find valid tokens and change nothing.
|
||||
|
||||
See [`docs/architecture.md`](docs/architecture.md) for the architecture
|
||||
decision record.
|
||||
## Configuration
|
||||
|
||||
`config.json` (template: `config.example.json`). The ones worth knowing:
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `autonomy` | `full` | `full` fixes and upgrades; `fix-only` fixes and only proposes upgrades; `notify` changes nothing |
|
||||
| `claude_model` | `claude-opus-5` | Model for every run |
|
||||
| `claude_oauth_token` | — | From `claude setup-token`; set with `--set-claude-token` |
|
||||
| `health_interval_seconds` / `down_confirmations` | 300 / 2 | Health check cadence, and checks a monitor must fail before remediation |
|
||||
| `upgrade_weekday` / `upgrade_hour_utc` | 5 / 22 | Weekly upgrade slot (0 = Monday) |
|
||||
| `digest_hour_utc` | 21 | Daily report |
|
||||
| `conversation_ttl_seconds` | 14400 | How long a follow-up continues the previous conversation |
|
||||
| `escalation_expiry_seconds` | 604800 | An unanswered decision holds upgrades until then |
|
||||
| `alerts.batch_seconds` / `alerts.cooldown_seconds` / `alerts.ignore` | 60 / 43200 / `["PipelineTest"]` | Alert batching, re-investigation interval, alerts never investigated |
|
||||
| `host.*` | 85% disk, 400 MB memory | Host-check thresholds and cooldown |
|
||||
| `git.repos` | semprini-core | Checkouts the daemon fast-forwards and pushes |
|
||||
| `extra_dirs` | blog, conk | Other repos the agent may read |
|
||||
|
||||
## Operating
|
||||
|
||||
- **Logs:** `journalctl -u semprini-maintainer -f`, or `status` in Matrix.
|
||||
- **Stop everything it does:** `sudo systemctl stop semprini-maintainer`. For "watch but
|
||||
don't touch", set `"autonomy": "notify"` and restart the service.
|
||||
- **Update the daemon:** push to `main` here. It fast-forwards within the hour, runs
|
||||
`--check`, and restarts itself, or rolls back and says why.
|
||||
|
||||
### When the agent cannot run at all
|
||||
|
||||
Expired or revoked credentials, a timeout, a crashed CLI: the CLI exits non-zero with no
|
||||
envelope. That is a *maintainer* outage, not a stack verdict (`AgentUnavailable`):
|
||||
|
||||
- The task stays in the persisted queue; nothing is lost.
|
||||
- One `⛔ maintainer degraded` message names the likely cause and the fix, then it stays
|
||||
quiet until recovery.
|
||||
- Retries back off from 60s to 15 min. Saving a new token with `--set-claude-token` skips
|
||||
the wait.
|
||||
- `✅ maintainer recovered` when a run succeeds again; the queue then drains.
|
||||
|
||||
## Test without the service
|
||||
|
||||
```bash
|
||||
python3 maintainer.py --check # parsers, schedule, config, paths
|
||||
python3 maintainer.py --once health # one health cycle and any agent work it queues
|
||||
python3 maintainer.py --once digest # post the daily report now
|
||||
python3 maintainer.py --once upgrade # run the upgrade now
|
||||
```
|
||||
|
||||
Stop the service first: `--once` shares the state file.
|
||||
Reference in new issue
Block a user