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(runtime): name owner records' processes by clock-stable start token (#2760)
Call Whitebf83c2069f8c
diff --git a/core/services/running_agents.py b/core/services/running_agents.pyindex d8f7fb18d..8a23e7e60 100644--- a/core/services/running_agents.py+++ b/core/services/running_agents.py@@ -322,7 +322,7 @@ def _collect_orphans(seen_native: dict[str, Optional[int]], seen_pids: set[int])AVIBE_CLAUDE_SESSION_OWNER,_load_owned_process_registry,_process_ages,- _process_start_time,+ recorded_process_mismatch,)except Exception: # noqa: BLE001return rows@@ -334,10 +334,9 @@ def _collect_orphans(seen_native: dict[str, Optional[int]], seen_pids: set[int])# Filter to session-owned registry rows not already backed by a live client.# The registry accumulates stale rows (the reaper prunes lazily), so an entry- # alone proves nothing — we must verify the process is genuinely alive. A- # missing/non-numeric ``started_at`` means we cannot prove identity, so we- # skip it rather than risk a false orphan from pid reuse.- candidates: list[tuple[Any, int, Optional[str], float]] = []+ # alone proves nothing — we must verify the process is genuinely alive and is+ # the one recorded, with the same verdict "end orphan" applies before it kills.+ candidates: list[tuple[Any, int, Optional[str]]] = []for record in registry:if getattr(record, "owner", None) != AVIBE_CLAUDE_SESSION_OWNER:continue@@ -354,27 +353,15 @@ def _collect_orphans(seen_native: dict[str, Optional[int]], seen_pids: set[int])continueif not isinstance(record_pid, int) or record_pid in seen_pids:continue- recorded = getattr(record, "started_at", None)- if not isinstance(recorded, (int, float)):- continue # identity unprovable — don't risk a false orphan- candidates.append((record, record_pid, native, float(recorded)))+ candidates.append((record, record_pid, native))if not candidates:return rows- # ONE batched ``ps`` to drop dead/stale pids (the common case: e.g. 88 stale- # dead entries collapse to zero here with a single subprocess call). Only the- # few survivors get the precise per-pid start-time identity check below, so- # we never fan out N blocking ``ps`` calls on the controller loop.- ages = _process_ages({pid for _, pid, _, _ in candidates})- for record, record_pid, native, recorded in candidates:- if record_pid not in ages:- continue # not alive — stale registry entry, not a leak- current_started_at = _process_start_time(record_pid)- if current_started_at is None:- continue- if abs(current_started_at - recorded) >= 1.0:- continue # pid was reused by a different process+ for record, record_pid, native in candidates:+ if recorded_process_mismatch(record) is not None:+ continue # gone, reused, or not provably the recorded process+ ages = _process_ages({record_pid})rows.append(_make_row(backend="claude",@@ -517,10 +504,10 @@ async def _end_orphan_pid(pid: int) -> dict[str, Any]:_build_children_map,_descendant_pids,_load_owned_process_registry,- _parse_ps_rows,- _process_start_time,+ _parse_process_table,+ _process_table,_reap_pid_set,- _run_ps,+ recorded_process_mismatch,)except Exception: # noqa: BLE001return {"ok": False, "error": "reaper_unavailable"}@@ -532,18 +519,11 @@ async def _end_orphan_pid(pid: int) -> dict[str, Any]:breakif record is None:return {"ok": False, "error": "not_an_owned_process", "pid": pid}- current = _process_start_time(pid)- if current is None:- return {"ok": False, "error": "process_not_alive", "pid": pid}- recorded = getattr(record, "started_at", None)- # FAIL CLOSED: refuse to kill unless identity is provable. A record with a- # missing/non-numeric ``started_at`` (e.g. the registration-time ``ps`` failed)- # cannot be distinguished from a reused pid, so we never SIGKILL it — matching- # the read path's conservatism (``_collect_orphans`` skips such records too).- if not isinstance(recorded, (int, float)):- return {"ok": False, "error": "identity_unprovable", "pid": pid}- if abs(current - recorded) >= 1.0:- return {"ok": False, "error": "pid_reused", "pid": pid}+ # FAIL CLOSED: refuse to kill unless the record provably names this live+ # process, by the verdict Running's orphan list applies, and say why not.+ mismatch = recorded_process_mismatch(record)+ if mismatch is not None:+ return {"ok": False, "error": mismatch, "pid": pid}# NOTE: a microscopic TOCTOU remains between this check and the signal (the pid# could exit + be reused in the gap); it's inherent to pid-based signaling and# negligible vs. the registration→kill window the start-time match already covers.@@ -554,12 +534,12 @@ async def _end_orphan_pid(pid: int) -> dict[str, Any]:# children leak with no registry root a later kill could target. Apply the# SAME safety subtractions as the sweep so we never signal the avibe service# (or its tree) or a process owned by a DIFFERENT registered session. The- # blocking ``ps`` read is offloaded so we don't stall the controller loop. If- # it fails, fall back to the verified root pid alone (better than nothing).+ # blocking process-table read is offloaded so we don't stall the controller+ # loop. If it fails, fall back to the verified root pid alone.target_pids = {pid}try:loop = asyncio.get_running_loop()- rows = _parse_ps_rows(await loop.run_in_executor(None, _run_ps))+ rows = _parse_process_table(await loop.run_in_executor(None, _process_table))children = _build_children_map(rows)target_pids |= _descendant_pids(rows, pid, children)# Never reap the avibe service itself or anything under it.diff --git a/modules/agents/claude_process_reaper.py b/modules/agents/claude_process_reaper.pyindex c60098bca..7d14a9fd7 100644--- a/modules/agents/claude_process_reaper.py+++ b/modules/agents/claude_process_reaper.py@@ -7,11 +7,13 @@ import jsonimport loggingimport osimport signal-import subprocessfrom concurrent.futures import Future, ThreadPoolExecutorfrom dataclasses import dataclass, replace+from datetime import datetimefrom pathlib import Path+import psutil+KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)NODE_EXECUTABLES = {"node", "nodejs", "node.exe"}AVIBE_CLAUDE_PROCESS_OWNER_ENV = "AVIBE_CLAUDE_PROCESS_OWNER"@@ -19,8 +21,8 @@ AVIBE_CLAUDE_SESSION_OWNER = "session"AVIBE_CLAUDE_AUTH_OWNER = "auth"CLAUDE_PROCESS_REGISTRY_NAME = "claude_processes.json"# This process's registry writer. Registering is called on the service's-# event loop, so reading the process's start time (`ps`) and rewriting the file-# run here instead, one write at a time; the registry's file lock orders them+# event loop, so reading the process's start token and rewriting the file run+# here instead, one write at a time; the registry's file lock orders them# against the other processes that register (the Web UI's auth and probes)._REGISTRY_WRITER = ThreadPoolExecutor(max_workers=1, thread_name_prefix="claude-process-registry")@@ -37,6 +39,11 @@ class ClaudeOwnedProcess:pid: intnative_session_id: str | None = Noneowner: str = AVIBE_CLAUDE_SESSION_OWNER+ # vibe.runtime.process_start_token at registration: the process's identity,+ # which no clock adjustment moves. None when it could not be read then.+ start_token: str | None = None+ # A record a released build wrote has no token. It carries instead the start+ # `ps -o lstart` showed, parsed as that build parsed it, and is judged so.started_at: float | None = None@@ -103,49 +110,55 @@ def get_claude_client_stderr_tail(client: object | None) -> str:return "\n".join(str(line).strip() for line in lines if str(line).strip())-def _process_start_time(pid: int) -> float | None:- try:- result = subprocess.run(- ["ps", "-o", "lstart=", "-p", str(pid)],- check=False,- capture_output=True,- text=True,- timeout=1.5,- )- except Exception:- return None- text = (result.stdout or "").strip()- if not text:- return None- try:- from email.utils import parsedate_to_datetime+def _released_lstart_reading(started: float) -> float:+ """The value a released build recorded for a process that started at ``started``.- return parsedate_to_datetime(text).timestamp()- except Exception:- return None+ It parsed ``ps -o lstart``: local time to the second, with no zone. A naive+ datetime reads as the first occurrence of a repeated hour, so a process that+ started in the second occurrence of a DST fold was recorded an hour early.+ The same reading of the process's start now reproduces that.+ """+ return datetime.fromtimestamp(int(started)).replace(fold=0).timestamp()-def _process_start_times(pids: set[int]) -> dict[int, float]:- starts: dict[int, float] = {}- for pid in pids:- started_at = _process_start_time(pid)- if started_at is not None:- starts[pid] = started_at- return starts+def recorded_process_mismatch(record: ClaudeOwnedProcess) -> str | None:+ """Why ``record`` does not name a live process it can be shown to be; None when it does.-def _process_identity_matches(- record: ClaudeOwnedProcess,- row: ClaudeProcessRow,- current_started_at: float | None,-) -> bool:- if record.pid != row.pid:- return False- if record.started_at is None:- return True- if current_started_at is None:- return False- return abs(current_started_at - record.started_at) < 1.0+ One verdict for every reader -- Running's orphans, "end orphan" and the+ reaper -- so a process is never listed by one and refused by another. A+ record names its process by start token. One a released build wrote is+ judged as that build judged it: its ``started_at`` within a second of the+ start ``ps -o lstart`` would show now, read without ``ps``. The reasons:++ - ``identity_unprovable``: the record has no identity, so it can never be+ told apart from a reused pid;+ - ``process_not_alive``: nothing runs at its pid;+ - ``identity_unverifiable``: a process runs there, but its start cannot be+ read now;+ - ``pid_reused``: the process there started at another time.+ """++ from vibe import runtime++ pid = record.pid+ start_token = getattr(record, "start_token", None)+ started_at = getattr(record, "started_at", None)+ if start_token is None and not isinstance(started_at, (int, float)):+ return "identity_unprovable"+ if not runtime.pid_alive(pid):+ return "process_not_alive"+ if start_token is not None:+ current = runtime.process_start_token(pid)+ if current is None:+ return "identity_unverifiable" if runtime.pid_alive(pid) else "process_not_alive"+ return None if current == start_token else "pid_reused"+ started = runtime.process_start_seconds(pid)+ if started is None:+ return "identity_unverifiable" if runtime.pid_alive(pid) else "process_not_alive"+ if abs(_released_lstart_reading(started) - started_at) < 1.0:+ return None+ return "pid_reused"def _registry_path(runtime_dir: Path | None = None) -> Path:@@ -174,13 +187,19 @@ def _load_owned_process_registry(runtime_dir: Path | None = None) -> list[Claudecontinuenative_session_id = item.get("native_session_id")owner = item.get("owner") or AVIBE_CLAUDE_SESSION_OWNER+ start_token = item.get("start_token")started_at = item.get("started_at")records.append(ClaudeOwnedProcess(pid=pid,native_session_id=str(native_session_id) if native_session_id else None,owner=str(owner),- started_at=float(started_at) if isinstance(started_at, (int, float)) else None,+ start_token=start_token if isinstance(start_token, str) and start_token else None,+ started_at=(+ float(started_at)+ if isinstance(started_at, (int, float)) and not isinstance(started_at, bool)+ else None+ ),))return records@@ -216,9 +235,10 @@ def _record_owned_process(runtime_dir: Path, owned: ClaudeOwnedProcess) -> None:"""Rewrite the registry with ``owned``, without the records of processes that have exited."""from storage.lock import MigrationFileLock+ from vibe import runtimepath = _registry_path(runtime_dir)- started_at = _process_start_time(owned.pid)+ start_token = runtime.process_start_token(owned.pid)try:path.parent.mkdir(parents=True, exist_ok=True)with MigrationFileLock(path.with_suffix(path.suffix + ".lock")):@@ -227,13 +247,15 @@ def _record_owned_process(runtime_dir: Path, owned: ClaudeOwnedProcess) -> None:for existing in _load_owned_process_registry(runtime_dir)if existing.pid != owned.pid and _pid_exists(existing.pid)]- records.append(replace(owned, started_at=started_at))+ records.append(replace(owned, start_token=start_token, started_at=None))payload = {"processes": [{"pid": record.pid,"native_session_id": record.native_session_id,"owner": record.owner,+ # A released record keeps the identity its build wrote.+ **({"start_token": record.start_token} if record.start_token is not None else {}),"started_at": record.started_at,}for record in records@@ -259,18 +281,24 @@ def _pid_exists(pid: int) -> bool:return True-def _run_ps() -> str:- result = subprocess.run(- ["ps", "-axo", "pid=,ppid=,command="],- check=False,- capture_output=True,- text=True,- timeout=1.5,- )- return result.stdout or ""+def _process_table() -> str:+ """Every process as ``pid ppid command`` lines, read through psutil rather than ``ps``.++ ``ps`` cannot run in every sandbox the service runs in (#2487). A process+ whose command line cannot be read is listed by its name, so the tree it+ belongs to stays whole.+ """+ lines: list[str] = []+ for process in psutil.process_iter(["pid", "ppid", "cmdline", "name"]):+ info = process.info+ command = " ".join(info.get("cmdline") or []) or (info.get("name") or "")+ if command:+ lines.append(f"{info['pid']} {info.get('ppid') or 0} {command}")+ return "\n".join(lines)-def _parse_ps_rows(output: str) -> list[ClaudeProcessRow]:++def _parse_process_table(output: str) -> list[ClaudeProcessRow]:rows: list[ClaudeProcessRow] = []for line in output.splitlines():parts = line.strip().split(None, 2)@@ -333,7 +361,7 @@ def find_claude_resume_processes(native_session_id: str, *, cli_path: str | Noneif os.name == "nt" or not native_session_id:return []try:- rows = _parse_ps_rows(_run_ps())+ rows = _parse_process_table(_process_table())except Exception:return []return [@@ -431,7 +459,7 @@ async def reap_duplicate_claude_resume_processes(return 0try:- all_rows = _parse_ps_rows(_run_ps())+ all_rows = _parse_process_table(_process_table())except Exception:logger.debug("Failed to read process table for Claude duplicate cleanup", exc_info=True)return 0@@ -507,7 +535,7 @@ async def stop_claude_process(if pid is None or _process_returncode(process) is not None:return Truetry:- rows = _parse_ps_rows(await asyncio.to_thread(_run_ps))+ rows = _parse_process_table(await asyncio.to_thread(_process_table))except Exception:# No process table, as on Windows: the CLI alone.rows = []@@ -556,35 +584,19 @@ async def _reap_pid_set(def _process_ages(pids: set[int]) -> dict[int, float]:- """Best-effort elapsed-seconds-since-start for the given pids via ``ps``.+ """How long each of ``pids`` has run, read without ``ps``.- Returns a ``{pid: age_seconds}`` map. Pids whose age cannot be determined- are simply absent (callers treat unknown age conservatively: do not reap).- ``etimes`` (elapsed seconds) is available on Linux procps-ng and macOS; on- busybox ``ps`` (Alpine) it is unsupported, so this returns ``{}`` and the- caller reaps nothing — the safe conservative fallback.+ Pids whose age cannot be read are absent: callers treat an unknown age+ conservatively and do not reap."""- if not pids:- return {}- try:- result = subprocess.run(- ["ps", "-o", "pid=,etimes=", "-p", ",".join(str(p) for p in sorted(pids))],- check=False,- capture_output=True,- text=True,- timeout=1.5,- )- except Exception:- return {}++ from vibe import runtime+ages: dict[int, float] = {}- for line in (result.stdout or "").splitlines():- parts = line.split()- if len(parts) < 2:- continue- try:- ages[int(parts[0])] = float(parts[1])- except ValueError:- continue+ for pid in pids:+ age = runtime.process_age_seconds(pid)+ if age is not None:+ ages[pid] = agereturn ages@@ -620,7 +632,7 @@ async def reap_orphaned_claude_processes(candidate whose age cannot be determined is **not** reaped.Returns the number of pids that were signalled, which includes descendant- helper processes — not the number of orphan roots. The blocking ``ps``+ helper processes — not the number of orphan roots. The blocking processreads are offloaded to a thread so this never stalls the event loop (thisruns on every periodic cleanup sweep)."""@@ -629,7 +641,7 @@ async def reap_orphaned_claude_processes(loop = asyncio.get_running_loop()try:- all_rows = _parse_ps_rows(await loop.run_in_executor(None, _run_ps))+ all_rows = _parse_process_table(await loop.run_in_executor(None, _process_table))except Exception:logger.debug("Failed to read process table for Claude orphan cleanup", exc_info=True)return 0@@ -662,21 +674,18 @@ async def reap_orphaned_claude_processes(if owned_processes is not Noneelse await loop.run_in_executor(None, _load_owned_process_registry))- registry_pids = {- record.pid- for record in registry- if record.started_at is not None and record.pid in row_by_pid- }- current_start_times = await loop.run_in_executor(None, _process_start_times, registry_pids)++ def live_records() -> list[ClaudeOwnedProcess]:+ return [+ record+ for record in registry+ if record.pid in row_by_pid and recorded_process_mismatch(record) is None+ ]candidates: set[int] = set()- for record in registry:- row = row_by_pid.get(record.pid)- if row is None or not _process_identity_matches(record, row, current_start_times.get(record.pid)):- continue- if record.started_at is None:- continue+ for record in await loop.run_in_executor(None, live_records):+ row = row_by_pid[record.pid]in_service_tree = row.pid in service_treeif record.owner != AVIBE_CLAUDE_SESSION_OWNER:continue@@ -698,7 +707,7 @@ async def reap_orphaned_claude_processes(return 0# TOCTOU grace window: never reap a process younger than the cutoff, and- # never reap one whose age we cannot establish. Offload the ``ps`` read.+ # never reap one whose age we cannot establish. Offload the reads.ages = await loop.run_in_executor(None, _process_ages, candidates)aged_candidates = {pid for pid in candidates if ages.get(pid, 0.0) >= min_age_seconds}if not aged_candidates:diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex a4307cd50..7dd56c45f 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -73,7 +73,7 @@ _UNRECORDED_RUNTIME_ID = object()# runs; it stops them once their work drains. A started process is owned from# its spawn, before its record is written, until a stop proves it gone or its# start proves it exited, so this controller's shutdown stops it, recorded or not.-_OWNED_HERE: dict[str, tuple[int, Optional[float]]] = {}+_OWNED_HERE: dict[str, "_ProcessIdentity"] = {}# The process handle of each owned generation this process spawned. Until the# handle reaps it, its pid cannot name another process, so the handle, never# the start time the platform reports (which moves with every clock step),@@ -1545,6 +1545,8 @@ class OpenCodeGeneration(OpenCodeServerClient):port: int,spec_digest: str,process_created_at: float | None,+ process_start_token: str | None = None,+ released_identity: bool = False,host: str = DEFAULT_OPENCODE_HOST,binary: str = "",binary_version: Optional[str] = None,@@ -1568,7 +1570,13 @@ class OpenCodeGeneration(OpenCodeServerClient):self.port = portself.host = hostself.spec_digest = spec_digest+ # The process's identity, judged as ``_ProcessIdentity`` describes: the+ # start token, which no clock adjustment moves; the wall-clock create+ # time, the proof of a record whose token could not be read; or, for a+ # record a released build wrote, the proof that build applied.+ self.process_start_token = process_start_tokenself.process_created_at = process_created_at+ self.released_identity = released_identityself.binary = binaryself.binary_version = binary_versionself.caller_context_path = caller_context_path@@ -1610,7 +1618,7 @@ class OpenCodeGeneration(OpenCodeServerClient):"schema": GENERATION_RECORD_SCHEMA,"generation_id": self.generation_id,"pid": self.pid,- "process_created_at": self.process_created_at,+ **self.process_identity().record_fields(),"host": self.host,"port": self.port,"started_at": self.started_at,@@ -1702,16 +1710,24 @@ class OpenCodeGeneration(OpenCodeServerClient):def has_requests_in_flight(self) -> bool:return self._active_requests > 0+ def process_identity(self) -> "_ProcessIdentity":+ return _ProcessIdentity(+ pid=self.pid,+ port=self.port,+ start_token=self.process_start_token,+ created_at=self.process_created_at,+ released=self.released_identity,+ )+def process_alive(self) -> bool:process = self._processif process is not None:# This controller's own child: its handle is the authority, and# its pid cannot be reused before the handle reaps it.return process.returncode is None- created_at = runtime.process_create_time(self.pid)- if self.process_created_at is None:- return created_at is not None or _pid_exists(self.pid)- return created_at == self.process_created_at+ # A process that cannot be proven to be this one counts as gone: it is+ # never signalled, and nothing waits for it to exit.+ return self.process_identity().names_live_process() is Truedef observed_exit_pid(self) -> int | None:"""This process's pid once it has exited, never a pid reused since."""@@ -1841,8 +1857,15 @@ async def start_generation(f"OpenCode CLI not found at '{spec.binary}'. Please install OpenCode or set OPENCODE_CLI_PATH.") from exc# Owned before anything else can fail, the record write included.+ start_token = runtime.process_start_token(process.pid)created_at = runtime.process_create_time(process.pid)- _OWNED_HERE[generation_id] = (process.pid, created_at)+ _OWNED_HERE[generation_id] = _ProcessIdentity(+ pid=process.pid,+ port=port,+ start_token=start_token,+ created_at=created_at,+ released=False,+ )_CHILDREN_HERE[generation_id] = processgeneration = OpenCodeGeneration(generation_id=generation_id,@@ -1850,6 +1873,7 @@ async def start_generation(port=port,spec_digest=spec.digest,process_created_at=created_at,+ process_start_token=start_token,binary=spec.binary,binary_version=spec.binary_version,caller_context_path=caller_context_path,@@ -2004,6 +2028,75 @@ def _record_runtime_id(info: Mapping[str, Any]) -> Any:return value if value is None or isinstance(value, str) else _UNRECORDED_RUNTIME_ID+@dataclass(frozen=True)+class _ProcessIdentity:+ """How a record names the process it started, and the proof that applies to it.++ A record this build writes names its process by start token+ (``vibe.runtime.process_start_token``), which no clock adjustment moves; it+ keeps the wall-clock ``process_created_at`` beside it, which a record whose+ token could not be read is judged by instead. A record a released build+ wrote has no token field and keeps the proof that build applied: its exact+ create time, or, when it recorded none, the command line and port of the+ process at its pid. A record of this build with neither proves nothing.+ """++ pid: int+ port: Optional[int]+ start_token: Optional[str]+ created_at: Optional[float]+ released: bool++ @classmethod+ def from_record(cls, info: Mapping[str, Any], pid: int) -> "_ProcessIdentity":+ token = info.get("process_start_token")+ return cls(+ pid=pid,+ port=_record_port(info),+ start_token=token if isinstance(token, str) and token else None,+ created_at=_record_number(info.get("process_created_at")),+ released="process_start_token" not in info,+ )++ def record_fields(self) -> Dict[str, Any]:+ """The fields that carry this identity in a record; a released one is kept as it was."""++ fields: Dict[str, Any] = {"process_created_at": self.created_at}+ if not self.released:+ fields["process_start_token"] = self.start_token+ return fields++ def names_live_process(self) -> Optional[bool]:+ """True while the pid still runs the recorded process; False once it does not; None when unprovable.++ Unprovable means the record carries no identity this build may act on,+ or the one it carries cannot be read now. Every caller treats it as+ not proven: such a process is never signalled, and never waited for.+ """++ if not _pid_exists(self.pid):+ return False+ if self.start_token is not None:+ current = runtime.process_start_token(self.pid)+ if current is None:+ return None if _pid_exists(self.pid) else False+ return current == self.start_token+ if self.created_at is not None:+ current_created = runtime.process_create_time(self.pid)+ if current_created is None:+ return None if _pid_exists(self.pid) else False+ return current_created == self.created_at+ if not self.released:+ return None+ # A released record that recorded no identity: the proof its build applied.+ command = _get_pid_command(self.pid)+ if command:+ if self.port is not None:+ return _is_opencode_serve_cmd(command, self.port)+ return "opencode" in command and "serve" in command+ return self.port is not None and _pid_listens_on(self.pid, self.port)++def _record_proves_process(info: Mapping[str, Any], *, require_port: bool = True) -> bool:"""Whether a record still names the exact ``opencode serve`` it started.@@ -2018,11 +2111,9 @@ def _record_proves_process(info: Mapping[str, Any], *, require_port: bool = Truehas_port = port is not Noneif require_port and not has_port:return False- created_at = _record_number(info.get("process_created_at"))- if created_at is not None:- # A command line alone can belong to a reused pid.- if runtime.process_create_time(pid) != created_at:- return False+ # A command line alone can belong to a reused pid.+ if _ProcessIdentity.from_record(info, pid).names_live_process() is not True:+ return Falsecommand = _get_pid_command(pid)if command:if has_port:@@ -2046,9 +2137,8 @@ def _generation_from_record() -> OpenCodeGeneration:binary = info.get("binary") if isinstance(info.get("binary"), dict) else {}pid = int(info["pid"])- created_at = _record_number(info.get("process_created_at"))- if created_at is None:- created_at = runtime.process_create_time(pid)+ # The identity stays as recorded: a released record keeps its build's proof.+ identity = _ProcessIdentity.from_record(info, pid)started_at = _record_number(info.get("started_at"))leases = info.get("leases") if isinstance(info.get("leases"), dict) else {}caller_context_path = info.get("caller_context_path")@@ -2061,7 +2151,9 @@ def _generation_from_record(port=int(info["port"]),host=host if isinstance(host, str) and host else DEFAULT_OPENCODE_HOST,spec_digest=spec_digest,- process_created_at=created_at,+ process_created_at=identity.created_at,+ process_start_token=identity.start_token,+ released_identity=identity.released,binary=binary_path if isinstance(binary_path, str) else "",binary_version=binary.get("version") if isinstance(binary.get("version"), str) else None,caller_context_path=caller_context_path if isinstance(caller_context_path, str) else None,@@ -2075,7 +2167,13 @@ def _generation_from_record(},# The process's age: a record without a start time, such as the# legacy one, started when its process did, never at its adoption.- started_at=started_at if started_at is not None else created_at,+ started_at=(+ started_at+ if started_at is not None+ else identity.created_at+ if identity.created_at is not None+ else runtime.process_create_time(pid)+ ),# Rewritten without a malformed id, so every later read judges it alike.desktop_runtime_id=_record_runtime_id(info),request_timeout_seconds=request_timeout_seconds,@@ -2186,7 +2284,7 @@ async def adopt_recorded_generations(*, request_timeout_seconds: int = 60) -> li"""adopted: list[OpenCodeGeneration] = []- adopted_processes: set[tuple[int, Optional[float]]] = set()+ adopted_processes: list[_ProcessIdentity] = []legacy_path = legacy_pid_file()for path, info in _recorded_processes():is_legacy = path == legacy_path@@ -2199,7 +2297,7 @@ async def adopt_recorded_generations(*, request_timeout_seconds: int = 60) -> liif not is_legacy and isinstance(info.get("generation_id"), str):_remove_quietly(generation_records_dir() / f"{info['generation_id']}.overlay.json")continue- if is_legacy and (int(info["pid"]), runtime.process_create_time(int(info["pid"]))) in adopted_processes:+ if is_legacy and _names_one_of(int(info["pid"]), adopted_processes):# This pass adopted it from its converted record; a crash or a# failed removal after the conversion left this file behind._remove_quietly(path)@@ -2230,7 +2328,7 @@ async def adopt_recorded_generations(*, request_timeout_seconds: int = 60) -> ligeneration.write_record_or_defer("the record of an adopted pre-generations server")logger.info("Adopted OpenCode generation %s pid=%s", generation.generation_id, generation.pid)adopted.append(generation)- adopted_processes.add((generation.pid, generation.process_created_at))+ adopted_processes.append(generation.process_identity())# No sweep of overlays without a record: another desktop Runtime writes# its overlay before it spawns and records the process.return adopted@@ -2248,12 +2346,18 @@ def _owned_here(info: Mapping[str, Any], *, by_id: bool = True) -> bool:pid = _record_pid(info)if pid is None:return False- return (pid, runtime.process_create_time(pid)) in _OWNED_HERE.values()+ return _names_one_of(pid, _OWNED_HERE.values())+++def _names_one_of(pid: int, identities: Iterable[_ProcessIdentity]) -> bool:+ """Whether ``pid`` still runs the process one of ``identities`` names, by that identity's proof."""++ return any(identity.pid == pid and identity.names_live_process() is True for identity in identities)def own_generation(generation: OpenCodeGeneration) -> None:"""Mark an adopted generation as attached to a runtime of this process."""- _OWNED_HERE[generation.generation_id] = (generation.pid, generation.process_created_at)+ _OWNED_HERE[generation.generation_id] = generation.process_identity()def forget_record(path: Path) -> None:@@ -2349,32 +2453,32 @@ def stop_owned_generations_sync() -> None:logger.warning("OpenCode generation %s survived its stop", generation_id)if isinstance(generation_id, str):recorded.add(generation_id)- for generation_id, (pid, created_at) in list(_OWNED_HERE.items()):+ for generation_id, identity in list(_OWNED_HERE.items()):if generation_id not in recorded:- _stop_unrecorded_process_sync(generation_id, pid, created_at)+ _stop_unrecorded_process_sync(generation_id, identity)-def _stop_unrecorded_process_sync(generation_id: str, pid: int, created_at: Optional[float]) -> None:+def _stop_unrecorded_process_sync(generation_id: str, identity: _ProcessIdentity) -> None:"""Stop an owned process no record names.This controller's own child is judged by its handle. Any other is proven by- its pid and create time: one whose create time is unknown or cannot be- read now is never signalled, since its pid may have been reused, and one- whose pid is gone, or now names another process, has ended and is no- longer owned here.+ its identity: one that cannot be proven now is never signalled, since its+ pid may have been reused, and one whose pid is gone, or now names another+ process, has ended and is no longer owned here."""+ pid = identity.pidrunning = _child_running(generation_id)if running is not None:if running and not terminate_pid_tree_sync(pid):logger.warning("OpenCode generation %s pid=%s survived its stop", generation_id, pid)returnelif _pid_exists(pid):- current = runtime.process_create_time(pid)- if created_at is None or current is None:+ names_it = identity.names_live_process()+ if names_it is None:logger.warning("Leaving OpenCode generation %s pid=%s: its process cannot be proven", generation_id, pid)return- if current == created_at and not terminate_pid_tree_sync(pid):+ if names_it and not terminate_pid_tree_sync(pid):logger.warning("OpenCode generation %s pid=%s survived its stop", generation_id, pid)return_disown(generation_id)diff --git a/tests/test_agent_backend_alive.py b/tests/test_agent_backend_alive.pyindex 280ff3973..214431031 100644--- a/tests/test_agent_backend_alive.py+++ b/tests/test_agent_backend_alive.py@@ -232,6 +232,9 @@ class OpenCodeResourceExitTests(unittest.TestCase):pressure = AgentResourceFailure(kind="pids", message="shared cgroup limit event")with patch(+ "modules.agents.opencode.server.runtime.pid_alive",+ return_value=True,+ ), patch("modules.agents.opencode.server.runtime.process_create_time",# Alive, then the pid belongs to a later process.side_effect=[1000.0, 2000.0],diff --git a/tests/test_claude_process_reaper.py b/tests/test_claude_process_reaper.pyindex ca7c49d42..1b29c588c 100644--- a/tests/test_claude_process_reaper.py+++ b/tests/test_claude_process_reaper.py@@ -1,4 +1,5 @@import asyncio+import jsonimport loggingimport osimport signal@@ -10,6 +11,8 @@ from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom types import SimpleNamespace+import pytest+from modules.agents import claude_process_reaper@@ -47,7 +50,7 @@ def test_find_claude_resume_processes_matches_exact_resume_id(monkeypatch):"105 1 /usr/local/bin/node /usr/local/bin/claude --resume sess-1",])- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)rows = claude_process_reaper.find_claude_resume_processes("sess-1")@@ -62,7 +65,7 @@ def test_find_claude_resume_processes_matches_configured_wrapper(monkeypatch):"102 1 /usr/local/bin/node /usr/local/bin/claude-proxy --resume=sess-1",])- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)rows = claude_process_reaper.find_claude_resume_processes("sess-1",@@ -94,7 +97,7 @@ def test_reap_duplicate_claude_resume_processes_kills_matches_and_descendants(mosignals.append((pid, sig))alive.discard(pid)- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)monkeypatch.setattr(claude_process_reaper.os, "kill", fake_kill)reaped = asyncio.run(@@ -115,7 +118,7 @@ def test_reap_duplicate_claude_resume_processes_keeps_single_tracked_pid(monkeypservice_pid = os.getpid()monkeypatch.setattr(claude_process_reaper,- "_run_ps",+ "_process_table",lambda: "\n".join([f"{service_pid} 1 python service_main.py",@@ -158,7 +161,7 @@ def test_reap_duplicate_claude_resume_processes_reaps_scoped_orphan_without_keepsignals.append((pid, sig))alive.discard(pid)- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)monkeypatch.setattr(claude_process_reaper.os, "kill", fake_kill)reaped = asyncio.run(@@ -201,7 +204,7 @@ def test_reap_duplicate_claude_resume_processes_spares_owned_replacement(monkeypsignals.append((pid, sig))alive.discard(pid)- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)monkeypatch.setattr(claude_process_reaper.os, "kill", fake_kill)reaped = asyncio.run(@@ -227,7 +230,7 @@ def test_reap_duplicate_claude_resume_processes_skips_when_all_matches_owned(mon])signals = []- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)monkeypatch.setattr(claude_process_reaper.os, "kill", lambda pid, sig: signals.append((pid, sig)))reaped = asyncio.run(@@ -270,7 +273,7 @@ def test_reap_duplicate_claude_resume_processes_counts_owned_matches_in_the_guarsignals.append((pid, sig))alive.discard(pid)- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)monkeypatch.setattr(claude_process_reaper.os, "kill", fake_kill)reaped = asyncio.run(@@ -291,7 +294,7 @@ def test_reap_duplicate_claude_resume_processes_ignores_unrelated_unique_match(mservice_pid = os.getpid()monkeypatch.setattr(claude_process_reaper,- "_run_ps",+ "_process_table",lambda: "\n".join([f"{service_pid} 1 python service_main.py",@@ -322,7 +325,7 @@ def _patch_orphan_env(monkeypatch, table: str, ages: dict[int, float], alive: sereturnalive.discard(pid)- monkeypatch.setattr(claude_process_reaper, "_run_ps", lambda: table)+ monkeypatch.setattr(claude_process_reaper, "_process_table", lambda: table)monkeypatch.setattr(claude_process_reaper, "_process_ages", lambda pids: ages)signals: list[tuple[int, int]] = []real_kill = fake_kill@@ -347,7 +350,8 @@ def test_reap_orphaned_reaps_in_tree_no_owner_and_descendants(monkeypatch):])signals = _patch_orphan_env(monkeypatch, table, {101: 999.0, 102: 999.0}, {100, 101, 102})- monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: True)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: 123.0)reaped = asyncio.run(claude_process_reaper.reap_orphaned_claude_processes(@@ -450,7 +454,8 @@ def test_reap_orphaned_respects_min_age_grace_window(monkeypatch):])signals = _patch_orphan_env(monkeypatch, table, {101: 5.0}, {101})- monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: True)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: 123.0)reaped = asyncio.run(claude_process_reaper.reap_orphaned_claude_processes(@@ -474,7 +479,8 @@ def test_reap_orphaned_skips_when_age_unknown(monkeypatch):])signals = _patch_orphan_env(monkeypatch, table, {}, {101})- monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: True)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: 123.0)reaped = asyncio.run(claude_process_reaper.reap_orphaned_claude_processes(@@ -547,7 +553,8 @@ def test_reap_orphaned_skips_in_tree_sweep_when_disabled(monkeypatch):])signals = _patch_orphan_env(monkeypatch, table, {101: 999.0}, {101})- monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: True)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: 123.0)reaped = asyncio.run(claude_process_reaper.reap_orphaned_claude_processes(@@ -648,7 +655,8 @@ def test_reap_orphaned_reaps_registry_owned_out_of_tree_resume_match(monkeypatch])signals = _patch_orphan_env(monkeypatch, table, {300: 999.0}, {100, 300})- monkeypatch.setattr(claude_process_reaper, "_process_start_times", lambda pids: {pid: 123.0 for pid in pids})+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: True)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: 123.0)reaped = asyncio.run(claude_process_reaper.reap_orphaned_claude_processes(@@ -731,14 +739,14 @@ def _sleeper() -> subprocess.Popen:def test_registering_a_process_reads_and_writes_on_the_registry_thread(tmp_path, monkeypatch):- # The service registers on its event loop; the `ps` read and the file rewrite must not run there.+ # The service registers on its event loop; the start-token read and the file rewrite must not run there.threads: list[str] = []- def start_time(pid):+ def start_token(pid):threads.append(threading.current_thread().name)- return 1000.0+ return "boot:1000"- monkeypatch.setattr(claude_process_reaper, "_process_start_time", start_time)+ monkeypatch.setattr("vibe.runtime.process_start_token", start_token)child = _sleeper()try:pending = claude_process_reaper.register_claude_owned_process(@@ -751,12 +759,12 @@ def test_registering_a_process_reads_and_writes_on_the_registry_thread(tmp_path,assert threads and all(name.startswith("claude-process-registry") for name in threads)assert claude_process_reaper._load_owned_process_registry(tmp_path) == [- claude_process_reaper.ClaudeOwnedProcess(pid=child.pid, native_session_id="sess-1", started_at=1000.0)+ claude_process_reaper.ClaudeOwnedProcess(pid=child.pid, native_session_id="sess-1", start_token="boot:1000")]def test_a_registration_drops_the_records_of_processes_that_have_exited(tmp_path, monkeypatch):- monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: "boot:1000")exited = subprocess.Popen([sys.executable, "-c", "pass"])exited.wait(10)running, registering = _sleeper(), _sleeper()@@ -776,7 +784,7 @@ def test_a_registration_drops_the_records_of_processes_that_have_exited(tmp_pathdef test_concurrent_registrations_keep_every_record(tmp_path, monkeypatch):- monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: "boot:1000")children = [_sleeper() for _ in range(4)]try:with ThreadPoolExecutor(max_workers=4) as callers:@@ -814,7 +822,7 @@ with MigrationFileLock(Path(sys.argv[2]), timeout_seconds=None):def test_a_registration_waits_while_another_process_rewrites_the_registry(tmp_path, monkeypatch):# The Web UI's process registers auth and probe clients into the same file.- monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: "boot:1000")lock_path = tmp_path / f"{claude_process_reaper.CLAUDE_PROCESS_REGISTRY_NAME}.lock"holder = subprocess.Popen([sys.executable, "-c", _HOLD_REGISTRY_LOCK, str(Path(__file__).resolve().parents[1]), str(lock_path)],@@ -844,7 +852,7 @@ def test_a_registration_waits_while_another_process_rewrites_the_registry(tmp_padef test_a_recorded_pid_no_process_can_have_is_dropped(tmp_path, monkeypatch):- monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: "boot:1000")(tmp_path / claude_process_reaper.CLAUDE_PROCESS_REGISTRY_NAME).write_text('{"processes":[{"pid":%d,"native_session_id":null,"owner":"session","started_at":1.0}]}' % 2**63)@@ -863,7 +871,7 @@ def test_a_recorded_pid_no_process_can_have_is_dropped(tmp_path, monkeypatch):def test_two_writers_interleaved_by_force_keep_both_records(tmp_path, monkeypatch):# Without the registry lock, the second writer would load the file before the first replaced it,# and its rewrite would drop the first record.- monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: "boot:1000")first_loaded = threading.Event()release_first = threading.Event()real_load = claude_process_reaper._load_owned_process_registry@@ -901,3 +909,125 @@ def test_two_writers_interleaved_by_force_keep_both_records(tmp_path, monkeypatcchild.wait(10)assert recorded == {first.pid, second.pid}+++# ---------------------------------------------------------------------------+# The registry's process identity (#2511)+# ---------------------------------------------------------------------------+++def _released_record(pid: int) -> dict:+ """The registry entry a released build wrote: the ``ps -o lstart`` text of the+ process's start, parsed as that build parsed it."""++ from email.utils import parsedate_to_datetime++ import psutil++ lstart = time.strftime("%a %b %e %H:%M:%S %Y", time.localtime(int(psutil.Process(pid).create_time())))+ started_at = parsedate_to_datetime(lstart).timestamp()+ return {"pid": pid, "native_session_id": "sess-released", "owner": "session", "started_at": started_at}++[email protected](os.name == "nt", reason="the registry is POSIX-only")+def test_a_registered_process_keeps_its_identity_across_a_clock_adjustment(tmp_path):+ """A record names its process by start token. The wall-clock start psutil shows+ moves when the clock is stepped (Linux) or ``kern.boottime`` ticks (macOS); the+ token does not, so the live process stays the recorded one."""++ from tests.test_process_start_token import _clock_adjusted++ child = _sleeper()+ try:+ claude_process_reaper.register_claude_owned_process(_client(child.pid), runtime_dir=tmp_path).result(timeout=10)+ (record,) = claude_process_reaper._load_owned_process_registry(tmp_path)+ assert record.start_token is not None and record.started_at is None+ assert claude_process_reaper.recorded_process_mismatch(record) is None++ with _clock_adjusted():+ assert claude_process_reaper.recorded_process_mismatch(record) is None+ finally:+ child.kill()+ child.wait(10)++[email protected](os.name == "nt", reason="the registry is POSIX-only")+def test_a_released_record_keeps_the_proof_its_build_applied(tmp_path):+ """A record a released build wrote carries ``started_at`` from ``ps -o lstart``+ and no token. It is not migrated: it still names its live process, read now+ without ``ps``, and a registration keeps it as it was."""++ child, registering = _sleeper(), _sleeper()+ try:+ released = _released_record(child.pid)+ registry = tmp_path / claude_process_reaper.CLAUDE_PROCESS_REGISTRY_NAME+ registry.write_text(json.dumps({"processes": [released]}), encoding="utf-8")++ (record,) = claude_process_reaper._load_owned_process_registry(tmp_path)+ assert record.start_token is None and record.started_at == released["started_at"]+ assert claude_process_reaper.recorded_process_mismatch(record) is None++ claude_process_reaper.register_claude_owned_process(_client(registering.pid), runtime_dir=tmp_path).result(+ timeout=10+ )+ entries = {entry["pid"]: entry for entry in json.loads(registry.read_text(encoding="utf-8"))["processes"]}+ assert entries[child.pid] == {**released, "native_session_id": "sess-released"}+ finally:+ for process in (child, registering):+ process.kill()+ process.wait(10)+++def new_york_time(monkeypatch):+ monkeypatch.setenv("TZ", "America/New_York")+ time.tzset()+ yield+ monkeypatch.undo()+ time.tzset()++[email protected](os.name == "nt", reason="the registry is POSIX-only")[email protected]("occurrence", ["first", "second"])+def test_a_released_record_written_in_a_dst_fold_keeps_matching(monkeypatch, new_york_time, occurrence):+ """``ps -o lstart`` prints local time without a zone, and the released parser read+ a repeated hour as its first occurrence. A process started in the second one was+ recorded an hour early, and must still match its record."""++ from email.utils import parsedate_to_datetime++ # 01:30 on 2026-11-01 happens twice in New York: at 05:30 and at 06:30 UTC.+ started = {"first": 1793511000.4, "second": 1793514600.4}[occurrence]+ recorded = parsedate_to_datetime("Sun Nov 1 01:30:00 2026").timestamp()+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: True)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: started)+ record = claude_process_reaper.ClaudeOwnedProcess(pid=4321, started_at=recorded)++ assert claude_process_reaper.recorded_process_mismatch(record) is None+ later = claude_process_reaper.ClaudeOwnedProcess(pid=4321, started_at=recorded + 7200)+ assert claude_process_reaper.recorded_process_mismatch(later) == "pid_reused"+++ ("record", "alive", "token", "started", "reason"),+ [+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321), True, "boot:1", 1000.0, "identity_unprovable"),+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321, start_token="boot:1"), False, None, None, "process_not_alive"),+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321, start_token="boot:1"), True, None, None, "identity_unverifiable"),+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321, start_token="boot:1"), True, "boot:2", None, "pid_reused"),+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321, start_token="boot:1"), True, "boot:1", None, None),+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321, started_at=1000.0), True, None, None, "identity_unverifiable"),+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321, started_at=1000.0), True, None, 5000.0, "pid_reused"),+ (claude_process_reaper.ClaudeOwnedProcess(pid=4321, started_at=1000.0), True, None, 1000.4, None),+ ],+)+def test_a_record_that_cannot_be_shown_to_name_its_process_says_why(monkeypatch, record, alive, token, started, reason):+ """Running's orphan list, "end orphan" and the reaper share this verdict. A record+ with no identity -- none could be read when it was written -- is never acted on;+ nor is one whose identity cannot be read now. "End orphan" reports which."""++ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: alive)+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: token)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: started)++ assert claude_process_reaper.recorded_process_mismatch(record) == reasondiff --git a/tests/test_desktop_backends.py b/tests/test_desktop_backends.pyindex 6b4d78e92..0f4842702 100644--- a/tests/test_desktop_backends.py+++ b/tests/test_desktop_backends.py@@ -669,7 +669,51 @@ def test_a_tree_whose_owner_pid_now_names_another_process_is_reaped(@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups")[email protected]("owner", ["missing", "malformed", "uninspectable"])+ ("shape", "kept"),+ [+ ("token-of-a-live-ui", True),+ ("another-token-at-a-ui-of-this-runtime", False),+ ("released-value-of-a-live-ui", True),+ ("released-value-of-an-exited-owner", False),+ ],+)+def test_an_owner_value_is_judged_by_the_identity_its_shape_carries(+ tmp_path, installer_tree, quiet_stop, children, shape, kept+):+ """#2511: an owner value this build writes names its owner by start token, so+ another token at its pid means the pid was reused -- even by another UI of the+ same Runtime, which the released ``pid:create_time`` value could not tell from+ its owner. Only a released value keeps that "a UI of this Runtime" fallback,+ because macOS can shift the create time it carries while its owner runs."""++ from vibe import runtime++ env, wait_for_tree = installer_tree+ cli, statuses = quiet_stop+ if shape == "released-value-of-an-exited-owner":+ exited = subprocess.Popen([sys.executable, "-c", "pass"])+ exited.wait(10)+ owner = f"{exited.pid}:{1.0!r}"+ else:+ ui_pid = _start_ui_stand_in(children, tmp_path, dict(os.environ))+ if shape == "token-of-a-live-ui":+ owner = f"v2:{ui_pid}:{runtime.process_start_token(ui_pid)}"+ elif shape == "another-token-at-a-ui-of-this-runtime":+ owner = f"v2:{ui_pid}:{runtime.process_start_token(ui_pid)}-earlier"+ else:+ # The create time macOS can show for an owner that keeps running.+ owner = f"{ui_pid}:{runtime.process_create_time(ui_pid) - 1.0!r}"+ pids = _start_tree_naming(children, env, wait_for_tree, owner)++ assert cli.cmd_stop() == 0++ assert statuses == [("stopped",)]+ assert _running(pids) == (pids if kept else [])++[email protected](os.name == "nt", reason="POSIX process groups")[email protected]("owner", ["missing", "malformed", "uninspectable", "token-unreadable"])@pytest.mark.parametrize("scoped", [False, True], ids=["full", "scoped"])def test_a_tree_whose_owner_cannot_be_told_fails_every_caller_closed(monkeypatch, installer_tree, quiet_stop, children, capsys, owner, scoped@@ -696,6 +740,15 @@ def test_a_tree_whose_owner_cannot_be_told_fails_every_caller_closed(for method in ("environ", "cmdline"):monkeypatch.setattr(psutil.Process, method, unreadable(getattr(psutil.Process, method)))+ elif owner == "token-unreadable":+ # It names its owner by start token, which cannot be read now.+ live = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])+ children.append(live)+ named = f"v2:{live.pid}:{runtime.process_start_token(live.pid)}"+ real_token = runtime.process_start_token+ monkeypatch.setattr(+ runtime, "process_start_token", lambda pid: None if pid == live.pid else real_token(pid)+ )pids = _start_tree_naming(children, env, wait_for_tree, named)npm_runs: list[bool] = []_patch_fake_install(monkeypatch, before=lambda: npm_runs.append(True))diff --git a/tests/test_opencode_generations.py b/tests/test_opencode_generations.pyindex 3644d4fdc..f6bc0f2c7 100644--- a/tests/test_opencode_generations.py+++ b/tests/test_opencode_generations.py@@ -13,6 +13,8 @@ import hashlibimport jsonimport osimport stat+import subprocess+import sysimport timefrom pathlib import Pathfrom types import SimpleNamespace@@ -326,12 +328,87 @@ def test_adoption_keeps_every_proven_serving_process_and_drops_the_rest(isolatedassert converted.spec_digest == opencode_server.LEGACY_SPEC_DIGESTassert converted.active_run_sessions == {"ses_legacy"}assert converted.record_path.exists() and not legacy.exists()+ # The converted record keeps the proof its released build applied (#2511).+ rewritten = json.loads(converted.record_path.read_text(encoding="utf-8"))+ assert "process_start_token" not in rewritten+ assert rewritten["process_created_at"] == legacy_shape.get("process_created_at")# Only the proven process that stopped serving is signalled.assert stopped == [fake_pid(13)]assert serving.exists()assert not dead.exists() and not reused.exists() and not unhealthy.exists()+def live_server_process():+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+ try:+ yield process+ finally:+ process.kill()+ process.wait(10)+++def test_an_adopted_generation_keeps_naming_its_process_across_a_clock_adjustment(live_server_process):+ """#2511: a generation record names its process by start token. The create time+ psutil shows moves when ``kern.boottime`` ticks (macOS) or the clock is stepped+ (Linux); an adopted live server judged by it read as dead and leaked."""++ from tests.test_process_start_token import _clock_adjusted++ pid = live_server_process.pid+ info = {+ "pid": pid,+ "port": 50200,+ "process_start_token": opencode_server.runtime.process_start_token(pid),+ "process_created_at": opencode_server.runtime.process_create_time(pid),+ }+ generation = opencode_server._generation_from_record(+ info, generation_id="ocg_tick", spec_digest="v1", request_timeout_seconds=60+ )+ assert generation.process_alive()++ with _clock_adjusted():+ assert generation.process_alive()+ assert opencode_server._names_one_of(pid, [generation.process_identity()])++[email protected]("unprovable", ["none-written", "token-unreadable-now"])+def test_a_record_whose_process_cannot_be_proven_is_never_signalled(+ live_server_process, tmp_path, monkeypatch, unprovable+):+ """A record this build wrote carries a token field. When neither a token nor a+ create time could be read for it, or its token cannot be read now, nothing+ proves its pid is still this server: another ``opencode serve`` on the same+ port may hold it now. It is never signalled, and a generation it names no+ longer counts any live pid as its own. Only a released record with no+ identity field keeps the command-line and port proof its build applied."""++ pid = live_server_process.pid+ monkeypatch.setattr(+ opencode_server.runtime, "get_process_command", lambda other: "/bin/opencode serve --port=50201"+ )+ signalled: list[int] = []+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda other, timeout=5.0: signalled.append(other) or True)+ token = None+ if unprovable == "token-unreadable-now":+ token = opencode_server.runtime.process_start_token(pid)+ monkeypatch.setattr(opencode_server.runtime, "process_start_token", lambda other: None)+ info = {"pid": pid, "port": 50201, "process_start_token": token, "process_created_at": None}+ path = tmp_path / "ocg_unproven.json"+ path.write_text(json.dumps(info), encoding="utf-8")++ assert opencode_server._record_proves_process(info) is False+ assert opencode_server.stop_recorded_server_sync(path, info) is opencode_server.StopOutcome.STOPPED+ assert signalled == [] and not path.exists()+ generation = opencode_server._generation_from_record(+ info, generation_id="ocg_unproven", spec_digest="v1", request_timeout_seconds=60+ )+ assert generation.process_alive() is False++ released = {"pid": pid, "port": 50201, "process_created_at": None}+ assert opencode_server._record_proves_process(released) is True++# ------------------------------------------------------- generation lifecycle@@ -1928,7 +2005,9 @@ def test_shutdown_stops_only_the_generations_this_controller_owns(isolated_launcown = _record(isolated_launch.records, "ocg_own", fake_pid(56), 50056)foreign = _record(isolated_launch.records, "ocg_foreign", fake_pid(57), 50057)- opencode_server._OWNED_HERE["ocg_own"] = (fake_pid(56), 100.0 + fake_pid(56))+ opencode_server._OWNED_HERE["ocg_own"] = opencode_server._ProcessIdentity(+ pid=fake_pid(56), port=50056, start_token=None, created_at=100.0 + fake_pid(56), released=False+ )monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")ports = {fake_pid(56): 50056, fake_pid(57): 50057}monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in ports)diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.pyindex b64943e7b..eb7385f30 100644--- a/tests/test_running_agents_service.py+++ b/tests/test_running_agents_service.py@@ -103,17 +103,15 @@ def _no_db_no_registry(monkeypatch):"modules.agents.claude_process_reaper.get_claude_client_pid",lambda client: getattr(client, "_fake_pid", None),)- # Orphan liveness: by default every probed pid is "alive" (batched ages) with- # a start time that matches the record (so identity passes). Tests exercising- # the dead/reused-pid filter override these per-pid.+ # Orphan liveness: by default every probed pid is alive, with a start that+ # matches a released record's ``started_at`` of 1000.0 (so identity passes).+ # Tests exercising the dead/reused-pid filter override these per-pid.monkeypatch.setattr("modules.agents.claude_process_reaper._process_ages",lambda pids: {p: 1.0 for p in pids},)- monkeypatch.setattr(- "modules.agents.claude_process_reaper._process_start_time",- lambda pid: 1000.0,- )+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: True)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", lambda pid: 1000.0)def test_safe_items_tolerates_concurrent_mutation():@@ -554,18 +552,15 @@ def test_orphan_skips_dead_and_reused_pids(monkeypatch):lambda *a, **k: [alive, dead, reused],)- # pid 20 is not alive (absent from batched ages → stale); pid 30 is alive but- # started far from the recorded time (reused by an unrelated process); pid 10- # is a real leak (alive + start matches the record within 1s).- monkeypatch.setattr(- "modules.agents.claude_process_reaper._process_ages",- lambda pids: {p: 1.0 for p in pids if p in {10, 30}},- )+ # pid 20 is not alive (stale); pid 30 is alive but started far from the+ # recorded time (reused by an unrelated process); pid 10 is a real leak+ # (alive + start matches the record within 1s).+ monkeypatch.setattr("vibe.runtime.pid_alive", lambda pid: pid in {10, 30})def _start(pid):return {10: 5000.4, 30: 9999.0}.get(pid)- monkeypatch.setattr("modules.agents.claude_process_reaper._process_start_time", _start)+ monkeypatch.setattr("vibe.runtime.process_start_seconds", _start)snap = running_agents.snapshot_running_agents(_make_controller())orphans = [r for r in snap["agents"] if r["state"] == "orphan"]@@ -585,7 +580,6 @@ def test_end_orphan_kills_verified_owned_pid(monkeypatch):rec = types.SimpleNamespace(pid=10, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])- monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)reap = _AsyncFlag(ret=1)monkeypatch.setattr(reaper, "_reap_pid_set", reap)@@ -603,7 +597,6 @@ def test_end_orphan_reaps_root_plus_descendants(monkeypatch):rec = types.SimpleNamespace(pid=100, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])- monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)# Tree: 100(root) -> 200(child) -> 300(grandchild); 999 is unrelated.ps_rows = [reaper.ClaudeProcessRow(pid=100, ppid=1, command="claude"),@@ -611,8 +604,8 @@ def test_end_orphan_reaps_root_plus_descendants(monkeypatch):reaper.ClaudeProcessRow(pid=300, ppid=200, command="node helper2"),reaper.ClaudeProcessRow(pid=999, ppid=1, command="unrelated"),]- monkeypatch.setattr(reaper, "_run_ps", lambda: "ignored")- monkeypatch.setattr(reaper, "_parse_ps_rows", lambda _out: ps_rows)+ monkeypatch.setattr(reaper, "_process_table", lambda: "ignored")+ monkeypatch.setattr(reaper, "_parse_process_table", lambda _out: ps_rows)captured = {}async def _reap(target_pids, *, terminate_timeout, logger):@@ -627,18 +620,17 @@ def test_end_orphan_reaps_root_plus_descendants(monkeypatch):def test_end_orphan_falls_back_to_root_when_ps_unreadable(monkeypatch):- # If the ps read fails during descendant expansion, still reap the verified+ # If the process-table read fails during descendant expansion, still reap the verified# root pid (better than reaping nothing).from modules.agents import claude_process_reaper as reaperrec = types.SimpleNamespace(pid=55, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])- monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)def _boom():raise RuntimeError("ps unavailable")- monkeypatch.setattr(reaper, "_run_ps", _boom)+ monkeypatch.setattr(reaper, "_process_table", _boom)captured = {}async def _reap(target_pids, *, terminate_timeout, logger):@@ -661,15 +653,14 @@ def test_end_orphan_excludes_other_registered_session_pids(monkeypatch):root = types.SimpleNamespace(pid=100, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)other = types.SimpleNamespace(pid=200, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [root, other])- monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)# 100(root) -> 200(other owned) -> 300(other's child)ps_rows = [reaper.ClaudeProcessRow(pid=100, ppid=1, command="claude"),reaper.ClaudeProcessRow(pid=200, ppid=100, command="claude"),reaper.ClaudeProcessRow(pid=300, ppid=200, command="node helper"),]- monkeypatch.setattr(reaper, "_run_ps", lambda: "ignored")- monkeypatch.setattr(reaper, "_parse_ps_rows", lambda _out: ps_rows)+ monkeypatch.setattr(reaper, "_process_table", lambda: "ignored")+ monkeypatch.setattr(reaper, "_parse_process_table", lambda _out: ps_rows)captured = {}async def _reap(target_pids, *, terminate_timeout, logger):@@ -691,15 +682,14 @@ def test_end_orphan_never_reaps_the_service_tree(monkeypatch):root = types.SimpleNamespace(pid=100, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [root])- monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)# 100(root) -> 200(== service pid) -> 300(service child)ps_rows = [reaper.ClaudeProcessRow(pid=100, ppid=1, command="claude"),reaper.ClaudeProcessRow(pid=200, ppid=100, command="python avibe"),reaper.ClaudeProcessRow(pid=300, ppid=200, command="python worker"),]- monkeypatch.setattr(reaper, "_run_ps", lambda: "ignored")- monkeypatch.setattr(reaper, "_parse_ps_rows", lambda _out: ps_rows)+ monkeypatch.setattr(reaper, "_process_table", lambda: "ignored")+ monkeypatch.setattr(reaper, "_parse_process_table", lambda _out: ps_rows)monkeypatch.setattr(running_agents.os, "getpid", lambda: 200) # avibe service is pid 200captured = {}@@ -734,7 +724,6 @@ def test_end_orphan_refuses_when_identity_unprovable(monkeypatch):rec = types.SimpleNamespace(pid=10, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=None)monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])- monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)reap = _AsyncFlag(ret=1)monkeypatch.setattr(reaper, "_reap_pid_set", reap)@@ -2090,3 +2079,51 @@ def test_end_rechecks_live_state_active_to_idle():)assert res["ok"] is Trueassert cleared.get("clr") == "b1" and cleared.get("treg") == "b1"+++def test_a_released_record_gets_one_verdict_where_no_process_has_a_start_token(monkeypatch):+ """#2511: on a platform with no start token (FreeBSD, OpenBSD, ...), a released+ record's ``started_at`` is the only identity. Running's orphan list and "end+ orphan" judge it alike, so a listed orphan is never refused as not alive."""++ from modules.agents import claude_process_reaper as reaper++ record = reaper.ClaudeOwnedProcess(pid=10, native_session_id="nat-released", started_at=1000.0)+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [record])+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: None)+ monkeypatch.setattr(reaper, "_process_table", lambda: "")+ reap = _AsyncFlag(ret=1)+ monkeypatch.setattr(reaper, "_reap_pid_set", reap)++ snap = running_agents.snapshot_running_agents(_make_controller())+ assert [row["pid"] for row in snap["agents"] if row["state"] == "orphan"] == [10]++ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=10))+ assert res["ok"] is True and reap.called+++ ("record", "reason"),+ [+ ({"pid": 10}, "identity_unprovable"),+ ({"pid": 10, "start_token": "boot:1"}, "identity_unverifiable"),+ ],+)+def test_end_orphan_refuses_a_record_it_cannot_verify_and_says_why(monkeypatch, record, reason):+ """A record whose start could not be read at registration, or whose identity+ cannot be read now, is neither listed nor killed; "end orphan" reports why."""++ from modules.agents import claude_process_reaper as reaper++ owned = reaper.ClaudeOwnedProcess(**record)+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [owned])+ monkeypatch.setattr("vibe.runtime.process_start_token", lambda pid: None)+ reap = _AsyncFlag(ret=1)+ monkeypatch.setattr(reaper, "_reap_pid_set", reap)++ snap = running_agents.snapshot_running_agents(_make_controller())+ assert [row for row in snap["agents"] if row["state"] == "orphan"] == []++ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=10))+ assert res == {"ok": False, "error": reason, "pid": 10}+ assert not reap.calleddiff --git a/vibe/desktop_backends.py b/vibe/desktop_backends.pyindex b82bdc662..ed77f1241 100644--- a/vibe/desktop_backends.py+++ b/vibe/desktop_backends.py@@ -839,31 +839,54 @@ def _clear_abandoned_install(record: _InstallerRecord) -> bool:return True+# The owner value an installer tree carries: this prefix, the owner's pid and+# its start token. A value without it is the ``pid:create_time`` a released+# build wrote.+_INSTALLER_OWNER_PREFIX = "v2:"++def _installer_owner() -> str:from vibe import runtime- started_at = runtime.process_create_time(os.getpid())- if started_at is None:+ start_token = runtime.process_start_token(os.getpid())+ if start_token is None:raise DesktopBackendError("Avibe could not identify itself as the owner of a desktop backend install.",code="desktop_install_failed",)- return f"{os.getpid()}:{started_at!r}"+ return f"{_INSTALLER_OWNER_PREFIX}{os.getpid()}:{start_token}"def _installer_owner_gone(owner: str, runtime_id: str | None) -> bool | None:"""Whether the process named by the owner value of a ``runtime_id`` tree has exited.The owner is gone when its pid is not alive, and alive while that pid- keeps its create time. macOS can shift the create time psutil shows for a- process that keeps running, so another one alone proves nothing: the pid- was reused only when the process now holding it is readable and is not a- UI of that Runtime, as every owner is. ``None`` when the value is- malformed, or the create time differs and the process cannot be read.+ keeps its start token, which no clock adjustment moves: another token+ means the pid was reused. A released build's value carries a create time+ instead, which macOS can shift for a process that keeps running, so+ another one alone proves nothing there: that pid was reused only when the+ process now holding it is readable and is not a UI of that Runtime, as+ every owner is. ``None`` when the value is malformed, or the owner's+ identity cannot be read now."""from vibe import runtime+ if owner.startswith(_INSTALLER_OWNER_PREFIX):+ pid_text, _, start_token = owner.removeprefix(_INSTALLER_OWNER_PREFIX).partition(":")+ try:+ pid = int(pid_text)+ except ValueError:+ return None+ if pid <= 0 or not start_token:+ return None+ if not runtime.pid_alive(pid):+ return True+ current = runtime.process_start_token(pid)+ if current is None:+ return None if runtime.pid_alive(pid) else True+ return current != start_token+pid_text, _, started_text = owner.partition(":")try:pid, started_at = int(pid_text), float(started_text)diff --git a/vibe/runtime.py b/vibe/runtime.pyindex b0392ac9b..99aae44b4 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -886,6 +886,46 @@ def process_start_token(pid: int) -> str | None:return None+def process_start_seconds(pid: int) -> float | None:+ """When a process started, as the platform's own tools print it; None if it cannot be read.++ This is a wall-clock time, so it is never an identity on its own: it is what+ ``ps -o lstart`` shows, which records written before start tokens carry.+ Linux computes it from the boot time and the start ticks, as procps does, and+ macOS keeps the wall-clock time the process started, which psutil reads back+ unadjusted through ``create_time(monotonic=True)``.+ """++ try:+ process = psutil.Process(pid)+ if sys.platform == "darwin" or sys.platform.startswith("netbsd"):+ return float(process._proc.create_time(monotonic=True))+ return float(process.create_time())+ except (psutil.Error, AttributeError, TypeError, ValueError, OSError):+ return None+++def process_age_seconds(pid: int) -> float | None:+ """How long a process has run; None if it cannot be read.++ Linux counts it from the boot, in the same ticks the start is recorded in,+ so a step of the wall clock does not change it. Elsewhere it is the wall+ clock's distance from the start.+ """++ if sys.platform.startswith("linux"):+ try:+ ticks = int(Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split()[19])+ uptime = float(Path("/proc/uptime").read_text(encoding="utf-8").split()[0])+ return max(0.0, uptime - ticks / os.sysconf("SC_CLK_TCK"))+ except (OSError, IndexError, ValueError):+ return None+ try:+ return max(0.0, time.time() - float(psutil.Process(pid).create_time()))+ except (psutil.Error, TypeError, ValueError, OSError):+ return None++def _safe_resolve_path(value: str | Path) -> Path | None:try:return Path(value).expanduser().resolve()