Files
semprini-maintainer/CLAUDE.md
T
paulandClaude Opus 5.5 9aa1abf0e2 Run everything on the local model; no cloud tier
GLM-4.7-Flash can reach core over SSH, check, diagnose and upgrade, so
operator messages, alert triage, health findings and the weekly upgrade all
route to the one local profile. The Anthropic profile and its cloud-first
routing go, and with them the API key and metered billing the first draft
needed. The local profile's context_tokens rises to 131072, the window Ollama
loads GLM with, so long runs are not trimmed early.

Profiles and routing stay in configuration: a second model can still be
added, with hand-over when the first is unreachable or fails the run.

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

153 lines
10 KiB
Markdown

# semprini-maintainer — Claude Instructions
## What this is
A standalone, always-on **autonomous maintenance agent** for the semprini.me container
stack. It runs on the **operator's workstation** (EVAI: Windows, RTX 4090), in **WSL
Ubuntu**, as the systemd service `semprini-maintainer`. It keeps the core stack on AWS
Lightsail (`Semprini-Core`, `ubuntu@3.107.254.151`) healthy and current, reaching it over
SSH, 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 notices
events, runs the stack-support agent in-process with **pydantic-ai** on the workstation's
local model (GLM-4.7-Flash on Ollama), and relays the agent's typed result.
Until 2026-09-26 it ran on the core host itself and drove Claude Code headless;
`docs/architecture.md` records why that changed.
## Relationship to other projects
- **semprini-core** (`~/semprini-core` on the core host, a git checkout of `main`) — the
stack this agent maintains. At runtime the agent reads, over SSH, from `repo_dir`:
- `agents/stack-support.agent.md` (injected into the instructions; a copy is cached in
the state directory for when core is unreachable)
- `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.
- **semprini-blog** (GitHub) and **conk** run on the core host and are listed in
`extra_dirs`. The agent can operate their containers but cannot push their repos, so it
proposes file changes instead.
- **semprini-data** and the home k3s cluster run on this workstation (Hyper-V VMs
`sem-k8s-1..3`, `sem-gw`). The agent reaches the cluster as the runbook says (kubectl and
ssh from core, through the tunnel) and can inspect the VMs from the `windows` host; the
agent definition says to escalate changes there.
## How it works (one screen)
- **Hosts** (`hosts.py`, `config.json` → `hosts`): `core` (ssh, one multiplexed
connection), `local` (WSL bash) and `windows` (`powershell.exe` through WSL interop).
The daemon's probes, its git bookkeeping and the agent's tools all run through them.
- **Models** (`agent.py`, `config.json` → `models`, `routing`, `limits`): one profile,
`local` (GLM-4.7-Flash on the Windows host's Ollama, at `{windows_host}`), routed for every
kind of task. The operator decided (2026-09-26) that the local model does all of it,
upgrades included, with no cloud tier. The mechanism stays general: a profile can be
`anthropic:…` with an API key, any OpenAI-compatible `base_url`, or anything pydantic-ai
infers, and a routing list with a second profile hands over when the first is unreachable
(`FallbackModel`) or fails the run. No usable model → `AgentUnavailable`: the task stays
queued, the operator is told once per kind, and that kind backs off from 60s to 15 min.
`--try-model` checks a profile calls tools and *uses their results*.
- **The agent**: tools `shell`, `read_file`, `write_file`, `edit_file` (all on a named
host) and `fetch_url`; result type `Envelope` (status, summary, details, question,
options). Conversations are pydantic-ai message histories in `<state dir>/sessions/`, so a
follow-up can resume on any model. `cancel` trips a `CancellationToken` and kills the
command in flight. Old tool output is shortened when a conversation nears a profile's
`context_tokens`.
- **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 session, so it behaves like a chat. `status`, `cancel`, `new`, `model`, `upgrade`,
`hold`, `resume` and `help` are answered by the listener without the agent, even mid-run.
- **Hold** (`hold 45m <why>` in Matrix, `maintainer.py --hold 45m --reason …` from a
shell): a time-boxed pause on everything the daemon starts by itself — health cycles,
alert triage, upgrades and the desk — while operator messages still run and alerts still
batch. There are two hold files: this machine's (`hold.json` beside the state file) and
the core host's (`remote_hold_file`), which `--hold` writes when run from the host's
old checkout — as semprini-core's `sync-to-host.sh` does, 15 minutes per deploy. The
daemon reads the host's each minute and honours whichever ends later. `--hold` never
shortens a longer hold already in force; `hold` in Matrix does what it says.
- **Service desk** (1 min, `desk` in config): runs semprini-core's
`core_stack/scripts/service-desk.py poll --json` **on the core host** over SSH (it needs
the host's `.env`, docker and kubectl). It is a script, not an agent run: it takes its turn
between runs and waits out a hold. What needs a person is posted to Stack Maintenance.
- **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): `probe.py` is piped to `ssh core python3 -` and returns one
JSON snapshot: Kuma monitors and DOWN→UP transitions (from `kuma.db` via a throwaway
`keinos/sqlite3` container), disk, memory, kernel OOM kills, container restart counts,
boot time and a pending reboot. Monitors confirmed DOWN over `down_confirmations`
cycles, blips, host anomalies and reboots become **one** health task. Three cycles that
cannot reach core raise 🚨. 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 core host; 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` (on their
host); after it, it pushes unpushed commits and reports new commits or a dirty tree. The
agent commits every change it applies to `main` in core's checkout and pushes it
(`GIT_POLICY` in `agent.py`; semprini-core `CLAUDE.md` → *Deploying changes*). On core,
git authenticates as `claude-code` with the host's own credential helper; the daemon
sets the author through the SSH environment. Pull requests are opened from `local`,
where `GITEA_*` is set.
- **Self-update:** hourly `git fetch` of this checkout; a newer `main` is fast-forwarded,
`uv sync`ed if `pyproject.toml`/`uv.lock` changed, checked with `--check`, and
re-exec'd, or rolled back if either fails.
- **Autonomy** (`config.json` → `autonomy`): `full` (default) | `fix-only` | `notify`
(notify also withholds the file-writing tools).
## Conventions / guardrails
- Runs as the WSL user (`paul`), **not root**, with that user's SSH key to core.
- The daemon needs **pydantic-ai** (`uv sync`; the unit runs `.venv/bin/python`). Three
paths stay **stdlib-only** and must remain so:
- `probe.py`: it runs on the core host's system python3.
- `hosts.py`: imported at start-up by everything.
- `maintainer.py --hold` / `--resume`: `agent.py` is imported lazily (`agentlib()`), so the
core host's checkout can still hold the daemon with plain python3.
- `agent.py` is written against **pydantic-ai 2.x** (capabilities, `CancellationToken`,
`FallbackModel`, `OllamaModel`, `httpx2`). Read the installed package before assuming an
API from memory; `uv.lock` pins the version.
- Secrets live in `config.json` (API keys, bot tokens) and `.bot-secrets` — **never
commit** (gitignored). API keys are re-read from disk before every run.
- **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 — and `--check --offline` free of network calls.
- **Cutover from the core host:** `install.sh` stops and disables the host's service before
starting this one. One Matrix bot means one daemon; never run both.
- 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 instructions say so (`agent.py` → `instructions`); keep that line when
editing prompts.
## Files
| File | Purpose |
|---|---|
| `maintainer.py` | The daemon: Matrix, queue, timers, health judgement, git bookkeeping, CLI. |
| `agent.py` | The agent: model profiles and routing, tools, instructions, sessions, `run_task`. |
| `hosts.py` | Running commands and reading/writing files on `local`, `ssh` and `powershell` hosts (stdlib). |
| `probe.py` | One health snapshot of the core host, run there over SSH (stdlib). |
| `pyproject.toml`, `uv.lock` | Dependencies (pydantic-ai-slim with anthropic and openai). |
| `config.example.json` | Template — copy to `config.json`. |
| `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` | WSL: uv, `.venv`, SSH check, `--check`, the unit; retires the core host's daemon. |
| `semprini-maintainer.service` | systemd unit template (`@USER@`, `@HOME@`, `@DIR@`). |
| `docs/architecture.md` | Architecture decision record. |
## Test without the service
```bash
.venv/bin/python maintainer.py --check # parsers, schedule, config, agent wiring, reachability
.venv/bin/python maintainer.py --check --offline # the same, no network
.venv/bin/python maintainer.py --try-model local # tool use, result faithfulness, context window
.venv/bin/python maintainer.py --once health # one health cycle + any agent work it queues
.venv/bin/python maintainer.py --once digest # post the daily report now
.venv/bin/python maintainer.py --once upgrade # run the upgrade now
```