Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(runtime): add low-noise macOS session diagnostics (#938)
Call Whitea99f72cd7e32
diff --git a/docs/plans/macos-session-diagnostics.md b/docs/plans/macos-session-diagnostics.mdnew file mode 100644index 000000000..fc61dae3b--- /dev/null+++ b/docs/plans/macos-session-diagnostics.md@@ -0,0 +1,57 @@+# macOS Session Diagnostics++## Background++Issue #891 cannot be explained by `PPID=1`: live Fast User Switching preserves+the Avibe account's Aqua domain, and the service and backend child keep the same+audit session ID while DNS remains healthy. The next failure must be recorded+before a restart without adding lifecycle changes or DNS workarounds.++## Goal++Add a macOS-only state-transition recorder owned by the existing service+lifecycle. It must distinguish an ordinary console-user switch from a missing,+recreated, or mismatched Aqua login domain while also recording resolver failure+and recovery.++## Design++- The service entrypoint owns one daemon monitor thread and stops it during the+ existing shutdown path. The monitor never starts, stops, or restarts Avibe.+- A snapshot contains only service PID/UID, console user, service and GUI audit+ session IDs, GUI-domain availability, ASID match, and DNS state/error class.+- Session context is checked every 60 seconds. The public-hostname resolver probe+ is bounded to two seconds, runs at startup, every five minutes, and immediately+ after a session-context transition.+- Logging is edge-triggered: one startup snapshot, then only console-user,+ GUI-domain, ASID-match, DNS-failure, and DNS-recovery transitions. Unchanged+ failures are deduplicated.+- Raw `launchctl`/resolver output, environment data, DNS servers, and resolved+ addresses never enter the log event.+- Missing tools, permissions, command timeouts, absent domains, and parse drift+ are non-fatal diagnostic states.++The obvious periodic-timer logger is intentionally rejected: it adds noise while+providing no extra evidence during a persistent failure.++## Residual Manual Matrix++- Lock/unlock and VNC disconnect/reconnect: expect no transition unless console,+ GUI-domain, ASID-match, or DNS state actually changes.+- Fast User Switching with both users logged in: expect a console-user transition+ while the Avibe GUI domain stays available and ASIDs stay matched.+- Explicit or automatic logout/login: observe GUI-domain disappearance and+ recreation, ASID mismatch/match changes, and whether the unmanaged service PID+ survives.+- Sleep/wake, VPN, and network reconfiguration: observe DNS failure/recovery+ without logging DNS servers or addresses.++These diagnostics collect evidence for the next occurrence; they do not prove+the stale-Aqua-domain hypothesis or change service lifecycle behavior.++## Todo++- [x] Add injected parsers/probes and a transition-deduplicating monitor.+- [x] Attach the monitor to service startup and shutdown on macOS only.+- [x] Add focused parsing, transition, failure, and non-macOS tests.+- [x] Run focused pytest and Ruff before delivery.diff --git a/main.py b/main.pyindex 68cb559ee..ce42a6c71 100644--- a/main.py+++ b/main.py@@ -10,6 +10,7 @@ from typing import Anyfrom config.paths import ensure_data_dirs, get_logs_dirfrom vibe.logging_config import APPLICATION_LOG_BACKUP_COUNT, APPLICATION_LOG_MAX_BYTES+from vibe.macos_session_diagnostics import start_macos_session_diagnosticsfrom vibe.runtime import (ServiceAlreadyRunningError,acquire_service_instance_lock,@@ -120,9 +121,19 @@ def _log_shutdown_intent(logger: logging.Logger, signum: int) -> None:logger.info("Accepted managed shutdown intent: %s", intent)+def _stop_macos_session_diagnostics(monitor: Any) -> None:+ if monitor is None:+ return+ try:+ monitor.stop()+ except Exception:+ logging.getLogger(__name__).debug("macOS session diagnostics cleanup failed")++def main():"""Main entry point"""lock_acquired = False+ macos_session_diagnostics = Nonetry:acquire_service_instance_lock()lock_acquired = True@@ -146,9 +157,11 @@ def main():shutdown_intent_required(),os.environ.get("VIBE_REQUIRE_SHUTDOWN_INTENT"),)- from core.process_diagnostics import log_process_snapshot+ macos_session_diagnostics = start_macos_session_diagnostics(logger)+ if sys.platform != "darwin":+ from core.process_diagnostics import log_process_snapshot- log_process_snapshot(logger, "service-start")+ log_process_snapshot(logger, "service-start")report = prepare_sqlite_state(config)logger.info("SQLite state ready: imported=%s db_path=%s backup_path=%s",@@ -176,6 +189,7 @@ def main():logger.info("Shutting down after signal %s", signum)except Exception:pass+ _stop_macos_session_diagnostics(macos_session_diagnostics)try:controller.cleanup_sync()except Exception as cleanup_err:@@ -190,6 +204,7 @@ def main():try:controller.run()finally:+ _stop_macos_session_diagnostics(macos_session_diagnostics)release_service_instance_lock()except ServiceAlreadyRunningError as e:@@ -200,6 +215,8 @@ def main():release_service_instance_lock()logging.error(f"Failed to start: {e}")sys.exit(1)+ finally:+ _stop_macos_session_diagnostics(macos_session_diagnostics)if __name__ == "__main__":diff --git a/tests/test_macos_session_diagnostics.py b/tests/test_macos_session_diagnostics.pynew file mode 100644index 000000000..77c7618f1--- /dev/null+++ b/tests/test_macos_session_diagnostics.py@@ -0,0 +1,386 @@+from __future__ import annotations++import json+import logging+from types import SimpleNamespace++from vibe.macos_session_diagnostics import (+ CommandResult,+ DnsProbeState,+ MacOSSessionMonitor,+ MacOSSessionProbe,+ SessionContext,+ parse_gui_domain_asid,+ parse_launchctl_asid,+)+++SERVICE_LAUNCHCTL_FIXTURE = """+pid/4242 = {+ type = pid+ security context = {+ uid = 501+ asid = 120001+ }+ task-special ports = {+ 0x123 4 bootstrap (unknown)+ }+}+"""++GUI_LAUNCHCTL_FIXTURE = """+gui/501 = {+ type = login+ handle = 120001+ session = Aqua+ security context = {+ uid = 501+ asid = 120001+ }+ environment = {+ SECRET_THAT_MUST_NOT_BE_LOGGED => value+ }+}+"""+++class FakeThread:+ def __init__(self, **kwargs) -> None:+ self.kwargs = kwargs+ self.started = False+ self.joined = False++ def start(self) -> None:+ self.started = True++ def join(self, timeout: float | None = None) -> None:+ self.joined = True+++class FakeProbe:+ service_pid = 4242+ service_uid = 501++ def __init__(self, contexts: list[SessionContext], dns_states: list[DnsProbeState]) -> None:+ self._contexts = iter(contexts)+ self._dns_states = iter(dns_states)+ self.context_calls = 0+ self.dns_calls = 0++ def capture_context(self) -> SessionContext:+ self.context_calls += 1+ return next(self._contexts)++ def capture_dns(self) -> DnsProbeState:+ self.dns_calls += 1+ return next(self._dns_states)+++class ExplodingProbe:+ service_pid = 4242+ service_uid = 501++ def capture_context(self) -> SessionContext:+ raise RuntimeError("raw launchctl output must not escape")++ def capture_dns(self) -> DnsProbeState:+ raise RuntimeError("resolved address must not escape")+++def context(+ *,+ console_user: str = "avibe",+ service_asid: int | None = 120001,+ gui_asid: int | None = 120001,+ gui_available: bool | None = True,+ gui_error: str | None = None,+) -> SessionContext:+ return SessionContext(+ service_pid=4242,+ service_uid=501,+ console_user=console_user,+ service_asid=service_asid,+ gui_asid=gui_asid,+ gui_domain_available=gui_available,+ gui_error_class=gui_error,+ )+++def event_payloads(caplog) -> list[dict[str, object]]:+ prefix = "macos_session_diagnostic "+ return [+ json.loads(record.getMessage()[len(prefix) :])+ for record in caplog.records+ if record.getMessage().startswith(prefix)+ ]+++def make_monitor(logger: logging.Logger, probe, *, dns_interval: float = 300.0):+ threads: list[FakeThread] = []++ def thread_factory(**kwargs):+ thread = FakeThread(**kwargs)+ threads.append(thread)+ return thread++ monitor = MacOSSessionMonitor(+ logger,+ platform="darwin",+ probe=probe,+ dns_interval=dns_interval,+ monotonic=lambda: 0.0,+ thread_factory=thread_factory,+ )+ return monitor, threads+++def test_launchctl_snapshot_parsing_uses_security_context_fixture() -> None:+ assert parse_launchctl_asid(SERVICE_LAUNCHCTL_FIXTURE) == 120001+ assert parse_gui_domain_asid(GUI_LAUNCHCTL_FIXTURE) == 120001+ assert parse_gui_domain_asid(GUI_LAUNCHCTL_FIXTURE.replace("Aqua", "Background")) is None+ assert parse_launchctl_asid("security context format changed") is None+++def test_probe_redacts_raw_launchctl_and_dns_results() -> None:+ outputs = {+ "pid/4242": CommandResult(0, SERVICE_LAUNCHCTL_FIXTURE),+ "gui/501": CommandResult(0, GUI_LAUNCHCTL_FIXTURE),+ "dns": CommandResult(0, "203.0.113.10 must be ignored"),+ }++ def runner(command, timeout):+ return outputs["dns" if command[-1] == "api.github.com" else command[-1]]++ probe = MacOSSessionProbe(+ service_pid=4242,+ service_uid=501,+ command_runner=runner,+ console_user_reader=lambda: ("avibe", None),+ )++ captured_context = probe.capture_context()+ captured_dns = probe.capture_dns()++ assert captured_context.asid_match is True+ assert captured_context.gui_domain_available is True+ assert captured_dns == DnsProbeState("healthy")+ assert "SECRET_THAT_MUST_NOT_BE_LOGGED" not in repr(captured_context)+ assert "203.0.113.10" not in repr(captured_dns)+++def test_initial_snapshot_is_single_compact_event_and_unchanged_poll_is_silent(caplog) -> None:+ caplog.set_level(logging.INFO)+ probe = FakeProbe([context(), context()], [DnsProbeState("healthy")])+ monitor, threads = make_monitor(logging.getLogger("test.macos.initial"), probe)++ monitor.start()+ assert probe.context_calls == 0+ assert probe.dns_calls == 0+ monitor._initialize_once(now=0.0)+ monitor.poll_once(now=1.0)++ payloads = event_payloads(caplog)+ assert len(payloads) == 1+ assert payloads[0] == {+ "asid_match": True,+ "console_user": "avibe",+ "dns_state": "healthy",+ "event": "macos_session_snapshot",+ "gui_asid": 120001,+ "gui_domain_available": True,+ "reason": ["service_start"],+ "service_asid": 120001,+ "service_pid": 4242,+ "service_uid": 501,+ }+ assert threads[0].started is True+++def test_fast_user_switch_logs_only_console_user_transition(caplog) -> None:+ caplog.set_level(logging.INFO)+ probe = FakeProbe(+ [context(console_user="avibe"), context(console_user="other-user")],+ [DnsProbeState("healthy"), DnsProbeState("healthy")],+ )+ monitor, _ = make_monitor(logging.getLogger("test.macos.fus"), probe)++ monitor.start()+ monitor._initialize_once(now=0.0)+ monitor.poll_once(now=1.0)++ payloads = event_payloads(caplog)+ assert payloads[-1]["reason"] == ["console_user_change"]+ assert payloads[-1]["gui_domain_available"] is True+ assert payloads[-1]["asid_match"] is True+ assert probe.dns_calls == 2+++def test_gui_domain_disappearance_and_recreation_are_edge_triggered(caplog) -> None:+ caplog.set_level(logging.INFO)+ probe = FakeProbe(+ [+ context(),+ context(gui_asid=None, gui_available=False, gui_error="absent"),+ context(gui_asid=None, gui_available=False, gui_error="absent"),+ context(gui_asid=120002, gui_available=True),+ ],+ [DnsProbeState("healthy"), DnsProbeState("healthy"), DnsProbeState("healthy")],+ )+ monitor, _ = make_monitor(logging.getLogger("test.macos.gui"), probe)++ monitor.start()+ monitor._initialize_once(now=0.0)+ monitor.poll_once(now=1.0)+ monitor.poll_once(now=2.0)+ monitor.poll_once(now=3.0)++ payloads = event_payloads(caplog)+ assert len(payloads) == 3+ assert payloads[1]["reason"] == ["gui_domain_change", "asid_match_change"]+ assert payloads[1]["gui_domain_available"] is False+ assert payloads[2]["reason"] == ["gui_domain_change", "asid_match_change"]+ assert payloads[2]["gui_asid"] == 120002+ assert payloads[2]["asid_match"] is False+++def test_asid_mismatch_transition_is_logged(caplog) -> None:+ caplog.set_level(logging.INFO)+ probe = FakeProbe(+ [context(), context(gui_asid=120002)],+ [DnsProbeState("healthy"), DnsProbeState("healthy")],+ )+ monitor, _ = make_monitor(logging.getLogger("test.macos.asid"), probe)++ monitor.start()+ monitor._initialize_once(now=0.0)+ monitor.poll_once(now=1.0)++ transition = event_payloads(caplog)[-1]+ assert transition["reason"] == ["gui_domain_change", "asid_match_change"]+ assert transition["asid_match"] is False+++def test_dns_failure_is_deduplicated_until_recovery(caplog) -> None:+ caplog.set_level(logging.INFO)+ probe = FakeProbe(+ [context(), context(), context(), context()],+ [+ DnsProbeState("healthy"),+ DnsProbeState("failed", "resolver_timeout"),+ DnsProbeState("failed", "resolver_timeout"),+ DnsProbeState("healthy"),+ ],+ )+ monitor, _ = make_monitor(logging.getLogger("test.macos.dns"), probe)++ monitor.start()+ monitor._initialize_once(now=0.0)+ monitor.poll_once(now=300.0)+ monitor.poll_once(now=600.0)+ monitor.poll_once(now=900.0)++ payloads = event_payloads(caplog)+ assert [payload["reason"] for payload in payloads] == [+ ["service_start"],+ ["dns_failed"],+ ["dns_recovered"],+ ]+ assert payloads[1]["dns_error_class"] == "resolver_timeout"+ assert "dns_error_class" not in payloads[2]+++def test_non_macos_monitor_is_noop(caplog) -> None:+ caplog.set_level(logging.INFO)+ probe = FakeProbe([context()], [DnsProbeState("healthy")])+ monitor = MacOSSessionMonitor(logging.getLogger("test.macos.noop"), platform="linux", probe=probe)++ monitor.start()+ monitor._initialize_once(now=0.0)+ monitor.poll_once(now=300.0)+ monitor.stop()++ assert probe.context_calls == 0+ assert probe.dns_calls == 0+ assert event_payloads(caplog) == []+++def test_probe_failures_are_nonfatal_and_redacted(caplog) -> None:+ caplog.set_level(logging.INFO)+ monitor, threads = make_monitor(logging.getLogger("test.macos.failure"), ExplodingProbe())++ monitor.start()+ monitor._initialize_once(now=0.0)++ payload = event_payloads(caplog)[0]+ assert payload["reason"] == ["service_start"]+ assert payload["gui_domain_available"] is None+ assert payload["dns_state"] == "unknown"+ assert payload["gui_error_class"] == "probe_error"+ assert payload["dns_error_class"] == "probe_error"+ assert "raw launchctl" not in caplog.text+ assert "resolved address" not in caplog.text+ diagnostic_record = next(+ record for record in caplog.records if record.getMessage().startswith("macos_session_diagnostic ")+ )+ assert diagnostic_record.levelno == logging.WARNING+ assert threads[0].started is True+++def test_monitor_stop_joins_its_worker() -> None:+ probe = FakeProbe([context()], [DnsProbeState("healthy")])+ monitor, threads = make_monitor(logging.getLogger("test.macos.stop"), probe)+ monitor.start()+ monitor._initialize_once(now=0.0)++ monitor.stop()++ assert threads[0].joined is True+++def test_service_main_owns_monitor_shutdown(monkeypatch) -> None:+ import config.v2_compat+ import core.controller+ import core.process_diagnostics+ import main as service_main+ import vibe.sentry_integration++ calls: list[str] = []++ class FakeMonitor:+ def stop(self) -> None:+ calls.append("diagnostics.stop")++ class FakeController:+ def __init__(self, config) -> None:+ calls.append("controller.init")++ def run(self) -> None:+ calls.append("controller.run")++ loaded_config = SimpleNamespace(+ runtime=SimpleNamespace(log_level="INFO", default_cwd="/tmp"),+ platform="avibe",+ )+ report = SimpleNamespace(imported=False, db_path="test.db", backup_path=None)++ monkeypatch.setattr(service_main, "acquire_service_instance_lock", lambda: calls.append("lock.acquire"))+ monkeypatch.setattr(service_main, "release_service_instance_lock", lambda: calls.append("lock.release"))+ monkeypatch.setattr(service_main, "load_config", lambda: loaded_config)+ monkeypatch.setattr(service_main, "setup_logging", lambda level: None)+ monkeypatch.setattr(service_main, "apply_claude_sdk_patches", lambda: None)+ monkeypatch.setattr(service_main, "prepare_sqlite_state", lambda loaded: report)+ monkeypatch.setattr(+ service_main,+ "start_macos_session_diagnostics",+ lambda logger: calls.append("diagnostics.start") or FakeMonitor(),+ )+ monkeypatch.setattr(vibe.sentry_integration, "init_sentry", lambda *args, **kwargs: None)+ monkeypatch.setattr(core.process_diagnostics, "log_process_snapshot", lambda *args, **kwargs: None)+ monkeypatch.setattr(core.controller, "Controller", FakeController)+ monkeypatch.setattr(config.v2_compat, "to_app_config", lambda loaded: loaded)+ monkeypatch.setattr(service_main.signal, "signal", lambda *args, **kwargs: None)++ service_main.main()++ assert calls.index("diagnostics.start") < calls.index("controller.run")+ assert calls.index("controller.run") < calls.index("diagnostics.stop")diff --git a/vibe/macos_session_diagnostics.py b/vibe/macos_session_diagnostics.pynew file mode 100644index 000000000..7c9fcd768--- /dev/null+++ b/vibe/macos_session_diagnostics.py@@ -0,0 +1,438 @@+"""Quiet macOS login-session and DNS diagnostics for the Avibe service."""++from __future__ import annotations++import json+import logging+import os+import re+import subprocess+import sys+import threading+import time+from dataclasses import dataclass+from typing import Callable, Sequence++try:+ import pwd+except ImportError: # pragma: no cover - Windows import path+ pwd = None # type: ignore[assignment]+++DEFAULT_POLL_INTERVAL_SECONDS = 60.0+DEFAULT_DNS_INTERVAL_SECONDS = 300.0+DEFAULT_COMMAND_TIMEOUT_SECONDS = 2.0+DNS_PROBE_HOSTNAME = "api.github.com"+_MAX_CAPTURE_CHARS = 64 * 1024+_DNS_PROBE_SCRIPT = "import socket, sys; socket.getaddrinfo(sys.argv[1], 443)"++_SECURITY_CONTEXT_RE = re.compile(r"security context\s*=\s*\{(?P<body>.*?)\}", re.DOTALL)+_ASID_RE = re.compile(r"^\s*asid\s*=\s*(?P<asid>\d+)\s*$", re.MULTILINE)+_GUI_DOMAIN_RE = re.compile(r"^gui/\d+\s*=\s*\{", re.MULTILINE)+_AQUA_SESSION_RE = re.compile(r"^\s*session\s*=\s*Aqua\s*$", re.MULTILINE)+++@dataclass(frozen=True)+class CommandResult:+ returncode: int | None+ output: str = ""+ error_class: str | None = None+++CommandRunner = Callable[[Sequence[str], float], CommandResult]+ConsoleUserReader = Callable[[], tuple[str | None, str | None]]+++def run_bounded_command(command: Sequence[str], timeout: float) -> CommandResult:+ """Run a diagnostic command without exposing its raw output to logs."""+ try:+ result = subprocess.run(+ list(command),+ check=False,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=timeout,+ )+ except FileNotFoundError:+ return CommandResult(None, error_class="tool_missing")+ except subprocess.TimeoutExpired:+ return CommandResult(None, error_class="timeout")+ except PermissionError:+ return CommandResult(None, error_class="permission")+ except OSError:+ return CommandResult(None, error_class="os_error")++ output = (result.stdout or result.stderr or "")[:_MAX_CAPTURE_CHARS]+ return CommandResult(result.returncode, output=output)+++def read_console_user() -> tuple[str | None, str | None]:+ """Read the foreground console owner without spawning ``stat``."""+ if pwd is None:+ return None, "tool_missing"+ try:+ console_uid = os.stat("/dev/console").st_uid+ return pwd.getpwuid(console_uid).pw_name, None+ except FileNotFoundError:+ return None, "console_missing"+ except KeyError:+ return None, "user_lookup_failed"+ except PermissionError:+ return None, "permission"+ except OSError:+ return None, "os_error"+++def parse_launchctl_asid(output: str) -> int | None:+ """Extract the audit session ID from a launchctl security context."""+ security_context = _SECURITY_CONTEXT_RE.search(output)+ if security_context is None:+ return None+ match = _ASID_RE.search(security_context.group("body"))+ return int(match.group("asid")) if match is not None else None+++def parse_gui_domain_asid(output: str) -> int | None:+ """Extract an Aqua GUI domain ASID, rejecting unrelated launchctl output."""+ if _GUI_DOMAIN_RE.search(output) is None or _AQUA_SESSION_RE.search(output) is None:+ return None+ return parse_launchctl_asid(output)+++def _command_error_class(result: CommandResult) -> str:+ if result.error_class:+ return result.error_class+ normalized = result.output.lower()+ if "could not find domain" in normalized or "no such process" in normalized:+ return "absent"+ if "not privileged" in normalized or "permission denied" in normalized:+ return "permission"+ return "command_failed"+++@dataclass(frozen=True)+class SessionContext:+ service_pid: int+ service_uid: int+ console_user: str | None+ service_asid: int | None+ gui_asid: int | None+ gui_domain_available: bool | None+ console_error_class: str | None = None+ service_error_class: str | None = None+ gui_error_class: str | None = None++ @property+ def asid_match(self) -> bool | None:+ if self.service_asid is None or self.gui_asid is None:+ return None+ return self.service_asid == self.gui_asid+++@dataclass(frozen=True)+class DnsProbeState:+ state: str+ error_class: str | None = None+++@dataclass(frozen=True)+class SessionDiagnosticSnapshot:+ context: SessionContext+ dns: DnsProbeState++ def event(self, reasons: Sequence[str]) -> dict[str, object]:+ payload: dict[str, object] = {+ "event": "macos_session_snapshot",+ "reason": list(reasons),+ "service_pid": self.context.service_pid,+ "service_uid": self.context.service_uid,+ "console_user": self.context.console_user,+ "service_asid": self.context.service_asid,+ "gui_asid": self.context.gui_asid,+ "gui_domain_available": self.context.gui_domain_available,+ "asid_match": self.context.asid_match,+ "dns_state": self.dns.state,+ }+ optional_fields = {+ "console_error_class": self.context.console_error_class,+ "service_error_class": self.context.service_error_class,+ "gui_error_class": self.context.gui_error_class,+ "dns_error_class": self.dns.error_class,+ }+ payload.update({key: value for key, value in optional_fields.items() if value is not None})+ return payload+++class MacOSSessionProbe:+ """Collect the small, redacted state used by the transition monitor."""++ def __init__(+ self,+ *,+ service_pid: int | None = None,+ service_uid: int | None = None,+ command_runner: CommandRunner = run_bounded_command,+ console_user_reader: ConsoleUserReader = read_console_user,+ command_timeout: float = DEFAULT_COMMAND_TIMEOUT_SECONDS,+ dns_hostname: str = DNS_PROBE_HOSTNAME,+ ) -> None:+ self.service_pid = service_pid if service_pid is not None else os.getpid()+ self.service_uid = service_uid if service_uid is not None else os.getuid()+ self._command_runner = command_runner+ self._console_user_reader = console_user_reader+ self._command_timeout = command_timeout+ self._dns_hostname = dns_hostname+ self._service_asid: int | None = None++ def capture_context(self) -> SessionContext:+ try:+ console_user, console_error = self._console_user_reader()+ except Exception:+ console_user, console_error = None, "probe_error"++ service_error = None+ if self._service_asid is None:+ result = self._command_runner(+ ["/bin/launchctl", "print", f"pid/{self.service_pid}"],+ self._command_timeout,+ )+ if result.returncode == 0:+ self._service_asid = parse_launchctl_asid(result.output)+ if self._service_asid is None:+ service_error = "parse_error"+ else:+ service_error = _command_error_class(result)++ gui_result = self._command_runner(+ ["/bin/launchctl", "print", f"gui/{self.service_uid}"],+ self._command_timeout,+ )+ gui_asid = None+ gui_available: bool | None+ gui_error = None+ if gui_result.returncode == 0:+ gui_asid = parse_gui_domain_asid(gui_result.output)+ gui_available = gui_asid is not None+ if gui_asid is None:+ gui_available = None+ gui_error = "parse_error"+ else:+ gui_error = _command_error_class(gui_result)+ gui_available = False if gui_error == "absent" else None++ return SessionContext(+ service_pid=self.service_pid,+ service_uid=self.service_uid,+ console_user=console_user,+ service_asid=self._service_asid,+ gui_asid=gui_asid,+ gui_domain_available=gui_available,+ console_error_class=console_error,+ service_error_class=service_error,+ gui_error_class=gui_error,+ )++ def capture_dns(self) -> DnsProbeState:+ result = self._command_runner(+ [sys.executable, "-c", _DNS_PROBE_SCRIPT, self._dns_hostname],+ self._command_timeout,+ )+ if result.returncode == 0:+ return DnsProbeState("healthy")+ error_class = _command_error_class(result)+ if error_class in {"tool_missing", "permission", "os_error"}:+ return DnsProbeState("unknown", error_class)+ return DnsProbeState("failed", "resolver_timeout" if error_class == "timeout" else "resolver_error")+++def _context_transition_reasons(previous: SessionContext, current: SessionContext) -> list[str]:+ reasons: list[str] = []+ if (previous.console_user, previous.console_error_class) != (+ current.console_user,+ current.console_error_class,+ ):+ reasons.append("console_user_change")+ if (+ previous.gui_domain_available,+ previous.gui_asid,+ previous.gui_error_class,+ ) != (+ current.gui_domain_available,+ current.gui_asid,+ current.gui_error_class,+ ):+ reasons.append("gui_domain_change")+ if previous.asid_match != current.asid_match:+ reasons.append("asid_match_change")+ return reasons+++def _dns_transition_reasons(previous: DnsProbeState, current: DnsProbeState) -> list[str]:+ if previous.state == "healthy" and current.state == "failed":+ return ["dns_failed"]+ if previous.state == "failed" and current.state == "healthy":+ return ["dns_recovered"]+ return []+++class MacOSSessionMonitor:+ """Record state transitions without emitting periodic success messages."""++ def __init__(+ self,+ logger: logging.Logger,+ *,+ platform: str = sys.platform,+ probe: MacOSSessionProbe | None = None,+ poll_interval: float = DEFAULT_POLL_INTERVAL_SECONDS,+ dns_interval: float = DEFAULT_DNS_INTERVAL_SECONDS,+ monotonic: Callable[[], float] = time.monotonic,+ thread_factory: Callable[..., threading.Thread] = threading.Thread,+ ) -> None:+ self._logger = logger+ self._enabled = platform == "darwin"+ self._probe = probe or (MacOSSessionProbe() if self._enabled else None)+ self._poll_interval = poll_interval+ self._dns_interval = dns_interval+ self._monotonic = monotonic+ self._thread_factory = thread_factory+ self._stop_event = threading.Event()+ self._thread: threading.Thread | None = None+ self._last_snapshot: SessionDiagnosticSnapshot | None = None+ self._last_dns_probe_at: float | None = None++ def start(self) -> None:+ if not self._enabled or self._thread is not None:+ return+ try:+ thread = self._thread_factory(+ target=self._run,+ name="macos-session-diagnostics",+ daemon=True,+ )+ self._thread = thread+ thread.start()+ except Exception:+ self._thread = None+ context = SessionContext(+ service_pid=getattr(self._probe, "service_pid", os.getpid()),+ service_uid=getattr(self._probe, "service_uid", os.getuid()),+ console_user=None,+ service_asid=None,+ gui_asid=None,+ gui_domain_available=None,+ service_error_class="thread_start_failed",+ gui_error_class="thread_start_failed",+ )+ self._last_snapshot = SessionDiagnosticSnapshot(+ context,+ DnsProbeState("unknown", "thread_start_failed"),+ )+ self._log_snapshot(self._last_snapshot, ["service_start"])++ def stop(self) -> None:+ self._stop_event.set()+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=DEFAULT_COMMAND_TIMEOUT_SECONDS * 3 + 1.0)+ self._thread = None++ def _initialize_once(self, *, now: float | None = None) -> None:+ if not self._enabled or self._last_snapshot is not None:+ return+ current_time = self._monotonic() if now is None else now+ snapshot = SessionDiagnosticSnapshot(self._capture_context(), self._capture_dns())+ self._last_snapshot = snapshot+ self._last_dns_probe_at = current_time+ self._log_snapshot(snapshot, ["service_start"])++ def poll_once(self, *, now: float | None = None) -> None:+ if not self._enabled:+ return+ if self._last_snapshot is None:+ self._initialize_once(now=now)+ return++ current_context = self._capture_context()+ context_reasons = _context_transition_reasons(self._last_snapshot.context, current_context)+ current_time = self._monotonic() if now is None else now+ last_dns_probe_at = self._last_dns_probe_at+ dns_due = last_dns_probe_at is None or current_time - last_dns_probe_at >= self._dns_interval+ if context_reasons or dns_due:+ current_dns = self._capture_dns()+ self._last_dns_probe_at = current_time+ else:+ current_dns = self._last_snapshot.dns++ snapshot = SessionDiagnosticSnapshot(current_context, current_dns)+ reasons = context_reasons + _dns_transition_reasons(self._last_snapshot.dns, current_dns)+ if reasons:+ self._log_snapshot(snapshot, reasons)+ self._last_snapshot = snapshot++ def _run(self) -> None:+ self._initialize_once()+ while not self._stop_event.wait(self._poll_interval):+ self.poll_once()++ def _capture_context(self) -> SessionContext:+ try:+ return self._probe.capture_context()+ except Exception:+ return SessionContext(+ service_pid=getattr(self._probe, "service_pid", os.getpid()),+ service_uid=getattr(self._probe, "service_uid", os.getuid()),+ console_user=None,+ service_asid=None,+ gui_asid=None,+ gui_domain_available=None,+ console_error_class="probe_error",+ service_error_class="probe_error",+ gui_error_class="probe_error",+ )++ def _capture_dns(self) -> DnsProbeState:+ try:+ return self._probe.capture_dns()+ except Exception:+ return DnsProbeState("unknown", "probe_error")++ def _log_snapshot(self, snapshot: SessionDiagnosticSnapshot, reasons: Sequence[str]) -> None:+ payload = json.dumps(snapshot.event(reasons), sort_keys=True, separators=(",", ":"))+ context = snapshot.context+ warning = (+ context.gui_domain_available is not True+ or context.asid_match is False+ or snapshot.dns.state == "failed"+ or snapshot.dns.error_class is not None+ or any(+ error is not None+ for error in (+ context.console_error_class,+ context.service_error_class,+ context.gui_error_class,+ )+ )+ )+ if warning:+ self._logger.warning("macos_session_diagnostic %s", payload)+ else:+ self._logger.info("macos_session_diagnostic %s", payload)+++def start_macos_session_diagnostics(+ logger: logging.Logger,+ *,+ platform: str = sys.platform,+) -> MacOSSessionMonitor:+ """Start diagnostics best-effort; probe failures never block the service."""+ monitor = MacOSSessionMonitor(logger, platform=platform)+ try:+ monitor.start()+ except Exception:+ # ``MacOSSessionMonitor`` already contains probe failures. This final+ # guard protects service startup from construction/threading surprises.+ pass+ return monitor