Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

fix(doctor): make health checks truthful and read-only

Pnant6d67d7059121
diff --git a/agent_reach/backends/opencli.py b/agent_reach/backends/opencli.py
index e03ba9e2..f7a14c23 100644
--- a/agent_reach/backends/opencli.py
+++ b/agent_reach/backends/opencli.py
@@ -9,11 +9,10 @@ Probing notes (verified live):
- `opencli doctor` AUTO-STARTS the daemon — a side effect, so health
checks must use `opencli daemon status` (pure query) instead.
- Exit codes are always 0; status must be parsed from text output.
- - "Extension: disconnected" does NOT mean unusable: the extension's
- service worker sleeps and any real opencli command wakes it up
- (verified: status flips disconnected→connected after one call).
- Since daemon status can't tell "sleeping" from "never installed",
- we check Chrome's Extensions directory on disk to disambiguate.
+ - "Extension: disconnected" can mean a sleeping service worker, a disabled
+ extension, or an extension that was never loaded. Disk files distinguish
+ possible installation sources, but only a live daemon connection proves
+ the browser actually loaded and enabled the extension.
"""
import glob
@@ -28,33 +27,53 @@ OPENCLI_EXTENSION_URL = (
f"https://chromewebstore.google.com/detail/opencli/{OPENCLI_EXTENSION_ID}"
)
-#: Chrome-family profile roots that contain <Profile>/Extensions/<id>/
+# OpenCLIApp 0.1.35 injected this now-unsupported variable into every child.
+# OpenCLI >=1.8.5 rejects it before even handling ``--version``. Doctor is a
+# read-only observer, so strip the stale app setting only from its child probes.
+_UNSUPPORTED_APP_ENV = ("OPENCLI_DAEMON_PORT",)
+
+#: Chromium-family profile roots that contain <Profile>/Extensions/<id>/
_CHROME_PROFILE_ROOTS = (
"~/Library/Application Support/Google/Chrome", # macOS Chrome
"~/Library/Application Support/Chromium", # macOS Chromium
+ "~/Library/Application Support/Microsoft Edge", # macOS Edge
"~/.config/google-chrome", # Linux Chrome
"~/.config/chromium", # Linux Chromium
+ "~/.config/microsoft-edge", # Linux Edge
)
+_OPENCLI_UNPACKED_EXTENSION = "~/.opencli/extension"
+
def _extension_installed_on_disk() -> bool:
- """True if the OpenCLI extension exists in any Chrome profile.
+ """True if store-installed OpenCLI files exist in a browser profile.
- Store-installed extensions always live under
- <profile>/Extensions/<extension id>/ — this disambiguates a sleeping
- service worker from a never-installed extension. Dev installs via
- "Load unpacked" are not covered (those users can read `opencli doctor`).
+ This is disk evidence only: a user may have disabled or removed the
+ extension while stale files remain, so callers must not treat it as proof
+ that the extension is loaded, connected, or usable.
"""
roots = [os.path.expanduser(p) for p in _CHROME_PROFILE_ROOTS]
local_app_data = os.environ.get("LOCALAPPDATA")
if local_app_data: # Windows
roots.append(os.path.join(local_app_data, "Google", "Chrome", "User Data"))
+ roots.append(os.path.join(local_app_data, "Microsoft", "Edge", "User Data"))
for root in roots:
if glob.glob(os.path.join(root, "*", "Extensions", OPENCLI_EXTENSION_ID)):
return True
return False
+def _unpacked_extension_files_present() -> bool:
+ """True when OpenCLI's unpacked extension source contains a manifest.
+
+ ``~/.opencli/extension`` is downloaded source, not browser state. Its
+ existence never proves the user completed “Load unpacked” or left the
+ extension enabled.
+ """
+ unpacked = os.path.expanduser(_OPENCLI_UNPACKED_EXTENSION)
+ return os.path.isfile(os.path.join(unpacked, "manifest.json"))
+
+
@dataclass
class OpenCLIStatus:
installed: bool = False
@@ -62,25 +81,28 @@ class OpenCLIStatus:
daemon_running: bool = False
extension_connected: bool = False
extension_installed: bool = False
+ unpacked_extension_files: bool = False
version: str = ""
hint: str = ""
@property
def ready(self) -> bool:
- """Usable now or on first call.
+ """True only when the backend is provably usable now.
- A live connection counts, and so does an installed-but-sleeping
- extension: its service worker wakes on the first real command.
+ Only a live daemon connection proves that a browser loaded and enabled
+ the extension. Disk files alone are deliberately not enough.
"""
- return self.installed and not self.broken and (
- self.extension_connected or self.extension_installed
- )
+ return self.installed and not self.broken and self.extension_connected
def opencli_status(timeout: int = 10) -> OpenCLIStatus:
"""Probe OpenCLI install + daemon/extension state without side effects."""
version_probe = probe_command(
- "opencli", ["--version"], timeout=timeout, package=OPENCLI_PACKAGE
+ "opencli",
+ ["--version"],
+ timeout=timeout,
+ package=OPENCLI_PACKAGE,
+ remove_env=_UNSUPPORTED_APP_ENV,
)
if version_probe.status == "missing":
return OpenCLIStatus(installed=False)
@@ -97,7 +119,11 @@ def opencli_status(timeout: int = 10) -> OpenCLIStatus:
st = OpenCLIStatus(installed=True, version=version_probe.output.strip())
daemon_probe = probe_command(
- "opencli", ["daemon", "status"], timeout=timeout, package=OPENCLI_PACKAGE
+ "opencli",
+ ["daemon", "status"],
+ timeout=timeout,
+ package=OPENCLI_PACKAGE,
+ remove_env=_UNSUPPORTED_APP_ENV,
)
output = daemon_probe.output if daemon_probe.ok else ""
# `opencli daemon status` prints lines like:
@@ -112,11 +138,24 @@ def opencli_status(timeout: int = 10) -> OpenCLIStatus:
if not st.extension_connected:
st.extension_installed = _extension_installed_on_disk()
- if not st.extension_installed:
+ st.unpacked_extension_files = _unpacked_extension_files_present()
+ if st.extension_installed:
+ st.hint = (
+ "检测到 Chrome/Edge 的 OpenCLI 扩展文件,但扩展当前未连接;"
+ "仅凭磁盘文件无法确认它已加载或启用。\n"
+ " 打开浏览器扩展页确认 OpenCLI 已启用,再运行一个 opencli 命令验证"
+ )
+ elif st.unpacked_extension_files:
+ st.hint = (
+ "检测到 ~/.opencli/extension/ 源文件,但文件存在不代表已经在"
+ " Chrome/Edge 中“加载已解压的扩展程序”。\n"
+ " 请在浏览器扩展页加载并启用该目录,再运行一个 opencli 命令验证"
+ )
+ else:
st.hint = (
- "OpenCLI 已安装,但 Chrome 扩展未安装。\n"
- f" 1. 安装扩展(需手动点一次):{OPENCLI_EXTENSION_URL}\n"
- " 2. 保持 Chrome 打开,运行 `opencli doctor` 验证"
+ "OpenCLI 已安装,但未检测到已连接的浏览器扩展。\n"
+ f" 1. 安装并启用扩展(Chrome/Edge):{OPENCLI_EXTENSION_URL}\n"
+ " 2. 保持浏览器打开,再运行一个 opencli 命令验证"
)
return st
@@ -129,8 +168,10 @@ def opencli_summary(st: OpenCLIStatus) -> str:
return "OpenCLI 无法执行(node 环境损坏)"
if st.extension_connected:
return f"OpenCLI 可用(浏览器登录态,v{st.version})"
- if st.ready:
- return "OpenCLI 可用(扩展睡眠中,调用时自动唤醒)"
+ if st.extension_installed:
+ return "OpenCLI 已安装,检测到扩展文件但当前未连接(无法确认已加载)"
+ if st.unpacked_extension_files:
+ return "OpenCLI 已安装,检测到 unpacked 源文件但尚未确认浏览器已加载"
if st.daemon_running:
return "OpenCLI 已安装,等待 Chrome 扩展安装"
return "OpenCLI 已安装(daemon 未运行,使用时自动启动;需 Chrome 扩展)"
diff --git a/agent_reach/channels/exa_search.py b/agent_reach/channels/exa_search.py
index 01a2fcf3..456dba02 100644
--- a/agent_reach/channels/exa_search.py
+++ b/agent_reach/channels/exa_search.py
@@ -4,6 +4,7 @@
from agent_reach.probe import probe_command
from .base import Channel
+from .mcporter import McporterConfigError, configured_server_names
#: mcporter 是 npm 包,断链处方与默认的 pipx/uv 不同
_MCPORTER_BROKEN_HINT = "mcporter 无法执行(node 环境损坏),重装:\n npm install -g mcporter"
@@ -20,7 +21,12 @@ class ExaSearchChannel(Channel):
def check(self, config=None):
self.active_backend = None
- probe = probe_command("mcporter", ["config", "list"], timeout=10, package="mcporter")
+ probe = probe_command(
+ "mcporter",
+ ["config", "list", "--json"],
+ timeout=10,
+ package="mcporter",
+ )
if probe.status == "missing":
return "off", (
"需要 mcporter + Exa MCP。安装:\n"
@@ -31,7 +37,11 @@ class ExaSearchChannel(Channel):
return "error", _MCPORTER_BROKEN_HINT
if not probe.ok: # timeout / error
return "error", f"mcporter 执行异常:{probe.hint or probe.output or probe.status}"
- if "exa" in probe.output.lower():
+ try:
+ server_names = configured_server_names(probe.output)
+ except McporterConfigError as exc:
+ return "error", f"mcporter 配置检查失败:{exc}"
+ if "exa" in server_names:
self.active_backend = self.backends[0]
return "ok", "全网语义搜索可用(免费,无需 API Key)"
return "off", (
diff --git a/agent_reach/channels/linkedin.py b/agent_reach/channels/linkedin.py
index 9b1bb5df..a2a5ddae 100644
--- a/agent_reach/channels/linkedin.py
+++ b/agent_reach/channels/linkedin.py
@@ -4,9 +4,11 @@
from agent_reach.probe import probe_command
from .base import Channel
+from .mcporter import McporterConfigError, configured_server_names
#: mcporter 是 npm 包,断链处方与默认的 pipx/uv 不同
_MCPORTER_BROKEN_HINT = "mcporter 无法执行(node 环境损坏),重装:\n npm install -g mcporter"
+_LINKEDIN_SERVER_NAMES = {"linkedin", "linkedin-scraper", "linkedin-scraper-mcp"}
class LinkedInChannel(Channel):
@@ -21,7 +23,12 @@ class LinkedInChannel(Channel):
def check(self, config=None):
self.active_backend = None
- probe = probe_command("mcporter", ["config", "list"], timeout=10, package="mcporter")
+ probe = probe_command(
+ "mcporter",
+ ["config", "list", "--json"],
+ timeout=10,
+ package="mcporter",
+ )
if probe.status == "missing":
return "off", (
"基本内容可通过 Jina Reader 读取。完整功能需要:\n"
@@ -33,7 +40,11 @@ class LinkedInChannel(Channel):
return "error", _MCPORTER_BROKEN_HINT
if not probe.ok: # timeout / error
return "error", f"mcporter 执行异常:{probe.hint or probe.output or probe.status}"
- if "linkedin" in probe.output.lower():
+ try:
+ server_names = configured_server_names(probe.output)
+ except McporterConfigError as exc:
+ return "error", f"mcporter 配置检查失败:{exc}"
+ if server_names & _LINKEDIN_SERVER_NAMES:
self.active_backend = "linkedin-scraper-mcp"
return "ok", "完整可用(Profile、公司、职位搜索)"
return "off", (
diff --git a/agent_reach/channels/mcporter.py b/agent_reach/channels/mcporter.py
new file mode 100644
index 00000000..a9aaab29
--- /dev/null
+++ b/agent_reach/channels/mcporter.py
@@ -0,0 +1,31 @@
+"""Helpers for interpreting mcporter's machine-readable config output."""
+
+from __future__ import annotations
+
+import json
+
+
+class McporterConfigError(ValueError):
+ """Raised when mcporter's advertised JSON output is not trustworthy."""
+
+
+def configured_server_names(output: str) -> set[str]:
+ """Return exact configured server names from ``mcporter ... --json``.
+
+ Paths, descriptions, endpoints, and other metadata are deliberately
+ ignored: only each server object's ``name`` field is a routing signal.
+ """
+ try:
+ payload = json.loads(output)
+ except (json.JSONDecodeError, TypeError) as exc:
+ raise McporterConfigError("mcporter 返回的 JSON 无法解析") from exc
+
+ if not isinstance(payload, dict) or not isinstance(payload.get("servers"), list):
+ raise McporterConfigError("mcporter JSON 缺少 servers 列表")
+
+ return {
+ name.casefold()
+ for server in payload["servers"]
+ if isinstance(server, dict)
+ if isinstance(name := server.get("name"), str) and name.strip()
+ }
diff --git a/agent_reach/channels/twitter.py b/agent_reach/channels/twitter.py
index 8c8869b4..0c444db7 100644
--- a/agent_reach/channels/twitter.py
+++ b/agent_reach/channels/twitter.py
@@ -1,9 +1,34 @@
# -*- coding: utf-8 -*-
"""Twitter/X — check if twitter-cli or bird CLI is available."""
-from .base import Channel
+import os
+
from agent_reach.probe import probe_command
+from .base import Channel
+
+
+def twitter_cli_child_env(config=None) -> dict[str, str]:
+ """Return saved credentials missing from the current process environment.
+
+ The returned mapping is meant for a single child process. Existing shell
+ variables remain authoritative and ``os.environ`` is never mutated.
+ """
+ if config is None:
+ return {}
+
+ child_env = {}
+ for env_name, config_key in (
+ ("TWITTER_AUTH_TOKEN", "twitter_auth_token"),
+ ("TWITTER_CT0", "twitter_ct0"),
+ ):
+ if env_name in os.environ:
+ continue
+ value = config.get(config_key)
+ if value:
+ child_env[env_name] = str(value)
+ return child_env
+
class TwitterChannel(Channel):
name = "twitter"
@@ -28,7 +53,7 @@ class TwitterChannel(Channel):
for backend in self.ordered_backends(config):
if backend == "twitter-cli":
- result = self._check_twitter_cli()
+ result = self._check_twitter_cli(config)
elif backend == "OpenCLI":
result = self._check_opencli()
elif backend == "bird CLI (legacy)":
@@ -56,7 +81,7 @@ class TwitterChannel(Channel):
" uv tool install twitter-cli"
)
- def _check_twitter_cli(self):
+ def _check_twitter_cli(self, config=None):
"""探测 twitter-cli。返回 None 表示未安装,否则返回 (status, message)。
`twitter status` 才是健康信号:已登录时输出 "ok: true",
@@ -64,7 +89,12 @@ class TwitterChannel(Channel):
所以 probe 的 error 状态也要看 output 内容再分类。
"""
probe = probe_command(
- "twitter", ["status"], timeout=15, retries=1, package="twitter-cli"
+ "twitter",
+ ["status"],
+ timeout=15,
+ retries=1,
+ package="twitter-cli",
+ env=twitter_cli_child_env(config),
)
if probe.status == "missing":
return None
diff --git a/agent_reach/cli.py b/agent_reach/cli.py
index ead38582..8936b46e 100644
--- a/agent_reach/cli.py
+++ b/agent_reach/cli.py
@@ -1161,9 +1161,11 @@ def _cmd_configure(args):
print("[!] twitter-cli not installed. Run: pipx install twitter-cli")
else:
import os
+
+ from agent_reach.channels.twitter import twitter_cli_child_env
+
env = os.environ.copy()
- env["TWITTER_AUTH_TOKEN"] = auth_token
- env["TWITTER_CT0"] = ct0
+ env.update(twitter_cli_child_env(config))
result = subprocess.run(
[twitter_bin, "status"],
capture_output=True, encoding="utf-8", errors="replace", timeout=15,
@@ -1559,7 +1561,7 @@ def _cmd_doctor(args=None):
from rich import print as rprint
except ImportError:
rprint = print
- config = Config()
+ config = Config(read_only=True)
results = check_all(config)
if args is not None and getattr(args, "json", False):
diff --git a/agent_reach/config.py b/agent_reach/config.py
index 59d91851..e34c7882 100644
--- a/agent_reach/config.py
+++ b/agent_reach/config.py
@@ -1,11 +1,13 @@
# -*- coding: utf-8 -*-
"""Configuration management for Agent Reach.
-Stores settings in ~/.agent-reach/config.yaml.
-Auto-creates directory on first use.
+Stores settings in ~/.agent-reach/config.yaml. Reads never create files or
+directories; the private directory is created only on the first write.
"""
import os
+import stat
+import tempfile
from pathlib import Path
from typing import Any, Optional
@@ -14,6 +16,76 @@ import yaml
from agent_reach.utils.paths import make_private_dir
+class ConfigError(RuntimeError):
+ """Base class for configuration errors safe to show to the user."""
+
+
+class ConfigReadOnlyError(ConfigError):
+ """Raised when code tries to mutate an explicitly read-only config."""
+
+
+class ConfigSecurityError(ConfigError):
+ """Raised when a config path could redirect credential reads or writes."""
+
+
+def _reject_symlink(path: Path, label: str) -> None:
+ if path.is_symlink():
+ raise ConfigSecurityError(f"{label}不能是符号链接:{path}")
+
+
+def _atomic_write_yaml(target: Path, data: dict) -> None:
+ """Atomically replace ``target`` with owner-only YAML.
+
+ The temporary file lives beside the target so ``os.replace`` remains an
+ atomic same-filesystem operation. Existing symlinks are rejected rather
+ than followed or silently replaced.
+ """
+ _reject_symlink(target, "配置文件")
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(target.parent),
+ prefix=f".{target.name}.",
+ suffix=".tmp",
+ )
+ tmp_path = Path(tmp_name)
+ try:
+ if os.name != "nt" and hasattr(os, "fchmod"):
+ os.fchmod(fd, stat.S_IRUSR | stat.S_IWUSR)
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ yaml.safe_dump(
+ data,
+ handle,
+ default_flow_style=False,
+ allow_unicode=True,
+ )
+ handle.flush()
+ os.fsync(handle.fileno())
+
+ # Fail closed if a link appeared while serialization was in progress.
+ # A later race is still safe: os.replace replaces a directory entry and
+ # never follows the symlink into its target.
+ _reject_symlink(target, "配置文件")
+ os.replace(tmp_path, target)
+ if os.name != "nt":
+ os.chmod(target, stat.S_IRUSR | stat.S_IWUSR)
+
+ # Persist the rename where directory fsync is supported.
+ if os.name != "nt" and hasattr(os, "O_DIRECTORY"):
+ try:
+ dir_fd = os.open(target.parent, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
+ except OSError:
+ pass
+ except BaseException:
+ try:
+ tmp_path.unlink(missing_ok=True)
+ except OSError:
+ pass
+ raise
+
+
class Config:
"""Manages Agent Reach configuration."""
@@ -29,48 +101,49 @@ class Config:
"github_token": ["github_token"],
}
- def __init__(self, config_path: Optional[Path] = None):
+ def __init__(
+ self,
+ config_path: Optional[Path] = None,
+ *,
+ read_only: bool = False,
+ ):
self.config_path = Path(config_path) if config_path else self.CONFIG_FILE
self.config_dir = self.config_path.parent
+ self.read_only = read_only
self.data: dict = {}
- self._ensure_dir()
self.load()
def _ensure_dir(self):
"""Create config directory if it doesn't exist."""
+ _reject_symlink(self.config_dir, "配置目录")
make_private_dir(self.config_dir)
+ _reject_symlink(self.config_dir, "配置目录")
def load(self):
"""Load config from YAML file."""
+ _reject_symlink(self.config_dir, "配置目录")
+ _reject_symlink(self.config_path, "配置文件")
if self.config_path.exists():
- with open(self.config_path, "r", encoding="utf-8") as f:
- self.data = yaml.safe_load(f) or {}
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(self.config_path, flags)
+ except OSError as exc:
+ if self.config_path.is_symlink():
+ raise ConfigSecurityError(
+ f"配置文件不能是符号链接:{self.config_path}"
+ ) from exc
+ raise
+ with os.fdopen(fd, "r", encoding="utf-8") as handle:
+ self.data = yaml.safe_load(handle) or {}
else:
self.data = {}
def save(self):
- """Save config to YAML file."""
+ """Save config atomically, refusing mutation in read-only mode."""
+ if self.read_only:
+ raise ConfigReadOnlyError("当前配置是只读的,不能保存")
self._ensure_dir()
- # Create file with restricted permissions from the start to avoid
- # a race window where credentials are briefly world-readable.
- try:
- import stat
- fd = os.open(
- str(self.config_path),
- os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
- stat.S_IRUSR | stat.S_IWUSR, # 0o600
- )
- if os.name != "nt":
- os.chmod(self.config_path, stat.S_IRUSR | stat.S_IWUSR)
- with os.fdopen(fd, "w", encoding="utf-8") as f:
- yaml.dump(self.data, f, default_flow_style=False, allow_unicode=True)
- except OSError:
- # Fallback for Windows or other edge cases where os.open flags
- # are not fully supported.
- with open(self.config_path, "w", encoding="utf-8") as f:
- yaml.dump(self.data, f, default_flow_style=False, allow_unicode=True)
- if os.name != "nt":
- os.chmod(self.config_path, 0o600)
+ _atomic_write_yaml(self.config_path, self.data)
def get(self, key: str, default: Any = None) -> Any:
"""Get a config value. Also checks environment variables (uppercase)."""
@@ -85,13 +158,32 @@ class Config:
def set(self, key: str, value: Any):
"""Set a config value and save."""
+ if self.read_only:
+ raise ConfigReadOnlyError("当前配置是只读的,不能修改")
+ missing = object()
+ previous = self.data.get(key, missing)
self.data[key] = value
- self.save()
+ try:
+ self.save()
+ except BaseException:
+ if previous is missing:
+ self.data.pop(key, None)
+ else:
+ self.data[key] = previous
+ raise
def delete(self, key: str):
"""Delete a config key and save."""
- self.data.pop(key, None)
- self.save()
+ if self.read_only:
+ raise ConfigReadOnlyError("当前配置是只读的,不能修改")
+ missing = object()
+ previous = self.data.pop(key, missing)
+ try:
+ self.save()
+ except BaseException:
+ if previous is not missing:
+ self.data[key] = previous
+ raise
def is_configured(self, feature: str) -> bool:
"""Check if a feature has all required config."""
diff --git a/agent_reach/guides/setup-twitter.md b/agent_reach/guides/setup-twitter.md
index 880656dd..1cccdfba 100644
--- a/agent_reach/guides/setup-twitter.md
+++ b/agent_reach/guides/setup-twitter.md
@@ -42,7 +42,14 @@ twitter search "test" -n 1
agent-reach configure twitter-cookies "粘贴的 cookie JSON"
```
-这会自动提取 `auth_token` 和 `ct0`,并写入环境变量。
+这会提取 `auth_token` 和 `ct0`,安全保存到
+`~/.agent-reach/config.yaml`。之后 `agent-reach doctor` 会只把凭据注入
+自己的 `twitter status` 子进程,不会修改当前 Shell 的环境变量。
+
+`twitter` 是独立的上游命令,不会读取 Agent Reach 的配置文件。直接运行
+`twitter search/read/...` 时,需要让 twitter-cli 从浏览器登录态提取,
+或按下节在当前 Shell 设置环境变量;已经存在的环境变量优先于 Agent Reach
+保存的值。
## 手动设置 Cookie
@@ -53,8 +60,8 @@ agent-reach configure twitter-cookies "粘贴的 cookie JSON"
2. 设置环境变量:
```bash
-export AUTH_TOKEN="你的auth_token"
-export CT0="你的ct0"
+export TWITTER_AUTH_TOKEN="你的auth_token"
+export TWITTER_CT0="你的ct0"
```
3. 测试:
diff --git a/agent_reach/probe.py b/agent_reach/probe.py
index 9a66a9a0..3652d8b9 100644
--- a/agent_reach/probe.py
+++ b/agent_reach/probe.py
@@ -16,7 +16,7 @@ not just file existence.
import shutil
import subprocess
from dataclasses import dataclass
-from typing import Optional, Sequence
+from typing import Mapping, Optional, Sequence
from agent_reach.utils.process import utf8_subprocess_env
@@ -50,6 +50,8 @@ def probe_command(
timeout: int = 10,
retries: int = 0,
package: Optional[str] = None,
+ env: Optional[Mapping[str, str]] = None,
+ remove_env: Sequence[str] = (),
) -> ProbeResult:
"""Actually execute `cmd *args` and classify the result.
@@ -59,6 +61,8 @@ def probe_command(
package: pip/pipx package name used in the broken-install hint
(defaults to cmd).
+ env: values added only to the probed child process.
+ remove_env: inherited variables removed only from the child process.
"""
path = shutil.which(cmd)
if not path:
@@ -66,25 +70,38 @@ def probe_command(
last: Optional[ProbeResult] = None
for _ in range(retries + 1):
- last = _run_once(path, args, timeout, package or cmd)
+ last = _run_once(path, args, timeout, package or cmd, env, remove_env)
if last.ok:
return last
# missing/broken won't heal between retries — only transient
# failures (timeout/error) are worth a second attempt
if last.status in ("missing", "broken"):
return last
+ assert last is not None # retries + 1 always executes at least once
return last
-def _run_once(path: str, args: Sequence[str], timeout: int, package: str) -> ProbeResult:
+def _run_once(
+ path: str,
+ args: Sequence[str],
+ timeout: int,
+ package: str,
+ env: Optional[Mapping[str, str]] = None,
+ remove_env: Sequence[str] = (),
+) -> ProbeResult:
try:
+ subprocess_env = utf8_subprocess_env()
+ for key in remove_env:
+ subprocess_env.pop(key, None)
+ if env:
+ subprocess_env.update(env)
r = subprocess.run(
[path, *args],
capture_output=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
- env=utf8_subprocess_env(),
+ env=subprocess_env,
)
except FileNotFoundError:
# which() found it but exec failed: the shebang interpreter is gone
diff --git a/tests/test_channels.py b/tests/test_channels.py
index 95419633..82b58864 100644
--- a/tests/test_channels.py
+++ b/tests/test_channels.py
@@ -1211,7 +1211,13 @@ class TestLinkedInChannel:
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, "linkedin http://localhost:3000/mcp", "")
+ assert cmd[-3:] == ["config", "list", "--json"]
+ return subprocess.CompletedProcess(
+ cmd,
+ 0,
+ json.dumps({"servers": [{"name": "linkedin-scraper"}]}),
+ "",
+ )
monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.linkedin import LinkedInChannel
@@ -1220,11 +1226,40 @@ class TestLinkedInChannel:
assert status == "ok"
assert ch.active_backend == "linkedin-scraper-mcp"
+ def test_config_path_containing_linkedin_is_not_a_backend(self, monkeypatch):
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
+
+ def fake_run(cmd, **kwargs):
+ payload = {
+ "servers": [
+ {
+ "name": "unrelated",
+ "source": {
+ "path": "/tmp/linkedin-project/config/mcporter.json",
+ },
+ }
+ ]
+ }
+ return subprocess.CompletedProcess(cmd, 0, json.dumps(payload), "")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ from agent_reach.channels.linkedin import LinkedInChannel
+
+ ch = LinkedInChannel()
+ status, _ = ch.check()
+ assert status == "off"
+ assert ch.active_backend is None
+
def test_off_without_backend_when_linkedin_not_configured(self, monkeypatch):
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, "exa https://mcp.exa.ai/mcp", "")
+ return subprocess.CompletedProcess(
+ cmd,
+ 0,
+ json.dumps({"servers": [{"name": "exa"}]}),
+ "",
+ )
monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.linkedin import LinkedInChannel
@@ -1254,7 +1289,13 @@ class TestExaSearchChannel:
monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
def fake_run(cmd, **kwargs):
- return subprocess.CompletedProcess(cmd, 0, "exa https://mcp.exa.ai/mcp", "")
+ assert cmd[-3:] == ["config", "list", "--json"]
+ return subprocess.CompletedProcess(
+ cmd,
+ 0,
+ json.dumps({"servers": [{"name": "exa"}]}),
+ "",
+ )
monkeypatch.setattr(subprocess, "run", fake_run)
from agent_reach.channels.exa_search import ExaSearchChannel
@@ -1263,6 +1304,52 @@ class TestExaSearchChannel:
assert status == "ok"
assert ch.active_backend == "Exa via mcporter"
+ def test_config_path_containing_exa_is_not_a_backend(self, monkeypatch):
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
+
+ def fake_run(cmd, **kwargs):
+ payload = {
+ "servers": [
+ {
+ "name": "unrelated",
+ "source": {
+ "path": "/tmp/example-project/config/mcporter.json",
+ },
+ }
+ ]
+ }
+ return subprocess.CompletedProcess(cmd, 0, json.dumps(payload), "")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ from agent_reach.channels.exa_search import ExaSearchChannel
+
+ ch = ExaSearchChannel()
+ status, _ = ch.check()
+ assert status == "off"
+ assert ch.active_backend is None
+
+ def test_invalid_mcporter_json_is_reported_as_error_not_unconfigured(
+ self, monkeypatch
+ ):
+ monkeypatch.setattr(shutil, "which", lambda _: "/usr/local/bin/mcporter")
+ monkeypatch.setattr(
+ subprocess,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(
+ cmd,
+ 0,
+ "Project config: /tmp/example/config/mcporter.json",
+ "",
+ ),
+ )
+ from agent_reach.channels.exa_search import ExaSearchChannel
+
+ ch = ExaSearchChannel()
+ status, message = ch.check()
+ assert status == "error"
+ assert "JSON" in message
+ assert ch.active_backend is None
+
class TestXiaoyuzhouChannel:
def test_reports_error_with_reinstall_hint_when_ffmpeg_broken(self, monkeypatch):
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 86790775..ddcdf41c 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -30,13 +30,30 @@ class TestCLI:
assert exc_info.value.code == 0
def test_doctor_runs(self, capsys):
- with patch("sys.argv", ["agent-reach", "doctor"]):
+ with patch(
+ "agent_reach.doctor.check_all",
+ return_value={
+ "web": {
+ "status": "ok",
+ "name": "网页",
+ "message": "可用",
+ "tier": 0,
+ "backends": ["Jina Reader"],
+ "active_backend": "Jina Reader",
+ }
+ },
+ ), patch(
+ "agent_reach.doctor.format_report",
+ return_value="Agent Reach\n✅ 网页可用",
+ ), patch("sys.argv", ["agent-reach", "doctor"]):
main()
captured = capsys.readouterr()
assert "Agent Reach" in captured.out
assert "✅" in captured.out
- def test_doctor_never_touches_existing_skill_install(self, monkeypatch, tmp_path, capsys):
+ def test_doctor_is_read_only_and_never_installs_skill(
+ self, monkeypatch, tmp_path, capsys
+ ):
skill_dir = tmp_path / ".agents" / "skills" / "agent-reach"
skill_dir.mkdir(parents=True)
skill_file = skill_dir / "SKILL.md"
@@ -53,14 +70,23 @@ class TestCLI:
monkeypatch.setattr(Config, "CONFIG_FILE", config_dir / "config.yaml")
monkeypatch.setattr("agent_reach.doctor.check_all", lambda config: {})
monkeypatch.setattr("agent_reach.doctor.format_report", lambda results: "report")
+ install_calls = []
+ monkeypatch.setattr(
+ cli,
+ "_install_skill",
+ lambda *args, **kwargs: install_calls.append((args, kwargs)),
+ )
cli._cmd_doctor(Namespace(json=False))
assert skill_file.read_text(encoding="utf-8") == custom_content
+ assert install_calls == []
+ assert not config_dir.exists()
out = capsys.readouterr().out
assert "report" in out
assert "Skill installed" not in out
assert "preserving existing files" not in out
+ assert f"Skill installed for Agent: {skill_dir}" not in out
def test_transcribe_command_prints_text(self, capsys):
with patch("agent_reach.transcribe.transcribe", return_value="hello transcript"):
@@ -89,6 +115,35 @@ class TestCLI:
assert auth_token == "token123"
assert ct0 == "ct0abc"
+ def test_twitter_config_verification_preserves_existing_env_priority(
+ self, monkeypatch, capsys
+ ):
+ monkeypatch.setenv("TWITTER_AUTH_TOKEN", "shell-auth")
+ monkeypatch.setenv("TWITTER_CT0", "shell-ct0")
+ monkeypatch.setattr(shutil, "which", lambda name: "/bin/twitter")
+ calls = []
+
+ def fake_run(cmd, **kwargs):
+ calls.append((cmd, kwargs))
+ return subprocess.CompletedProcess(cmd, 0, "ok: true\n", "")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+
+ cli._cmd_configure(
+ Namespace(
+ from_browser=None,
+ key="twitter-cookies",
+ value=["saved-auth", "saved-ct0"],
+ )
+ )
+
+ child_env = calls[0][1]["env"]
+ assert child_env["TWITTER_AUTH_TOKEN"] == "shell-auth"
+ assert child_env["TWITTER_CT0"] == "shell-ct0"
+ assert cli.os.environ["TWITTER_AUTH_TOKEN"] == "shell-auth"
+ assert cli.os.environ["TWITTER_CT0"] == "shell-ct0"
+ assert "Twitter access works" in capsys.readouterr().out
+
def test_install_rdt_cli_prefers_github_source(self, monkeypatch, capsys):
state = {"rdt_installed": False}
commands = []
diff --git a/tests/test_config.py b/tests/test_config.py
index 9fe6f196..3ecfa1ff 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -3,7 +3,7 @@
import pytest
-from agent_reach.config import Config
+from agent_reach.config import Config, ConfigReadOnlyError, ConfigSecurityError
@pytest.fixture
@@ -14,10 +14,20 @@ def tmp_config(tmp_path):
class TestConfig:
- def test_init_creates_dir(self, tmp_path):
+ def test_init_is_read_only_on_disk_until_first_save(self, tmp_path):
config_file = tmp_path / "subdir" / "config.yaml"
Config(config_path=config_file)
- assert config_file.parent.exists()
+ assert not config_file.parent.exists()
+
+ def test_read_only_config_never_creates_or_changes_files(self, tmp_path):
+ config_file = tmp_path / "subdir" / "config.yaml"
+ config = Config(config_path=config_file, read_only=True)
+
+ assert config.get("missing") is None
+ assert not config_file.parent.exists()
+ with pytest.raises(ConfigReadOnlyError):
+ config.set("secret", "value")
+ assert not config_file.parent.exists()
def test_set_and_get(self, tmp_config):
tmp_config.set("test_key", "test_value")
@@ -125,7 +135,8 @@ class TestConfig:
import sys
config_file = tmp_path / "private" / "config.yaml"
- Config(config_path=config_file)
+ config = Config(config_path=config_file)
+ config.set("key", "value")
if sys.platform != "win32":
mode = config_file.parent.stat().st_mode
@@ -133,3 +144,84 @@ class TestConfig:
assert not (mode & stat.S_IXGRP), "group execute should not be set"
assert not (mode & stat.S_IROTH), "other read should not be set"
assert not (mode & stat.S_IXOTH), "other execute should not be set"
+
+ def test_load_refuses_symlink_config_path(self, tmp_path):
+ victim = tmp_path / "victim.yaml"
+ victim.write_text("secret: victim-data\n", encoding="utf-8")
+ config_file = tmp_path / "config.yaml"
+ try:
+ config_file.symlink_to(victim)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+
+ with pytest.raises(ConfigSecurityError, match="符号链接"):
+ Config(config_path=config_file)
+ assert victim.read_text(encoding="utf-8") == "secret: victim-data\n"
+
+ def test_save_refuses_symlink_inserted_after_load(self, tmp_path):
+ victim = tmp_path / "victim.yaml"
+ victim.write_text("secret: victim-data\n", encoding="utf-8")
+ config_file = tmp_path / "config.yaml"
+ config = Config(config_path=config_file)
+ try:
+ config_file.symlink_to(victim)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+
+ with pytest.raises(ConfigSecurityError, match="符号链接"):
+ config.set("secret", "new-data")
+
+ assert config_file.is_symlink()
+ assert victim.read_text(encoding="utf-8") == "secret: victim-data\n"
+
+ def test_config_directory_symlink_is_rejected(self, tmp_path):
+ real_dir = tmp_path / "real"
+ real_dir.mkdir()
+ linked_dir = tmp_path / "linked"
+ try:
+ linked_dir.symlink_to(real_dir, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+
+ with pytest.raises(ConfigSecurityError, match="配置目录"):
+ Config(config_path=linked_dir / "config.yaml")
+ assert list(real_dir.iterdir()) == []
+
+ def test_save_preserves_previous_file_on_serialization_failure(
+ self, tmp_path, monkeypatch
+ ):
+ config_file = tmp_path / "config.yaml"
+ config = Config(config_path=config_file)
+ config.set("keep_key", "keep_value")
+ previous = config_file.read_bytes()
+
+ def fail_dump(*args, **kwargs):
+ raise RuntimeError("simulated write failure")
+
+ monkeypatch.setattr("agent_reach.config.yaml.safe_dump", fail_dump)
+ with pytest.raises(RuntimeError, match="simulated"):
+ config.set("new_key", "new_value")
+
+ assert config_file.read_bytes() == previous
+ assert config.get("new_key") is None
+ assert list(tmp_path.glob(".config.yaml.*.tmp")) == []
+
+ def test_atomic_temp_file_is_created_next_to_custom_config_path(
+ self, tmp_path, monkeypatch
+ ):
+ import tempfile
+
+ config_file = tmp_path / "custom" / "nested" / "settings.yaml"
+ config = Config(config_path=config_file)
+ observed = {}
+ real_mkstemp = tempfile.mkstemp
+
+ def spy_mkstemp(*args, **kwargs):
+ observed["dir"] = kwargs.get("dir")
+ return real_mkstemp(*args, **kwargs)
+
+ monkeypatch.setattr("agent_reach.config.tempfile.mkstemp", spy_mkstemp)
+ config.set("key", "value")
+
+ assert observed["dir"] == str(config_file.parent)
+ assert config_file.read_text(encoding="utf-8") == "key: value\n"
diff --git a/tests/test_home_isolation.py b/tests/test_home_isolation.py
new file mode 100644
index 00000000..c572c97d
--- /dev/null
+++ b/tests/test_home_isolation.py
@@ -0,0 +1,36 @@
+# -*- coding: utf-8 -*-
+"""Regression guards for test-suite and Doctor filesystem isolation."""
+
+import os
+from argparse import Namespace
+from pathlib import Path
+
+import agent_reach.cli as cli
+from agent_reach.config import Config
+
+
+def test_runtime_home_and_config_are_inside_test_sandbox(isolated_home):
+ assert Path.home() == isolated_home
+ assert Path(os.path.expanduser("~")) == isolated_home
+ assert Config.CONFIG_DIR.is_relative_to(isolated_home)
+ assert Config.CONFIG_FILE.is_relative_to(isolated_home)
+
+
+def test_doctor_leaves_sandbox_home_unchanged(
+ isolated_home, monkeypatch, capsys
+):
+ """If Doctor is truly read-only, even the sandbox remains empty."""
+ monkeypatch.setattr("agent_reach.doctor.check_all", lambda config: {})
+ monkeypatch.setattr("agent_reach.doctor.format_report", lambda results: "report")
+ monkeypatch.setattr(
+ cli,
+ "_install_skill",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("doctor must not install skills")
+ ),
+ )
+
+ cli._cmd_doctor(Namespace(json=False))
+
+ assert capsys.readouterr().out.strip() == "report"
+ assert list(isolated_home.iterdir()) == []
diff --git a/tests/test_opencli_backend.py b/tests/test_opencli_backend.py
index 3714ecc2..92709180 100644
--- a/tests/test_opencli_backend.py
+++ b/tests/test_opencli_backend.py
@@ -4,10 +4,20 @@
from unittest.mock import patch
from agent_reach.backends import opencli_status, opencli_summary
+from agent_reach.backends.opencli import (
+ OPENCLI_EXTENSION_ID,
+ _extension_installed_on_disk,
+ _unpacked_extension_files_present,
+)
from agent_reach.probe import ProbeResult
-def _status_with(version_probe, daemon_probe=None, ext_on_disk=False):
+def _status_with(
+ version_probe,
+ daemon_probe=None,
+ ext_on_disk=False,
+ unpacked_files=False,
+):
"""Run opencli_status with probe_command and disk check patched."""
calls = []
@@ -21,6 +31,10 @@ def _status_with(version_probe, daemon_probe=None, ext_on_disk=False):
patch(
"agent_reach.backends.opencli._extension_installed_on_disk",
return_value=ext_on_disk,
+ ), \
+ patch(
+ "agent_reach.backends.opencli._unpacked_extension_files_present",
+ return_value=unpacked_files,
):
return opencli_status(), calls
@@ -62,9 +76,8 @@ def test_extension_never_installed_not_ready_with_store_guide():
assert "chromewebstore.google.com" in st.hint
-def test_sleeping_extension_counts_as_ready():
- """实测:扩展 service worker 睡眠时 daemon status 报 disconnected,
- 但任何真实命令会唤醒它——装在磁盘上即视为可用。"""
+def test_extension_files_on_disk_are_not_reported_as_loaded_or_ready():
+ """A disabled/stale extension leaves files behind, so disk != loaded."""
daemon_out = "Daemon: running (PID 1)\nExtension: disconnected\n"
st, _ = _status_with(
ProbeResult("ok", output="1.8.3"),
@@ -73,9 +86,23 @@ def test_sleeping_extension_counts_as_ready():
)
assert not st.extension_connected
assert st.extension_installed
- assert st.ready
- assert "唤醒" in opencli_summary(st)
- assert st.hint == ""
+ assert not st.ready
+ assert "可用" not in opencli_summary(st)
+ assert "无法确认" in st.hint
+
+
+def test_unpacked_source_files_are_not_reported_as_loaded_or_ready():
+ daemon_out = "Daemon: running (PID 1)\nExtension: disconnected\n"
+ st, _ = _status_with(
+ ProbeResult("ok", output="1.8.3"),
+ ProbeResult("ok", output=daemon_out),
+ unpacked_files=True,
+ )
+ assert st.unpacked_extension_files
+ assert not st.extension_connected
+ assert not st.ready
+ assert "不代表" in st.hint
+ assert "可用" not in opencli_summary(st)
def test_daemon_not_running_parsed_correctly():
@@ -98,3 +125,71 @@ def test_probe_uses_daemon_status_not_doctor():
)
assert ["daemon", "status"] in calls
assert ["doctor"] not in calls
+
+
+def test_opencli_probes_strip_deprecated_app_env_only_from_children(monkeypatch):
+ """OpenCLIApp can inject a variable that makes every CLI command exit 78.
+
+ Agent Reach must remove it from both read-only child probes without
+ mutating the desktop app's parent environment.
+ """
+ monkeypatch.setenv("OPENCLI_DAEMON_PORT", "19825")
+ calls = []
+
+ def fake_probe(cmd, args=("--version",), **kwargs):
+ calls.append((list(args), tuple(kwargs.get("remove_env", ()))))
+ if "OPENCLI_DAEMON_PORT" not in kwargs.get("remove_env", ()):
+ return ProbeResult(
+ "error",
+ output="OPENCLI_DAEMON_PORT is no longer supported",
+ )
+ if list(args) == ["--version"]:
+ return ProbeResult("ok", output="1.8.6")
+ return ProbeResult("ok", output="Daemon: not running\n")
+
+ with patch("agent_reach.backends.opencli.probe_command", side_effect=fake_probe), patch(
+ "agent_reach.backends.opencli._extension_installed_on_disk",
+ return_value=False,
+ ):
+ status = opencli_status()
+
+ assert status.installed and not status.broken
+ assert calls == [
+ (["--version"], ("OPENCLI_DAEMON_PORT",)),
+ (["daemon", "status"], ("OPENCLI_DAEMON_PORT",)),
+ ]
+ assert "OPENCLI_DAEMON_PORT" in __import__("os").environ
+
+
+def test_store_install_scan_includes_edge_profiles(tmp_path, monkeypatch):
+ edge_root = tmp_path / "Microsoft Edge"
+ (
+ edge_root
+ / "Default"
+ / "Extensions"
+ / OPENCLI_EXTENSION_ID
+ / "1.0.0"
+ ).mkdir(parents=True)
+
+ monkeypatch.setattr(
+ "agent_reach.backends.opencli._CHROME_PROFILE_ROOTS",
+ (str(edge_root),),
+ )
+ monkeypatch.delenv("LOCALAPPDATA", raising=False)
+
+ assert _extension_installed_on_disk()
+
+
+def test_unpacked_scan_requires_manifest_but_does_not_claim_browser_load(
+ tmp_path, monkeypatch
+):
+ unpacked = tmp_path / ".opencli" / "extension"
+ unpacked.mkdir(parents=True)
+ monkeypatch.setattr(
+ "agent_reach.backends.opencli._OPENCLI_UNPACKED_EXTENSION",
+ str(unpacked),
+ )
+
+ assert not _unpacked_extension_files_present()
+ (unpacked / "manifest.json").write_text('{"name": "OpenCLI"}', encoding="utf-8")
+ assert _unpacked_extension_files_present()
diff --git a/tests/test_probe.py b/tests/test_probe.py
index f1a673f8..ac8e2d9c 100644
--- a/tests/test_probe.py
+++ b/tests/test_probe.py
@@ -7,7 +7,7 @@ import sys
import pytest
-from agent_reach.probe import ProbeResult, probe_command, reinstall_hint
+from agent_reach.probe import probe_command, reinstall_hint
def _make_executable(path, content):
@@ -25,7 +25,7 @@ def test_missing_command():
@pytest.mark.skipif(sys.platform == "win32", reason="shebang semantics are POSIX-only")
def test_broken_shebang_detected_as_broken(tmp_path, monkeypatch):
"""A stale venv shim: which() finds it, exec raises FileNotFoundError."""
- script = _make_executable(
+ _make_executable(
tmp_path / "stale-tool", "#!/nonexistent/venv/bin/python\nprint('hi')\n"
)
monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ.get("PATH", ""))
@@ -38,7 +38,7 @@ def test_broken_shebang_detected_as_broken(tmp_path, monkeypatch):
@pytest.mark.skipif(sys.platform == "win32", reason="shell script fixture is POSIX-only")
def test_healthy_command_returns_ok_with_output(tmp_path, monkeypatch):
- script = _make_executable(
+ _make_executable(
tmp_path / "healthy-tool", "#!/bin/sh\necho 'healthy-tool 1.2.3'\n"
)
monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ.get("PATH", ""))
@@ -48,9 +48,34 @@ def test_healthy_command_returns_ok_with_output(tmp_path, monkeypatch):
assert "1.2.3" in r.output
[email protected](sys.platform == "win32", reason="shell script fixture is POSIX-only")
+def test_probe_child_env_can_add_and_remove_without_mutating_parent(tmp_path, monkeypatch):
+ _make_executable(
+ tmp_path / "env-tool",
+ (
+ "#!/bin/sh\n"
+ 'if [ -n "${BLOCKED_APP_VAR+x}" ]; then exit 78; fi\n'
+ 'echo "$PROBE_ONLY_VALUE"\n'
+ ),
+ )
+ monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ.get("PATH", ""))
+ monkeypatch.setenv("BLOCKED_APP_VAR", "inherited")
+
+ result = probe_command(
+ "env-tool",
+ env={"PROBE_ONLY_VALUE": "child-only"},
+ remove_env=("BLOCKED_APP_VAR",),
+ )
+
+ assert result.ok
+ assert result.output == "child-only"
+ assert os.environ["BLOCKED_APP_VAR"] == "inherited"
+ assert "PROBE_ONLY_VALUE" not in os.environ
+
+
@pytest.mark.skipif(sys.platform == "win32", reason="shell script fixture is POSIX-only")
def test_nonzero_exit_classified_as_error(tmp_path, monkeypatch):
- script = _make_executable(
+ _make_executable(
tmp_path / "failing-tool", "#!/bin/sh\necho 'boom' >&2\nexit 3\n"
)
monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ.get("PATH", ""))
@@ -62,7 +87,7 @@ def test_nonzero_exit_classified_as_error(tmp_path, monkeypatch):
@pytest.mark.skipif(sys.platform == "win32", reason="shell script fixture is POSIX-only")
def test_exit_127_classified_as_broken(tmp_path, monkeypatch):
- script = _make_executable(tmp_path / "wrapper-tool", "#!/bin/sh\nexit 127\n")
+ _make_executable(tmp_path / "wrapper-tool", "#!/bin/sh\nexit 127\n")
monkeypatch.setenv("PATH", str(tmp_path) + os.pathsep + os.environ.get("PATH", ""))
r = probe_command("wrapper-tool", package="wrapper-pkg")
@@ -74,7 +99,7 @@ def test_exit_127_classified_as_broken(tmp_path, monkeypatch):
def test_retries_help_transient_failures(tmp_path, monkeypatch):
"""First call fails (exit 1), second succeeds — retries=1 should return ok."""
marker = tmp_path / "ran-once"
- script = _make_executable(
+ _make_executable(
tmp_path / "flaky-tool",
f"#!/bin/sh\nif [ -f {marker} ]; then echo ok; exit 0; fi\ntouch {marker}\nexit 1\n",
)
diff --git a/tests/test_twitter_channel.py b/tests/test_twitter_channel.py
index 0670a212..b77d26e8 100644
--- a/tests/test_twitter_channel.py
+++ b/tests/test_twitter_channel.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
-from unittest.mock import patch, Mock
+import os
+from unittest.mock import Mock, patch
from agent_reach.channels.twitter import TwitterChannel
@@ -29,6 +30,61 @@ def test_check_twitter_cli_found_and_auth_ok():
assert channel.active_backend == "twitter-cli"
+def test_check_uses_credentials_saved_by_agent_reach_only_in_child_env(monkeypatch):
+ """Saved cookies must make the independent doctor probe authenticated."""
+ channel = TwitterChannel()
+ config = Mock()
+ config.get.side_effect = lambda key: {
+ "twitter_auth_token": "saved-auth-token",
+ "twitter_ct0": "saved-ct0",
+ }.get(key)
+ monkeypatch.delenv("TWITTER_AUTH_TOKEN", raising=False)
+ monkeypatch.delenv("TWITTER_CT0", raising=False)
+
+ with patch(
+ "shutil.which",
+ side_effect=lambda name: "/usr/local/bin/twitter" if name == "twitter" else None,
+ ), patch(
+ "subprocess.run",
+ return_value=_cp(stdout="ok: true\n", returncode=0),
+ ) as run:
+ status, _ = channel.check(config)
+
+ child_env = run.call_args.kwargs["env"]
+ assert status == "ok"
+ assert child_env["TWITTER_AUTH_TOKEN"] == "saved-auth-token"
+ assert child_env["TWITTER_CT0"] == "saved-ct0"
+ assert "TWITTER_AUTH_TOKEN" not in os.environ
+ assert "TWITTER_CT0" not in os.environ
+
+
+def test_existing_twitter_env_takes_priority_over_saved_config(monkeypatch):
+ channel = TwitterChannel()
+ config = Mock()
+ config.get.side_effect = lambda key: {
+ "twitter_auth_token": "saved-auth-token",
+ "twitter_ct0": "saved-ct0",
+ }.get(key)
+ monkeypatch.setenv("TWITTER_AUTH_TOKEN", "shell-auth-token")
+ monkeypatch.setenv("TWITTER_CT0", "shell-ct0")
+
+ with patch(
+ "shutil.which",
+ side_effect=lambda name: "/usr/local/bin/twitter" if name == "twitter" else None,
+ ), patch(
+ "subprocess.run",
+ return_value=_cp(stdout="ok: true\n", returncode=0),
+ ) as run:
+ status, _ = channel.check(config)
+
+ child_env = run.call_args.kwargs["env"]
+ assert status == "ok"
+ assert child_env["TWITTER_AUTH_TOKEN"] == "shell-auth-token"
+ assert child_env["TWITTER_CT0"] == "shell-ct0"
+ assert os.environ["TWITTER_AUTH_TOKEN"] == "shell-auth-token"
+ assert os.environ["TWITTER_CT0"] == "shell-ct0"
+
+
def test_check_twitter_cli_found_auth_missing():
"""twitter-cli found + not_authenticated → warn about auth."""
channel = TwitterChannel()