#!/usr/bin/env python3 """kernel-cleanup-rule.py — the old-kernel clean-up RULE, as a read-only plan. EVIDENCE, NOT PRODUCT (spike 2026-11-10). It runs ON the Proxmox host as root (`ssh demo-hp python3 - [options] < kernel-cleanup-rule.py`). It changes nothing: it reads dpkg, `uname -r`, the kernel step's state file, the one-shot flag and grub.cfg, and it asks apt for a SIMULATION (`apt-get -s`). It prints the keep set, the removal set and every reason to refuse. Exit code: 0 = the plan is safe to run (or there is nothing to remove), 3 = REFUSED. The removal itself is one `apt-get purge` of the exact names this prints; a person ran it by hand in the spike. The rule (the brief's, `11-os-updates.md` §5.11.1): KEEP the running kernel; the last kernel that booted well before it (the step's `from`, else the next lower installed one); the newest installed kernel; and every kernel the kernel lane still names: the step's `to`, the GRUB default in grub.cfg, the pinned default file, the one-shot flag, an operator's proxmox-boot pin. REMOVE every other installed kernel image package, by its exact name. REFUSE the whole clean-up when P1 a kernel step is in a phase that has not ended (staged, oneshot, judging, reverting) or in an unknown phase; P2 the one-shot flag names a kernel (a one-shot boot is armed); P3 the pinned default and grub.cfg's default do not name the same kernel, or that kernel is not installed; K1 a keep-kernel is in the removal set; N1 a name in the removal set is not an installed kernel image package; S1 the simulation fails, or would install or upgrade anything; S2 the simulation would remove anything that is not in the removal set (a meta-package, proxmox-ve, anything). Test inputs (negative controls, SIMULATION ONLY — nothing is ever removed by this file): --pretend-set a,b,c use this removal set in place of the computed one --pretend-add a,b add these names to the computed removal set --pretend-phase NAME judge as if the kernel step were in this phase """ import json, os, re, subprocess, sys STATE = "/var/lib/felhom-kernel/state.json" DEFAULT_CFG = "/etc/default/grub.d/zz-felhom-kernel-default.cfg" GRUB_CFG = "/boot/grub/grub.cfg" ONESHOT_ENV = "/boot/efi/EFI/felhom/oneshot.env" PIN_FILE = "/etc/kernel/proxmox-boot-pin" IMAGE_RE = re.compile(r"^proxmox-kernel-([0-9]+\.[0-9]+\.[0-9]+-[0-9]+-pve)(-signed)?$") # = the wrapper's KERNEL_IMAGE_RE KVER_RE = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+-[0-9]+-pve") ENDED = ("good", "self_reverted", "revert_failed", "fell_back", "cancelled", "none") # the wrapper's phases, minus KERNEL_ACTIVE def sh(cmd): p = subprocess.run(cmd, capture_output=True, text=True) return p.returncode, p.stdout, p.stderr def key(kver): return tuple(int(x) for x in re.findall(r"\d+", kver)) def read(path): try: return open(path, encoding="utf-8", errors="replace").read() except OSError: return None def opt(name): return sys.argv[sys.argv.index(name) + 1] if name in sys.argv else None def main(): refuse = [] # --- what is installed (dpkg status "ii" only) --- _, out, _ = sh(["dpkg-query", "-W", "-f", "${Package}\t${db:Status-Abbrev}\n", "proxmox-kernel-*"]) images = {} # kver -> package name for line in out.splitlines(): name, _, st = line.partition("\t") m = IMAGE_RE.match(name) if m and st.strip() == "ii": images[m.group(1)] = name running = os.uname().release newest = max(images, key=key) if images else None # --- the kernel lane's own records --- raw = read(STATE) st = json.loads(raw) if raw else {} phase = opt("--pretend-phase") or st.get("phase", "none") if phase not in ENDED: refuse.append(f"P1 a kernel step is in phase {phase!r} — not ended") flag = "" if os.path.exists(ONESHOT_ENV): _, o, _ = sh(["grub-editenv", ONESHOT_ENV, "list"]) flag = dict(l.partition("=")[::2] for l in o.splitlines()).get("felhom_next", "") if flag: refuse.append(f"P2 the one-shot flag names {flag!r}") cfg = read(GRUB_CFG) or "" m = re.search(r'^\s*set default="[^"]*?(%s)[^"]*"' % KVER_RE.pattern, cfg, re.M) grub_default = m.group(1) if m else None m = KVER_RE.search(read(DEFAULT_CFG) or "") pinned = m.group(0) if m else None if pinned is None or pinned != grub_default or pinned not in images: refuse.append(f"P3 pinned default {pinned!r}, grub.cfg default {grub_default!r} — not the same installed kernel") m = KVER_RE.search(read(PIN_FILE) or "") boot_pin = m.group(0) if m else None # --- the keep set --- keep = {} def k(kver, why): if kver: keep.setdefault(kver, []).append(why) k(running, "running") last_good = st.get("from") if st.get("to") == running and st.get("from") in images else None if not last_good: lower = [v for v in images if key(v) < key(running)] last_good = max(lower, key=key) if lower else None k(last_good, "next lower installed kernel (no step record names the last good one)") else: k(last_good, "the last kernel that booted well before the running one (state.json `from`)") k(newest, "newest installed") k(st.get("from"), "kernel step `from` (a self-revert boots it)") k(st.get("to"), "kernel step `to`") k(st.get("default_before"), "kernel step `default_before`") k(grub_default, "GRUB default in grub.cfg") k(pinned, "pinned default file") k(flag and (KVER_RE.search(flag) or [None])[0], "one-shot flag") k(boot_pin, "operator's proxmox-boot pin") if running not in images: refuse.append(f"K1 the running kernel {running} is not an installed image package — the box is not as expected") # --- the removal set: exact package names --- computed = sorted((images[v] for v in images if v not in keep), key=lambda n: key(IMAGE_RE.match(n).group(1))) removal = list(computed) if opt("--pretend-set") is not None: removal = [x for x in opt("--pretend-set").split(",") if x] if opt("--pretend-add"): removal += [x for x in opt("--pretend-add").split(",") if x] by_name = {n: v for v, n in images.items()} for n in removal: if n not in by_name: refuse.append(f"N1 {n} is not an installed kernel image package") elif by_name[n] in keep: refuse.append(f"K1 {n} is a keep-kernel ({'; '.join(keep[by_name[n]])})") # --- apt's simulation of exactly that set --- sim = {"rc": None, "removes": [], "installs": []} if removal: rc, o, e = sh(["apt-get", "-s", "-q", "-o", "Debug::NoLocking=1", "purge"] + removal) sim["rc"] = rc sim["removes"] = sorted({l.split()[1] for l in o.splitlines() if l.startswith(("Remv ", "Purg "))}) sim["installs"] = sorted({l.split()[1] for l in o.splitlines() if l.startswith(("Inst ", "Conf "))}) if rc != 0: refuse.append("S1 the simulation failed: " + ((e or o).strip().splitlines() or ["?"])[-1][:200]) if sim["installs"]: refuse.append(f"S1 the simulation would install or configure {', '.join(sim['installs'][:6])}") extra = [p for p in sim["removes"] if p not in removal] if extra: refuse.append(f"S2 the simulation would also remove {', '.join(extra[:8])} — not in the removal set") missing = [p for p in removal if p not in sim["removes"] and p in by_name] if missing and rc == 0: refuse.append(f"S1 the simulation does not remove {', '.join(missing[:6])}") verdict = "REFUSED" if refuse else ("NOTHING TO REMOVE" if not removal else "SAFE TO RUN") res = {"host": os.uname().nodename, "running": running, "newest": newest, "phase": phase, "step": {x: st.get(x) for x in ("step_id", "from", "to", "default_before", "result_at")}, "oneshot_flag": flag, "grub_default": grub_default, "pinned_default": pinned, "boot_pin": boot_pin, "installed": {v: images[v] for v in sorted(images, key=key)}, "keep": {v: keep[v] for v in sorted(keep, key=key)}, "computed_removal": computed, "removal": removal, "pretend": [a for a in sys.argv[1:]], "simulation": sim, "refuse": refuse, "verdict": verdict} print(json.dumps(res, indent=1)) print(f"\nVERDICT: {verdict}") for r in refuse: print(" REFUSE " + r) if not refuse and removal: print(" the one command: apt-get -y -q purge " + " ".join(removal)) return 3 if refuse else 0 sys.exit(main())