The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(review): keep /refine under the background_review origin; attendedness is its own flag
kshitijk4poore33311387190
diff --git a/agent/background_review.py b/agent/background_review.pyindex 8dc7d5a76d8..46b2394694b 100644--- a/agent/background_review.py+++ b/agent/background_review.py@@ -1021,11 +1021,11 @@ def _run_review_fork("""Fork phase (inside thread-scoped silence): build the fork, run the prompt under the toolwhitelist, snapshot its messages/usage, release its clients. Partial progress lands on ``st``so the caller's error path still sees usage and the fork to clean up. ``explicit`` (/refine)- forks under the ``refine_review`` origin: a user-requested review keeps the full memory- operation set — the unattended-only delete gate must not treat it as automatic."""+ keeps the ``background_review`` origin (curator/skill guards still apply) but marks the fork+ attended, so the unattended-only memory delete gate leaves the full operation set available."""st.review_agent, _rt, _routed = build_cache_parity_fork(- agent, task_cfg, max_iterations=_REVIEW_MAX_ITERATIONS,- write_origin="refine_review" if explicit else "background_review")+ agent, task_cfg, max_iterations=_REVIEW_MAX_ITERATIONS)+ st.review_agent._review_attended = explicit_track_review_fork(agent, st.review_agent, register=True)from hermes_cli.plugins import set_thread_tool_whitelist, clear_thread_tool_whitelistreview_whitelist, configured_extra_tools = _review_tool_whitelist(st.review_agent, task_cfg, review_memory)diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 379d299cb4b..3fa0c304168 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -835,6 +835,8 @@ def build_turn_context(# warning and a needless first-turn prefix cache miss. (Issue #45499.)set_session_context(agent.session_id)set_current_write_origin(getattr(agent, "_memory_write_origin", "assistant_tool"))+ from tools.skill_provenance import set_review_attended+ set_review_attended(getattr(agent, "_review_attended", False))agent._restore_primary_runtime()_publish_runtime_main(agent)_refresh_mcp_tools_between_turns(agent)diff --git a/tests/agent/test_background_review_memory_scope.py b/tests/agent/test_background_review_memory_scope.pyindex 252f185ee01..7453a394381 100644--- a/tests/agent/test_background_review_memory_scope.py+++ b/tests/agent/test_background_review_memory_scope.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport osimport sys+import pytestfrom types import SimpleNamespacefrom unittest.mock import patch@@ -88,34 +89,17 @@ class TestExplicitRefineOrigin:target()assert captured["explicit"] is True- def test_explicit_fork_uses_refine_review_origin(self):- captured = {}-- def fake_build(agent, task_cfg=None, *, max_iterations, write_origin="background_review"):- captured["write_origin"] = write_origin- fork = SimpleNamespace(- _memory_enabled=True, _user_profile_enabled=False,- run_conversation=lambda **kw: None, _session_messages=[])- return fork, {}, False-- noop = lambda *a, **k: None- with patch.object(bg, "build_cache_parity_fork", fake_build), \- patch.object(bg, "_track_review_fork", noop), \- patch.object(bg, "_snapshot_review_usage", lambda a: {}), \- patch.object(bg, "_record_review_usage_to_parent", noop), \- patch.object(bg, "finish_background_review_run", noop), \- patch.object(bg, "_release_fork_clients", noop):- bg._run_review_fork(SimpleNamespace(), [], "p", None, None, bg._ReviewForkState(), True, True)- assert captured["write_origin"] == "refine_review"-- def test_automatic_fork_keeps_background_review_origin(self):- captured = {}+ @pytest.mark.parametrize("explicit", [True, False])+ def test_fork_keeps_background_review_origin_and_carries_attendedness(self, explicit):+ """Every curator/skill guard keys on the background_review origin, so an explicit /refine+ must NOT change the origin; attendedness rides on the fork as its own flag."""+ forks = []def fake_build(agent, task_cfg=None, *, max_iterations, write_origin="background_review"):- captured["write_origin"] = write_originfork = SimpleNamespace(- _memory_enabled=True, _user_profile_enabled=False,+ _memory_enabled=True, _user_profile_enabled=False, _memory_write_origin=write_origin,run_conversation=lambda **kw: None, _session_messages=[])+ forks.append(fork)return fork, {}, Falsenoop = lambda *a, **k: None@@ -125,8 +109,10 @@ class TestExplicitRefineOrigin:patch.object(bg, "_record_review_usage_to_parent", noop), \patch.object(bg, "finish_background_review_run", noop), \patch.object(bg, "_release_fork_clients", noop):- bg._run_review_fork(SimpleNamespace(), [], "p", None, None, bg._ReviewForkState(), True, False)- assert captured["write_origin"] == "background_review"+ bg._run_review_fork(SimpleNamespace(), [], "p", None, None, bg._ReviewForkState(), True, explicit)+ (fork,) = forks+ assert fork._memory_write_origin == "background_review"+ assert fork._review_attended is explicitclass TestConsolidationProposalSurfaces:diff --git a/tests/agent/test_refine_snapshot_isolation.py b/tests/agent/test_refine_snapshot_isolation.pyindex 1520456cee1..29b2db960bd 100644--- a/tests/agent/test_refine_snapshot_isolation.py+++ b/tests/agent/test_refine_snapshot_isolation.py@@ -77,7 +77,7 @@ def test_cli_refine_snapshot_does_not_alias_live_history(monkeypatch):def test_cli_refine_reaches_spawn_as_explicit(monkeypatch):"""The explicit /refine path must reach the spawn with ``explicit=True`` so the fork runs- under the refine_review origin and keeps the full memory operation set (#105921 review)."""+ is marked attended and keeps the full memory operation set (#105921 review)."""from hermes_cli.cli_commands_mixin import CLICommandsMixinmonkeypatch.setattr("cli._cprint", lambda *a, **k: None, raising=False)diff --git a/tests/tools/test_memory_tool.py b/tests/tools/test_memory_tool.pyindex ea7cc1e419f..11466ba2179 100644--- a/tests/tools/test_memory_tool.py+++ b/tests/tools/test_memory_tool.py@@ -834,16 +834,18 @@ class TestBackgroundReviewDeleteGate:assert result["success"] is Trueassert "entry a supervised turn may remove" not in store._entries_for("memory")- def test_refine_review_origin_keeps_full_operation_set(self, store):- # A user-requested /refine fork runs under the refine_review origin: it is not an- # unattended review, so replace/remove keep working on that supervised surface.+ def test_attended_review_keeps_full_operation_set(self, store):+ # A user-requested /refine fork keeps the background_review origin (skill guards still+ # apply) but is attended, so replace/remove keep working on that supervised surface.+ from tools.skill_provenance import reset_review_attended, set_review_attendedstore.add("memory", "entry an explicit refine may rewrite")- token = set_current_write_origin("refine_review")+ token = set_current_write_origin("background_review")+ att = set_review_attended(True)try:result = json.loads(memory_tool(action="replace", old_text="entry an explicit", content="rewritten by refine", store=store))finally:+ reset_review_attended(att)reset_current_write_origin(token)assert result["success"] is Trueassert "rewritten by refine" in store._entries_for("memory")- assert "entry an explicit refine may rewrite" not in store._entries_for("memory")diff --git a/tests/tools/test_skill_provenance.py b/tests/tools/test_skill_provenance.pyindex 31776fa6600..d3fce754843 100644--- a/tests/tools/test_skill_provenance.py+++ b/tests/tools/test_skill_provenance.py@@ -50,3 +50,24 @@ def test_context_isolation_between_copies():assert inside == BACKGROUND_REVIEW# Parent context unaffected.assert get_current_write_origin() == original+++def test_attended_review_is_still_a_background_review():+ """/refine keeps the background_review origin: every curator/skill-ledger/approval guard keyed on+ is_background_review() must still apply; only the unattended-only memory delete gate stands down."""+ from tools.skill_provenance import (+ BACKGROUND_REVIEW, is_background_review, is_unattended_review, reset_current_write_origin,+ reset_review_attended, set_current_write_origin, set_review_attended,+ )++ token = set_current_write_origin(BACKGROUND_REVIEW)+ try:+ assert is_background_review() and is_unattended_review()+ att = set_review_attended(True)+ try:+ assert is_background_review() and not is_unattended_review()+ finally:+ reset_review_attended(att)+ finally:+ reset_current_write_origin(token)+ assert not is_background_review() and not is_unattended_review()diff --git a/tools/memory_tool.py b/tools/memory_tool.pyindex 6f3447b9cde..adf740d5c92 100644--- a/tools/memory_tool.py+++ b/tools/memory_tool.py@@ -136,9 +136,9 @@ def _background_delete_gate(action, operations, target="memory", content=None, ostore instead of merely denied: the fork's own review summary is never published back, soa plain denial would drop the consolidation request with no surfacing path at all. Astaging failure fails closed to a plain denial."""- from tools.skill_provenance import is_background_review+ from tools.skill_provenance import is_unattended_review- if not is_background_review():+ if not is_unattended_review():return Nonehit = action in _BG_DELETE_ACTIONS or any(isinstance(op, dict) and op.get("action") in _BG_DELETE_ACTIONS for op in (operations or []))@@ -184,12 +184,12 @@ 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, target, content, old_text)- if denied is not None:- return deniedif operations:if not isinstance(operations, list):return tool_error("operations must be a list of {action, content?, old_text?} objects.", success=False)+ denied = _background_delete_gate(action, operations, target)+ if denied is not None:+ return denied# Approval gate: stages (background/gateway) or prompts inline (CLI); off by default.gate_result = _apply_write_gate("batch", target, None, None, operations)if gate_result is not None:@@ -198,6 +198,7 @@ def memory_tool(action: str = None, target: str = "memory", content: str = None,if action not in _STORE_ACTIONS:return tool_error(f"Unknown action '{action}'. Use: add, replace, remove", success=False)invalid = (_validate_single_op(store, action, target, content, old_text)+ or _background_delete_gate(action, None, target, content, old_text)or _apply_write_gate(action, target, content, old_text))if invalid is not None:return invaliddiff --git a/tools/skill_provenance.py b/tools/skill_provenance.pyindex 3df9cf14304..4ab73ce2563 100644--- a/tools/skill_provenance.py+++ b/tools/skill_provenance.py@@ -24,3 +24,21 @@ def get_current_write_origin() -> str:def is_background_review() -> bool:return get_current_write_origin() == BACKGROUND_REVIEW+++# Attendedness is orthogonal to origin: an explicit ``/refine`` fork IS a background review (every+# curator / skill-ledger / approval guard keyed on ``is_background_review()`` must still apply), but a+# user asked for it, so the unattended-only memory delete gate (#105921) does not.+_review_attended: contextvars.ContextVar[bool] = contextvars.ContextVar("review_attended", default=False)+++def set_review_attended(attended: bool) -> contextvars.Token[bool]:+ return _review_attended.set(bool(attended))+++def reset_review_attended(token: contextvars.Token[bool]) -> None:+ _review_attended.reset(token)+++def is_unattended_review() -> bool:+ return is_background_review() and not _review_attended.get()