Skip to content

The agent that grows with you

feat: suppress rules skills and memory readers in private safe workers

Teknium25cda66a8bff
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 30157f735ff..535eb47940b 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1239,6 +1239,11 @@ def _init_memory(agent, _agent_cfg, skip_memory, platform):
agent._memory_nudge_interval = 10
agent._turns_since_memory = 0
agent._iters_since_skill = 0
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ agent._memory_manager = None
+ return
# skip_memory skips the external *provider*; enabled_toolsets=["memory"] still gets the
# built-in store so the memory tool never sees store=None.
# Flush/background agents can still pass enabled_toolsets=["memory"] so the built-in file store exists
@@ -1746,6 +1751,10 @@ def _resolve_context_length(agent, _agent_cfg, base_url):
def _select_context_engine(_agent_cfg):
"""Config-driven context engine: ``context.engine`` → plugins/context_engine/<name>/ →
general plugin system → None (built-in ContextCompressor)."""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return None
_engine_name = "compressor"
with suppress(Exception):
_ctx_cfg = _agent_cfg.get("context", {}) if isinstance(_agent_cfg, dict) else {}
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py
index f7f6956f344..cb42a380ed2 100644
--- a/agent/prompt_builder.py
+++ b/agent/prompt_builder.py
@@ -1203,6 +1203,10 @@ def build_skills_system_prompt(
``skills_dir_override`` makes home resolution EXPLICIT: a build thread that never bound the HERMES_HOME
ContextVar would otherwise leak the default profile's skills into a bot's prompt.
"""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return ""
_home_token = None
if skills_dir_override is not None:
skills_dir = Path(skills_dir_override)
@@ -1448,6 +1452,10 @@ def load_soul_md(context_length: Optional[int] = None, home_override: "Path | No
ContextVar falls back to the launch home and reads the wrong profile's SOUL.md (#50233, same class as
the skills-index leak fixed in #86313).
"""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return None
try:
from hermes_cli.config import ensure_hermes_home
ensure_hermes_home()
@@ -1579,6 +1587,10 @@ def build_context_files_prompt(
AGENTS.md chain (git root → cwd) → CLAUDE.md (cwd) → .cursorrules + .cursor/rules/*.mdc (cwd). SOUL.md
from HERMES_HOME is independent and always included unless *skip_soul* (already the identity slot).
"""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return ""
cwd_path = Path(cwd if cwd is not None else os.getcwd()).resolve()
# A FALLBACK-picked cwd inside the Hermes install tree must not gain system-prompt authority (the desktop
# default would load this repo's contributor AGENTS.md). An explicit cwd is honored verbatim.
diff --git a/agent/skill_commands.py b/agent/skill_commands.py
index 6a09f774c00..c612fd1b820 100644
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@ -151,6 +151,10 @@ def _resolve_skill_commands_home() -> str:
def _load_skill_payload(skill_identifier: str, task_id: str | None = None) -> tuple[dict[str, Any], Path | None, str] | None:
"""Load a skill by name/path and return (loaded_payload, skill_dir, display_name)."""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return None
raw_identifier = (skill_identifier or "").strip()
if not raw_identifier:
return None
@@ -365,6 +369,10 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
Builds a local map and publishes once at the end: writing straight into the
global exposed partial results to overlapping scans, which then logged
bogus "already claimed" collisions against their own incumbents."""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return {}
global _skill_commands, _skill_commands_platform, _skill_commands_home
platform = _resolve_skill_commands_platform()
home = _resolve_skill_commands_home()
@@ -421,6 +429,10 @@ def get_skill_commands() -> Dict[str, Dict[str, Any]]:
See #14536, #88023.
"""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return {}
current_platform = _resolve_skill_commands_platform()
current_home = _resolve_skill_commands_home()
with _publish_lock:
@@ -583,6 +595,10 @@ def build_preloaded_skills_prompt(skill_identifiers: list[str], task_id: str | N
``_load_skill_payload``, bypassing ``get_skill_commands()``'s scan-time disabled filter — mirrors the
bundle-invocation gate (#59156).
"""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return "", [], list(skill_identifiers)
loaded_names, missing, _disabled, prompt_parts = _load_skill_blocks(
[(raw or "").strip() for raw in skill_identifiers],
lambda identifier: _load_skill_payload(identifier, task_id=task_id),
diff --git a/agent/subdirectory_hints.py b/agent/subdirectory_hints.py
index 68512719cb1..ce7eef0ff22 100644
--- a/agent/subdirectory_hints.py
+++ b/agent/subdirectory_hints.py
@@ -40,6 +40,10 @@ def _digest(content: str) -> str:
def _first_hint_file(directory: Path):
"""``(path, stripped content)`` of the first readable non-empty hint file
in *directory* (priority order), or None. Unreadable files are skipped."""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return None
for filename in _HINT_FILENAMES:
candidate = directory / filename
try:
@@ -73,6 +77,10 @@ class SubdirectoryHintTracker:
def check_tool_call(self, tool_name: str, tool_args: Dict[str, Any]) -> Optional[str]:
"""Return formatted hint text for newly visited directories, or None."""
+ from agent.safe_worker_policy import safe_worker_enabled
+
+ if safe_worker_enabled():
+ return None
all_hints = [h for d in self._extract_directories(tool_name, tool_args) if (h := self._load_hints_for_directory(d))]
return "\n\n" + "\n\n".join(all_hints) if all_hints else None
diff --git a/tests/agent/test_safe_worker_policy.py b/tests/agent/test_safe_worker_policy.py
index cd555344123..b5ec89ffe76 100644
--- a/tests/agent/test_safe_worker_policy.py
+++ b/tests/agent/test_safe_worker_policy.py
@@ -16,9 +16,12 @@ def run_worker(tmp_path, body, mode="safe"):
env = dict(os.environ, HERMES_HOME=str(home), HOME=str(home), PROBE_MODE=mode)
for key in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG", "HERMES_IGNORE_RULES"):
env.pop(key, None)
+ root = Path(__file__).resolve().parents[2]
+ script = home / "worker_probe.py"
+ script.write_text(f"import sys; sys.path.insert(0, {str(root)!r})\n" + textwrap.dedent(body))
result = subprocess.run(
- [sys.executable, "-c", textwrap.dedent(body)], env=env,
- cwd=Path(__file__).resolve().parents[2], stdin=subprocess.DEVNULL,
+ [sys.executable, str(script)], env=env,
+ cwd=root, stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=45,
)
assert result.returncode == 0, result.stdout + result.stderr
@@ -159,3 +162,60 @@ def test_safe_worker_never_discovers_or_invokes_customizations(tmp_path, mode):
else:
assert {"plugin-import", "plugin-register", "plugin-hook", "model-providers/nested", "flat", "direct-hook", "middleware", "observer", "shell", "outbound"} <= set(result["events"])
assert result["reads"] and result["injected"]
+
+
[email protected]("mode", ["safe", "config", "ordinary"])
+def test_safe_worker_bypasses_rule_readers_even_without_cli_flags(tmp_path, mode):
+ result = run_worker(tmp_path, r"""
+ import json, os, sys
+ from pathlib import Path
+ mode = os.environ["PROBE_MODE"]
+ home = Path(os.environ["HERMES_HOME"])
+ project = home / "project"; project.mkdir()
+ (project / "AGENTS.md").write_text("PROJECT_SENTINEL")
+ sub = project / "sub"; sub.mkdir()
+ (sub / "AGENTS.md").write_text("SUB_SENTINEL")
+ (home / "SOUL.md").write_text("SOUL_SENTINEL")
+ mem = home / "memories"; mem.mkdir()
+ (mem / "MEMORY.md").write_text("MEMORY_SENTINEL")
+ skill = home / "skills" / "probe"; skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: probe\ndescription: SKILL_SENTINEL\n---\nSKILL_SENTINEL\n")
+ if mode != "ordinary":
+ from agent.safe_worker_policy import _bind_safe_worker_policy
+ _bind_safe_worker_policy(safe_mode=mode == "safe", ignore_user_config=True, config={})
+ reads = []
+ selected = {"SOUL.md", "AGENTS.md", "MEMORY.md", "USER.md", "SKILL.md"}
+ def audit(event, args):
+ if event == "open" and Path(str(args[0])).name in selected and args[1] != "w":
+ reads.append(Path(str(args[0])).name)
+ sys.addaudithook(audit)
+ from agent.prompt_builder import build_context_files_prompt, load_soul_md, build_skills_system_prompt
+ from agent.skill_commands import build_preloaded_skills_prompt
+ from agent.subdirectory_hints import SubdirectoryHintTracker
+ context = build_context_files_prompt(cwd=str(project))
+ soul = load_soul_md()
+ skills = build_skills_system_prompt()
+ preloaded = build_preloaded_skills_prompt(["probe"])
+ hints = SubdirectoryHintTracker(str(project)).check_tool_call("read_file", {"path": str(sub / "file.py")})
+ from agent.agent_init import _init_memory, _select_context_engine
+ from types import SimpleNamespace
+ agent = SimpleNamespace(enabled_toolsets=["memory"], disabled_toolsets=[])
+ _init_memory(agent, {"memory": {"memory_enabled": True, "user_profile_enabled": True}}, False, "cli")
+ # Explicit custom-engine selection must not escape the process policy.
+ import plugins.context_engine
+ engines = []
+ plugins.context_engine.load_context_engine = lambda name: engines.append(name)
+ _select_context_engine({"context": {"engine": "sentinel"}})
+ print(json.dumps({"context": context, "soul": soul, "skills": skills,
+ "preloaded": preloaded, "hints": hints, "reads": reads, "engines": engines,
+ "memory": agent._memory_store is not None}))
+ """, mode)
+ if mode == "safe":
+ assert result == {"context": "", "soul": None, "skills": "", "preloaded": ["", [], ["probe"]],
+ "hints": None, "reads": [], "engines": [], "memory": False}
+ else:
+ assert "PROJECT_SENTINEL" in result["context"] and "SOUL_SENTINEL" in result["soul"]
+ assert "SKILL_SENTINEL" in result["skills"] and "SKILL_SENTINEL" in result["preloaded"][0]
+ assert "SUB_SENTINEL" in result["hints"]
+ assert {"AGENTS.md", "SOUL.md", "SKILL.md", "MEMORY.md"} <= set(result["reads"])
+ assert result["engines"] == ["sentinel"] and result["memory"]