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): self-bootstrap service into delegated user cgroup scope (#968)
Qi Qi7e08d7ca4c0a
diff --git a/core/resource_governance.py b/core/resource_governance.pyindex 50f86a659..76379f41f 100644--- a/core/resource_governance.py+++ b/core/resource_governance.py@@ -283,6 +283,11 @@ def _is_under_runtime_dir(cmdline: str) -> bool:return False+def _is_package_service_main(cmdline: str) -> bool:+ service_main = Path(__file__).resolve().parents[1] / "vibe" / "service_main.py"+ return any(path in cmdline for path in _path_variants(service_main))++def _is_managed_cloudflared(pid: int, cmdline: str) -> bool:if not _is_cloudflared_cmd(cmdline):return False@@ -308,6 +313,8 @@ def _is_known_avibe_runtime_member(pid: int, *, uid: int | None = None) -> bool:return Trueif _is_managed_cloudflared(pid, cmdline):return True+ if _is_package_service_main(cmdline):+ return Trueruntime_cwd = _current_runtime_cwd()pid_cwd = _pid_cwd(pid)diff --git a/scripts/incus_regression_supervisor.py b/scripts/incus_regression_supervisor.pyindex e5c833b44..ce7125592 100644--- a/scripts/incus_regression_supervisor.py+++ b/scripts/incus_regression_supervisor.py@@ -79,15 +79,18 @@ def main() -> int:bind_host = runtime.effective_ui_bind_host(config)ui_pid = runtime.start_ui(bind_host, config.ui.setup_port)- if runtime.service_pid_recorded(service_pid):- runtime.write_status("running", "incus regression started", service_pid, ui_pid)- elif runtime.wait_for_service_pid(service_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS):- runtime.write_status("running", "incus regression started", service_pid, ui_pid)- else:- runtime.write_status("error", "service did not become ready", service_pid, ui_pid)- runtime.stop_ui()- runtime.stop_service()- return 1+ if not runtime.service_pid_recorded(service_pid):+ ready_service_pid = runtime.wait_for_service_ready(+ service_pid,+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,+ )+ if ready_service_pid is None:+ runtime.write_status("error", "service did not become ready", service_pid, ui_pid)+ runtime.stop_ui()+ runtime.stop_service()+ return 1+ service_pid = ready_service_pid+ runtime.write_status("running", "incus regression started", service_pid, ui_pid)while not stopping:# _restart_in_progress() is read fresh at each decision below rather thandiff --git a/tests/test_incus_regression_supervisor.py b/tests/test_incus_regression_supervisor.pyindex cedc8b34c..4418227da 100644--- a/tests/test_incus_regression_supervisor.py+++ b/tests/test_incus_regression_supervisor.py@@ -155,3 +155,44 @@ def test_main_backs_off_during_active_restart(monkeypatch, tmp_path):assert "restarting" in statusesassert "error" not in statuses+++def test_main_adopts_scoped_service_lock_holder(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ paths.ensure_data_dirs()++ monkeypatch.setattr(supervisor, "_config", lambda: SimpleNamespace(ui=SimpleNamespace(setup_port=8080)))+ monkeypatch.setattr(runtime, "start_service", lambda wait_for_ready=True: 100)+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda config: "127.0.0.1")+ monkeypatch.setattr(runtime, "start_ui", lambda host, port: 333)+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 200)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in {200, 333})++ waited: list[tuple[int, float]] = []++ def wait_for_ready(pid, timeout):+ waited.append((pid, timeout))+ return 200++ monkeypatch.setattr(runtime, "wait_for_service_ready", wait_for_ready)++ statuses: list[tuple[str, int | None, int | None]] = []+ monkeypatch.setattr(+ runtime,+ "write_status",+ lambda state, _message, service_pid=None, ui_pid=None: statuses.append((state, service_pid, ui_pid)),+ )++ class _Stop(Exception):+ pass++ def stop_on_sleep(_seconds):+ raise _Stop()++ monkeypatch.setattr(supervisor.time, "sleep", stop_on_sleep)++ with pytest.raises(_Stop):+ supervisor.main()++ assert waited == [(100, runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS)]+ assert statuses[0] == ("running", 200, 333)diff --git a/tests/test_resource_governance.py b/tests/test_resource_governance.pyindex 6f5a4512e..30881df6e 100644--- a/tests/test_resource_governance.py+++ b/tests/test_resource_governance.py@@ -129,6 +129,25 @@ def test_known_runtime_member_rejects_unrelated_main_py(assert _is_known_avibe_runtime_member(1234, uid=1000) is False+def test_known_runtime_member_accepts_scoped_package_service_wrapper(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ package_service_main = Path(__file__).resolve().parents[1] / "vibe" / "service_main.py"++ monkeypatch.setattr("core.resource_governance._pid_uid", lambda pid: 1000)+ monkeypatch.setattr("core.resource_governance._pid_cwd", lambda pid: None)+ monkeypatch.setattr("core.resource_governance._current_runtime_cwd", lambda: None)+ monkeypatch.setattr(+ "core.resource_governance._pid_cmdline",+ lambda pid: (+ "systemd-run --user --scope -q -p Delegate=yes -- "+ f"/opt/avibe/venv/bin/python {package_service_main}"+ ),+ )++ assert _is_known_avibe_runtime_member(1234, uid=1000) is True++def test_known_runtime_member_accepts_custom_avibe_runtime_path(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex a1396fc15..de08acd4b 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -358,7 +358,7 @@ def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", slow_start_runtime)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: False)- monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: pid == 222)+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 222 if pid == 222 else None)rc = restart_supervisor._run_restart_job(job_id="jobslow", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")diff --git a/tests/test_runtime_scope_bootstrap.py b/tests/test_runtime_scope_bootstrap.pynew file mode 100644index 000000000..eec3141e0--- /dev/null+++ b/tests/test_runtime_scope_bootstrap.py@@ -0,0 +1,294 @@+import sys+import unittest+from contextlib import ExitStack+from pathlib import Path+from unittest.mock import Mock, patch++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from vibe import runtime+++def _passing_patches():+ """Every predicate in maybe_systemd_scope_prefix() set to the happy path.++ Individual tests override one entry to assert it fails open to []."""+ stack = ExitStack()+ stack.enter_context(patch.object(runtime.sys, "platform", "linux"))+ stack.enter_context(patch("vibe.runtime.shutil.which", return_value="/usr/bin/systemd-run"))+ stack.enter_context(patch("vibe.runtime.os.getuid", return_value=1018, create=True))+ stack.enter_context(patch("vibe.runtime.Path.is_socket", return_value=True))+ stack.enter_context(patch("core.resource_governance.detect_cgroup_root", return_value=Path("/sys/fs/cgroup")))+ stack.enter_context(patch("vibe.runtime._resource_governance_mode", return_value="auto"))+ stack.enter_context(patch("vibe.runtime._ensure_linger_enabled", return_value=True))+ stack.enter_context(patch("vibe.runtime._systemd_run_self_test_ok", return_value=True))+ return stack+++class MaybeSystemdScopePrefixTests(unittest.TestCase):+ def test_all_predicates_pass_returns_full_prefix(self):+ with _passing_patches():+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), list(runtime.SYSTEMD_SCOPE_PREFIX))++ def test_prefix_ends_with_double_dash_separator(self):+ with _passing_patches():+ self.assertEqual(runtime.maybe_systemd_scope_prefix()[-1], "--")++ def test_non_linux_fails_open(self):+ with _passing_patches():+ with patch.object(runtime.sys, "platform", "darwin"):+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), [])++ def test_missing_systemd_run_fails_open(self):+ with _passing_patches():+ with patch("vibe.runtime.shutil.which", return_value=None):+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), [])++ def test_no_user_manager_socket_fails_open(self):+ with _passing_patches():+ with patch("vibe.runtime.Path.is_socket", return_value=False):+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), [])++ def test_no_cgroup_v2_fails_open(self):+ with _passing_patches():+ with patch("core.resource_governance.detect_cgroup_root", return_value=None):+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), [])++ def test_governance_disabled_fails_open(self):+ with _passing_patches():+ with patch("vibe.runtime._resource_governance_mode", return_value="disabled"):+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), [])++ def test_auto_mode_only_checks_linger(self):+ with _passing_patches():+ with patch("vibe.runtime._ensure_linger_enabled", return_value=True) as ensure_linger:+ runtime.maybe_systemd_scope_prefix()++ ensure_linger.assert_called_once_with(allow_enable=False)++ def test_enabled_mode_may_enable_linger(self):+ with _passing_patches():+ with patch("vibe.runtime._resource_governance_mode", return_value="enabled"):+ with patch("vibe.runtime._ensure_linger_enabled", return_value=True) as ensure_linger:+ runtime.maybe_systemd_scope_prefix()++ ensure_linger.assert_called_once_with(allow_enable=True)++ def test_linger_unconfirmed_fails_open(self):+ with _passing_patches():+ with patch("vibe.runtime._ensure_linger_enabled", return_value=False):+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), [])++ def test_self_test_failure_fails_open(self):+ with _passing_patches():+ with patch("vibe.runtime._systemd_run_self_test_ok", return_value=False):+ self.assertEqual(runtime.maybe_systemd_scope_prefix(), [])+++class LingerHelperTests(unittest.TestCase):+ def test_already_enabled_short_circuits_without_enable(self):+ with patch("vibe.runtime._linger_is_enabled", return_value=True) as is_enabled:+ with patch("vibe.runtime.subprocess.run") as run:+ self.assertTrue(runtime._ensure_linger_enabled(allow_enable=False))+ run.assert_not_called()+ is_enabled.assert_called_once()++ def test_auto_mode_does_not_enable_when_initially_off(self):+ with patch("vibe.runtime._linger_is_enabled", return_value=False):+ with patch("vibe.runtime.subprocess.run") as run:+ self.assertFalse(runtime._ensure_linger_enabled(allow_enable=False))+ run.assert_not_called()++ def test_explicit_mode_self_enables_when_initially_off(self):+ # first check False -> enable-linger -> re-check True+ with patch("vibe.runtime._linger_is_enabled", side_effect=[False, True]):+ with patch("vibe.runtime.subprocess.run") as run:+ self.assertTrue(runtime._ensure_linger_enabled(allow_enable=True))+ run.assert_called_once()+ self.assertIn("enable-linger", run.call_args.args[0])++ def test_fails_open_when_enable_does_not_take(self):+ with patch("vibe.runtime._linger_is_enabled", side_effect=[False, False]):+ with patch("vibe.runtime.subprocess.run"):+ self.assertFalse(runtime._ensure_linger_enabled(allow_enable=True))+++class ResourceGovernanceModeTests(unittest.TestCase):+ def test_broken_config_defaults_to_auto(self):+ with patch("config.v2_config.V2Config.load", side_effect=RuntimeError("boom")):+ self.assertEqual(runtime._resource_governance_mode(), "auto")+++class StartServiceUsesScopePrefixTests(unittest.TestCase):+ def test_start_service_prepends_scope_prefix_to_argv(self):+ marker = ["systemd-run", "--user", "--scope", "-q", "-p", "Delegate=yes", "--"]+ captured = {}++ def fake_spawn(args, *a, **kw):+ captured["args"] = args+ raise _StopSpawn()++ with ExitStack() as stack:+ stack.enter_context(patch("vibe.runtime.extra_service_process_pids", return_value=[]))+ stack.enter_context(+ patch("vibe.runtime.service_instance_lock_available", return_value=(True, 0))+ )+ stack.enter_context(patch("vibe.runtime.paths.get_runtime_pid_path", return_value=Path("/nonexistent/x.pid")))+ stack.enter_context(patch("vibe.runtime.maybe_systemd_scope_prefix", return_value=marker))+ stack.enter_context(patch("vibe.runtime.spawn_service_background_process", side_effect=fake_spawn))+ stack.enter_context(+ patch("storage.migrations.guard_source_checkout_default_state_bootstrap", create=True)+ )+ with self.assertRaises(_StopSpawn):+ runtime.start_service(wait_for_ready=False, initial_ready_timeout=0)++ self.assertEqual(captured["args"][: len(marker)], marker)+ self.assertEqual(captured["args"][len(marker):], [sys.executable, str(runtime.get_service_main_path())])+++class AdoptScopedServiceOwnerTests(unittest.TestCase):+ """The scope-gated fallback that neutralizes the systemd-run pid concern."""++ def test_adopts_live_lock_holder_when_it_differs_from_shim(self):+ proc = object()+ with ExitStack() as stack:+ stack.enter_context(patch("vibe.runtime.resolve_service_owner_pid", return_value=4321))+ stack.enter_context(patch("vibe.runtime.pid_alive", return_value=True))+ rec = stack.enter_context(patch("vibe.runtime._record_service_pid_reservation"))+ reap = stack.enter_context(+ patch(+ "vibe.runtime._reap_service_start_process",+ side_effect=lambda pid: runtime._SERVICE_START_PROCESSES.pop(pid, None),+ )+ )+ stack.enter_context(patch.dict("vibe.runtime._SERVICE_START_PROCESSES", {1234: proc}, clear=True))+ self.assertEqual(runtime._adopt_scoped_service_owner(1234), 4321)+ rec.assert_called_once_with(4321)+ reap.assert_called_once_with(1234)+ self.assertNotIn(1234, runtime._SERVICE_START_PROCESSES)+ self.assertNotIn(4321, runtime._SERVICE_START_PROCESSES)++ def test_no_adoption_when_owner_matches_shim_pid(self):+ # The normal exec() case: Popen.pid already IS the lock holder.+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=1234):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with patch("vibe.runtime._record_service_pid_reservation") as rec:+ self.assertIsNone(runtime._adopt_scoped_service_owner(1234))+ rec.assert_not_called()++ def test_no_adoption_when_no_live_owner_yet(self):+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=None):+ with patch("vibe.runtime._record_service_pid_reservation") as rec:+ self.assertIsNone(runtime._adopt_scoped_service_owner(1234))+ rec.assert_not_called()++ def test_no_adoption_when_owner_not_alive(self):+ with patch("vibe.runtime.resolve_service_owner_pid", return_value=4321):+ with patch("vibe.runtime.pid_alive", return_value=False):+ self.assertIsNone(runtime._adopt_scoped_service_owner(1234))+++class ReapServiceStartProcessTests(unittest.TestCase):+ def test_reaps_tracked_process_in_daemon_thread(self):+ process = Mock()+ thread = Mock()+ with patch.dict(runtime._SERVICE_START_PROCESSES, {1234: process}, clear=True):+ with patch("vibe.runtime.threading.Thread", return_value=thread) as thread_factory:+ runtime._reap_service_start_process(1234)++ self.assertNotIn(1234, runtime._SERVICE_START_PROCESSES)+ thread_factory.assert_called_once()+ self.assertTrue(thread_factory.call_args.kwargs["daemon"])+ thread_factory.call_args.kwargs["target"]()+ process.wait.assert_called_once_with()+ thread.start.assert_called_once_with()+++class WaitForScopedServicePidTests(unittest.TestCase):+ """Poll-and-adopt loop that resolves the authoritative lock-holder pid."""++ def test_returns_spawn_pid_when_recorded_immediately(self):+ with patch("vibe.runtime.service_pid_recorded", return_value=True):+ with patch.dict("vibe.runtime._SERVICE_START_PROCESSES", {111: object()}, clear=True):+ self.assertEqual(runtime._wait_for_scoped_service_pid(111, 5.0), 111)+ self.assertNotIn(111, runtime._SERVICE_START_PROCESSES)++ def test_adopts_lock_holder_then_returns_it(self):+ with ExitStack() as stack:+ # spawn pid never recorded; adopted owner is recorded on the next tick.+ stack.enter_context(patch("vibe.runtime.service_pid_recorded", side_effect=[False, True]))+ stack.enter_context(patch("vibe.runtime._adopt_scoped_service_owner", return_value=222))+ stack.enter_context(patch("vibe.runtime.time.sleep"))+ self.assertEqual(runtime._wait_for_scoped_service_pid(111, 5.0), 222)++ def test_returns_none_on_timeout(self):+ times = iter([0.0, 0.0, 10.0]) # deadline=5.0; third tick is past it+ with ExitStack() as stack:+ stack.enter_context(patch("vibe.runtime.service_pid_recorded", return_value=False))+ stack.enter_context(patch("vibe.runtime._adopt_scoped_service_owner", return_value=None))+ stack.enter_context(patch("vibe.runtime._service_start_exit_code", return_value=None))+ stack.enter_context(patch("vibe.runtime.pid_alive", return_value=True))+ stack.enter_context(patch("vibe.runtime.resolve_service_owner_pid", return_value=None))+ stack.enter_context(patch("vibe.runtime.time.sleep"))+ stack.enter_context(patch("vibe.runtime.time.monotonic", side_effect=lambda: next(times)))+ self.assertIsNone(runtime._wait_for_scoped_service_pid(111, 5.0))+++class StartScopedServiceResultTests(unittest.TestCase):+ def test_returns_ready_pid_from_first_phase(self):+ with patch("vibe.runtime._wait_for_scoped_service_pid", return_value=333):+ self.assertEqual(+ runtime._start_scoped_service_result(333, initial_ready_timeout=5.0, wait_for_ready=True),+ 333,+ )++ def test_fast_return_adopts_owner_when_not_waiting(self):+ with ExitStack() as stack:+ stack.enter_context(patch("vibe.runtime._wait_for_scoped_service_pid", return_value=None))+ stack.enter_context(patch("vibe.runtime._service_start_exit_code", return_value=None))+ stack.enter_context(patch("vibe.runtime.resolve_service_owner_pid", return_value=444))+ stack.enter_context(patch("vibe.runtime.pid_alive", return_value=True))+ self.assertEqual(+ runtime._start_scoped_service_result(111, initial_ready_timeout=0, wait_for_ready=False),+ 444,+ )++ def test_raises_when_spawn_exits_with_no_owner(self):+ with ExitStack() as stack:+ stack.enter_context(patch("vibe.runtime._wait_for_scoped_service_pid", return_value=None))+ stack.enter_context(patch("vibe.runtime._service_start_exit_code", return_value=1))+ stack.enter_context(patch("vibe.runtime.resolve_service_owner_pid", return_value=None))+ with self.assertRaises(RuntimeError):+ runtime._start_scoped_service_result(111, initial_ready_timeout=5.0, wait_for_ready=True)+++class WaitForServiceReadyTests(unittest.TestCase):+ """Public wait that resolves the authoritative owner for any caller."""++ def test_returns_resolved_owner_when_spawn_pid_is_a_wrapper(self):+ # spawn pid never records itself; the lock holder is a different pid.+ with ExitStack() as stack:+ stack.enter_context(patch("vibe.runtime.service_pid_recorded", side_effect=[False, True]))+ stack.enter_context(patch("vibe.runtime._adopt_scoped_service_owner", return_value=999))+ stack.enter_context(patch("vibe.runtime.time.sleep"))+ self.assertEqual(runtime.wait_for_service_ready(111, 5.0), 999)++ def test_returns_none_when_no_owner_appears(self):+ times = iter([0.0, 0.0, 10.0])+ with ExitStack() as stack:+ stack.enter_context(patch("vibe.runtime.service_pid_recorded", return_value=False))+ stack.enter_context(patch("vibe.runtime._adopt_scoped_service_owner", return_value=None))+ stack.enter_context(patch("vibe.runtime._service_start_exit_code", return_value=None))+ stack.enter_context(patch("vibe.runtime.pid_alive", return_value=True))+ stack.enter_context(patch("vibe.runtime.resolve_service_owner_pid", return_value=None))+ stack.enter_context(patch("vibe.runtime.time.sleep"))+ stack.enter_context(patch("vibe.runtime.time.monotonic", side_effect=lambda: next(times)))+ self.assertIsNone(runtime.wait_for_service_ready(111, 5.0))+++class _StopSpawn(Exception):+ pass+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.pyindex 9044b40d1..8482d41ab 100644--- a/tests/test_runtime_service_lock.py+++ b/tests/test_runtime_service_lock.py@@ -15,8 +15,16 @@ class RuntimeServiceLockTests(unittest.TestCase):def setUp(self):self._extra_service_pids = patch("vibe.runtime.extra_service_process_pids", return_value=[])self._extra_service_pids.start()+ # These tests target the generic (non-scoped) start_service contract via+ # wait_for_service_pid. On a Linux dev host with a user systemd manager,+ # maybe_systemd_scope_prefix() is truthy and would route start_service+ # through the scoped poll-and-adopt path (and real host lock state), so+ # pin it off here. The scoped path has its own dedicated tests.+ self._no_scope = patch("vibe.runtime.maybe_systemd_scope_prefix", return_value=[])+ self._no_scope.start()def tearDown(self):+ self._no_scope.stop()self._extra_service_pids.stop()def test_start_service_reuses_existing_live_pid(self):@@ -236,6 +244,67 @@ class RuntimeServiceLockTests(unittest.TestCase):self.assertEqual(pid, 67890)spawn_background.assert_not_called()+ def test_start_service_reuses_scoped_wrapper_reservation(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ pid_path = Path(tmpdir) / "service.pid"+ pid_path.write_text("67890", encoding="utf-8")+ command = runtime.shlex.join(+ [+ "systemd-run",+ "--user",+ "--scope",+ "-q",+ "-p",+ "Delegate=yes",+ "--",+ sys.executable,+ str(runtime.get_service_main_path()),+ ]+ )++ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with patch("vibe.runtime.get_process_command", return_value=command):+ with patch("vibe.runtime.service_pid_recorded", return_value=False):+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:+ pid = runtime.start_service(wait_for_ready=False)++ self.assertEqual(pid, 67890)+ spawn_background.assert_not_called()++ def test_start_service_adopts_scoped_wrapper_lock_holder(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ pid_path = Path(tmpdir) / "service.pid"+ pid_path.write_text("67890", encoding="utf-8")+ command = runtime.shlex.join(+ [+ "systemd-run",+ "--user",+ "--scope",+ "-q",+ "-p",+ "Delegate=yes",+ "--",+ sys.executable,+ str(runtime.get_service_main_path()),+ ]+ )++ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with patch("vibe.runtime.get_process_command", return_value=command):+ with patch("vibe.runtime.service_pid_recorded", return_value=False):+ with patch("vibe.runtime.wait_for_service_ready", return_value=78901) as wait_for_ready:+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:+ pid = runtime.start_service()++ self.assertEqual(pid, 78901)+ wait_for_ready.assert_called_once_with(+ 67890,+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,+ )+ spawn_background.assert_not_called()+def test_stop_service_stops_pending_pid_reservation(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"@@ -336,6 +405,40 @@ class RuntimeServiceLockTests(unittest.TestCase):self.assertTrue(processes[0]["home_match"])self.assertFalse(processes[0]["lock_owner"])+ def test_service_processes_ignores_systemd_scope_wrapper(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ home = Path(tmpdir) / "home"+ home.mkdir()+ command = [+ "systemd-run",+ "--user",+ "--scope",+ "-q",+ "-p",+ "Delegate=yes",+ "--",+ sys.executable,+ str(runtime.get_service_main_path()),+ ]++ class FakeProcess:+ info = {"pid": 33333, "cmdline": command}++ def cwd(self):+ return str(runtime.get_working_dir())++ def environ(self):+ return {+ "AVIBE_HOME": str(home),+ "VIBE_REQUIRE_SHUTDOWN_INTENT": "1",+ }++ with patch("vibe.runtime.paths.get_vibe_remote_dir", return_value=home):+ with patch("vibe.runtime.psutil.process_iter", return_value=[FakeProcess()]):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with patch("vibe.runtime.service_lock_held_by", return_value=False):+ self.assertEqual(runtime.service_processes(), [])+def test_service_processes_ignores_same_user_service_main_without_avibe_marker(self):with tempfile.TemporaryDirectory() as tmpdir:home = Path(tmpdir)diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.pyindex 87f977ccf..4f697725c 100644--- a/tests/test_service_logging_handlers.py+++ b/tests/test_service_logging_handlers.py@@ -59,6 +59,10 @@ def test_start_service_disables_stdout_logging_for_background_process(monkeypatcmonkeypatch.setattr(runtime, "pid_alive", lambda pid: False)monkeypatch.setattr(runtime, "get_service_main_path", lambda: Path("/tmp/main.py"))monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, 0))+ # Exercise the generic (non-scoped) spawn path deterministically: on a Linux+ # dev host maybe_systemd_scope_prefix() is truthy and would route through the+ # scoped poll-and-adopt path instead of wait_for_service_pid.+ monkeypatch.setattr(runtime, "maybe_systemd_scope_prefix", lambda: [])# Stub the real spawn so we never fork a real vibe service, and short-circuit# the post-spawn lock wait. This captures the env start_service would launch with.monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, *args, **kwargs: True)diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex bcb4ee42b..61123fb27 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -626,7 +626,7 @@ def test_cmd_start_keeps_ui_up_while_service_lock_is_slow(monkeypatch):monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port: calls.append(("start_ui", host, port)) or 5678)monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: False)- monkeypatch.setattr(cli.runtime, "wait_for_service_pid", lambda pid, timeout: False)+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: None)monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: pid == 1234)monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))@@ -651,7 +651,7 @@ def test_cmd_start_fails_only_when_slow_service_exits(monkeypatch):monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port: 5678)monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: False)- monkeypatch.setattr(cli.runtime, "wait_for_service_pid", lambda pid, timeout: False)+ monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: None)monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: False)monkeypatch.setattr(cli.runtime, "write_status", lambda *args: statuses.append(args))diff --git a/ui/package-lock.json b/ui/package-lock.jsonindex 1707e1cde..897eca530 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -124,7 +124,6 @@"integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@babel/code-frame": "^7.28.6","@babel/generator": "^7.28.6",@@ -291,7 +290,6 @@"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz","integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==","license": "MIT",- "peer": true,"engines": {"node": ">=6.9.0"}@@ -394,6 +392,7 @@"dev": true,"license": "MIT","optional": true,+ "peer": true,"dependencies": {"tslib": "^2.4.0"}@@ -939,7 +938,6 @@"resolved": "https://registry.npmjs.org/@lexical/react/-/react-0.45.0.tgz","integrity": "sha512-LAaceAtcQpVMDvldhkrQC1MSawpj7aAm1CfGg6RbyQgTDDp2fKnP1gDhjQIef3lH8W2fYeXRe66EdzaFkoGHKA==","license": "MIT",- "peer": true,"dependencies": {"@floating-ui/react": "^0.27.19","@lexical/devtools-core": "0.45.0",@@ -1027,7 +1025,6 @@"resolved": "https://registry.npmjs.org/@lexical/utils/-/utils-0.45.0.tgz","integrity": "sha512-Fo5MMErqoPlUyTw1qVMZ9kE33ZjJF957KU683tsCrrlaVisVxpboL7BbAnxWTwCcIpAsfc6AUndJJ70M9NDMGg==","license": "MIT",- "peer": true,"dependencies": {"@lexical/internal": "0.45.0","@lexical/selection": "0.45.0",@@ -2642,7 +2639,6 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.8.tgz","integrity": "sha512-3MbSL37jEchWZz2p2mjntRZtPt837ij10ApxKfgmXCTuHWagYg7iA5bqPw6C8BMPfwidlvfPI/fxOc42HLhcyg==","license": "MIT",- "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -2653,7 +2649,6 @@"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==","devOptional": true,"license": "MIT",- "peer": true,"peerDependencies": {"@types/react": "^19.2.0"}@@ -2715,7 +2710,6 @@"integrity": "sha512-npiaib8XzbjtzS2N4HlqPvlpxpmZ14FjSJrteZpPxGUaYPlvhzlzUZ4mZyABo0EFrOWnvyd0Xxroq//hKhtAWg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "8.53.0","@typescript-eslint/types": "8.53.0",@@ -3174,7 +3168,6 @@"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","dev": true,"license": "MIT",- "peer": true,"bin": {"acorn": "bin/acorn"},@@ -3367,7 +3360,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -3495,7 +3487,6 @@"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz","integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==","license": "MIT",- "peer": true,"dependencies": {"@kurkle/color": "^0.3.0"},@@ -3886,7 +3877,6 @@"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.8.0","@eslint-community/regexpp": "^4.12.1",@@ -4437,7 +4427,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"@babel/runtime": "^7.28.4"},@@ -4611,6 +4600,7 @@"resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz","integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==","license": "MIT",+ "peer": true,"funding": {"type": "GitHub Sponsors ❤","url": "https://github.com/sponsors/dmonad"@@ -4734,7 +4724,6 @@"resolved": "https://registry.npmjs.org/lexical/-/lexical-0.45.0.tgz","integrity": "sha512-z2M9C2ILPW7SopQE1aKbOFdZJbe3HvsrgWnJKveMDrSEvVjU9Hce4UpKVsAdkwY7TgY9RDuCV3+sfrGu0WkL+w==","license": "MIT",- "peer": true,"dependencies": {"@lexical/internal": "0.45.0"}@@ -4757,6 +4746,7 @@"resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz","integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==","license": "MIT",+ "peer": true,"dependencies": {"isomorphic.js": "^0.2.4"},@@ -6004,7 +5994,6 @@"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz","integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==","license": "MIT",- "peer": true,"dependencies": {"dompurify": "3.2.7","marked": "14.0.0"@@ -6235,7 +6224,6 @@"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=12"},@@ -6263,7 +6251,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"nanoid": "^3.3.12","picocolors": "^1.1.1",@@ -6351,7 +6338,6 @@"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz","integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==","license": "MIT",- "peer": true,"engines": {"node": ">=0.10.0"}@@ -6361,7 +6347,6 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz","integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==","license": "MIT",- "peer": true,"dependencies": {"scheduler": "^0.27.0"},@@ -7055,7 +7040,6 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","devOptional": true,"license": "Apache-2.0",- "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -7315,7 +7299,6 @@"integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"lightningcss": "^1.32.0","picomatch": "^4.0.4",@@ -7847,7 +7830,6 @@"integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==","dev": true,"license": "MIT",- "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}diff --git a/vibe/cli.py b/vibe/cli.pyindex 2653958ea..ca704b88b 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -9693,10 +9693,17 @@ def cmd_start():service_ready = runtime.service_pid_recorded(service_pid)if not service_ready:runtime.write_status("starting", "waiting for service process", service_pid, ui_pid)- service_ready = runtime.wait_for_service_pid(+ # Resolve the authoritative service.lock holder rather than waiting on the+ # raw pid start_service handed back: under a delegated user scope that pid+ # can be a launcher that never takes the lock, so wait_for_service_ready+ # adopts and returns the real owner instead of stalling the full timeout.+ resolved_pid = runtime.wait_for_service_ready(service_pid,timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,)+ if resolved_pid is not None:+ service_pid = resolved_pid+ service_ready = Trueif service_ready:runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)elif runtime.pid_alive(service_pid):diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 1e7a78dae..bb2ab74fa 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -354,7 +354,11 @@ def _run_restart_job(if not runtime.service_pid_recorded(new_pid):write(f"start runtime returned while service pid={new_pid} is still acquiring its lock")wait_lock_started_at = time.monotonic()- if not runtime.wait_for_service_pid(new_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS):+ # Resolve the real lock holder: under a delegated user scope the+ # returned pid may be a launcher that never records itself, so adopt+ # the authoritative owner instead of waiting on a pid that can't win.+ resolved_pid = runtime.wait_for_service_ready(new_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS)+ if resolved_pid is None:mark_duration("wait_service_lock_seconds", wait_lock_started_at)return _fail(payload,@@ -363,6 +367,7 @@ def _run_restart_job(3,started_at=restart_started_at,)+ new_pid = resolved_pidmark_duration("wait_service_lock_seconds", wait_lock_started_at)recorded_ui_pid = service_status.get("ui_pid") if service_status else ui_pidruntime.write_status("running", f"pid={new_pid}", new_pid, recorded_ui_pid if isinstance(recorded_ui_pid, int) else None)diff --git a/vibe/runtime.py b/vibe/runtime.pyindex 40000a5ad..f8bc3398c 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -1,9 +1,11 @@+import getpassimport ipaddressimport jsonimport loggingimport osimport signalimport shlex+import shutilimport socketimport subprocessimport sys@@ -575,10 +577,29 @@ def _path_is_service_entry(path: Path, current_main: Path | None) -> bool:return False+def _systemd_scope_target_argv(args: list[str]) -> list[str] | None:+ if not args:+ return None+ executable_name = Path(args[0].strip("\"'")).name.lower()+ if executable_name != "systemd-run":+ return None+ try:+ separator = args.index("--")+ except ValueError:+ return None+ if "--scope" not in args[1:separator]:+ return None+ target = args[separator + 1 :]+ return target or None++def _service_entry_arg_from_argv(args: list[str]) -> str | None:if not args:return Noneexecutable_name = Path(args[0].strip("\"'")).name.lower()+ scope_target = _systemd_scope_target_argv(args)+ if scope_target is not None:+ return _service_entry_arg_from_argv(scope_target)if executable_name.startswith("python"):for arg in args[1:]:cleaned_arg = arg.strip("\"'")@@ -593,13 +614,20 @@ def _service_entry_arg_from_argv(args: list[str]) -> str | None:return None-def _command_looks_like_service_entry(command: str | None, *, cwd: str | None = None) -> bool:+def _command_looks_like_service_entry(+ command: str | None,+ *,+ cwd: str | None = None,+ include_scope_wrapper: bool = True,+) -> bool:if not command:return Falsetry:args = shlex.split(command, posix=(os.name != "nt"))except ValueError:return False+ if not include_scope_wrapper and _systemd_scope_target_argv(args) is not None:+ return Falsecurrent_main = _safe_resolve_path(get_service_main_path())cwd_path = _safe_resolve_path(cwd) if cwd else Noneentry_arg = _service_entry_arg_from_argv(args)@@ -697,7 +725,11 @@ def service_processes(*, include_unverified: bool = False) -> list[dict]:continuesession_leader = _process_is_service_session_leader(pid)command = _process_command_from_info(proc)- if not _command_looks_like_service_entry(command, cwd=_process_cwd(proc)):+ if not _command_looks_like_service_entry(+ command,+ cwd=_process_cwd(proc),+ include_scope_wrapper=False,+ ):continuelock_owner = service_lock_held_by(pid)home_match = _process_home_matches_current(proc)@@ -888,8 +920,27 @@ def _record_service_pid_reservation(pid: int) -> None:pid_path.write_text(str(pid), encoding="utf-8")+def _reap_service_start_process(pid: int) -> None:+ process = _SERVICE_START_PROCESSES.pop(pid, None)+ wait = getattr(process, "wait", None)+ if not callable(wait):+ return++ def _wait() -> None:+ try:+ wait()+ except Exception:+ logger.debug("Failed to reap service launcher pid=%s", pid, exc_info=True)++ threading.Thread(+ target=_wait,+ name=f"vibe-service-launcher-reaper-{pid}",+ daemon=True,+ ).start()++def _clear_service_pid_reservation(pid: int) -> None:- _SERVICE_START_PROCESSES.pop(pid, None)+ _reap_service_start_process(pid)pid_path = paths.get_runtime_pid_path()try:recorded_pid = int(pid_path.read_text(encoding="utf-8").strip())@@ -981,7 +1032,7 @@ def wait_for_service_pid(pid: int, timeout: float = SERVICE_LOCK_READY_TIMEOUT_Sdeadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:if service_pid_recorded(pid):- _SERVICE_START_PROCESSES.pop(pid, None)+ _reap_service_start_process(pid)return Trueif _service_start_exit_code(pid) is not None:return False@@ -991,7 +1042,7 @@ def wait_for_service_pid(pid: int, timeout: float = SERVICE_LOCK_READY_TIMEOUT_Stime.sleep(0.1)ready = service_pid_recorded(pid)if ready:- _SERVICE_START_PROCESSES.pop(pid, None)+ _reap_service_start_process(pid)elif _service_start_exit_code(pid) is not None:return Falsereturn ready@@ -1127,6 +1178,273 @@ def _raise_service_start_not_ready(pid: int, *, timeout: float) -> None:raise RuntimeError(f"Vibe service process pid={pid} did not acquire the service lock")+# --- cgroup resource-governance bootstrap -----------------------------------+#+# ``core/resource_governance.py`` can only move agent subprocesses into a+# memory-capped cgroup when Avibe itself runs inside a *delegated* cgroup+# subtree. A normal login lands the service in a root-owned, non-delegated+# ``session-*.scope`` where ``mkdir`` returns EPERM, so governance is inert.+#+# The kernel's delegation-containment rule forbids a non-root process from+# migrating itself out of that session scope into the user manager's delegated+# tree (the common ancestor ``user-<uid>.slice`` is root-owned). The only way+# in is to be *launched* inside the delegated tree. ``systemd-run --user+# --scope`` does exactly that: it asks the user systemd manager to create a+# transient scope under ``user@<uid>.service/app.slice`` (qiqi-owned, memory ++# pids delegated) and then ``execve()``s into the target — so the launched+# process keeps its real pid and cmdline (no supervising parent), and Avibe's+# pid-tracking is unaffected.+#+# This is best-effort and fails open: on macOS, without systemd, without a live+# user manager, when governance is disabled, or when linger can't be confirmed,+# the prefix is empty and the service starts exactly as before.++SYSTEMD_SCOPE_PREFIX = (+ "systemd-run",+ "--user",+ "--scope",+ "-q", # suppress the "Running scope as unit ..." banner from the log sink+ "-p",+ "Delegate=yes",+ "--",+)+++def _resource_governance_mode() -> str:+ try:+ from config.v2_config import V2Config+ from core.resource_governance import config_from_runtime++ return str(config_from_runtime(V2Config.load()).get("mode") or "auto").strip().lower()+ except Exception:+ # Absent/broken config must not block startup; treat as the default.+ return "auto"+++def _current_username() -> str:+ try:+ return getpass.getuser()+ except Exception:+ return str(os.getuid())+++def _linger_is_enabled(user: str) -> bool:+ try:+ result = subprocess.run(+ ["loginctl", "show-user", user, "-p", "Linger"],+ capture_output=True,+ text=True,+ timeout=5,+ )+ except Exception:+ return False+ return "Linger=yes" in (result.stdout or "")+++def _ensure_linger_enabled(*, allow_enable: bool) -> bool:+ """Confirm that the user lingers, enabling it only when explicitly allowed.++ Once the service lives under ``user@<uid>.service`` instead of a login+ session scope, logind tears that manager down on last-session-end unless+ lingering is enabled — which would kill Avibe on the first SSH logout.+ ``loginctl enable-linger`` changes persistent account state, so automatic+ governance only observes it. Explicitly enabled governance may opt in to+ that change. Fail open: if we can't confirm linger, skip the scope wrap.+ """+ user = _current_username()+ if _linger_is_enabled(user):+ return True+ if not allow_enable:+ return False+ try:+ subprocess.run(+ ["loginctl", "enable-linger", user],+ capture_output=True,+ text=True,+ timeout=5,+ )+ except Exception:+ return False+ return _linger_is_enabled(user)+++def _systemd_run_self_test_ok(timeout: float = 5.0) -> bool:+ """Bounded dry-run so DBus/user-manager flakiness surfaces here, not as an+ opaque 'service did not acquire lock' timeout 30s later."""+ try:+ result = subprocess.run(+ ["systemd-run", "--user", "--scope", "-q", "-p", "Delegate=yes", "--", "true"],+ capture_output=True,+ text=True,+ timeout=timeout,+ )+ except Exception:+ return False+ return result.returncode == 0+++def maybe_systemd_scope_prefix() -> list[str]:+ """Return the ``systemd-run --user --scope`` argv prefix to launch the+ service inside a delegated user cgroup, or ``[]`` to start unwrapped.++ All predicates must hold; any failure fails open to today's behavior. There+ is deliberately no "already inside our own scope" guard: nested+ ``systemd-run --scope`` creates a harmless *sibling* scope (not a nested+ child), and such a guard would misfire when a governed agent shells out to+ ``vibe restart`` — landing the restarted service inside the old+ memory-capped, ``oom.group`` agent cgroup.+ """+ if not sys.platform.startswith("linux"):+ return []+ if shutil.which("systemd-run") is None:+ return []+ getuid = getattr(os, "getuid", None)+ if getuid is None:+ return []+ if not Path(f"/run/user/{getuid()}/systemd/private").is_socket():+ return []+ try:+ from core.resource_governance import detect_cgroup_root++ if detect_cgroup_root() is None:+ return []+ except Exception:+ return []+ governance_mode = _resource_governance_mode()+ if governance_mode == "disabled":+ return []+ if not _ensure_linger_enabled(allow_enable=governance_mode == "enabled"):+ logger.warning(+ "cgroup scope bootstrap: could not confirm user linger; "+ "starting service without a delegated user scope"+ )+ return []+ if not _systemd_run_self_test_ok():+ logger.warning(+ "cgroup scope bootstrap: systemd-run self-test failed; "+ "starting service without a delegated user scope"+ )+ return []+ return list(SYSTEMD_SCOPE_PREFIX)+++def _adopt_scoped_service_owner(prev_pid: int) -> int | None:+ """Adopt the authoritative ``service.lock`` holder if it differs from ``prev_pid``.++ Called on every tick of ``_wait_for_scoped_service_pid``. ``--scope`` exec()s+ into the target, so ``prev_pid`` is normally already the real service pid and+ the owner matches it (no-op). This exists to stay correct on any host where a+ shim survives as a distinct parent: the flock in ``service.lock`` is the+ authoritative owner signal (see ``resolve_service_owner_pid``), so if a+ *different* live process now holds it, adopt that pid instead of the shim's.+ Returns the adopted pid, or ``None`` to leave ``prev_pid`` in place.+ """+ owner = resolve_service_owner_pid(include_starting=False)+ if owner and owner != prev_pid and pid_alive(owner):+ # The shim's Popen must not be attributed to `owner`, but a long-lived+ # caller still needs to wait() it after the service exits.+ _reap_service_start_process(prev_pid)+ _record_service_pid_reservation(owner)+ logger.info(+ "cgroup scope bootstrap: adopting lock-holder pid=%s as the service owner (shim pid=%s)",+ owner,+ prev_pid,+ )+ return owner+ return None+++def _wait_for_scoped_service_pid(spawn_pid: int, timeout: float) -> int | None:+ """Poll a ``systemd-run --user --scope`` launch until it is lock-verified.++ ``--scope`` exec()s into the target, so ``spawn_pid`` is normally already the+ service pid. To stay correct even if a shim ever survives as a distinct+ parent, the ``service.lock`` flock holder is authoritative: on every tick we+ adopt a differing live lock holder, so we never settle on an unverified+ (possibly wrapper) pid. Returns the ready pid, or ``None`` if it neither+ became ready nor left a live owner within ``timeout``.+ """+ pid = spawn_pid+ deadline = time.monotonic() + timeout+ while True:+ if service_pid_recorded(pid):+ _reap_service_start_process(pid)+ return pid+ adopted = _adopt_scoped_service_owner(pid)+ if adopted is not None:+ pid = adopted+ continue+ # The spawn process is gone and nobody holds the lock -> startup failed.+ if _service_start_exit_code(spawn_pid) is not None:+ if resolve_service_owner_pid(include_starting=False) is None:+ return None+ elif not pid_alive(pid) and resolve_service_owner_pid(include_starting=False) is None:+ return None+ if time.monotonic() >= deadline:+ return None+ time.sleep(0.05)+++def wait_for_service_ready(+ spawn_pid: int, timeout: float = SERVICE_SLOW_START_TIMEOUT_SECONDS+) -> int | None:+ """Wait until the service is lock-verified and return the authoritative owner pid.++ Unlike ``wait_for_service_pid()``, which only confirms a *specific* pid, this+ resolves the real ``service.lock`` holder: if the pid handed back by+ ``start_service()`` was a launcher/wrapper that never takes the lock (e.g. a+ surviving ``systemd-run`` parent under some host configuration), this adopts+ and returns the live lock holder instead of waiting forever on a pid that can+ never be recorded. Returns the resolved owner pid, or ``None`` if no owner+ became ready within ``timeout``. In the common case ``spawn_pid`` already IS+ the owner and this behaves like ``wait_for_service_pid`` returning that pid.+ """+ return _wait_for_scoped_service_pid(spawn_pid, timeout)+++def _start_scoped_service_result(+ spawn_pid: int,+ *,+ initial_ready_timeout: float,+ wait_for_ready: bool,+) -> int:+ """Resolve the final service pid for a scoped launch, polling+adopting the+ authoritative lock holder rather than trusting the spawn pid."""+ # A scoped launch must resolve to a lock-verified pid, so give the first+ # phase a floor even when the caller passed initial_ready_timeout=0 (e.g.+ # restart_supervisor): the spawn pid alone is not a trustworthy owner signal+ # under a scope wrapper. In the common exec() case this returns as soon as+ # the service acquires the lock, so the floor rarely costs anything.+ first_timeout = max(initial_ready_timeout, SERVICE_LOCK_READY_TIMEOUT_SECONDS)+ ready = _wait_for_scoped_service_pid(spawn_pid, first_timeout)+ if ready is not None:+ return ready+ exit_code = _service_start_exit_code(spawn_pid)+ if exit_code is not None and resolve_service_owner_pid(include_starting=False) is None:+ raise RuntimeError(+ f"Vibe service process pid={spawn_pid} exited with code {exit_code} before acquiring the service lock"+ )+ if not wait_for_ready:+ candidate = resolve_service_owner_pid() or spawn_pid+ if pid_alive(candidate):+ logger.warning(+ "Scoped Vibe service pid=%s has not acquired the service lock yet; "+ "continuing while it finishes startup",+ candidate,+ )+ return candidate+ ready = _wait_for_scoped_service_pid(spawn_pid, SERVICE_SLOW_START_TIMEOUT_SECONDS)+ if ready is not None:+ return ready+ exit_code = _service_start_exit_code(spawn_pid)+ if exit_code is not None:+ raise RuntimeError(+ f"Vibe service process pid={spawn_pid} exited with code {exit_code} before acquiring the service lock"+ )+ _raise_service_start_not_ready(spawn_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)+ return spawn_pid++def start_service(*,wait_for_ready: bool = True,@@ -1150,8 +1468,12 @@ def start_service(if _pid_reservation_is_fresh(pid_path, existing_pid):if not wait_for_ready:return existing_pid- if wait_for_service_pid(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS):- return existing_pid+ ready_pid = wait_for_service_ready(+ existing_pid,+ timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS,+ )+ if ready_pid is not None:+ return ready_pid_raise_service_start_not_ready(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)logger.warning("Ignoring stale service pid file pid=%s because it never acquired the service lock",@@ -1186,8 +1508,11 @@ def start_service(raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=extra_pids[0])main_path = get_service_main_path()+ scope_prefix = maybe_systemd_scope_prefix()+ if scope_prefix:+ logger.info("cgroup scope bootstrap: launching service inside a delegated user scope")process = spawn_service_background_process(- [sys.executable, str(main_path)],+ [*scope_prefix, sys.executable, str(main_path)],"service_stdout.log","service_stderr.log",env={@@ -1199,6 +1524,14 @@ def start_service(pid = process.pid_SERVICE_START_PROCESSES[pid] = process_record_service_pid_reservation(pid)+ if scope_prefix:+ # Scoped launches resolve their pid via the authoritative lock holder+ # (poll-and-adopt), never by trusting the spawn pid alone.+ return _start_scoped_service_result(+ pid,+ initial_ready_timeout=initial_ready_timeout,+ wait_for_ready=wait_for_ready,+ )if initial_ready_timeout > 0 and wait_for_service_pid(pid, timeout=initial_ready_timeout):return pidexit_code = _service_start_exit_code(pid)