Skip to content

The agent that grows with you

feat(local-runtime): defer background reviews to machine idle on the managed local server

emozilla920e0585df8a
diff --git a/agent/review_idle_queue.py b/agent/review_idle_queue.py
new file mode 100644
index 00000000000..9c962cf5848
--- /dev/null
+++ b/agent/review_idle_queue.py
@@ -0,0 +1,256 @@
+"""Idle deferral for background reviews on the managed local runtime.
+
+The post-turn review fork replays the whole conversation on the review
+runtime. On a cloud provider that costs seconds and runs concurrently
+with whatever the user does next. When the review runtime IS the managed
+llama-server, the same fork monopolizes the GPU the user's next prompt
+needs, for minutes — and the next live turn cancels it, so an active
+session tends to pay the decode cost AND lose the learning.
+
+This module keeps the decision to learn exactly where it was (turn end,
+nudge intervals, full-strength model, full transcript) and moves only
+the execution moment: reviews bound for the managed local endpoint are
+queued and dispatched when the machine is quiet. Everything else runs
+immediately, as before.
+
+Policy (auxiliary.background_review.defer):
+ auto (default) — defer exactly when the resolved review runtime
+ targets the managed local server.
+ never — old behavior everywhere.
+Explicit /refine (focus set) never defers: an explicit ask runs now,
+matching its bypass of the enabled gate.
+
+Queue semantics:
+- One slot per session, newest snapshot wins. A review replays the whole
+ conversation, so a newer snapshot strictly supersedes an older one —
+ coalescing is deduplication, not loss.
+- Preempted (cancelled-by-live-turn) reviews are requeued by the spawn
+ wrapper observing the run token's cancel flag, not killed-and-forgotten.
+- Aged-out events (defer_max_age_s, default 30 min) dispatch regardless
+ of idleness — deferral may delay learning, never lose it.
+- In-memory, best-effort: dropped on process exit, the same durability
+ contract the immediate daemon-thread fork always had.
+
+Idle truth comes from the supervisor's /slots (machine-level: it sees
+every client of the managed server, including other Hermes profiles) and
+must hold for a settle window so a review is not launched into the gap
+between two quick prompts. Local in-process turn liveness is tracked via
+note_turn_started/note_turn_finished from run_conversation.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import threading
+import time
+import urllib.request
+from typing import Any, Callable, Dict, List, Optional
+
+logger = logging.getLogger(__name__)
+
+# Sustained-quiet window before dispatch. Long enough that "typed two
+# prompts back to back" does not look idle; short enough that walking
+# away for coffee runs the queue.
+_IDLE_SETTLE_S = 15.0
+# Poll cadence while the queue is non-empty. The thread parks when empty.
+_POLL_INTERVAL_S = 5.0
+# Age at which a queued review dispatches regardless of idleness.
+_MAX_AGE_DEFAULT_S = 30.0 * 60.0
+
+
+def defer_mode(task_cfg: Optional[Dict[str, Any]]) -> str:
+ """'auto' (default) or 'never' from auxiliary.background_review.defer."""
+ raw = str((task_cfg or {}).get("defer", "auto")).strip().lower()
+ return raw if raw in ("auto", "never") else "auto"
+
+
+def defer_max_age_s(task_cfg: Optional[Dict[str, Any]]) -> float:
+ raw = (task_cfg or {}).get("defer_max_age_s", _MAX_AGE_DEFAULT_S)
+ try:
+ value = float(raw)
+ except (TypeError, ValueError):
+ return _MAX_AGE_DEFAULT_S
+ return value if value > 0 else _MAX_AGE_DEFAULT_S
+
+
+def review_targets_managed_local(agent: Any,
+ task_cfg: Optional[Dict[str, Any]]) -> bool:
+ """Would this review fork decode on the llama-server WE manage?
+
+ Resolves the review runtime the same way the fork itself will and
+ exact-matches its netloc against the supervisor state file — the
+ matcher that cannot false-positive on external local servers. Any
+ failure reads False: immediate spawn is always the safe default.
+ """
+ try:
+ from agent.auxiliary_client import _is_managed_local_endpoint
+ from agent.background_review import _resolve_review_runtime
+
+ runtime = _resolve_review_runtime(agent, task_cfg)
+ return _is_managed_local_endpoint(runtime.get("base_url"))
+ except Exception: # noqa: BLE001
+ return False
+
+
+class _PendingReview:
+ __slots__ = ("agent", "kwargs", "enqueued_at", "session_key")
+
+ def __init__(self, agent: Any, session_key: str, kwargs: Dict[str, Any]):
+ self.agent = agent
+ self.session_key = session_key
+ self.kwargs = kwargs
+ self.enqueued_at = time.monotonic()
+
+
+class ReviewIdleQueue:
+ """Session-coalescing queue + idle-gated dispatcher thread."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._pending: Dict[str, _PendingReview] = {}
+ self._wake = threading.Event()
+ self._thread: Optional[threading.Thread] = None
+ self._live_turns = 0
+ self._quiet_since: Optional[float] = None
+ # Test seams — replaced by unit tests, never in production.
+ self._now: Callable[[], float] = time.monotonic
+ self._server_idle: Callable[[], bool] = _managed_server_idle
+
+ # ── turn liveness (this process) ────────────────────────────
+
+ def note_turn_started(self) -> None:
+ with self._lock:
+ self._live_turns += 1
+ self._quiet_since = None
+
+ def note_turn_finished(self) -> None:
+ with self._lock:
+ self._live_turns = max(0, self._live_turns - 1)
+ if self._live_turns == 0:
+ self._quiet_since = self._now()
+ self._wake.set()
+
+ # ── queue ────────────────────────────────────────────────────
+
+ def enqueue(self, agent: Any, session_key: str,
+ kwargs: Dict[str, Any]) -> None:
+ """Add (or replace — newest snapshot wins) a session's pending review."""
+ with self._lock:
+ existing = self._pending.get(session_key)
+ item = _PendingReview(agent, session_key, kwargs)
+ # Stamp through the queue's clock (test seam); keep the ORIGINAL
+ # enqueue time on coalesce so a busy session cannot push its
+ # review's age-out forever.
+ item.enqueued_at = (existing.enqueued_at if existing is not None
+ else self._now())
+ self._pending[session_key] = item
+ self._ensure_thread()
+ self._wake.set()
+ logger.info("Background review deferred (session=%s, queued=%d)",
+ session_key[-12:], len(self._pending))
+
+ def pending_count(self) -> int:
+ with self._lock:
+ return len(self._pending)
+
+ # ── dispatcher ───────────────────────────────────────────────
+
+ def _ensure_thread(self) -> None:
+ with self._lock:
+ if self._thread is None or not self._thread.is_alive():
+ self._thread = threading.Thread(
+ target=self._run, daemon=True, name="bg-review-idle-queue")
+ self._thread.start()
+
+ def _quiet_for(self) -> float:
+ """Seconds this process has been turn-free (0 while a turn runs)."""
+ with self._lock:
+ if self._live_turns > 0 or self._quiet_since is None:
+ return 0.0
+ return self._now() - self._quiet_since
+
+ def _pop_dispatchable(self) -> Optional[_PendingReview]:
+ """Oldest aged-out item, else any item once quiet+idle hold."""
+ with self._lock:
+ if not self._pending:
+ return None
+ items = sorted(self._pending.values(),
+ key=lambda p: p.enqueued_at)
+ aged = [p for p in items
+ if self._now() - p.enqueued_at
+ >= defer_max_age_s(p.kwargs.get("task_cfg"))]
+ candidate = aged[0] if aged else None
+ if candidate is None:
+ if self._quiet_for() < _IDLE_SETTLE_S:
+ return None
+ if not self._server_idle():
+ return None
+ with self._lock:
+ if not self._pending:
+ return None
+ candidate = min(self._pending.values(),
+ key=lambda p: p.enqueued_at)
+ with self._lock:
+ return self._pending.pop(candidate.session_key, None)
+
+ def _run(self) -> None:
+ while True:
+ self._wake.wait()
+ with self._lock:
+ if not self._pending:
+ self._wake.clear()
+ continue
+ item = None
+ try:
+ item = self._pop_dispatchable()
+ if item is not None:
+ logger.info(
+ "Dispatching deferred background review "
+ "(session=%s, waited=%.0fs, queued=%d)",
+ item.session_key[-12:],
+ self._now() - item.enqueued_at,
+ self.pending_count())
+ item.agent._spawn_background_review_now(**item.kwargs)
+ except Exception: # noqa: BLE001 — dispatcher must survive anything
+ logger.warning("Deferred review dispatch failed",
+ exc_info=True)
+ if item is None:
+ time.sleep(_POLL_INTERVAL_S)
+
+
+def _managed_server_idle() -> bool:
+ """Machine-level idle: no processing slot on any loaded model of the
+ managed router. Unreachable/no state file reads idle (nothing to
+ contend with). One /models + one /slots call per loaded model."""
+ try:
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ state = json.loads(state_path().read_text(encoding="utf-8"))
+ base = str(state.get("base_url", "")).rsplit("/v1", 1)[0]
+ key = str(state.get("api_key", ""))
+ if not base:
+ return True
+ headers = {"Authorization": f"Bearer {key}"}
+ req = urllib.request.Request(f"{base}/models", headers=headers)
+ with urllib.request.urlopen(req, timeout=3) as r:
+ models = json.loads(r.read())
+ loaded = [m["id"] for m in models.get("data", [])
+ if (m.get("status") or {}).get("value") in ("loaded", "ready")]
+ from urllib.parse import quote
+
+ for mid in loaded:
+ req = urllib.request.Request(f"{base}/slots?model={quote(mid)}",
+ headers=headers)
+ with urllib.request.urlopen(req, timeout=3) as r:
+ slots = json.loads(r.read())
+ if any(s.get("is_processing") for s in slots
+ if isinstance(s, dict)):
+ return False
+ return True
+ except Exception: # noqa: BLE001
+ return True
+
+
+# Module singleton — one queue per process, like the load-progress watcher.
+QUEUE = ReviewIdleQueue()
diff --git a/run_agent.py b/run_agent.py
index c6638b6cacd..296ece8b7f3 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -1886,6 +1886,56 @@ class AIAgent:
review_memory: bool = False,
review_skills: bool = False,
focus: Optional[str] = None,
+ ) -> None:
+ """Post-turn review entry point: decide WHEN, then spawn.
+
+ The decision to review (nudge intervals, enabled gate) already
+ happened at the call site. This wrapper adds one policy: a review
+ whose runtime resolves to the MANAGED LOCAL llama-server is queued
+ for machine idle instead of spawned into the user's GPU mid-session
+ (auxiliary.background_review.defer: auto|never). Everything else —
+ cloud runtimes, external local servers, explicit /refine — spawns
+ immediately, exactly as before.
+ """
+ # Delegation-subagent and enabled gates live here so a DEFERRED
+ # dispatch cannot resurrect a review the config has since disabled.
+ if focus is None and getattr(self, "_delegate_depth", 0) > 0:
+ return
+ task_cfg = None
+ if focus is None:
+ from agent.background_review import load_background_review_settings
+ enabled, task_cfg = load_background_review_settings()
+ if not enabled:
+ return
+
+ kwargs = dict(
+ messages_snapshot=messages_snapshot,
+ review_memory=review_memory,
+ review_skills=review_skills,
+ focus=focus,
+ task_cfg=task_cfg,
+ )
+ if focus is None:
+ from agent.review_idle_queue import (
+ QUEUE,
+ defer_mode,
+ review_targets_managed_local,
+ )
+ if (defer_mode(task_cfg) == "auto"
+ and review_targets_managed_local(self, task_cfg)):
+ session_key = str(getattr(self, "session_id", None) or id(self))
+ QUEUE.enqueue(self, session_key, kwargs)
+ return
+ self._spawn_background_review_now(**kwargs)
+
+ def _spawn_background_review_now(
+ self,
+ messages_snapshot: List[Dict],
+ review_memory: bool = False,
+ review_skills: bool = False,
+ focus: Optional[str] = None,
+ task_cfg: Optional[Dict[str, Any]] = None,
+ _requeue_attempts: int = 0,
) -> None:
"""Spawn the background memory/skill review thread.
@@ -1898,28 +1948,17 @@ class AIAgent:
``focus`` is optional user-supplied steering (from ``/refine``)
appended to the review prompt — e.g. "save the deploy workflow as a
skill". The automatic post-turn triggers never set it.
+
+ ``task_cfg`` is the pre-loaded ``auxiliary.background_review``
+ block from the entry wrapper (None on direct calls, e.g. /refine —
+ the spawn path reads config itself then).
+
+ A deferred review preempted by a live turn is REQUEUED (bounded by
+ ``_requeue_attempts``) instead of lost: on the managed local
+ runtime a review takes minutes, so cancel-and-forget — harmless on
+ cloud, where reviews finish in seconds — would silently discard
+ most learning on an active session.
"""
- # A delegation subagent (``_delegate_depth > 0``) must not run the
- # automatic post-turn review. Subagents are ephemeral workers already
- # barred from writing shared MEMORY.md (``DELEGATE_BLOCKED_TOOLS``) and
- # are spawned with ``skip_memory=True``, so a review here has little to
- # persist — yet it inherits the subagent's (often premium) delegation
- # model and replays the whole conversation at premium rates, silently
- # inflating token cost (#85859). An explicit ``/refine`` (``focus`` set)
- # is a deliberate user request and still runs.
- if focus is None and getattr(self, "_delegate_depth", 0) > 0:
- return
- # Explicit off-switch for automatic post-turn forks
- # (``auxiliary.background_review.enabled: false``). Manual ``/refine``
- # still works — same contract as zeroing the nudge intervals (#87250).
- # Load the task block once here and pass it into the spawn path so
- # aux routing does not re-read config.
- task_cfg = None
- if focus is None:
- from agent.background_review import load_background_review_settings
- enabled, task_cfg = load_background_review_settings()
- if not enabled:
- return
from agent.background_review import (
finish_background_review_run,
prepare_background_review_run,
@@ -1940,10 +1979,25 @@ class AIAgent:
task_cfg=task_cfg,
review_run=review_run,
)
+
+ def _target_with_requeue() -> None:
+ target()
+ self._maybe_requeue_preempted_review(
+ review_run,
+ dict(
+ messages_snapshot=messages_snapshot,
+ review_memory=review_memory,
+ review_skills=review_skills,
+ focus=focus,
+ task_cfg=task_cfg,
+ _requeue_attempts=_requeue_attempts + 1,
+ ),
+ )
+
# Carry the active profile into the review thread so MEMORY.md /
# skill review writes land in the right profile (#54937).
t = threading.Thread(
- target=propagate_context_to_thread(target),
+ target=propagate_context_to_thread(_target_with_requeue),
daemon=True,
name="bg-review",
)
@@ -1952,6 +2006,42 @@ class AIAgent:
finish_background_review_run(self, review_run)
raise
+ _REVIEW_REQUEUE_MAX_ATTEMPTS = 3
+
+ def _maybe_requeue_preempted_review(self, review_run, kwargs) -> None:
+ """Requeue a deferred-mode review that a live turn cancelled.
+
+ Only fires for automatic reviews whose runtime targets the managed
+ local server (the deferred population); bounded attempts prevent a
+ busy box from cycling one review forever — past the cap it is
+ dropped exactly like the pre-deferral behavior dropped every
+ cancelled review.
+ """
+ try:
+ if not review_run.cancel_requested.is_set():
+ return # ran to completion (or never admitted for other reasons)
+ if kwargs.get("focus") is not None:
+ return
+ if kwargs.get("_requeue_attempts", 0) > self._REVIEW_REQUEUE_MAX_ATTEMPTS:
+ logger.info("Preempted background review dropped after %d requeues",
+ self._REVIEW_REQUEUE_MAX_ATTEMPTS)
+ return
+ from agent.review_idle_queue import (
+ QUEUE,
+ defer_mode,
+ review_targets_managed_local,
+ )
+ task_cfg = kwargs.get("task_cfg")
+ if (defer_mode(task_cfg) != "auto"
+ or not review_targets_managed_local(self, task_cfg)):
+ return
+ session_key = str(getattr(self, "session_id", None) or id(self))
+ # kwargs carries the incremented _requeue_attempts through the
+ # queue so the cap survives the round trip.
+ QUEUE.enqueue(self, session_key, dict(kwargs))
+ except Exception: # noqa: BLE001 — requeue is best-effort
+ logger.debug("Preempted-review requeue failed", exc_info=True)
+
def _build_memory_write_metadata(
self,
*,
@@ -8512,6 +8602,13 @@ class AIAgent:
cancel_background_review_for_live_turn(self)
+ # Turn liveness for the deferred-review idle queue: a queued review
+ # must not dispatch into the settle gap between two quick prompts.
+ # Marked inside the try below so the balancing note_turn_finished in
+ # its finally covers every exit; the actual start-mark happens as the
+ # first statement of the try.
+ from agent.review_idle_queue import QUEUE as _review_queue
+
from agent.aux_accounting import (
reset_accounting_context,
set_accounting_context,
@@ -8588,6 +8685,7 @@ class AIAgent:
_clear_if_owned()
try:
+ _review_queue.note_turn_started()
# Serialize the full load -> run -> flush region across Hermes
# processes. Gateway's asyncio lease closes alias routing inside one
# process; this durable lease covers Desktop, CLI resume, gateway,
@@ -8968,6 +9066,13 @@ class AIAgent:
reset_accounting_context(acct_token)
if token is not None:
reset_conversation_context(token)
+ # Balance the note_turn_started above — every exit path
+ # lands here, so the idle queue's live-turn count cannot
+ # leak upward and starve deferred reviews.
+ try:
+ _review_queue.note_turn_finished()
+ except Exception:
+ pass
def chat(self, message: str, stream_callback: Optional[callable] = None) -> str:
"""
diff --git a/tests/agent/test_review_idle_queue.py b/tests/agent/test_review_idle_queue.py
new file mode 100644
index 00000000000..21645d1bea1
--- /dev/null
+++ b/tests/agent/test_review_idle_queue.py
@@ -0,0 +1,297 @@
+"""Deferred background review on the managed local runtime.
+
+Behavior contracts for agent/review_idle_queue.py and the decision
+wrapper in run_agent.AIAgent._spawn_background_review:
+
+- defer: auto + review runtime == managed local -> queued, not spawned
+- defer: never, or non-managed runtime, or /refine -> immediate spawn
+- queue coalesces per session (newest snapshot wins, age preserved)
+- dispatch requires sustained process-quiet AND server idle
+- aged-out items dispatch regardless of idleness (delay, never lose)
+- preempted deferred reviews requeue with a bounded attempt cap
+"""
+
+import threading
+import time
+import types
+
+import pytest
+
+from agent.review_idle_queue import (
+ ReviewIdleQueue,
+ _IDLE_SETTLE_S,
+ defer_max_age_s,
+ defer_mode,
+)
+
+
+# ── config parsing ───────────────────────────────────────────────
+
+
+def test_defer_mode_values():
+ assert defer_mode(None) == "auto"
+ assert defer_mode({}) == "auto"
+ assert defer_mode({"defer": "auto"}) == "auto"
+ assert defer_mode({"defer": "never"}) == "never"
+ assert defer_mode({"defer": "NEVER"}) == "never"
+ # Unknown values fall back to auto (the safe, documented default).
+ assert defer_mode({"defer": "sometimes"}) == "auto"
+ assert defer_mode({"defer": 3}) == "auto"
+
+
+def test_defer_max_age_parsing():
+ assert defer_max_age_s(None) == 30 * 60
+ assert defer_max_age_s({"defer_max_age_s": 120}) == 120.0
+ assert defer_max_age_s({"defer_max_age_s": "600"}) == 600.0
+ # Nonsense and non-positive fall back to the default.
+ assert defer_max_age_s({"defer_max_age_s": "soon"}) == 30 * 60
+ assert defer_max_age_s({"defer_max_age_s": 0}) == 30 * 60
+ assert defer_max_age_s({"defer_max_age_s": -5}) == 30 * 60
+
+
+# ── queue harness ────────────────────────────────────────────────
+
+
+class _FakeAgent:
+ def __init__(self):
+ self.spawned = []
+ self.session_id = "sess-x"
+
+ def _spawn_background_review_now(self, **kwargs):
+ self.spawned.append(kwargs)
+
+
+def _make_queue(now=None, server_idle=True):
+ q = ReviewIdleQueue()
+ clock = {"t": 0.0}
+ if now is None:
+ q._now = lambda: clock["t"]
+ else:
+ q._now = now
+ q._server_idle = lambda: server_idle
+ # Never start the real dispatcher thread in unit tests.
+ q._ensure_thread = lambda: None
+ return q, clock
+
+
+def test_enqueue_coalesces_per_session_newest_wins_oldest_age():
+ q, clock = _make_queue()
+ agent = _FakeAgent()
+
+ clock["t"] = 100.0
+ q.enqueue(agent, "s1", {"messages_snapshot": ["old"], "task_cfg": {}})
+ clock["t"] = 200.0
+ q.enqueue(agent, "s1", {"messages_snapshot": ["new"], "task_cfg": {}})
+ q.enqueue(agent, "s2", {"messages_snapshot": ["other"], "task_cfg": {}})
+
+ assert q.pending_count() == 2
+ with q._lock:
+ item = q._pending["s1"]
+ # Newest snapshot won, but the age clock kept the ORIGINAL enqueue
+ # time so a busy session cannot push its own age-out forever.
+ assert item.kwargs["messages_snapshot"] == ["new"]
+ assert item.enqueued_at == 100.0
+
+
+def test_dispatch_waits_for_sustained_quiet():
+ q, clock = _make_queue()
+ agent = _FakeAgent()
+ q.enqueue(agent, "s1", {"task_cfg": {}})
+
+ # A live turn: nothing dispatches.
+ q.note_turn_started()
+ assert q._pop_dispatchable() is None
+
+ # Turn finished, but the settle window hasn't elapsed.
+ q.note_turn_finished()
+ assert q._pop_dispatchable() is None
+
+ # Quiet long enough -> dispatchable.
+ clock["t"] += _IDLE_SETTLE_S + 1
+ item = q._pop_dispatchable()
+ assert item is not None and item.session_key == "s1"
+ assert q.pending_count() == 0
+
+
+def test_dispatch_blocked_by_busy_server():
+ q, clock = _make_queue(server_idle=False)
+ agent = _FakeAgent()
+ q.enqueue(agent, "s1", {"task_cfg": {}})
+ q.note_turn_started()
+ q.note_turn_finished()
+ clock["t"] += _IDLE_SETTLE_S + 1
+ # Process is quiet but the managed server has a processing slot
+ # (another profile's session, a live prefill): hold.
+ assert q._pop_dispatchable() is None
+ assert q.pending_count() == 1
+
+
+def test_aged_out_item_dispatches_despite_busy_server():
+ q, clock = _make_queue(server_idle=False)
+ agent = _FakeAgent()
+ q.enqueue(agent, "s1", {"task_cfg": {"defer_max_age_s": 60}})
+ q.note_turn_started() # never goes quiet
+ clock["t"] += 61
+ item = q._pop_dispatchable()
+ assert item is not None
+ assert item.session_key == "s1"
+
+
+def test_new_turn_resets_the_quiet_clock():
+ q, clock = _make_queue()
+ agent = _FakeAgent()
+ q.enqueue(agent, "s1", {"task_cfg": {}})
+ q.note_turn_started()
+ q.note_turn_finished()
+ clock["t"] += _IDLE_SETTLE_S - 2
+ # A new prompt arrives just before the settle window closes.
+ q.note_turn_started()
+ clock["t"] += 30
+ assert q._pop_dispatchable() is None # still live
+ q.note_turn_finished()
+ assert q._pop_dispatchable() is None # settle restarts
+ clock["t"] += _IDLE_SETTLE_S + 1
+ assert q._pop_dispatchable() is not None
+
+
+def test_nested_turns_require_all_to_finish():
+ q, clock = _make_queue()
+ agent = _FakeAgent()
+ q.enqueue(agent, "s1", {"task_cfg": {}})
+ q.note_turn_started()
+ q.note_turn_started()
+ q.note_turn_finished()
+ clock["t"] += _IDLE_SETTLE_S + 1
+ assert q._pop_dispatchable() is None # one turn still live
+ q.note_turn_finished()
+ clock["t"] += _IDLE_SETTLE_S + 1
+ assert q._pop_dispatchable() is not None
+
+
+# ── the decision wrapper ─────────────────────────────────────────
+
+
+def _wrapper_agent(monkeypatch, defer="auto", managed=True):
+ """A minimal object wearing the real _spawn_background_review."""
+ import run_agent
+ from agent import review_idle_queue as riq
+
+ agent = _FakeAgent()
+ agent._delegate_depth = 0
+ calls = {"enqueued": [], "spawned": []}
+
+ monkeypatch.setattr(
+ "agent.background_review.load_background_review_settings",
+ lambda: (True, {"defer": defer}),
+ )
+ monkeypatch.setattr(
+ riq, "review_targets_managed_local", lambda a, cfg: managed
+ )
+ monkeypatch.setattr(
+ riq.QUEUE, "enqueue",
+ lambda a, key, kw: calls["enqueued"].append((key, kw)),
+ )
+ agent._spawn_background_review_now = (
+ lambda **kw: calls["spawned"].append(kw)
+ )
+ bound = types.MethodType(run_agent.AIAgent._spawn_background_review, agent)
+ return bound, calls
+
+
+def test_wrapper_defers_managed_local_auto(monkeypatch):
+ spawn, calls = _wrapper_agent(monkeypatch, defer="auto", managed=True)
+ spawn([{"role": "user", "content": "hi"}], review_memory=True)
+ assert len(calls["enqueued"]) == 1
+ assert calls["spawned"] == []
+ key, kwargs = calls["enqueued"][0]
+ assert key == "sess-x"
+ assert kwargs["review_memory"] is True
+
+
+def test_wrapper_spawns_immediately_for_non_managed(monkeypatch):
+ spawn, calls = _wrapper_agent(monkeypatch, defer="auto", managed=False)
+ spawn([{"role": "user", "content": "hi"}], review_skills=True)
+ assert calls["enqueued"] == []
+ assert len(calls["spawned"]) == 1
+
+
+def test_wrapper_defer_never_is_old_behavior(monkeypatch):
+ spawn, calls = _wrapper_agent(monkeypatch, defer="never", managed=True)
+ spawn([{"role": "user", "content": "hi"}], review_memory=True)
+ assert calls["enqueued"] == []
+ assert len(calls["spawned"]) == 1
+
+
+def test_wrapper_refine_bypasses_queue(monkeypatch):
+ spawn, calls = _wrapper_agent(monkeypatch, defer="auto", managed=True)
+ spawn([{"role": "user", "content": "hi"}], review_memory=True,
+ focus="save the deploy workflow")
+ assert calls["enqueued"] == []
+ assert len(calls["spawned"]) == 1
+ assert calls["spawned"][0]["focus"] == "save the deploy workflow"
+
+
+# ── requeue on preemption ────────────────────────────────────────
+
+
+class _Run:
+ def __init__(self, cancelled):
+ self.cancel_requested = threading.Event()
+ if cancelled:
+ self.cancel_requested.set()
+
+
+def _requeue_agent(monkeypatch, managed=True):
+ import run_agent
+ from agent import review_idle_queue as riq
+
+ agent = _FakeAgent()
+ calls = {"enqueued": []}
+ monkeypatch.setattr(
+ riq, "review_targets_managed_local", lambda a, cfg: managed
+ )
+ monkeypatch.setattr(
+ riq.QUEUE, "enqueue",
+ lambda a, key, kw: calls["enqueued"].append(kw),
+ )
+ agent._REVIEW_REQUEUE_MAX_ATTEMPTS = (
+ run_agent.AIAgent._REVIEW_REQUEUE_MAX_ATTEMPTS
+ )
+ bound = types.MethodType(
+ run_agent.AIAgent._maybe_requeue_preempted_review, agent
+ )
+ return bound, calls
+
+
+def test_preempted_review_requeues(monkeypatch):
+ requeue, calls = _requeue_agent(monkeypatch)
+ requeue(_Run(cancelled=True),
+ {"task_cfg": {"defer": "auto"}, "focus": None,
+ "_requeue_attempts": 1})
+ assert len(calls["enqueued"]) == 1
+ # The attempt counter rides along so the cap survives the round trip.
+ assert calls["enqueued"][0]["_requeue_attempts"] == 1
+
+
+def test_completed_review_does_not_requeue(monkeypatch):
+ requeue, calls = _requeue_agent(monkeypatch)
+ requeue(_Run(cancelled=False),
+ {"task_cfg": {"defer": "auto"}, "focus": None,
+ "_requeue_attempts": 1})
+ assert calls["enqueued"] == []
+
+
+def test_requeue_attempt_cap(monkeypatch):
+ requeue, calls = _requeue_agent(monkeypatch)
+ requeue(_Run(cancelled=True),
+ {"task_cfg": {"defer": "auto"}, "focus": None,
+ "_requeue_attempts": 4})
+ assert calls["enqueued"] == []
+
+
+def test_requeue_skips_non_managed(monkeypatch):
+ requeue, calls = _requeue_agent(monkeypatch, managed=False)
+ requeue(_Run(cancelled=True),
+ {"task_cfg": {"defer": "auto"}, "focus": None,
+ "_requeue_attempts": 1})
+ assert calls["enqueued"] == []
diff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.md
index 205f3e493b4..1a9dc1867b5 100644
--- a/website/docs/user-guide/features/memory.md
+++ b/website/docs/user-guide/features/memory.md
@@ -350,6 +350,38 @@ Fork usage is persisted in `session_model_usage` with `task='background_review'`
and a completion line is written to `agent.log`
(`Background review complete: thread=bg-review calls=… in=… out=… result=…`).
+### Local models: reviews wait for an idle GPU (`defer`)
+
+On a cloud provider the review finishes in seconds and runs alongside
+whatever you do next. When the review's runtime is the **managed local
+llama-server** (Settings → Local models), the same fork occupies the GPU your
+next prompt needs — for minutes on a large model — and sending a new prompt
+cancels it, discarding the learning. So on the managed local runtime, reviews
+are **deferred by default**: queued at turn end and executed once the machine
+has been quiet for a short settle window. Nothing about the review itself
+changes — same model, same full-transcript replay, same writes — only the
+execution moment moves.
+
+```yaml
+auxiliary:
+ background_review:
+ defer: auto # auto (default) | never
+ defer_max_age_s: 1800 # run a queued review anyway after this long
+```
+
+| Value | Behaviour |
+|-------|-----------|
+| `auto` (default) | Reviews whose runtime resolves to the managed local server are queued and run at idle; every other runtime (cloud, external servers) spawns immediately as before. |
+| `never` | Old behavior everywhere: spawn immediately at turn end, even on the managed local GPU. |
+
+Queued reviews coalesce per session (a newer turn's snapshot replaces the
+older one — the review replays the whole conversation, so nothing is lost),
+a review preempted by a new prompt is re-queued instead of discarded, and a
+review that has waited longer than `defer_max_age_s` runs even if the machine
+never goes idle. Explicit `/refine` always runs immediately. The queue is
+in-memory: reviews still pending when the app exits are dropped, same as an
+in-flight fork would have been.
+
## Controlling skill writes (`skills.write_approval`)
Skills use the same on/off gate, but the review UX differs because a