Skip to content

Self-hosted AI workspace.

Python

Merge lab into fix/procfs-pid-file-liveness

Alexandre Teixeirad63932f1adb5
diff --cc src/agent_tools/web_tools.py
index 6e974c47a,84bce8d5c..4a04b8b10
--- a/src/agent_tools/web_tools.py
+++ b/src/agent_tools/web_tools.py
@@@ -18,7 -18,6 +18,7 @@@ import urllib.reques
from pathlib import Path
from typing import Dict, Any
- from core.platform_compat import pid_alive
++from core import platform_compat
from src.constants import MAX_OUTPUT_CHARS
PDF_EXTRACT_MAX_BYTES = 80_000_000
@@@ -124,43 -123,7 +124,42 @@@ def _browser_pid_file_candidates
# Linux exposes one command line per pid under /proc; macOS and Windows do not.
# Kept as a module attribute so the procfs-dependent paths stay testable on a
# host that has no procfs, and on one that does.
--_PROC_ROOT = Path("/proc")
+
+
+def _process_command_line(pid: int) -> str | None:
+ """Command line of a running process, or ``None`` when it cannot be read.
+
+ ``None`` means "this host cannot tell", not "the process is gone". Off
+ Linux there is no procfs to read a command line from, so callers must not
+ treat it as proof that the process exited.
+ """
+
+ try:
- return (_PROC_ROOT / str(pid) / "cmdline").read_bytes().replace(
++ return (platform_compat.PROC_ROOT / str(pid) / "cmdline").read_bytes().replace(
+ b"\0", b" "
+ ).decode("utf-8", errors="replace")
+ except (OSError, UnicodeError):
+ return None
+
+
+def _process_is_alive(pid: int) -> bool:
+ """Whether a pid currently exists.
+
+ Delegates to ``core.platform_compat.pid_alive`` rather than probing with
+ ``os.kill(pid, 0)`` directly. That probe is POSIX-only: CPython's Windows
+ ``os.kill`` calls ``TerminateProcess(handle, sig)`` for any signal other
+ than CTRL_C / CTRL_BREAK, so it would *kill* the daemon it is asked about.
+ Windows is also where there is no procfs, which is precisely when this
+ function gets called at all.
+
+ ``pid_alive`` reads False for a pid that ``os.kill`` reports with
+ ``PermissionError`` — a live process owned by another user. Neither caller
+ here wants a different answer: the sweep only unlinks a pid file it wrote
+ itself, and treating somebody else's pid as "not our daemon" is the safe
+ reading in both.
+ """
+
- return pid_alive(pid)
++ return platform_compat.pid_alive(pid)
_SCHOLARLY_METADATA_CUE_RE = re.compile(
r"\b(?:accept(?:ed|ance)?|publish(?:ed|ing|cation)?|venue|conference|"
@@@ -2359,14 -2322,14 +2358,14 @@@ class PrivateBrowserTool
except OSError:
return
profile_prefix = str(tmpdir / "agent-browser-chrome-")
-- if not _PROC_ROOT.is_dir():
++ if not platform_compat.has_procfs():
# Without procfs there is no way to match a reparented Chrome by
# its command line, and the sweep is an optimisation rather than a
# correctness requirement. Leave those trees to the daemon's own
# lifecycle instead of failing the whole shutdown path.
return
pids: list[int] = []
-- for entry in _PROC_ROOT.iterdir():
++ for entry in platform_compat.PROC_ROOT.iterdir():
if not entry.name.isdigit():
continue
try:
diff --cc tests/test_private_browser_tool.py
index 7df8db9fe,34fbce363..79c761e60
--- a/tests/test_private_browser_tool.py
+++ b/tests/test_private_browser_tool.py
@@@ -4,6 -4,6 +4,7 @@@ import base6
import json
from pathlib import Path
++from core import platform_compat
import src.agent_tools.web_tools as web_tools
from src.agent_tools.web_tools import (
PrivateBrowserTool,
@@@ -1809,7 -1809,7 +1810,7 @@@ def test_terminate_owned_chrome_skips_t
"""macOS and Windows have no /proc; shutdown must degrade, not raise."""
missing = tmp_path / "no-procfs"
-- monkeypatch.setattr(web_tools, "_PROC_ROOT", missing)
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", missing)
def _unexpected_iterdir(*args, **kwargs):
raise AssertionError("the pid sweep must not run without procfs")
@@@ -1838,112 -1838,10 +1839,112 @@@ def test_terminate_owned_chrome_kills_o
_write_pid("202", "chrome --user-data-dir=/Users/someone/Library/Chrome")
(proc / "self").mkdir()
-- monkeypatch.setattr(web_tools, "_PROC_ROOT", proc)
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", proc)
killed: list[int] = []
monkeypatch.setattr(web_tools.os, "kill", lambda pid, sig: killed.append(pid))
PrivateBrowserTool._terminate_owned_chrome({"TMPDIR": str(tmpdir)})
assert killed == [101]
+
+
+def _pid_file_for(tmp_path, monkeypatch, namespace, session, pid):
+ """Write a pid file where the daemon helpers will look for it."""
+ monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path))
+ monkeypatch.setenv("ODYSSEUS_BROWSER_NAMESPACE", namespace)
+ candidates = web_tools._browser_pid_file_candidates(tmp_path, namespace, session)
+ target = candidates[0]
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(str(pid))
+ return target
+
+
+def test_live_daemon_pid_file_survives_a_host_without_procfs(
+ monkeypatch, tmp_path
+) -> None:
+ """Off Linux a missing cmdline is not evidence the daemon exited."""
+
- monkeypatch.setattr(web_tools, "_PROC_ROOT", tmp_path / "no-procfs")
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "no-procfs")
+ monkeypatch.setattr(web_tools, "_process_is_alive", lambda pid: True)
+ killed: list[int] = []
+ monkeypatch.setattr(web_tools.os, "kill", lambda pid, sig: killed.append(pid))
+ pid_file = _pid_file_for(tmp_path, monkeypatch, "clawmm-test", "session-1", 4321)
+
+ PrivateBrowserTool._terminate_owned_daemon({}, "session-1")
+
+ assert pid_file.exists(), "a live daemon's pid file must not be removed"
+ assert killed == [], "an unverified process must not be killed"
+
+
+def test_dead_daemon_pid_file_is_removed_without_procfs(monkeypatch, tmp_path) -> None:
+ """A pid that no longer exists is the one case that justifies forgetting it."""
+
- monkeypatch.setattr(web_tools, "_PROC_ROOT", tmp_path / "no-procfs")
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "no-procfs")
+ monkeypatch.setattr(web_tools, "_process_is_alive", lambda pid: False)
+ pid_file = _pid_file_for(tmp_path, monkeypatch, "clawmm-test", "session-2", 4322)
+
+ PrivateBrowserTool._terminate_owned_daemon({}, "session-2")
+
+ assert not pid_file.exists()
+
+
+def test_owned_daemon_is_detected_from_a_live_pid_without_procfs(
+ monkeypatch, tmp_path
+) -> None:
+ """Answering "no daemon" here is what lets close bootstrap a fresh one."""
+
- monkeypatch.setattr(web_tools, "_PROC_ROOT", tmp_path / "no-procfs")
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "no-procfs")
+ monkeypatch.setattr(web_tools, "_process_is_alive", lambda pid: True)
+ _pid_file_for(tmp_path, monkeypatch, "clawmm-test", "session-3", 4323)
+
+ assert PrivateBrowserTool._owned_daemon_exists({}, "session-3") is True
+
+
+def test_owned_daemon_absent_when_the_pid_is_gone(monkeypatch, tmp_path) -> None:
- monkeypatch.setattr(web_tools, "_PROC_ROOT", tmp_path / "no-procfs")
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "no-procfs")
+ monkeypatch.setattr(web_tools, "_process_is_alive", lambda pid: False)
+ _pid_file_for(tmp_path, monkeypatch, "clawmm-test", "session-4", 4324)
+
+ assert PrivateBrowserTool._owned_daemon_exists({}, "session-4") is False
+
+
+def test_procfs_host_still_matches_on_the_command_line(monkeypatch, tmp_path) -> None:
+ """With procfs present the identity check stays exact, not pid-liveness."""
+
+ proc = tmp_path / "proc"
+ (proc / "5555").mkdir(parents=True)
+ (proc / "5555" / "cmdline").write_bytes(b"node\0agent-browser\0--serve")
+ (proc / "6666").mkdir(parents=True)
+ (proc / "6666" / "cmdline").write_bytes(b"some\0other\0process")
- monkeypatch.setattr(web_tools, "_PROC_ROOT", proc)
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", proc)
+ monkeypatch.setattr(web_tools, "_process_is_alive", lambda pid: True)
+
+ _pid_file_for(tmp_path, monkeypatch, "clawmm-test", "session-5", 5555)
+ assert PrivateBrowserTool._owned_daemon_exists({}, "session-5") is True
+
+ _pid_file_for(tmp_path, monkeypatch, "clawmm-test", "session-6", 6666)
+ assert PrivateBrowserTool._owned_daemon_exists({}, "session-6") is False
+
+
+def test_liveness_probe_goes_through_the_platform_safe_helper(monkeypatch) -> None:
+ """The no-procfs path must not reach a bare ``os.kill(pid, 0)``.
+
+ CPython's Windows ``os.kill`` calls ``TerminateProcess(handle, sig)`` for
+ any signal other than CTRL_C / CTRL_BREAK, so probing liveness with signal
+ 0 terminates the process it asks about — and the only hosts that reach this
+ probe are the ones with no procfs, Windows among them.
+ ``core.platform_compat.pid_alive`` is the tree's platform-safe answer.
+ """
+
+ asked: list[int] = []
+ monkeypatch.setattr(
- web_tools, "pid_alive", lambda pid: asked.append(pid) or True
++ platform_compat, "pid_alive", lambda pid: asked.append(pid) or True
+ )
+ monkeypatch.setattr(
+ web_tools.os,
+ "kill",
+ lambda *a, **kw: pytest.fail("os.kill must not be used to probe liveness"),
+ )
+
+ assert web_tools._process_is_alive(4242) is True
+ assert asked == [4242]
diff --cc tests/test_runtime_behavior_regressions.py
index 000000000,84ca3ad15..9563bb177
mode 000000,100644..100644
--- a/tests/test_runtime_behavior_regressions.py
+++ b/tests/test_runtime_behavior_regressions.py
@@@ -1,0 -1,268 +1,269 @@@
+ """Deterministic regression coverage for runtime behaviours, test-only.
+
+ These drive ``stream_agent_loop`` with a fake model so the assertions are about
+ what the runtime offers and does, not about what a model happens to answer.
+ Nothing here imports benchmark fixtures or allowlists, and nothing here touches
+ production runtime code: the lane exists so the implementation side can move
+ without losing the behaviours underneath it.
+
+ The fake-model pattern is the one already used by tests/test_tool_policy.py:
+ patch ``stream_llm_with_fallback`` and inspect the ``tools`` kwarg the loop
+ hands it, which is the runtime's decision about what the turn may do.
+ """
+
+ import asyncio
+ import json
+
+ import pytest
+
++from core import platform_compat
+ import src.agent_loop as al
+ import src.agent_tools.web_tools as al_web
+
+
+ def _collect(gen):
+ async def _run():
+ return [c async for c in gen]
+
+ return asyncio.run(_run())
+
+
+ def _delta_chunk(text):
+ payload = {"choices": [{"delta": {"content": text}}]}
+ return f"data: {json.dumps(payload)}\n\n"
+
+
+ def _schema_names(tools):
+ return {
+ tool.get("function", {}).get("name") or tool.get("name")
+ for tool in (tools or [])
+ }
+
+
+ def _patch_loop_basics(monkeypatch):
+ monkeypatch.setattr(al, "get_setting", lambda key, default=None: default, raising=False)
+ monkeypatch.setattr(al, "get_mcp_manager", lambda: None, raising=False)
+ monkeypatch.setattr(al, "estimate_tokens", lambda *a, **k: 10, raising=False)
+
+
+ def _run_turn(monkeypatch, messages, **kwargs):
+ """Drive one agent turn and return the tool sets offered to the model."""
+ _patch_loop_basics(monkeypatch)
+ offered = []
+
+ async def _fake_stream(_candidates, _messages, **kw):
+ offered.append(kw.get("tools"))
+ yield _delta_chunk("ok")
+ yield "data: [DONE]\n\n"
+
+ monkeypatch.setattr(al, "stream_llm_with_fallback", _fake_stream, raising=False)
+ _collect(
+ al.stream_agent_loop(
+ "http://local.test/v1",
+ "moonshotai/kimi-k3",
+ messages,
+ max_rounds=kwargs.pop("max_rounds", 1),
+ relevant_tools=kwargs.pop("relevant_tools", {"ask_user", "update_plan"}),
+ owner=kwargs.pop("owner", "sft_alex_creator"),
+ **kwargs,
+ )
+ )
+ return offered
+
+
+
+ def _contract(offered=("ask_user", "update_plan", "manage_notes"),
+ required=("manage_notes",)):
+ """A minimal valid TurnContract.
+
+ The dataclass validates required <= offered <= executable and that the
+ schema inventory matches offered exactly, so the schemas are built from
+ the same names rather than hand-written.
+ """
+ from src.turn_contract import TurnContract
+
+ return TurnContract(
+ capabilities=frozenset({"notes"}),
+ required=frozenset(required),
+ offered=frozenset(offered),
+ executable=frozenset(offered),
+ unavailable=frozenset(),
+ schema_json=tuple(
+ json.dumps({"type": "function", "function": {"name": n, "parameters": {}}})
+ for n in offered
+ ),
+ )
+
+
+ # ── negative capability wording ─────────────────────────────────────────────
+ # A turn that says not to search must not be handed the search tools. The
+ # failure this guards is a model that obeys the wording while the runtime
+ # contradicted it by offering the tool anyway.
+ #
+ # SCOPE, and it matters: these cover the inferred path, where the turn has no
+ # explicit web toggle and the runtime decides from intent. Measured on
+ # lab@c499c01b, detection there is partial: "don't search online" suppresses
+ # the intent and the web tools are withheld; "Do not search the web" and "No
+ # web search please" do not, and the tools are offered.
+ #
+ # When the user explicitly enables web for the turn, wording does not withhold
+ # anything: confirmed end to end against a local Qwen3.5-9B Q4_K_M, where all
+ # three phrasings were offered web_search, web_fetch and private_browser. That
+ # may well be correct, an explicit toggle beating an inferred negative, so it
+ # is recorded here rather than asserted either way.
+ #
+ # The two inferred-path cases that do not hold are xfail(strict=True): they
+ # document the target, run on every suite, and fail the moment the behaviour
+ # lands. Delete the marker then.
+
+ HELD = ["Answer from memory only, don't search online."]
+
+ NOT_HELD_YET = [
+ "Summarise what you already know. Do not search the web.",
+ "No web search please, just tell me what you know about Python decorators.",
+ ]
+
+
+ @pytest.mark.parametrize("phrasing", HELD)
+ def test_negative_web_wording_withholds_the_web_tools(monkeypatch, phrasing):
+ offered = _run_turn(monkeypatch, [{"role": "user", "content": phrasing}])
+
+ names = _schema_names(offered[0])
+ assert "web_search" not in names, f"web_search offered despite: {phrasing!r}"
+ assert "web_fetch" not in names, f"web_fetch offered despite: {phrasing!r}"
+
+
+ @pytest.mark.xfail(
+ strict=True,
+ reason="negative web wording is only partially detected on lab@c499c01b; "
+ "these phrasings still get the web tools offered",
+ )
+ @pytest.mark.parametrize("phrasing", NOT_HELD_YET)
+ def test_negative_web_wording_withholds_the_web_tools_unhandled(monkeypatch, phrasing):
+ offered = _run_turn(monkeypatch, [{"role": "user", "content": phrasing}])
+
+ names = _schema_names(offered[0])
+ assert "web_search" not in names, f"web_search offered despite: {phrasing!r}"
+ assert "web_fetch" not in names, f"web_fetch offered despite: {phrasing!r}"
+
+
+ def test_plain_web_request_still_offers_search(monkeypatch):
+ """The guard above must not become a blanket removal of the web tools."""
+ offered = _run_turn(
+ monkeypatch,
+ [{"role": "user", "content": "Search the web for the latest Python release."}],
+ )
+
+ assert "web_search" in _schema_names(offered[0])
+
+
+ # ── supplied workspace context must not produce a clarification ─────────────
+ # When the turn already carries what it needs, an answer that hands the next
+ # decision back to the user is a failed turn, not a polite one. The runtime
+ # detects that shape; these pin the detector so a reworded prompt cannot slip
+ # past it silently.
+
+ @pytest.mark.parametrize(
+ "answer",
+ [
+ "Could you please share the file you want me to edit?",
+ "Would you like me to go ahead and refactor it?",
+ "Shall I start with the parser?",
+ "Please let me know which approach you prefer.",
+ ],
+ )
+ def test_handing_the_decision_back_is_recognised_as_clarification(answer):
+ assert al._looks_like_unattended_clarification(answer) is True
+
+
+ @pytest.mark.parametrize(
+ "answer",
+ [
+ "I read config.py and the timeout is set to 30 seconds.",
+ "The parser fails on empty input because it indexes before checking length.",
+ "Done. The workspace now has three files.",
+ ],
+ )
+ def test_ordinary_answers_are_not_clarifications(answer):
+ assert al._looks_like_unattended_clarification(answer) is False
+
+
+ # ── repeated update_plan is not the turn's actionable work ─────────────────
+ # update_plan and ask_user are permitted on almost every turn, so if they
+ # counted as execution a model could loop on them forever and look busy. The
+ # runtime must not advertise them as the tools that satisfy the request.
+
+ def test_plan_and_ask_are_not_advertised_as_the_turns_available_tools():
+ contract = _contract()
+
+ reason = al._tool_rejection_reason("web_search", set(), None, contract=contract)
+
+ assert "manage_notes" in reason
+ assert "update_plan" not in reason, "update_plan advertised as actionable work"
+ assert "ask_user" not in reason, "ask_user advertised as actionable work"
+
+
+ def test_update_plan_is_permitted_but_never_the_requirement():
+ contract = _contract()
+
+ assert contract.permits("update_plan") is True
+ assert "update_plan" not in contract.required
+
+
+ # ── request-scoped tool authority ──────────────────────────────────────────
+ # An external contract names what the request may do. A tool the caller never
+ # declared must not become executable just because the runtime knows it.
+
+ def test_request_scope_excludes_tools_the_caller_never_declared():
+ declared = [{"function": {"name": "write_file"}}]
+ offered = [{"function": {"name": "write_file"}}, {"function": {"name": "bash"}}]
+
+ allowed = al._request_scoped_allowed_tool_names(
+ declared, offered, native_terminal_runtime=False
+ )
+
+ assert allowed == {"write_file"}
+ assert "bash" not in allowed, "an undeclared tool became executable"
+
+
+ def test_native_terminal_runtime_adds_offered_tools_deliberately():
+ """The widening exists, so pin it: it is opt-in, not the default."""
+ declared = [{"function": {"name": "write_file"}}]
+ offered = [{"function": {"name": "write_file"}}, {"function": {"name": "bash"}}]
+
+ allowed = al._request_scoped_allowed_tool_names(
+ declared, offered, native_terminal_runtime=True
+ )
+
+ assert allowed == {"write_file", "bash"}
+
+
+ # ── owned process cleanup, foreign-process safety ──────────────────────────
+ # The Chrome sweep matches on this runtime's own profile prefix. A browser
+ # belonging to the user, or to another worktree, must survive it.
+
+ def test_chrome_sweep_kills_only_this_runtimes_profile(monkeypatch, tmp_path):
+ from src.agent_tools.web_tools import PrivateBrowserTool
+
+ proc = tmp_path / "proc"
+ tmpdir = tmp_path / "runtime-tmp"
+ tmpdir.mkdir()
+ ours = str(tmpdir.resolve() / "agent-browser-chrome-")
+
+ def _pid(pid, cmdline):
+ entry = proc / pid
+ entry.mkdir(parents=True)
+ (entry / "cmdline").write_bytes(cmdline.replace(" ", "\0").encode())
+
+ _pid("101", f"chrome --user-data-dir={ours}session-a")
+ _pid("202", "chrome --user-data-dir=/Users/someone/Library/Chrome")
+ _pid("303", "chrome --user-data-dir=/tmp/other-worktree/agent-browser-chrome-x")
+ (proc / "self").mkdir()
+
- monkeypatch.setattr(al_web, "_PROC_ROOT", proc)
++ monkeypatch.setattr(platform_compat, "PROC_ROOT", proc)
+ killed = []
+ monkeypatch.setattr(al_web.os, "kill", lambda pid, sig: killed.append(pid))
+
+ PrivateBrowserTool._terminate_owned_chrome({"TMPDIR": str(tmpdir)})
+
+ assert killed == [101], f"swept a process that was not ours: {killed}"