2402 lines
108 KiB
Python
Executable File
2402 lines
108 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""
|
||
semprini-maintainer — autonomous stack maintenance daemon.
|
||
|
||
Event-driven where something announces itself:
|
||
|
||
* Matrix is read with a long-poll /sync. The homeserver holds the request
|
||
open and answers the moment an event lands, so a message reaches the daemon
|
||
within about a second, with no polling interval.
|
||
- Stack Maintenance room: the operator's instructions and replies.
|
||
Follow-ups resume the same agent session, so it reads like a chat.
|
||
- Stack alerts room: FIRING alerts from the Loki -> Alertmanager ->
|
||
matrix-alerts bridge start a triage run, answered in a thread.
|
||
`status`, `cancel`, `new`, `model`, `upgrade`, `hold`, `resume` and
|
||
`help` are answered by the listener at once, even while an agent run is
|
||
in progress.
|
||
|
||
* Timers cover what nothing announces:
|
||
- health (5 min): Uptime Kuma monitors confirmed down, outages that
|
||
recovered on their own, host resources (disk, memory, OOM kills,
|
||
restart loops, a stale Kuma), and host reboots
|
||
- a daily report at a fixed UTC hour
|
||
- the weekly upgrade at a fixed UTC weekday and hour
|
||
- self-update from this checkout's git remote
|
||
- the service desk (1 min): semprini-core's scripts/service-desk.py
|
||
fulfils the open requests in Semprini/service-desk. It is a script,
|
||
not an agent run; what needs a person is posted to Stack Maintenance.
|
||
|
||
All agent work runs one task at a time through the canonical stack-support
|
||
agent (semprini-core/agents/stack-support.agent.md), run in-process with
|
||
pydantic-ai (agent.py), on Claude through the Anthropic API unless
|
||
config.json names other models.
|
||
Operator messages go to the front of the queue.
|
||
|
||
The daemon runs on the core host itself, which is always on: commands run
|
||
there directly (hosts.py), probe.py reads the host's health, and the agent
|
||
edits and commits core's live checkout in place. It reaches the home
|
||
cluster through the WireGuard tunnel.
|
||
|
||
Remediation scope is whatever Uptime Kuma tracks at check time, re-read every
|
||
cycle. Changes the agent applies are committed to semprini-core `main` and
|
||
pushed, so the repo always describes what runs.
|
||
|
||
The daemon needs pydantic-ai (`uv sync`). `--hold` and `--resume` stay stdlib
|
||
only, so a deploy script on the core host can still hold it with python3.
|
||
"""
|
||
|
||
import argparse
|
||
import getpass
|
||
import hashlib
|
||
import html
|
||
import json
|
||
import os
|
||
import re
|
||
import shlex
|
||
import socket
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import traceback
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
import hosts as hostlib
|
||
|
||
HOME = os.path.expanduser("~")
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Config / state
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
CORE_HOME = "/home/ubuntu"
|
||
|
||
DEFAULTS = {
|
||
# Where commands run (hosts.py). Replaced whole by config.json, not merged.
|
||
"hosts": {
|
||
# No "ssh": the daemon runs on this host, so commands run here directly.
|
||
"core": {
|
||
"about": "the core stack host, where this daemon runs: AWS Lightsail "
|
||
"Semprini-Core, Ubuntu, user ubuntu (docker group, passwordless "
|
||
"sudo). Docker Compose runs the core stack, semprini-blog and "
|
||
"conk; Loki, Kuma and Gitea are here. GITEA_* is set for API "
|
||
"calls. kubectl (as elz-operator) and `ssh sem-k8s-1..3`, "
|
||
"`ssh sem-gw` reach the home cluster through the WireGuard tunnel "
|
||
"while the operator's workstation, which hosts it, is on",
|
||
},
|
||
},
|
||
# The host semprini-core runs from, and its checkout there.
|
||
"repo_host": "core",
|
||
"repo_dir": f"{CORE_HOME}/semprini-core",
|
||
# Other projects running on the core host. The agent may read them but
|
||
# cannot push them, so it proposes changes there instead.
|
||
"extra_dirs": [f"{CORE_HOME}/semprini-blog", f"{CORE_HOME}/conk"],
|
||
"agent_file": "agents/stack-support.agent.md",
|
||
"runbook_file": "docs/stack-support-runbook.md",
|
||
# Model profiles (agent.py). One Claude model does everything. Its api_key
|
||
# is saved with --set-api-key and re-read before every run. Replaced whole
|
||
# by config.json, not merged.
|
||
"models": {
|
||
# A history is shortened past context_tokens: 200k keeps one long run
|
||
# from re-sending (and paying for) a near-million-token prompt per step.
|
||
"claude": {"model": "anthropic:claude-sonnet-5-5", "context_tokens": 200000},
|
||
},
|
||
# Which profiles each kind of task tries, best first; a later one takes
|
||
# over when the first is unreachable or fails the run. Replaced whole.
|
||
"routing": {
|
||
"operator": ["claude"],
|
||
"alerts": ["claude"],
|
||
"health": ["claude"],
|
||
"upgrade": ["claude"],
|
||
},
|
||
# Per run. cost_usd caps metered runs by kind.
|
||
"limits": {
|
||
"request_limit": 150,
|
||
"tool_calls_limit": 300,
|
||
"cost_usd": {"default": 5, "upgrade": 15},
|
||
},
|
||
"agent_timeout_seconds": 2700,
|
||
# A hold set on another machine, read each minute over the repo host. Empty
|
||
# while the daemon runs on the core host: `--hold` there (as semprini-core's
|
||
# sync-to-host.sh runs it) writes the daemon's own hold file.
|
||
"remote_hold_file": "",
|
||
"uv_bin": f"{HOME}/.local/bin/uv",
|
||
"kuma_volume": "uptime-kuma-data",
|
||
"sqlite_image": "keinos/sqlite3",
|
||
# autonomy: "full" (fix + upgrade), "fix-only" (remediate, only report
|
||
# upgrades), or "notify" (never act, only report).
|
||
"autonomy": "full",
|
||
"health_interval_seconds": 300,
|
||
# A monitor must be seen DOWN this many consecutive cycles before we act,
|
||
# to ride out restarts / flapping.
|
||
"down_confirmations": 2,
|
||
# Weekly upgrade slot (weekday 0=Mon .. 6=Sun, UTC). Sat 22:00 UTC is
|
||
# Sunday morning in Sydney: quiet, and the operator is around to answer.
|
||
"upgrade_weekday": 5,
|
||
"upgrade_hour_utc": 22,
|
||
"digest_hour_utc": 21,
|
||
# An operator message within this long of the last exchange in the same
|
||
# room or thread resumes that Claude session instead of starting fresh.
|
||
"conversation_ttl_seconds": 14400,
|
||
# An unanswered escalation holds upgrades until it is answered or expires.
|
||
"escalation_expiry_seconds": 604800,
|
||
"self_update_interval_seconds": 3600,
|
||
"state_file": f"{HOME}/.local/state/semprini-maintainer/state.json",
|
||
"alerts": {
|
||
"sender": "@alerts:semprini.me",
|
||
# Alerts arriving within this window of each other share one run.
|
||
"batch_seconds": 60,
|
||
# A re-sent FIRING (Alertmanager repeats every 6h) is looked at again
|
||
# at most this often.
|
||
"cooldown_seconds": 43200,
|
||
# Acknowledged in the room, never investigated.
|
||
"ignore": ["PipelineTest"],
|
||
},
|
||
"host": {
|
||
"disk_warn_percent": 85,
|
||
"mem_available_min_mb": 400,
|
||
"kuma_stale_seconds": 600,
|
||
"check_cooldown_seconds": 43200,
|
||
},
|
||
# Repos the agent commits to, and the host each is on (default repo_host).
|
||
# The daemon fast-forwards them before a run and pushes anything left
|
||
# unpushed after it.
|
||
"git": {
|
||
"repos": [{"path": f"{CORE_HOME}/semprini-core", "slug": "paul/semprini-core"}],
|
||
"branch": "main",
|
||
},
|
||
# Gitea (git.semprini.me): the agent pushes as `claude-code`. Empty token
|
||
# disables pushing; commits then stay local and the daemon warns.
|
||
"gitea": {
|
||
"api_base": "https://git.semprini.me/api/v1",
|
||
"web_base": "https://git.semprini.me",
|
||
"user": "claude-code",
|
||
"repo": "paul/semprini-core",
|
||
"token": "",
|
||
"git_author_name": "Claude Code",
|
||
"git_author_email": "claude-code@semprini.me",
|
||
},
|
||
# The service desk: requests to core, as issues in Semprini/service-desk.
|
||
# semprini-core's script fulfils them on the core host (it needs the
|
||
# host's .env, docker and kubectl); the daemon starts it there over SSH so
|
||
# it takes turns with agent runs and waits out a hold. 0 turns it off.
|
||
"desk": {
|
||
"script": "core_stack/scripts/service-desk.py",
|
||
"interval_seconds": 60,
|
||
"timeout_seconds": 900,
|
||
},
|
||
"matrix": {
|
||
"homeserver": "https://matrix.semprini.me",
|
||
"user_id": "",
|
||
"access_token": "",
|
||
"room_id": "", # Stack Maintenance
|
||
"alerts_room": "#stack-alerts:semprini.me", # alias or room id
|
||
"admin_user_id": "@paul:semprini.me",
|
||
},
|
||
}
|
||
|
||
NESTED = ("alerts", "host", "git", "gitea", "desk", "matrix", "limits")
|
||
|
||
|
||
def load_config(path):
|
||
cfg = json.loads(json.dumps(DEFAULTS)) # deep copy
|
||
if path and os.path.exists(path):
|
||
with open(path) as fh:
|
||
user = json.load(fh)
|
||
for k, v in user.items():
|
||
if k in NESTED and isinstance(v, dict):
|
||
cfg[k].update(v)
|
||
else:
|
||
cfg[k] = v
|
||
cfg["_path"] = os.path.abspath(path) if path else ""
|
||
return cfg
|
||
|
||
|
||
def fresh_state():
|
||
now = time.time()
|
||
return {
|
||
"matrix_since": None, # /sync token
|
||
"outbox": [], # messages that failed to send, retried
|
||
"queue": [], # agent tasks not yet run (survives restarts)
|
||
"conversations": {}, # "room|thread" -> {session_id, updated}
|
||
"pending": None, # escalation awaiting the operator
|
||
"alerts": {}, # fingerprint -> alert record
|
||
"alert_batch": None, # {fps, last} gathering before a triage run
|
||
"down_streak": {}, # monitor name -> consecutive-down count
|
||
"last_event_check": None, # max kuma heartbeat id seen
|
||
"open_outages": {}, # monitor_id -> open DOWN window, cross-cycle
|
||
"last_health": 0,
|
||
"last_kuma": None, # {"up", "total", "at"}
|
||
"kuma_failures": 0,
|
||
# Baselines, so a first start neither upgrades nor reports at once.
|
||
"last_upgrade": now,
|
||
"last_digest": now,
|
||
"last_self_update": 0,
|
||
"host": {"restarts": {}, "oom_since": now, "cooldowns": {},
|
||
"btime": None, "snapshot": {}},
|
||
"day": {}, # tallies for the daily report
|
||
"agent_degraded": {}, # kind -> {since, failures, last_error, token, retry_after}
|
||
"last_online": {}, # {"at", "version"}
|
||
"error_notes": {}, # message -> last sent, to rate-limit errors
|
||
"hold_seen": None, # set_at of the hold already announced
|
||
"hold_expiry_seen": None, # set_at of the hold whose end was announced
|
||
"remote_hold": None, # the core host's hold.json, as last read
|
||
"core_failures": 0, # consecutive health cycles that could not reach core
|
||
"model_override": {}, # "room|thread" -> profile, from `model <profile>`
|
||
}
|
||
|
||
|
||
def load_state(cfg):
|
||
state = fresh_state()
|
||
path = cfg["state_file"]
|
||
if os.path.exists(path):
|
||
try:
|
||
with open(path) as fh:
|
||
state.update(json.load(fh))
|
||
except Exception:
|
||
log("WARN: could not parse state file, starting fresh")
|
||
for k, v in fresh_state().items(): # keys added since the file was written
|
||
state.setdefault(k, v)
|
||
# Before 2026-09-26 one record covered every kind of task.
|
||
degraded = state.get("agent_degraded")
|
||
if not isinstance(degraded, dict) or "since" in degraded:
|
||
state["agent_degraded"] = {}
|
||
state.pop("agent_retry_after", None)
|
||
return state
|
||
|
||
|
||
def save_state(cfg, state):
|
||
path = cfg["state_file"]
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
tmp = path + ".tmp"
|
||
with open(tmp, "w") as fh:
|
||
json.dump(state, fh, indent=2)
|
||
os.replace(tmp, path)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Hold — a time-boxed pause on everything the daemon starts by itself
|
||
# --------------------------------------------------------------------------- #
|
||
# Someone working on the stack (a person, a Claude Code session, a deploy) can
|
||
# stop the daemon acting for a while, without stopping the service and without
|
||
# it forgetting: a hold expires on its own, so nothing stays paused by accident.
|
||
#
|
||
# It lives in its own small file rather than in the state the daemon owns,
|
||
# because `--hold` from a shell has to reach an already-running daemon, which
|
||
# rewrites its state file whenever it pleases.
|
||
#
|
||
# There are two such files: this machine's, and the core host's
|
||
# (remote_hold_file), which `maintainer.py --hold` writes when a script on the
|
||
# host runs it from a checkout there. The daemon reads the host's each minute
|
||
# and honours whichever hold ends later.
|
||
|
||
HOLD_DEFAULT_MINUTES = 30
|
||
HOLD_MAX_MINUTES = 480
|
||
DURATION_RE = re.compile(r"^(\d+)\s*(m|min|mins|minute|minutes|h|hr|hrs|hour|hours)?$", re.I)
|
||
HOLD_RE = re.compile(r"^(?:[!/])?hold(?:\s+(\d+\s*[a-z]*))?(?:\s+(.*))?$", re.I | re.S)
|
||
|
||
|
||
def parse_duration(text):
|
||
"""Minutes from '45', '45m' or '2h'; None if it is not a duration."""
|
||
m = DURATION_RE.match((text or "").strip())
|
||
if not m:
|
||
return None
|
||
minutes = int(m.group(1)) * (60 if (m.group(2) or "m").lower().startswith("h") else 1)
|
||
return max(1, min(HOLD_MAX_MINUTES, minutes))
|
||
|
||
|
||
def parse_hold(body):
|
||
"""`hold`, `hold 45m`, `hold 2h <reason>` -> {minutes, reason}, else None.
|
||
|
||
A reason needs a duration in front of it, so an instruction that merely
|
||
starts with the word — "hold off on the upgrade" — stays a message for the
|
||
agent instead of silently pausing it.
|
||
"""
|
||
m = HOLD_RE.match((body or "").strip())
|
||
if not m:
|
||
return None
|
||
duration, rest = m.group(1), (m.group(2) or "").strip()
|
||
if duration is None:
|
||
return {"minutes": HOLD_DEFAULT_MINUTES, "reason": ""} if not rest else None
|
||
minutes = parse_duration(duration)
|
||
return None if minutes is None else {"minutes": minutes, "reason": rest}
|
||
|
||
|
||
def hold_path(cfg):
|
||
return os.path.join(os.path.dirname(cfg["state_file"]), "hold.json")
|
||
|
||
|
||
def read_hold(cfg):
|
||
"""The hold in force, or None. An expired one is removed as it is read."""
|
||
try:
|
||
with open(hold_path(cfg)) as fh:
|
||
hold = json.load(fh)
|
||
except (OSError, ValueError):
|
||
return None
|
||
if hold.get("until", 0) <= time.time():
|
||
clear_hold(cfg)
|
||
return None
|
||
return hold
|
||
|
||
|
||
def write_hold(cfg, minutes, reason, by):
|
||
hold = {"until": time.time() + minutes * 60, "minutes": minutes, "by": by,
|
||
"reason": (reason or "").strip(), "set_at": time.time()}
|
||
path = hold_path(cfg)
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
tmp = path + ".tmp"
|
||
with open(tmp, "w") as fh:
|
||
json.dump(hold, fh, indent=2)
|
||
os.replace(tmp, path)
|
||
return hold
|
||
|
||
|
||
def clear_hold(cfg):
|
||
try:
|
||
os.remove(hold_path(cfg))
|
||
return True
|
||
except OSError:
|
||
return False
|
||
|
||
|
||
def later_hold(*holds):
|
||
"""Of the holds given, the one in force that ends last, or None."""
|
||
live = [h for h in holds if h and h.get("until", 0) > time.time()]
|
||
return max(live, key=lambda h: h["until"]) if live else None
|
||
|
||
|
||
def hold_line(hold):
|
||
until = datetime.fromtimestamp(hold["until"], timezone.utc)
|
||
left = max(0, round((hold["until"] - time.time()) / 60))
|
||
reason = f" — {hold['reason']}" if hold.get("reason") else ""
|
||
return (f"until {until:%H:%M} UTC ({left} min left), set from "
|
||
f"{hold.get('by', '?')}{reason}")
|
||
|
||
|
||
def log(msg):
|
||
print(f"[{datetime.now(timezone.utc).isoformat(timespec='seconds')}] {msg}",
|
||
flush=True)
|
||
|
||
|
||
def utcnow():
|
||
return datetime.now(timezone.utc)
|
||
|
||
|
||
def ago(ts):
|
||
secs = max(0, int(time.time() - (ts or 0)))
|
||
if secs < 90:
|
||
return f"{secs}s"
|
||
if secs < 5400:
|
||
return f"{secs // 60}m"
|
||
if secs < 172800:
|
||
return f"{secs // 3600}h"
|
||
return f"{secs // 86400}d"
|
||
|
||
|
||
def bump(counts, key, n=1):
|
||
counts[key] = counts.get(key, 0) + n
|
||
|
||
|
||
def fmt_counts(counts):
|
||
return ", ".join(f"{k} ×{v}" for k, v in sorted(counts.items()))
|
||
|
||
|
||
def version():
|
||
out = subprocess.run(["git", "-C", HERE, "rev-parse", "--short", "HEAD"],
|
||
capture_output=True, text=True)
|
||
return out.stdout.strip() or "unknown"
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Uptime Kuma — up/down transitions, read by probe.py on the core host
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
KUMA_DOWN, KUMA_UP, KUMA_PENDING, KUMA_MAINT = 0, 1, 2, 3
|
||
|
||
|
||
def detect_outages(events, open_outages):
|
||
"""Pair DOWN→UP transitions into recovered outage windows. `open_outages`
|
||
carries windows still open from earlier cycles and is mutated in place."""
|
||
recovered = []
|
||
for ev in events:
|
||
mid = str(ev["monitor_id"])
|
||
if ev["status"] == KUMA_DOWN:
|
||
open_outages[mid] = {"name": ev["name"], "down_at": ev["time"],
|
||
"msg": ev.get("msg")}
|
||
elif ev["status"] == KUMA_UP:
|
||
o = open_outages.pop(mid, None)
|
||
recovered.append({
|
||
"name": ev["name"],
|
||
"down_at": (o or {}).get("down_at"), # None => began before us
|
||
"up_at": ev["time"],
|
||
"msg": (o or {}).get("msg") or ev.get("msg"),
|
||
})
|
||
return recovered
|
||
|
||
|
||
def parse_kuma_time(t):
|
||
for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"):
|
||
try:
|
||
return datetime.strptime(t, fmt).replace(tzinfo=timezone.utc)
|
||
except (ValueError, TypeError):
|
||
continue
|
||
return None
|
||
|
||
|
||
def fmt_duration(down_at, up_at):
|
||
d, u = parse_kuma_time(down_at), parse_kuma_time(up_at)
|
||
if not d or not u:
|
||
return "?"
|
||
secs = max(0, int((u - d).total_seconds()))
|
||
h, rem = divmod(secs, 3600)
|
||
m, s = divmod(rem, 60)
|
||
if h:
|
||
return f"{h}h{m:02d}m"
|
||
return f"{m}m{s:02d}s" if m else f"{s}s"
|
||
|
||
|
||
def status_label(code):
|
||
return {KUMA_DOWN: "DOWN", KUMA_UP: "UP", KUMA_PENDING: "PENDING",
|
||
KUMA_MAINT: "MAINTENANCE"}.get(code, f"?{code}")
|
||
|
||
|
||
PROBE = os.path.join(HERE, "probe.py")
|
||
|
||
|
||
def probe_core(cfg, host, event_since, oom_since):
|
||
"""One snapshot of the core host (probe.py, run there over SSH)."""
|
||
args = json.dumps({"kuma_volume": cfg["kuma_volume"], "sqlite_image": cfg["sqlite_image"],
|
||
"event_since": event_since, "oom_since": oom_since})
|
||
with open(PROBE) as fh:
|
||
script = fh.read()
|
||
out = host.check(f"python3 - {shlex.quote(args)}", timeout=180, input=script)
|
||
return json.loads(out)
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Host checks — what Kuma cannot see
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def host_check(cfg, state, snap):
|
||
"""Judge a probe snapshot and return anomalies [(key, description)].
|
||
|
||
Restart counts are compared per container id, so a recreated container
|
||
(count back to 0) is not mistaken for anything. The first call only
|
||
records a baseline."""
|
||
h = cfg["host"]
|
||
hs = state["host"]
|
||
anomalies = []
|
||
|
||
disk, mem = snap.get("disk") or {}, snap.get("mem") or {}
|
||
avail = mem.get("MemAvailable", 0)
|
||
swap_used = mem.get("SwapTotal", 0) - mem.get("SwapFree", 0)
|
||
hs["snapshot"] = {"disk_pct": disk.get("pct", 0), "disk_free_gb": disk.get("free_gb", 0),
|
||
"mem_avail_mb": avail, "swap_used_mb": swap_used,
|
||
"reboot": snap.get("reboot"), "at": snap.get("at", time.time())}
|
||
|
||
if disk and disk["pct"] >= h["disk_warn_percent"]:
|
||
anomalies.append(("disk", f"root filesystem {disk['pct']}% used "
|
||
f"({disk['free_gb']} GB free)"))
|
||
if mem and avail < h["mem_available_min_mb"]:
|
||
anomalies.append(("memory", f"only {avail} MB memory available, "
|
||
f"{swap_used} MB swap in use"))
|
||
|
||
if "ooms" in snap:
|
||
hs["oom_since"] = snap.get("at", time.time())
|
||
if snap["ooms"]:
|
||
anomalies.append(("oom", "kernel OOM kills:\n" +
|
||
"\n".join(f" {l}" for l in snap["ooms"])))
|
||
|
||
if "containers" in snap:
|
||
now = snap["containers"]
|
||
prev = hs.get("restarts") or {}
|
||
for cid, (name, count, status) in now.items():
|
||
before = prev.get(cid)
|
||
if status == "restarting" or (before and count > before[1]):
|
||
n = count - (before[1] if before else 0)
|
||
anomalies.append((f"restart:{name}",
|
||
f"container {name} is {status}, restarted "
|
||
f"{n} time(s) in the last check interval "
|
||
f"(total {count})"))
|
||
hs["restarts"] = now
|
||
|
||
kuma_latest = (snap.get("kuma") or {}).get("latest")
|
||
latest = parse_kuma_time(kuma_latest) if kuma_latest else None
|
||
if latest and (utcnow() - latest).total_seconds() > h["kuma_stale_seconds"]:
|
||
anomalies.append(("kuma-stale",
|
||
f"Uptime Kuma's newest heartbeat is from {kuma_latest} "
|
||
"UTC — it has stopped probing, so its status is stale"))
|
||
return anomalies
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Git — keep the stack host's checkout and the remote in step
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def git(host, repo, *args, timeout=90, env=None):
|
||
"""`git -C repo …` on a host. `env` (agent_git_env) applies to local
|
||
checkouts only: pushes on the core host authenticate with the host's own
|
||
credential helper for claude-code, and the token stays off the wire."""
|
||
return host.run(shlex.join(["git", "-C", repo, *args]), timeout=timeout,
|
||
env=env if host.kind == "local" else None)
|
||
|
||
|
||
def repo_host(cfg, hosts, r):
|
||
return hosts[r.get("host") or cfg["repo_host"]]
|
||
|
||
|
||
def repo_status(host, repo, branch, env=None):
|
||
"""Fetch and describe a checkout: head, branch, dirty files, ahead/behind."""
|
||
fetched = git(host, repo, "fetch", "-q", "origin", branch, env=env).returncode == 0
|
||
head = git(host, repo, "rev-parse", "HEAD").stdout.strip()
|
||
current = git(host, repo, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
|
||
dirty = [l for l in git(host, repo, "status", "--porcelain",
|
||
"--untracked-files=normal").stdout.splitlines() if l]
|
||
counts = git(host, repo, "rev-list", "--left-right", "--count",
|
||
f"HEAD...origin/{branch}").stdout.split()
|
||
ahead, behind = (int(counts[0]), int(counts[1])) if len(counts) == 2 else (0, 0)
|
||
return {"head": head, "branch": current, "dirty": dirty, "ahead": ahead,
|
||
"behind": behind, "fetched": fetched}
|
||
|
||
|
||
def repo_before(cfg, hosts, env):
|
||
"""Before a run: fast-forward clean checkouts that are behind. Returns
|
||
(context lines for the prompt, {path: head before the run})."""
|
||
branch = cfg["git"]["branch"]
|
||
lines, heads = [], {}
|
||
for r in cfg["git"]["repos"]:
|
||
path, host = r["path"], repo_host(cfg, hosts, r)
|
||
where = f"{path} on {host.name}"
|
||
try:
|
||
if not host.exists(os.path.join(path, ".git").replace("\\", "/")):
|
||
lines.append(f"- {where}: NOT a git checkout (or {host.name} is unreachable) — "
|
||
"commits are impossible; say so in your summary")
|
||
continue
|
||
s = repo_status(host, path, branch, env)
|
||
note = ""
|
||
if (s["branch"] == branch and s["behind"] and not s["ahead"]
|
||
and not s["dirty"]):
|
||
old = s["head"]
|
||
if git(host, path, "merge", "-q", "--ff-only", f"origin/{branch}").returncode == 0:
|
||
pulled = git(host, path, "log", "--oneline", f"{old}..HEAD").stdout.strip()
|
||
note = (f"; pulled {s['behind']} new commit(s) from origin — on "
|
||
"disk but possibly not applied to running containers:\n"
|
||
+ "\n".join(f" {l}" for l in pulled.splitlines()[:15]))
|
||
s = repo_status(host, path, branch, env)
|
||
desc = f"- {where}: {s['branch']} @ {s['head'][:8]}"
|
||
if s["branch"] != branch:
|
||
desc += f" (expected {branch}!)"
|
||
if s["ahead"]:
|
||
desc += f"; {s['ahead']} local commit(s) not yet pushed"
|
||
if s["behind"]:
|
||
desc += f"; {s['behind']} commit(s) behind origin, not fast-forwarded"
|
||
if not s["fetched"]:
|
||
desc += "; fetch from origin failed (Gitea down?)"
|
||
if s["dirty"]:
|
||
desc += ("; uncommitted changes present before this run:\n" +
|
||
"\n".join(f" {l}" for l in s["dirty"][:15]))
|
||
lines.append(desc + note)
|
||
heads[path] = s["head"]
|
||
except Exception as e:
|
||
lines.append(f"- {where}: git status failed: {e}")
|
||
return lines, heads
|
||
|
||
|
||
def repo_after(cfg, hosts, env, heads):
|
||
"""After a run: push anything unpushed and report what changed. Returns
|
||
lines for the operator; empty when nothing happened."""
|
||
branch = cfg["git"]["branch"]
|
||
web = cfg["gitea"].get("web_base", "").rstrip("/")
|
||
lines = []
|
||
for r in cfg["git"]["repos"]:
|
||
path, slug, host = r["path"], r.get("slug", ""), repo_host(cfg, hosts, r)
|
||
if path not in heads:
|
||
continue
|
||
name = os.path.basename(path)
|
||
try:
|
||
new = git(host, path, "log", "--format=%h %s",
|
||
f"{heads[path]}..HEAD").stdout.strip().splitlines()
|
||
s = repo_status(host, path, branch, env)
|
||
if s["ahead"] and s["branch"] == branch:
|
||
push = git(host, path, "push", "-q", "origin", branch, env=env)
|
||
if push.returncode == 0:
|
||
s["ahead"] = 0
|
||
else:
|
||
lines.append(f"⚠️ {name}: {s['ahead']} commit(s) could not be "
|
||
f"pushed — retrying later "
|
||
f"(`{push.stderr.strip()[:150]}`)")
|
||
if new:
|
||
link = f" — {web}/{slug}/commits/branch/{branch}" if web and slug else ""
|
||
lines.append(f"📝 {name}: {len(new)} commit(s) on {s['branch']}{link}\n" +
|
||
"\n".join(f" • `{c[:8]}` {c[9:]}" for c in new[:10]))
|
||
if s["dirty"]:
|
||
lines.append(f"⚠️ {name}: uncommitted changes left in the {host.name} checkout "
|
||
"(the repo no longer matches what runs):\n" +
|
||
"\n".join(f" `{l}`" for l in s["dirty"][:10]))
|
||
except Exception as e:
|
||
lines.append(f"⚠️ {name}: git check failed: {e}")
|
||
return lines
|
||
|
||
|
||
def push_pending(cfg, hosts, env):
|
||
"""Retry pushing commits a run left behind (e.g. while Gitea was down)."""
|
||
branch = cfg["git"]["branch"]
|
||
for r in cfg["git"]["repos"]:
|
||
path, host = r["path"], repo_host(cfg, hosts, r)
|
||
counts = git(host, path, "rev-list", "--count", f"origin/{branch}..{branch}").stdout.strip()
|
||
if counts.isdigit() and int(counts):
|
||
res = git(host, path, "push", "-q", "origin", branch, env=env)
|
||
log(f"retry push {path} on {host.name}: "
|
||
f"{'ok' if res.returncode == 0 else res.stderr.strip()[:200]}")
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Matrix client-server API over stdlib
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def matrix_req(cfg, method, path, body=None, params=None, timeout=60):
|
||
base = cfg["matrix"]["homeserver"].rstrip("/")
|
||
url = f"{base}{path}"
|
||
if params:
|
||
url += "?" + urllib.parse.urlencode(params)
|
||
data = json.dumps(body).encode() if body is not None else None
|
||
req = urllib.request.Request(url, data=data, method=method)
|
||
req.add_header("Authorization", f"Bearer {cfg['matrix']['access_token']}")
|
||
req.add_header("Content-Type", "application/json")
|
||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||
raw = resp.read().decode()
|
||
return json.loads(raw) if raw else {}
|
||
|
||
|
||
def q(value):
|
||
return urllib.parse.quote(value, safe="")
|
||
|
||
|
||
def md_to_html(text):
|
||
"""Small markdown -> HTML for Matrix formatted bodies: code blocks, inline
|
||
code, bold, links, headings and bullets."""
|
||
out, in_code = [], False
|
||
for line in text.split("\n"):
|
||
if line.strip().startswith("```"):
|
||
out.append("</code></pre>" if in_code else "<pre><code>")
|
||
in_code = not in_code
|
||
continue
|
||
esc = html.escape(line)
|
||
if in_code:
|
||
out.append(esc + "\n")
|
||
continue
|
||
esc = re.sub(r"`([^`]+)`", r"<code>\1</code>", esc)
|
||
esc = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", esc)
|
||
esc = re.sub(r"\[([^\]]+)\]\((https?://[^)\s]+)\)", r'<a href="\2">\1</a>', esc)
|
||
esc = re.sub(r"^#{1,4} (.*)$", r"<b>\1</b>", esc)
|
||
esc = re.sub(r"^(\s*)[-*] ", r"\1• ", esc)
|
||
out.append(esc + "<br>")
|
||
if in_code:
|
||
out.append("</code></pre>")
|
||
return "".join(out)
|
||
|
||
|
||
def message_content(text, thread_root=None, reply_to=None):
|
||
if len(text) > 30000:
|
||
text = text[:30000] + "\n\n…(truncated)"
|
||
content = {"msgtype": "m.text", "body": text,
|
||
"format": "org.matrix.custom.html",
|
||
"formatted_body": md_to_html(text)}
|
||
if thread_root:
|
||
content["m.relates_to"] = {
|
||
"rel_type": "m.thread", "event_id": thread_root,
|
||
"is_falling_back": True,
|
||
"m.in_reply_to": {"event_id": reply_to or thread_root}}
|
||
elif reply_to:
|
||
content["m.relates_to"] = {"m.in_reply_to": {"event_id": reply_to}}
|
||
return content
|
||
|
||
|
||
_txn_lock = threading.Lock()
|
||
_txn_n = [0]
|
||
|
||
|
||
def txn_id():
|
||
with _txn_lock:
|
||
_txn_n[0] += 1
|
||
return f"{int(time.time() * 1000)}.{_txn_n[0]}"
|
||
|
||
|
||
def matrix_put_event(cfg, room, event_type, content):
|
||
"""Send one event; returns its event id. Raises on failure."""
|
||
resp = matrix_req(cfg, "PUT", f"/_matrix/client/v3/rooms/{q(room)}/send/"
|
||
f"{event_type}/{txn_id()}", body=content)
|
||
return resp.get("event_id")
|
||
|
||
|
||
def matrix_typing(cfg, room, on):
|
||
try:
|
||
matrix_req(cfg, "PUT", f"/_matrix/client/v3/rooms/{q(room)}/typing/"
|
||
f"{q(cfg['matrix']['user_id'])}",
|
||
body={"typing": on, "timeout": 30000} if on else {"typing": False},
|
||
timeout=15)
|
||
except Exception:
|
||
pass # cosmetic
|
||
|
||
|
||
def matrix_ack(cfg, room, event_id, reaction=None):
|
||
"""Mark an event read and, optionally, react to it — the operator's cue
|
||
that the message arrived."""
|
||
try:
|
||
matrix_req(cfg, "POST", f"/_matrix/client/v3/rooms/{q(room)}/receipt/"
|
||
f"m.read/{q(event_id)}", body={}, timeout=15)
|
||
if reaction:
|
||
matrix_put_event(cfg, room, "m.reaction", {"m.relates_to": {
|
||
"rel_type": "m.annotation", "event_id": event_id,
|
||
"key": reaction}})
|
||
except Exception as e:
|
||
log(f"WARN: ack failed: {e}")
|
||
|
||
|
||
def resolve_room(cfg, room):
|
||
"""Room id for an alias (#name:server) or id (!id:server)."""
|
||
if not room or room.startswith("!"):
|
||
return room
|
||
resp = matrix_req(cfg, "GET", f"/_matrix/client/v3/directory/room/{q(room)}")
|
||
return resp["room_id"]
|
||
|
||
|
||
def ensure_joined(cfg, rooms):
|
||
joined = set(matrix_req(cfg, "GET", "/_matrix/client/v3/joined_rooms")
|
||
.get("joined_rooms", []))
|
||
for room in rooms:
|
||
if room and room not in joined:
|
||
try:
|
||
matrix_req(cfg, "POST", f"/_matrix/client/v3/join/{q(room)}", body={})
|
||
log(f"joined {room}")
|
||
except Exception as e:
|
||
log(f"WARN: cannot join {room} (invite the bot): {e}")
|
||
|
||
|
||
def sync_filter(rooms, initial=False):
|
||
return json.dumps({
|
||
"presence": {"types": []},
|
||
"account_data": {"types": []},
|
||
"room": {
|
||
"rooms": rooms,
|
||
"timeline": {"limit": 0 if initial else 50,
|
||
"types": ["m.room.message", "m.room.encrypted"]},
|
||
"state": {"types": []},
|
||
"ephemeral": {"types": []},
|
||
"account_data": {"types": []},
|
||
},
|
||
})
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# Message parsing — alerts from the bridge, commands from the operator
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
# As rendered by core_stack/matrix-alerts/config.yml, e.g.
|
||
# **FIRING LogErrorBurst** · service `user-test`
|
||
# user-test is logging errors: 42 in the last 5 minutes
|
||
# LogQL: `{service="user-test", level=~"error|fatal"}`
|
||
# since 2026-09-15 06:53:53 UTC · fingerprint `34d3f155ae58b655`
|
||
ALERT_RE = re.compile(
|
||
r"\*\*(FIRING|RESOLVED) ([^*\s]+)\*\*"
|
||
r"(?: · service `([^`]+)`)?(?: · router `([^`]+)`)?")
|
||
FINGERPRINT_RE = re.compile(r"fingerprint `([0-9a-f]+)`")
|
||
|
||
|
||
def parse_alert(body):
|
||
m = ALERT_RE.search(body or "")
|
||
fp = FINGERPRINT_RE.search(body or "")
|
||
if not m or not fp:
|
||
return None
|
||
return {"state": m.group(1), "name": m.group(2), "service": m.group(3),
|
||
"router": m.group(4), "fingerprint": fp.group(1), "text": body.strip()}
|
||
|
||
|
||
COMMANDS = {"status": "status", "cancel": "cancel", "stop": "cancel",
|
||
"new": "new", "upgrade": "upgrade", "help": "help",
|
||
"resume": "resume"}
|
||
|
||
|
||
def parse_command(body):
|
||
word = (body or "").strip().lower().lstrip("!/").rstrip("?!. ")
|
||
return COMMANDS.get(word)
|
||
|
||
|
||
MODEL_RE = re.compile(r"^[!/]?models?(?:\s+([a-z0-9][\w.-]*))?[?!. ]*$", re.I)
|
||
|
||
|
||
def parse_model(body):
|
||
"""`model` -> {"profile": None} (show), `model local` -> {"profile": "local"},
|
||
`model auto` -> {"profile": "auto"}; anything longer is a message."""
|
||
m = MODEL_RE.match((body or "").strip())
|
||
return {"profile": m.group(1).lower() if m.group(1) else None} if m else None
|
||
|
||
|
||
def thread_root_of(content):
|
||
rel = content.get("m.relates_to") or {}
|
||
return rel.get("event_id") if rel.get("rel_type") == "m.thread" else None
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# The agent's credentials and environment (the agent itself is agent.py)
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def agent_git_env(cfg):
|
||
"""Environment for the agent's commands on this machine: the Gitea API
|
||
variables its pull requests use, and git as claude-code.
|
||
|
||
git.semprini.me has password login and HTTP basic auth disabled but accepts
|
||
a personal access token as the git-over-HTTPS password and as the API
|
||
`Authorization: token` header. We materialise a 0600 credential store and
|
||
inject, at highest precedence (GIT_CONFIG_*, which overrides the repo's own
|
||
user.* config), the bot identity and a credential helper scoped to the
|
||
Gitea host. Returns {} when no token is provisioned.
|
||
|
||
On the core host none of this is needed: its git is configured for
|
||
claude-code already (bot_identity sets the author there).
|
||
"""
|
||
gt = cfg.get("gitea", {})
|
||
token = gt.get("token", "")
|
||
if not token or token.startswith("FILLED_BY_"):
|
||
return {}
|
||
|
||
state_dir = os.path.dirname(cfg["state_file"])
|
||
os.makedirs(state_dir, exist_ok=True)
|
||
cred_file = os.path.join(state_dir, "git-credentials")
|
||
|
||
web = gt.get("web_base", "https://git.semprini.me").rstrip("/")
|
||
parts = urllib.parse.urlsplit(web)
|
||
user = gt.get("user", "claude-code")
|
||
line = (f"{parts.scheme}://{urllib.parse.quote(user)}:"
|
||
f"{urllib.parse.quote(token)}@{parts.netloc}\n")
|
||
fd = os.open(cred_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||
with os.fdopen(fd, "w") as fh:
|
||
fh.write(line)
|
||
|
||
return {
|
||
"GIT_CONFIG_COUNT": "4",
|
||
"GIT_CONFIG_KEY_0": "user.name",
|
||
"GIT_CONFIG_VALUE_0": gt.get("git_author_name", "Claude Code"),
|
||
"GIT_CONFIG_KEY_1": "user.email",
|
||
"GIT_CONFIG_VALUE_1": gt.get("git_author_email", f"{user}@semprini.me"),
|
||
"GIT_CONFIG_KEY_2": f"credential.{web}.helper",
|
||
"GIT_CONFIG_VALUE_2": f"store --file={cred_file}",
|
||
"GIT_CONFIG_KEY_3": f"credential.{web}.username",
|
||
"GIT_CONFIG_VALUE_3": user,
|
||
"GITEA_API": gt.get("api_base", web + "/api/v1"),
|
||
"GITEA_WEB": web,
|
||
"GITEA_REPO": gt.get("repo", ""),
|
||
"GITEA_USER": user,
|
||
"GITEA_TOKEN": token,
|
||
}
|
||
|
||
|
||
def bot_identity(cfg):
|
||
"""Commits the agent makes on the core host are authored as the bot."""
|
||
gt = cfg.get("gitea", {})
|
||
name = gt.get("git_author_name", "Claude Code")
|
||
email = gt.get("git_author_email", "claude-code@semprini.me")
|
||
return {"GIT_AUTHOR_NAME": name, "GIT_AUTHOR_EMAIL": email,
|
||
"GIT_COMMITTER_NAME": name, "GIT_COMMITTER_EMAIL": email}
|
||
|
||
|
||
def load_hosts(cfg):
|
||
hosts = hostlib.load_hosts(cfg)
|
||
core = hosts.get(cfg["repo_host"])
|
||
if core is not None and core.kind != "powershell":
|
||
core.env = {**bot_identity(cfg), **core.env}
|
||
return hosts
|
||
|
||
|
||
# Wait between attempts while no model can run, so a revoked key or a stopped
|
||
# Ollama does not mean a doomed run on every task.
|
||
AGENT_BACKOFF_BASE = 60
|
||
AGENT_BACKOFF_MAX = 900
|
||
|
||
AUTH_ERROR_RE = re.compile(
|
||
r"api[ _-]?key|authentication|unauthori[sz]ed|\b401\b|\b403\b|credit balance|"
|
||
r"permission", re.I)
|
||
|
||
|
||
def current_keys(cfg):
|
||
"""Each model profile's API key, re-read from disk so a key saved by
|
||
--set-api-key applies to the running daemon."""
|
||
try:
|
||
with open(cfg["_path"]) as fh:
|
||
models = json.load(fh).get("models") or {}
|
||
except Exception:
|
||
models = cfg.get("models") or {}
|
||
return {name: m.get("api_key", "") for name, m in models.items() if m.get("api_key")}
|
||
|
||
|
||
def keys_tag(keys):
|
||
return hashlib.sha256(json.dumps(keys, sort_keys=True).encode()).hexdigest()[:8]
|
||
|
||
|
||
def agentlib():
|
||
"""agent.py, imported on first use: it needs pydantic-ai, which --hold
|
||
and --resume must not."""
|
||
import agent
|
||
return agent
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# The daemon
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
PRIORITY = {"operator": 0, "alerts": 1, "health": 2, "upgrade": 3}
|
||
KIND_NAMES = {"operator": "your messages", "alerts": "alert triage",
|
||
"health": "health check findings", "upgrade": "the weekly upgrade"}
|
||
|
||
HELP_TEXT = """🤖 **Stack maintainer**
|
||
Write to me in plain language and I act on it. A follow-up within a few hours continues the same conversation, like a chat. Alerts in *Stack alerts* are triaged automatically and answered in a thread; reply there to discuss one.
|
||
|
||
**Commands**
|
||
- `status` — what I am doing, the queue, host and health
|
||
- `cancel` — stop the agent run in progress
|
||
- `hold 45m <why>` — stand down for a while (`hold` alone is 30 min, 8h is the most). Your messages still run and alerts still collect; health checks, triage and upgrades wait
|
||
- `resume` — end a hold now
|
||
- `new` — forget this room's conversation
|
||
- `model` — the model I run on; with more than one configured, `model <name>` picks one for your messages in this room and `model auto` goes back to the default
|
||
- `upgrade` — run the weekly upgrade now
|
||
- `help` — this message"""
|
||
|
||
|
||
def conv_key(room, thread=None):
|
||
return f"{room}|{thread or ''}"
|
||
|
||
|
||
def task_label(task):
|
||
kind = task["kind"]
|
||
if kind == "operator":
|
||
return "your message: " + task["body"][:60]
|
||
if kind == "alerts":
|
||
return f"triage of {len(task['fps'])} alert(s)"
|
||
if kind == "health":
|
||
return "health check findings"
|
||
return "weekly upgrade"
|
||
|
||
|
||
class Maintainer:
|
||
def __init__(self, cfg, state):
|
||
self.cfg = cfg
|
||
self.state = state
|
||
self.lock = threading.RLock()
|
||
self.wake = threading.Event()
|
||
self.current = None # {"label", "started", "handle"}
|
||
self.started = time.time()
|
||
self.version = version()
|
||
m = cfg["matrix"]
|
||
self.matrix_ok = bool(m.get("access_token") and m.get("room_id"))
|
||
self.maint_room = m.get("room_id")
|
||
self.alerts_room = None
|
||
self.hosts = load_hosts(cfg)
|
||
self.core = self.hosts[cfg["repo_host"]]
|
||
self.local = hostlib.Host("local", {}, os.path.dirname(cfg["state_file"]))
|
||
|
||
# -- state -------------------------------------------------------------- #
|
||
|
||
def save(self):
|
||
with self.lock:
|
||
save_state(self.cfg, self.state)
|
||
|
||
def day(self):
|
||
return self.state.setdefault("day", {})
|
||
|
||
# -- Matrix output ------------------------------------------------------ #
|
||
|
||
def send(self, text, room=None, thread_root=None, reply_to=None):
|
||
room = room or self.maint_room
|
||
if not self.matrix_ok:
|
||
log(f"MATRIX (not configured) >> {text}")
|
||
return None
|
||
content = message_content(text, thread_root, reply_to)
|
||
try:
|
||
return matrix_put_event(self.cfg, room, "m.room.message", content)
|
||
except Exception as e:
|
||
log(f"ERROR sending to Matrix, kept for retry: {e}")
|
||
with self.lock:
|
||
outbox = self.state.setdefault("outbox", [])
|
||
outbox.append({"room": room, "content": content})
|
||
del outbox[:-50]
|
||
self.save()
|
||
return None
|
||
|
||
def flush_outbox(self):
|
||
with self.lock:
|
||
outbox, self.state["outbox"] = self.state.get("outbox") or [], []
|
||
failed = []
|
||
for item in outbox:
|
||
try:
|
||
matrix_put_event(self.cfg, item["room"], "m.room.message", item["content"])
|
||
except Exception:
|
||
failed.append(item)
|
||
with self.lock:
|
||
self.state["outbox"] = failed + self.state["outbox"]
|
||
self.save()
|
||
|
||
def note_error(self, text):
|
||
"""Tell the operator about a daemon fault, at most hourly per message."""
|
||
with self.lock:
|
||
notes = self.state.setdefault("error_notes", {})
|
||
key, now = text[:120], time.time()
|
||
if now - notes.get(key, 0) < 3600:
|
||
return
|
||
notes[key] = now
|
||
for k in [k for k, v in notes.items() if now - v > 86400]:
|
||
del notes[k]
|
||
self.send(f"⛔ **maintainer error**: `{text[:400]}`")
|
||
|
||
# -- Matrix input: long-poll listener thread ---------------------------- #
|
||
|
||
def listen(self):
|
||
rooms = [r for r in (self.maint_room, self.alerts_room) if r]
|
||
backoff = 5
|
||
while True:
|
||
try:
|
||
with self.lock:
|
||
since = self.state.get("matrix_since")
|
||
if since:
|
||
# The homeserver holds this open until an event arrives
|
||
# (or 30s pass), so new messages are handled immediately.
|
||
resp = matrix_req(self.cfg, "GET", "/_matrix/client/v3/sync",
|
||
params={"since": since, "timeout": "30000",
|
||
"filter": sync_filter(rooms)},
|
||
timeout=90)
|
||
joined = resp.get("rooms", {}).get("join", {})
|
||
for room_id, room in joined.items():
|
||
timeline = room.get("timeline", {})
|
||
if timeline.get("limited"):
|
||
log(f"WARN: sync gap in {room_id}; older events skipped")
|
||
for ev in timeline.get("events", []):
|
||
try:
|
||
self.on_event(room_id, ev)
|
||
except Exception:
|
||
log("ERROR handling event:\n" + traceback.format_exc())
|
||
invited = resp.get("rooms", {}).get("invite", {})
|
||
if any(r in rooms for r in invited):
|
||
ensure_joined(self.cfg, [r for r in invited if r in rooms])
|
||
else:
|
||
# First start: take a position without replaying history.
|
||
resp = matrix_req(self.cfg, "GET", "/_matrix/client/v3/sync",
|
||
params={"timeout": "0",
|
||
"filter": sync_filter(rooms, initial=True)})
|
||
with self.lock:
|
||
self.state["matrix_since"] = resp.get("next_batch", since)
|
||
self.save()
|
||
if self.state.get("outbox"):
|
||
self.flush_outbox()
|
||
backoff = 5
|
||
except Exception as e:
|
||
log(f"WARN: Matrix sync failed: {e} — retrying in {backoff}s")
|
||
time.sleep(backoff)
|
||
backoff = min(120, backoff * 2)
|
||
|
||
def on_event(self, room, ev):
|
||
m = self.cfg["matrix"]
|
||
sender, content = ev.get("sender"), ev.get("content") or {}
|
||
if sender == m["user_id"]:
|
||
return
|
||
if (content.get("m.relates_to") or {}).get("rel_type") == "m.replace":
|
||
return # an edit of an earlier message
|
||
if room == self.alerts_room and sender == self.cfg["alerts"]["sender"]:
|
||
alert = parse_alert(content.get("body", ""))
|
||
if alert:
|
||
self.on_alert(alert, ev["event_id"])
|
||
return
|
||
if sender != m["admin_user_id"]:
|
||
return
|
||
if ev.get("type") == "m.room.encrypted":
|
||
self.send("⚠️ I received an encrypted message and cannot read it. "
|
||
"This room must stay unencrypted.", room=room)
|
||
return
|
||
if content.get("msgtype") not in ("m.text", "m.notice"):
|
||
return
|
||
body = content.get("body", "").strip()
|
||
if body.startswith("> <@"): # reply fallback: drop the quoted part
|
||
body = body.split("\n\n", 1)[1].strip() if "\n\n" in body else ""
|
||
if not body:
|
||
return
|
||
thread = thread_root_of(content)
|
||
held = parse_hold(body)
|
||
if held:
|
||
matrix_ack(self.cfg, room, ev["event_id"])
|
||
self.on_hold(held, room, thread, ev["event_id"])
|
||
return
|
||
cmd = parse_command(body)
|
||
if cmd:
|
||
matrix_ack(self.cfg, room, ev["event_id"])
|
||
self.on_command(cmd, room, thread, ev["event_id"])
|
||
return
|
||
pick = parse_model(body)
|
||
if pick:
|
||
matrix_ack(self.cfg, room, ev["event_id"])
|
||
self.on_model(pick["profile"], room, thread, ev["event_id"])
|
||
return
|
||
log(f"operator message in {room}: {body[:120]!r}")
|
||
matrix_ack(self.cfg, room, ev["event_id"], reaction="👀")
|
||
busy = self.current
|
||
self.enqueue({"kind": "operator", "room": room, "thread": thread,
|
||
"event_id": ev["event_id"], "body": body})
|
||
if busy:
|
||
self.send(f"Queued behind *{busy['label']}* ({ago(busy['started'])} in). "
|
||
"`cancel` stops that run.",
|
||
room=room, thread_root=thread, reply_to=ev["event_id"])
|
||
|
||
def on_alert(self, alert, event_id):
|
||
acfg, fp, now = self.cfg["alerts"], alert["fingerprint"], time.time()
|
||
with self.lock:
|
||
alerts = self.state.setdefault("alerts", {})
|
||
rec = alerts.setdefault(fp, {"name": alert["name"],
|
||
"service": alert["service"],
|
||
"router": alert["router"],
|
||
"first_seen": now, "fired": 0})
|
||
if alert["state"] == "RESOLVED":
|
||
rec.update(status="resolved", resolved_at=now)
|
||
self.save()
|
||
log(f"alert resolved: {alert['name']} {fp}")
|
||
return
|
||
rec.update(status="firing", last_fired=now, text=alert["text"],
|
||
event_id=event_id)
|
||
rec["fired"] += 1
|
||
bump(self.day().setdefault("alerts", {}), alert["name"])
|
||
ignored = alert["name"] in acfg["ignore"]
|
||
cooling = now - (rec.get("investigated_at") or 0) < acfg["cooldown_seconds"]
|
||
if not ignored and not cooling:
|
||
batch = self.state.get("alert_batch") or {"fps": [], "last": now}
|
||
if fp not in batch["fps"]:
|
||
batch["fps"].append(fp)
|
||
batch["last"] = now
|
||
self.state["alert_batch"] = batch
|
||
for k in [k for k, v in alerts.items()
|
||
if now - v.get("last_fired", v["first_seen"]) > 7 * 86400]:
|
||
del alerts[k]
|
||
self.save()
|
||
matrix_ack(self.cfg, self.alerts_room, event_id)
|
||
if ignored:
|
||
self.send(f"Test alert **{alert['name']}** received: the path from "
|
||
"Alertmanager to the maintainer works. Not investigated.",
|
||
room=self.alerts_room, thread_root=event_id)
|
||
elif cooling:
|
||
log(f"alert {alert['name']} {fp} re-fired; investigated "
|
||
f"{ago(rec['investigated_at'])} ago, cooling down")
|
||
else:
|
||
log(f"alert {alert['name']} {fp} batched for triage")
|
||
self.wake.set()
|
||
|
||
def on_command(self, cmd, room, thread, event_id):
|
||
cur = self.current
|
||
if cmd == "help":
|
||
text = HELP_TEXT
|
||
elif cmd == "status":
|
||
text = self.status_text()
|
||
elif cmd == "cancel":
|
||
if cur:
|
||
threading.Thread(target=cur["handle"].cancel, daemon=True).start()
|
||
text = f"Cancelling *{cur['label']}*."
|
||
else:
|
||
text = "Nothing is running."
|
||
elif cmd == "resume":
|
||
if self.hold():
|
||
clear_hold(self.cfg)
|
||
self.clear_remote_hold()
|
||
with self.lock:
|
||
self.state["hold_expiry_seen"] = self.state.get("hold_seen")
|
||
self.save()
|
||
text = ("▶️ Hold cleared; I act on my own again. Anything that came up "
|
||
"meanwhile is picked up at the next check.")
|
||
else:
|
||
text = "Nothing is on hold."
|
||
elif cmd == "new":
|
||
with self.lock:
|
||
self.state["conversations"].pop(conv_key(room, thread), None)
|
||
self.save()
|
||
text = "Starting fresh: my next reply here won't carry the earlier conversation."
|
||
else: # upgrade
|
||
queued = self.enqueue({"kind": "upgrade", "manual": True})
|
||
text = "Upgrade queued." if queued else "An upgrade is already queued."
|
||
if cur:
|
||
text += f" It runs after *{cur['label']}*."
|
||
self.send(text, room=room, thread_root=thread, reply_to=event_id)
|
||
|
||
# -- hold --------------------------------------------------------------- #
|
||
|
||
def hold(self):
|
||
"""The hold in force: this machine's, or the core host's as last read,
|
||
whichever ends later."""
|
||
return later_hold(read_hold(self.cfg), self.state.get("remote_hold"))
|
||
|
||
def refresh_remote_hold(self):
|
||
"""Read the hold a shell on the core host set (sync-to-host.sh does on
|
||
every deploy). An unreachable host keeps the last reading."""
|
||
path = self.cfg.get("remote_hold_file")
|
||
if not path:
|
||
return
|
||
res = self.core.run(f"cat {shlex.quote(path)} 2>/dev/null || true", timeout=60)
|
||
if res.returncode != 0:
|
||
return
|
||
try:
|
||
hold = json.loads(res.stdout) if res.stdout.strip() else None
|
||
except ValueError:
|
||
hold = None
|
||
if hold and hold.get("until", 0) > time.time():
|
||
hold["by"] = f"{hold.get('by', '?')} on {self.core.name}"
|
||
else:
|
||
hold = None
|
||
with self.lock:
|
||
self.state["remote_hold"] = hold
|
||
|
||
def clear_remote_hold(self):
|
||
path = self.cfg.get("remote_hold_file")
|
||
with self.lock:
|
||
had = self.state.get("remote_hold")
|
||
self.state["remote_hold"] = None
|
||
if path and had:
|
||
self.core.run(f"rm -f {shlex.quote(path)}", timeout=60)
|
||
|
||
def on_model(self, profile, room, thread, event_id):
|
||
key = conv_key(room, thread)
|
||
models = self.cfg["models"]
|
||
with self.lock:
|
||
overrides = self.state.setdefault("model_override", {})
|
||
if profile is None:
|
||
pinned = overrides.get(key)
|
||
text = "\n".join(
|
||
["🧠 **Models**"] +
|
||
[f"- `{n}`: {m['model']}" for n, m in models.items()] +
|
||
["**Tried in order:** " + "; ".join(
|
||
f"{kind} {' → '.join(chain)}" for kind, chain in self.cfg["routing"].items())] +
|
||
[f"**Your messages here:** `{pinned}` first (`model auto` undoes it)" if pinned
|
||
else "**Your messages here:** the default order"])
|
||
elif profile == "auto":
|
||
overrides.pop(key, None)
|
||
text = ("Your messages here follow the default order again: "
|
||
+ " → ".join(self.cfg["routing"].get("operator") or []) + ".")
|
||
elif profile not in models:
|
||
text = f"No model profile `{profile}`. There are: " + ", ".join(f"`{n}`" for n in models)
|
||
else:
|
||
overrides[key] = profile
|
||
text = (f"Your messages here now go to `{profile}` ({models[profile]['model']}) "
|
||
"first. `model auto` goes back to the default.")
|
||
self.save()
|
||
self.send(text, room=room, thread_root=thread, reply_to=event_id)
|
||
|
||
def on_hold(self, req, room, thread, event_id):
|
||
hold = write_hold(self.cfg, req["minutes"], req["reason"], "matrix")
|
||
with self.lock:
|
||
self.state["hold_seen"] = hold["set_at"]
|
||
self.state["hold_expiry_seen"] = None
|
||
self.save()
|
||
text = (f"⏸️ Standing down {hold_line(hold)}.\n"
|
||
"Your messages still run and alerts still collect; health checks, "
|
||
"triage and upgrades wait. `resume` ends it early.")
|
||
cur = self.current
|
||
if cur:
|
||
text += f"\n\n*{cur['label']}* is already running — `cancel` stops it."
|
||
self.send(text, room=room, thread_root=thread, reply_to=event_id)
|
||
|
||
def announce_hold(self):
|
||
"""Say once when a hold begins, and once when it runs out."""
|
||
s, hold = self.state, self.hold()
|
||
if hold and s.get("hold_seen") != hold["set_at"]:
|
||
s["hold_seen"] = hold["set_at"]
|
||
s["hold_expiry_seen"] = None
|
||
self.send(f"⏸️ Standing down {hold_line(hold)}.\n"
|
||
"Your messages still run and alerts still collect; health checks, "
|
||
"triage and upgrades wait. `resume` ends it early.")
|
||
elif not hold and s.get("hold_seen") and s.get("hold_expiry_seen") != s["hold_seen"]:
|
||
s["hold_expiry_seen"] = s["hold_seen"]
|
||
self.send("▶️ Hold over; I act on my own again.")
|
||
|
||
# -- queue -------------------------------------------------------------- #
|
||
|
||
def enqueue(self, task):
|
||
task.setdefault("created", time.time())
|
||
with self.lock:
|
||
queue = self.state.setdefault("queue", [])
|
||
if task["kind"] in ("health", "upgrade") and any(
|
||
t["kind"] == task["kind"] for t in queue):
|
||
return False
|
||
queue.append(task)
|
||
self.save()
|
||
self.wake.set()
|
||
return True
|
||
|
||
def runnable(self):
|
||
"""Queued tasks that may run now. A hold stops what the daemon starts
|
||
by itself (the operator's own messages are why they would be talking
|
||
to it); a kind of task no model could run waits out its back-off,
|
||
unless a key has changed since."""
|
||
with self.lock:
|
||
queue = self.state.get("queue") or []
|
||
if not queue:
|
||
return []
|
||
degraded = self.state.get("agent_degraded") or {}
|
||
tag = keys_tag(current_keys(self.cfg)) if degraded else None
|
||
now, held = time.time(), self.hold()
|
||
|
||
def waiting(t):
|
||
d = degraded.get(t["kind"])
|
||
return bool(d) and d.get("retry_after", 0) > now and d.get("token") == tag
|
||
|
||
return [t for t in queue
|
||
if not (held and t["kind"] != "operator") and not waiting(t)]
|
||
|
||
def next_task(self):
|
||
with self.lock:
|
||
runnable = self.runnable()
|
||
if not runnable:
|
||
return None
|
||
queue = self.state["queue"]
|
||
task = min(runnable, key=lambda t: (PRIORITY[t["kind"]], t["created"]))
|
||
queue.remove(task)
|
||
self.save()
|
||
return task
|
||
|
||
def promote_alert_batch(self):
|
||
if self.hold():
|
||
return # keep gathering; one triage run covers the whole hold
|
||
with self.lock:
|
||
batch = self.state.get("alert_batch")
|
||
if not batch or time.time() - batch["last"] < self.cfg["alerts"]["batch_seconds"]:
|
||
return
|
||
self.state["alert_batch"] = None
|
||
self.enqueue({"kind": "alerts", "fps": batch["fps"]})
|
||
|
||
# -- agent availability ------------------------------------------------- #
|
||
|
||
def agent_down(self, exc, what, kind):
|
||
"""No model could run a task of this kind. Only this kind backs off:
|
||
another kind routed to a model that works carries on."""
|
||
with self.lock:
|
||
degraded = self.state.setdefault("agent_degraded", {})
|
||
first = kind not in degraded
|
||
d = degraded.setdefault(kind, {"since": time.time(), "failures": 0})
|
||
d["failures"] += 1
|
||
d["last_error"] = str(exc)[:500]
|
||
d["token"] = keys_tag(current_keys(self.cfg))
|
||
delay = min(AGENT_BACKOFF_MAX, AGENT_BACKOFF_BASE * 2 ** (d["failures"] - 1))
|
||
d["retry_after"] = time.time() + delay
|
||
queued = sum(1 for t in self.state.get("queue") or [] if t["kind"] == kind)
|
||
self.save()
|
||
log(f"WARN: agent unavailable for {kind} during {what}: {exc} — retry in {int(delay)}s")
|
||
if not first:
|
||
return
|
||
chain = " → ".join(self.cfg["routing"].get(kind) or []) or "none"
|
||
msg = (f"⛔ **maintainer degraded** — no model can run {KIND_NAMES[kind]} "
|
||
f"(tried {chain}), so they wait. Other work carries on if its models can "
|
||
f"run it.\nFailed during {what}: `{str(exc)[:300]}`")
|
||
if AUTH_ERROR_RE.search(str(exc)):
|
||
msg += ("\n\nThis is a model credential problem, not a stack fault. Create an "
|
||
"API key in the provider's console, then on the core host run "
|
||
f"`{HERE}/maintainer.py --set-api-key <profile>`. The next run picks it up.")
|
||
elif re.search(r"connect|timed? ?out|overloaded|529", str(exc), re.I):
|
||
msg += ("\n\nThe model provider looks unreachable or overloaded: check its status "
|
||
"page and this host's outbound network.")
|
||
if queued:
|
||
msg += f"\n\n{queued} task(s) are queued and will run once this clears."
|
||
msg += "\n\n_Retrying automatically; quiet until it recovers._"
|
||
self.send(msg)
|
||
|
||
def agent_up(self, kind):
|
||
with self.lock:
|
||
d = (self.state.get("agent_degraded") or {}).pop(kind, None)
|
||
if d:
|
||
self.send(f"✅ **maintainer recovered** — a model can run {KIND_NAMES[kind]} again, "
|
||
f"after {ago(d.get('since'))} and {d['failures']} failed attempt(s).")
|
||
|
||
# -- status ------------------------------------------------------------- #
|
||
|
||
def status_text(self):
|
||
s, cur = self.state, self.current
|
||
lines = [f"🤖 **Maintainer status** — {socket.gethostname()}, version "
|
||
f"`{self.version}`, up {ago(self.started)}"]
|
||
lines.append(f"**Now:** {cur['label']} ({ago(cur['started'])})" if cur
|
||
else "**Now:** idle")
|
||
lines.append("**Models:** " + "; ".join(
|
||
f"{kind} {' → '.join(chain)}" for kind, chain in self.cfg["routing"].items()))
|
||
if s.get("core_failures"):
|
||
lines.append(f"⚠️ **{self.core.name} unreachable** for the last "
|
||
f"{s['core_failures']} health check(s)")
|
||
hold = self.hold()
|
||
if hold:
|
||
lines.append(f"⏸️ **On hold** {hold_line(hold)}. `resume` ends it.")
|
||
with self.lock:
|
||
queue = sorted(s.get("queue") or [],
|
||
key=lambda t: (PRIORITY[t["kind"]], t["created"]))
|
||
batch = s.get("alert_batch")
|
||
if queue:
|
||
lines.append("**Queued:** " + "; ".join(task_label(t) for t in queue))
|
||
if batch:
|
||
lines.append(f"**Alerts gathering for triage:** {len(batch['fps'])}")
|
||
for kind, d in (s.get("agent_degraded") or {}).items():
|
||
lines.append(f"⛔ **No model can run {KIND_NAMES[kind]}** for {ago(d['since'])}: "
|
||
f"`{d['last_error'][:200]}`")
|
||
k = s.get("last_kuma")
|
||
if k:
|
||
lines.append(f"**Health:** {k['up']}/{k['total']} Kuma monitors up, "
|
||
f"checked {ago(k['at'])} ago")
|
||
snap = s["host"].get("snapshot") or {}
|
||
if snap:
|
||
lines.append(f"**Host:** disk {snap['disk_pct']}% used, "
|
||
f"{snap['mem_avail_mb']} MB memory available"
|
||
+ (", reboot pending" if snap.get("reboot") is not None else ""))
|
||
p = s.get("pending")
|
||
if p:
|
||
lines.append(f"❓ **Awaiting your decision** ({ago(p['asked_at'])}): "
|
||
f"{p['question']}")
|
||
lines.append(f"**Next upgrade:** {self.next_upgrade():%a %d %b %H:%M} UTC")
|
||
return "\n".join(lines)
|
||
|
||
# -- timers ------------------------------------------------------------- #
|
||
|
||
def next_upgrade(self):
|
||
last = last_weekly_slot(utcnow(), self.cfg["upgrade_weekday"],
|
||
self.cfg["upgrade_hour_utc"])
|
||
done = self.state.get("last_upgrade", 0) >= last.timestamp()
|
||
return last + timedelta(days=7) if done else last
|
||
|
||
def timers(self):
|
||
cfg, s, now = self.cfg, self.state, time.time()
|
||
if now - s.get("last_remote_hold", 0) >= 60:
|
||
s["last_remote_hold"] = now
|
||
self.refresh_remote_hold()
|
||
self.announce_hold()
|
||
if now - s.get("last_health", 0) >= cfg["health_interval_seconds"]:
|
||
s["last_health"] = now
|
||
self.health_cycle()
|
||
if (cfg["desk"]["interval_seconds"] and not self.hold()
|
||
and now - s.get("last_desk", 0) >= cfg["desk"]["interval_seconds"]):
|
||
s["last_desk"] = now
|
||
self.desk_poll()
|
||
if s.get("last_digest", 0) < last_daily_slot(utcnow(), cfg["digest_hour_utc"]).timestamp():
|
||
s["last_digest"] = now
|
||
self.digest()
|
||
pending = s.get("pending")
|
||
if pending and now - pending["asked_at"] > cfg["escalation_expiry_seconds"]:
|
||
s["pending"] = None
|
||
self.send(f"❔ No answer in {ago(pending['asked_at'])} to: {pending['question']}\n"
|
||
"I've dropped it, and upgrades resume.")
|
||
if (not s.get("pending") and not self.hold() and s.get("last_upgrade", 0)
|
||
< last_weekly_slot(utcnow(), cfg["upgrade_weekday"],
|
||
cfg["upgrade_hour_utc"]).timestamp()):
|
||
s["last_upgrade"] = now # the queued task persists until it runs
|
||
self.enqueue({"kind": "upgrade"})
|
||
if now - s.get("last_self_update", 0) >= cfg["self_update_interval_seconds"]:
|
||
s["last_self_update"] = now
|
||
push_pending(cfg, self.hosts, agent_git_env(cfg))
|
||
self.self_update()
|
||
self.save()
|
||
|
||
def desk_poll(self):
|
||
"""One pass over the service desk's open requests. The script builds
|
||
what they ask for and answers in each issue; this relays what needs a
|
||
person: an approval, a failure, a request for a person, a finished one.
|
||
|
||
It runs on the core host, where its .env, docker and kubectl are."""
|
||
script = f"{self.cfg['repo_dir']}/{self.cfg['desk']['script']}"
|
||
q_script = shlex.quote(script)
|
||
p = self.core.run(f"test -f {q_script} || exit 97; exec python3 {q_script} poll --json",
|
||
cwd=os.path.dirname(os.path.dirname(script)).replace("\\", "/"),
|
||
timeout=self.cfg["desk"]["timeout_seconds"])
|
||
if p.returncode == 97:
|
||
return # no desk in this checkout
|
||
if p.returncode == 255 and not p.stdout:
|
||
log(f"Desk: {self.core.name} unreachable: {p.stderr.strip()[:200]}")
|
||
return # the health cycle reports an unreachable host
|
||
try:
|
||
out = json.loads(p.stdout or "{}") if p.returncode == 0 else None
|
||
except ValueError as e:
|
||
self.note_error(f"service desk: {e}")
|
||
return
|
||
if out is None:
|
||
self.note_error(f"service desk exited {p.returncode}: {p.stderr.strip()[-300:]}")
|
||
return
|
||
say = {"needs-approval": ("🙋", "needs your approval: {text}. Comment `/approve` or `/reject` on it"),
|
||
"failed": ("⛔", "failed: {text}. Once fixed, comment `/retry` on it"),
|
||
"triage": ("📨", "is a request for a person"),
|
||
"done": ("✅", "is done")}
|
||
for ev in out.get("events", []):
|
||
log(f"Desk #{ev['issue']} {ev['state']}: {ev['text']}")
|
||
if ev.get("notify") and ev["state"] in say:
|
||
icon, what = say[ev["state"]]
|
||
self.send(f"{icon} **Service desk #{ev['issue']}** {ev['title']} "
|
||
f"{what.format(text=ev['text'][:400])}: {ev['url']}")
|
||
for err in out.get("errors", []):
|
||
log(f"Desk: {err}")
|
||
if not err.startswith("#"): # the desk itself, not one request
|
||
self.note_error(f"service desk: {err}")
|
||
|
||
def health_cycle(self):
|
||
with self.lock:
|
||
if any(t["kind"] == "health" for t in self.state.get("queue") or []):
|
||
return # the last findings have not been handled yet
|
||
held = self.hold()
|
||
if held:
|
||
# Skipped whole, so streaks and host-check cooldowns are not spent on
|
||
# findings nobody acts on: the next cycle after the hold sees them again.
|
||
log(f"Health cycle skipped — holding {hold_line(held)}")
|
||
return
|
||
cfg, s, now = self.cfg, self.state, time.time()
|
||
day = self.day()
|
||
log("Health cycle…")
|
||
try:
|
||
snap = probe_core(cfg, self.core, s.get("last_event_check"),
|
||
s["host"].get("oom_since") or now)
|
||
except Exception as e:
|
||
# Seeing this is what running off the host buys: the host's own
|
||
# death is now noticed. Matrix lives there too, so the message may
|
||
# wait in the outbox until it is back.
|
||
s["core_failures"] = s.get("core_failures", 0) + 1
|
||
log(f"WARN: cannot probe {self.core.name}: {e}")
|
||
if s["core_failures"] == 3:
|
||
self.send(f"🚨 **{self.core.name} unreachable** — three health checks running "
|
||
f"could not reach it over SSH: `{str(e)[:300]}`")
|
||
return
|
||
if s.get("core_failures", 0) >= 3:
|
||
self.send(f"✅ **{self.core.name} reachable again** after "
|
||
f"{s['core_failures']} failed health checks.")
|
||
s["core_failures"] = 0
|
||
|
||
monitors, confirmed, recovered = None, [], []
|
||
if "kuma" in snap:
|
||
monitors = snap["kuma"].get("monitors") or []
|
||
s["kuma_failures"] = 0
|
||
else:
|
||
s["kuma_failures"] = s.get("kuma_failures", 0) + 1
|
||
log(f"WARN: {snap.get('kuma_error')}")
|
||
if s["kuma_failures"] == 3:
|
||
self.send(f"⚠️ Cannot read Uptime Kuma's database (3 checks running), "
|
||
f"so health checks are blind: `{str(snap.get('kuma_error'))[:300]}`")
|
||
|
||
if monitors is not None:
|
||
streak = s.setdefault("down_streak", {})
|
||
down = []
|
||
for m in monitors:
|
||
if m.get("status") == KUMA_DOWN:
|
||
streak[m["name"]] = streak.get(m["name"], 0) + 1
|
||
down.append(m)
|
||
else:
|
||
streak.pop(m["name"], None)
|
||
confirmed = [m for m in down if streak[m["name"]] >= cfg["down_confirmations"]]
|
||
for m in confirmed:
|
||
if streak[m["name"]] == cfg["down_confirmations"]:
|
||
bump(day.setdefault("incidents", {}), m["name"])
|
||
up = sum(1 for m in monitors if m.get("status") == KUMA_UP)
|
||
s["last_kuma"] = {"up": up, "total": len(monitors), "at": now}
|
||
log(f" {len(monitors)} tracked, {len(down)} down, {len(confirmed)} confirmed")
|
||
events = snap.get("events") or {}
|
||
recovered = detect_outages(events.get("events") or [],
|
||
s.setdefault("open_outages", {}))
|
||
s["last_event_check"] = events.get("watermark", s.get("last_event_check"))
|
||
for o in recovered:
|
||
bump(day.setdefault("recovered", {}), o["name"])
|
||
for key in ("mem", "ooms", "containers", "btime"):
|
||
if key + "_error" in snap:
|
||
log(f"WARN: host check {key}: {snap[key + '_error']}")
|
||
|
||
host = []
|
||
cooldowns = s["host"].setdefault("cooldowns", {})
|
||
for key, desc in host_check(cfg, s, snap):
|
||
if now - cooldowns.get(key, 0) >= cfg["host"]["check_cooldown_seconds"]:
|
||
cooldowns[key] = now
|
||
host.append([key, desc])
|
||
|
||
rebooted = None
|
||
btime = snap.get("btime")
|
||
if s["host"].get("btime") and btime and btime != s["host"]["btime"]:
|
||
rebooted = btime
|
||
s["host"]["btime"] = btime
|
||
|
||
if not (confirmed or recovered or host or rebooted):
|
||
return
|
||
if cfg["autonomy"] == "notify":
|
||
lines = [f"• **{m['name']}** DOWN: {m.get('msg') or 'n/a'}" for m in confirmed]
|
||
lines += [f"• {o['name']} recovered on its own ({o['down_at']} → {o['up_at']})"
|
||
for o in recovered]
|
||
lines += [f"• {desc}" for _, desc in host]
|
||
if rebooted:
|
||
lines.append(f"• host rebooted at {datetime.fromtimestamp(rebooted, timezone.utc):%Y-%m-%d %H:%M} UTC")
|
||
self.send("⚠️ **Health check** (notify-only, nothing investigated):\n" + "\n".join(lines))
|
||
return
|
||
self.enqueue({"kind": "health", "rebooted": rebooted, "host": host,
|
||
"recovered": recovered,
|
||
"down": [{k: m.get(k) for k in ("name", "type", "url", "hostname",
|
||
"port", "msg")} for m in confirmed]})
|
||
|
||
def digest(self):
|
||
s = self.state
|
||
day = s.get("day") or {}
|
||
k = s.get("last_kuma") or {}
|
||
snap = s["host"].get("snapshot") or {}
|
||
head = f"📋 **Daily report** — {k.get('up', '?')}/{k.get('total', '?')} Kuma monitors up"
|
||
if snap:
|
||
head += f" · disk {snap['disk_pct']}% · {snap['mem_avail_mb']} MB memory available"
|
||
lines = [head]
|
||
inc, rec = day.get("incidents", {}), day.get("recovered", {})
|
||
parts = []
|
||
if inc:
|
||
parts.append(f"sustained: {fmt_counts(inc)}")
|
||
if rec:
|
||
parts.append(f"recovered on their own: {fmt_counts(rec)}")
|
||
lines.append("**Downtime:** " + ("; ".join(parts) if parts else "none"))
|
||
alerts = day.get("alerts", {})
|
||
lines.append("**Alerts:** " + (fmt_counts(alerts) if alerts else "none"))
|
||
runs = day.get("runs", {})
|
||
if runs:
|
||
line = f"**Agent runs:** {sum(runs.values())} ({fmt_counts(runs)})"
|
||
if day.get("models"):
|
||
line += f" · {fmt_counts(day['models'])}"
|
||
if day.get("cost"):
|
||
line += f" · ${day['cost']:.2f} metered"
|
||
lines.append(line)
|
||
if day.get("commits"):
|
||
lines.append(f"**Commits pushed:** {day['commits']}")
|
||
if snap.get("reboot") is not None:
|
||
pkgs = ", ".join(snap["reboot"][:4]) or "system updates"
|
||
lines.append(f"⚠️ **Host reboot pending** ({pkgs}). The weekly upgrade asks you for a window.")
|
||
for kind, d in (s.get("agent_degraded") or {}).items():
|
||
lines.append(f"⛔ **No model can run {KIND_NAMES[kind]}** for {ago(d['since'])}.")
|
||
if s.get("pending"):
|
||
lines.append(f"❓ **Still waiting on your decision:** {s['pending']['question']}")
|
||
lines.append(f"Next upgrade {self.next_upgrade():%a %d %b %H:%M} UTC.")
|
||
self.send("\n".join(lines))
|
||
s["day"] = {}
|
||
|
||
def sync_deps(self):
|
||
"""Install what pyproject.toml / uv.lock now ask for into .venv."""
|
||
res = self.local.run(f"{shlex.quote(self.cfg['uv_bin'])} sync --frozen --quiet",
|
||
cwd=HERE, timeout=600)
|
||
return res.returncode == 0, (res.stdout + res.stderr)[-800:]
|
||
|
||
def self_update(self):
|
||
"""Fast-forward this checkout from its remote and re-exec, when idle."""
|
||
if not os.path.isdir(os.path.join(HERE, ".git")):
|
||
return
|
||
me = self.local
|
||
branch = git(me, HERE, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
|
||
if (git(me, HERE, "fetch", "-q", "origin", branch).returncode != 0
|
||
or git(me, HERE, "status", "--porcelain", "--untracked-files=no").stdout.strip()):
|
||
return
|
||
target = git(me, HERE, "rev-parse", "--short", f"origin/{branch}").stdout.strip()
|
||
behind = git(me, HERE, "rev-list", "--count", f"HEAD..origin/{branch}").stdout.strip()
|
||
if not behind.isdigit() or int(behind) == 0 or target == self.state.get("bad_update"):
|
||
return
|
||
old = git(me, HERE, "rev-parse", "HEAD").stdout.strip()
|
||
if git(me, HERE, "merge", "-q", "--ff-only", f"origin/{branch}").returncode != 0:
|
||
return
|
||
deps_changed = bool(git(me, HERE, "diff", "--name-only", old, "HEAD", "--",
|
||
"pyproject.toml", "uv.lock").stdout.strip())
|
||
synced, why = self.sync_deps() if deps_changed else (True, "")
|
||
check = subprocess.run([sys.executable, os.path.abspath(__file__),
|
||
"--config", self.cfg["_path"], "--check"],
|
||
capture_output=True, text=True, timeout=180)
|
||
if not synced or check.returncode != 0:
|
||
git(me, HERE, "reset", "-q", "--hard", old)
|
||
if deps_changed:
|
||
self.sync_deps()
|
||
check.stdout = (why + "\n" if not synced else "") + check.stdout
|
||
self.state["bad_update"] = target
|
||
self.send(f"⚠️ Self-update to `{target}` failed its check and was rolled back:\n"
|
||
f"```\n{(check.stdout + check.stderr)[-1200:]}\n```")
|
||
return
|
||
self.send(f"🔄 Updating myself `{old[:7]}` → `{target}` ({behind} commit(s)).")
|
||
self.save()
|
||
log(f"self-update to {target}: re-executing")
|
||
os.execv(sys.executable, [sys.executable, os.path.abspath(__file__), *sys.argv[1:]])
|
||
|
||
# -- tasks -------------------------------------------------------------- #
|
||
|
||
def build_operator(self, task):
|
||
s, now = self.state, time.time()
|
||
room, thread, body = task["room"], task.get("thread"), task["body"]
|
||
key = conv_key(room, thread)
|
||
conv = s["conversations"].get(key)
|
||
pending = s.get("pending")
|
||
resume, answering = None, False
|
||
if pending and ((room == self.maint_room and not thread)
|
||
or (conv and conv["session_id"] == pending.get("session_id"))):
|
||
answering, resume = True, pending.get("session_id")
|
||
opts = pending.get("options") or []
|
||
answer = opts[int(body) - 1] if body.isdigit() and 1 <= int(body) <= len(opts) else body
|
||
prompt = ("The operator answered your escalation.\n"
|
||
f" Question: {pending['question']}\n Options: {opts}\n"
|
||
f" Their answer: {answer}\n\n"
|
||
"Carry out that decision now, with full testing and rollback on "
|
||
"failure, and report the outcome. If the answer is not a decision "
|
||
"(a question, say), respond to it and escalate again if you still "
|
||
"need one.")
|
||
elif conv and now - conv["updated"] < self.cfg["conversation_ttl_seconds"]:
|
||
resume = conv["session_id"]
|
||
prompt = f"The operator replied over Matrix:\n\n{body}"
|
||
else:
|
||
prompt = ("The operator sent this over Matrix. Act on it autonomously and "
|
||
"report back; if it is a question, answer it from the live stack."
|
||
f"\n\n{body}")
|
||
|
||
def after(result):
|
||
if answering:
|
||
with self.lock:
|
||
s["pending"] = None
|
||
|
||
return {"label": "your message: " + body[:50], "prompt": prompt, "resume": resume,
|
||
"typing_room": room, "header": None, "after": after,
|
||
"targets": [(room, thread, task["event_id"])], "conv_keys": [key]}
|
||
|
||
def build_alerts(self, task):
|
||
s = self.state
|
||
with self.lock:
|
||
recs = [(fp, dict(s["alerts"][fp])) for fp in task["fps"] if fp in s["alerts"]]
|
||
if not recs:
|
||
return None
|
||
lines = []
|
||
for fp, r in recs:
|
||
status = (f"resolved {ago(r['resolved_at'])} ago"
|
||
if r.get("status") == "resolved" else "still firing")
|
||
text = r.get("text", "").replace("\n", "\n ")
|
||
line = f"- {r['name']} (fingerprint {fp}, {status}, fired {r['fired']}×)\n {text}"
|
||
if r.get("investigated_at"):
|
||
line += (f"\n You investigated this {ago(r['investigated_at'])} ago and "
|
||
f"reported: {r.get('last_summary', '')[:300]}")
|
||
lines.append(line)
|
||
names = ", ".join(sorted({r["name"] + (f" · {r['service'] or r['router']}"
|
||
if (r["service"] or r["router"]) else "")
|
||
for _, r in recs}))
|
||
prompt = ("ALERT TRIAGE — the log-alerting pipeline (Loki ruler → Alertmanager → "
|
||
"#stack-alerts) posted these critical alerts:\n\n" + "\n".join(lines) +
|
||
"\n\nFor each: run its LogQL against Loki (runbook → Logs and Alerts) "
|
||
"and read the lines behind it, find the cause, and fix it if it is a "
|
||
"real fault. If the lines are benign noise, demote that message in "
|
||
"core_stack/alloy/config.alloy as CLAUDE.md describes (never raise a "
|
||
"rule threshold) and commit it. An alert that already resolved still "
|
||
"happened: find out why, but change nothing that is healthy now. Set "
|
||
"status=ok when nothing needed changing.")
|
||
if self.cfg["autonomy"] == "notify":
|
||
prompt += "\n\nMode is NOTIFY-ONLY: investigate and report; change nothing."
|
||
root = recs[0][1].get("event_id")
|
||
|
||
def after(result):
|
||
with self.lock:
|
||
for fp, _ in recs:
|
||
if fp in s["alerts"]:
|
||
s["alerts"][fp]["investigated_at"] = time.time()
|
||
s["alerts"][fp]["last_summary"] = result.get("summary", "")[:500]
|
||
|
||
return {"label": f"alert triage: {names}"[:90], "prompt": prompt, "resume": None,
|
||
"typing_room": self.alerts_room, "header": f"Triage — {names}",
|
||
"after": after, "targets": [(self.alerts_room, root, None)],
|
||
"conv_keys": [conv_key(self.alerts_room, root), conv_key(self.alerts_room)],
|
||
"mirror": f"Alert triage — {names}"}
|
||
|
||
def build_health(self, task):
|
||
sections = []
|
||
if task.get("rebooted"):
|
||
when = datetime.fromtimestamp(task["rebooted"], timezone.utc)
|
||
sections.append(f"THE CORE HOST ({self.core.name}) REBOOTED at "
|
||
f"{when:%Y-%m-%d %H:%M} UTC. Verify every "
|
||
"stack came back in dependency order and passes the runbook's "
|
||
"Post-Recovery Smoke Tests, and that nothing with an active Kuma "
|
||
"monitor is left stopped.")
|
||
if task.get("down"):
|
||
lines = "\n".join(
|
||
f" • {m['name']} | type={m['type']} | target="
|
||
f"{m.get('url') or (m.get('hostname') or '') + ':' + str(m.get('port') or '')}"
|
||
f" | last_msg={m.get('msg') or 'n/a'}" for m in task["down"])
|
||
sections.append("SERVICES DOWN — Uptime Kuma reports these tracked monitors "
|
||
f"DOWN, confirmed over consecutive checks:\n{lines}\n\nFor each: "
|
||
"map the monitor target (a compose service name or network "
|
||
"alias) to its container, diagnose with the runbook, remediate, "
|
||
"and re-verify. If one is down by design or needs a human "
|
||
"decision, set status=escalate.")
|
||
if task.get("host"):
|
||
lines = "\n".join(f" • {desc}" for _, desc in task["host"])
|
||
sections.append(f"HOST ANOMALIES on {self.core.name} — found by the daemon's "
|
||
"host checks:\n"
|
||
f"{lines}\n\nInvestigate each and fix what is safe: for disk, "
|
||
"build cache, unused images and log growth; for an OOM kill, "
|
||
"which container and its mem_limit against real use; for a "
|
||
"restart loop, its cause.")
|
||
if task.get("recovered"):
|
||
lines = "\n".join(
|
||
f" • {o['name']}: DOWN {o['down_at'] or '(before the last check)'} → "
|
||
f"UP {o['up_at']} ({fmt_duration(o['down_at'], o['up_at']) if o['down_at'] else '?'})"
|
||
f" — {o.get('msg') or 'n/a'}" for o in task["recovered"])
|
||
sections.append("SELF-RECOVERED OUTAGES — these monitors went DOWN and came "
|
||
f"back on their own:\n{lines}\n\nFind the likely cause in the "
|
||
"logs around each window (Loki keeps 30 days; restart counts; "
|
||
"journald). Change nothing that is healthy now.")
|
||
prompt = ("HEALTH CHECK — the daemon's periodic check found:\n\n" +
|
||
"\n\n".join(sections) +
|
||
f"\n\nCurrent containers on {self.core.name}:\n{self.docker_ps()}")
|
||
|
||
def after(result):
|
||
with self.lock: # a fixed service needs fresh confirmations
|
||
for m in task.get("down") or []:
|
||
self.state["down_streak"].pop(m["name"], None)
|
||
|
||
return {"label": "health check findings", "prompt": prompt, "resume": None,
|
||
"typing_room": self.maint_room, "header": "Health check", "after": after,
|
||
"targets": [(self.maint_room, None, None)],
|
||
"conv_keys": [conv_key(self.maint_room)]}
|
||
|
||
def build_upgrade(self, task):
|
||
autonomy = self.cfg["autonomy"]
|
||
if autonomy == "notify":
|
||
note = ("Mode is NOTIFY-ONLY: change nothing. Report available upgrades and "
|
||
"recommendations; set status=escalate with the list.")
|
||
elif autonomy == "fix-only":
|
||
note = ("Mode is FIX-ONLY for upgrades: research and report; apply nothing. "
|
||
"Set status=escalate to ask which to apply.")
|
||
else:
|
||
note = ("Mode is FULL: apply safe upgrades yourself. For a MAJOR or breaking "
|
||
"upgrade with trade-offs, set status=escalate with options instead.")
|
||
reboot = (self.state["host"].get("snapshot") or {}).get("reboot")
|
||
reboot_note = ""
|
||
if reboot is not None:
|
||
reboot_note = (f"\n\nA host reboot is pending ({', '.join(reboot[:6]) or 'system updates'}). "
|
||
"If it is still pending after your work, set status=escalate "
|
||
"asking the operator to approve a reboot now or at a time they "
|
||
"choose. Once approved, `sudo systemctl reboot`: containers "
|
||
"return by their restart policies and this daemon verifies the "
|
||
"stack after boot.")
|
||
prompt = (
|
||
"WEEKLY UPGRADE" + (" (requested by the operator)" if task.get("manual") else "") +
|
||
f" — scope is everything the core host (`{self.core.name}`) runs, not only "
|
||
"what Kuma tracks:\n"
|
||
"- semprini-core: every `image:` in core_stack/compose*.yml. conk is built "
|
||
"from source; skip it.\n"
|
||
"- semprini-blog (its docker-compose.yml): pull newer images for floating "
|
||
"tags; propose pin changes rather than editing its files.\n"
|
||
"- host packages: `apt list --upgradable` (unattended-upgrades already "
|
||
"installs security updates).\n\n"
|
||
f"Running containers:\n{self.docker_ps()}\n\n"
|
||
"Follow agents/skills/upgrade-services/SKILL.md. Before upgrading anything "
|
||
"stateful (Postgres, Keycloak, Synapse, Gitea, Vaultwarden), take a fresh "
|
||
"dump with `docker exec mgmt-pg-backup /backup.sh`. Upgrade in dependency "
|
||
"order, one service at a time, verifying each, and roll back on failure. "
|
||
"Commit the new pins to main and push.\n\n"
|
||
f"{note}{reboot_note}\n\n"
|
||
"Summarise what is current, what you upgraded (old → new, and why: security, "
|
||
"bug fix, routine), what you rolled back and why, and what needs a decision.")
|
||
return {"label": "weekly upgrade", "prompt": prompt, "resume": None,
|
||
"typing_room": self.maint_room, "header": "Weekly upgrade",
|
||
"after": lambda result: None, "targets": [(self.maint_room, None, None)],
|
||
"conv_keys": [conv_key(self.maint_room)]}
|
||
|
||
def keep_typing(self, room, stop):
|
||
while not stop.is_set():
|
||
matrix_typing(self.cfg, room, True)
|
||
stop.wait(25)
|
||
|
||
def docker_ps(self):
|
||
res = self.core.run("docker ps -a --format 'table {{.Names}}\\t{{.Status}}\\t{{.Image}}'",
|
||
timeout=60)
|
||
return res.stdout.strip() or f"(docker ps failed: {res.stderr.strip()[:200]})"
|
||
|
||
def agent_definition(self):
|
||
"""agents/stack-support.agent.md from core's checkout, or the last copy
|
||
read, so the agent can still answer while core is unreachable."""
|
||
cache = os.path.join(os.path.dirname(self.cfg["state_file"]), "stack-support.agent.md")
|
||
try:
|
||
text = self.core.read_text(f"{self.cfg['repo_dir']}/{self.cfg['agent_file']}")
|
||
except Exception as e:
|
||
try:
|
||
with open(cache, encoding="utf-8") as fh:
|
||
log(f"WARN: agent definition from cache: {e}")
|
||
return fh.read()
|
||
except OSError:
|
||
raise agentlib().AgentUnavailable(
|
||
f"cannot read the agent definition on {self.core.name}: {e}")
|
||
try:
|
||
os.makedirs(os.path.dirname(cache), exist_ok=True)
|
||
with open(cache, "w", encoding="utf-8") as fh:
|
||
fh.write(text)
|
||
except OSError as e:
|
||
log(f"WARN: cannot cache the agent definition: {e}")
|
||
return text
|
||
|
||
def run_agent(self, kind, prompt, resume=None, override=None, handle=None):
|
||
ag = agentlib()
|
||
writes = self.cfg["autonomy"] != "notify"
|
||
git_env = agent_git_env(self.cfg)
|
||
text = ag.instructions(self.cfg, self.hosts, self.agent_definition(), writes, bool(git_env))
|
||
log(f"Running the agent: {kind}, {len(prompt)} char task"
|
||
f"{', resuming ' + resume[:8] if resume else ''}; "
|
||
f"{ag.describe_chain(self.cfg, kind, override)}")
|
||
result = ag.run_task(self.cfg, kind, prompt, instructions_text=text, hosts=self.hosts,
|
||
local_env=git_env, writes=writes, session_id=resume,
|
||
override=override, handle=handle, keys=current_keys(self.cfg), log=log)
|
||
log(f"agent finished in {result['seconds']}s on {result['model']} ({result['profile']}): "
|
||
f"{result['status']}, {result.get('requests')} requests, {result.get('tool_calls')} "
|
||
f"tool calls, {result.get('tokens')} tokens, cost {result.get('cost')}")
|
||
return result
|
||
|
||
def execute(self, task):
|
||
build = {"operator": self.build_operator, "alerts": self.build_alerts,
|
||
"health": self.build_health, "upgrade": self.build_upgrade}[task["kind"]]
|
||
job = build(task)
|
||
if job is None:
|
||
return
|
||
ag = agentlib()
|
||
git_env = agent_git_env(self.cfg)
|
||
repo_lines, heads = repo_before(self.cfg, self.hosts, git_env)
|
||
prompt = job["prompt"]
|
||
if repo_lines:
|
||
prompt += "\n\nRepository state before this run:\n" + "\n".join(repo_lines)
|
||
override = None
|
||
if task["kind"] == "operator":
|
||
override = (self.state.get("model_override") or {}).get(
|
||
conv_key(task["room"], task.get("thread")))
|
||
|
||
handle, stop = ag.Handle(), threading.Event()
|
||
self.current = {"label": job["label"], "started": time.time(), "handle": handle}
|
||
room = job.get("typing_room")
|
||
if room:
|
||
threading.Thread(target=self.keep_typing, args=(room, stop), daemon=True).start()
|
||
try:
|
||
result = self.run_agent(task["kind"], prompt, resume=job.get("resume"),
|
||
override=override, handle=handle)
|
||
except ag.AgentUnavailable as e:
|
||
with self.lock:
|
||
self.state["queue"].append(task)
|
||
self.save()
|
||
self.agent_down(e, job["label"], task["kind"])
|
||
return
|
||
finally:
|
||
stop.set()
|
||
self.current = None
|
||
if room:
|
||
matrix_typing(self.cfg, room, False)
|
||
self.agent_up(task["kind"])
|
||
|
||
notes = repo_after(self.cfg, self.hosts, git_env, heads)
|
||
with self.lock:
|
||
day = self.day()
|
||
bump(day.setdefault("runs", {}), result.get("status", "unknown"))
|
||
bump(day.setdefault("models", {}), result.get("profile", "?"))
|
||
if result.get("cost"):
|
||
day["cost"] = day.get("cost", 0) + result["cost"]
|
||
for line in notes:
|
||
m = re.match(r"📝 \S+: (\d+) commit", line)
|
||
if m:
|
||
day["commits"] = day.get("commits", 0) + int(m.group(1))
|
||
job["after"](result)
|
||
self.relay(job, result, notes)
|
||
self.save()
|
||
|
||
def relay(self, job, result, notes):
|
||
status = result.get("status", "unknown")
|
||
icon = {"ok": "✅", "action_taken": "🔧", "escalate": "❓",
|
||
"blocked": "⛔", "unknown": "⚠️"}.get(status, "•")
|
||
label = status.replace("_", " ")
|
||
summary = result.get("summary", "")
|
||
session = result.get("session_id")
|
||
|
||
decision = ""
|
||
if status == "escalate" and result.get("question"):
|
||
opts = result.get("options") or []
|
||
decision = f"\n\n**Decision needed:** {result['question']}"
|
||
if opts:
|
||
decision += "\n" + "\n".join(f"{i + 1}. {o}" for i, o in enumerate(opts))
|
||
decision += "\n\n_Reply with a number or in your own words._"
|
||
with self.lock:
|
||
self.state["pending"] = {"question": result["question"], "options": opts,
|
||
"session_id": session, "asked_at": time.time()}
|
||
tail = decision + ("\n\n" + "\n".join(notes) if notes else "")
|
||
|
||
if job.get("header"):
|
||
text = f"{icon} **{job['header']}** — {label}\n{summary}"
|
||
else:
|
||
text = summary if status == "ok" else f"{icon} {summary}"
|
||
if result.get("details"):
|
||
text += f"\n\n{result['details']}"
|
||
tail += "\n\n" + run_footer(result)
|
||
for room, thread, reply_to in job["targets"]:
|
||
self.send(text + tail, room=room, thread_root=thread, reply_to=reply_to)
|
||
|
||
keys = list(job["conv_keys"])
|
||
if job.get("mirror") and (status != "ok" or notes):
|
||
self.send(f"{icon} **{job['mirror']}** — {label}\n{summary}{tail}\n\n"
|
||
"_Details in the Stack alerts thread; reply here or there._")
|
||
keys.append(conv_key(self.maint_room))
|
||
if session:
|
||
with self.lock:
|
||
convs, now = self.state["conversations"], time.time()
|
||
for key in keys:
|
||
convs[key] = {"session_id": session, "updated": now}
|
||
ttl = self.cfg["conversation_ttl_seconds"]
|
||
for key in [k for k, v in convs.items() if now - v["updated"] > 6 * ttl]:
|
||
del convs[key]
|
||
keep = {v["session_id"] for v in convs.values()}
|
||
keep.add((self.state.get("pending") or {}).get("session_id"))
|
||
agentlib().prune_sessions(self.cfg, keep)
|
||
|
||
# -- main loop ---------------------------------------------------------- #
|
||
|
||
def matrix_main(self):
|
||
alias = self.cfg["matrix"].get("alerts_room")
|
||
delay = 5
|
||
while alias and not self.alerts_room:
|
||
try:
|
||
self.alerts_room = resolve_room(self.cfg, alias)
|
||
ensure_joined(self.cfg, [self.maint_room, self.alerts_room])
|
||
except Exception as e:
|
||
log(f"WARN: cannot resolve {alias}: {e} — retrying in {delay}s")
|
||
time.sleep(delay)
|
||
delay = min(300, delay * 2)
|
||
self.listen()
|
||
|
||
def model_problems(self):
|
||
"""Profiles the routing names that cannot be built as configured."""
|
||
ag, keys, problems = agentlib(), current_keys(self.cfg), []
|
||
for name in sorted({n for chain in self.cfg["routing"].values() for n in chain}):
|
||
try:
|
||
ag.build_model(self.cfg, name, keys)
|
||
except ag.AgentUnavailable as e:
|
||
problems.append(str(e))
|
||
return problems
|
||
|
||
def announce(self):
|
||
last = self.state.get("last_online") or {}
|
||
problems = self.model_problems()
|
||
if (last.get("version") == self.version and not problems
|
||
and time.time() - last.get("at", 0) < 3600):
|
||
return # a quick restart; don't repeat ourselves
|
||
msg = (f"🤖 **stack-maintainer online** on {socket.gethostname()} (`{self.version}`)"
|
||
f", keeping {self.core.name} over SSH — listening here and in Stack alerts; "
|
||
f"health checks every {self.cfg['health_interval_seconds'] // 60} min; next "
|
||
f"upgrade {self.next_upgrade():%a %d %b %H:%M} UTC. Models: "
|
||
+ ", ".join(f"`{n}` {m['model']}" for n, m in self.cfg["models"].items())
|
||
+ ". Send `help` for commands.")
|
||
if problems:
|
||
msg += ("\n\n⚠️ **Some models cannot run**, so their tasks fall to the next in line:\n"
|
||
+ "\n".join(f"- {p}" for p in problems))
|
||
self.send(msg)
|
||
self.state["last_online"] = {"at": time.time(), "version": self.version}
|
||
|
||
def run(self):
|
||
log(f"semprini-maintainer {self.version} starting.")
|
||
if self.matrix_ok:
|
||
threading.Thread(target=self.matrix_main, name="matrix", daemon=True).start()
|
||
self.announce()
|
||
self.save()
|
||
while True:
|
||
self.wake.clear()
|
||
try:
|
||
self.promote_alert_batch()
|
||
task = self.next_task()
|
||
if task:
|
||
self.execute(task)
|
||
continue
|
||
self.timers()
|
||
if self.next_task_ready():
|
||
continue
|
||
except Exception as e:
|
||
log("ERROR in main loop:\n" + traceback.format_exc())
|
||
self.note_error(str(e))
|
||
self.wake.wait(timeout=15)
|
||
|
||
def next_task_ready(self):
|
||
# The same rule as next_task, or a task that is held or backing off
|
||
# would spin the main loop instead of letting it sleep.
|
||
return bool(self.runnable())
|
||
|
||
|
||
def run_footer(result):
|
||
"""One small line under a reply: which model answered, how long, what it
|
||
cost — so it is clear what a local model is doing and what cloud runs cost."""
|
||
secs = result.get("seconds") or 0
|
||
parts = [f"{result.get('model', '?')} ({result.get('profile', '?')})",
|
||
f"{secs // 60}m{secs % 60:02d}s" if secs >= 60 else f"{secs}s"]
|
||
if result.get("tool_calls"):
|
||
parts.append(f"{result['tool_calls']} tool calls")
|
||
if result.get("cost"):
|
||
parts.append(f"${result['cost']:.2f}")
|
||
if result.get("fell_back"):
|
||
parts.append("after " + "; ".join(result["fell_back"]))
|
||
return "_" + " · ".join(parts) + "_"
|
||
|
||
|
||
def last_weekly_slot(now, weekday, hour):
|
||
slot = now.replace(hour=hour, minute=0, second=0, microsecond=0) - timedelta(
|
||
days=(now.weekday() - weekday) % 7)
|
||
return slot - timedelta(days=7) if slot > now else slot
|
||
|
||
|
||
def last_daily_slot(now, hour):
|
||
slot = now.replace(hour=hour, minute=0, second=0, microsecond=0)
|
||
return slot - timedelta(days=1) if slot > now else slot
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# CLI
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def self_check(cfg, offline=False):
|
||
"""Validate code paths and config. Used by install.sh and before a
|
||
self-update is accepted, so a failure here means "do not run this code".
|
||
Whether the hosts and models answer right now is only warned about."""
|
||
errors, warnings = [], []
|
||
firing = parse_alert("**FIRING LogErrorBurst** · service `user-test`\nuser-test is "
|
||
"logging errors\nsince 2026-09-15 06:53:53 UTC · fingerprint "
|
||
"`34d3f155ae58b655`")
|
||
resolved = parse_alert("**RESOLVED HttpServerErrors** · router `blog-root@file`\nended "
|
||
"2026-09-15 08:45:33 UTC · fingerprint `87b361b7bf668868`")
|
||
if not (firing and firing["state"] == "FIRING" and firing["service"] == "user-test"
|
||
and resolved and resolved["router"] == "blog-root@file"):
|
||
errors.append("alert parsing is broken")
|
||
if parse_command("Status?") != "status" or parse_command("stop the ops stack"):
|
||
errors.append("command parsing is broken")
|
||
if (parse_model("model") != {"profile": None} or parse_model("Model local")
|
||
!= {"profile": "local"} or parse_model("model the upgrade on the blog")):
|
||
errors.append("model command parsing is broken")
|
||
if ((parse_hold("hold 45m rebuilding grafana") or {}) != {"minutes": 45, "reason": "rebuilding grafana"}
|
||
or (parse_hold("hold 2h") or {}).get("minutes") != 120
|
||
or (parse_hold("hold") or {}).get("minutes") != HOLD_DEFAULT_MINUTES
|
||
or (parse_hold("hold 99h") or {}).get("minutes") != HOLD_MAX_MINUTES
|
||
or parse_hold("hold off on the upgrade") is not None
|
||
or parse_command("resume") != "resume"):
|
||
errors.append("hold parsing is broken")
|
||
t = time.time()
|
||
if ((later_hold({"until": t + 60}, {"until": t + 600}) or {}).get("until") != t + 600
|
||
or later_hold({"until": t - 1}, None) is not None):
|
||
errors.append("hold merging is broken")
|
||
now = datetime(2026, 9, 16, 12, tzinfo=timezone.utc) # a Wednesday
|
||
if last_weekly_slot(now, 5, 22) != datetime(2026, 9, 12, 22, tzinfo=timezone.utc):
|
||
errors.append("weekly schedule is broken")
|
||
state = fresh_state()
|
||
snap = {"at": t, "disk": {"pct": 91.0, "free_gb": 3}, "mem": {"MemAvailable": 200},
|
||
"ooms": [], "reboot": None, "btime": 1,
|
||
"containers": {"c1": ["loki", 3, "running"]}}
|
||
host_check(cfg, state, snap)
|
||
snap["containers"] = {"c1": ["loki", 5, "running"]}
|
||
found = [k for k, _ in host_check(cfg, state, snap)]
|
||
if found != ["disk", "memory", "restart:loki"]:
|
||
errors.append(f"host check is broken: {found}")
|
||
try:
|
||
with open(PROBE) as fh:
|
||
compile(fh.read(), PROBE, "exec")
|
||
except (OSError, SyntaxError) as e:
|
||
errors.append(f"probe.py: {e}")
|
||
|
||
if not cfg["_path"] or not os.path.exists(cfg["_path"]):
|
||
errors.append(f"config file not found: {cfg['_path']}")
|
||
m = cfg["matrix"]
|
||
for key in ("user_id", "access_token", "room_id"):
|
||
if not m.get(key) or str(m[key]).startswith("FILLED_BY"):
|
||
errors.append(f"matrix.{key} is not set (run register-matrix-bot.sh)")
|
||
if cfg["repo_host"] not in cfg["hosts"]:
|
||
errors.append(f"repo_host {cfg['repo_host']!r} is not in hosts")
|
||
for kind in PRIORITY:
|
||
if not cfg["routing"].get(kind):
|
||
errors.append(f"routing.{kind} names no model")
|
||
|
||
try:
|
||
ag = agentlib()
|
||
except ImportError as e:
|
||
errors.append(f"pydantic-ai is not installed ({e}): run `uv sync` and start "
|
||
"maintainer.py with .venv/bin/python")
|
||
ag = None
|
||
if ag:
|
||
problem = ag.smoke_test(cfg, hostlib.load_hosts(cfg))
|
||
if problem:
|
||
errors.append(problem)
|
||
keys = current_keys(cfg)
|
||
for name in sorted({n for chain in cfg["routing"].values() for n in chain}):
|
||
try:
|
||
ag.build_model(cfg, name, keys)
|
||
except ag.AgentUnavailable as e:
|
||
warnings.append(str(e))
|
||
if not agent_git_env(cfg):
|
||
warnings.append("no Gitea token: the agent cannot open pull requests (register-gitea-bot.sh)")
|
||
|
||
if not offline:
|
||
warnings += reachability(cfg)
|
||
for w in warnings:
|
||
print(f"WARN: {w}")
|
||
for e in errors:
|
||
print(f"ERROR: {e}")
|
||
print("check: ok" if not errors else "check: FAILED")
|
||
return 1 if errors else 0
|
||
|
||
|
||
def reachability(cfg):
|
||
"""Warnings about hosts and local models that do not answer right now."""
|
||
warnings = []
|
||
hosts = load_hosts(cfg)
|
||
core = hosts[cfg["repo_host"]]
|
||
res = core.run("true", timeout=30)
|
||
if res.returncode != 0:
|
||
return [f"cannot reach {core.name} over SSH: {res.stderr.strip()[:200]} — "
|
||
"health checks, the desk and the agent's core work all need it"]
|
||
for path, what in ((f"{cfg['repo_dir']}/{cfg['agent_file']}", "agent definition"),
|
||
(f"{cfg['repo_dir']}/{cfg['desk']['script']}", "service desk script")):
|
||
if not core.exists(path):
|
||
warnings.append(f"no {what} at {path} on {core.name}")
|
||
for r in cfg["git"]["repos"]:
|
||
h = repo_host(cfg, hosts, r)
|
||
if not h.exists(f"{r['path']}/.git"):
|
||
warnings.append(f"{r['path']} on {h.name} is not a git checkout")
|
||
win = next((h for h in hosts.values() if h.kind == "powershell"), None)
|
||
if win and win.run("$PSVersionTable.PSVersion.Major", timeout=60).returncode != 0:
|
||
warnings.append(f"host {win.name}: powershell.exe does not run from here (WSL interop?)")
|
||
for name, prof in cfg["models"].items():
|
||
if not prof["model"].startswith("ollama:"):
|
||
continue
|
||
base = agentlib().resolve_url(prof.get("base_url") or "http://localhost:11434/v1")
|
||
tags = base.rstrip("/").removesuffix("/v1") + "/api/tags"
|
||
try:
|
||
with urllib.request.urlopen(tags, timeout=5) as resp:
|
||
have = [t["name"] for t in json.load(resp).get("models", [])]
|
||
want = prof["model"].partition(":")[2]
|
||
if not any(h == want or h.startswith(want + ":") for h in have):
|
||
warnings.append(f"model profile {name!r}: Ollama has no {want!r} "
|
||
f"(ollama pull {want}); it has {', '.join(have) or 'none'}")
|
||
except Exception as e:
|
||
warnings.append(f"model profile {name!r}: Ollama not reachable at {tags}: {e}")
|
||
return warnings
|
||
|
||
|
||
def write_config(cfg, update):
|
||
"""Apply update(data) to config.json on disk, keeping it 0600."""
|
||
path = cfg["_path"]
|
||
with open(path) as fh:
|
||
data = json.load(fh)
|
||
update(data)
|
||
tmp = path + ".tmp"
|
||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||
with os.fdopen(fd, "w") as fh:
|
||
json.dump(data, fh, indent=2)
|
||
fh.write("\n")
|
||
os.replace(tmp, path)
|
||
|
||
|
||
def set_api_key(cfg, profile):
|
||
if profile not in cfg["models"]:
|
||
print(f"No model profile {profile!r}; there are: {', '.join(cfg['models'])}")
|
||
return 1
|
||
key = getpass.getpass(f"API key for {profile} ({cfg['models'][profile]['model']}): ").strip()
|
||
if not key:
|
||
print("No key given.")
|
||
return 1
|
||
print("→ checking it with a one-line request…")
|
||
ok, detail = agentlib().ping(cfg, profile, keys={profile: key})
|
||
print(("✓ " if ok else "✗ ") + detail)
|
||
if not ok:
|
||
return 1
|
||
|
||
def update(data):
|
||
models = data.setdefault("models", json.loads(json.dumps(cfg["models"])))
|
||
models.setdefault(profile, dict(cfg["models"][profile]))["api_key"] = key
|
||
write_config(cfg, update)
|
||
print("✓ saved. The running service uses it from its next agent run.")
|
||
return 0
|
||
|
||
|
||
def try_model(cfg, profile):
|
||
"""Can this profile answer and call a tool? The one thing a local model
|
||
must do to be any use here."""
|
||
if profile not in cfg["models"]:
|
||
print(f"No model profile {profile!r}; there are: {', '.join(cfg['models'])}")
|
||
return 1
|
||
ag = agentlib()
|
||
prof = ag.profile_of(cfg, profile)
|
||
print(f"→ {profile}: {prof['model']}")
|
||
ok, detail = ag.ping(cfg, profile, keys=current_keys(cfg))
|
||
print(("✓ " if ok else "✗ ") + detail)
|
||
if ok and prof["model"].startswith("ollama:"):
|
||
# Ollama cuts a prompt longer than its window without saying so, and the
|
||
# agent's instructions alone are several thousand tokens.
|
||
base = ag.resolve_url(prof.get("base_url") or "http://localhost:11434/v1")
|
||
try:
|
||
with urllib.request.urlopen(base.rstrip("/").removesuffix("/v1") + "/api/ps",
|
||
timeout=10) as resp:
|
||
loaded = json.load(resp).get("models", [])
|
||
want = prof["model"].partition(":")[2]
|
||
ctx = next((m.get("context_length") for m in loaded
|
||
if m["name"] == want or m["name"].startswith(want + ":")), None)
|
||
if ctx and ctx < prof["context_tokens"]:
|
||
print(f"✗ Ollama loaded it with a {ctx}-token window, less than this profile's "
|
||
f"context_tokens ({prof['context_tokens']}): long runs will be cut. Set "
|
||
f"OLLAMA_CONTEXT_LENGTH={prof['context_tokens']} for Ollama on Windows and "
|
||
"restart it, or lower context_tokens.")
|
||
return 1
|
||
if ctx:
|
||
print(f"✓ context window {ctx} tokens")
|
||
except Exception as e:
|
||
print(f"(could not read Ollama's context window: {e})")
|
||
return 0 if ok else 1
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser(description="semprini stack maintenance daemon")
|
||
ap.add_argument("--config", default=os.path.join(HERE, "config.json"))
|
||
ap.add_argument("--once", choices=["health", "upgrade", "digest"],
|
||
help="run one cycle (and any agent work it queues), then exit")
|
||
ap.add_argument("--check", action="store_true",
|
||
help="validate the code and config, then exit")
|
||
ap.add_argument("--offline", action="store_true",
|
||
help="with --check: skip the SSH and model reachability warnings")
|
||
ap.add_argument("--set-api-key", metavar="PROFILE",
|
||
help="check and store an API key for a model profile that needs one")
|
||
ap.add_argument("--try-model", metavar="PROFILE",
|
||
help="one request with one tool call to a model profile, then exit")
|
||
ap.add_argument("--hold", metavar="DURATION",
|
||
help="stand down for e.g. 45m or 2h (8h is the most), then exit. "
|
||
"A running daemon picks it up within a minute")
|
||
ap.add_argument("--reason", default="",
|
||
help="why the hold, shown in Matrix and in `status`")
|
||
ap.add_argument("--resume", action="store_true", help="end a hold now, then exit")
|
||
args = ap.parse_args()
|
||
|
||
cfg = load_config(args.config)
|
||
if args.check:
|
||
return self_check(cfg, offline=args.offline)
|
||
if args.set_api_key:
|
||
return set_api_key(cfg, args.set_api_key)
|
||
if args.try_model:
|
||
return try_model(cfg, args.try_model)
|
||
if args.hold:
|
||
minutes = parse_duration(args.hold)
|
||
if minutes is None:
|
||
print(f"not a duration: {args.hold!r} — try 45m or 2h")
|
||
return 1
|
||
# Scripts hold too (sync-to-host.sh sets 15 minutes on every deploy), and
|
||
# must not cut short a longer hold someone set for their own work.
|
||
held = read_hold(cfg)
|
||
if held and held["until"] >= time.time() + minutes * 60:
|
||
print("already holding " + hold_line(held))
|
||
return 0
|
||
print("holding " + hold_line(write_hold(cfg, minutes, args.reason, "the command line")))
|
||
return 0
|
||
if args.resume:
|
||
print("hold cleared" if clear_hold(cfg) else "nothing was on hold")
|
||
return 0
|
||
|
||
bot = Maintainer(cfg, load_state(cfg))
|
||
if args.once:
|
||
log(f"Running a single '{args.once}' cycle…")
|
||
if bot.matrix_ok and cfg["matrix"].get("alerts_room"):
|
||
bot.alerts_room = resolve_room(cfg, cfg["matrix"]["alerts_room"])
|
||
if args.once == "health":
|
||
bot.health_cycle()
|
||
elif args.once == "upgrade":
|
||
bot.enqueue({"kind": "upgrade", "manual": True})
|
||
else:
|
||
bot.digest()
|
||
task = bot.next_task()
|
||
while task:
|
||
bot.execute(task)
|
||
task = bot.next_task()
|
||
bot.save()
|
||
return 0
|
||
bot.run()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|