diff --git a/CLAUDE.md b/CLAUDE.md index a173685..990587d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,15 @@ JSON result. - **Operator messages** (Stack Maintenance room): read by a long-poll `/sync`, so they arrive within about a second. A follow-up within `conversation_ttl_seconds` resumes the same Claude session (`--resume`), so it behaves like a chat. `status`, `cancel`, `new`, - `upgrade` and `help` are answered by the listener without the agent, even mid-run. + `upgrade`, `hold`, `resume` and `help` are answered by the listener without the agent, + even mid-run. +- **Hold** (`hold 45m ` in Matrix, `maintainer.py --hold 45m --reason …` from a + shell): a time-boxed pause on everything the daemon starts by itself — health cycles, + alert triage and upgrades — while operator messages still run and alerts still batch, so + one triage run covers the whole hold. It lives in `hold.json` next to the state file + because a shell has to reach a daemon that owns its own state file, and it expires by + itself so nothing stays paused by accident. semprini-core's `sync-to-host.sh` sets 15 + minutes on each deploy. - **Alerts** (`#stack-alerts`, written by `@alerts` via Loki → Alertmanager → matrix-alerts): FIRING messages are batched for `alerts.batch_seconds` and triaged in one run, answered in a thread under the alert. Non-`ok` results are mirrored to Stack diff --git a/README.md b/README.md index 703ee4c..f701ab5 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ A message that is exactly one of these words is handled at once, even mid-run: |---|---| | `status` | What it is doing, the queue, health, host, next upgrade | | `cancel` / `stop` | Stop the agent run in progress | +| `hold 45m ` | Stand down for a while: `hold` alone is 30 minutes, 8 hours is the most. Your messages still run and alerts still collect; health checks, triage and upgrades wait, and it says so when the hold starts and when it runs out | +| `resume` | End a hold now | | `new` | Forget this room's conversation | | `upgrade` | Run the weekly upgrade now | | `help` | The list | @@ -145,6 +147,18 @@ register scripts find valid tokens and change nothing. ## Operating - **Logs:** `journalctl -u semprini-maintainer -f`, or `status` in Matrix. +- **Working on the stack yourself:** hold it, rather than stopping the service — a hold + expires on its own, so nothing stays paused because someone forgot. From Matrix, + `hold 45m upgrading postgres`; from a shell on the host, or over ssh from a session: + + ```bash + ~/semprini-maintainer/maintainer.py --hold 45m --reason "upgrading postgres" + ~/semprini-maintainer/maintainer.py --resume + ``` + + The hold lives in `hold.json` beside the state file, so it reaches a running daemon and + survives a restart. semprini-core's `infra/sync-to-host.sh` sets 15 minutes on every + deploy, so the daemon does not chase the churn a deploy makes. - **Stop everything it does:** `sudo systemctl stop semprini-maintainer`. For "watch but don't touch", set `"autonomy": "notify"` and restart the service. - **Update the daemon:** push to `main` here. It fast-forwards within the hour, runs diff --git a/maintainer.py b/maintainer.py index 11f7b59..020f8a1 100755 --- a/maintainer.py +++ b/maintainer.py @@ -183,6 +183,8 @@ def fresh_state(): "agent_retry_after": 0, "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 } @@ -209,6 +211,94 @@ def save_state(cfg, state): 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. + +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 ` -> {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 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) @@ -749,7 +839,8 @@ def parse_alert(body): COMMANDS = {"status": "status", "cancel": "cancel", "stop": "cancel", - "new": "new", "upgrade": "upgrade", "help": "help"} + "new": "new", "upgrade": "upgrade", "help": "help", + "resume": "resume"} def parse_command(body): @@ -1064,6 +1155,8 @@ Write to me in plain language and I act on it. A follow-up within a few hours co **Commands** - `status` — what I am doing, the queue, host and health - `cancel` — stop the agent run in progress +- `hold 45m ` — 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 - `upgrade` — run the weekly upgrade now - `help` — this message""" @@ -1223,6 +1316,11 @@ class Maintainer: 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"]) @@ -1293,6 +1391,16 @@ class Maintainer: text = f"Cancelling *{cur['label']}*." else: text = "Nothing is running." + elif cmd == "resume": + hold = read_hold(self.cfg) + if hold and clear_hold(self.cfg): + 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) @@ -1305,6 +1413,38 @@ class Maintainer: text += f" It runs after *{cur['label']}*." self.send(text, room=room, thread_root=thread, reply_to=event_id) + # -- hold --------------------------------------------------------------- # + + def hold(self): + return read_hold(self.cfg) + + 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, read_hold(self.cfg) + 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): @@ -1329,12 +1469,20 @@ class Maintainer: queue = self.state.get("queue") or [] if not queue: return None - task = min(queue, key=lambda t: (PRIORITY[t["kind"]], t["created"])) + # A hold stops what the daemon starts by itself; the operator's own + # messages are why they would be talking to it in the first place. + runnable = ([t for t in queue if t["kind"] == "operator"] + if read_hold(self.cfg) else queue) + if not runnable: + return None + 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"]: @@ -1391,6 +1539,9 @@ class Maintainer: f"`{self.version}`, up {ago(self.started)}"] lines.append(f"**Now:** {cur['label']} ({ago(cur['started'])})" if cur else "**Now:** idle") + hold = read_hold(self.cfg) + 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"])) @@ -1429,6 +1580,7 @@ class Maintainer: def timers(self): cfg, s, now = self.cfg, self.state, time.time() + self.announce_hold() if now - s.get("last_health", 0) >= cfg["health_interval_seconds"]: s["last_health"] = now self.health_cycle() @@ -1440,7 +1592,7 @@ class Maintainer: 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 s.get("last_upgrade", 0) + 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 @@ -1455,6 +1607,12 @@ class Maintainer: 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…") @@ -1945,6 +2103,13 @@ def self_check(cfg): 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_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") 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") @@ -2016,6 +2181,12 @@ def main(): help="validate the code and config, then exit") ap.add_argument("--set-claude-token", action="store_true", help="store a token from `claude setup-token` in the config") + 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) @@ -2023,6 +2194,16 @@ def main(): return self_check(cfg) if args.set_claude_token: return set_claude_token(cfg) + 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 + 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: