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 ## What this is
A standalone, always-on **autonomous maintenance agent** for the semprini.me A standalone, always-on **autonomous maintenance agent** for the semprini.me container
container stack, deployed as a systemd service (`semprini-maintainer`). It keeps stack. It runs **on the stack host itself** (AWS Lightsail `Semprini-Core`,
the stack healthy and current and talks to the operator over Matrix `ubuntu@3.107.254.151`) as the systemd service `semprini-maintainer`. It keeps the stack
(chat.semprini.me). 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 It is the *unattended driver* for the canonical **stack-support agent**, which lives in the
lives in the separate **semprini-core** repo. This project does not reimplement separate **semprini-core** repo. This project does not reimplement that logic: it notices
that logic — it gathers state and invokes the stack-support agent headless via events, invokes the stack-support agent headless via Claude Code, and relays the agent's
Claude Code, then relays/acts on the agent's JSON result. JSON result.
## Relationship to other projects ## Relationship to other projects
- **semprini-core** (`../semprini-core`) — the Enterprise Landing Zone this agent - **semprini-core** (`~/semprini-core` on the host, a git checkout of `main`) — the stack
maintains. At runtime the daemon reads, from the path in `config.json` this agent maintains. At runtime the agent reads, from `repo_dir`:
`repo_dir`:
- `agents/stack-support.agent.md` (injected as system prompt) - `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` - `core_stack/compose*.yml`
Keep the stack-support agent definition canonical **in semprini-core** — do not
fork a copy here. Keep the stack-support agent definition canonical **in semprini-core** — do not fork a
- **Other projects** (e.g. `../semprini-blog`) that register Uptime Kuma monitors copy here.
are also maintained; their repos are exposed to the agent via `extra_dirs`. - **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) ## How it works (one screen)
- **Scope** = whatever **Uptime Kuma** tracks at check time, re-read every cycle - **Operator messages** (Stack Maintenance room): read by a long-poll `/sync`, so they
(never hard-coded). Kuma's heartbeat is the health signal — the daemon does not arrive within about a second. A follow-up within `conversation_ttl_seconds` resumes the
re-probe. Kuma's root-owned `kuma.db` is read via a throwaway `keinos/sqlite3` same Claude session (`--resume`), so it behaves like a chat. `status`, `cancel`, `new`,
container mounting the `uptime-kuma-data` volume read-only. `upgrade` and `help` are answered by the listener without the agent, even mid-run.
- **Health loop** (5 min): down services confirmed over `down_confirmations` - **Alerts** (`#stack-alerts`, written by `@alerts` via Loki → Alertmanager →
cycles → invoke stack-support agent to remediate → report to Matrix. Also matrix-alerts): FIRING messages are batched for `alerts.batch_seconds` and triaged in
reads Kuma's `important=1` heartbeat transitions since the last cycle (tracked one run, answered in a thread under the alert. Non-`ok` results are mirrored to Stack
by heartbeat id) to catch services that blipped DOWN→UP on their own, and Maintenance. A fingerprint is re-investigated at most every `alerts.cooldown_seconds`.
hands those self-recovered windows to the agent for a log post-mortem. `PipelineTest` is acknowledged, never investigated.
- **Upgrade loop** (7 days): resolve containers behind tracked services → agent - **Health timer** (5 min): Kuma monitors confirmed DOWN over `down_confirmations` cycles,
researches + applies safe upgrades (test, pin, rollback); escalates DOWN→UP blips (Kuma `important=1` heartbeats since a watermark), host checks (disk,
major/breaking ones to Matrix. memory, kernel OOM kills, container restart loops, a stale Kuma) and host reboots. All
- **Matrix**: bot `@maintainer-bot:semprini.me` DMs `@paul:semprini.me`. Escalations findings from one cycle become **one** health task. Kuma's `kuma.db` is read via a
are numbered questions; the reply is fed back to the agent to carry out. throwaway `keinos/sqlite3` container. Scope = Kuma's active monitors, re-read every
- **Git/PRs**: when the agent changes tracked files it branches, pushes, and opens cycle.
a **pull request** on git.semprini.me (Gitea) as the `claude-code` user (never - **Daily report** at `digest_hour_utc`; **weekly upgrade** at `upgrade_weekday` /
commits to `main`); live remediation still happens immediately and directly. `upgrade_hour_utc` (all images on the host, not only Kuma-tracked ones; a pending reboot
The daemon injects claude-code's git identity + credential and the Gitea API is escalated for approval).
env into the headless agent (see `agent_git_env` / `GIT_PR_POLICY` in - **One agent run at a time.** The queue is persisted in the state file with priority
`maintainer.py`); token provisioned by `register-gitea-bot.sh`. Empty operator > alerts > health > upgrade, so nothing is lost across restarts.
`gitea.token` disables the workflow. - **Git:** before a run the daemon fast-forwards clean checkouts in `git.repos`; after it,
- **Autonomy** (`config.json` → `autonomy`): `full` (default) | `fix-only` | it pushes unpushed commits and reports new commits or a dirty tree. The agent commits
`notify`. 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 ## 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. refuses `--permission-mode bypassPermissions` under root.
- `maintainer.py` is **stdlib-only** — keep it dependency-free so it deploys - `maintainer.py` is **stdlib-only** — keep it dependency-free so it deploys without a venv.
without a venv.
- Secrets live in `config.json` and `.bot-secrets` — **never commit** (gitignored). - 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. - 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 ## Files
@@ -66,16 +80,17 @@ Claude Code, then relays/acts on the agent's JSON result.
|---|---| |---|---|
| `maintainer.py` | The daemon (stdlib only). | | `maintainer.py` | The daemon (stdlib only). |
| `config.example.json` | Template — copy to `config.json`. | | `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. | | `register-gitea-bot.sh` | Mints the `claude-code` Gitea token (push + PRs); writes it to config. |
| `install.sh` | Syntax-check, install unit, enable + start. | | `install.sh` | Checks, git credential helper, renders + enables the unit. |
| `semprini-maintainer.service` | systemd unit (runs as `paul`). | | `semprini-maintainer.service` | systemd unit template (`@USER@`, `@HOME@`, `@DIR@`). |
| `docs/architecture.md` | Architecture decision record. | | `docs/architecture.md` | Architecture decision record. |
## Test without the service ## Test without the service
```bash ```bash
python3 maintainer.py --config config.json --once health python3 maintainer.py --check # parsers, schedule, config, paths
python3 maintainer.py --config config.json --once upgrade python3 maintainer.py --once health # one health cycle + any agent work it queues
python3 maintainer.py --config config.json --once replies python3 maintainer.py --once digest # post the daily report now
python3 maintainer.py --once upgrade # run the upgrade now
``` ```
+136 -128
View File
@@ -1,165 +1,173 @@
# semprini-maintainer — autonomous stack maintenance agent # semprini-maintainer — autonomous stack maintenance agent
A standalone systemd service that keeps the container stack healthy and current, A systemd service on the semprini.me stack host (AWS Lightsail `Semprini-Core`). It keeps
and talks to the operator over Matrix (chat.semprini.me). 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 It is the *unattended driver* for the canonical stack-support agent in the **semprini-core**
in the **semprini-core** repo (`agents/stack-support.agent.md`): the daemon repo (`agents/stack-support.agent.md`). The daemon notices events and hands the judgement
gathers state and hands the judgement calls (diagnosis, remediation, upgrade calls to that agent, run headless via Claude Code. Design and decisions:
planning) to that agent, run headless via Claude Code. [`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 Two rooms on chat.semprini.me:
its own copy of the stack logic — at runtime it reads, from the semprini-core
checkout pointed to by `repo_dir` in `config.json`:
- `agents/stack-support.agent.md` — injected as the agent's system prompt | Room | Written by | What happens |
- `docs/stack-support-runbook.md` — the remediation runbook |---|---|---|
- `core_stack/compose*.yml` — the compose files it operates on | **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 Messages are read with a long-poll `/sync`: the homeserver answers as soon as something is
host** (they are what this agent maintains). The canonical stack-support agent posted, so there is no polling delay.
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`.
### Prerequisites A message that is exactly one of these words is handled at once, even mid-run:
- Docker (host user in the `docker` group) | Command | Effect |
- Python 3 (stdlib only — no venv needed) |---|---|
- [Claude Code](https://claude.com/claude-code) CLI on `PATH` | `status` | What it is doing, the queue, health, host, next upgrade |
- A semprini-core checkout + the core stack running (incl. Uptime Kuma) | `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 ## 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. | | Operator message | Agent run; the reply goes to the same room or thread |
| **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. | | 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 |
| **Continuous** (`matrix_poll_seconds`) | Poll the Matrix room for the admin's replies — to answer escalations, or to take ad-hoc instructions. | | Every 5 min | Health check, below. Any findings become one agent run |
| **Daily** (`heartbeat_interval_seconds`) | Quiet "N/M services up" heartbeat when all is well. | | — 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 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
Scope is **whatever Uptime Kuma is tracking at the moment the check runs** — the `docs/stack-support-runbook.md` → *Deliberately Stopped Services*. Upgrades cover every
monitor list is re-read every cycle, nothing is hard-coded. This deliberately image on the host.
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
``` ```
┌─────────────────────────────────────────┐ Stack Maintenance ──┐ long-poll /sync ┌── Uptime Kuma (kuma.db via sqlite container)
│ maintainer.py (daemon) │ #stack-alerts ──────┤ ├── host: /proc, docker, kernel log
Uptime Kuma ──┤ read monitors+status (sqlite in volume) │ ▼ ▼
(kuma.db) │ │ ┌──────────────────── maintainer.py ────────────────────┐
│ on down / on schedule: │ │ listener thread: commands now, tasks → persisted queue │
│ claude -p --append-system-prompt │──▶ stack-support │ worker: one agent run at a time (operator > alerts > │
│ (agents/stack-support.agent.md) │ agent does the │ health > upgrade); timers when idle │
│ │ diagnosis/fix └───────────┬───────────────────────────────▲────────────┘
│ parse JSON result envelope │◀── + returns JSON │ claude -p [--resume] --output-format json
│ │ ▼ │ JSON envelope
Matrix ◀─────┤ send summaries / ask questions │ stack-support agent (semprini-core) ───────┘
(@paul) ─────┤ poll replies → resume escalations │ │ 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 ```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 ## Git: the repo is what runs
until the admin replies; the reply is fed back to the agent to carry out.
## 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 ## Setup on the host
(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.
## Why it runs as `paul`, not root Prerequisites:
- the stack is running, including Synapse, Gitea, matrix-alerts and Uptime Kuma
- Claude Code refuses `--permission-mode bypassPermissions` under root. - `~/semprini-core` is a git checkout of `main`
- `paul` is in the `docker` group, so the agent can drive Docker/Compose. - the host user is in the `docker` group
- 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
```bash ```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 ./register-matrix-bot.sh # @maintainer-bot + Stack Maintenance room → config.json
cp config.example.json config.json ./register-gitea-bot.sh # claude-code token for pushes and PRs → config.json
# set repo_dir to the semprini-core checkout; edit paths/intervals if needed ( cd ~/semprini-core/core_stack && python3 scripts/setup-matrix-alerts.py ) # invites the bot to #stack-alerts
# (defaults match this host) ./install.sh # checks, git credential helper, systemd unit, start
# 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
``` ```
`config.json` and `.bot-secrets` hold the bot token/password and are gitignored. 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
### Pushing code & pull requests host:
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
```bash ```bash
journalctl -u semprini-maintainer -f # logs ssh -t ubuntu@3.107.254.151 ~/semprini-maintainer/maintainer.py --set-claude-token
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
``` ```
## 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 | **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.
| `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. |
See [`docs/architecture.md`](docs/architecture.md) for the architecture ## Configuration
decision record.
`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.
+33 -9
View File
@@ -1,24 +1,47 @@
{ {
"repo_dir": "/home/paul/Dev/semprini-core", "repo_dir": "/home/ubuntu/semprini-core",
"extra_dirs": ["/home/paul/Dev"], "extra_dirs": ["/home/ubuntu/semprini-blog", "/home/ubuntu/conk"],
"agent_file": "agents/stack-support.agent.md", "agent_file": "agents/stack-support.agent.md",
"runbook_file": "docs/stack-support-runbook.md", "runbook_file": "docs/stack-support-runbook.md",
"claude_bin": "/home/paul/.local/bin/claude", "claude_bin": "/home/ubuntu/.local/bin/claude",
"claude_model": "claude-sonnet-4-6", "claude_model": "claude-opus-5",
"claude_oauth_token": "",
"claude_extra_args": [], "claude_extra_args": [],
"agent_timeout_seconds": 1800, "agent_timeout_seconds": 2700,
"kuma_volume": "uptime-kuma-data", "kuma_volume": "uptime-kuma-data",
"sqlite_image": "keinos/sqlite3", "sqlite_image": "keinos/sqlite3",
"autonomy": "full", "autonomy": "full",
"health_interval_seconds": 300, "health_interval_seconds": 300,
"upgrade_interval_seconds": 604800,
"matrix_poll_seconds": 30,
"down_confirmations": 2, "down_confirmations": 2,
"heartbeat_interval_seconds": 86400, "upgrade_weekday": 5,
"upgrade_hour_utc": 22,
"digest_hour_utc": 21,
"conversation_ttl_seconds": 14400,
"escalation_expiry_seconds": 604800,
"self_update_interval_seconds": 3600,
"state_file": "/home/paul/.local/state/semprini-maintainer/state.json", "state_file": "/home/ubuntu/.local/state/semprini-maintainer/state.json",
"alerts": {
"sender": "@alerts:semprini.me",
"batch_seconds": 60,
"cooldown_seconds": 43200,
"ignore": ["PipelineTest"]
},
"host": {
"disk_warn_percent": 85,
"mem_available_min_mb": 400,
"kuma_stale_seconds": 600,
"check_cooldown_seconds": 43200
},
"git": {
"repos": [{"path": "/home/ubuntu/semprini-core", "slug": "paul/semprini-core"}],
"branch": "main"
},
"gitea": { "gitea": {
"api_base": "https://git.semprini.me/api/v1", "api_base": "https://git.semprini.me/api/v1",
@@ -35,6 +58,7 @@
"user_id": "@maintainer-bot:semprini.me", "user_id": "@maintainer-bot:semprini.me",
"access_token": "FILLED_BY_register-matrix-bot.sh", "access_token": "FILLED_BY_register-matrix-bot.sh",
"room_id": "FILLED_BY_register-matrix-bot.sh", "room_id": "FILLED_BY_register-matrix-bot.sh",
"alerts_room": "#stack-alerts:semprini.me",
"admin_user_id": "@paul:semprini.me" "admin_user_id": "@paul:semprini.me"
} }
} }
+88 -60
View File
@@ -1,75 +1,103 @@
# Maintenance Agent (semprini-maintainer) # Maintenance Agent (semprini-maintainer)
Autonomous, always-on agent that keeps the container stack healthy and current. Autonomous, always-on agent that keeps the semprini.me stack healthy and current.
Implementation: this repository — see [`README.md`](../README.md). It maintains Implementation: this repository — see [`README.md`](../README.md). It maintains the
the **semprini-core** stack (a separate repo) referenced via `repo_dir`. **semprini-core** stack (a separate repo) referenced via `repo_dir`.
Revised 2026-09-15 for the move to AWS Lightsail: the daemon runs on the stack host,
reacts to Matrix events instead of polling, and keeps the repo equal to what runs.
## Purpose ## Purpose
Continuously maintain the running stack without an operator at the keyboard: Maintain the running stack without an operator at the keyboard:
1. Detect and **remediate** service outages. 1. **Remediate** outages, and act on critical log alerts as they arrive.
2. Periodically **check for and apply container upgrades** (with test + rollback). 2. **Upgrade** everything the host runs weekly, with test and rollback.
3. **Communicate with the operator over Matrix** (chat.semprini.me), including 3. **Keep the repo current**, so the stack can be rebuilt from git plus the host's secrets.
asking questions when an upgrade needs a human decision. 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 It is the unattended driver for the canonical stack-support agent
(`agents/stack-support.agent.md`) — it does not re-implement that logic, it (`semprini-core/agents/stack-support.agent.md`): it feeds the agent events and state and
feeds the agent state and relays its results. 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) |
| 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: disk ≥ 85%, memory < 400 MB, OOM kill, restart loop, Kuma stale, reboot | Agent investigates (12h cooldown per finding) | Report in Stack Maintenance |
| Daily report | 21:00 UTC | No agent: monitors, downtime, alerts, 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; pins, commits, pushes; escalates majors and reboots | Report + decisions |
| Self-update | Hourly | Fast-forward this checkout, `--check`, re-exec | 🔄 notice |
## Key decisions ## Key decisions
- **Scope = Uptime Kuma's live monitor list.** Read every health cycle, never - **Runs on the stack host.** Lightsail `Semprini-Core`, user `ubuntu`, systemd. Kuma's
hard-coded. Anything Kuma tracks is in scope — including services owned by database, Docker, Loki and the kernel log are local, and there is no second machine to
other projects (e.g. `semprini-blog`) that register Kuma monitors. This keeps keep alive. Consequence: a dead VM takes the maintainer with it (see *Residual risks*).
the maintained set and the monitored set identical by construction. - **Event-driven via long-poll `/sync`, not a Synapse application service.** The
- **Health signal = Kuma heartbeat.** The daemon reads Kuma's own up/down homeserver holds a `/sync` request open and answers the moment an event lands, so
result rather than re-probing, reusing the stack's existing monitoring. messages are handled within about a second. That is the push mechanism of the Matrix
- **Kuma data access** via a throwaway `keinos/sqlite3` container mounting the client-server API. An appservice would push over HTTP instead, but it needs a
`uptime-kuma-data` volume read-only (the daemon user has Docker but not host registration file in the generated `homeserver.yaml`, a listener reachable from the
access to root-owned volume files). Synapse container, and a Synapse restart. It would gain nothing a person could notice.
- **Runner = Claude Code headless** (`claude -p`), with - **One agent run at a time, priority queue.** Two agents changing the same stack at once
`agents/stack-support.agent.md` injected as the system prompt. The agent would fight. The queue is persisted, so an instruction or alert survives a restart or an
returns a JSON envelope (`status/summary/question/options`) the daemon acts on. unusable agent. Priority: operator > alerts > health > upgrade. The listener answers
- **Runs as `paul`** (in the `docker` group), not root — Claude Code refuses `status` and `cancel` itself while a run is in progress.
`bypassPermissions` as root. - **Conversations resume Claude sessions.** Each room, and each alert thread, maps to the
- **Autonomy = full** by default: remediate and apply safe upgrades; escalate last session used there. A reply within 4 hours runs `claude -p --resume`, so "why?"
only major/breaking upgrades to Matrix and resume on reply. Configurable to and "do option 2" work. An escalation's answer always resumes the session that asked.
`fix-only` or `notify`. - **Scope of remediation = Uptime Kuma's active monitors.** Re-read every cycle, so
- **Matrix transport**: dedicated bot `@maintainer:semprini.me` (created via the pausing a monitor takes a service out of scope (runbook → *Deliberately Stopped
Synapse registration shared secret) in a private room with `@paul:semprini.me`. Services*). Upgrades cover every image on the host.
- **Code changes go through pull requests.** When the agent edits tracked files - **Health signal = Kuma heartbeat**, read from `kuma.db` through a throwaway
it branches, pushes, and opens a PR on Gitea (`git.semprini.me`) as the `keinos/sqlite3` container on the volume, read-only. Host checks cover what Kuma cannot
`claude-code` user rather than committing to `main`, giving the operator a see. Prometheus stays out: semprini-core's observability design chose this check
review gate. Live remediation (restart/redeploy) is *not* gated — only the git instead.
change is. claude-code is an OIDC-linked, push-capable collaborator; since - **Alerts go to the agent, not a person.** Every alert can start a paid run, so alerts
git.semprini.me disables password login + HTTP basic auth, `register-gitea-bot.sh` are batched, re-investigated at most every 12h per fingerprint, and benign messages are
mints a personal access token via the gitea admin CLI inside the `user-gitea` demoted at the source in Alloy rather than by raising thresholds.
container (mirroring the Matrix bot's shared-secret pattern). A PAT still works - **Applied changes go straight to `main`; proposals go through pull requests.** This
for git-over-HTTPS and the API, so no SSH exposure or core-stack change is reverses the 2026-06 rule that every agent change went to a PR. Live changes then sat on
required. The daemon injects the bot's git identity + credential (`GIT_CONFIG_*`, unmerged branches while `main` fell 15 commits behind what ran. The migration itself was
scoped to the Gitea host so it overrides the repo's own `user.*`) and the API built on one of those branches. The host is now a git checkout of `main`, the laptop
coordinates into the headless agent; the agent opens the PR itself. 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.
- **Runner = Claude Code headless** (`claude -p --output-format json`), with the agent
definition appended to the system prompt and a JSON envelope
(`status/summary/details/question/options`) at the end of each reply.
- **Credential = long-lived subscription token** (`claude setup-token`) passed as
`CLAUDE_CODE_OAUTH_TOKEN`. On the laptop the daemon shared `~/.claude/.credentials.json`
with interactive sessions, and a re-login revoked its token (2026-08-19).
- **Runs as `ubuntu`, not root** (Claude Code refuses `bypassPermissions` as root). The
agent still has root-equivalent power through Docker and passwordless sudo, 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 is
stdlib-only and cannot do E2EE.
## Cadence ## Trust boundary
| Loop | Default interval | Config key | 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
| Health check + remediation | 5 min | `health_interval_seconds` | agent reads while working is untrusted: log lines, access-log paths, alert annotations,
| Upgrade review | 7 days | `upgrade_interval_seconds` | web pages. The system prompt tells the agent never to follow instructions found in them.
| Matrix reply polling | 30 s | `matrix_poll_seconds` | This is a mitigation, not a guarantee, for an agent with Docker access.
| Quiet health heartbeat | daily | `heartbeat_interval_seconds` |
## Escalation flow ## Residual risks
1. Agent returns `status=escalate` with a `question` + `options`. - **Nothing outside the VM watches it.** If the host dies, Kuma, Gitea, Matrix and the
2. Daemon posts a numbered question to Matrix and pauses upgrade cycles. maintainer die together and nobody is told. Cheapest fix: an external dead-man's switch
3. Admin replies (a number or free text). (e.g. healthchecks.io) pinged by the daily report.
4. Daemon feeds the decision back to the agent, which carries it out and reports. - **Gitea lives on the host it describes.** vol-backup copies its volume to S3 nightly, and
laptop clones exist. A push mirror to GitHub would make a rebuild independent of S3.
## Operational notes - **The Claude token expires after a year.** The agent then reports itself degraded;
re-run `claude setup-token` and `--set-claude-token`.
- The bot DM room invite must be accepted once by `@paul` in Element. - **Health checks pause during an agent run.** A 30-minute upgrade delays the next Kuma
- Secrets (`config.json`, `.bot-secrets`) are gitignored. check by up to that long; alerts and operator messages still queue and are acknowledged.
- A single unanswered escalation blocks new upgrade cycles (health remediation
continues regardless).
+45 -22
View File
@@ -1,44 +1,67 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# install.sh — install & enable the semprini-maintainer systemd service. # install.sh — install & enable the semprini-maintainer systemd service.
# #
# Run from this directory. Requires sudo for the systemd parts. # Run on the stack host, from this checkout, as the user the service runs as
# (not root; sudo is used for the systemd parts). Idempotent.
set -euo pipefail set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
UNIT="semprini-maintainer.service" UNIT="semprini-maintainer.service"
DEST="/etc/systemd/system/$UNIT" DEST="/etc/systemd/system/$UNIT"
USER_NAME="$(id -un)"
[ "$USER_NAME" != root ] || { echo "ERROR: run as the service user, not root"; exit 1; }
echo "→ Pre-flight checks" echo "→ Pre-flight checks"
command -v docker >/dev/null || { echo "ERROR: docker not found"; exit 1; } for bin in docker python3 git curl; do
command -v python3 >/dev/null || { echo "ERROR: python3 not found"; exit 1; } command -v "$bin" >/dev/null || { echo "ERROR: $bin not found"; exit 1; }
done
CLAUDE_BIN="$(python3 -c "import json;print(json.load(open('$DIR/config.json'))['claude_bin'])" 2>/dev/null || echo /home/paul/.local/bin/claude)" id -nG | grep -qw docker || echo "WARN: $USER_NAME is not in the docker group"
[ -x "$CLAUDE_BIN" ] || echo "WARN: claude binary not executable at $CLAUDE_BIN"
if [ ! -f "$DIR/config.json" ]; then if [ ! -f "$DIR/config.json" ]; then
echo "ERROR: config.json missing. Run:" echo "ERROR: config.json missing. Copy config.example.json to config.json and"
echo " cp $DIR/config.example.json $DIR/config.json" echo " adjust the paths, then run register-matrix-bot.sh and register-gitea-bot.sh."
echo " $DIR/register-matrix-bot.sh"
exit 1 exit 1
fi fi
chmod 600 "$DIR/config.json"
TOKEN="$(python3 -c "import json;print(json.load(open('$DIR/config.json'))['matrix']['access_token'])")" cfg_get() {
case "$TOKEN" in python3 - "$DIR" "$1" <<'PY'
""|FILLED_BY_*) echo "ERROR: Matrix not provisioned. Run register-matrix-bot.sh first."; exit 1;; import sys
esac sys.path.insert(0, sys.argv[1])
import maintainer
cfg = maintainer.load_config(sys.argv[1] + "/config.json")
if sys.argv[2] == "git-credential":
env = maintainer.agent_git_env(cfg) # also writes the credential store
if env:
print(cfg["gitea"]["web_base"].rstrip("/"), env["GIT_CONFIG_VALUE_2"])
else:
print(cfg[sys.argv[2]])
PY
}
# Gitea (push/PR capability) is optional — warn but don't block if unprovisioned. CLAUDE_BIN="$(cfg_get claude_bin)"
GTOK="$(python3 -c "import json;print(json.load(open('$DIR/config.json')).get('gitea',{}).get('token',''))")" if [ ! -x "$CLAUDE_BIN" ]; then
case "$GTOK" in echo "→ Installing Claude Code"
""|FILLED_BY_*) echo "WARN: Gitea not provisioned — the agent will not push or open PRs."; curl -fsSL https://claude.ai/install.sh | bash
echo " Run register-gitea-bot.sh to enable it.";; fi
esac
echo "→ Syntax-checking maintainer.py" echo "→ Checking maintainer.py and config"
python3 -m py_compile "$DIR/maintainer.py" python3 -m py_compile "$DIR/maintainer.py"
python3 "$DIR/maintainer.py" --config "$DIR/config.json" --check
# Git on this host authenticates to Gitea as claude-code — for the agent, for
# the daemon's own pushes, and for sync-to-host.sh's fast-forward alike.
read -r WEB HELPER <<<"$(cfg_get git-credential)" || true
if [ -n "${WEB:-}" ]; then
echo "→ Git credential helper for $WEB"
git config --global "credential.$WEB.helper" "$HELPER"
else
echo "WARN: no Gitea token — the agent cannot push. Run register-gitea-bot.sh."
fi
echo "→ Installing $UNIT" echo "→ Installing $UNIT"
sudo cp "$DIR/$UNIT" "$DEST" sed -e "s|@USER@|$USER_NAME|g" -e "s|@HOME@|$HOME|g" -e "s|@DIR@|$DIR|g" \
"$DIR/$UNIT" | sudo tee "$DEST" >/dev/null
sudo systemctl daemon-reload sudo systemctl daemon-reload
sudo systemctl enable "$UNIT" sudo systemctl enable "$UNIT"
sudo systemctl restart "$UNIT" sudo systemctl restart "$UNIT"
@@ -46,5 +69,5 @@ sudo systemctl restart "$UNIT"
echo echo
echo "✓ Installed and started." echo "✓ Installed and started."
echo " Logs: journalctl -u $UNIT -f" echo " Logs: journalctl -u $UNIT -f"
echo " Status: systemctl status $UNIT" echo " Status: systemctl status $UNIT (or send 'status' in Matrix)"
echo " Stop: sudo systemctl stop $UNIT" echo " Stop: sudo systemctl stop $UNIT"
+1754 -581
View File
File diff suppressed because it is too large. Load diff
+13 -15
View File
@@ -1,28 +1,26 @@
[Unit] [Unit]
Description=semprini-core autonomous stack maintenance agent Description=semprini-core autonomous stack maintenance agent
Documentation=file:///home/paul/Dev/semprini-maintainer/README.md Documentation=https://git.semprini.me/paul/semprini-maintainer
After=docker.service network-online.target After=docker.service network-online.target
Wants=network-online.target Wants=network-online.target
Requires=docker.service Requires=docker.service
[Service] [Service]
Type=simple Type=simple
# Runs as the host user (must be in the 'docker' group). NOT root: Claude Code # A template: install.sh fills in @USER@, @HOME@ and @DIR@.
# refuses --permission-mode bypassPermissions when running as root. # NOT root: Claude Code refuses --permission-mode bypassPermissions as root.
User=paul User=@USER@
Group=paul Group=@USER@
SupplementaryGroups=docker # docker: drive the stack. adm: read the kernel log for OOM kills.
WorkingDirectory=/home/paul/Dev/semprini-maintainer SupplementaryGroups=docker adm
Environment=HOME=/home/paul WorkingDirectory=@DIR@
Environment=PATH=/home/paul/.local/bin:/usr/local/bin:/usr/bin:/bin Environment=HOME=@HOME@
ExecStart=/usr/bin/python3 /home/paul/Dev/semprini-maintainer/maintainer.py --config /home/paul/Dev/semprini-maintainer/config.json Environment=PATH=@HOME@/.local/bin:/usr/local/bin:/usr/bin:/bin
ExecStart=/usr/bin/python3 @DIR@/maintainer.py --config @DIR@/config.json
Restart=always Restart=always
RestartSec=30 RestartSec=30
# Give a long-running upgrade plenty of time before any stop is considered hung. # Stopping kills the whole cgroup, an agent run in progress included.
TimeoutStopSec=120 TimeoutStopSec=30
# Light hardening (kept permissive — the agent legitimately drives Docker).
NoNewPrivileges=false
StandardOutput=journal StandardOutput=journal
StandardError=journal StandardError=journal
SyslogIdentifier=semprini-maintainer SyslogIdentifier=semprini-maintainer