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
fix(memory): simplify subprocess lifecycle with retained public references (#1992)
rkrkrkke84c4c17f637
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 58ebdf7ed..c38500698 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -261,7 +261,7 @@ jobs:uv run --frozen --project scripts/memory_runtime \--with 'pytest==9.0.3' --with 'pytest-asyncio==1.4.0' \python -m pytest \- tests/test_memory_wake.py::test_pinned_everos_runtime_wakes_through_production_sidecar \+ tests/scenarios/memory_repair/test_memory_lifecycle_runtime.py::test_real_wake_preserves_old_and_processes_new_input \-ra | tee "$output"if grep -Eq '(^|[[:space:]])[0-9]+ skipped|SKIPPED' "$output"; thenecho "Memory Runtime contract tests must not skip."diff --git a/avibe_memory/process.py b/avibe_memory/process.pyindex df21bc34c..fac2e5fa2 100644--- a/avibe_memory/process.py+++ b/avibe_memory/process.py@@ -112,7 +112,6 @@ _PROCESSING_PROBE_TIMEOUT_SECONDS = PROCESSING_PROBE_MAX_DEADLINE_SECONDS_PROCESSING_PROBE_STDERR_BYTES = 2048_SOCKET_MODE = 0o600_OWNER_DIR_MODE = 0o700-_SAFETY_MONITOR_INTERVAL_SECONDS = 0.2_TREE_INSPECTION_INTERVAL_SECONDS = 1.0_SIDECAR_RECORD_FILENAME = "everos.sidecar.json"_SIDECAR_RECORD_MAX_BYTES = 4 * 1024@@ -252,7 +251,9 @@ class _ProcessHost(Protocol):def inspect_identity(self, pid: int) -> _ProcessIdentity | None: ...- def snapshot_tree(self, pid: int, process_group: int | None) -> dict[int, float]: ...+ def capture(self, pid: int) -> psutil.Process | None: ...++ def snapshot_tree(self, pid: int, process_group: int | None, owned=None) -> dict[int, psutil.Process | None]: ...def recorded_group_members(self,@@ -261,11 +262,11 @@ class _ProcessHost(Protocol):socket_path: Path,provider_root: Path,role: str | None = None,- ) -> tuple[dict[int, float], list[int]]: ...+ ) -> tuple[dict[int, psutil.Process | None], list[int]]: ...- def find_sidecars(self, *, socket_path: Path) -> dict[int, float]: ...+ def find_sidecars(self, *, socket_path: Path) -> dict[int, psutil.Process | None]: ...- def find_sidecars_by_root(self, *, provider_root: Path) -> dict[int, float]: ...+ def find_sidecars_by_root(self, *, provider_root: Path) -> dict[int, psutil.Process | None]: ...def find_syncs(self,@@ -273,13 +274,13 @@ class _ProcessHost(Protocol):provider_root: Path,python: Path,nonce: str,- ) -> dict[int, float]: ...+ ) -> dict[int, psutil.Process | None]: ...- def live(self, identities: Mapping[int, float]) -> dict[int, float]: ...+ def live(self, identities: Mapping[int, psutil.Process | None]) -> dict[int, psutil.Process | None]: ...def signal(self,- identities: Mapping[int, float],+ identities: Mapping[int, psutil.Process | None],signum: int,*,process_group: int | None = None,@@ -288,14 +289,14 @@ class _ProcessHost(Protocol):async def wait_for_exit(self,- identities: dict[int, float],+ identities: dict[int, psutil.Process | None],timeout_seconds: float,*,process_group: int | None = None,process: asyncio.subprocess.Process | None = None,) -> bool: ...- def has_tcp_listener(self, identities: Mapping[int, float]) -> bool: ...+ def has_tcp_listener(self, identities: Mapping[int, psutil.Process | None]) -> bool: ...class EverOSProcess:@@ -360,7 +361,7 @@ class EverOSProcess:self._watch_task: asyncio.Task[None] | None = Noneself._monitor_task: asyncio.Task[None] | None = Noneself._retained_provider_root_lock: _ProviderRootLock | None = None- self._owned_processes: dict[int, float] = {}+ self._owned_processes: dict[int, psutil.Process | None] = {}self._on_ready = on_readyself._before_start = before_startself._on_unexpected_exit = on_unexpected_exit@@ -411,7 +412,7 @@ class EverOSProcess:self._desired_running = Falseprocess = self._processprocess_group = self._process_group- owned_processes = dict(self._owned_processes)+ owned_processes = self._owned_processeswatch_task = self._watch_taskmonitor_task = self._monitor_taskself._starting = False@@ -451,7 +452,7 @@ class EverOSProcess:_ProcessKind.PROCESSING_PROBE,self._python,cwd=self._effective_home,- env=self._child_environment(),+ env=self._child_environment(role=_ProcessKind.PROCESSING_PROBE.value),capture_stderr=True,)except TypeError:@@ -459,14 +460,15 @@ class EverOSProcess:_ProcessKind.PROCESSING_PROBE,self._python,cwd=self._effective_home,- env=self._child_environment(),+ env=self._child_environment(role=_ProcessKind.PROCESSING_PROBE.value),)except (OSError, ValueError):logger.warning("EverOS processing probe could not start; branch=probe_spawn")return False+ owned_processes = {probe.pid: self._host.capture(probe.pid)}process_group = self._host.process_group(probe.pid)- owned_processes = self._host.snapshot_tree(probe.pid, process_group)+ _refresh_owned_process_tree(self._host, owned_processes, probe.pid, process_group)stderr = getattr(probe, "stderr", None)stderr_task = asyncio.create_task(_drain_probe_stderr(stderr)) if stderr is not None else Nonetry:@@ -480,6 +482,7 @@ class EverOSProcess:probe,process_group=process_group,owned_processes=owned_processes,+ role=_ProcessKind.PROCESSING_PROBE.value,)except Exception:logger.warning("EverOS processing probe cleanup failed")@@ -496,6 +499,7 @@ class EverOSProcess:probe,process_group=process_group,owned_processes=owned_processes,+ role=_ProcessKind.PROCESSING_PROBE.value,)except Exception:logger.warning("EverOS processing probe cleanup failed")@@ -509,6 +513,7 @@ class EverOSProcess:probe,process_group=process_group,owned_processes=owned_processes,+ role=_ProcessKind.PROCESSING_PROBE.value,)except Exception:logger.warning("EverOS processing probe cleanup failed")@@ -544,13 +549,15 @@ class EverOSProcess:))self._process = process+ self._owned_processes = {process.pid: self._host.capture(process.pid)}self._process_group = self._host.process_group(process.pid)- self._owned_processes = self._host.snapshot_tree(process.pid, self._process_group)- if not _host_identity_is_live(self._host, process.pid, self._owned_processes):- raise RuntimeError("could not establish sidecar process ownership")+ _refresh_owned_process_tree(self._host, self._owned_processes, process.pid, self._process_group)+ identity = _inspect_captured_identity(self._host, process.pid, self._owned_processes[process.pid])+ if identity is None:+ raise RuntimeError("sidecar exited before ownership could be recorded")self._ownership.record_launch(process.pid,- self._owned_processes[process.pid],+ identity.stamp,self._process_group,)if spawn_interrupted:@@ -573,7 +580,7 @@ class EverOSProcess:self._terminate_owned_tree(process,process_group=process_group,- owned_processes=dict(self._owned_processes),+ owned_processes=self._owned_processes,))except Exception:@@ -610,7 +617,7 @@ class EverOSProcess:logger.exception("EverOS sidecar start failed")process = self._processprocess_group = self._process_group- owned_processes = dict(self._owned_processes)+ owned_processes = self._owned_processescleanup_failed = Falseif process is not None:try:@@ -713,13 +720,7 @@ class EverOSProcess:while time.monotonic() < deadline:if process.returncode is not None:raise RuntimeError("sidecar exited before readiness")- if not _refresh_owned_process_tree(- self._host,- self._owned_processes,- process.pid,- self._process_group,- ):- raise RuntimeError("sidecar ownership changed before readiness")+ _refresh_owned_process_tree(self._host, self._owned_processes, process.pid, self._process_group)if self._socket_path.exists():self._secure_socket()if await client.health():@@ -733,7 +734,7 @@ class EverOSProcess:if process is not self._process:returnprocess_group = self._process_group- owned_processes = dict(self._owned_processes)+ owned_processes = self._owned_processesmonitor_task = self._monitor_tasktry:await self._terminate_owned_tree(@@ -775,41 +776,17 @@ class EverOSProcess:"""Keep tracking descendants and reject any later TCP listener."""try:- next_tree_inspection = time.monotonic()while process is self._process and process.returncode is None:- observed_at = time.monotonic()- if observed_at >= next_tree_inspection:- owned_processes = self._refresh_owned_processes(process.pid)- self._assert_no_tcp_listener(- process.pid,- owned_processes=owned_processes,- )- next_tree_inspection = observed_at + _TREE_INSPECTION_INTERVAL_SECONDS- elif not _host_identity_is_live(self._host, process.pid, self._owned_processes):- raise RuntimeError("sidecar ownership changed during monitoring")- await asyncio.sleep(_SAFETY_MONITOR_INTERVAL_SECONDS)+ owned_processes = self._refresh_owned_processes(process.pid)+ self._assert_no_tcp_listener(process.pid, owned_processes=owned_processes)+ await asyncio.sleep(_TREE_INSPECTION_INTERVAL_SECONDS)except asyncio.CancelledError:returnexcept Exception:if not self._desired_running:returnnotify_unexpected_exit = False- recorded_stamp = (- self._owned_processes.get(process.pid) if process.pid is not None else None- )- live_stamp = None- if process.pid is not None:- try:- live_stamp = _process_creation_stamp(psutil.Process(process.pid))- except Exception:- live_stamp = None- logger.exception(- "EverOS sidecar safety monitor rejected the child tree "- "(pid %s recorded_stamp=%s live_stamp=%s)",- process.pid,- recorded_stamp,- live_stamp,- )+ logger.exception("EverOS sidecar safety monitor rejected the child tree (pid %s)", process.pid)async with self._lifecycle_lock:if process is not self._process:return@@ -820,7 +797,7 @@ class EverOSProcess:await self._terminate_owned_tree(process,process_group=process_group,- owned_processes=dict(self._owned_processes),+ owned_processes=self._owned_processes,)except Exception:logger.warning("EverOS sidecar safety shutdown did not reap the child tree")@@ -915,41 +892,21 @@ class EverOSProcess:except FileNotFoundError:return- def _refresh_owned_processes(self, pid: int) -> dict[int, float]:- if not _refresh_owned_process_tree(- self._host,- self._owned_processes,- pid,- self._process_group,- ):- raise RuntimeError("sidecar ownership changed during monitoring")- unverifiable = {- process_id: created_at- for process_id, created_at in self._owned_processes.items()- if created_at < 0- }- self._owned_processes = self._host.live(self._owned_processes)- # AccessDenied group members use a negative identity sentinel. Retain- # those for fail-closed group cleanup even though ordinary dead PIDs are- # pruned from the hot monitor set.- _merge_owned_processes(self._owned_processes, unverifiable)- if pid not in self._owned_processes:- raise RuntimeError("sidecar ownership changed during monitoring")+ def _refresh_owned_processes(self, pid: int) -> dict[int, psutil.Process | None]:+ _refresh_owned_process_tree(self._host, self._owned_processes, pid, self._process_group)return dict(self._owned_processes)def _assert_no_tcp_listener(self,pid: int,*,- owned_processes: Mapping[int, float] | None = None,+ owned_processes: Mapping[int, psutil.Process | None] | None = None,) -> None:live_processes = (dict(owned_processes)if owned_processes is not Noneelse self._refresh_owned_processes(pid))- if pid not in live_processes:- raise RuntimeError("sidecar ownership changed during listener inspection")if self._host.has_tcp_listener(live_processes):raise RuntimeError("sidecar opened a TCP listener")@@ -958,7 +915,8 @@ class EverOSProcess:process: asyncio.subprocess.Process,*,process_group: int | None,- owned_processes: Mapping[int, float] | None = None,+ owned_processes: Mapping[int, psutil.Process | None] | None = None,+ role: str = _SIDECAR_ROLE,) -> None:await _terminate_owned_process_tree(self._host,@@ -966,6 +924,7 @@ class EverOSProcess:process_group=process_group,owned_processes=owned_processes,stop_timeout_seconds=self._stop_timeout_seconds,+ socket_path=self._socket_path, provider_root=self._provider_root, role=role,)async def _notify_ready(self) -> None:@@ -1256,11 +1215,9 @@ class SidecarOwnership:the group and keep the provider root open."""- if created_at < 0:- # A negative sentinel means the OS would not disclose the creation time,- # and the liveness check above this call should already have rejected- # that. Recording it would produce a record nothing can ever match, so- # fail rather than launch a child no later boot can identify.+ if not _is_identity_stamp(created_at):+ # Released records still require a readable diagnostic stamp. A+ # failed record write retains the live reference for startup cleanup.raise RuntimeError("could not verify the sidecar creation time to record")if self._python is None:raise RuntimeError("could not verify the EverOS child interpreter to record")@@ -1347,7 +1304,8 @@ class SidecarOwnership:group_match_role = (None if isinstance(record, dict) and record.get("role") is None else recorded_role)- identity = self._host.inspect_identity(pid)+ reference = self._host.capture(pid)+ identity = _inspect_captured_identity(self._host, pid, reference)verdict = _classify_recorded_child(record,identity,@@ -1392,7 +1350,11 @@ class SidecarOwnership:)terminated = await self._terminate_orphan_tree(pid,- confirmed_create_time,+ reference,+ process_group=_recorded_sidecar_group(+ record, socket_path=self._socket_path, provider_root=self._provider_root,+ ),+ role=group_match_role,)if not terminated:raise RuntimeError(f"orphaned sidecar did not exit (pid {pid}, record {self.record_path})")@@ -1410,7 +1372,10 @@ class SidecarOwnership:await self._reap_unidentified_child()_remove_sidecar_record(self.record_path)- async def _terminate_orphan_tree(self, pid: int, created_at: float) -> bool:+ async def _terminate_orphan_tree(+ self, pid: int, reference: psutil.Process | None,+ *, process_group: int | None, role: str | None,+ ) -> bool:"""Reap an orphan's whole tree, not just the pid the record names.The sidecar may have spawned helpers before the service died, and those@@ -1422,27 +1387,19 @@ class SidecarOwnership:liveness is decided purely from the captured identities."""- identities: dict[int, float] = {pid: created_at}+ identities: dict[int, psutil.Process | None] = {pid: reference}rounds = ((signal.SIGTERM, self._stop_timeout_seconds),(getattr(signal, "SIGKILL", signal.SIGTERM), min(self._stop_timeout_seconds, 3.0)),)+ process_group = _captured_process_group(self._host, pid, reference, process_group)for signum, timeout_seconds in rounds:- if _host_identity_is_live(self._host, pid, identities):- # Only rediscover while the recorded root is still the process we- # identified; a dead root's pid may already have been recycled.- process_group = self._host.process_group(pid)- if not _refresh_owned_process_tree(- self._host,- identities,- pid,- process_group,- ):- process_group = None- else:- process_group = None+ _refresh_terminating_process_tree(+ self._host, identities, pid, process_group,+ socket_path=self._socket_path, provider_root=self._provider_root, role=role,+ )self._host.signal(identities, signum, process_group=process_group)- if await self._host.wait_for_exit(identities, timeout_seconds):+ if await self._host.wait_for_exit(identities, timeout_seconds, process_group=process_group):return Truereturn False@@ -1585,7 +1542,10 @@ class SidecarOwnership:"sidecar process group could not be verified "f"(group {process_group}, record {self.record_path})")- return+ raise RuntimeError(+ "sidecar process group did not exit "+ f"(group {process_group}, record {self.record_path})"+ )_remove_sidecar_record(self.record_path)async def _reap_unidentified_child(self) -> None:@@ -1611,16 +1571,18 @@ class SidecarOwnership:provider_root=self._provider_root)root_only = set(root_anchors).difference(socket_anchors)- socket_anchors.update(root_anchors)+ _merge_owned_processes(socket_anchors, root_anchors)if not socket_anchors:return- for pid, created_at in sorted(socket_anchors.items()):+ for pid, reference in sorted(socket_anchors.items()):+ identity = _inspect_captured_identity(self._host, pid, reference)+ if identity is None:+ if not await self._terminate_orphan_tree(pid, reference, process_group=pid, role=None):+ raise RuntimeError("orphaned sidecar group did not exit")+ continueif pid in root_only:- identity = self._host.inspect_identity(pid)if (- identity is None- or identity.stamp != created_at- or identity.cmdline is None+ identity.cmdline is Noneor not _cmdline_matches_role(identity.cmdline,role=_SIDECAR_ROLE,@@ -1634,14 +1596,14 @@ class SidecarOwnership:"Reaping an EverOS sidecar an unusable ownership record could not identify (pid %s)",pid,)- identities = {pid: created_at}+ identities = {pid: reference}# Helpers are reached through the anchor's own group rather than by# widening the machine-wide test, because membership is what makes the# looser per-member claim safe.- group = self._host.process_group(pid)+ group = _captured_process_group(self._host, pid, reference, pid)self._persist_record(pid,- created_at,+ identity.stamp,group,role=None,python=None,@@ -1682,7 +1644,7 @@ class SidecarOwnership:async def _terminate_claimed_processes(self,process_group: int | None,- identities: dict[int, float],+ identities: dict[int, psutil.Process | None],*,role: str | None = None,) -> tuple[bool, list[int]]:@@ -1691,8 +1653,8 @@ class SidecarOwnership:Mirrors ``_terminate_orphan_tree``, minus the recorded root: whatever thisrun claimed is all there is to work from. A process group, when one isknown, is both the rediscovery anchor and the only thing that permits a- group-wide signal; rediscovery runs only while an already-claimed process- is alive to prove the group has not emptied out from under the scan.+ group-wide signal. Late members must pass contextual classification;+ terminal retained references are never replaced by these discoveries.The result carries both the claimed-tree death proof and every unverifiablegroup member observed during those rediscovery rounds."""@@ -1703,7 +1665,7 @@ class SidecarOwnership:)foreign: set[int] = set()for signum, timeout_seconds in rounds:- if process_group is not None and self._host.live(identities):+ if process_group is not None:discovered, round_foreign = self._host.recorded_group_members(process_group,socket_path=self._socket_path,@@ -1713,7 +1675,7 @@ class SidecarOwnership:_merge_owned_processes(identities, discovered)foreign.update(round_foreign)self._host.signal(identities, signum, process_group=process_group)- if await self._host.wait_for_exit(identities, timeout_seconds):+ if await self._host.wait_for_exit(identities, timeout_seconds, process_group=process_group):return True, sorted(foreign)return False, sorted(foreign)@@ -1800,7 +1762,7 @@ class _ReleasedSyncReaper:return float(identity.wall_create_time) == float(record["parent_create_time"])async def _reconcile_exclusive(self, record: Mapping[str, Any]) -> None:- identities: dict[int, float] = {}+ identities: dict[int, psutil.Process | None] = {}if record["state"] == "pending":candidates = self._host.find_syncs(provider_root=self._provider_root,@@ -1812,23 +1774,22 @@ class _ReleasedSyncReaper:returnif len(candidates) != 1:raise RuntimeError("released pending sync ownership is ambiguous")- pid, created_at = next(iter(candidates.items()))- identity = self._host.inspect_identity(pid)- _validate_legacy_sync_identity(- identity,- record,- created_at=created_at,- provider_root=self._provider_root,- require_argv=True,- )- group = self._host.process_group(pid)+ pid, reference = next(iter(candidates.items()))+ identity = _inspect_captured_identity(self._host, pid, reference)+ if identity is not None:+ _validate_legacy_sync_identity(+ identity, record, provider_root=self._provider_root, require_argv=True,+ )+ # Released sync launches use setsid; never read a replacement PID's group.+ group = _captured_process_group(self._host, pid, reference, pid)if group is None:raise RuntimeError("released pending sync process group is unavailable")- identities[pid] = created_at+ identities[pid] = referenceelse:pid = int(record["pid"])group = int(record["process_group"])- identity = self._host.inspect_identity(pid)+ reference = self._host.capture(pid)+ identity = _inspect_captured_identity(self._host, pid, reference)if identity is not None:verdict = _classify_recorded_child(record,@@ -1847,17 +1808,16 @@ class _ReleasedSyncReaper:_validate_legacy_sync_identity(identity,record,- created_at=float(identity.stamp),provider_root=self._provider_root,require_argv=True,)- identities[pid] = float(identity.stamp)+ identities[pid] = referenceif hasattr(os, "getpgrp") and group == os.getpgrp():raise RuntimeError("released sync process group is unsafe")self._merge_validated_group(record, group, identities)await self._terminate_group(record, group, identities)- remaining: dict[int, float] = {}+ remaining: dict[int, psutil.Process | None] = {}self._merge_validated_group(record, group, remaining)if self._host.live(remaining):raise RuntimeError("released sync process group did not exit")@@ -1867,7 +1827,7 @@ class _ReleasedSyncReaper:self,record: Mapping[str, Any],group: int,- identities: dict[int, float],+ identities: dict[int, psutil.Process | None],) -> None:claimed, foreign = self._host.recorded_group_members(group,@@ -1877,24 +1837,23 @@ class _ReleasedSyncReaper:)if foreign:raise RuntimeError("released sync process group is unverifiable")- for pid, created_at in claimed.items():- identity = self._host.inspect_identity(pid)+ for pid, reference in claimed.items():+ identity = _inspect_captured_identity(self._host, pid, reference)if identity is None:continue_validate_legacy_sync_identity(identity,record,- created_at=created_at,provider_root=self._provider_root,require_argv=pid == record.get("pid"),)- identities.setdefault(pid, created_at)+ identities.setdefault(pid, reference)async def _terminate_group(self,record: Mapping[str, Any],group: int,- identities: dict[int, float],+ identities: dict[int, psutil.Process | None],) -> None:rounds = ((signal.SIGTERM, self._stop_timeout_seconds),@@ -1904,10 +1863,9 @@ class _ReleasedSyncReaper:),)for signum, timeout_seconds in rounds:- if self._host.live(identities):- self._merge_validated_group(record, group, identities)+ self._merge_validated_group(record, group, identities)self._host.signal(identities, signum, process_group=group)- if await self._host.wait_for_exit(identities, timeout_seconds):+ if await self._host.wait_for_exit(identities, timeout_seconds, process_group=group):returnraise RuntimeError("released sync process group did not exit")@@ -2019,15 +1977,10 @@ def _validate_legacy_sync_identity(identity: _ProcessIdentity | None,record: Mapping[str, Any],*,- created_at: float,provider_root: Path,require_argv: bool,) -> None:- if (- identity is None- or not _is_identity_stamp(created_at)- or identity.stamp != created_at- ):+ if identity is None or not _is_identity_stamp(identity.stamp):raise RuntimeError("released sync identity is unavailable")if require_argv and identity.cmdline != tuple(record["argv"]):raise RuntimeError("released sync identity is unavailable")@@ -2259,40 +2212,27 @@ async def _terminate_owned_process_tree(process: asyncio.subprocess.Process,*,process_group: int | None,- owned_processes: Mapping[int, float] | None,+ owned_processes: Mapping[int, psutil.Process | None] | None,stop_timeout_seconds: float,+ socket_path: Path,+ provider_root: Path,+ role: str | None = _SIDECAR_ROLE,) -> None:- identities = dict(owned_processes or {})- _refresh_owned_process_tree(host, identities, process.pid, process_group)- host.signal(- identities,- signal.SIGTERM,- process_group=process_group,- process=process,+ identities = owned_processes if isinstance(owned_processes, dict) else dict(owned_processes or {})+ rounds = (+ (signal.SIGTERM, stop_timeout_seconds),+ (getattr(signal, "SIGKILL", signal.SIGTERM), min(stop_timeout_seconds, 3.0)),)- if await host.wait_for_exit(- identities,- stop_timeout_seconds,- process_group=process_group,- process=process,- ):- return-- kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM)- _refresh_owned_process_tree(host, identities, process.pid, process_group)- host.signal(- identities,- kill_signal,- process_group=process_group,- process=process,- )- if await host.wait_for_exit(- identities,- min(stop_timeout_seconds, 3.0),- process_group=process_group,- process=process,- ):- return+ for signum, timeout_seconds in rounds:+ _refresh_terminating_process_tree(+ host, identities, process.pid, process_group,+ socket_path=socket_path, provider_root=provider_root, role=role,+ )+ host.signal(identities, signum, process_group=process_group, process=process)+ if await host.wait_for_exit(+ identities, timeout_seconds, process_group=process_group, process=process,+ ):+ returnraise RuntimeError("EverOS child process tree did not exit")@@ -2652,29 +2592,28 @@ def _recorded_group_members(socket_path: Path,provider_root: Path,role: str | None = None,-) -> tuple[dict[int, float], list[int]]:+) -> tuple[dict[int, psutil.Process | None], list[int]]:"""Split a recorded group's live members into ours and ones to leave alone.- Returns claimed ``(pid, create_time)`` identities plus the pids that could not+ Returns retained public Process references plus the pids that could notbe tied to this installation, so the caller can log what it deliberately spared."""- claimed: dict[int, float] = {}+ claimed: dict[int, psutil.Process | None] = {}foreign: list[int] = []own_pid = os.getpid()- for pid, created_at in _snapshot_process_group(process_group).items():- if pid == own_pid:+ for pid, reference in _snapshot_process_group(process_group).items():+ if pid == own_pid or _reference_state(reference, pid) is False:continue- if created_at >= 0 and _process_names_owned_runtime(+ if _reference_state(reference, pid) is True and _process_names_owned_runtime(pid,socket_path=socket_path,provider_root=provider_root,role=role,- ):- claimed[pid] = created_at- else:- # Either the identity is unreadable (the negative sentinel) or nothing- # observable ties the process to this installation.+ ) and _reference_state(reference, pid) is True:+ claimed[pid] = reference+ elif _reference_state(reference, pid) is not False:+ # Either unreadable or not attributable; never signal it.foreign.append(pid)return claimed, sorted(foreign)@@ -3023,7 +2962,7 @@ def _remove_legacy_sync_record(path: Path) -> None:raise RuntimeError("released sync ownership record cannot be retired") from exc-def _processes_serving_owned_socket(*, socket_path: Path) -> dict[int, float]:+def _processes_serving_owned_socket(*, socket_path: Path) -> dict[int, psutil.Process | None]:"""Live processes running this home's sidecar entrypoint against its socket.The anchor for a recovery that has no usable record to work from, so unlike@@ -3039,11 +2978,17 @@ def _processes_serving_owned_socket(*, socket_path: Path) -> dict[int, float]:what makes the looser per-member claim safe."""- claimed: dict[int, float] = {}+ claimed: dict[int, psutil.Process | None] = {}own_pid = os.getpid()getuid = getattr(os, "getuid", None)own_uid = getuid() if callable(getuid) else None- for candidate in psutil.process_iter():+ for observed in psutil.process_iter():+ # process_iter may return a cached generation. Capture afresh for this+ # discovery, then bracket classification without adopting old references.+ reference = _capture_process(observed.pid)+ if reference is not None and _reference_state(reference, observed.pid) is False:+ continue+ candidate = reference if reference is not None else observedif candidate.pid == own_pid:continuetry:@@ -3052,24 +2997,31 @@ def _processes_serving_owned_socket(*, socket_path: Path) -> dict[int, float]:cmdline = _disclosed_identity_field(candidate.cmdline)if cmdline is None or not _cmdline_serves_socket(tuple(str(value) for value in cmdline), socket_path):continue- created_at = _disclosed_identity_field(lambda: _process_creation_stamp(candidate))except psutil.Error:continue- # A claimed process whose creation time is withheld carries the negative- # sentinel: it can never be signaled by identity, and it never counts as- # reaped, so it fails the launch closed instead of being written off.- claimed[candidate.pid] = -1.0 if created_at is None else float(created_at)+ state = _reference_state(reference, candidate.pid)+ if state is False:+ continue+ if state is None and reference is not None:+ raise RuntimeError("sidecar unreadable during ownership classification")+ claimed[candidate.pid] = referencereturn claimed-def _processes_serving_owned_root(*, provider_root: Path) -> dict[int, float]:+def _processes_serving_owned_root(*, provider_root: Path) -> dict[int, psutil.Process | None]:"""Live exact sidecar entrypoints owned by this uid and provider root."""- claimed: dict[int, float] = {}+ claimed: dict[int, psutil.Process | None] = {}own_pid = os.getpid()getuid = getattr(os, "getuid", None)own_uid = getuid() if callable(getuid) else None- for candidate in psutil.process_iter():+ for observed in psutil.process_iter():+ # process_iter may return a cached generation. Capture afresh for this+ # discovery, then bracket classification without adopting old references.+ reference = _capture_process(observed.pid)+ if reference is not None and _reference_state(reference, observed.pid) is False:+ continue+ candidate = reference if reference is not None else observedif candidate.pid == own_pid:continuetry:@@ -3083,7 +3035,6 @@ def _processes_serving_owned_root(*, provider_root: Path) -> dict[int, float]:if not _cmdline_is_sidecar(rendered):continueenvironment = _disclosed_process_environment(candidate)- created_at = _disclosed_identity_field(lambda: _process_creation_stamp(candidate))except psutil.NoSuchProcess:continueexcept psutil.Error:@@ -3100,7 +3051,12 @@ def _processes_serving_owned_root(*, provider_root: Path) -> dict[int, float]:role = environment.get("AVIBE_MEMORY_CHILD_ROLE")if role not in (None, _SIDECAR_ROLE):continue- claimed[candidate.pid] = -1.0 if created_at is None else float(created_at)+ state = _reference_state(reference, candidate.pid)+ if state is False:+ continue+ if state is None and reference is not None:+ raise RuntimeError("sidecar unreadable during ownership classification")+ claimed[candidate.pid] = referencereturn claimed@@ -3109,14 +3065,20 @@ def _processes_syncing_owned_root(provider_root: Path,python: Path,nonce: str,-) -> dict[int, float]:+) -> dict[int, psutil.Process | None]:"""Discover one exact released nonce-bearing sync child."""- claimed: dict[int, float] = {}+ claimed: dict[int, psutil.Process | None] = {}own_pid = os.getpid()getuid = getattr(os, "getuid", None)own_uid = getuid() if callable(getuid) else None- for candidate in psutil.process_iter():+ for observed in psutil.process_iter():+ # process_iter may return a cached generation. Capture afresh for this+ # discovery, then bracket classification without adopting old references.+ reference = _capture_process(observed.pid)+ if reference is not None and _reference_state(reference, observed.pid) is False:+ continue+ candidate = reference if reference is not None else observedif candidate.pid == own_pid:continuetry:@@ -3171,7 +3133,12 @@ def _processes_syncing_owned_root(or environment.get(_SYNC_NONCE_ENV) != nonce):continue- claimed[candidate.pid] = float(created_at)+ state = _reference_state(reference, candidate.pid)+ if state is False:+ continue+ if state is None and reference is not None:+ raise RuntimeError("sync child unreadable during ownership classification")+ claimed[candidate.pid] = referencereturn claimed@@ -3188,164 +3155,191 @@ def _remove_sidecar_record(path: Path) -> None:return-async def _wait_for_identities_exit(identities: Mapping[int, float], timeout_seconds: float) -> bool:+async def _wait_for_identities_exit(identities: Mapping[int, psutil.Process | None], timeout_seconds: float, process_group: int | None = None) -> bool:"""Poll recorded identities until none is live or the bound expires."""deadline = time.monotonic() + max(timeout_seconds, 0.1)while time.monotonic() < deadline:- if not _live_owned_processes(identities):+ if not _live_owned_processes(identities) and not _snapshot_process_group(process_group):return Trueawait asyncio.sleep(0.05)- return not _live_owned_processes(identities)+ return not _live_owned_processes(identities) and not _snapshot_process_group(process_group)-def _snapshot_owned_processes(pid: int, process_group: int | None) -> dict[int, float]:- """Record `(pid, stamp)` identities while the child is still owned."""+def _inspect_captured_identity(+ host: _ProcessHost,+ pid: int,+ reference: psutil.Process | None,+) -> _ProcessIdentity | None:+ state = _reference_state(reference, pid)+ if state is False:+ return None+ if state is None:+ raise RuntimeError("process unreadable before ownership classification")+ identity = host.inspect_identity(pid)+ state = _reference_state(reference, pid)+ if state is False:+ return None+ if state is None:+ raise RuntimeError("process unreadable during ownership classification")+ return identity+- identities: dict[int, float] = {}+def _captured_process_group(+ host: _ProcessHost, pid: int, reference: psutil.Process | None, known_group: int | None,+) -> int | None:+ """Keep the established cleanup scope if its leader exits during lookup."""+ state = _reference_state(reference, pid)+ if state is False:+ return known_group+ if state is None:+ raise RuntimeError("process group is unreadable")+ group = host.process_group(pid)+ state = _reference_state(reference, pid)+ if state is False:+ return known_group+ if state is None:+ raise RuntimeError("process group is unreadable")+ return group+++def _capture_process(pid: int) -> psutil.Process | None:try:- root = psutil.Process(pid)- candidates = [root, *root.children(recursive=True)]+ # Retain the public reference even if later reads are temporarily denied.+ # State and signal checks decide authority at their existing boundaries.+ return psutil.Process(pid)except psutil.Error:- candidates = []- for candidate in candidates:+ return None+++def _reference_state(reference: psutil.Process | None, pid: int) -> bool | None:+ """True is live, False is gone/reused, None is unresolved presence."""+ try:+ if reference is None:+ return None if psutil.pid_exists(pid) else False+ if not reference.is_running():+ return False+ return reference.status() != psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return False+ except (psutil.Error, OSError):+ return None+++def _snapshot_owned_processes(+ pid: int,+ process_group: int | None,+ owned: Mapping[int, psutil.Process | None] | None = None,+) -> dict[int, psutil.Process | None]:+ identities = dict(owned) if owned is not None else {pid: _capture_process(pid)}+ # Children are observed through retained parents, even after reparenting or+ # leaving the original group. Never refresh a captured PID into a new birth.+ for parent_pid, parent in list(identities.items()):+ if _reference_state(parent, parent_pid) is not True:+ continuetry:- identities.setdefault(candidate.pid, _process_creation_stamp(candidate))- except psutil.Error:+ children = parent.children(recursive=True)+ group = _snapshot_process_group(process_group) if parent_pid == pid else {}+ if _reference_state(parent, parent_pid) is not True:+ continue+ discovered = {child.pid: child for child in children}+ if parent_pid == pid and _isolated_process_group(pid) == process_group:+ discovered.update(group)+ _merge_owned_processes(identities, discovered)+ except (psutil.Error, OSError):+ # Keep captured members on read errors; listener inspection and the+ # independent group-clear check still fail closed on unknown presence.continue- _merge_owned_processes(identities, _snapshot_process_group(process_group))return identities-def _snapshot_process_group(process_group: int | None) -> dict[int, float]:+def _snapshot_process_group(process_group: int | None) -> dict[int, psutil.Process | None]:if process_group is None or os.name != "posix" or not hasattr(os, "getpgid"):return {}- identities: dict[int, float] = {}+ identities = {}for candidate in psutil.process_iter():try:if os.getpgid(candidate.pid) == process_group:- identities[candidate.pid] = _process_creation_stamp(candidate)- except psutil.AccessDenied:- # The member exists but its identity cannot be verified. Keep it with a- # sentinel so the "all confirmed" check sees an unverifiable member and- # fails closed (no killpg) rather than silently dropping it.- identities[candidate.pid] = -1.0- except (OSError, psutil.Error):+ reference = _capture_process(candidate.pid)+ if (+ _reference_state(reference, candidate.pid) is not False+ and os.getpgid(candidate.pid) == process_group+ ):+ identities[candidate.pid] = reference+ except (PermissionError, psutil.AccessDenied):+ identities[candidate.pid] = None+ except (ProcessLookupError, psutil.NoSuchProcess):continuereturn identities-def _merge_owned_processes(identities: dict[int, float], discovered: Mapping[int, float]) -> None:- """Add newly seen children without changing a captured process identity."""-- for process_id, created_at in discovered.items():- identities.setdefault(process_id, created_at)---def _host_identity_is_live(- host: _ProcessHost,- process_id: int,- identities: Mapping[int, float],-) -> bool:- created_at = identities.get(process_id)- return created_at is not None and process_id in host.live({process_id: created_at})+def _merge_owned_processes(+ identities: dict[int, psutil.Process | None],+ discovered: Mapping[int, psutil.Process | None],+) -> None:+ for pid, reference in discovered.items():+ if pid not in identities or identities[pid] is None:+ identities[pid] = referencedef _refresh_owned_process_tree(host: _ProcessHost,- identities: dict[int, float],+ identities: dict[int, psutil.Process | None],process_id: int,process_group: int | None,-) -> bool:- """Extend ownership only while the captured root identity remains live."""-- created_at = identities.get(process_id)- if created_at is None or not _host_identity_is_live(- host,- process_id,- {process_id: created_at},- ):- return False- discovered = host.snapshot_tree(process_id, process_group)- if discovered.get(process_id) != created_at or not _host_identity_is_live(- host,- process_id,- {process_id: created_at},- ):- return False+) -> None:+ discovered = host.snapshot_tree(process_id, process_group, identities)_merge_owned_processes(identities, discovered)- return True-def _live_owned_processes(identities: Mapping[int, float]) -> dict[int, float]:- live: dict[int, float] = {}- for process_id, created_at in identities.items():- try:- candidate = psutil.Process(process_id)- if _process_creation_stamp(candidate) != created_at:- continue- if candidate.status() == psutil.STATUS_ZOMBIE:- continue- except psutil.NoSuchProcess:- continue- except psutil.AccessDenied:- # An uninspectable descendant cannot be treated as cleanly reaped.- pass- except psutil.Error:- continue- live[process_id] = created_at- return live+def _refresh_terminating_process_tree(+ host: _ProcessHost,+ identities: dict[int, psutil.Process | None],+ pid: int,+ process_group: int | None,+ *,+ socket_path: Path,+ provider_root: Path,+ role: str | None,+) -> None:+ _refresh_owned_process_tree(host, identities, pid, process_group)+ if process_group is not None and _reference_state(identities.get(pid), pid) is False:+ # A helper born after the last scan has no retained reference. Only the+ # existing ownership classifier can attribute it after its leader exits.+ claimed, _foreign = host.recorded_group_members(+ process_group, socket_path=socket_path, provider_root=provider_root, role=role,+ )+ for member_pid, reference in claimed.items():+ if member_pid != pid:+ identities.setdefault(member_pid, reference)+ # Foreign/unknown members remain visible to group signaling and wait proof.-def _confirmed_owned_processes(identities: Mapping[int, float]) -> dict[int, float]:- """Return identities whose current creation stamp is readable and unchanged."""+def _live_owned_processes(identities: Mapping[int, psutil.Process | None]) -> dict[int, psutil.Process | None]:+ return {pid: ref for pid, ref in identities.items() if _reference_state(ref, pid) is not False}- confirmed: dict[int, float] = {}- for process_id, created_at in identities.items():- try:- candidate = psutil.Process(process_id)- if _process_creation_stamp(candidate) != created_at or candidate.status() == psutil.STATUS_ZOMBIE:- continue- except psutil.Error:- # AccessDenied is live-but-unverified: retain it for reaping, but- # never use it as authority to signal a numeric PID.- continue- confirmed[process_id] = created_at- return confirmed++def _confirmed_owned_processes(identities: Mapping[int, psutil.Process | None]) -> dict[int, psutil.Process]:+ return {pid: ref for pid, ref in identities.items() if ref is not None and _reference_state(ref, pid) is True}def _group_contains_only_confirmed_owned_processes(process_group: int | None,- identities: Mapping[int, float],+ identities: Mapping[int, psutil.Process | None],) -> bool:- """Whether a group can be signaled without bypassing PID identity checks."""-- if process_group is None:+ if process_group is None or (hasattr(os, "getpgrp") and process_group == os.getpgrp()):return False- group_members = _snapshot_process_group(process_group)+ members = _snapshot_process_group(process_group)confirmed = _confirmed_owned_processes(identities)- return bool(group_members) and all(- confirmed.get(process_id) == created_at for process_id, created_at in group_members.items()- )+ return bool(members) and all(ref is not None and confirmed.get(pid) == ref for pid, ref in members.items())def _signal_owned_group(process_group: int | None,- identities: Mapping[int, float],+ identities: Mapping[int, psutil.Process | None],signum: int,) -> bool:- """Signal a whole isolated group, but only if every member is confirmed owned.-- Returns whether the group signal settled the delivery, so a caller holding a- direct child handle can fall back to it without widening the blast radius: a- group with an unverifiable member is never signaled group-wide.- """-- if (- process_group is None- or not hasattr(os, "killpg")- or not _group_contains_only_confirmed_owned_processes(process_group, identities)- ):+ if not hasattr(os, "killpg") or not _group_contains_only_confirmed_owned_processes(process_group, identities):return Falsetry:os.killpg(process_group, signum)@@ -3356,60 +3350,38 @@ def _signal_owned_group(return True-def _signal_owned_group_or_process(- process: asyncio.subprocess.Process,- process_group: int | None,- identities: Mapping[int, float],- signum: int,+def _signal_owned_processes(+ identities: Mapping[int, psutil.Process | None], signum: int,+ *, delivered_group: int | None = None,) -> None:- if _signal_owned_group(process_group, identities, signum):- return- if process.returncode is not None:- return- created_at = identities.get(process.pid)- if created_at is None or process.pid not in _confirmed_owned_processes(- {process.pid: created_at}- ):- return- try:- process.send_signal(signum)- except ProcessLookupError:- return---def _signal_owned_processes(identities: Mapping[int, float], signum: int) -> None:- for process_id, created_at in _confirmed_owned_processes(identities).items():+ for reference in _confirmed_owned_processes(identities).values():try:- candidate = psutil.Process(process_id)- if _process_creation_stamp(candidate) != created_at:- continue- candidate.send_signal(signum)- except (psutil.NoSuchProcess, psutil.AccessDenied):- continue- except psutil.Error:+ if delivered_group is not None:+ if _reference_state(reference, reference.pid) is not True:+ continue+ group = os.getpgid(reference.pid)+ if _reference_state(reference, reference.pid) is not True or group == delivered_group:+ continue+ reference.send_signal(signum)+ except (psutil.Error, OSError):continueasync def _wait_for_owned_exit(+ host: _ProcessHost,process: asyncio.subprocess.Process,*,process_group: int | None,- identities: dict[int, float],+ identities: dict[int, psutil.Process | None],timeout_seconds: float,) -> bool:- """Wait for the direct child and every discovered descendant to disappear."""-+ """Reap the direct child AND prove retained descendants and group are clear."""deadline = time.monotonic() + max(timeout_seconds, 0.1)waiter = asyncio.create_task(process.wait(), name="memory-everos-reap")try:while time.monotonic() < deadline:- _refresh_owned_process_tree(- _SystemProcessHost(),- identities,- process.pid,- process_group,- )- if waiter.done() and not _live_owned_processes(identities):+ _refresh_owned_process_tree(host, identities, process.pid, process_group)+ if waiter.done() and not host.live(identities) and not _snapshot_process_group(process_group):await waiterreturn Trueawait asyncio.sleep(0.05)@@ -3587,8 +3559,11 @@ class _SystemProcessHost:def inspect_identity(self, pid: int) -> _ProcessIdentity | None:return _inspect_process_identity(pid)- def snapshot_tree(self, pid: int, process_group: int | None) -> dict[int, float]:- return _snapshot_owned_processes(pid, process_group)+ def capture(self, pid: int) -> psutil.Process | None:+ return _capture_process(pid)++ def snapshot_tree(self, pid: int, process_group: int | None, owned=None) -> dict[int, psutil.Process | None]:+ return _snapshot_owned_processes(pid, process_group, owned)def recorded_group_members(self,@@ -3597,7 +3572,7 @@ class _SystemProcessHost:socket_path: Path,provider_root: Path,role: str | None = None,- ) -> tuple[dict[int, float], list[int]]:+ ) -> tuple[dict[int, psutil.Process | None], list[int]]:return _recorded_group_members(process_group,socket_path=socket_path,@@ -3605,10 +3580,10 @@ class _SystemProcessHost:role=role,)- def find_sidecars(self, *, socket_path: Path) -> dict[int, float]:+ def find_sidecars(self, *, socket_path: Path) -> dict[int, psutil.Process | None]:return _processes_serving_owned_socket(socket_path=socket_path)- def find_sidecars_by_root(self, *, provider_root: Path) -> dict[int, float]:+ def find_sidecars_by_root(self, *, provider_root: Path) -> dict[int, psutil.Process | None]:return _processes_serving_owned_root(provider_root=provider_root)def find_syncs(@@ -3617,51 +3592,59 @@ class _SystemProcessHost:provider_root: Path,python: Path,nonce: str,- ) -> dict[int, float]:+ ) -> dict[int, psutil.Process | None]:return _processes_syncing_owned_root(provider_root=provider_root,python=python,nonce=nonce,)- def live(self, identities: Mapping[int, float]) -> dict[int, float]:+ def live(self, identities: Mapping[int, psutil.Process | None]) -> dict[int, psutil.Process | None]:return _live_owned_processes(identities)def signal(self,- identities: Mapping[int, float],+ identities: Mapping[int, psutil.Process | None],signum: int,*,process_group: int | None = None,process: asyncio.subprocess.Process | None = None,) -> None:- if process is None:- _signal_owned_group(process_group, identities, signum)- else:- _signal_owned_group_or_process(process, process_group, identities, signum)- _signal_owned_processes(identities, signum)+ delivered = _signal_owned_group(process_group, identities, signum)+ # With stable membership these sets are disjoint. Group movement and+ # delivery are not atomic; retained-reference checks still fence reuse.+ _signal_owned_processes(+ identities, signum, delivered_group=process_group if delivered else None,+ )async def wait_for_exit(self,- identities: dict[int, float],+ identities: dict[int, psutil.Process | None],timeout_seconds: float,*,process_group: int | None = None,process: asyncio.subprocess.Process | None = None,) -> bool:if process is None:- return await _wait_for_identities_exit(identities, timeout_seconds)+ return await _wait_for_identities_exit(identities, timeout_seconds, process_group)return await _wait_for_owned_exit(- process,+ self, process,process_group=process_group,identities=identities,timeout_seconds=timeout_seconds,)- def has_tcp_listener(self, identities: Mapping[int, float]) -> bool:- for process_id in identities:+ def has_tcp_listener(self, identities: Mapping[int, psutil.Process | None]) -> bool:+ for pid, reference in identities.items():+ state = _reference_state(reference, pid)+ if state is False:+ continue+ if state is None:+ raise RuntimeError("could not inspect sidecar listeners")try:- connections = psutil.Process(process_id).net_connections(kind="inet")+ connections = reference.net_connections(kind="inet")+ if _reference_state(reference, pid) is False:+ continueexcept (psutil.NoSuchProcess, psutil.ZombieProcess):continueexcept psutil.Error as exc:diff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex 72b4c5547..8ed29850e 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -246,6 +246,11 @@ Settings names this path by user intent: `degraded` shows **Retry startup**,while `running` keeps **Restart Memory service** under **More actions**. Both usethe same non-destructive Wake path.+If automatic Wake retries are exhausted and the state remains `degraded` with+`memory_wake_failed`, correct the underlying fault and choose **Retry startup**+for an explicit Wake attempt. Automatic retries are bounded; Wake preserves+existing data and requires the previous process tree to stop before replacement.+Provider, credential, disk, and permission faults produce `degraded` with asanitized reason. Correct the external condition and choose **Retry startup**.These faults never enable or route to destructive Repair.diff --git a/docs/plans/memory-macos-identity-recovery-1990.md b/docs/plans/memory-macos-identity-recovery-1990.mdnew file mode 100644index 000000000..eb518e19b--- /dev/null+++ b/docs/plans/memory-macos-identity-recovery-1990.md@@ -0,0 +1,106 @@+# Memory subprocess lifecycle — issue 1990++Owner-approved implementation summary, 2026-09-15. The full investigation and+review remain outside this PR. This summary preserves the approved product contract.++## Problem and decision++On macOS, psutil's public display creation time can shift while a child remains+the same execution. Avibe repeatedly compared that display value, rejected a+healthy Memory child, and exhausted bounded Wake retries without clearing it.++Use direct `asyncio` child waiting as lifecycle authority. Keep public retained+`psutil.Process` references for action-boundary reuse protection. Remove the+independent 0.2-second authentication loop and readiness timestamp gate; preserve+discovery at existing readiness polls and the one-second descendant/TCP inspection. A timestamp shift alone neither+marks the child down nor pauses claims or consumes restart attempts.++## Ownership and cleanup invariants++- `EverOSProcess._owned_processes` owns one map of references; `_ProcessHost`+ stays stateless. The probe and orphan reapers use execution-local maps.+- Capture before readiness. Preserve references across reparenting, group escape,+ and failed cleanup; do not discard a constructed reference on extra read failure.+- Gone/reused references stay terminal in that execution map. Never recapture+ their PIDs into another generation. `None` means unresolved presence, not exit.+- Use retained public references for individual signals. Group signals require+ every current member to match a confirmed owned reference and cannot target+ Avibe's own group. Successful group delivery sends individually only to escaped+ references; failed/refused group delivery uses the full confirmed individual set.+- TERM, bounded wait, KILL and final wait remain. Direct-child reaping alone is+ insufficient: known descendants and unknown group members block cleanup.+ Late helpers after leader exit enter each bounded round through existing+ root/socket/role classification; second-round arrivals receive KILL within the bound.+- Existing locks, child-object identity and supervisor generations serialize+ stop, natural exit, Wake and close. No new lifecycle state machine is added.++## Compatibility and bounded recovery++Released JSON shapes and historical command/UID/role/interpreter/root/socket+classification remain unchanged. Capture a reference before classification reads+and validate it afterward; retain it through signals and exit waiting. Historical+stamps remain record fields, never live-child authentication authority.++Both root and companion distributions require `psutil>=7.1.0`, which provides+the public monotonic identity behavior needed on macOS and Linux. The lockfile+resolves 7.2.2. Built wheel metadata enforces the floor independently of the lock.++Automatic recovery keeps its existing bounded budget. After unrelated failures+exhaust it, `degraded` with `memory_wake_failed` requires an explicit **Retry+startup** (Wake) once cleanup is possible. Wake preserves existing data.++## Validation and reproduction++Scenario IDs: MEMORY-WAKE-001, MEMORY-WAKE-202, MEMORY-WAKE-204, MEMORY-WAKE-205.++- Focused process, lifecycle, supervisor, Wake and provider regression: 225 passed.+- Darwin arm64 psutil floor and resolved environments: 37 passed each, including+ real processing/recall. Boot-time injection is test-only and checks its hook.+- Native tests cover full scan cycles during a shift, probe capture before shift+ then timeout cleanup, a prohibited TCP listener, and leader/child/grandchild exit.+- Controlled distinct generations cover delayed exit callbacks, PID reuse,+ unknown/denied members, group escape, and failed-stop reference retention.+ Native orphan reaping covers classification, shift, waiting and record retirement.+- Actual production Wake, admission, claims, writer, EverOS 1.2.3 extraction,+ storage/indexing and keyword recall preserve old input, process another input+ during a shift without recovery, then process/recall new input after Wake.+- Root/companion wheel and sdist builds passed; four declaration/built-wheel+ dependency checks passed. Changed-file Ruff and normal UI asset build passed.++Old-test mapping: health-only pinned Wake -> full MEMORY-WAKE-205 (required in CI);+fake lifecycle self-tests -> supervisor callback/non-overlap consumers; generic+orphan success -> shift/retirement case covering all three released record shapes;+native orphan helper -> consuming reaper; duplicate capture-read dimension merged.+Readiness regression: observed startup helpers remain owned after detachment,+through successful startup/Stop and failed-start timeout cleanup.+PM follow-up: ordinary exits skip classification but retain surviving-group cleanup;+missing record identity is explicit; legacy sync equality is removed. Group lookups+retain the established scope across exit/reuse; gone anchors retain legacy role context.++```sh+uv sync --no-install-project --group dev+uv run --no-sync pytest tests/test_memory_process.py tests/test_memory_process_lifecycle.py tests/test_memory_supervisor.py tests/test_memory_wake.py tests/test_memory_everos.py -q+uv sync --frozen --project scripts/memory_runtime+AVIBE_REQUIRE_MEMORY_RUNTIME_CONTRACT=1 uv run --frozen --project scripts/memory_runtime --with 'pytest==9.0.3' --with 'pytest-asyncio==1.4.0' python -m pytest tests/test_memory_process_lifecycle.py tests/scenarios/memory_repair/test_memory_lifecycle_runtime.py -q+AVIBE_REQUIRE_MEMORY_RUNTIME_CONTRACT=1 uv run --no-sync --with 'everos==1.2.3' --with 'psutil==7.1.0' pytest tests/test_memory_process_lifecycle.py tests/scenarios/memory_repair/test_memory_lifecycle_runtime.py -q+```++## Evidence limits++Tests own their HOME/XDG/config/storage and every signaled child. The loopback+HTTP server replaces only external model/1024-dimensional embedding answers;+there are no runtime/storage doubles or direct DB inserts. This proves lifecycle+and data continuity, not model quality or real host PID-recycling stress.++Local Incus provisioning was blocked before target creation by required IM/model+seed configuration. Runner status/reconcile confirmed no task target remained.+The shared Lima VM was started and left running. The orchestrator approved native+full-pipeline evidence instead; four-platform Incus deployment remains unverified.+No production credentials or regression state were copied/reset.++If no initial reference is acquired, cleanup stays unknown (a probe may remain+unreaped); a later PID or delayed child callback cannot authorize recapture.+An unseen helper that reparents and leaves the group entirely between observations+remains outside this polling model, as before. Public checks are not atomic macOS pidfds; group movement/delivery is not exactly-once.+No private identity API, native ABI, schema, recovery loop, service-manager/IPC,+writer-lock redesign, running-property change or expanded retries were added.diff --git a/packaging/avibe-memory/pyproject.toml b/packaging/avibe-memory/pyproject.tomlindex ede4f2f11..bc18375f4 100644--- a/packaging/avibe-memory/pyproject.toml+++ b/packaging/avibe-memory/pyproject.toml@@ -23,6 +23,7 @@ classifiers = ["Programming Language :: Python :: 3.12",]dependencies = [+ "psutil>=7.1.0","avibe-os>=3.0.14.dev0,<3.1",]diff --git a/pyproject.toml b/pyproject.tomlindex eb520bafe..0ab74c8a7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -66,7 +66,7 @@ dependencies = ["PyJWT[crypto]>=2.9.0","SQLAlchemy>=2.0.0","alembic>=1.13.0",- "psutil>=5.9.0",+ "psutil>=7.1.0","packaging>=23.0","uvicorn[standard]>=0.27","imagesize>=1.4.1",diff --git a/tests/scenarios/memory_repair/catalog.yaml b/tests/scenarios/memory_repair/catalog.yamlindex 193712fe5..5ab5e9ec5 100644--- a/tests/scenarios/memory_repair/catalog.yaml+++ b/tests/scenarios/memory_repair/catalog.yaml@@ -30,7 +30,7 @@ scenarios:layer: contracttest: tests/test_memory_wake.py::test_wake_reuses_existing_root_and_proves_native_readinessrelated_tests:- - tests/test_memory_wake.py::test_pinned_everos_runtime_wakes_through_production_sidecar+ - tests/scenarios/memory_repair/test_memory_lifecycle_runtime.py::test_real_wake_preserves_old_and_processes_new_inputactor: Memory runtimetrigger: Startup or an explicit Wake requestconditions:@@ -227,3 +227,31 @@ scenarios:- Ready, missing, error, or unsupported status with the retained reason- No repair offer for an unsupported platform- Controller-owned artifact installation for supported repair++ - id: MEMORY-WAKE-204+ name: Display-time shifts never authenticate a live execution+ status: covered+ kind: lifecycle+ layer: contract+ test: tests/test_memory_process_lifecycle.py::test_native_shift_survives_full_scans_and_stop+ related_tests:+ - tests/test_memory_process_lifecycle.py::test_native_probe_timeout_during_shift+ - tests/test_memory_process_lifecycle.py::test_reused_pid_stays_terminal_during_delayed_child_callback+ - tests/test_memory_process_lifecycle.py::test_unknown_group_and_retained_descendant_prevent_false_cleanup+ - tests/test_memory_process_lifecycle.py::test_successful_group_signal_also_reaches_escaped_retained_child+ - tests/test_memory_process_lifecycle.py::test_native_leader_exit_retains_child_and_grandchild+ - tests/test_memory_process.py::test_orphan_record_survives_shift_until_classified_execution_exits+ given: One retained execution with direct-child wait and public process references+ when: Display creation times shift, the leader exits, or PIDs are reused+ then: Real exit and complete tree cleanup govern replacement; unknown and reused targets are never signaled+ evidence_boundary: Darwin arm64 native fault injection at psutil 7.1.0 and 7.2.2; deterministic generation model covers PID reuse without forcing host PID recycling+ - id: MEMORY-WAKE-205+ name: Real processing and recall continue across non-destructive Wake+ status: covered+ kind: recovery+ layer: integration+ test: tests/scenarios/memory_repair/test_memory_lifecycle_runtime.py::test_real_wake_preserves_old_and_processes_new_input+ given: Actual pinned EverOS, production claims and writer, test-owned storage, loopback model provider+ when: An old memory is captured and Wake replaces the child before a new capture+ then: Old and newly processed inputs are both recallable+ evidence_boundary: External model responses are deterministic doubles; Incus deployment requires unavailable seed configurationdiff --git a/tests/scenarios/memory_repair/observations.yaml b/tests/scenarios/memory_repair/observations.yamlindex 88f23c23f..b941ac1b1 100644--- a/tests/scenarios/memory_repair/observations.yaml+++ b/tests/scenarios/memory_repair/observations.yaml@@ -21,3 +21,9 @@ observations:- MEMORY-REPAIR-204- MEMORY-REPAIR-205observation: No operation stage is persisted or resumed; startup reevaluates the native root, while ordinary provider and machine faults stay degraded.++ - id: MEMORY-REPAIR-OBS-004+ scenarios:+ - MEMORY-WAKE-204+ - MEMORY-WAKE-205+ observation: Darwin arm64 tests inject the psutil boot-time read locally; public references survive the display-time shift. The real EverOS 1.2.3 pipeline requires 1024-dimensional embedding responses. Native production Wake, claims, writer, extraction, indexing and keyword recall run with test-owned storage and loopback model doubles; this is not model-quality or four-platform deployment evidence. Local Incus provisioning is blocked before target creation by required IM/model seed configuration.diff --git a/tests/scenarios/memory_repair/test_memory_lifecycle_runtime.py b/tests/scenarios/memory_repair/test_memory_lifecycle_runtime.pynew file mode 100644index 000000000..8154d982c--- /dev/null+++ b/tests/scenarios/memory_repair/test_memory_lifecycle_runtime.py@@ -0,0 +1,185 @@+"""Real EverOS storage/processing with a loopback external-provider double."""++from __future__ import annotations++import asyncio+import importlib.metadata+import importlib.util+import json+import os+import sys++import psutil+from pathlib import Path+import tempfile+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest++from avibe_memory.artifact import EVEROS_VERSION, MemoryArtifactManager+from avibe_memory.types import CaptureAccepted, CaptureRequest, RecallPolicy+from config.v2_config import MemoryConfig, MemoryEndpointConfig, MemoryProcessingConfig+++def lifecycle_provider():+ # Same stdlib HTTP boundary used by the Model Hub test upstream. This fixture+ # replaces only external model answers; Avibe/EverOS storage is never mocked.+ requests = []++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ requests.append((self.path, body))+ if self.path.endswith("/embeddings"):+ inputs = body["input"]+ if isinstance(inputs, str):+ inputs = [inputs]+ result = {+ "object": "list",+ "model": "fixture",+ "data": [+ {"object": "embedding", "index": i, "embedding": [1.0] + [0.0] * 1023}+ for i, _ in enumerate(inputs)+ ],+ "usage": {"prompt_tokens": 1, "total_tokens": 1},+ }+ else:+ prompt = json.dumps(body.get("messages", []), ensure_ascii=False)+ token = next(+ (value for value in ("lifecycle-new-1990", "lifecycle-during-1990") if value in prompt),+ "lifecycle-old-1990",+ )+ content = json.dumps(+ {+ "title": token,+ "content": f"The user prefers {token} tea. 测试记忆。",+ "atomic_facts": {"time": "2026-09-15", "atomic_fact": [f"The user prefers {token} tea."]},+ "foresights": [],+ "should_split": False,+ }+ )+ if "should_end" in prompt:+ content = json.dumps({"should_end": False, "reason": "fixture", "topic_summary": "tea"})+ elif "should_wait" in prompt:+ content = json.dumps({"boundaries": [], "should_wait": True})+ result = {+ "id": "fixture",+ "object": "chat.completion",+ "created": 1,+ "model": "fixture",+ "choices": [+ {"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": content}}+ ],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ }+ raw = json.dumps(result).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}/v1", requests+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++async def test_real_wake_preserves_old_and_processes_new_input(monkeypatch, memory_runtime_factory, lifecycle_provider):+ """MEMORY-WAKE-205: real claims/writer -> EverOS -> recall across Wake."""+ runtime_python = Path.cwd() / "scripts/memory_runtime/.venv/bin/python"+ if importlib.util.find_spec("everos") is None or not runtime_python.is_file():+ if os.environ.get("AVIBE_REQUIRE_MEMORY_RUNTIME_CONTRACT") == "1":+ pytest.fail("pinned EverOS 1.2.3 runtime environment is required")+ pytest.skip("pinned EverOS 1.2.3 runtime environment is not installed")+ assert importlib.metadata.version("everos") == EVEROS_VERSION+ monkeypatch.setenv("AVIBE_MEMORY_DEV_RUNTIME", str(runtime_python))+ url, requests = lifecycle_provider+ config = MemoryConfig(+ enabled=True,+ profile_enabled=False,+ processing=MemoryProcessingConfig(+ llm=MemoryEndpointConfig(url, "fixture", "fixture-key"),+ embedding=MemoryEndpointConfig(url, "fixture", "fixture-key"),+ ),+ )+ with tempfile.TemporaryDirectory(prefix="ml1990-", dir="/tmp") as temporary:+ home = Path(temporary).resolve()+ artifact = MemoryArtifactManager(+ runtime_dir=home / "runtime", offline=True, provider_root=home / "memory/everos-root"+ )+ runtime = memory_runtime_factory(config, artifact_manager=artifact, effective_home=home)+ principal = "u-" + "1" * 32++ async def capture_and_recall(token):+ assert (+ await runtime.module.capture(+ CaptureRequest(+ source_message_id=token,+ session_id=token,+ principal_id=principal,+ project_id="default",+ provenance="user_input",+ text=f"I prefer {token} tea. 测试记忆。",+ occurred_at_ms=1789488000000,+ )+ )+ == CaptureAccepted()+ )+ await runtime.module.wait_writer_idle_for_tests(timeout_seconds=30)+ assert runtime.module.offer_barrier(token) == "queued"+ await runtime.module.wait_writer_idle_for_tests(timeout_seconds=30)+ return await recall(token)++ async def recall(token):+ for _ in range(100):+ result = await runtime.module.recall(+ token,+ policy=RecallPolicy(mode="keyword", include_profile=False),+ principal_id=principal,+ project_id="default",+ )+ if token in str(result):+ return result+ await asyncio.sleep(0.2)+ pytest.fail(+ f"real EverOS did not recall {token}; result={result}; provider routes={[p for p, _ in requests]}"+ )++ try:+ assert await asyncio.wait_for(runtime.wake(), 60) == {"ok": True, "state": "running"}+ old_process = runtime._supervisor._child+ await capture_and_recall("lifecycle-old-1990")+ native_child = old_process._process+ if sys.platform == "darwin":+ from psutil import _psosx++ stamp = psutil.Process(native_child.pid).create_time()+ monkeypatch.setattr(_psosx, "boot_time", lambda: _psosx.INIT_BOOT_TIME + 1)+ assert psutil.Process(native_child.pid).create_time() == stamp + 1+ await asyncio.sleep(3.2)+ await capture_and_recall("lifecycle-during-1990")+ assert runtime._supervisor._child is old_process+ assert native_child.returncode is None+ assert runtime._supervisor._restart_attempts == 0+ assert await asyncio.wait_for(runtime.wake(), 60) == {"ok": True, "state": "running"}+ assert native_child.returncode is not None+ assert not old_process.running+ assert not old_process.retains_active_config+ await recall("lifecycle-old-1990")+ await capture_and_recall("lifecycle-new-1990")+ await recall("lifecycle-old-1990")+ assert requests+ finally:+ await memory_runtime_factory.close(runtime)diff --git a/tests/test_memory_distribution.py b/tests/test_memory_distribution.pyindex dff84d459..54fb289f7 100644--- a/tests/test_memory_distribution.py+++ b/tests/test_memory_distribution.py@@ -785,3 +785,19 @@ def test_wheel_installation_matrix(),cwd=tmp_path,)++[email protected]("project", [ROOT / "pyproject.toml", MEMORY_PROJECT / "pyproject.toml"])+def test_memory_process_dependency_requires_monotonic_public_identity(project) -> None:+ requirement = _requirement(_project(project)["dependencies"], "psutil")+ assert Version("7.0.0") not in requirement.specifier+ assert Version("7.1.0") in requirement.specifier+ assert Version("7.2.2") in requirement.specifier++[email protected]("variable", ["AVIBE_CORE_WHEEL", "AVIBE_MEMORY_WHEEL"])+def test_built_memory_process_dependency_floor(variable) -> None:+ _, metadata = _wheel_metadata(_wheel_path(variable))+ requirement = _requirement(metadata.get_all("Requires-Dist"), "psutil")+ assert Version("7.0.0") not in requirement.specifier+ assert Version("7.1.0") in requirement.specifierdiff --git a/tests/test_memory_process.py b/tests/test_memory_process.pyindex 3b97cd0bb..57b5692fd 100644--- a/tests/test_memory_process.py+++ b/tests/test_memory_process.py@@ -1,6 +1,5 @@from __future__ import annotations-from collections import dequeimport jsonimport osfrom pathlib import Path@@ -14,13 +13,24 @@ from avibe_memory.process import (_cmdline_is_sidecar,_memory_child_environment,EverOSProcessSettings,- FakeEverOSProcess,FakeEverOSProcessFactory,ReleasedEverOSOrphanReconciler,legacy_sync_record_path,)+class _TestReference:+ def __init__(self, host, pid):+ self.host, self.pid = host, pid+ self.generation = host.children.get(pid)++ def is_running(self):+ return self.generation is not None and self.host.children.get(self.pid) is self.generation++ def status(self):+ return "running"++class _ReleasedSyncHost:def __init__(self,@@ -34,6 +44,9 @@ class _ReleasedSyncHost:self.parent = parentself.signals: list[tuple[dict[int, float], int | None]] = []+ def capture(self, pid: int):+ return _TestReference(self, pid) if pid in self.children else None+def inspect_identity(self, pid: int):return self.parent if pid == 99 else self.children.get(pid)@@ -43,13 +56,13 @@ class _ReleasedSyncHost:def recorded_group_members(self, _group, *, role=None, **_kwargs):assert role == "cascade_sync"return {- pid: float(identity.stamp)+ pid: self.capture(pid)for pid, identity in self.children.items()if identity.stamp is not None}, []def find_syncs(self, **_kwargs):- return dict(self.candidates)+ return {pid: self.capture(pid) for pid in self.candidates}def find_sidecars(self, **_kwargs):return {}@@ -62,13 +75,12 @@ class _ReleasedSyncHost:pid: created_atfor pid, created_at in identities.items()if (- (identity := self.children.get(pid)) is not None- and identity.stamp == created_at+created_at is not None and created_at.is_running())}def signal(self, identities, _signum, *, process_group=None, **_kwargs) -> None:- self.signals.append((dict(identities), process_group))+ self.signals.append(({pid: ref.generation.stamp for pid, ref in identities.items()}, process_group))for pid in identities:self.children.pop(pid, None)@@ -89,18 +101,21 @@ class _SidecarHost:self.group_foreign = group_foreign or []self.signals: list[dict[int, float]] = []+ def capture(self, pid: int):+ return _TestReference(self, pid) if pid in self.children else None+def inspect_identity(self, pid: int):return self.children.get(pid)def process_group(self, pid: int) -> int | None:return pid- def snapshot_tree(self, pid: int, _group: int | None):+ def snapshot_tree(self, pid: int, _group: int | None, owned=None):identity = self.children.get(pid)- return {} if identity is None else {pid: float(identity.stamp)}+ return dict(owned) if owned is not None else ({} if identity is None else {pid: self.capture(pid)})def recorded_group_members(self, _group, **_kwargs):- return dict(self.group_owned), list(self.group_foreign)+ return {pid: self.capture(pid) for pid in self.group_owned}, list(self.group_foreign)def find_sidecars(self, **_kwargs):return {}@@ -116,13 +131,12 @@ class _SidecarHost:pid: created_atfor pid, created_at in identities.items()if (- (identity := self.children.get(pid)) is not None- and identity.stamp == created_at+created_at is not None and created_at.is_running())}def signal(self, identities, _signum, **_kwargs) -> None:- self.signals.append(dict(identities))+ self.signals.append({pid: ref.generation.stamp for pid, ref in identities.items()})for pid in identities:self.children.pop(pid, None)self.group_owned.pop(pid, None)@@ -255,39 +269,6 @@ def _released_sync_environment(}-async def test_fake_sidecar_start_and_stop_expose_proven_lifecycle() -> None:- ready = 0-- async def on_ready() -> None:- nonlocal ready- ready += 1-- process = FakeEverOSProcess(- start_results=deque([True]),- on_ready=on_ready,- )-- assert await process.start() is True- assert process.running is True- await process.stop()-- assert process.running is False- assert process.stopped is True- assert ready == 1---async def test_sidecar_stop_failure_retains_process_tree_proof() -> None:- process = FakeEverOSProcess(stop_failure=RuntimeError("still alive"))- assert await process.start() is True-- with pytest.raises(RuntimeError, match="still alive"):- await process.stop()-- assert process.retains_active_config is True--def test_process_factory_keeps_secrets_out_of_repr(tmp_path: Path) -> None:factory = FakeEverOSProcessFactory()settings = EverOSProcessSettings(@@ -355,43 +336,6 @@ async def test_recorded_sidecar_reaper_accepts_empty_owned_root(tmp_path: Path)assert provider_root.is_dir()- ("entrypoint", "legacy_record"),- [- ("avibe_memory.sidecar", False),- ("core.memory.sidecar", False),- ("core.memory.sidecar", True),- ],-)-async def test_sidecar_reaper_verifies_identity_before_signalling(- tmp_path: Path,- entrypoint: str,- legacy_record: bool,-) -> None:- home = tmp_path / "home"- provider_root = home / "memory" / "everos-root"- provider_root.mkdir(mode=0o700, parents=True)- home.chmod(0o700)- (home / "memory").chmod(0o700)- path, record = _sidecar_record(home)- if legacy_record:- record.pop("role")- path.write_text(json.dumps(record), encoding="utf-8")- identity = _sidecar_identity(home, record, entrypoint=entrypoint)- host = _SidecarHost({451: identity})- reaper = ReleasedEverOSOrphanReconciler(- provider_root=provider_root,- effective_home=home,- _host=host,- )-- await reaper.reconcile_orphans()-- assert host.signals[0] == {451: 10.5}- assert not path.exists()--@pytest.mark.parametrize("entrypoint",["avibe_memory.sidecar", "core.memory.sidecar"],@@ -613,3 +557,214 @@ def test_generated_ome_profile_strategies_follow_switch(tmp_path: Path, profile_assert strategies["extract_user_profile"]["enabled"] is profile_enabledassert strategies["reflect_episodes"]["enabled"] is Falseassert strategies["extract_foresight"]["enabled"] is False+++ ("entrypoint", "legacy_record"),+ [+ ("avibe_memory.sidecar", False),+ ("core.memory.sidecar", False),+ ("core.memory.sidecar", True),+ ],+)+async def test_orphan_record_survives_shift_until_classified_execution_exits(tmp_path, entrypoint, legacy_record):+ """MEMORY-WAKE-204: classification, signals, wait and retirement share one reference."""+ from dataclasses import replace++ home = tmp_path / "home"+ root = home / "memory" / "everos-root"+ root.mkdir(parents=True, mode=0o700)+ home.chmod(0o700)+ root.parent.chmod(0o700)+ record_path, record = _sidecar_record(home)+ if legacy_record:+ record.pop("role")+ record_path.write_text(json.dumps(record), encoding="utf-8")+ identity = _sidecar_identity(home, record, entrypoint=entrypoint)++ class ShiftHost(_SidecarHost):+ shifted = False+ rounds = 0+ captured = None++ def capture(self, pid):+ self.captured = super().capture(pid)+ return self.captured++ def inspect_identity(self, pid):+ value = super().inspect_identity(pid)+ return replace(value, stamp=value.stamp + 1) if self.shifted and value else value++ def signal(self, identities, signum, **kwargs):+ self.rounds += 1+ assert identities[451] is self.captured+ self.shifted = True+ if self.rounds == 2:+ super().signal(identities, signum, **kwargs)++ async def wait_for_exit(self, identities, timeout, **kwargs):+ assert record_path.exists()+ assert identities[451] is self.captured+ if self.rounds == 1:+ assert self.inspect_identity(451).stamp == 11.5+ assert self.live(identities)+ return False+ assert not self.live(identities)+ return True++ host = ShiftHost({451: identity})+ reaper = ReleasedEverOSOrphanReconciler(+ provider_root=root, effective_home=home, _host=host+ )+ await reaper.reconcile_orphans()+ assert host.rounds == 2+ assert not record_path.exists()+++def test_record_retirement_rejects_a_late_claimed_survivor(tmp_path):+ from avibe_memory.process import SidecarOwnership+ home = tmp_path / "home"+ record_path, record = _sidecar_record(home)+ host = _SidecarHost(group_owned={452: 10.5})+ ownership = SidecarOwnership(record_path=record_path,+ socket_path=Path(record["socket_path"]),+ provider_root=Path(record["provider_root"]), _host=host)+ with pytest.raises(RuntimeError, match="did not exit"):+ ownership.retire_if_group_is_clear(451, 451)+ assert record_path.exists()++[email protected]("exit_phase", ["before", "during"])+async def test_orphan_exit_during_classification_still_reaps_surviving_group(tmp_path, exit_phase):+ """A normal exit is absence, but its recorded group must still be cleaned."""+ home = tmp_path / "home"+ root = home / "memory/everos-root"+ root.mkdir(parents=True, mode=0o700)+ home.chmod(0o700)+ root.parent.chmod(0o700)+ path, record = _sidecar_record(home)+ identity = _sidecar_identity(home, record)++ class Host(_SidecarHost):+ def capture(self, pid):+ reference = super().capture(pid)+ if pid == 451 and exit_phase == "before":+ self.children.pop(pid, None)+ return reference++ def inspect_identity(self, pid):+ if pid == 451 and exit_phase == "during":+ self.children.pop(pid, None)+ return super().inspect_identity(pid)++ host = Host({451: identity, 452: identity}, group_owned={452: 10.5})+ reaper = ReleasedEverOSOrphanReconciler(provider_root=root, effective_home=home, _host=host)+ await reaper.reconcile_orphans()+ assert host.signals == [{452: 10.5}]+ assert not path.exists()++[email protected]("consumer", ["orphan", "pending_sync"])[email protected]("exit_phase", ["before_group", "during_group"])+async def test_reaper_never_targets_replacement_process_group(tmp_path, consumer, exit_phase):+ """A recycled non-leader PID cannot redirect old ownership into its group."""+ from avibe_memory.process import _confirmed_owned_processes++ home = tmp_path / "home"+ root = home / "memory/everos-root"+ root.mkdir(parents=True, mode=0o700)+ home.chmod(0o700)+ root.parent.chmod(0o700)+ if consumer == "orphan":+ path, record = _sidecar_record(home)+ identity = _sidecar_identity(home, record)+ else:+ path, record = _released_sync_record(home, state="pending")+ identity = _ProcessIdentity(+ stamp=10.5, cmdline=tuple(record["argv"]), uid=os.getuid(),+ environment=_released_sync_environment(home, record), wall_create_time=10.5,+ )+ replacement = _ProcessIdentity(stamp=99, cmdline=("foreign",), uid=os.getuid())+ base = _SidecarHost if consumer == "orphan" else _ReleasedSyncHost+ group_reads = []+ cleanup_groups = []++ class Reference(_TestReference):+ reads = 0++ def is_running(self):+ self.reads += 1+ if exit_phase == "before_group" and self.reads == 3:+ self.host.children[451] = replacement+ return super().is_running()++ class Host(base):+ def capture(self, pid):+ return Reference(self, pid)++ def find_syncs(self, **kwargs):+ return {451: self.capture(451)} if consumer == "pending_sync" else {}++ def process_group(self, pid):+ assert self.children[451] is identity, "looked up a known terminal PID"+ group_reads.append(pid)+ self.children[451] = replacement+ return 999 # Replacement is not this unrelated group's leader.++ def recorded_group_members(self, group, **kwargs):+ assert group == 451+ cleanup_groups.append(group)+ return {}, []++ def signal(self, identities, signum, *, process_group=None, **kwargs):+ assert process_group == 451+ assert not _confirmed_owned_processes(identities)++ async def wait_for_exit(self, identities, timeout, *, process_group=None, **kwargs):+ assert process_group == 451+ return not self.live(identities)++ host = Host({451: identity})+ reaper = ReleasedEverOSOrphanReconciler(provider_root=root, effective_home=home, _host=host)+ await reaper.reconcile_orphans()+ assert group_reads == ([] if exit_phase == "before_group" else [451])+ assert cleanup_groups and set(cleanup_groups) == {451}+ assert host.children[451] is replacement+ assert not path.exists()+++async def test_gone_unidentified_anchor_preserves_legacy_helper_classification(tmp_path):+ home = tmp_path / "home"+ root = home / "memory/everos-root"+ root.mkdir(parents=True, mode=0o700)+ home.chmod(0o700)+ root.parent.chmod(0o700)+ path, record = _sidecar_record(home)+ path.write_text("unusable")+ identity = _sidecar_identity(home, record)+ seen_roles = []++ class Host(_SidecarHost):+ def find_sidecars(self, **kwargs):+ reference = self.capture(451)+ self.children.pop(451)+ return {451: reference}++ def process_group(self, pid):+ pytest.fail("gone anchor must keep its original isolated group")++ def recorded_group_members(self, group, *, role=None, **kwargs):+ assert group == 451+ seen_roles.append(role)+ # Shipped unidentified recovery accepts a helper without a role tag.+ return super().recorded_group_members(group) if role is None else ({}, [452])++ host = Host({451: identity, 452: identity}, group_owned={452: 10.5})+ reaper = ReleasedEverOSOrphanReconciler(provider_root=root, effective_home=home, _host=host)+ await reaper.reconcile_orphans()+ assert seen_roles and set(seen_roles) == {None}+ assert not host.children and not path.exists()diff --git a/tests/test_memory_process_lifecycle.py b/tests/test_memory_process_lifecycle.pynew file mode 100644index 000000000..60242e13d--- /dev/null+++ b/tests/test_memory_process_lifecycle.py@@ -0,0 +1,804 @@+"""MEMORY-WAKE-204: native lifecycle and deterministic generation boundaries."""++from __future__ import annotations++import asyncio+import os+from pathlib import Path+import signal+import socket+import sys+import tempfile+import time+from types import SimpleNamespace++import psutil+import pytest++import avibe_memory.process as module++pytestmark = pytest.mark.asyncio+++async def spawn(tmp_path, code="import time; time.sleep(60)"):+ return await asyncio.create_subprocess_exec(+ sys.executable,+ "-u",+ "-c",+ code,+ cwd=tmp_path,+ env={+ "HOME": str(tmp_path),+ "XDG_CONFIG_HOME": str(tmp_path / "config"),+ "XDG_DATA_HOME": str(tmp_path / "data"),+ "PATH": os.defpath,+ },+ start_new_session=True,+ stdout=asyncio.subprocess.PIPE,+ stdin=asyncio.subprocess.PIPE,+ )+++async def dispose(child):+ if child.returncode is None:+ child.kill()+ await child.wait()+++def settings():+ return module.EverOSProcessSettings(+ llm_base_url="http://127.0.0.1:1/v1",+ llm_model="test",+ llm_api_key="test",+ embedding_base_url="http://127.0.0.1:1/v1",+ embedding_model="test",+ embedding_api_key="test",+ )+++async def test_native_shift_survives_full_scans_and_stop(tmp_path, monkeypatch):+ if sys.platform != "darwin":+ pytest.skip("Darwin native fault")+ from psutil import _psosx++ host = module._SystemProcessHost()+ child = await spawn(tmp_path, "import sys; [print(line.strip().upper(), flush=True) for line in sys.stdin]")+ owner = module.EverOSProcess(sys.executable, effective_home=tmp_path, _host=host)+ owner._process = child+ owner._process_group = host.process_group(child.pid)+ owner._owned_processes = host.snapshot_tree(child.pid, owner._process_group)+ owner._desired_running = True+ original = owner._owned_processes[child.pid]+ stamp = psutil.Process(child.pid).create_time()+ notifications = []+ owner._on_unexpected_exit = lambda: notifications.append("wake")+ monitor = asyncio.create_task(owner._monitor_child(child))+ try:+ monkeypatch.setattr(_psosx, "boot_time", lambda: _psosx.INIT_BOOT_TIME + 1)+ assert psutil.Process(child.pid).create_time() == stamp + 1+ await asyncio.sleep(3.2) # More than three unshortened production scans.+ child.stdin.write(b"new input\n")+ await child.stdin.drain()+ assert await asyncio.wait_for(child.stdout.readline(), 2) == b"NEW INPUT\n"+ assert child.returncode is None+ assert notifications == []+ assert owner._owned_processes[child.pid] is original+ await owner._terminate_owned_tree(+ child, process_group=owner._process_group, owned_processes=owner._owned_processes+ )+ assert child.returncode is not None+ assert not original.is_running()+ finally:+ monitor.cancel()+ await asyncio.gather(monitor, return_exceptions=True)+ await dispose(child)+++async def test_native_probe_timeout_during_shift(tmp_path, monkeypatch):+ if sys.platform != "darwin":+ pytest.skip("version-bound Darwin boot-time fault injection")+ from psutil import _psosx++ class Host(module._SystemProcessHost):+ async def spawn(self, *args, **kwargs):+ self.child = await spawn(tmp_path)+ return self.child++ def capture(self, pid):+ reference = super().capture(pid)+ stamp = reference.create_time()+ monkeypatch.setattr(_psosx, "boot_time", lambda: _psosx.INIT_BOOT_TIME + 1)+ assert psutil.Process(pid).create_time() == stamp + 1+ return reference++ host = Host()+ owner = module.EverOSProcess(+ sys.executable, effective_home=tmp_path, settings=settings(), _host=host, stop_timeout_seconds=0.2+ )+ monkeypatch.setattr(module, "_processing_probe_timeout_seconds", lambda _: 0.1)+ assert not await owner.processing_healthy()+ assert host.child.returncode is not None++[email protected]("consumer", ["stop", "start_failure", "record_exit", "probe_timeout"])+async def test_capture_keeps_reference_through_transient_read_failure(+ tmp_path, monkeypatch, caplog, consumer,+):+ with tempfile.TemporaryDirectory(prefix="mc1990-", dir="/tmp") as temporary:+ tmp_path = Path(temporary).resolve()+ (tmp_path / "memory/everos-root").mkdir(parents=True, mode=0o700)+ (tmp_path / "memory").chmod(0o700)++ class Host(module._SystemProcessHost):+ async def spawn(self, *args, **kwargs):+ self.child = await spawn(tmp_path)+ return self.child++ def capture(self, pid):+ reference = psutil.Process(pid)+ self.reference = reference++ def inaccessible():+ raise psutil.AccessDenied(pid)++ # Only the capture boundary loses visibility; it must not discard+ # a successfully constructed reference because of an extra read.+ with monkeypatch.context() as fault:+ fault.setattr(reference, "create_time", inaccessible)+ fault.setattr(reference, "is_running", inaccessible)+ fault.setattr(psutil, "Process", lambda target: reference)+ captured = super().capture(pid)+ assert captured is reference+ return captured++ def inspect_identity(self, pid):+ if consumer == "record_exit":+ self.reference.terminate()+ return None+ return super().inspect_identity(pid)++ def signal(self, identities, signum, **kwargs):+ assert identities[self.child.pid] is self.reference+ super().signal(identities, signum, **kwargs)++ host = Host()+ owner = module.EverOSProcess(+ sys.executable, effective_home=tmp_path, settings=settings(), _host=host,+ startup_timeout_seconds=0.1, stop_timeout_seconds=0.2,+ provider_root_guard=lambda: None,+ )+ try:+ if consumer == "probe_timeout":+ monkeypatch.setattr(module, "_processing_probe_timeout_seconds", lambda _: 0.1)+ assert not await owner.processing_healthy()+ elif consumer in {"start_failure", "record_exit"}:+ # Real start/record/failed-readiness cleanup, with a sleeping test child.+ assert not await owner.start()+ else:+ owner._process = await host.spawn()+ owner._process_group = host.process_group(host.child.pid)+ owner._owned_processes = {host.child.pid: host.capture(host.child.pid)}+ await owner.stop()+ assert host.child.returncode is not None+ assert not host.reference.is_running()+ assert not owner.retains_active_config+ if consumer == "record_exit":+ assert "sidecar exited before ownership could be recorded" in caplog.text+ assert "AttributeError" not in caplog.text+ finally:+ if hasattr(host, "child"):+ await dispose(host.child)+++async def test_probe_without_initial_reference_reports_incomplete_cleanup(tmp_path, monkeypatch):+ class Host(module._SystemProcessHost):+ async def spawn(self, *args, **kwargs):+ self.child = await spawn(tmp_path)+ return self.child++ def capture(self, pid):+ return None++ host = Host()+ owner = module.EverOSProcess(+ sys.executable, effective_home=tmp_path, settings=settings(), _host=host,+ stop_timeout_seconds=0.1,+ )+ monkeypatch.setattr(module, "_processing_probe_timeout_seconds", lambda _: 0.1)+ try:+ assert not await owner.processing_healthy()+ assert host.child.returncode is None # Unknown is neither authority nor cleanup.+ finally:+ await dispose(host.child)+++async def test_native_orphan_reaper_retains_record_through_shift(tmp_path, monkeypatch):+ if sys.platform != "darwin":+ pytest.skip("Darwin native fault")+ from psutil import _psosx++ # A test-owned module has the released CLI/environment shape. Classification,+ # retained references, signals, waits and record retirement are production code.+ package = tmp_path / "avibe_memory"+ package.mkdir()+ (package / "__init__.py").touch()+ (package / "sidecar.py").write_text("import time; time.sleep(60)")+ root = tmp_path / "memory/everos-root"+ root.mkdir(parents=True, mode=0o700)+ root.parent.chmod(0o700)+ socket_path = tmp_path / "memory/.rt/everos.sock"+ record_path = socket_path.with_suffix(".sidecar.json")+ child = await asyncio.create_subprocess_exec(+ sys.executable, "-m", "avibe_memory.sidecar", "--uds", str(socket_path),+ cwd=tmp_path, start_new_session=True,+ env={"HOME": str(tmp_path), "EVEROS_ROOT": str(root), "AVIBE_MEMORY_CHILD_ROLE": "sidecar"},+ )+ stamp = psutil.Process(child.pid).create_time()++ class Host(module._SystemProcessHost):+ rounds = 0++ def signal(self, identities, signum, **kwargs):+ self.rounds += 1+ assert record_path.exists()+ if self.rounds == 1:+ monkeypatch.setattr(_psosx, "boot_time", lambda: _psosx.INIT_BOOT_TIME + 1)+ assert psutil.Process(child.pid).create_time() == stamp + 1+ return # First bounded wait must not retire this live execution.+ super().signal(identities, signum, **kwargs)++ async def wait_for_exit(self, identities, timeout_seconds, **kwargs):+ result = await super().wait_for_exit(identities, timeout_seconds, **kwargs)+ assert record_path.exists()+ assert result is (self.rounds == 2)+ return result++ host = Host()+ ownership = module.SidecarOwnership(+ record_path=record_path, socket_path=socket_path, provider_root=root,+ python=Path(sys.executable), stop_timeout_seconds=0.1, _host=host,+ )+ try:+ ownership.record_launch(child.pid, stamp, child.pid)+ await ownership.reap()+ await child.wait()+ assert host.rounds == 2+ assert not record_path.exists()+ finally:+ await dispose(child)+++async def test_real_tcp_listener_is_rejected(tmp_path):+ child = await spawn(+ tmp_path,+ "import socket,time; s=socket.socket(); s.bind(('127.0.0.1',0)); s.listen(); print('ready',flush=True); time.sleep(60)",+ )+ try:+ assert await child.stdout.readline() == b"ready\n"+ host = module._SystemProcessHost()+ assert host.has_tcp_listener(host.snapshot_tree(child.pid, host.process_group(child.pid)))+ finally:+ await dispose(child)+++class Generation:+ """Controlled kernel generation; replacing the table entry is actual model reuse."""++ def __init__(self, kernel, pid):+ self.kernel, self.pid = kernel, pid+ self.birth = object()+ self.terminal = False+ self.denied = False+ self.signals = []+ self.descendants = []+ kernel[pid] = self++ def is_running(self):+ if self.kernel.get(self.pid) is not self:+ self.terminal = True+ return not self.terminal++ def status(self):+ if self.denied:+ raise psutil.AccessDenied(self.pid)+ return "running"++ def children(self, recursive=False):+ return self.descendants++ def send_signal(self, signum):+ assert self.is_running(), "signal attempted on a replacement generation"+ self.signals.append(signum)++ def net_connections(self, kind):+ assert self.is_running(), "inspected replacement generation"+ return []++[email protected]("captured", [True, False])+async def test_reused_pid_stays_terminal_during_delayed_child_callback(monkeypatch, captured):+ kernel = {}+ old = Generation(kernel, 451)+ retained = old if captured else None+ owned = {451: retained}+ replacement = Generation(kernel, 451)+ host = module._SystemProcessHost()+ callback = asyncio.Event()++ async def wait():+ await callback.wait()+ return 0++ child = SimpleNamespace(pid=451, returncode=None, wait=wait)+ monkeypatch.setattr(module, "_snapshot_process_group", lambda group: {})+ monkeypatch.setattr(psutil, "pid_exists", lambda pid: pid in kernel)+ host.snapshot_tree(451, None, owned)+ host.signal(owned, signal.SIGTERM, process=child)+ assert replacement.birth is not old.birth+ assert not old.signals and not replacement.signals+ assert owned[451] is retained+ if captured:+ assert not host.has_tcp_listener(owned)+ else:+ with pytest.raises(RuntimeError, match="listeners"):+ host.has_tcp_listener(owned)+ assert not await host.wait_for_exit(owned, 0.1, process=child)+ callback.set()+ if not captured:+ assert not await host.wait_for_exit(owned, 0.1, process=child)+ kernel.clear()+ assert await host.wait_for_exit(owned, 0.2, process=child)+++async def test_unknown_group_and_retained_descendant_prevent_false_cleanup(monkeypatch):+ kernel = {}+ root = Generation(kernel, 451)+ helper = Generation(kernel, 452)+ root.descendants = [helper]+ owned = {451: root}+ monkeypatch.setattr(module, "_snapshot_process_group", lambda group: {453: None} if group else {})+ monkeypatch.setattr(module, "_isolated_process_group", lambda pid: None)+ host = module._SystemProcessHost()+ module._refresh_owned_process_tree(host, owned, 451, None)+ del kernel[451]+ helper.denied = True+ assert module._live_owned_processes(owned) == {452: helper}+ host.signal(owned, signal.SIGTERM, process_group=451)+ assert helper.signals == []+ assert not module._group_contains_only_confirmed_owned_processes(451, owned)+ assert not await module._wait_for_identities_exit(owned, 0.1, 451)+ helper.denied = False+ host.signal(owned, signal.SIGTERM, process_group=451)+ assert helper.signals == [signal.SIGTERM]+ del kernel[452]+ assert not await module._wait_for_identities_exit(owned, 0.1, 451)+ monkeypatch.setattr(module, "_snapshot_process_group", lambda group: {})+ assert await module._wait_for_identities_exit(owned, 0.1, 451)++[email protected]("leader_exited", [False, True])+async def test_reused_member_cannot_be_readopted_from_group(monkeypatch, leader_exited):+ kernel = {}+ root = Generation(kernel, 451)+ old = Generation(kernel, 452)+ owned = {451: root, 452: old}+ replacement = Generation(kernel, 452)+ monkeypatch.setattr(module, "_snapshot_process_group", lambda group: {451: root, 452: replacement})+ monkeypatch.setattr(module, "_isolated_process_group", lambda pid: 451)+ host = module._SystemProcessHost()+ if leader_exited:+ del kernel[451]+ monkeypatch.setattr(host, "recorded_group_members", lambda *args, **kwargs: ({452: replacement}, []))+ module._refresh_terminating_process_tree(+ host, owned, 451, 451, socket_path=Path("/test/socket"),+ provider_root=Path("/test/root"), role="sidecar",+ )+ assert owned[452] is old+ assert not module._group_contains_only_confirmed_owned_processes(451, owned)+ module._signal_owned_processes(owned, signal.SIGTERM)+ assert replacement.signals == []+++async def test_classifier_cannot_transfer_authority_between_generations():+ kernel = {}+ old = Generation(kernel, 451)++ class Host:+ def inspect_identity(self, pid):+ Generation(kernel, pid)+ return SimpleNamespace(stamp=1)++ assert module._inspect_captured_identity(Host(), 451, old) is None++[email protected]("group_delivery", ["success", "refused", "failed", "reused_during_lookup"])+async def test_successful_group_signal_also_reaches_escaped_retained_child(monkeypatch, group_delivery):+ kernel = {}+ leader = Generation(kernel, 451)+ escaped = Generation(kernel, 452)+ group_signals = []+ monkeypatch.setattr(module, "_snapshot_process_group", lambda group: {451: leader})+ terminal = Generation(kernel, 453)+ Generation(kernel, 453)+ denied = Generation(kernel, 454)+ denied.denied = True++ def getpgid(pid):+ assert pid in {451, 452}, "looked up a terminal/unreadable reference"+ if pid == 452 and group_delivery == "reused_during_lookup":+ Generation(kernel, pid)+ return 451 if pid == leader.pid else 452++ monkeypatch.setattr(module.os, "getpgid", getpgid)++ def killpg(group, sig):+ if group_delivery == "failed":+ raise PermissionError+ group_signals.append((group, sig))+ leader.send_signal(sig)++ monkeypatch.setattr(module.os, "killpg", killpg)+ if group_delivery == "refused":+ monkeypatch.setattr(module, "_group_contains_only_confirmed_owned_processes", lambda *args: False)+ host = module._SystemProcessHost()+ owned = {451: leader, 452: escaped, 453: terminal, 454: denied}+ host.signal(owned, signal.SIGTERM, process_group=451)+ assert group_signals == ([(451, signal.SIGTERM)] if group_delivery in {"success", "reused_during_lookup"} else [])+ assert leader.signals == [signal.SIGTERM]+ assert escaped.signals == ([] if group_delivery == "reused_during_lookup" else [signal.SIGTERM])+ assert not terminal.signals and not denied.signals+ if group_delivery == "reused_during_lookup":+ assert not kernel[452].signals+ kernel.clear()+ monkeypatch.setattr(module, "_snapshot_process_group", lambda group: {})+ assert await host.wait_for_exit(owned, 0.1, process_group=451)+++async def test_failed_stop_keeps_newly_discovered_references(monkeypatch):+ kernel = {}+ root = Generation(kernel, 451)+ descendant = Generation(kernel, 452)+ root.descendants = [descendant]+ owned = {451: root}+ monkeypatch.setattr(module, "_snapshot_process_group", lambda group: {})++ class Host(module._SystemProcessHost):+ async def wait_for_exit(self, identities, *args, **kwargs):+ return False++ with pytest.raises(RuntimeError, match="did not exit"):+ await module._terminate_owned_process_tree(+ Host(), SimpleNamespace(pid=451), process_group=None, owned_processes=owned, stop_timeout_seconds=0.1,+ socket_path=Path("/test/socket"), provider_root=Path("/test/root"),+ )+ assert owned[452] is descendant+++async def test_native_leader_exit_retains_child_and_grandchild(tmp_path):+ helper_code = "import subprocess,sys,time; p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']); print(p.pid,flush=True); time.sleep(60)"+ code = f"import subprocess,sys; subprocess.Popen([sys.executable,'-u','-c',{helper_code!r}]); sys.stdin.readline()"+ child = await spawn(tmp_path, code)+ owned = {}+ try:+ grandchild_pid = int(await asyncio.wait_for(child.stdout.readline(), 3))+ host = module._SystemProcessHost()+ group = host.process_group(child.pid)+ owned = host.snapshot_tree(child.pid, group)+ assert grandchild_pid in owned+ assert len(owned) == 3+ child.stdin.write(b"exit\n")+ await child.stdin.drain()+ for _ in range(100):+ if child.returncode is not None:+ break+ await asyncio.sleep(0.01)+ assert child.returncode == 0+ assert host.live(owned)+ await module._terminate_owned_process_tree(+ host, child, process_group=group, owned_processes=owned, stop_timeout_seconds=1,+ socket_path=tmp_path / "memory.sock", provider_root=tmp_path,+ )+ assert not host.live(owned)+ finally:+ # Only retained test-created generations are eligible for fallback cleanup.+ module._signal_owned_processes(owned, signal.SIGKILL)+ await dispose(child)+++async def test_unreadable_discovered_sidecar_remains_unresolved(monkeypatch, tmp_path):+ socket_path = tmp_path / "owned.sock"+ observed = SimpleNamespace(+ pid=451,+ uids=lambda: SimpleNamespace(real=os.getuid()),+ cmdline=lambda: [sys.executable, "-m", "avibe_memory.sidecar", "--uds", str(socket_path)],+ )+ monkeypatch.setattr(module.psutil, "process_iter", lambda: [observed])+ monkeypatch.setattr(module, "_capture_process", lambda pid: None)+ monkeypatch.setattr(module.psutil, "pid_exists", lambda pid: True)+ found = module._processes_serving_owned_socket(socket_path=socket_path)+ assert found == {451: None}+ assert module._live_owned_processes(found) == found+ assert module._confirmed_owned_processes(found) == {}+ module._signal_owned_processes(found, signal.SIGTERM)+ with pytest.raises(RuntimeError, match="listeners"):+ module._SystemProcessHost().has_tcp_listener(found)+++ ("consumer", "timing", "mismatch"),+ [("stop", "before", None), ("stop", "term", None),+ ("watch", "before", None), ("probe", "before", None),+ ("probe", "term", None), ("orphan", "term", None),+ ("stop", "before", "root"), ("stop", "before", "role"),+ ("stop", "before", "unreadable")],+)+async def test_native_late_group_helper_is_classified_before_cleanup(+ monkeypatch, consumer, timing, mismatch,+):+ """MEMORY-WAKE-204: unseen helper survives leader; context, not PGID, owns it."""+ with tempfile.TemporaryDirectory(prefix="mlate-", dir="/tmp") as temporary:+ home = Path(temporary).resolve()+ root = home / "memory/everos-root"+ root.mkdir(parents=True, mode=0o700)+ root.parent.chmod(0o700)+ package = home / "avibe_memory"+ package.mkdir()+ (package / "__init__.py").touch()+ (package / "sidecar.py").write_text(+ "import os,signal,subprocess,sys,time\n"+ "def leave(*args):\n"+ " with open('term-count','a') as log: log.write('1')\n"+ " if len(open('term-count').read()) > 1: return\n"+ " time.sleep(0.05)\n"+ " env=dict(os.environ)\n"+ f" if {mismatch == 'root'!r}: env['EVEROS_ROOT'] += '-foreign'\n"+ f" if {mismatch == 'role'!r}: env['AVIBE_MEMORY_CHILD_ROLE'] = 'foreign'\n"+ " p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)'],env=env,"+ "stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)\n"+ " print(p.pid,flush=True)\n"+ " sys.exit(0)\n"+ "signal.signal(signal.SIGTERM,leave)\n"+ "print('ready',flush=True)\n"+ "sys.stdin.readline()\n"+ "leave()\n"+ )+ socket_path = home / "memory/.rt/everos.sock"+ role = "processing_probe" if consumer == "probe" else "sidecar"+ child = await asyncio.create_subprocess_exec(+ sys.executable, "-m", "avibe_memory.sidecar", "--uds", str(socket_path),+ cwd=home, start_new_session=True,+ env={"HOME": str(home), "EVEROS_ROOT": str(root), "AVIBE_MEMORY_CHILD_ROLE": role},+ stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,+ )+ assert await child.stdout.readline() == b"ready\n"+ async def observe_helper():+ line = await child.stdout.readline()+ try:+ return psutil.Process(int(line)) if line else None+ except psutil.NoSuchProcess:+ return None++ if timing == "term":+ deliver_group = module._signal_owned_group++ def group_delivery(*args):+ delivered = deliver_group(*args)+ if delivered and args[2] == signal.SIGTERM:+ # Ensure the native handler has begun before individual+ # delivery, so coalescing cannot hide a duplicate TERM.+ for _ in range(50):+ if (home / "term-count").exists():+ break+ time.sleep(0.002)+ return delivered++ monkeypatch.setattr(module, "_signal_owned_group", group_delivery)+ helper_task = asyncio.create_task(observe_helper())+ helper = None+ host = module._SystemProcessHost()+ owner = module.EverOSProcess(+ sys.executable, effective_home=home, _host=host, settings=settings(),+ provider_root_guard=lambda: None, stop_timeout_seconds=0.1,+ )+ owned = {child.pid: host.capture(child.pid)}+ owner._process, owner._process_group, owner._owned_processes = child, child.pid, owned+ owner._ownership.record_launch(child.pid, module._process_creation_stamp(owned[child.pid]), child.pid)+ record_path = owner._ownership.record_path+ try:+ if consumer == "probe":+ async def probe_spawn(*args, **kwargs):+ assert kwargs["env"]["AVIBE_MEMORY_CHILD_ROLE"] == role+ return child++ monkeypatch.setattr(host, "spawn", probe_spawn)+ monkeypatch.setattr(module, "_processing_probe_timeout_seconds", lambda _: 0.1)+ # The probe's own capture/scan happens before release of this leader.+ original_snapshot = host.snapshot_tree++ def snapshot(*args, **kwargs):+ result = original_snapshot(*args, **kwargs)+ if timing == "before" and child.returncode is None:+ child.stdin.write(b"go\n")+ return result++ monkeypatch.setattr(host, "snapshot_tree", snapshot)+ elif timing == "before":+ child.stdin.write(b"go\n")+ await child.stdin.drain()+ helper = await helper_task+ await child.wait()+ assert helper.pid not in owned+ if mismatch == "unreadable":+ original_environment = module._disclosed_process_environment+ monkeypatch.setattr(+ module, "_disclosed_process_environment",+ lambda process: None if process.pid == helper.pid else original_environment(process),+ )+ if mismatch:+ with pytest.raises(RuntimeError, match="did not exit"):+ await owner.stop()+ assert helper.is_running() and record_path.exists()+ assert owner.retains_active_config+ else:+ if consumer == "probe":+ result = await owner.processing_healthy()+ assert result is (timing == "before")+ elif consumer == "orphan":+ await owner._ownership.reap()+ elif consumer == "watch":+ await owner._watch_child(child)+ else:+ await owner.stop()+ if helper is None:+ helper = await helper_task if child.returncode is None else None+ assert child.returncode is not None+ assert not module._snapshot_process_group(child.pid)+ assert (home / "term-count").read_text() == "1"+ if consumer != "probe":+ assert not record_path.exists()+ if consumer in {"stop", "watch"}:+ assert not owner.retains_active_config # Replacement admission is clear.+ finally:+ await dispose(child)+ helper = await asyncio.wait_for(helper_task, 2)+ if helper is not None and module._reference_state(helper, helper.pid) is True:+ helper.kill()++[email protected]("discovery", ["socket", "root", "sync"])+async def test_discovery_skips_generation_gone_during_classification(monkeypatch, tmp_path, discovery):+ kernel = {}+ reference = Generation(kernel, 451)+ socket_path = tmp_path / "memory.sock"+ cmdline = [sys.executable, "-m", "avibe_memory.sidecar", "--uds", str(socket_path)]+ if discovery == "sync":+ cmdline = [sys.executable, "-I", "-m", "everos.entrypoints.cli.main", "cascade", "sync"]+ reference.uids = lambda: SimpleNamespace(real=os.getuid())+ reference.cmdline = lambda: cmdline+ reference.create_time = lambda: 1.0++ def environment():+ kernel.clear()+ return {"EVEROS_ROOT": str(tmp_path), "AVIBE_MEMORY_CHILD_ROLE": "cascade_sync" if discovery == "sync" else "sidecar", "AVIBE_MEMORY_SYNC_NONCE": "test"}++ reference.environ = environment+ if discovery == "socket":+ def command():+ kernel.clear()+ return cmdline+ reference.cmdline = command+ monkeypatch.setattr(psutil, "process_iter", lambda: [reference])+ monkeypatch.setattr(module, "_capture_process", lambda pid: reference)+ monkeypatch.setattr(module, "_process_creation_stamp", lambda process: 1.0)+ if discovery == "socket":+ result = module._processes_serving_owned_socket(socket_path=socket_path)+ elif discovery == "root":+ result = module._processes_serving_owned_root(provider_root=tmp_path)+ else:+ result = module._processes_syncing_owned_root(provider_root=tmp_path, python=Path(sys.executable), nonce="test")+ assert not kernel, "test must reach the classification race"+ assert result == {}++[email protected]("timeout", [False, True], ids=["ready-stop", "startup-timeout"])+async def test_startup_retains_helper_observed_before_detachment(monkeypatch, timeout):+ """Readiness discovery must survive later loss of both ancestry and group."""+ with tempfile.TemporaryDirectory(prefix="mr1990-", dir="/tmp") as temporary:+ root = Path(temporary).resolve()+ (root / "memory/everos-root").mkdir(parents=True, mode=0o700)+ (root / "memory").chmod(0o700)+ helper_code = """+import os, pathlib, time+root = pathlib.Path('.')+(root / 'helper.tmp').write_text(str(os.getpid()))+(root / 'helper.tmp').replace(root / 'helper')+while not (root / 'detach').exists(): time.sleep(.005)+os.setsid()+(root / 'detached').touch()+time.sleep(60)+"""+ middle_code = f"""+import pathlib, subprocess, sys, time+subprocess.Popen([sys.executable, '-c', {helper_code!r}],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+while not pathlib.Path('detach').exists(): time.sleep(.005)+"""+ leader_code = f"""+import pathlib, subprocess, sys, time+while not pathlib.Path('spawn-helper').exists(): time.sleep(.005)+subprocess.Popen([sys.executable, '-c', {middle_code!r}],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+time.sleep(60)+"""+ helper = None+ observed = None+ children = []++ async def until(predicate):+ async with asyncio.timeout(3):+ while not predicate():+ await asyncio.sleep(.005)++ class Host(module._SystemProcessHost):+ async def spawn(self, *args, **kwargs):+ if children:+ assert module._reference_state(helper, helper.pid) is False+ child = await spawn(root, leader_code if not children else "import time; time.sleep(60)")+ children.append(child)+ owner._socket_path.parent.mkdir(parents=True, exist_ok=True)+ owner._socket_path.touch()+ return child++ def inspect_identity(self, pid):+ identity = super().inspect_identity(pid)+ if len(children) == 1:+ assert list(owner._owned_processes) == [pid]+ (root / "spawn-helper").touch()+ return identity++ class Port:+ def __init__(self, *args, **kwargs):+ self.polls = 0++ async def health(self):+ nonlocal helper, observed+ if len(children) > 1:+ return True+ self.polls += 1+ if self.polls == 1:+ await until(lambda: (root / "helper").exists())+ helper = psutil.Process(int((root / "helper").read_text()))+ return False # Leave the helper visible for the next discovery poll.+ if self.polls == 2:+ observed = owner._owned_processes.get(helper.pid)+ original_parent = helper.ppid()+ (root / "detach").touch()+ await until(lambda: (root / "detached").exists() and helper.ppid() != original_parent)+ assert os.getpgid(helper.pid) == helper.pid+ assert helper.pid not in {+ child.pid for child in psutil.Process(children[0].pid).children(recursive=True)+ }+ return not timeout++ owner = module.EverOSProcess(+ sys.executable, effective_home=root, settings=settings(), _host=Host(),+ provider_root_guard=lambda: None, startup_timeout_seconds=2, stop_timeout_seconds=.3,+ )+ monkeypatch.setattr(module, "EverOSPort", Port)+ monkeypatch.setattr(owner, "_secure_socket", lambda: None)+ try:+ assert await owner.start() is (not timeout)+ if not timeout:+ await owner.stop()+ assert helper is not None+ assert module._reference_state(helper, helper.pid) is False+ assert observed is not None+ assert module._reference_state(observed, helper.pid) is False+ assert not owner.retains_active_config+ assert await owner.start() # Spawn checks old helper is gone before replacement.+ finally:+ if helper is not None and module._reference_state(helper, helper.pid) is True:+ helper.kill()+ await owner.stop()+ for child in children:+ await dispose(child)diff --git a/tests/test_memory_supervisor.py b/tests/test_memory_supervisor.pyindex 9b4f2980c..37f4d3fb1 100644--- a/tests/test_memory_supervisor.py+++ b/tests/test_memory_supervisor.py@@ -426,6 +426,9 @@ async def test_retained_child_exhausts_recovery_without_dual_ownership(assert supervisor.status.state == "degraded"retained.stop_failure = None+ assert await supervisor.wake(Path(sys.executable), _settings()) is True+ assert supervisor.status.state == "running"+ assert len(factory.supervised) == 2await supervisor.close()diff --git a/tests/test_memory_wake.py b/tests/test_memory_wake.pyindex 9bb0967d0..95e98ba06 100644--- a/tests/test_memory_wake.py+++ b/tests/test_memory_wake.py@@ -1,11 +1,7 @@from __future__ import annotationsimport asyncio-import importlib.metadata-import importlib.util-import osimport sys-import tempfileimport threadingfrom pathlib import Path@@ -17,7 +13,6 @@ from avibe_memory.artifact import (EVEROS_VERSION,FakeMemoryArtifactManager,MemoryArtifactCandidate,- MemoryArtifactManager,MemoryProviderRootState,)from avibe_memory.confined_filesystem import ConfinedFilesystemError@@ -89,47 +84,6 @@ async def test_wake_reuses_existing_root_and_proves_native_readiness(assert processes.supervised[0].running-async def test_pinned_everos_runtime_wakes_through_production_sidecar(- monkeypatch: pytest.MonkeyPatch,- memory_runtime_factory,-) -> None:- """MEMORY-WAKE-001: the pinned wheel satisfies production Wake and health."""-- required = os.environ.get("AVIBE_REQUIRE_MEMORY_RUNTIME_CONTRACT") == "1"- if importlib.util.find_spec("everos") is None:- if required:- pytest.fail("managed EverOS runtime is required for this contract")- pytest.skip("managed EverOS runtime is not installed")- assert importlib.metadata.version("everos") == EVEROS_VERSION-- runtime_python = Path.cwd() / "scripts" / "memory_runtime" / ".venv" / "bin" / "python"- if not runtime_python.is_file():- if required:- pytest.fail("provisioned Memory runtime interpreter is missing")- pytest.skip("provisioned Memory runtime interpreter is missing")- monkeypatch.setenv("AVIBE_MEMORY_DEV_RUNTIME", str(runtime_python))- with tempfile.TemporaryDirectory(prefix="avw-", dir="/tmp") as temporary:- effective_home = Path(temporary).resolve()- artifact = MemoryArtifactManager(- runtime_dir=effective_home / "runtime",- offline=True,- provider_root=effective_home / "memory" / "everos-root",- )- runtime = memory_runtime_factory(- _config(),- artifact_manager=artifact,- effective_home=effective_home,- )- try:- result = await asyncio.wait_for(runtime.wake(), timeout=60)-- assert result == {"ok": True, "state": "running"}- assert runtime.runtime_state() == "running"- finally:- await memory_runtime_factory.close(runtime)--@pytest.mark.asyncioasync def test_wake_never_routes_needs_repair_into_deletion(tmp_path: Path,diff --git a/uv.lock b/uv.lockindex d222c5f58..17d0b080a 100644--- a/uv.lock+++ b/uv.lock@@ -299,10 +299,14 @@ name = "avibe-memory"source = { directory = "packaging/avibe-memory" }dependencies = [{ name = "avibe-os" },+ { name = "psutil" },][package.metadata]-requires-dist = [{ name = "avibe-os", specifier = ">=3.0.14.dev0,<3.1" }]+requires-dist = [+ { name = "avibe-os", specifier = ">=3.0.14.dev0,<3.1" },+ { name = "psutil", specifier = ">=7.1.0" },+][[package]]name = "avibe-os"@@ -373,7 +377,7 @@ requires-dist = [{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },{ name = "packaging", specifier = ">=23.0" },{ name = "prometheus-client", specifier = ">=0.20.0" },- { name = "psutil", specifier = ">=5.9.0" },+ { name = "psutil", specifier = ">=7.1.0" },{ name = "pycryptodome", specifier = ">=3.20" },{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },{ name = "python-multipart", specifier = ">=0.0.9" },