diff --git a/docs/status-overview.md b/docs/status-overview.md index e43f000..e892aeb 100644 --- a/docs/status-overview.md +++ b/docs/status-overview.md @@ -34,6 +34,16 @@ SSH diagnostics are kept separate from the container data, and login banners are ignored only before the remote snapshot marker. Unexpected data inside the snapshot remains an error. +For Debian Compose services, record the operator's expected state explicitly: +`./jeannie compose-intent stopped PROJECT/SERVICE` or +`./jeannie compose-intent running PROJECT/SERVICE`. Use `list` to inspect and +`clear PROJECT/SERVICE` to forget it. These commands only record intent and do +not operate containers. A recorded stopped service that is actually stopped is +reported as expected; if it is running, the discrepancy is a warning. Services +without a record remain unknown when stopped. Intent is stored locally under +the Jeannie state directory and is not inferred from Docker's exit code. Remote +hosts are not covered by this record. + The cluster scope lists Argo CD application health and sync state from one snapshot. Degraded or missing applications are failures; progressing, unknown, or out-of-sync applications are warnings. These are Argo CD's reported states, diff --git a/jeannie b/jeannie index cd0a50d..818fd07 100755 --- a/jeannie +++ b/jeannie @@ -87,6 +87,7 @@ Build And Bootstrap goose-graph [question] Explore the repo with Goose and Graphify. ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]|doctor-auto-rank REPORT|doctor-add-external REPORT RANKING MODEL|doctor-rank REPORT REVIEW} Manage AI experiments. + compose-intent {stopped|running|clear|list} [PROJECT/SERVICE...] Record Debian Compose desired state. lab-window Apply the scheduled lab power window. deploy-omniroute Deploy the OmniRoute LLM routing gateway. deploy-hermes Deploy the Hermes agent (git-install + venv + gateway service). @@ -323,6 +324,10 @@ case "${1:-}" in esac case "${1:-}" in + compose-intent) + require_debian_server "compose-intent" + python3 "${REPO_ROOT}/scripts/compose-intent.py" --file "${HOMELAB_STATE_DIR}/compose-intent.json" "${@:2}" + ;; ai-lab) require_debian_server "ai-lab" case "${2:-plan}" in diff --git a/scripts/compose-intent.py b/scripts/compose-intent.py new file mode 100644 index 0000000..01d96da --- /dev/null +++ b/scripts/compose-intent.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Record expected state for Debian Compose services; never operates Docker.""" +import argparse +import fcntl +import json +import os +from pathlib import Path +import re +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--file", type=Path, required=True) + parser.add_argument("action", choices=("stopped", "running", "clear", "list")) + parser.add_argument("services", nargs="*") + args = parser.parse_args() + if (args.action == "list") != (not args.services): + parser.error("list takes no services; other actions require project/service names") + if any(not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*/[a-zA-Z0-9][a-zA-Z0-9_.-]*", name) for name in args.services): + parser.error("services must be exact project/service names") + args.file.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + with (args.file.parent / (args.file.name + ".lock")).open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + data = json.loads(args.file.read_text()) if args.file.exists() else {"version": 1, "services": {}} + if data.get("version") != 1 or not isinstance(data.get("services"), dict): + raise ValueError("invalid Compose intent record") + if args.action == "list": + print(json.dumps(data, indent=2, sort_keys=True)) + return + for name in args.services: + if args.action == "clear": + data["services"].pop(name, None) + else: + data["services"][name] = args.action + fd, temporary = tempfile.mkstemp(prefix=".compose-intent-", dir=args.file.parent) + try: + with os.fdopen(fd, "w") as stream: + json.dump(data, stream, indent=2, sort_keys=True) + stream.write("\n") + os.replace(temporary, args.file) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + print("Recorded expected state only; no containers were started or stopped.") + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, AttributeError) as exc: + raise SystemExit(f"Compose intent: {exc}") diff --git a/scripts/doctor-narrative.py b/scripts/doctor-narrative.py index 52cf89b..5dca91e 100644 --- a/scripts/doctor-narrative.py +++ b/scripts/doctor-narrative.py @@ -1,6 +1,8 @@ #!/usr/bin/env python3 """Render collected doctor evidence without inventing a repair.""" +import re +import shlex import sys @@ -17,9 +19,19 @@ def main(): print("\nWhat needs attention:") for row in problems: print(f"- {row[1]} / {row[2]}: {row[3]}") + 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]: + print(" The container is unhealthy or not running; whether it should be running is not recorded.") + elif "operator recorded expected state: stopped" in row[3]: + print(" The observed state differs from the operator's recorded stopped state.") + print(" Read-only next check:") + print(" $ sudo -n docker inspect --format 'state={{.State.Status}} exit={{.State.ExitCode}} restarts={{.RestartCount}}' " + shlex.quote(match.group(1))) else: print("\nNo failing or warning checks were observed.") print("\nCollected evidence:") + if any(row[1] == "Debian Compose" for row in rows): + print("$ sudo -n docker ps -a --filter label=com.docker.compose.project --format '{{json .}}'") for status, area, check, summary, detail, *_ in rows: if status == "skip": continue @@ -30,7 +42,7 @@ def main(): 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.") + print("Record the intended state or inspect the affected service before making changes.") if __name__ == "__main__": diff --git a/scripts/report-ai-explain.py b/scripts/report-ai-explain.py index 482be92..bc77270 100644 --- a/scripts/report-ai-explain.py +++ b/scripts/report-ai-explain.py @@ -85,6 +85,11 @@ def validate(answer, report): raise ValueError("invalid possible cause") prose(cause["hypothesis"], 400) refs(cause["check_ids"]) + if any(cause["hypothesis"].strip().lower() in { + checks[identifier].get("check", "").strip().lower(), + checks[identifier].get("check", "").split(" (", 1)[0].strip().lower(), + } for identifier in cause["check_ids"]): + raise ValueError("hypothesis repeats a check name without explaining a cause") cited = " ".join( f"{checks[identifier].get('summary', '')} {checks[identifier].get('detail', '')}" for identifier in cause["check_ids"] @@ -177,6 +182,6 @@ if __name__ == "__main__": reason = str(error) if type(error) is ValueError and str(error) in { "response must contain exactly the required fields", "response cites an unknown or missing check", "response contains invalid prose or an unvalidated command", "invalid possible causes", - "invalid possible cause", "invalid missing evidence", + "invalid possible cause", "invalid missing evidence", "hypothesis repeats a check name without explaining a cause", "next command is not an approved read-only command from this report", "unsupported AI provider"} else type(error).__name__ print(f"AI explanation unavailable or rejected: {reason}. Deterministic report remains available.") diff --git a/scripts/status-app-snapshot.py b/scripts/status-app-snapshot.py index 62ce2da..54c23e4 100644 --- a/scripts/status-app-snapshot.py +++ b/scripts/status-app-snapshot.py @@ -13,7 +13,20 @@ def emit(status, name, detail): print("\t".join(map(clean, (status, name, detail)))) -def compose(lines): +def compose(lines, intent_path=None): + intent = {} + if intent_path: + try: + with open(intent_path, encoding="utf-8") as stream: + data = json.load(stream) + if data.get("version") != 1 or not isinstance(data.get("services"), dict) or any( + value not in ("running", "stopped") for value in data["services"].values()): + raise ValueError("invalid intent record") + intent = data["services"] + except FileNotFoundError: + pass + except (OSError, ValueError, AttributeError) as exc: + emit("warn", "Compose desired state", f"Cannot read operator intent: {type(exc).__name__}; state is unknown") count = 0 for line in lines: if not line.strip(): @@ -30,6 +43,17 @@ def compose(lines): description = item.get("Status", state) unhealthy = "(unhealthy)" in description.lower() or "(health: starting)" in description.lower() status = "ok" if state == "running" and not unhealthy else "warn" + expected = intent.get(f"{project}/{service}") + if expected == "stopped" and state in ("exited", "created"): + status = "ok" + description += "; operator recorded expected state: stopped" + elif expected == "stopped": + status = "warn" + description += "; operator recorded expected state: stopped" + elif expected == "running": + description += "; operator recorded expected state: running" + elif status == "warn": + description += "; desired state unknown" name = item.get("Names", service) emit(status, f"{project}/{service} ({name})", description) count += 1 @@ -95,7 +119,7 @@ def main(): if len(sys.argv) not in (2, 3): raise ValueError("Expected compose or applications") if sys.argv[1] == "compose": - compose(sys.stdin) + compose(sys.stdin, sys.argv[2] if len(sys.argv) == 3 else None) elif sys.argv[1] == "applications": if len(sys.argv) == 3 and sys.argv[2] != "--expected-runner": raise ValueError("Unknown applications option") diff --git a/scripts/status-focus b/scripts/status-focus index 3a23269..e27ca57 100644 --- a/scripts/status-focus +++ b/scripts/status-focus @@ -96,7 +96,9 @@ status_focus_compose_report() { snapshot="${snapshot#$'\n'}" fi rm -f "${err_file}" - rows="$(printf '%s\n' "${snapshot}" | python3 "${REPO_ROOT}/scripts/status-app-snapshot.py" compose 2>&1)" || { + local -a intent_args=() + if [[ "${host}" == local ]]; then intent_args+=("${HOMELAB_STATE_DIR:-${HOME}/.local/share/homelab}/compose-intent.json"); fi + rows="$(printf '%s\n' "${snapshot}" | python3 "${REPO_ROOT}/scripts/status-app-snapshot.py" compose "${intent_args[@]}" 2>&1)" || { report_ui_emit warn "${area}" "Compose inventory" "Cannot interpret Docker snapshot" "${rows}"; return 0; } while IFS=$'\t' read -r severity name detail; do diff --git a/tests/jeannie/test_doctor_focus.py b/tests/jeannie/test_doctor_focus.py index fe7c32d..2823767 100644 --- a/tests/jeannie/test_doctor_focus.py +++ b/tests/jeannie/test_doctor_focus.py @@ -34,6 +34,16 @@ class DoctorFocusTests(unittest.TestCase): self.assertIn("No specific automatic mitigation", result.stdout) self.assertNotIn("deploy-service", result.stdout) + def test_stopped_debian_container_has_a_safe_specific_next_check(self): + with tempfile.TemporaryDirectory() as temp: + rows = Path(temp) / "rows" + rows.write_text("warn\tDebian Compose\tlab/media (media)\tExited (143); desired state unknown\t\t\t\t\n") + result = subprocess.run([sys.executable, str(NARRATIVE), str(rows), "Doctor"], + capture_output=True, text=True, check=True) + self.assertIn("whether it should be running is not recorded", result.stdout) + self.assertIn("docker inspect --format", result.stdout) + self.assertIn(" media", result.stdout) + def runner_report(self, service_state): code = r''' source "$1" diff --git a/tests/jeannie/test_report_ai_explain.py b/tests/jeannie/test_report_ai_explain.py index e775960..19ee25b 100644 --- a/tests/jeannie/test_report_ai_explain.py +++ b/tests/jeannie/test_report_ai_explain.py @@ -18,6 +18,15 @@ SPEC.loader.exec_module(MODULE) class EvidenceExplanationTests(unittest.TestCase): + def test_service_name_alone_is_not_a_cause(self): + report = {"checks": [{"id": "C01", "check": "homelab-arr/suwayomi (arr-suwayomi)", + "summary": "Exited", "read_only_command": None}]} + answer = {"observed_facts": ["C01"], "possible_causes": [ + {"hypothesis": "homelab-arr/suwayomi", "check_ids": ["C01"]}], + "missing_evidence": [], "next_command": None} + with self.assertRaisesRegex(ValueError, "repeats a check name"): + MODULE.validate(answer, report) + def setUp(self): self.report = {"checks": [{"id": "C01", "area": "Gitea", "check": "HTTP", "summary": "HTTP 503", "read_only_command": "./jeannie doctor-gitea"}]} diff --git a/tests/jeannie/test_status_app_snapshot.py b/tests/jeannie/test_status_app_snapshot.py index 3f5d7f1..9a1efce 100644 --- a/tests/jeannie/test_status_app_snapshot.py +++ b/tests/jeannie/test_status_app_snapshot.py @@ -1,10 +1,12 @@ import json import subprocess import sys +import tempfile import unittest from pathlib import Path SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "status-app-snapshot.py" +INTENT = SCRIPT.with_name("compose-intent.py") def parse(kind, data, *args): @@ -13,6 +15,40 @@ def parse(kind, data, *args): class ApplicationSnapshotTests(unittest.TestCase): + def test_record_and_clear_compose_intent_without_operating_docker(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "intent.json" + result = subprocess.run([sys.executable, str(INTENT), "--file", str(path), "stopped", "lab/media"], + text=True, capture_output=True, check=True) + self.assertIn("no containers were started or stopped", result.stdout) + self.assertEqual(json.loads(path.read_text())["services"], {"lab/media": "stopped"}) + subprocess.run([sys.executable, str(INTENT), "--file", str(path), "clear", "lab/media"], check=True) + self.assertEqual(json.loads(path.read_text())["services"], {}) + + def test_explicit_stopped_intent_does_not_hide_a_running_container(self): + with tempfile.TemporaryDirectory() as directory: + intent = Path(directory) / "intent.json" + intent.write_text(json.dumps({"version": 1, "services": {"lab/media": "stopped"}})) + def snapshot(state): + return json.dumps({"Names": "media", "State": state, "Status": state, + "Labels": "com.docker.compose.project=lab,com.docker.compose.service=media"}) + stopped = parse("compose", snapshot("exited"), str(intent)) + running = parse("compose", snapshot("running"), str(intent)) + self.assertIn("ok\tlab/media (media)", stopped) + self.assertIn("operator recorded expected state: stopped", stopped) + self.assertIn("warn\tlab/media (media)", running) + + def test_invalid_intent_warns_and_never_suppresses_stopped_service(self): + with tempfile.TemporaryDirectory() as directory: + intent = Path(directory) / "intent.json" + intent.write_text("not json") + data = json.dumps({"Names": "media", "State": "exited", "Status": "Exited (0)", + "Labels": "com.docker.compose.project=lab,com.docker.compose.service=media"}) + result = parse("compose", data, str(intent)) + self.assertIn("warn\tCompose desired state", result) + self.assertIn("warn\tlab/media", result) + self.assertIn("desired state unknown", result) + def test_runner_candidate_requires_synced_revision_and_no_other_unhealthy_resources(self): runner = {"metadata": {"name": "gitea-runner"}, "status": { "health": {"status": "Progressing"}, "sync": {"status": "Synced", "revision": "abc123"},