diff --git a/docs/doctor-overview.md b/docs/doctor-overview.md index 817fcfb..359f6fa 100644 --- a/docs/doctor-overview.md +++ b/docs/doctor-overview.md @@ -45,6 +45,21 @@ and is off by default for a whole host or cluster scope. It does not perform repairs. `--json` returns structured evidence without AI output. These are read-only checks; any suggested remediation should be reviewed separately. +For native K3s on the Orange Pi, `doctor opi5` collects the K3s service state, +data and runtime mount identities, USB ext4 candidates and recent storage +errors. If it detects a stale read-only mount whose device disappeared, it +offers `./jeannie doctor opi5 --repair-k3s`. That explicit local CLI action +checks the selected profile, pinned cluster identity, exclusive runtime and +operation locks, and requires failed or inactive K3s and one unmounted USB +ext4 partition. Before stopping private K3s workloads, it mounts the candidate +read-only with journal replay disabled and checks its K3s CA against the pinned +identity. It then unmounts the stale mounts without force, remounts the SSD, +verifies the CA and bind mount, starts K3s, and checks the live cluster identity. +It does not format a disk, run filesystem repair, or recreate the cluster. +If any mount is busy or a check fails, recovery stops; the report identifies the +last failure and further investigation is needed. A healthy K3s API does not +prove application health. The local runtime repair is refused through the API. + The Gitea runner has a specific diagnosis: it compares the live Argo CD revision and Deployment with the committed zero-replica configuration, then checks the Debian runner service. If the installed host service is inactive, diff --git a/scripts/cluster-runtime-guard.py b/scripts/cluster-runtime-guard.py index bc322fe..8fd2dac 100644 --- a/scripts/cluster-runtime-guard.py +++ b/scripts/cluster-runtime-guard.py @@ -58,7 +58,7 @@ def is_competing_cluster_vm(vmid, name, cluster_vmids): return vmid in cluster_vmids or name.startswith(('pimox-cp-', 'pimox-worker-')) -def check(profile=None, vm_start=False): +def check(profile=None, vm_start=False, require_storage=True): inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text()) profiles = inventory["cluster"]["profiles"] selected = profile or resolve()["profile"] @@ -69,7 +69,7 @@ def check(profile=None, vm_start=False): if os.environ.get(variable, runtime) != runtime: raise RuntimeError(f"{variable} conflicts with profile {selected}; expected {runtime}") required_mount = profiles[selected].get("storage", {}).get("required_mount", "") - if required_mount: + if required_mount and require_storage: control = profiles[selected]["control_plane"] spec = importlib.util.spec_from_file_location("registry_storage_guard", REPO / "scripts/registry-storage-reconcile.py") storage = importlib.util.module_from_spec(spec) diff --git a/scripts/doctor-focus b/scripts/doctor-focus index 8c9da21..46fcde2 100644 --- a/scripts/doctor-focus +++ b/scripts/doctor-focus @@ -17,6 +17,8 @@ shown by status. There is no all-area doctor. --details Show supporting evidence. --all Include healthy checks (default). --item NAME Alternative to positional ITEM. + --repair-k3s Recover a confirmed stale Orange Pi K3s storage mount. + This changes host mounts and restarts K3s; local CLI only. Examples: ./jeannie doctor rpi @@ -30,6 +32,22 @@ doctor_focus_https() { curl -fsS -o /dev/null --connect-timeout 3 --max-time 8 "${LAB_PUBLIC_URL%/}/edge-health" } +doctor_focus_k3s_storage_report() { + local evidence summary severity + if ! evidence="$(python3 "${REPO_ROOT}/scripts/doctor-k3s-storage.py" inspect 2>&1)"; then + report_ui_emit warn "Orange Pi diagnostics" "K3s storage evidence" "Cannot inspect K3s storage" "${evidence}" + return 0 + fi + if printf '%s' "${evidence}" | python3 -c 'import json,sys; sys.exit(0 if json.load(sys.stdin).get("stale_readonly_mount") else 1)'; then + summary="Stale read-only K3s mount; the mounted device is no longer detected" + severity=warn + else + summary="No stale read-only K3s mount detected in this snapshot" + severity=ok + fi + report_ui_emit "${severity}" "Orange Pi diagnostics" "K3s storage evidence" "${summary}" "${evidence}" "./jeannie doctor opi5 --repair-k3s" +} + doctor_focus_application_fetch() { local name="$1" [[ "${name}" =~ ^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$ ]] || { echo "Invalid application name" >&2; return 1; } @@ -151,13 +169,28 @@ doctor_focus_extra() { report_ui_check warn "Kubernetes diagnostics" "Problem pods" "kubectl get pods -A -o wide" "" "" status_no_problem_pods report_ui_check warn "Kubernetes diagnostics" "Recent deployments" "kubectl get deployments -A" "" "" status_recent_deployments ;; - opi5) ;; + opi5) + if [[ "${LAB_CLUSTER_PROFILE:-}" == k3s && "${LAB_CLUSTER_RUNTIME:-}" == k3s && "${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-}" == "${LAB_PIMOX_HOST:-}" ]]; then + report_ui_enqueue doctor_focus_k3s_storage_report + fi + ;; esac } doctor_focus() { local scope="${1:-}" item="" rc=0 selected area check severity evidence direct=false local -a flags=() + if [[ "${1:-}" == opi5 && "${2:-}" == --repair-k3s ]]; then + [[ $# == 2 ]] || { echo "Usage: ./jeannie doctor opi5 --repair-k3s" >&2; return 2; } + require_debian_server "doctor opi5 --repair-k3s" + if [[ "${JEANNIE_REMOTE_SERVER:-false}" == true ]]; then + echo "K3s storage recovery requires the local Debian CLI." >&2 + return 2 + fi + record_change_journal "doctor-k3s-storage" "$@" + python3 "${REPO_ROOT}/scripts/doctor-k3s-storage.py" repair + return $? + fi case "${scope}" in -h|--help) doctor_focus_usage; return 0 ;; oci|rpi|opi5|debian|cluster) shift ;; diff --git a/scripts/doctor-k3s-storage-host.py b/scripts/doctor-k3s-storage-host.py new file mode 100644 index 0000000..f13a77e --- /dev/null +++ b/scripts/doctor-k3s-storage-host.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Orange Pi side of stale K3s storage diagnosis and guarded recovery. + +EXPECTED_CA, DATA_MOUNT, RUNTIME_PATH and STOP_SCRIPT are supplied by the +controller over SSH. This helper is never executed from untrusted inventory. +""" +import hashlib +import json +import os +from pathlib import Path +import re +import ssl +import subprocess +import sys +import tempfile + + +def run(command, check=True, timeout=30, input_text=None): + result = subprocess.run(command, input=input_text, text=True, capture_output=True, timeout=timeout) + if check and result.returncode: + raise RuntimeError(f"{command[0]} failed: {(result.stderr or result.stdout).strip()[-500:]}") + return result.stdout.strip() + + +def mount(target): + result = run(["findmnt", "-J", "-M", target, "-o", "TARGET,SOURCE,MAJ:MIN,OPTIONS"], check=False) + if not result: + return None + return (json.loads(result).get("filesystems") or [None])[0] + + +def disks(): + data = json.loads(run(["lsblk", "-J", "-o", "NAME,TYPE,MAJ:MIN,FSTYPE,UUID,MOUNTPOINTS,TRAN"])) + return data.get("blockdevices") or [] + + +def inspect(): + data, runtime = mount(DATA_MOUNT), mount("/var/lib/rancher/k3s") + devices = disks() + present = set() + candidates = [] + def visit(device, transport=None): + transport = device.get("tran") or transport + present.add(device.get("maj:min")) + if (device.get("type") == "part" and transport == "usb" and device.get("fstype") == "ext4" + and device.get("uuid") and not any(device.get("mountpoints") or [])): + candidates.append({"name": device.get("name"), "uuid": device["uuid"], "maj:min": device.get("maj:min")}) + for child in device.get("children") or []: + visit(child, transport) + for device in devices: + visit(device) + service = run(["systemctl", "is-active", "k3s"], check=False) or "unknown" + journal = run(["journalctl", "-k", "-b", "-n", "500", "--no-pager", "-o", "cat"], check=False, timeout=15) + errors = [line for line in journal.splitlines() if re.search(r"EXT4-fs.*error|I/O error|usb.*(?:disconnect|reset)", line, re.I)][-3:] + stale = bool(data and runtime and data.get("maj:min") and + "ro" in data.get("options", "").split(",") and "ro" in runtime.get("options", "").split(",") and + data.get("maj:min") == runtime.get("maj:min") and data.get("maj:min") not in present) + return {"service": service, "data_mount": data, "runtime_mount": runtime, + "stale_readonly_mount": stale, "reappeared_usb_ext4": candidates, "recent_storage_errors": errors} + + +def ca_fingerprint(path): + pem = path.read_text() + blocks = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", pem, flags=re.S) + if len(blocks) != 1: + raise RuntimeError("Expected exactly one K3s server CA certificate") + return hashlib.sha256(ssl.PEM_cert_to_DER_cert(blocks[0])).hexdigest() + + +def runtime_ca(root, relative): + root = Path(root).resolve() + runtime = (root / relative).resolve() + if not runtime.is_relative_to(root) or runtime == root: + raise RuntimeError("K3s runtime resolves outside the expected data mount") + return ca_fingerprint(runtime / "server/tls/server-ca.crt") + + +def repair(uuid): + if not re.fullmatch(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", uuid): + raise RuntimeError("Candidate filesystem UUID is invalid") + before = inspect() + candidates = before["reappeared_usb_ext4"] + if (not before["stale_readonly_mount"] or before["service"] not in ("failed", "inactive") or + len(candidates) != 1 or candidates[0]["uuid"] != uuid): + raise RuntimeError("Stale mount or unique reappeared SSD no longer matches the reviewed evidence") + source = "/dev/disk/by-uuid/" + uuid + relative = Path(RUNTIME_PATH).relative_to(DATA_MOUNT) + with tempfile.TemporaryDirectory(prefix="jeannie-k3s-check-") as directory: + run(["mount", "-o", "ro,noload", source, directory]) + try: + if runtime_ca(directory, relative) != EXPECTED_CA: + raise RuntimeError("Reappeared SSD does not contain the pinned K3s CA") + finally: + run(["umount", directory]) + print("Verified the SSD contains the pinned K3s CA; stopping private K3s workloads.", flush=True) + run(["bash"], timeout=90, input_text=STOP_SCRIPT) + run(["umount", "/var/lib/rancher/k3s"], timeout=60) + run(["umount", DATA_MOUNT], timeout=60) + run(["mount", source, DATA_MOUNT], timeout=60) + current = mount(DATA_MOUNT) + if not current or "rw" not in current.get("options", "").split(","): + raise RuntimeError("SSD did not mount read-write; K3s remains stopped") + if runtime_ca(DATA_MOUNT, relative) != EXPECTED_CA: + raise RuntimeError("Mounted K3s CA differs from pinned identity; K3s remains stopped") + run(["mount", "--bind", RUNTIME_PATH, "/var/lib/rancher/k3s"], timeout=60) + source_stat, runtime_stat = os.stat(RUNTIME_PATH), os.stat("/var/lib/rancher/k3s") + if (source_stat.st_dev, source_stat.st_ino) != (runtime_stat.st_dev, runtime_stat.st_ino): + raise RuntimeError("K3s bind mount differs from the SSD runtime directory") + run(["systemctl", "reset-failed", "k3s"]) + run(["systemctl", "start", "k3s"], timeout=300) + print("K3s started; verifying the pinned live cluster identity next.", flush=True) + + +if __name__ == "__main__": + try: + if sys.argv[1:] == ["inspect"]: + print(json.dumps(inspect())) + elif len(sys.argv) == 3 and sys.argv[1] == "repair": + repair(sys.argv[2]) + else: + raise RuntimeError("Invalid storage doctor action") + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print(f"K3s storage recovery stopped: {exc}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/doctor-k3s-storage.py b/scripts/doctor-k3s-storage.py new file mode 100644 index 0000000..40480ca --- /dev/null +++ b/scripts/doctor-k3s-storage.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Diagnose and recover a stale USB-backed K3s runtime on its selected host.""" +from contextlib import ExitStack +import fcntl +import importlib.util +import json +import os +from pathlib import Path +import shlex +import subprocess +import sys +import time + +REPO = Path(__file__).resolve().parents[1] + + +def load(name, filename): + spec = importlib.util.spec_from_file_location(name, REPO / "scripts" / filename) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def main(action): + runtime = load("doctor_storage_runtime", "cluster_runtime_context.py").resolve() + if runtime["profile"] != "k3s" or runtime["runtime"] != "k3s": + raise RuntimeError("Selected profile is not native K3s") + data = Path(runtime["required_mount"]) + target = Path(runtime["runtime_path"]) + if not data.is_absolute() or not target.is_absolute() or ".." in data.parts or ".." in target.parts or data == Path("/") or data == target or not target.is_relative_to(data): + raise RuntimeError("K3s runtime storage paths are invalid") + context = load("doctor_storage_context", "cluster-context.py") + registry = load("doctor_storage_ssh", "registry-storage-reconcile.py") + ctx = context.Context("k3s", runtime["kubeconfig"]) + binding = json.loads(ctx.binding.read_text()) if ctx.binding.exists() else {} + ca = binding.get("ca_sha256", "") + if action == "repair" and (not isinstance(ca, str) or len(ca) != 64 or any(c not in "0123456789abcdef" for c in ca)): + raise RuntimeError("Pinned K3s CA fingerprint is unavailable") + code = ("EXPECTED_CA = " + repr(ca) + "\nDATA_MOUNT = " + repr(str(data)) + "\nRUNTIME_PATH = " + repr(str(target)) + + "\nSTOP_SCRIPT = " + repr((REPO / "scripts/k3s-stop.sh").read_text()) + "\n" + + (REPO / "scripts/doctor-k3s-storage-host.py").read_text()) + + def remote(*args): + command = "sudo -n python3 - " + shlex.join(args) + result = subprocess.run(registry.ssh(runtime["host"], runtime["user"], runtime["key"], command), + input=code, text=True, capture_output=True, timeout=900) + if result.returncode: + raise RuntimeError((result.stderr or "Remote storage check failed").strip()[-1200:]) + return result.stdout.strip() + + if action == "inspect": + evidence = json.loads(remote("inspect")) + print(json.dumps(evidence, sort_keys=True)) + return + if action != "repair": + raise RuntimeError("Unknown K3s storage doctor action") + root = ctx.root + root.mkdir(parents=True, exist_ok=True, mode=0o700) + with ExitStack() as locks: + for path in [root.parent / ".runtime-pipeline.lock", *(root / f".{name}.operation.lock" for name in ("cluster", "platform", "apps"))]: + lock = locks.enter_context(path.open("a")) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + transition = root / "runtime-storage-transition.json" + if transition.exists() and json.loads(transition.read_text()).get("phase") != "complete": + raise RuntimeError("An unfinished K3s storage transition exists; recovery is refused") + ctx.observed(startup=True) + load("doctor_storage_guard", "cluster-runtime-guard.py").check("k3s", require_storage=False) + evidence = json.loads(remote("inspect")) + candidates = evidence.get("reappeared_usb_ext4") or [] + if not evidence.get("stale_readonly_mount") or evidence.get("service") not in ("failed", "inactive") or len(candidates) != 1: + raise RuntimeError("Recovery requires failed or inactive K3s, a stale read-only mount, and exactly one unmounted USB ext4 partition") + print("Verified evidence:", json.dumps(evidence, sort_keys=True), flush=True) + print("Recovering the stale K3s mount after checking the SSD against the pinned CA; busy mounts are not forced.", flush=True) + print(remote("repair", candidates[0]["uuid"]), flush=True) + deadline = time.monotonic() + 300 + while True: + try: + identity = ctx.check() + node = json.loads(context.capture(ctx.client() + ["--request-timeout=10s", "get", "node", ctx.expected_node, "-o", "json"])) + if not any(condition.get("type") == "Ready" and condition.get("status") == "True" for condition in (node.get("status", {}).get("conditions") or [])): + raise RuntimeError("K3s node is not Ready") + print("Pinned cluster identity verified:", json.dumps(identity, sort_keys=True), flush=True) + print(f"K3s node {ctx.expected_node} is Ready.", flush=True) + break + except (context.Refused, RuntimeError, subprocess.SubprocessError): + if time.monotonic() >= deadline: + raise RuntimeError("K3s started, but the pinned live cluster identity was not verified") + time.sleep(5) + + +if __name__ == "__main__": + try: + if len(sys.argv) != 2 or sys.argv[1] not in ("inspect", "repair"): + raise RuntimeError("Usage: doctor-k3s-storage.py inspect|repair") + main(sys.argv[1]) + except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError, BlockingIOError) as exc: + print(f"K3s storage doctor: {exc}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/doctor-narrative.py b/scripts/doctor-narrative.py index 5dca91e..adbbc47 100644 --- a/scripts/doctor-narrative.py +++ b/scripts/doctor-narrative.py @@ -19,6 +19,10 @@ def main(): print("\nWhat needs attention:") for row in problems: print(f"- {row[1]} / {row[2]}: {row[3]}") + if row[1:3] == ["Orange Pi diagnostics", "K3s storage evidence"] and row[3].startswith("Stale read-only K3s mount"): + print(" The former mounted device is absent. A reappeared disk is a candidate, not yet verified as the K3s volume.") + print(" Evidence comes from systemctl is-active k3s, findmnt, lsblk and the kernel journal on the Orange Pi.") + print(" To apply the guarded recovery: ./jeannie doctor opi5 --repair-k3s") match = re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*/[a-zA-Z0-9][a-zA-Z0-9_.-]* \(([a-zA-Z0-9][a-zA-Z0-9_.-]*)\)", row[2]) if row[1] == "Debian Compose" and match: if "desired state unknown" in row[3]: diff --git a/scripts/validate-homelab b/scripts/validate-homelab index 3d5b985..9db25a6 100755 --- a/scripts/validate-homelab +++ b/scripts/validate-homelab @@ -126,6 +126,7 @@ validate_unit_tests() { python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_status_app_snapshot.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_go_launchers.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_focus.py' + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_k3s_storage.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_report_ai_explain.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_model_lab.py' } diff --git a/tests/jeannie/test_doctor_focus.py b/tests/jeannie/test_doctor_focus.py index 2823767..eb516c9 100644 --- a/tests/jeannie/test_doctor_focus.py +++ b/tests/jeannie/test_doctor_focus.py @@ -23,6 +23,19 @@ def run_filter(item, rows): class DoctorFocusTests(unittest.TestCase): + def test_k3s_storage_repair_is_refused_through_remote_api(self): + code = r''' +source "$1" +require_debian_server() { :; } +record_change_journal() { printf 'unexpected journal\n'; } +python3() { printf 'unexpected repair\n'; } +JEANNIE_REMOTE_SERVER=true doctor_focus opi5 --repair-k3s +''' + result = subprocess.run(["bash", "-c", code, "test", str(DOCTOR)], text=True, capture_output=True) + self.assertEqual(result.returncode, 2) + self.assertIn("requires the local Debian CLI", result.stderr) + self.assertNotIn("unexpected", result.stdout) + def test_narrative_does_not_invent_or_execute_a_fix(self): with tempfile.TemporaryDirectory() as temp: rows = Path(temp) / "rows" diff --git a/tests/jeannie/test_doctor_k3s_storage.py b/tests/jeannie/test_doctor_k3s_storage.py new file mode 100644 index 0000000..8a5969a --- /dev/null +++ b/tests/jeannie/test_doctor_k3s_storage.py @@ -0,0 +1,82 @@ +"""Regression tests for evidence and safety gates; no host actions.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +SPEC = importlib.util.spec_from_file_location("doctor_k3s_host", ROOT / "scripts/doctor-k3s-storage-host.py") +host = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(host) +host.DATA_MOUNT = "/data" +host.RUNTIME_PATH = "/data/jeannie/k3s-runtime" +host.EXPECTED_CA = "a" * 64 +host.STOP_SCRIPT = "stop-only" +UUID = "19972338-9757-4f4b-89d7-c202df14a9aa" + + +class StorageDoctorTests(unittest.TestCase): + def test_stale_mount_is_distinguished_from_reappeared_partition(self): + stale = {"target": "/data", "source": "/dev/sda1", "maj:min": "8:1", "options": "ro,relatime"} + runtime = {"target": "/var/lib/rancher/k3s", "maj:min": "8:1", "options": "ro,relatime"} + devices = [{"name": "sdb", "type": "disk", "maj:min": "8:16", "tran": "usb", "children": [ + {"name": "sdb1", "type": "part", "maj:min": "8:17", "fstype": "ext4", "uuid": "uuid", "mountpoints": [None]}]}] + with mock.patch.object(host, "mount", side_effect=[stale, runtime]), \ + mock.patch.object(host, "disks", return_value=devices), \ + mock.patch.object(host, "run", side_effect=["failed", "EXT4-fs error on sda1"]): + result = host.inspect() + self.assertTrue(result["stale_readonly_mount"]) + self.assertEqual(result["reappeared_usb_ext4"][0]["maj:min"], "8:17") + + def test_ambiguous_or_running_service_never_changes_mounts(self): + for evidence in ({"stale_readonly_mount": True, "service": "active", "reappeared_usb_ext4": [{"uuid": UUID}]}, + {"stale_readonly_mount": True, "service": "failed", "reappeared_usb_ext4": [{"uuid": UUID}, {"uuid": "y"}]}, + {"stale_readonly_mount": False, "service": "failed", "reappeared_usb_ext4": [{"uuid": UUID}]}): + with self.subTest(evidence=evidence), mock.patch.object(host, "inspect", return_value=evidence), \ + mock.patch.object(host, "run") as run: + with self.assertRaises(RuntimeError): + host.repair(UUID) + run.assert_not_called() + + def test_wrong_ca_is_unmounted_before_any_service_stop(self): + evidence = {"stale_readonly_mount": True, "service": "failed", "reappeared_usb_ext4": [{"uuid": UUID}]} + with mock.patch.object(host, "inspect", return_value=evidence), \ + mock.patch.object(host, "runtime_ca", return_value="b" * 64), \ + mock.patch.object(host, "run", return_value="") as run: + with self.assertRaisesRegex(RuntimeError, "pinned K3s CA"): + host.repair(UUID) + commands = [call.args[0] for call in run.call_args_list] + self.assertEqual(commands[0][:3], ["mount", "-o", "ro,noload"]) + self.assertEqual(commands[1][0], "umount") + self.assertFalse(any(command[0] in ("bash", "systemctl") for command in commands)) + + def test_busy_data_mount_never_mounts_or_starts_k3s(self): + evidence = {"stale_readonly_mount": True, "service": "failed", "reappeared_usb_ext4": [{"uuid": UUID}]} + def run(command, **kwargs): + if command == ["umount", "/data"]: + raise RuntimeError("mount is busy") + return "" + with mock.patch.object(host, "inspect", return_value=evidence), \ + mock.patch.object(host, "runtime_ca", return_value=host.EXPECTED_CA), \ + mock.patch.object(host, "run", side_effect=run) as called: + with self.assertRaisesRegex(RuntimeError, "busy"): + host.repair(UUID) + commands = [call.args[0] for call in called.call_args_list] + self.assertFalse(any(command[:2] == ["systemctl", "start"] for command in commands)) + self.assertFalse(any(command[0] == "mount" and command[-1] == "/data" for command in commands)) + + def test_doctor_narrative_explains_stale_mount_and_repair_command(self): + with tempfile.TemporaryDirectory() as directory: + rows = Path(directory) / "rows" + rows.write_text("warn\tOrange Pi diagnostics\tK3s storage evidence\tStale read-only K3s mount; the mounted device is no longer detected\tdevice evidence\t\t\t\n") + result = subprocess.run(["python3", str(ROOT / "scripts/doctor-narrative.py"), str(rows), "Doctor"], + capture_output=True, text=True, check=True) + self.assertIn("candidate, not yet verified", result.stdout) + self.assertIn("doctor opi5 --repair-k3s", result.stdout) + + +if __name__ == "__main__": + unittest.main()