Files
semprini-maintainer/CLAUDE.md
T
paulandCopilot 12e6fef51c Run on the core host, on Claude Sonnet 5.5 via the Anthropic API; no Ollama
The daemon moves from WSL on the workstation to the core host, where it runs
commands directly (core is the only host). One model profile, claude, with a
200k context and the existing cost caps. install.sh runs on the core host.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-26 16:59:28 +13:00

11 KiB

semprini-maintainer — Claude Instructions

What this is

A standalone, always-on autonomous maintenance agent for the semprini.me container stack. It runs on the core host it keeps, AWS Lightsail Semprini-Core (ubuntu@3.107.254.151), as the systemd service semprini-maintainer, user ubuntu, checkout ~/semprini-maintainer. It keeps the core 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 notices events, runs the stack-support agent in-process with pydantic-ai on Claude (anthropic:claude-sonnet-5.5, through the Anthropic API), and relays the agent's typed result.

Until 2026-09-26 it ran on the core host and drove Claude Code headless; from then until 2026-11-26 it ran in WSL on the operator's workstation on a local model (GLM-4.7-Flash). docs/architecture.md records why each 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, 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 the operator's workstation (Hyper-V VMs sem-k8s-1..3, sem-gw). The agent maintains the cluster from core, through the WireGuard tunnel: kubectl as elz-operator and ssh sem-k8s-N / ssh sem-gw, only while the workstation is on. Hyper-V itself is out of the agent's reach: anything about the VMs is escalated to the operator.

How it works (one screen)

  • Hosts (hosts.py, config.json → hosts): only core, which has no ssh, so it is a local host: bash runs directly on the core host. ssh (one multiplexed connection) and powershell hosts remain supported for a daemon run elsewhere. 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, claude (anthropic:claude-sonnet-5.5, context_tokens 200000 to cap what one long run re-sends per step), routed for every kind of task, with no fallback (operator's decision, 2026-11-26). Billed per token with an API key, set by --set-api-key claude; limits.cost_usd caps each run ($5, $15 for the upgrade). The mechanism stays general: a profile can be ollama:…, 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. The hold is hold.json beside the state file; --hold on the core host (as semprini-core's sync-to-host.sh runs it, 15 minutes per deploy) writes it directly. remote_hold_file is "": it remains for a daemon run elsewhere, which reads the repo host's hold 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 (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 the core host's 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 where the probe fails 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 bot's author identity in core's environment, along with GITEA_*, so pull requests are opened from core too.
  • Self-update: hourly git fetch of this checkout; a newer main is fast-forwarded, uv synced 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 ubuntu on the core host, not root; ubuntu has docker and passwordless sudo.
  • 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 a shell (or sync-to-host.sh) can 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.
  • One Matrix bot means one daemon; never run two. install.sh retires the daemon on the repo host when that host is reached over ssh; a daemon anywhere else (the WSL one, until 2026-11-26) is stopped by hand first: sudo systemctl disable --now semprini-maintainer.
  • 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. Claude resists such text better than the small local model did, but the line stays.

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 by its system python3 (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 On the core host: uv, .venv, --check, the unit; retires a daemon on an ssh repo host.
semprini-maintainer.service systemd unit template (@USER@, @HOME@, @DIR@).
docs/architecture.md Architecture decision record.

Test without the service

.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 claude  # tool use, result faithfulness
.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