Skip to content

The agent that grows with you

fix(agent): scope background review memory access to its trigger (#105921)

liuhao10241571f502a991
diff --git a/agent/background_review.py b/agent/background_review.py
index 34eb6f29d41..d409762884e 100644
--- a/agent/background_review.py
+++ b/agent/background_review.py
@@ -952,14 +952,17 @@ def _track_review_fork(agent: Any, review_agent: Any, *, register: bool) -> None
agent._active_children.remove(review_agent)
-def _review_tool_whitelist(review_agent: Any, task_cfg: Optional[Dict[str, Any]]) -> Tuple[set, set]:
+def _review_tool_whitelist(
+ review_agent: Any, task_cfg: Optional[Dict[str, Any]], review_memory: bool = False,
+) -> Tuple[set, set]:
"""``(whitelist, configured_extra_tools)`` for the review fork — DISPATCH-side only, so the
advertised ``tools[]`` stays byte-identical to the parent's (prompt-cache parity)."""
from model_tools import get_tool_definitions
- # Gate the built-in memory tool on the profile's memory flags so a memory-disabled profile
- # is never contaminated by the review LLM.
+ # Gate the built-in memory tool on BOTH the profile's memory flags and the trigger that fired
+ # (#105921): a skill-nudge review never gets the memory tool, so an unattended fork cannot
+ # act on the memory tool's "consolidate now" hint and delete entries no one reviewed.
memory_on = review_agent._memory_enabled or review_agent._user_profile_enabled
- review_toolsets = ["memory", "skills"] if memory_on else ["skills"]
+ review_toolsets = ["memory", "skills"] if memory_on and review_memory else ["skills"]
whitelist = {t["function"]["name"] for t in get_tool_definitions(enabled_toolsets=review_toolsets, quiet_mode=True)}
# Read-only file tools: denying read_file/search_files caused a per-review denial storm that
# starved the loop (read_file also registers the read with the read-before-write guard).
@@ -1010,7 +1013,7 @@ def _release_fork_clients(review_agent: Any) -> None:
def _run_review_fork(
agent: Any, messages_snapshot: List[Dict], prompt: str, task_cfg: Optional[Dict[str, Any]],
- review_run: Optional[_BackgroundReviewRun], st: _ReviewForkState,
+ review_run: Optional[_BackgroundReviewRun], st: _ReviewForkState, review_memory: bool = False,
) -> None:
"""Fork phase (inside thread-scoped silence): build the fork, run the prompt under the tool
whitelist, snapshot its messages/usage, release its clients. Partial progress lands on ``st``
@@ -1018,17 +1021,21 @@ def _run_review_fork(
st.review_agent, _rt, _routed = build_cache_parity_fork(agent, task_cfg, max_iterations=_REVIEW_MAX_ITERATIONS)
_track_review_fork(agent, st.review_agent, register=True)
from hermes_cli.plugins import set_thread_tool_whitelist, clear_thread_tool_whitelist
- review_whitelist, configured_extra_tools = _review_tool_whitelist(st.review_agent, task_cfg)
+ review_whitelist, configured_extra_tools = _review_tool_whitelist(st.review_agent, task_cfg, review_memory)
extra_list = ", ".join(sorted(configured_extra_tools))
deny_extra = f" Configured extra tools also allowed: {extra_list}." if configured_extra_tools else ""
prompt_extra = f" Exception — these configured tools are also allowed: {extra_list}." if configured_extra_tools else ""
+ # Keep the deny/prompt wording in sync with the whitelist: a memory-less review must not
+ # tell the model that memory is available, or it will burn iterations on denied calls.
+ memory_phrase_deny = " and memory for notes (add only)" if "memory" in review_whitelist else ""
+ memory_phrase_prompt = "memory and skill " if "memory" in review_whitelist else "skill "
set_thread_tool_whitelist(
review_whitelist,
deny_msg_fmt=(
"Background review denied non-whitelisted tool: "
"{tool_name}. Allowed here: skill_view/skills_list/read_file/search_files to read, "
- "skill_manage(action='patch'|...) to change skills, and "
- "memory for notes." + deny_extra + " Do not retry {tool_name}."
+ "skill_manage(action='patch'|...) to change skills"
+ + memory_phrase_deny + "." + deny_extra + " Do not retry {tool_name}."
),
)
with suppress(Exception):
@@ -1040,7 +1047,7 @@ def _run_review_fork(
# Routed -> digest (cache cold anyway); same model -> full snapshot (warm cache reads).
st.review_agent.run_conversation(
user_message=(
- prompt + "\n\nYou can only call memory and skill "
+ prompt + "\n\nYou can only call " + memory_phrase_prompt +
"management tools. Other tools will be denied "
"at runtime — do not attempt them." + prompt_extra
),
@@ -1074,6 +1081,7 @@ def _publish_review_summary(agent: Any, actions: List[str]) -> None:
def _run_review_in_thread(
agent: Any, messages_snapshot: List[Dict], prompt: str,
task_cfg: Optional[Dict[str, Any]] = None, review_run: Optional[_BackgroundReviewRun] = None,
+ review_memory: bool = False,
) -> None:
"""Daemon-thread worker: build the fork, run the prompt, surface the action summary via
``agent._safe_print`` / ``background_review_callback``. ``review_run`` (from
@@ -1108,7 +1116,7 @@ def _run_review_in_thread(
# their console output (#55769 / #55925). ``thread_scoped_silence`` routes only this thread's writes
# to devnull and leaves all other threads on the real streams.
with thread_scoped_silence():
- _run_review_fork(agent, messages_snapshot, prompt, task_cfg, review_run, st)
+ _run_review_fork(agent, messages_snapshot, prompt, task_cfg, review_run, st, review_memory)
# A buggy/legacy tool response shape must NOT take down the whole review (the outer
# except would discard every action the fork DID complete), so coerce to an empty list.
try:
@@ -1182,7 +1190,9 @@ def spawn_background_review_thread(
)
def _target() -> None: # resolves _run_review_in_thread at call time (tests patch it)
- _run_review_in_thread(agent, messages_snapshot, prompt, task_cfg=task_cfg, review_run=review_run)
+ _run_review_in_thread(
+ agent, messages_snapshot, prompt, task_cfg=task_cfg, review_run=review_run,
+ review_memory=review_memory)
return _target, prompt
diff --git a/tests/agent/test_background_review_memory_scope.py b/tests/agent/test_background_review_memory_scope.py
new file mode 100644
index 00000000000..f63ed5cae9f
--- /dev/null
+++ b/tests/agent/test_background_review_memory_scope.py
@@ -0,0 +1,69 @@
+"""The review fork's memory access must follow the trigger that fired (#105921).
+
+``spawn_background_review_thread`` already received ``review_memory`` /
+``review_skills`` but used them only to pick the prompt — the tool whitelist
+granted the whole ``memory`` toolset whenever the profile had memory enabled,
+so a skill-nudge fork held ``remove``/``replace`` on MEMORY.md it was never
+asked to use. These tests pin the scope-aware whitelist and the pass-through
+from ``spawn_background_review_thread`` down to it.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from types import SimpleNamespace
+from unittest.mock import patch
+
+_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+if _REPO_ROOT not in sys.path:
+ sys.path.insert(0, _REPO_ROOT)
+
+import agent.background_review as bg # noqa: E402
+
+
+def _review_agent(memory_enabled=True, user_profile_enabled=False) -> SimpleNamespace:
+ """The whitelist only reads the profile's memory flags off the fork."""
+ return SimpleNamespace(_memory_enabled=memory_enabled, _user_profile_enabled=user_profile_enabled)
+
+
+class TestReviewToolWhitelistScope:
+ def test_skill_only_review_omits_memory_tool(self):
+ whitelist, _extra = bg._review_tool_whitelist(_review_agent(), None, review_memory=False)
+ assert "memory" not in whitelist
+ assert "skill_manage" in whitelist # the skill review keeps its own surface
+
+ def test_memory_review_keeps_memory_tool(self):
+ whitelist, _extra = bg._review_tool_whitelist(_review_agent(), None, review_memory=True)
+ assert "memory" in whitelist
+
+ def test_memory_disabled_profile_stays_memory_free(self):
+ whitelist, _extra = bg._review_tool_whitelist(
+ _review_agent(memory_enabled=False, user_profile_enabled=False), None, review_memory=True)
+ assert "memory" not in whitelist
+
+ def test_default_scope_is_memoryless_fail_closed(self):
+ # Unknown trigger (default) must not grant memory: the incident fork was a
+ # skill review that used memory nobody asked it to touch.
+ whitelist, _extra = bg._review_tool_whitelist(_review_agent(), None)
+ assert "memory" not in whitelist
+
+
+class TestSpawnForwardsScope:
+ def test_target_passes_review_memory_to_worker(self):
+ captured = {}
+
+ def fake_worker(agent, messages_snapshot, prompt, task_cfg=None, review_run=None, review_memory=False):
+ captured["review_memory"] = review_memory
+
+ agent = SimpleNamespace()
+ with patch.object(bg, "_run_review_in_thread", fake_worker):
+ target, _prompt = bg.spawn_background_review_thread(
+ agent, [], review_memory=False, review_skills=True)
+ target()
+ assert captured["review_memory"] is False
+
+ target, _prompt = bg.spawn_background_review_thread(
+ agent, [], review_memory=True, review_skills=False)
+ target()
+ assert captured["review_memory"] is True
diff --git a/tests/tools/test_memory_tool.py b/tests/tools/test_memory_tool.py
index 44d43d4d31d..084f7582044 100644
--- a/tests/tools/test_memory_tool.py
+++ b/tests/tools/test_memory_tool.py
@@ -9,6 +9,7 @@ from tools.memory_tool import (
memory_tool,
_scan_memory_content,
)
+from tools.skill_provenance import reset_current_write_origin, set_current_write_origin
def _blocked(content, pattern_id=None):
@@ -755,3 +756,65 @@ class TestBatchRefusesToEmptyNonEmptyStore:
assert result["success"] is True
assert seed not in store._entries_for(target)
assert "replacement entry here" in store._entries_for(target)
+
+
+# =========================================================================
+# Background-review delete gate (#105921)
+# =========================================================================
+
+class TestBackgroundReviewDeleteGate:
+ """An unattended background-review fork may append, never delete: the near-limit
+ 'consolidate now' hint is otherwise an instruction to decide what to forget,
+ executed with no human in the loop."""
+
+ def test_remove_denied_and_store_untouched(self, store):
+ store.add("memory", "never create records without permission")
+ token = set_current_write_origin("background_review")
+ try:
+ result = json.loads(memory_tool(action="remove", old_text="without permission", store=store))
+ finally:
+ reset_current_write_origin(token)
+ assert result["success"] is False
+ assert "Background review may not delete" in result["error"]
+ # Fail-closed: the standing rule is still on disk.
+ assert "never create records without permission" in store._entries_for("memory")
+
+ def test_replace_denied_in_background_review(self, store):
+ store.add("memory", "entry the fork must not rewrite")
+ token = set_current_write_origin("background_review")
+ try:
+ result = json.loads(memory_tool(
+ action="replace", old_text="entry the fork", content="rewritten by fork", store=store))
+ finally:
+ reset_current_write_origin(token)
+ assert result["success"] is False
+ assert "Background review may not delete" in result["error"]
+
+ def test_batch_containing_remove_denied(self, store):
+ store.add("memory", "rule one")
+ token = set_current_write_origin("background_review")
+ try:
+ result = json.loads(memory_tool(operations=[
+ {"action": "remove", "old_text": "rule one"},
+ {"action": "add", "content": "fork consolidation"},
+ ], store=store))
+ finally:
+ reset_current_write_origin(token)
+ assert result["success"] is False
+ # Atomic denial: the batch's add must not land either.
+ assert "fork consolidation" not in store._entries_for("memory")
+
+ def test_add_still_allowed_in_background_review(self, store):
+ token = set_current_write_origin("background_review")
+ try:
+ result = json.loads(memory_tool(action="add", content="a fact worth keeping", store=store))
+ finally:
+ reset_current_write_origin(token)
+ assert result["success"] is True
+ assert "a fact worth keeping" in store._entries_for("memory")
+
+ def test_foreground_remove_unaffected(self, store):
+ store.add("memory", "entry a supervised turn may remove")
+ result = json.loads(memory_tool(action="remove", old_text="supervised turn", store=store))
+ assert result["success"] is True
+ assert "entry a supervised turn may remove" not in store._entries_for("memory")
diff --git a/tools/memory_tool.py b/tools/memory_tool.py
index 8028ffd88a9..faa775a11c2 100644
--- a/tools/memory_tool.py
+++ b/tools/memory_tool.py
@@ -126,6 +126,28 @@ def _validate_single_op(store, action, target, content, old_text) -> Optional[st
return None
+_BG_DELETE_ACTIONS = ("replace", "remove")
+
+
+def _background_delete_gate(action, operations) -> Optional[str]:
+ """Fail-closed operation gate for unattended background-review forks (#105921): ``add``
+ stays available (it is all any review prompt asks for), while ``replace``/``remove`` —
+ single or inside a batch — are denied. The near-limit "consolidate now" hint is otherwise
+ an instruction to decide what to forget, executed with no human in the loop."""
+ from tools.skill_provenance import is_background_review
+
+ if not is_background_review():
+ return None
+ if action in _BG_DELETE_ACTIONS or any(
+ isinstance(op, dict) and op.get("action") in _BG_DELETE_ACTIONS for op in (operations or [])
+ ):
+ return tool_error(
+ "Background review may not delete memory entries ('replace'/'remove', including in a "
+ "batch); 'add' is still available. Propose a consolidation in your review summary "
+ "instead.", success=False)
+ return None
+
+
def memory_tool(action: str = None, target: str = "memory", content: str = None, old_text: str = None,
new_text: str = None, operations: Optional[List[Dict[str, Any]]] = None,
store: Optional[MemoryStore] = None) -> str:
@@ -141,6 +163,9 @@ def memory_tool(action: str = None, target: str = "memory", content: str = None,
target_error = _memory_target_error(store, target)
if target_error is not None:
return json.dumps(target_error)
+ denied = _background_delete_gate(action, operations)
+ if denied is not None:
+ return denied
if operations:
if not isinstance(operations, list):
return tool_error("operations must be a list of {action, content?, old_text?} objects.", success=False)