From 8bc51dd8dca2e6c490e8f054029c0ca77a2f8629 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Wed, 11 Nov 2026 15:55:07 -0600 Subject: [PATCH] Improve evidence and mitigation in doctor reports --- docs/doctor-overview.md | 9 +++ jeannie | 1 + scripts/doctor-focus | 22 +++++- scripts/doctor-narrative.py | 37 ++++++++++ scripts/doctor-runner-report | 78 +++++++++++++++++++++ scripts/report-ai-explain.py | 9 +++ scripts/validate-homelab | 1 + tests/jeannie/test_doctor_focus.py | 93 +++++++++++++++++++++++-- tests/jeannie/test_report_ai_explain.py | 10 +++ 9 files changed, 253 insertions(+), 7 deletions(-) create mode 100644 scripts/doctor-narrative.py create mode 100644 scripts/doctor-runner-report diff --git a/docs/doctor-overview.md b/docs/doctor-overview.md index 578363d..817fcfb 100644 --- a/docs/doctor-overview.md +++ b/docs/doctor-overview.md @@ -44,3 +44,12 @@ Use `--ai` to request the existing evidence-validated AI explanation, or 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. + +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, +the report proposes a specific start command and asks before executing it in +an interactive terminal. A noninteractive or remote invocation never applies +that mitigation; it prints the command for a human to review. A running +systemd service alone does not prove runner registration or job execution. +The deterministic runner report does not request an AI explanation. diff --git a/jeannie b/jeannie index 68a348c..ce931bc 100755 --- a/jeannie +++ b/jeannie @@ -28,6 +28,7 @@ JEANNIE_STEP_TOTAL=0 source "${REPO_ROOT}/scripts/report-ui" source "${REPO_ROOT}/scripts/status-focus" source "${REPO_ROOT}/scripts/doctor-focus" +source "${REPO_ROOT}/scripts/doctor-runner-report" source "${REPO_ROOT}/lib/jeannie/core.sh" source "${REPO_ROOT}/lib/jeannie/env.sh" source "${REPO_ROOT}/lib/jeannie/cluster-context.sh" diff --git a/scripts/doctor-focus b/scripts/doctor-focus index 6bd9a99..8c9da21 100644 --- a/scripts/doctor-focus +++ b/scripts/doctor-focus @@ -52,17 +52,18 @@ doctor_focus_application_lookup() { doctor_focus_application_evidence() { local name="$1" snapshot deployments namespace deployment state count=0 failed=0 snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${name}")" || return 1 + printf '$ kubectl --kubeconfig %q --request-timeout=10s -n argocd get application %q --ignore-not-found -o json | python3 %q\n' "${KUBECONFIG_PATH}" "${name}" "${REPO_ROOT}/scripts/doctor-application.py" printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" || return 1 deployments="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --deployments)" || return 1 while read -r namespace deployment; do [[ -n "${namespace}" && -n "${deployment}" ]] || continue ((count < 8)) || { echo "Additional deployments omitted"; break; } count=$((count + 1)) - printf 'deployment %s/%s: ' "${namespace}" "${deployment}" + printf '$ kubectl --kubeconfig %q --request-timeout=10s -n %q get deployment %q -o json | python3 %q --deployment\n' "${KUBECONFIG_PATH}" "${namespace}" "${deployment}" "${REPO_ROOT}/scripts/doctor-application.py" if state="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" get deployment "${deployment}" -o json 2>/dev/null)"; then printf '%s' "${state}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --deployment || failed=1 else - echo "unavailable" + echo "Deployment state unavailable." failed=1 fi done <<<"${deployments}" @@ -112,6 +113,7 @@ doctor_focus_compose_evidence() { [[ "${name}" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]] || { echo "Invalid container name" >&2; return 1; } local format='{{.State.Status}} restarts={{.RestartCount}} exit={{.State.ExitCode}} health={{if .State.Health}}{{.State.Health.Status}}{{else}}not-configured{{end}}' if [[ "${scope}" == debian ]]; then + printf '$ sudo -n docker inspect --format %q %q\n' "${format}" "${name}" timeout 10 sudo -n docker inspect --format "${format}" "${name}" return fi @@ -122,6 +124,8 @@ doctor_focus_compose_evidence() { *) return 2 ;; esac [[ -n "${host}" && -n "${user}" ]] || { echo "Host or user is missing from inventory" >&2; return 1; } + printf '$ ssh -n -i %q -o BatchMode=yes -o ConnectTimeout=3 -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes %q %q\n' \ + "${key}" "${user}@${host}" "sudo -n docker inspect --format '${format}' '${name}'" timeout 10 ssh -n -i "${key}" -o BatchMode=yes -o ConnectTimeout=3 \ -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes "${user}@${host}" \ "sudo -n docker inspect --format '${format}' '${name}'" @@ -230,7 +234,19 @@ doctor_focus() { fi fi ((REPORT_UI_FAILURES == 0)) || rc=1 - report_ui_render "Jeannie Doctor: ${scope}${item:+ / ${item}}" + if [[ "${item}" == gitea-runner && "${area}" == "Kubernetes apps" && "${REPORT_UI_JSON}" != true ]]; then + doctor_runner_report || rc=$? + report_ui_cleanup + return "${rc}" + fi + if [[ "${REPORT_UI_JSON}" == true ]]; then + report_ui_render "Jeannie Doctor: ${scope}${item:+ / ${item}}" + else + python3 "${REPO_ROOT}/scripts/doctor-narrative.py" "${REPORT_UI_ROWS_FILE}" "Jeannie Doctor: ${scope}${item:+ / ${item}}" + if truthy "${REPORT_UI_LOCAL_RCA:-false}"; then + report_ui_local_rca "Jeannie Doctor: ${scope}${item:+ / ${item}}" + fi + fi report_ui_cleanup return "${rc}" } diff --git a/scripts/doctor-narrative.py b/scripts/doctor-narrative.py new file mode 100644 index 0000000..52cf89b --- /dev/null +++ b/scripts/doctor-narrative.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Render collected doctor evidence without inventing a repair.""" + +import sys + + +def main(): + rows = [] + with open(sys.argv[1], encoding="utf-8") as stream: + for line in stream: + fields = (line.rstrip("\n").split("\t") + [""] * 8)[:8] + rows.append(fields) + print(sys.argv[2]) + print("=" * len(sys.argv[2])) + problems = [row for row in rows if row[0] in ("warn", "fail")] + if problems: + print("\nWhat needs attention:") + for row in problems: + print(f"- {row[1]} / {row[2]}: {row[3]}") + else: + print("\nNo failing or warning checks were observed.") + print("\nCollected evidence:") + for status, area, check, summary, detail, *_ in rows: + if status == "skip": + continue + print(f"- {area} / {check}: {summary}") + if detail and detail != summary: + print(f" {detail}") + if not rows: + print("- No evidence was collected.") + if problems: + print("\nNo specific automatic mitigation has been established from these checks.") + print("Review the evidence and use a focused doctor before changing the service.") + + +if __name__ == "__main__": + main() diff --git a/scripts/doctor-runner-report b/scripts/doctor-runner-report new file mode 100644 index 0000000..7608742 --- /dev/null +++ b/scripts/doctor-runner-report @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Sourced by Jeannie. This diagnosis and its single optional mitigation are +# deliberately limited to the Debian-hosted Gitea Actions runner. + +doctor_runner_report() { + local app deployment host configured revision head state load rc=0 answer baseline=false + local kubeconfig="${KUBECONFIG_PATH}" + printf 'Gitea Actions runner\n====================\n' + printf 'Profile: %s (%s)\n\n' "${LAB_CLUSTER_PROFILE:-unknown}" "${LAB_CLUSTER_RUNTIME:-unknown}" + + printf 'Evidence from the selected cluster:\n' + printf '$ kubectl --kubeconfig %q --request-timeout=10s -n argocd get application gitea-runner -o jsonpath=\047{.status.health.status}{" "}{.status.sync.status}{" "}{.status.sync.revision}\047\n' "${kubeconfig}" + app="$(kubectl --kubeconfig "${kubeconfig}" --request-timeout=10s -n argocd get application gitea-runner -o jsonpath='{.status.health.status}{" "}{.status.sync.status}{" "}{.status.sync.revision}' 2>&1)" || rc=1 + printf '%s\n' "${app}" + printf '$ kubectl --kubeconfig %q --request-timeout=10s -n gitea-runner get deployment gitea-runner -o jsonpath=\047desired={.spec.replicas} ready={.status.readyReplicas} available={.status.availableReplicas}\047\n' "${kubeconfig}" + deployment="$(kubectl --kubeconfig "${kubeconfig}" --request-timeout=10s -n gitea-runner get deployment gitea-runner -o jsonpath='desired={.spec.replicas} ready={.status.readyReplicas} available={.status.availableReplicas}' 2>&1)" || rc=1 + printf '%s\n\n' "${deployment}" + + printf 'Evidence from the Debian host:\n' + printf '$ systemctl show homelab-gitea-runner.service -p LoadState -p ActiveState\n' + host="$(systemctl show homelab-gitea-runner.service -p LoadState -p ActiveState 2>&1)" || rc=1 + printf '%s\n\n' "${host}" + state="$(printf '%s\n' "${host}" | sed -n 's/^ActiveState=//p')" + load="$(printf '%s\n' "${host}" | sed -n 's/^LoadState=//p')" + read -r _ _ revision <<<"${app}" + head="$(git -C "${REPO_ROOT}" rev-parse HEAD 2>/dev/null || true)" + configured="$(git -C "${REPO_ROOT}" show HEAD:apps/gitea-runner/deployment.yaml 2>/dev/null | awk '/^ replicas:/ && !seen {print $2; seen=1}')" || configured="" + + if [[ "${rc}" != 0 ]]; then + echo 'Diagnosis: A required check failed; the runner state cannot be established from this report.' + echo 'No mitigation is proposed until access to the failed check is restored.' + return 1 + fi + if [[ "${deployment}" == desired=0\ * && "${configured}" == 0 && -n "${revision}" && "${revision}" == "${head}" && "${app}" == *" Synced "* ]]; then + baseline=true + printf 'Diagnosis: Argo CD reports %s, but the synced repository intentionally sets the Kubernetes runner to zero replicas. The Debian service is the intended CI runner.\n' "${app%% *}" + printf '$ git -C %q show HEAD:apps/gitea-runner/deployment.yaml | awk \047/^ replicas:/ && !seen {print $2; seen=1}\047\n%s\n' "${REPO_ROOT}" "${configured}" + else + echo 'Diagnosis: The Argo CD state and live deployment are shown above. The local zero-replica configuration cannot be confirmed as the synced revision, so its intent is not assumed.' + fi + + if [[ "${load}" == loaded && "${state}" == active ]]; then + echo 'The Debian CI runner service is active; this alone does not verify registration or job execution.' + if [[ ( "${baseline}" == true && "${app}" == "Progressing Synced "* ) || "${app}" == "Healthy Synced "* ]]; then + echo 'No runner restart or Kubernetes scaling is indicated by these checks.' + return 0 + fi + echo 'The Kubernetes application still needs investigation. No specific mitigation is established.' + return 1 + fi + if [[ "${load}" != loaded ]]; then + echo 'The Debian runner service is not loaded. Inspect its installation before choosing a repair.' + echo 'Read-only check: systemctl status homelab-gitea-runner.service --no-pager -l' + return 1 + fi + if [[ "${state}" != inactive && "${state}" != failed ]]; then + printf 'The Debian runner service is %s. Inspect its state before choosing a repair.\n' "${state:-unknown}" + echo 'Read-only check: systemctl status homelab-gitea-runner.service --no-pager -l' + return 1 + fi + printf 'The Debian CI runner service is %s. Starting it may restore job execution; this does not verify runner registration or job execution.\n' "${state}" + echo 'Proposed mitigation: sudo -n systemctl start homelab-gitea-runner.service' + if [[ ! -t 0 || ! -t 1 ]]; then + echo 'Approval is required; run the command above on Debian or rerun this doctor in an interactive terminal.' + return 1 + fi + read -r -p 'Apply this mitigation? [y/N] ' answer || answer="" + if [[ "${answer}" != y && "${answer}" != Y ]]; then + echo 'Mitigation not applied.' + return 1 + fi + if ! sudo -n systemctl start homelab-gitea-runner.service; then + echo 'The start command failed. Inspect the service journal.' + return 1 + fi + echo '$ systemctl is-active homelab-gitea-runner.service' + systemctl is-active homelab-gitea-runner.service || return 1 +} diff --git a/scripts/report-ai-explain.py b/scripts/report-ai-explain.py index e3e47ad..827257d 100644 --- a/scripts/report-ai-explain.py +++ b/scripts/report-ai-explain.py @@ -85,6 +85,15 @@ def validate(answer, report): raise ValueError("invalid possible cause") prose(cause["hypothesis"], 400) refs(cause["check_ids"]) + cited = " ".join( + f"{checks[identifier].get('summary', '')} {checks[identifier].get('detail', '')}" + for identifier in cause["check_ids"] + ).lower() + claim = cause["hypothesis"].lower() + if ("desired=0" in cited or "health=progressing" in cited) and re.search( + r"\b(?:is|are)\s+(?:healthy|running)\b|\bno\s+(?:errors|issues|problems)\b", claim + ): + raise ValueError("hypothesis asserts health unsupported by the cited check") missing = answer["missing_evidence"] if not isinstance(missing, list) or len(missing) > 4: raise ValueError("invalid missing evidence") diff --git a/scripts/validate-homelab b/scripts/validate-homelab index 75fecc7..89743ac 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_report_ai_explain.py' } main() { diff --git a/tests/jeannie/test_doctor_focus.py b/tests/jeannie/test_doctor_focus.py index 12985de..fe7c32d 100644 --- a/tests/jeannie/test_doctor_focus.py +++ b/tests/jeannie/test_doctor_focus.py @@ -2,6 +2,8 @@ import json import subprocess import sys import os +import pty +import tempfile import unittest from pathlib import Path @@ -11,6 +13,8 @@ FILTER = ROOT / "scripts" / "doctor-filter.py" APP = ROOT / "scripts" / "doctor-application.py" DOCTOR = ROOT / "scripts" / "doctor-focus" RPI_OS = ROOT / "scripts" / "doctor-rpi-os.py" +RUNNER_REPORT = ROOT / "scripts" / "doctor-runner-report" +NARRATIVE = ROOT / "scripts" / "doctor-narrative.py" def run_filter(item, rows): @@ -19,6 +23,84 @@ def run_filter(item, rows): class DoctorFocusTests(unittest.TestCase): + def test_narrative_does_not_invent_or_execute_a_fix(self): + with tempfile.TemporaryDirectory() as temp: + rows = Path(temp) / "rows" + rows.write_text("warn\tService\tContainer\tUnavailable\tconnection refused\tdeploy-service\t\t\n") + result = subprocess.run([sys.executable, str(NARRATIVE), str(rows), "Doctor"], + capture_output=True, text=True, check=True) + self.assertIn("Unavailable", result.stdout) + self.assertIn("connection refused", result.stdout) + self.assertIn("No specific automatic mitigation", result.stdout) + self.assertNotIn("deploy-service", result.stdout) + + def runner_report(self, service_state): + code = r''' +source "$1" +kubectl() { + case "$*" in + *"get application"*) printf 'Progressing Synced abc123' ;; + *"get deployment"*) printf 'desired=0 ready=0 available=0' ;; + *) return 1 ;; + esac +} +git() { case "$*" in *"rev-parse HEAD"*) printf 'abc123\n';; *"show HEAD:"*) printf ' replicas: 0\n';; *) return 1;; esac; } +systemctl() { printf 'LoadState=loaded\nActiveState=%s\n' "$SERVICE_STATE"; } +doctor_runner_report +''' + env = os.environ.copy() + env.update(REPO_ROOT=str(ROOT), KUBECONFIG_PATH="/tmp/kubeconfig", + SERVICE_STATE=service_state) + return subprocess.run(["bash", "-c", code, "test", str(RUNNER_REPORT)], + env=env, text=True, capture_output=True) + + def test_runner_expected_zero_and_active_host_needs_no_fix(self): + result = self.runner_report("active") + self.assertEqual(result.returncode, 0) + self.assertIn("intentionally sets the Kubernetes runner to zero", result.stdout) + self.assertIn("desired=0 ready=0", result.stdout) + self.assertIn("No runner restart", result.stdout) + self.assertNotIn("Proposed mitigation", result.stdout) + + def test_inactive_runner_proposes_start_without_noninteractive_execution(self): + result = self.runner_report("inactive") + self.assertEqual(result.returncode, 1) + self.assertIn("sudo -n systemctl start homelab-gitea-runner.service", result.stdout) + self.assertIn("Approval is required", result.stdout) + + def test_runner_mitigation_requires_explicit_interactive_yes(self): + code = r''' +source "$1" +kubectl() { + case "$*" in + *"get application"*) printf 'Progressing Synced abc123' ;; + *"get deployment"*) printf 'desired=0 ready=0 available=0' ;; + esac +} +git() { case "$*" in *"rev-parse HEAD"*) printf 'abc123\n';; *"show HEAD:"*) printf ' replicas: 0\n';; esac; } +systemctl() { if [[ "$1" == show ]]; then printf 'LoadState=loaded\nActiveState=inactive\n'; else printf 'active\n'; fi; } +sudo() { printf 'started' >"$MARKER"; } +doctor_runner_report +''' + for answer, expected in (("n", False), ("y", True)): + with self.subTest(answer=answer), tempfile.TemporaryDirectory() as temp: + marker = Path(temp) / "started" + env = os.environ.copy() + env.update(REPO_ROOT=str(ROOT), KUBECONFIG_PATH="/tmp/kubeconfig", MARKER=str(marker)) + master, slave = pty.openpty() + try: + process = subprocess.Popen(["bash", "-c", code, "test", str(RUNNER_REPORT)], + stdin=slave, stdout=slave, stderr=slave, env=env) + os.close(slave) + slave = -1 + os.write(master, (answer + "\n").encode()) + process.wait(timeout=10) + self.assertEqual(marker.exists(), expected) + finally: + os.close(master) + if slave >= 0: + os.close(slave) + def test_select_exact_application_or_compose_service(self): rows = ("warn\tKubernetes apps\tgitea-runner\tProgressing\t\t\t\t\n" "ok\tDebian Compose\thomelab-gitea/gitea (homelab-gitea)\tUp\t\t\t\t\n") @@ -76,6 +158,7 @@ status_focus_collect() { report_ui_finish() { REPORT_UI_FAILURES=1; } doctor_focus_application_evidence() { printf 'deployment replicas: desired=1 ready=0\n'; } report_ui_emit() { printf 'evidence-requested:%s %s\n' "$3" "$5"; } +truthy() { return 1; } report_ui_render() { cat "$REPORT_UI_ROWS_FILE"; } report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; } doctor_focus cluster runner @@ -101,18 +184,19 @@ status_focus_compose_report() { :; } report_ui_finish() { REPORT_UI_FAILURES=0; } doctor_focus_application_evidence() { printf 'desired=1 ready=0\n'; } report_ui_emit() { printf 'evidence:%s\n' "$5"; } -report_ui_render() { printf 'ai=%s\n' "$REPORT_UI_LOCAL_RCA"; cat "$REPORT_UI_ROWS_FILE"; } +truthy() { [[ "$1" == true ]]; } +report_ui_local_rca() { printf 'ai=%s\n' "$REPORT_UI_LOCAL_RCA"; } report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; } -doctor_focus gitea-runner +doctor_focus sample-runner ''' env = os.environ.copy() env.update(REPO_ROOT=str(ROOT), APP_JSON=json.dumps({ - "metadata": {"name": "gitea-runner"}, "status": { + "metadata": {"name": "sample-runner"}, "status": { "health": {"status": "Progressing"}, "sync": {"status": "Synced"}}})) result = subprocess.run(["bash", "-c", code, "test", str(DOCTOR)], env=env, capture_output=True, text=True, check=True) self.assertIn("ai=true", result.stdout) - self.assertIn("gitea-runner", result.stdout) + self.assertIn("sample-runner", result.stdout) self.assertIn("desired=1 ready=0", result.stdout) def test_rpi_os_snapshot_reports_disk_and_memory_pressure(self): @@ -141,6 +225,7 @@ status_focus_compose_report() { report_ui_finish() { REPORT_UI_FAILURES=0; } doctor_focus_compose_evidence() { printf 'scope=%s restarts=2\n' "$1"; } report_ui_emit() { printf 'evidence:%s %s\n' "$1" "$5"; } +truthy() { return 1; } report_ui_render() { cat "$REPORT_UI_ROWS_FILE"; } report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; } doctor_focus homelab-gitea/gitea diff --git a/tests/jeannie/test_report_ai_explain.py b/tests/jeannie/test_report_ai_explain.py index 64a9042..e775960 100644 --- a/tests/jeannie/test_report_ai_explain.py +++ b/tests/jeannie/test_report_ai_explain.py @@ -48,6 +48,16 @@ class EvidenceExplanationTests(unittest.TestCase): with self.assertRaises(ValueError): MODULE.validate(dict(self.answer, extra="unexpected"), self.report) + def test_progressing_zero_replicas_cannot_be_claimed_healthy(self): + report = {"checks": [{"id": "C01", "area": "runner", "check": "state", + "summary": "health=Progressing", "detail": "desired=0 ready=0", + "read_only_command": None}]} + answer = {"observed_facts": ["C01"], "possible_causes": [ + {"hypothesis": "The runner is healthy and running", "check_ids": ["C01"]}], + "missing_evidence": [], "next_command": None} + with self.assertRaises(ValueError): + MODULE.validate(answer, report) + def test_report_excludes_mutating_fixes_and_redacts_token(self): with tempfile.TemporaryDirectory() as directory: rows = Path(directory) / "rows"