Skip to content

The agent that grows with you

feat(notifications): opt-in suppression of user-channel warning notifications

Victor Kyriazakoscd3de040ab9c
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 537013d77f6..cd4c532ec36 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -952,7 +952,9 @@ def _init_openai_client(agent, api_key, base_url, fallback_model, _provider_time
print(f"🤖 AI Agent initialized with model: {agent.model}")
if base_url:
print(f"🔗 Using custom base URL: {base_url}")
- _print_key_banner(client_kwargs.get("api_key", "none"), "API key", warn_missing=True)
+ from gateway.warning_notifications import warning_notifications_enabled
+ _print_key_banner(client_kwargs.get("api_key", "none"), "API key",
+ warn_missing=warning_notifications_enabled(agent.platform))
except Exception as e:
raise RuntimeError(f"Failed to initialize OpenAI client: {e}")
@@ -1097,7 +1099,7 @@ def _load_tools(agent, enabled_toolsets, disabled_toolsets):
requirements = model_tools.check_toolset_requirements()
missing_reqs = [name for name, available in requirements.items() if not available]
if missing_reqs:
- print(f"⚠️ Some tools may not work due to missing requirements: {missing_reqs}")
+ agent._safe_print(f"⚠️ Some tools may not work due to missing requirements: {missing_reqs}", diagnostic=True)
else:
print("🛠️ No tools loaded (all tools filtered out or unavailable)")
if agent.save_trajectories:
@@ -1522,12 +1524,23 @@ def _parse_compression_config(agent, _agent_cfg) -> CompressionSettings:
def _warn_invalid_config_int(
what: str, value: Any, requirement: str, fallback: str, print_fallback: str = "",
+ agent: Any = None,
) -> None:
"""Log + stderr-print an invalid integer config value (``print_fallback``: user-facing
- wording where it differs from the log line)."""
+ wording where it differs from the log line). The print is an automatic diagnostic and
+ honors the warning-notification policy; the log line never does."""
_ra().logger.warning(
"Invalid %s: %r — %s. Falling back to %s.", what, value, requirement, fallback,
)
+ from gateway.warning_notifications import warning_notifications_enabled
+ try:
+ if not warning_notifications_enabled(
+ getattr(agent, "_notification_platform", getattr(agent, "platform", "cli")),
+ getattr(agent, "_notification_config", None),
+ ):
+ return
+ except Exception:
+ pass
print(
f"\n⚠ Invalid {what}: {value!r}\n"
f" {requirement[0].upper() + requirement[1:]}.\n"
@@ -1681,6 +1694,7 @@ def _warn_invalid_custom_provider_context_length(agent, _custom_providers) -> No
_warn_invalid_config_int(
f"context_length for model {agent.model!r} in custom_providers",
_cp_ctx, _CTX_LEN_REQUIREMENT, "auto-detection", "auto-detected context window",
+ agent=agent,
)
return
@@ -1708,7 +1722,7 @@ def _resolve_context_length(agent, _agent_cfg, base_url):
_warn_invalid_config_int(
"model.context_length in config.yaml", _config_context_length,
"must be a plain integer (e.g. 256000, not '256K')",
- "auto-detection", "auto-detected context window",
+ "auto-detection", "auto-detected context window", agent=agent,
)
_config_context_length = None
@@ -2083,7 +2097,7 @@ def _emit_compression_summary(agent, cs):
print(f"📊 Context limit: {_cc.context_length:,} tokens (auto-compression disabled)")
# Gateway users get the same text via _compression_warning on turn 1.
if _autoraise_notice:
- print(_autoraise_notice)
+ agent._safe_print(_autoraise_notice, diagnostic=True)
# status_callback isn't wired yet: stash for replay on the first turn; mark shown so
# repeated inits stay silent.
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 43b095a340b..90f3078c328 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -970,7 +970,7 @@ def try_recover_primary_transport(
wait_time = min(3 + retry_count, 8)
agent._vprint(
f"{agent.log_prefix}🔁 Transient {error_type} on {agent.provider} — "
- f"rebuilt client, waiting {wait_time}s before one last primary attempt.", force=True,
+ f"rebuilt client, waiting {wait_time}s before one last primary attempt.", force=True, diagnostic=True,
)
time.sleep(wait_time)
return True
@@ -1195,7 +1195,7 @@ def restore_primary_runtime(agent) -> bool:
if provider_fallback_active:
# Notification surfaces are best-effort and must never undo a successful restore.
with contextlib.suppress(Exception):
- agent._emit_status(
+ agent._emit_diagnostic_status(
f"✅ Primary model restored: {agent.model} via {agent.provider}; "
f"fallback {previous_model} via {previous_provider} is no longer active."
)
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index ec44738a7c2..a940e631c03 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -589,7 +589,7 @@ def _report_stale_nonstream_kill(agent, api_kwargs: dict, elapsed: float, stale_
"model=%s context=~%s tokens. Killing connection.", "Inline n" if inline else "N", elapsed,
stale_timeout, model, f"{estimate_request_context_tokens(api_kwargs):,}")
try:
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"⚠️ No response from provider for {int(elapsed)}s (non-streaming, model: {model}). {hint or 'Aborting call.'}")
except Exception:
logger.debug("stale status buffering failed", exc_info=True)
@@ -1894,7 +1894,7 @@ def _rescope_fallback_extra_body(agent, old_model: str, old_provider: str, old_b
def _buffer_fallback_notice(agent, notice: str) -> None:
"""Buffer the switch notice for terminal failure AND retain it as a durable one-shot for
_emit_pending_fallback_notice (a successful fallback clears retry chatter)."""
- agent._buffer_status(notice)
+ agent._buffer_diagnostic_status(notice)
pending = getattr(agent, "_pending_fallback_notice", None)
if isinstance(pending, list):
pending.append(notice)
@@ -2164,7 +2164,7 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str:
# stdout so wrappers receive only the final assistant content (#93220 class).
logger.warning(warning)
else:
- agent._safe_print(warning)
+ agent._safe_print(warning, diagnostic=True)
summary_api_request_id = f"iteration-summary:{uuid.uuid4()}"
summary_call_outcome = "failed"
@@ -2396,7 +2396,7 @@ class _BedrockStream:
self.agent._disable_streaming = True
self.agent._safe_print("\n⚠ AWS IAM denied bedrock:InvokeModelWithResponseStream — "
"falling back to non-streaming InvokeModel.\n"
- " Grant that action to restore streaming output.\n")
+ " Grant that action to restore streaming output.\n", diagnostic=True)
logger.info("bedrock: converse_stream denied by IAM (%s) — "
"using non-streaming converse() for this session.", type(exc).__name__)
return normalize_converse_response(client.converse(**final_kwargs))
@@ -2464,7 +2464,7 @@ class _BedrockStream:
logger.warning("Bedrock stream stale for %.0fs (threshold %.0fs) — no events "
"received. region=%s model=%s. Aborting call.", stale_elapsed, self.stale_timeout, self.region,
self._model())
- agent._buffer_status(f"⚠️ No events from Bedrock for {int(stale_elapsed)}s (model: {self._model()}). Aborting...")
+ agent._buffer_diagnostic_status(f"⚠️ No events from Bedrock for {int(stale_elapsed)}s (model: {self._model()}). Aborting...")
_bump_stale_streak(agent)
# Evict the region's cached client so the NEXT call gets a fresh pool.
# This does NOT abort the in-flight botocore EventStream (no external
@@ -3234,7 +3234,8 @@ class _StreamingCall(StreamingWaitMonitor):
" Grant that action to restore streaming output.\n"
if _is_bedrock_stream_denied else
"\n⚠ Streaming is not supported for this model/provider. Switching to non-streaming.\n"
- " To avoid this delay, set display.streaming: false in config.yaml\n"
+ " To avoid this delay, set display.streaming: false in config.yaml\n",
+ diagnostic=True,
)
def _handle_stream_error(self, e: Exception, attempt: int, max_retries: int) -> bool:
@@ -3293,7 +3294,8 @@ class _StreamingCall(StreamingWaitMonitor):
return False
# Marker explains the re-streamed preamble (``_emit_stream_drop`` logs the WARNING);
# reset the streamed-text buffer so it isn't double-recorded; fresh accumulators.
- self._quiet(self.agent._fire_stream_delta, "\n\n⚠ Connection dropped mid tool-call; reconnecting…\n\n")
+ if self.agent._warning_presentation_enabled():
+ self._quiet(self.agent._fire_stream_delta, "\n\n⚠ Connection dropped mid tool-call; reconnecting…\n\n")
self._quiet(self.agent._reset_stream_delivery_tracking)
self.deltas_were_sent["yes"] = False
self.first_delta_fired["done"] = False
@@ -3312,7 +3314,7 @@ class _StreamingCall(StreamingWaitMonitor):
_what = ("Provider returned malformed streaming data after" if _is_stream_parse_err
else "Provider returned an empty response stream after" if _is_empty_stream
else "Connection to provider failed after")
- self.agent._buffer_status(
+ self.agent._buffer_diagnostic_status(
f"❌ {_what} {max_retries + 1} attempts. The provider may be experiencing issues — try again in a moment.")
else:
self._maybe_disable_streaming(e)
@@ -3421,7 +3423,7 @@ class _StreamingCall(StreamingWaitMonitor):
"Stream stale for %.0fs (threshold %.0fs) — no chunks received. model=%s context=~%s tokens. Killing connection.",
elapsed, self._stream_stale_timeout, self.api_kwargs.get("model", "unknown"), f"{_est_ctx:,}",
)
- self.agent._buffer_status(
+ self.agent._buffer_diagnostic_status(
f"⚠️ No response from provider for {int(elapsed)}s (model: {self.api_kwargs.get('model', 'unknown')}, "
f"context: ~{_est_ctx:,} tokens). Reconnecting...")
# Captured BEFORE the cancel/abort: the pool sweep can miss a checked-out
@@ -3435,7 +3437,7 @@ class _StreamingCall(StreamingWaitMonitor):
_bump_stale_streak(self.agent) # circuit breaker, see ``_stale_streak()``
# Reset the timer so we don't kill repeatedly while the worker unwinds.
self.last_chunk_time["t"] = time.time()
- self.agent._emit_wait_notice(f"⚠ no output from provider for {int(elapsed)}s — reconnecting...")
+ self.agent._emit_diagnostic_wait(f"⚠ no output from provider for {int(elapsed)}s — reconnecting...")
self.agent._touch_activity(f"stale stream detected after {int(elapsed)}s, reconnecting")
def _abort_for_interrupt(self, stale_elapsed: float) -> None:
@@ -3499,8 +3501,9 @@ class _StreamingCall(StreamingWaitMonitor):
_name_str += f", +{len(_partial_names) - 3} more"
_warn = (f"\n\n⚠ Stream stalled mid tool-call ({_name_str}); the action was not executed. "
f"Ask me to retry if you want to continue.")
- _partial_text = (_partial_text or "") + _warn
- self._quiet(self.agent._fire_stream_delta, _warn) # visible immediately
+ _partial_text = (_partial_text or "") + _warn # model/result bookkeeping, never gated
+ if self.agent._warning_presentation_enabled():
+ self._quiet(self.agent._fire_stream_delta, _warn) # visible immediately
logger.warning(
"Partial stream dropped tool call(s) %s after %s chars of text; surfaced warning to user: %s",
_partial_names, len(_partial_text or ""), error)
diff --git a/agent/chat_completion_nonstream.py b/agent/chat_completion_nonstream.py
index f9edbfcb01e..17127b41157 100644
--- a/agent/chat_completion_nonstream.py
+++ b/agent/chat_completion_nonstream.py
@@ -173,11 +173,11 @@ class _NonStreamRequest:
"(%.0fs > %.0fs, model=%s). Backend accepted the connection "
"but sent no stream events. Killing connection so the retry loop can reconnect.", elapsed,
wd.ttfb_timeout, self._model())
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"⚠️ No first stream event from provider in {int(elapsed)}s (codex stream, model: {self._model()}). "
f"Reconnecting." + (f" {silent_hint}" if silent_hint else ""))
self._abort_request("codex_ttfb_kill")
- agent._emit_wait_notice(f"⚠ no response from provider in {int(elapsed)}s — reconnecting...")
+ agent._emit_diagnostic_wait(f"⚠ no response from provider in {int(elapsed)}s — reconnecting...")
agent._touch_activity(f"codex stream killed after {int(elapsed)}s with no first stream event")
self._await_worker_after_kill(
f"Codex stream produced no parsed stream event within {int(elapsed)}s "
@@ -197,7 +197,7 @@ class _NonStreamRequest:
"(threshold %.0fs, model=%s, context=~%s tokens). Killing "
"connection so the retry loop can reconnect.", event_stale_elapsed, arm_point, wd.idle_timeout,
self._model(), f"{wd.est_tokens:,}")
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"⚠️ Codex stream sent no events for {int(event_stale_elapsed)}s after {arm_point} "
f"(model: {self._model()}). Reconnecting.")
self._abort_request("codex_stream_idle_kill")
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 82a39d14a36..25e6756f331 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -1847,7 +1847,7 @@ def _lower_threshold_to_aux_context(
f"{recomputed_threshold:,} tokens, still above the compression model's {aux_context:,}.)"
)
agent._compression_warning = msg
- agent._emit_status(msg)
+ agent._emit_diagnostic_status(msg)
logger.warning(
"Auxiliary compression model %s has %d token context, below the main model's compression threshold of %d "
"tokens — auto-lowered session threshold to %d to keep compression working.", aux_model, aux_context,
@@ -1904,7 +1904,7 @@ def check_compression_model_feasibility(agent: Any) -> None:
"long chats, so older messages will be cut without a summary. Run `hermes setup` to add one."
)
agent._compression_warning = msg
- agent._emit_status(msg)
+ agent._emit_diagnostic_status(msg)
logger.warning("No auxiliary LLM provider for compression — summaries will be unavailable.")
return
aux_base_url = str(getattr(client, "base_url", ""))
@@ -1958,8 +1958,10 @@ def replay_compression_warning(agent: Any) -> None:
``__init__``) is finally wired."""
msg = getattr(agent, "_compression_warning", None)
if msg and agent.status_callback:
+ # Replayed as a classified diagnostic so every sink applies its own policy snapshot.
+ from gateway.warning_notifications import DiagnosticText
with contextlib.suppress(Exception):
- agent.status_callback("lifecycle", msg)
+ agent.status_callback("lifecycle", DiagnosticText(msg))
def conversation_history_after_compression(
@@ -3216,7 +3218,7 @@ def _finish_compaction_boundary(
f"{agent.log_prefix}⚠️ Session compressed {_cc} times — accuracy may degrade. Consider /new to start fresh."
)
agent._compression_warning = _cc_msg
- agent._emit_status(_cc_msg)
+ agent._emit_diagnostic_status(_cc_msg)
# session:compress lets hooks ingest the old session before it's lost;
# in_place=True tells them the same id was compacted rather than rotated.
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 258af33cbfc..6065da4ac0a 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -465,7 +465,7 @@ def _print_guidance(agent, message: str) -> bool:
if not message:
return False
for line in message.splitlines():
- agent._vprint(f"{agent.log_prefix} 💡 {line}", force=True)
+ agent._vprint(f"{agent.log_prefix} 💡 {line}", force=True, diagnostic=True)
return True
diff --git a/agent/fallback_cooldown.py b/agent/fallback_cooldown.py
index 5ed9261f7be..ee4efae5db2 100644
--- a/agent/fallback_cooldown.py
+++ b/agent/fallback_cooldown.py
@@ -65,7 +65,7 @@ def _mark_entitlement_rejected_model(agent, api_error) -> bool:
"treating it as unavailable for this session",
model, provider,
)
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"🚫 This account is not entitled to {model} via {provider}; it will be skipped "
"until restart. Switch to an entitled model via /model or `hermes model`."
)
diff --git a/agent/notification_presentation.py b/agent/notification_presentation.py
new file mode 100644
index 00000000000..f4ac9558b14
--- /dev/null
+++ b/agent/notification_presentation.py
@@ -0,0 +1,83 @@
+"""Turn-local presentation of diagnostic-only wakes; execution and controls stay live."""
+from contextlib import contextmanager
+from contextvars import ContextVar
+
+
+_muted_surface: ContextVar[str | None] = ContextVar("muted_notification_surface", default=None)
+# These are text/media UI events, not approval/clarify/connection requests or outcomes.
+_FREEFORM_EVENTS = frozenset({
+ "message.start", "message.delta", "message.interim", "message.complete",
+ "reasoning.delta", "thinking.delta", "status.update", "notification.show",
+ "tool.start", "tool.complete", "tool.generating", "error", "reaction",
+})
+_PRESENTATION_CALLBACKS = (
+ "stream_delta_callback", "interim_assistant_callback", "reasoning_callback",
+ "tool_progress_callback",
+ "tool_start_callback", "tool_complete_callback", "tool_gen_callback", "reaction_callback",
+)
+
+
+def event_presentation_muted(event: str, session_id: str) -> bool:
+ return _muted_surface.get() == session_id and event in _FREEFORM_EVENTS
+
+
+def diagnostic_process_event(event: dict) -> bool:
+ """Early failure/monitor diagnostics, not the explicitly requested final result."""
+ return bool(event.get("task_failure_notice")) or event.get("type") in {
+ "watch_disabled", "watch_overflow_tripped", "watch_overflow_released",
+ }
+
+
+def notification_config_snapshot():
+ """Read the canonical owning effective config once; presentation fails open."""
+ from copy import deepcopy
+ from hermes_cli.config_effective import load_user_config_effective
+ try:
+ config = load_user_config_effective()
+ return deepcopy(config) if isinstance(config, dict) else {}
+ except Exception:
+ return {}
+
+
+@contextmanager
+def notification_policy_snapshot(agent, platform, config):
+ """Bind one foreground policy for callbacks, including worker threads."""
+ from copy import deepcopy
+ missing = object()
+ saved = {key: getattr(agent, key, missing)
+ for key in ("_notification_config", "_notification_platform")}
+ try:
+ agent._notification_config = deepcopy(config)
+ agent._notification_platform = platform
+ yield
+ finally:
+ for key, value in saved.items():
+ if value is missing:
+ delattr(agent, key)
+ else:
+ setattr(agent, key, value)
+
+
+@contextmanager
+def notification_turn(agent, *, muted: bool, session_id: str = ""):
+ """Freeze the current turn's presentation without touching prompts or tool schemas."""
+ if not muted:
+ yield
+ return
+ missing = object()
+ keys = (*_PRESENTATION_CALLBACKS, "suppress_status_output", "_mute_notification_reply")
+ saved = {key: getattr(agent, key, missing) for key in keys}
+ token = _muted_surface.set(session_id)
+ try:
+ for key in _PRESENTATION_CALLBACKS:
+ setattr(agent, key, None)
+ agent.suppress_status_output = True
+ agent._mute_notification_reply = True
+ yield
+ finally:
+ for key, value in saved.items():
+ if value is missing:
+ delattr(agent, key)
+ else:
+ setattr(agent, key, value)
+ _muted_surface.reset(token)
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 5af23d1aa36..26572c32d90 100644
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@ -207,6 +207,11 @@ def _db_flush_collect(agent, messages: List[Dict], conversation_history: Optiona
) and not msg.get(_PERSIST_AFTER_ADMISSION_INTERRUPT):
msg[_DB_PERSISTED_MARKER] = True
continue
+ if getattr(agent, "_mute_notification_reply", False):
+ # Only new rows, never the cached history prefix. Keep evidence/model
+ # context intact while transcript pollers omit unsolicited presentation.
+ msg["display_kind"] = "hidden"
+ msg["display_metadata"] = {**(msg.get("display_metadata") or {}), "notification_category": "diagnostic"}
batch_rows.append(_db_flush_row(agent, msg, ov_idx == msg_idx or msg is pending_cli_message))
batch_msgs.append(msg)
return batch_rows, batch_msgs
diff --git a/agent/status_output.py b/agent/status_output.py
index 7ba5c71d755..dad0ff2680e 100644
--- a/agent/status_output.py
+++ b/agent/status_output.py
@@ -16,19 +16,25 @@ logger = logging.getLogger("run_agent")
class StatusOutputMixin:
"""Status/warning/notice emission and retry-chatter buffering (see module docstring)."""
- def _safe_print(self, *args, **kwargs):
+ def _safe_print(self, *args, diagnostic: bool = False, **kwargs):
"""Print that swallows broken pipes / closed stdout (headless stdout can vanish mid-session);
routes through ``self._print_fn`` so the CLI can inject an ANSI-aware renderer."""
+ if getattr(self, "_mute_notification_reply", False):
+ return
+ if diagnostic and not self._warning_presentation_enabled():
+ return
try:
(self._print_fn or print)(*args, **kwargs)
except (OSError, ValueError):
pass
- def _vprint(self, *args, force: bool = False, **kwargs):
+ def _vprint(self, *args, force: bool = False, diagnostic: bool = False, **kwargs):
"""Verbose print — suppressed while tokens are streaming (allowed during tool execution) and after
the main response; ``force=True`` bypasses both. ``suppress_status_output`` (``hermes chat -q``) wins."""
if getattr(self, "suppress_status_output", False):
return
+ if diagnostic and not self._warning_presentation_enabled():
+ return
if force or not (getattr(self, "_mute_post_response", False) or (self._has_stream_consumers() and not self._executing_tools)):
self._safe_print(*args, **kwargs)
@@ -66,12 +72,30 @@ class StatusOutputMixin:
def _emit_status_kind(self, kind: str, message: str, *, origin: str) -> None:
"""Print to the CLI (``_vprint(force=True)``) and forward to ``status_callback(kind, message)``. Never raises."""
+ from gateway.warning_notifications import is_warning_status
try:
- self._vprint(f"{self.log_prefix}{message}", force=True)
+ if not is_warning_status(kind, message) or self._warning_presentation_enabled():
+ self._vprint(f"{self.log_prefix}{message}", force=True)
except Exception:
pass
self._call_callback("status_callback", kind, message, origin=origin)
+ def _warning_presentation_enabled(self) -> bool:
+ from gateway.warning_notifications import warning_notifications_enabled
+ try:
+ return warning_notifications_enabled(
+ getattr(self, "_notification_platform", getattr(self, "platform", "cli")),
+ getattr(self, "_notification_config", None),
+ )
+ except Exception:
+ # A presentation preference must never turn a recoverable notice into a failed turn.
+ return True
+
+ def _emit_diagnostic_status(self, message: str) -> None:
+ """A diagnostic on the lifecycle rail, without changing legacy formatting."""
+ from gateway.warning_notifications import DiagnosticText
+ self._emit_status(DiagnosticText(message))
+
def _emit_status(self, message: str) -> None:
"""Emit a lifecycle status message (CLI + gateway ``status_callback``)."""
self._emit_status_kind("lifecycle", message, origin="_emit_status")
@@ -132,6 +156,10 @@ class StatusOutputMixin:
self._touch_activity(text)
self._call_callback("thinking_callback", text, origin="_emit_wait_notice")
+ def _emit_diagnostic_wait(self, text: str) -> None:
+ from gateway.warning_notifications import DiagnosticText
+ self._emit_wait_notice(DiagnosticText(text))
+
# ── Buffered retry/fallback status: shown only when every retry/fallback is exhausted, dropped on
# success. Backend logs are unaffected (every site still logs). ──
@@ -149,6 +177,10 @@ class StatusOutputMixin:
def _buffer_status(self, message: str) -> None:
self._buffer_retry_message("status", message)
+ def _buffer_diagnostic_status(self, message: str) -> None:
+ from gateway.warning_notifications import DiagnosticText
+ self._buffer_status(DiagnosticText(message))
+
def _buffer_vprint(self, message: str) -> None:
self._buffer_retry_message("vprint", message)
@@ -169,7 +201,7 @@ class StatusOutputMixin:
self._pending_fallback_notice = None
for item in notice if isinstance(notice, list) else [notice]:
try:
- self._emit_status(str(item))
+ self._emit_diagnostic_status(item)
except Exception:
# One surface failure must not hide later switches from the same chain.
continue
@@ -190,6 +222,7 @@ class StatusOutputMixin:
if kind in replay:
replay[kind](msg)
else:
- self._vprint(f"{self.log_prefix}{msg}", force=True)
+ if self._warning_presentation_enabled():
+ self._vprint(f"{self.log_prefix}{msg}", force=True)
except Exception:
pass
diff --git a/agent/stream_diag.py b/agent/stream_diag.py
index f832bf976df..3bc1d56b537 100644
--- a/agent/stream_diag.py
+++ b/agent/stream_diag.py
@@ -146,7 +146,7 @@ def emit_stream_drop(
except Exception:
pass
try:
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"⚠️ {provider} stream {kind} ({type(error).__name__}){_suffix} "
f"— reconnecting, retry {attempt}/{max_attempts}"
)
diff --git a/agent/system_prompt.py b/agent/system_prompt.py
index 73e13d57465..9d5c5e1eccc 100644
--- a/agent/system_prompt.py
+++ b/agent/system_prompt.py
@@ -727,7 +727,7 @@ def build_system_prompt(agent: Any, system_message: Optional[str] = None) -> str
agent._cached_system_prompt_static = parts["stable"]
# Surface context-file truncation warnings in chat, not only in logs.
for warning in drain_truncation_warnings():
- agent._emit_status(warning)
+ agent._emit_diagnostic_status(warning)
return "\n\n".join(p for p in (parts["stable"], parts["context"], parts["volatile"]) if p)
diff --git a/agent/turn_api_call.py b/agent/turn_api_call.py
index 953a6843443..d8e14a891c3 100644
--- a/agent/turn_api_call.py
+++ b/agent/turn_api_call.py
@@ -254,7 +254,7 @@ def nous_rate_limit_guard(
else:
_nous_msg = f"Your Nous account has hit its rate limit; it resets in {reset}."
agent._buffer_vprint(f"⏳ {_nous_msg} Trying fallback...")
- agent._buffer_status(f"⏳ {_nous_msg}")
+ agent._buffer_diagnostic_status(f"⏳ {_nous_msg}")
if agent._try_activate_fallback():
active_system_prompt = _arm_fallback_restart(
agent, api_messages, active_system_prompt, _retry)
diff --git a/agent/turn_api_error.py b/agent/turn_api_error.py
index 8057b468790..1f056d9730d 100644
--- a/agent/turn_api_error.py
+++ b/agent/turn_api_error.py
@@ -326,7 +326,7 @@ def settle_unrecovered_error(
# before a silent abort.
if agent._has_pending_fallback():
_label = _NONRETRYABLE_LABELS.get(classified.reason, f"Non-retryable error (HTTP {status_code})")
- agent._buffer_status(f"⚠️ {_label} — trying fallback...")
+ agent._buffer_diagnostic_status(f"⚠️ {_label} — trying fallback...")
if agent._try_activate_fallback():
# Direct ``return _verdict("break")`` is load-bearing: the restart handler
# re-runs the pre-API preflight against the fallback's context window.
@@ -355,7 +355,7 @@ def settle_unrecovered_error(
agent._fallback_activated = False
return _verdict("continue")
if agent._has_pending_fallback():
- agent._buffer_status(f"⚠️ Max retries ({max_retries}) exhausted — trying fallback...")
+ agent._buffer_diagnostic_status(f"⚠️ Max retries ({max_retries}) exhausted — trying fallback...")
if agent._try_activate_fallback():
# Direct ``return _verdict("break")`` is load-bearing: the restart handler
# re-runs the pre-API preflight against the fallback's context window.
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 1847ccd71cf..fd671e52d52 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -521,7 +521,7 @@ def _reset_per_turn_agent_state(agent: Any) -> None:
if agent.api_mode != "anthropic_messages":
with suppress(Exception):
if agent._cleanup_dead_connections():
- agent._emit_status(
+ agent._emit_diagnostic_status(
"🔌 Detected stale connections from a previous provider "
"issue — cleaned up automatically. Proceeding with fresh "
"connection."
diff --git a/agent/turn_empty_response.py b/agent/turn_empty_response.py
index 813c53b43da..d13c8ceb215 100644
--- a/agent/turn_empty_response.py
+++ b/agent/turn_empty_response.py
@@ -74,7 +74,7 @@ def _retry_empty(
" — high-cost request, reduced retry budget"
if budget < _empty_guard.DEFAULT_EMPTY_RETRY_BUDGET else ""
)
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"⚠️ Empty response from model — retrying ({n}/{budget}) in {wait_time:.0f}s{_budget_note}"
)
_interrupted = interruptible_backoff_sleep(
@@ -99,7 +99,7 @@ def _terminal_empty(agent: Any, assistant_message: Any, finish_reason: str, mess
the sentinel so later "continue" turns don't replay it and loop on empties."""
_streak_cost = _empty_guard.streak_cost_usd(agent)
if _streak_cost is not None:
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"ℹ️ Estimated cost of these empty attempts: ~${_streak_cost:.2f} (input tokens are billed "
f"per attempt even when no answer is produced)"
)
@@ -118,7 +118,7 @@ def _terminal_empty(agent: Any, assistant_message: Any, finish_reason: str, mess
agent._empty_content_retries, agent.model,
agent.provider,
)
- agent._emit_status(
+ agent._emit_diagnostic_status(
"❌ Model returned no content after all retries"
+ (" and fallback attempts." if agent._fallback_chain else
". No fallback providers configured.")
@@ -129,7 +129,7 @@ def _terminal_empty(agent: Any, assistant_message: Any, finish_reason: str, mess
logger.warning(
"Reasoning-only response (no visible content) after exhausting retries and fallback. Reasoning: %s", reasoning_preview,
)
- agent._emit_status(
+ agent._emit_diagnostic_status(
"⚠️ Model produced reasoning but no visible response after all retries. Returning empty."
)
return site_copy("reasoning_only", model=agent.model, preview=reasoning_preview)
@@ -166,7 +166,7 @@ def recover_empty_response(
"Partial stream content delivered (%d chars) — using as final response",
len(_recovered),
)
- agent._emit_status("↻ Stream interrupted — using delivered content " "as final response")
+ agent._emit_diagnostic_status("↻ Stream interrupted — using delivered content " "as final response")
final_response = _recovered
# A streamed fragment isn't a confirmed preview: gateway fallback delivery
# sends the text plus the abnormal-turn explanation.
@@ -180,7 +180,7 @@ def recover_empty_response(
if fallback and getattr(agent, '_last_content_tools_all_housekeeping', False):
_turn_exit_reason = "fallback_prior_turn_content"
logger.info("Empty follow-up after tool calls — using prior turn content as final response")
- agent._emit_status("↻ Empty response after tool calls — using earlier content as final answer")
+ agent._emit_diagnostic_status("↻ Empty response after tool calls — using earlier content as final answer")
agent._last_content_with_tools = None
agent._last_content_tools_all_housekeeping = False
agent._empty_content_retries = 0
@@ -204,7 +204,7 @@ def recover_empty_response(
agent._last_content_with_tools = None
agent._last_content_tools_all_housekeeping = False
logger.info("Empty response after tool calls — nudging model " "to continue processing")
- agent._buffer_status("⚠️ Model returned empty after tool calls — " "nudging to continue")
+ agent._buffer_diagnostic_status("⚠️ Model returned empty after tool calls — " "nudging to continue")
# tool → assistant("(empty)") → user keeps the sequence valid.
_nudge_msg = agent._build_assistant_message(assistant_message, finish_reason)
_nudge_msg["content"] = "(empty)"
@@ -229,7 +229,7 @@ def recover_empty_response(
"Thinking-only response (no visible content) — prefilling to continue (%d/2)",
agent._thinking_prefill_retries,
)
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"↻ Thinking-only response — prefilling to continue ({agent._thinking_prefill_retries}/2)"
)
interim_msg = agent._build_assistant_message(assistant_message, "incomplete")
@@ -256,7 +256,7 @@ def recover_empty_response(
"skipping remaining retries",
agent.model, agent.provider, finish_reason,
)
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
"⚠️ Model is repeatedly returning empty content — skipping further retries "
"to avoid repeat charges"
)
@@ -267,11 +267,11 @@ def recover_empty_response(
"Empty response after %d retries — attempting fallback (model=%s, provider=%s)",
agent._empty_content_retries, agent.model, agent.provider,
)
- agent._buffer_status("⚠️ Model returning empty responses — " "switching to fallback provider...")
+ agent._buffer_diagnostic_status("⚠️ Model returning empty responses — " "switching to fallback provider...")
if agent._try_activate_fallback():
active_system_prompt = _sync_failover_system_message(agent, api_messages, active_system_prompt)
agent._empty_content_retries = 0
- agent._buffer_status(f"↻ Switched to fallback: {agent.model} " f"({agent.provider})")
+ agent._buffer_diagnostic_status(f"↻ Switched to fallback: {agent.model} " f"({agent.provider})")
logger.info(
"Fallback activated after empty responses: now using %s on %s",
agent.model, agent.provider,
diff --git a/agent/turn_final_response.py b/agent/turn_final_response.py
index 2fab0bc4f76..ecda17c965d 100644
--- a/agent/turn_final_response.py
+++ b/agent/turn_final_response.py
@@ -226,7 +226,7 @@ def finish_text_response(
"(retry %d/3, model=%s provider=%s)",
agent._dropped_toolcall_retries, agent.model, agent.provider,
)
- agent._emit_status(
+ agent._emit_diagnostic_status(
"↻ Model signaled a tool call but sent none — "
f"re-prompting ({agent._dropped_toolcall_retries}/3)"
)
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py
index f466ce35cbf..a1a46cfc488 100644
--- a/agent/turn_finalizer.py
+++ b/agent/turn_finalizer.py
@@ -144,14 +144,14 @@ def _resolve_budget_fallback(
preserved_verification_fallback = True
else:
# _handle_max_iterations makes one extra toolless request for a summary.
- agent._emit_status(
+ agent._emit_diagnostic_status(
f"⚠️ Iteration budget exhausted ({api_call_count}/{agent.max_iterations}) "
"— asking model to summarise"
)
if not agent.quiet_mode:
agent._safe_print(
f"\n⚠️ Iteration budget exhausted ({api_call_count}/{agent.max_iterations}) "
- "— requesting summary..."
+ "— requesting summary...", diagnostic=True,
)
final_response = agent._handle_max_iterations(messages, api_call_count)
diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.py
index 950f1ed6a16..865ce3ed927 100644
--- a/agent/turn_iteration_prep.py
+++ b/agent/turn_iteration_prep.py
@@ -344,7 +344,7 @@ def begin_iteration(
agent._safe_print(
f"\n⏹️ Review input budget exhausted "
f"({int(agent.session_input_tokens):,} tokens) — stopping "
- f"the review tool loop before the next provider call."
+ f"the review tool loop before the next provider call.", diagnostic=True,
)
return _verdict("break")
@@ -361,7 +361,7 @@ def begin_iteration(
elif not agent.iteration_budget.consume():
_turn_exit_reason = "budget_exhausted"
if not agent.quiet_mode:
- agent._safe_print(f"\n⚠️ Iteration budget exhausted ({agent.iteration_budget.used}/{agent.iteration_budget.max_total} iterations used)")
+ agent._safe_print(f"\n⚠️ Iteration budget exhausted ({agent.iteration_budget.used}/{agent.iteration_budget.max_total} iterations used)", diagnostic=True)
return _verdict("break")
return _verdict("fallthrough")
@@ -512,7 +512,7 @@ def apply_retry_restarts(
# All retries may exhaust with `response` still None; break out cleanly.
if response is None:
_turn_exit_reason = "all_retries_exhausted_no_response"
- agent._emit_status("❌ The model provider didn't answer after all retries. Send /retry, or switch models with /model.")
+ agent._emit_diagnostic_status("❌ The model provider didn't answer after all retries. Send /retry, or switch models with /model.")
agent._persist_session(messages, conversation_history)
return _verdict("break")
return _verdict("fallthrough")
diff --git a/agent/turn_loop_errors.py b/agent/turn_loop_errors.py
index 09f69819360..1e90dd81a5e 100644
--- a/agent/turn_loop_errors.py
+++ b/agent/turn_loop_errors.py
@@ -71,7 +71,7 @@ def handle_outer_loop_error(
if sys.is_finalizing() or _is_interpreter_shutdown_error(e):
error_msg = f"Interpreter is shutting down — cannot continue (API call #{api_call_count}): {e}"
try:
- agent._safe_print(f"❌ {error_msg}")
+ agent._safe_print(f"❌ {error_msg}", diagnostic=True)
except (OSError, ValueError):
pass
logger.warning(error_msg)
@@ -110,7 +110,7 @@ def handle_outer_loop_error(
logger.error(error_msg)
else:
try:
- print(f"❌ {error_msg}")
+ agent._safe_print(f"❌ {error_msg}", diagnostic=True)
except (OSError, ValueError):
logger.error(error_msg)
diff --git a/agent/turn_overflow.py b/agent/turn_overflow.py
index 29df54a4d63..8bfe095dc6e 100644
--- a/agent/turn_overflow.py
+++ b/agent/turn_overflow.py
@@ -96,7 +96,7 @@ class _Recovery(OverflowVerdict):
if notices:
agent._flush_status_buffer()
for line in notices:
- agent._vprint(f"{agent.log_prefix}{line}", force=True)
+ agent._vprint(f"{agent.log_prefix}{line}", force=True, diagnostic=True)
if log:
logger.error(*log)
agent._persist_session(self.messages, self.conversation_history)
@@ -203,9 +203,9 @@ class _Recovery(OverflowVerdict):
new_tokens = estimate_messages_tokens_rough(messages)
shrank_tokens = new_tokens > 0 and new_tokens < original_tokens * 0.95
if len(messages) < original_len:
- self.agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
+ self.agent._buffer_diagnostic_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
elif shrank_tokens:
- self.agent._buffer_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))
+ self.agent._buffer_diagnostic_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))
return None, len(messages) < original_len or shrank_tokens, new_tokens
def request_tokens(self) -> int:
@@ -226,7 +226,7 @@ def _recover_payload_too_large(st: _Recovery, _retry: TurnRetryState) -> Overflo
exhausted = st.count_attempt(payload_too_large=True)
if exhausted is not None:
return exhausted
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"⚠️ Request payload too large (413) — compression attempt "
f"{st.compression_attempts}/{st.max_compression_attempts}..."
)
@@ -252,9 +252,9 @@ def _recover_payload_too_large(st: _Recovery, _retry: TurnRetryState) -> Overflo
new_bytes = serialized_messages_bytes(messages)
if len(messages) < original_len or (new_bytes > 0 and new_bytes < original_bytes * 0.95):
if len(messages) < original_len:
- agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
+ agent._buffer_diagnostic_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))
else:
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
f"🗜️ Compressed {original_bytes:,} → {new_bytes:,} " f"payload bytes, retrying..."
)
time.sleep(2) # Brief pause between compression retries
@@ -262,7 +262,7 @@ def _recover_payload_too_large(st: _Recovery, _retry: TurnRetryState) -> Overflo
return st.done("break")
if agent._try_strip_image_parts_from_tool_messages(st.api_messages, remember_model=False):
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
"📐 Compression could not reduce the request further — "
"removed retained vision payloads and retrying..."
)
@@ -390,7 +390,7 @@ def _recover_context_length(st: _Recovery, _retry: TurnRetryState, error_msg: st
exhausted = st.count_attempt()
if exhausted is not None:
return exhausted
- agent._buffer_status(COMPRESSION_RETRY_TOO_LARGE_STATUS_TEMPLATE.format(
+ agent._buffer_diagnostic_status(COMPRESSION_RETRY_TOO_LARGE_STATUS_TEMPLATE.format(
tokens=st.approx_tokens, attempt=st.compression_attempts, cap=st.max_compression_attempts,
))
@@ -447,7 +447,7 @@ def recover_from_overflow(
and base_url_host_matches(agent.base_url, "models.inference.ai.azure.com")
):
for line in _GITHUB_MODELS_HINT:
- agent._vprint(f"{agent.log_prefix}{line}", force=True)
+ agent._vprint(f"{agent.log_prefix}{line}", force=True, diagnostic=True)
if classified.reason == FailoverReason.payload_too_large:
return _recover_payload_too_large(st, _retry)
diff --git a/agent/turn_preflight_gate.py b/agent/turn_preflight_gate.py
index b01224107c2..514038fb55f 100644
--- a/agent/turn_preflight_gate.py
+++ b/agent/turn_preflight_gate.py
@@ -49,7 +49,7 @@ def run_preflight_gate(
v.failed = True
v._turn_exit_reason = "ollama_runtime_context_too_small"
append_message(messages, {"role": "assistant", "content": v.final_response})
- agent._emit_status("❌ Ollama runtime context is too small for Hermes tool use")
+ agent._emit_diagnostic_status("❌ Ollama runtime context is too small for Hermes tool use")
v.api_call_count -= 1
agent._api_call_count = v.api_call_count
with suppress(Exception):
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index ecd557d3236..e0e5451e4a2 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -41,13 +41,16 @@ logger = logging.getLogger("agent.conversation_loop")
def _vlines(agent: Any, *lines: str) -> None:
"""Force-``_vprint`` each line prefixed with ``agent.log_prefix``."""
for line in lines:
- agent._vprint(f"{agent.log_prefix}{line}", force=True)
+ agent._vprint(f"{agent.log_prefix}{line}", force=True, diagnostic=True)
def _plines(agent: Any, *lines: str) -> None:
"""``print`` each line prefixed with ``agent.log_prefix``."""
- for line in lines:
- print(f"{agent.log_prefix}{line}")
+ from gateway.warning_notifications import render_notification
+ render_notification(
+ lambda: [print(f"{agent.log_prefix}{line}") for line in lines],
+ platform=getattr(agent, "_notification_platform", getattr(agent, "platform", "cli")),
+ user_config=getattr(agent, "_notification_config", None))
def _blines(agent: Any, *lines: str) -> None:
@@ -818,7 +821,7 @@ def nonretryable_client_error_result(
_nonretryable_summary = agent._summarize_api_error(api_error)
_plabel = provider_label_for(provider)
_label = _NONRETRYABLE_LABELS.get(classified.reason, f"{_plabel} rejected the request and retrying won't help")
- agent._emit_status(f"❌ {_label}: {_nonretryable_summary}")
+ agent._emit_diagnostic_status(f"❌ {_label}: {_nonretryable_summary}")
# The endpoint/status trace is developer detail: verbose only (the log has it always).
if getattr(agent, "verbose_logging", False):
_vlines(
@@ -940,12 +943,12 @@ def max_retries_exhausted_result(
if _is_billing:
if classified.billing_unverified:
# Ambiguous body — hedge the terminal line.
- agent._emit_status(
+ agent._emit_diagnostic_status(
"❌ Provider reported usage/credit exhaustion "
f"(unverified — may be a content-filter rejection) — {_final_summary}"
)
else:
- agent._emit_status(f"❌ Billing or credits exhausted — {_final_summary}")
+ agent._emit_diagnostic_status(f"❌ Billing or credits exhausted — {_final_summary}")
_billing_kw = dict(
capability="model access", provider=provider, base_url=str(base_url), model=model,
unverified=classified.billing_unverified,
@@ -953,9 +956,9 @@ def max_retries_exhausted_result(
_billing_guidance = _billing_or_entitlement_message(**_billing_kw)
_print_billing_or_entitlement_guidance(agent, **_billing_kw)
elif is_rate_limited:
- agent._emit_status(f"❌ Rate limited after {max_retries} retries — {_final_summary}")
+ agent._emit_diagnostic_status(f"❌ Rate limited after {max_retries} retries — {_final_summary}")
else:
- agent._emit_status(f"❌ API failed after {max_retries} retries — {_final_summary}")
+ agent._emit_diagnostic_status(f"❌ API failed after {max_retries} retries — {_final_summary}")
_vlines(agent, f" 💀 Final error: {_final_summary}")
_welcome_hint = _welcome_tier_guidance(classified, model=model, in_chat=False)
if _welcome_hint:
@@ -1201,9 +1204,9 @@ def compute_error_backoff(
_wait_reason = "Provider overloaded" if is_zai_coding_overload and not is_rate_limited else "Rate limited"
_rate_limit_status = f"⏱️ {_wait_reason}. Waiting {wait_time:.1f}s (attempt {retry_count + 1}/{max_retries}){_policy_note}..."
if _backoff_policy == "zai_coding_overload_long":
- agent._emit_status(_rate_limit_status)
+ agent._emit_diagnostic_status(_rate_limit_status)
else:
- agent._buffer_status(_rate_limit_status)
+ agent._buffer_diagnostic_status(_rate_limit_status)
else:
_retry_status = (
f"⏳ Retrying in {wait_time:.1f}s (attempt {retry_count}/{max_retries})..."
@@ -1212,15 +1215,15 @@ def compute_error_backoff(
# A 5xx Retry-After can now reach the 600s cap; buffering that wait
# would leave the user silent for minutes, so surface long provider
# cooldowns immediately (mirrors the zai_coding_overload_long path).
- agent._emit_status(_retry_status)
+ agent._emit_diagnostic_status(_retry_status)
else:
- agent._buffer_status(_retry_status)
+ agent._buffer_diagnostic_status(_retry_status)
# The buffered line only replays if every retry fails; the live status
# line is the one thing the user sees meanwhile. Name the wait there so a
# 60s backoff after a 5xx is not an anonymous spinner — this is transient
# (rewritten by the next frame, cleared on recovery), so it does not add
# the transcript chatter the buffer exists to avoid.
- agent._emit_wait_notice(
+ agent._emit_diagnostic_wait(
f"⏳ waiting on provider — retrying in {wait_time:.0f}s (attempt {retry_count}/{max_retries})"
)
logger.warning(
@@ -1547,7 +1550,7 @@ def route_classified_error(
)
conversation_history = conversation_history_after_compression(agent, messages, conversation_history)
if len(messages) < original_len or old_ctx > _LONG_CONTEXT_TIER_CAP:
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
COMPRESSION_RETRY_CONTEXT_REDUCED_STATUS_TEMPLATE.format(
new_ctx=_LONG_CONTEXT_TIER_CAP, old_ctx=old_ctx
)
@@ -1594,7 +1597,7 @@ def route_classified_error(
False if _is_upstream else _ra()._pool_may_recover_from_rate_limit(agent._credential_pool)
)
if not pool_may_recover:
- agent._buffer_status(_eager_fallback_status(classified, _is_upstream, _is_transport_failure))
+ agent._buffer_diagnostic_status(_eager_fallback_status(classified, _is_upstream, _is_transport_failure))
if agent._try_activate_fallback(reason=classified.reason):
return _fallback_break()
@@ -1606,7 +1609,7 @@ def route_classified_error(
and agent._fallback_index < len(agent._fallback_chain)
):
_retry.auth_failover_attempted = True
- agent._buffer_status(
+ agent._buffer_diagnostic_status(
"🔐 Authentication failed and could not be refreshed — "
"switching to fallback provider..."
)
diff --git a/agent/turn_response_check.py b/agent/turn_response_check.py
index f442155cfcd..b09b07c0d42 100644
--- a/agent/turn_response_check.py
+++ b/agent/turn_response_check.py
@@ -76,7 +76,7 @@ def _derive_finish_reason(agent: Any, response: Any, messages: Any) -> str:
):
agent._vprint(
f"{agent.log_prefix}⚠️ Treating suspicious Ollama/GLM stop response as truncated",
- force=True,
+ force=True, diagnostic=True,
)
return "length"
return finish_reason
@@ -259,7 +259,7 @@ def retry_invalid_response(
# Eager fallback: empty/malformed responses often mean rate limiting.
if agent._fallback_index < len(agent._fallback_chain):
- agent._buffer_status("⚠️ Empty/malformed response — switching to fallback...")
+ agent._buffer_diagnostic_status("⚠️ Empty/malformed response — switching to fallback...")
if agent._try_activate_fallback():
active_system_prompt = _arm_fallback_restart(
agent, api_messages, active_system_prompt, _retry)
@@ -277,7 +277,7 @@ def retry_invalid_response(
if retry_count >= max_retries:
if agent._has_pending_fallback():
- agent._buffer_status(f"⚠️ Max retries ({max_retries}) for invalid responses — trying fallback...")
+ agent._buffer_diagnostic_status(f"⚠️ Max retries ({max_retries}) for invalid responses — trying fallback...")
if agent._try_activate_fallback():
active_system_prompt = _arm_fallback_restart(
agent, api_messages, active_system_prompt, _retry)
@@ -286,7 +286,7 @@ def retry_invalid_response(
return _verdict("break")
# Terminal — flush buffered retry trace so user sees what happened.
agent._flush_status_buffer()
- agent._emit_status(f"❌ Max retries ({max_retries}) exceeded for invalid responses. Giving up.")
+ agent._emit_diagnostic_status(f"❌ Max retries ({max_retries}) exceeded for invalid responses. Giving up.")
logger.error("%sInvalid API response after %d retries.", agent.log_prefix, max_retries)
agent._persist_session(messages, conversation_history)
# "model=<id>" is describe_invalid_response's OpenRouter fallback, not a provider name.
diff --git a/agent/turn_response_intake.py b/agent/turn_response_intake.py
index 072fd700cb4..b24e6bdf844 100644
--- a/agent/turn_response_intake.py
+++ b/agent/turn_response_intake.py
@@ -159,7 +159,7 @@ def normalize_model_response(
agent._buffer_vprint(f"🔄 Retrying API call ({agent._incomplete_scratchpad_retries}/2)...")
return _verdict("continue") # don't add the broken message
agent._flush_status_buffer()
- agent._vprint(f"{agent.log_prefix}❌ Max retries (2) for incomplete scratchpad. Saving as partial.", force=True)
+ agent._vprint(f"{agent.log_prefix}❌ Max retries (2) for incomplete scratchpad. Saving as partial.", force=True, diagnostic=True)
agent._incomplete_scratchpad_retries = 0
rolled_back_messages = agent._get_messages_up_to_last_assistant(messages)
agent._cleanup_task_resources(effective_task_id)
diff --git a/agent/turn_stop_gates.py b/agent/turn_stop_gates.py
index 35aefe53349..c9f9c304de8 100644
--- a/agent/turn_stop_gates.py
+++ b/agent/turn_stop_gates.py
@@ -162,7 +162,7 @@ def apply_stop_gates(
agent._kanban_stop_nudges,
os.environ.get("HERMES_KANBAN_TASK", ""),
)
- agent._emit_status(
+ agent._emit_diagnostic_status(
"⚠️ Kanban worker tried to exit without "
"kanban_complete/kanban_block — nudging to finish"
)
diff --git a/agent/turn_tool_round.py b/agent/turn_tool_round.py
index daa009ac80b..62e5f306c28 100644
--- a/agent/turn_tool_round.py
+++ b/agent/turn_tool_round.py
@@ -163,7 +163,7 @@ def run_tool_round(
decision = agent._tool_guardrail_halt_decision
_turn_exit_reason = "guardrail_halt"
final_response = agent._toolguard_controlled_halt_response(decision)
- agent._emit_status(f"⚠️ Tool guardrail halted {decision.tool_name}: {decision.code}")
+ agent._emit_diagnostic_status(f"⚠️ Tool guardrail halted {decision.tool_name}: {decision.code}")
append_message(messages, {"role": "assistant", "content": final_response})
# Emit the halt so it isn't mistaken for a crash; the stream callback is still
# alive, so SSE/TUI clients see the explanation.
diff --git a/agent/turn_tool_validation.py b/agent/turn_tool_validation.py
index 56d8154bc03..a3146887170 100644
--- a/agent/turn_tool_validation.py
+++ b/agent/turn_tool_validation.py
@@ -93,7 +93,8 @@ def validate_tool_calls(
if tc.function.name not in valid_names:
repaired = agent._repair_tool_call(tc.function.name)
if repaired:
- print(f"{agent.log_prefix}🔧 Auto-repaired tool name: '{tc.function.name}' -> '{repaired}'")
+ agent._vprint(f"{agent.log_prefix}🔧 Auto-repaired tool name: '{tc.function.name}' -> '{repaired}'",
+ force=True, diagnostic=True)
tc.function.name = repaired
invalid_tool_calls = [tc.function.name for tc in tool_calls if tc.function.name not in valid_names]
# Mixed batch: error-result ONLY the invalid calls and run the valid
@@ -117,7 +118,7 @@ def validate_tool_calls(
if agent._invalid_tool_retries >= 3:
agent._flush_status_buffer()
- agent._vprint(f"{agent.log_prefix}❌ Max retries (3) for invalid tool calls exceeded. Stopping as partial.", force=True)
+ agent._vprint(f"{agent.log_prefix}❌ Max retries (3) for invalid tool calls exceeded. Stopping as partial.", force=True, diagnostic=True)
agent._invalid_tool_retries = 0
return _verdict("return", _partial_exit(
agent, messages, conversation_history, api_call_count,
@@ -172,7 +173,7 @@ def validate_tool_calls(
agent._vprint(
f"{agent.log_prefix}⚠️ Truncated tool call arguments detected "
f"(finish_reason={finish_reason!r}) — refusing to execute.",
- force=True,
+ force=True, diagnostic=True,
)
agent._invalid_json_retries = 0
agent._cleanup_task_resources(effective_task_id)
diff --git a/agent/turn_truncation.py b/agent/turn_truncation.py
index 63d218acecd..c820298d357 100644
--- a/agent/turn_truncation.py
+++ b/agent/turn_truncation.py
@@ -207,9 +207,9 @@ def _content_filter_fallback(st: _Trunc, _retry: TurnRetryState) -> Optional[Tru
return None
agent._vprint(
f"{agent.log_prefix}🛡️ Content filter terminated stream — activating fallback provider...",
- force=True,
+ force=True, diagnostic=True,
)
- agent._emit_status("Content filter terminated stream; switching to fallback...")
+ agent._emit_diagnostic_status("Content filter terminated stream; switching to fallback...")
if agent._try_activate_fallback():
# Roll partial content back to the last clean turn so the fallback gets a
# coherent continuation point; unmark survivors (their text left the partial).
@@ -230,7 +230,7 @@ def _content_filter_fallback(st: _Trunc, _retry: TurnRetryState) -> Optional[Tru
agent._vprint(
f"{agent.log_prefix}⚠️ No fallback provider configured — retrying with same provider "
f"(may re-hit filter)...",
- force=True,
+ force=True, diagnostic=True,
)
return None
@@ -262,12 +262,12 @@ def _continue_text(st: _Trunc, _retry: TurnRetryState, assistant_message: Any) -
if st.is_stub and _dropped_tools:
agent._vprint(
f"{agent.log_prefix}↻ Stream interrupted mid "
- f"tool-call ({', '.join(_dropped_tools[:3])}) — requesting chunked retry ({n}/4)..."
+ f"tool-call ({', '.join(_dropped_tools[:3])}) — requesting chunked retry ({n}/4)...", diagnostic=True,
)
elif st.is_stub:
- agent._vprint(f"{agent.log_prefix}↻ Stream interrupted — requesting continuation ({n}/4)...")
+ agent._vprint(f"{agent.log_prefix}↻ Stream interrupted — requesting continuation ({n}/4)...", diagnostic=True)
else:
- agent._vprint(f"{agent.log_prefix}↻ Requesting continuation ({n}/4)...")
+ agent._vprint(f"{agent.log_prefix}↻ Requesting continuation ({n}/4)...", diagnostic=True)
append_message(messages, {
"role": "user", "content": _get_continuation_prompt(st.is_stub, _dropped_tools),
"_length_continuation_nudge": True,
@@ -285,7 +285,7 @@ def _continue_text(st: _Trunc, _retry: TurnRetryState, assistant_message: Any) -
f"{agent.log_prefix}⚠️ Response still truncated after {n} continuation attempts — "
+ ("keeping the partial response received so far." if partial_response
else "no visible text was produced."),
- force=True,
+ force=True, diagnostic=True,
)
# Unanswered continue nudges made every later turn re-truncate: drop the trail.
idx = st.current_turn_user_idx
@@ -335,13 +335,13 @@ def _retry_truncated_tool_call(st: _Trunc, api_kwargs: Any) -> TruncationVerdict
if st.is_stub:
agent._vprint(
f"{agent.log_prefix}⚠️ Stream kept dropping mid tool-call after 4 retries — the action was not executed.",
- force=True,
+ force=True, diagnostic=True,
)
_final_response = site_copy("stream_dropped_tool_call", label=provider_label_for(agent.provider))
else:
agent._vprint(
f"{agent.log_prefix}⚠️ Truncated tool call response detected again — refusing to execute incomplete tool arguments.",
- force=True,
+ force=True, diagnostic=True,
)
_final_response = _TRUNCATED_FINAL
agent._cleanup_task_resources(st.effective_task_id)
@@ -381,7 +381,7 @@ def recover_from_truncation(
f"context window ({st.window_filled[0]:,}/{st.window_filled[1]:,} tokens)"
if st.window_filled else
f"{agent.log_prefix}⚠️ Response truncated (finish_reason='length') - model hit max output tokens",
- force=True,
+ force=True, diagnostic=True,
)
# #106260: a context-overflow error after partial delivery must not seed a
@@ -396,7 +396,7 @@ def recover_from_truncation(
f"{agent.log_prefix}⚠️ Stream ended on a context-overflow error after "
"partial delivery — not continuing (the request no longer fits the model's "
"context window).",
- force=True,
+ force=True, diagnostic=True,
)
# Prior tool batches can leave a tool-result tail; this path never reaches
# finalize_turn (same as the truncated-tool-call terminal above).
@@ -419,7 +419,7 @@ def recover_from_truncation(
abort = _abort_reason(agent, _trunc_content, _trunc_has_tool_calls)
if abort is not None:
line, user_response, error = abort
- agent._vprint(f"{agent.log_prefix}{line}", force=True)
+ agent._vprint(f"{agent.log_prefix}{line}", force=True, diagnostic=True)
return st.end_turn(user_response, error)
if agent.api_mode in _CONTINUABLE_MODES:
@@ -432,13 +432,13 @@ def recover_from_truncation(
return _retry_truncated_tool_call(st, api_kwargs)
if len(messages) > 1:
- agent._vprint(f"{agent.log_prefix} ⏪ Rolling back to last complete assistant turn")
+ agent._vprint(f"{agent.log_prefix} ⏪ Rolling back to last complete assistant turn", diagnostic=True)
return st.end_turn(
_TRUNCATED_FINAL, result_messages=agent._get_messages_up_to_last_assistant(messages)
)
# First message was truncated - mark as failed
agent._flush_status_buffer()
- agent._vprint(f"{agent.log_prefix}❌ First response truncated - cannot recover", force=True)
+ agent._vprint(f"{agent.log_prefix}❌ First response truncated - cannot recover", force=True, diagnostic=True)
return st.end_turn(_FIRST_TRUNCATED_FINAL, cleanup=False, failed=True)
@@ -533,7 +533,7 @@ def continue_codex_incomplete(
base = agent.max_tokens or int(observed or 0) or 4096
agent._ephemeral_max_output_tokens = min(base * (2 ** n), max(32768, base))
if not agent.quiet_mode:
- agent._vprint(f"{agent.log_prefix}↻ Codex response incomplete; continuing turn ({n}/3)")
+ agent._vprint(f"{agent.log_prefix}↻ Codex response incomplete; continuing turn ({n}/3)", diagnostic=True)
# Spinner/heartbeat notice: these retries can take minutes and otherwise look
# like infinite thinking.
# #70773: same FD-recycle corruption vector as #67142. The shared OpenAI client's connection pool
@@ -544,7 +544,7 @@ def continue_codex_incomplete(
# Surface the continuation on the live spinner/status line (CLI/TUI/Desktop) and gateway heartbeat:
# each of these retries can spend minutes waiting on the provider, and without a distinct notice the
# user only sees a generic thinking spinner ("infinite thinking", #64434).
- agent._emit_wait_notice(
+ agent._emit_diagnostic_wait(
f"↻ model returned reasoning with no final answer — asking it to continue ({n}/3)"
)
agent._session_messages = messages
@@ -596,7 +596,7 @@ def handle_content_policy_refusal(
stop_thinking_spinner(agent, thinking_spinner)
if agent._has_pending_fallback():
- agent._buffer_status("⚠️ Model declined to respond (safety refusal) — trying fallback...")
+ agent._buffer_diagnostic_status("⚠️ Model declined to respond (safety refusal) — trying fallback...")
if agent._try_activate_fallback():
active_system_prompt = _arm_fallback_restart(agent, api_messages, active_system_prompt, _retry)
return RefusalVerdict("break", None, active_system_prompt)
@@ -608,7 +608,7 @@ def handle_content_policy_refusal(
agent.log_prefix, agent.model, agent.provider,
_refusal_log or "(no text)",
)
- agent._emit_status("⚠️ The model declined to respond to this request (safety refusal).")
+ agent._emit_diagnostic_status("⚠️ The model declined to respond to this request (safety refusal).")
_refusal_response = "⚠️ " + content_policy_copy(
label=provider_label_for(agent.provider),
summary=_refusal_text or "the model returned no explanation",
diff --git a/cli.py b/cli.py
index 46889d5bfeb..14009b0280b 100644
--- a/cli.py
+++ b/cli.py
@@ -2511,6 +2511,7 @@ class _ChatTurn:
"""
result: Optional[dict] = None
+ mute_notification_reply: bool = False
use_streaming_tts: bool = False
box_opened: bool = False
thinking_started: bool = False
@@ -2851,20 +2852,24 @@ class HermesCLI(CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMix
logger.warning("Failed to initialize SessionDB — session will NOT be indexed for search: %s", e)
from hermes_state_user_copy import describe_storage_failure, storage_failure_details
failure = describe_storage_failure(e)
- try:
- Console(stderr=True).print(
- "[bold yellow]⚠ Session store unavailable[/bold yellow] — "
- "this conversation will [bold]NOT be saved[/bold] and cannot be resumed later. "
- "Searching past sessions is also disabled.\n"
- f" Reason: {failure.gloss}.\n"
- f" {failure.action}\n"
- f" [dim]Details: {storage_failure_details(e)}[/dim]"
- )
- except Exception:
- print(
- "WARNING: Session store unavailable — this conversation will NOT be "
- f"saved and cannot be resumed later. Reason: {failure.gloss}. {failure.action}"
- )
+ def _present_store_warning():
+ try:
+ Console(stderr=True).print(
+ "[bold yellow]⚠ Session store unavailable[/bold yellow] — "
+ "this conversation will [bold]NOT be saved[/bold] and cannot be resumed later. "
+ "Searching past sessions is also disabled.\n"
+ f" Reason: {failure.gloss}.\n"
+ f" {failure.action}\n"
+ f" [dim]Details: {storage_failure_details(e)}[/dim]"
+ )
+ except Exception:
+ print(
+ "WARNING: Session store unavailable — this conversation will NOT be "
+ f"saved and cannot be resumed later. Reason: {failure.gloss}. {failure.action}"
+ )
+ # Same automatic diagnostic the gateway gates for its home channel (run_notifications).
+ from gateway.warning_notifications import render_notification
+ render_notification(_present_store_warning, platform="cli")
_run_state_db_auto_maintenance(self._session_db)
_run_checkpoint_auto_maintenance()
@@ -3055,7 +3060,8 @@ class HermesCLI(CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMix
notice = default_downgrade_notice()
if notice:
- self._console_print(f"[yellow]⚠ {notice}[/yellow]")
+ from gateway.warning_notifications import render_notification
+ render_notification(lambda: self._console_print(f"[yellow]⚠ {notice}[/yellow]"), platform="cli")
except Exception:
logger.debug("browser backend notice failed", exc_info=True)
diff --git a/cron/bot_chat_delivery.py b/cron/bot_chat_delivery.py
index 1cc21a3ce2c..f061f7a3371 100644
--- a/cron/bot_chat_delivery.py
+++ b/cron/bot_chat_delivery.py
@@ -50,18 +50,25 @@ def _records(root: Path) -> list[tuple[Path, dict]]:
return records
-def defer(key: str, job: dict, content: str, profile: str, home: Path) -> dict:
+def defer(key: str, job: dict, content: str, profile: str, home: Path, *,
+ for_failure: bool = False, suppressed: bool = False) -> dict:
root = _root()
root.mkdir(parents=True, exist_ok=True, mode=0o700)
with _FileLock(root / ".lock"):
record = read_pending(key)
if record is not None:
- if record["content"] != content or record["home"] != str(home):
+ if (record["content"] != content or record["home"] != str(home)
+ or bool(record.get("for_failure")) != for_failure):
raise ValueError("delivery id already belongs to a different payload")
+ if suppressed and record["status"] == "queued":
+ record.update(status="suppressed", error=None)
+ atomic_json_write(root / f"{key}.json", record, fsync_dir=True, mode=0o600)
return record
sequence = max((record["sequence"] for _, record in _records(root)), default=0) + 1
- record = dict(id=key, status="queued", job=job, content=content,
+ record = dict(id=key, status="suppressed" if suppressed else "queued", job=job, content=content,
profile=profile, home=str(home), sequence=sequence)
+ if for_failure:
+ record["for_failure"] = True
atomic_json_write(root / f"{key}.json", record, fsync_dir=True, mode=0o600)
return record
@@ -72,9 +79,14 @@ def drain(root: Path | None = None) -> None:
root = root if root is not None else _root()
with retirement.work() as admitted:
- if admitted and root.is_dir():
+ if not admitted:
+ return
+ if root.is_dir():
with _FileLock(root / ".drain.lock"):
_drain(root)
+ # Receipt replay is work too: it stays behind the same admission as the drain.
+ from cron.executions import reconcile_delivery_projections
+ reconcile_delivery_projections()
def _drain(root: Path) -> None:
@@ -90,6 +102,13 @@ def _drain(root: Path) -> None:
if record["status"] != "queued":
continue
home = Path(record["home"])
+ from gateway.warning_notifications import warning_notifications_enabled
+ from hermes_cli.config_effective import load_user_config_effective
+ if (record.get("for_failure")
+ and not warning_notifications_enabled("tui", load_user_config_effective(home / "config.yaml"))):
+ record.update(status="suppressed", error=None)
+ atomic_json_write(path, record, fsync_dir=True, mode=0o600)
+ continue
try:
owner = find_canonical_owner(home)
if owner is not None and find_canonical_live_owner(home) is None:
@@ -110,6 +129,8 @@ def _drain(root: Path) -> None:
receipt = job.get("_bot_chat_delivery_receipts", {}).get(
f"bot-chat:{record['profile'] or '(own)'}")
status = "transferred" if receipt else "ambiguous" if error else "settled"
+ if job.get("_notification_all_targets_suppressed"):
+ status = "suppressed"
record.update(status=status, error=error)
# A transferred live-owner receipt remains authoritative, including queued.
atomic_json_write(path, record, fsync_dir=True, mode=0o600)
@@ -120,6 +141,8 @@ def drain_in_background() -> None:
home = get_hermes_home().resolve()
root = home / "cron" / "bot_chat_pending"
if not root.is_dir():
+ from cron.executions import reconcile_delivery_projections
+ reconcile_delivery_projections()
return
from hermes_cli.backend_retirement import retirement
diff --git a/cron/delivery_queue.py b/cron/delivery_queue.py
index a69c2db0e88..f78d65537ea 100644
--- a/cron/delivery_queue.py
+++ b/cron/delivery_queue.py
@@ -31,7 +31,7 @@ DELIVERY_DB: Optional[Path] = None
_PROCESS_ID = uuid.uuid4().hex
_lock = threading.RLock()
_ACTIVE_DELIVERIES: set[str] = set()
-_TERMINAL = ("delivered", "failed", "unknown")
+_TERMINAL = ("delivered", "failed", "unknown", "suppressed")
MAX_TERMINAL_DELIVERIES = 1000
DEFAULT_DELIVERY_WAIT_TIMEOUT_SECONDS = 300.0
@@ -40,14 +40,14 @@ def _prune_terminal_unlocked(conn: sqlite3.Connection) -> None:
"""Redact terminal payloads and retain only bounded outcome metadata."""
conn.execute(
"""UPDATE deliveries SET job_json='{}', content=''
- WHERE status IN ('delivered','failed','unknown')
+ WHERE status IN ('delivered','failed','unknown','suppressed')
AND (job_json != '{}' OR content != '')"""
)
keep = max(0, int(MAX_TERMINAL_DELIVERIES))
terminal_count = int(
conn.execute(
"SELECT COUNT(*) FROM deliveries "
- "WHERE status IN ('delivered','failed','unknown')"
+ "WHERE status IN ('delivered','failed','unknown','suppressed')"
).fetchone()[0]
)
excess = terminal_count - keep
@@ -56,7 +56,7 @@ def _prune_terminal_unlocked(conn: sqlite3.Connection) -> None:
"""INSERT OR IGNORE INTO delivery_tombstones
(execution_id, terminal_status, finished_at)
SELECT execution_id, status, finished_at FROM deliveries
- WHERE status IN ('delivered','failed','unknown')
+ WHERE status IN ('delivered','failed','unknown','suppressed')
ORDER BY finished_at, created_at, execution_id
LIMIT ?""",
(excess,),
@@ -64,7 +64,7 @@ def _prune_terminal_unlocked(conn: sqlite3.Connection) -> None:
conn.execute(
"""DELETE FROM deliveries WHERE execution_id IN (
SELECT execution_id FROM deliveries
- WHERE status IN ('delivered','failed','unknown')
+ WHERE status IN ('delivered','failed','unknown','suppressed')
ORDER BY finished_at, created_at, execution_id
LIMIT ?
)""",
@@ -79,6 +79,23 @@ def _path() -> Path:
def _initialize_schema(conn: sqlite3.Connection) -> None:
from hermes_cli.sqlite_util import add_column_if_missing
+ # SQLite cannot widen a CHECK in place. Preserve all old rows atomically,
+ # including claimed sends, while admitting a distinct never-sent disposition.
+ for table in ("deliveries", "delivery_tombstones"):
+ row = conn.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (table,)).fetchone()
+ if row and "'suppressed'" not in row[0]:
+ conn.execute("SAVEPOINT notification_disposition")
+ try:
+ conn.execute(f"ALTER TABLE {table} RENAME TO {table}_old")
+ conn.execute(row[0].replace("'unknown'", "'unknown','suppressed'"))
+ conn.execute(f"INSERT INTO {table} SELECT * FROM {table}_old")
+ conn.execute(f"DROP TABLE {table}_old")
+ conn.execute("RELEASE notification_disposition")
+ except BaseException:
+ conn.execute("ROLLBACK TO notification_disposition")
+ conn.execute("RELEASE notification_disposition")
+ raise
+
conn.execute(
"""CREATE TABLE IF NOT EXISTS deliveries (
execution_id TEXT PRIMARY KEY,
@@ -86,7 +103,7 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
content TEXT NOT NULL,
for_failure INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL CHECK(status IN
- ('pending','delivering','delivered','failed','unknown')),
+ ('pending','delivering','delivered','failed','unknown','suppressed')),
owner_process_id TEXT,
owner_pid INTEGER,
owner_started_at INTEGER,
@@ -99,7 +116,7 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
"""CREATE TABLE IF NOT EXISTS delivery_tombstones (
execution_id TEXT PRIMARY KEY,
terminal_status TEXT NOT NULL CHECK(terminal_status IN
- ('delivered','failed','unknown')),
+ ('delivered','failed','unknown','suppressed')),
finished_at TEXT
)"""
)
@@ -226,8 +243,8 @@ def claim_next() -> Optional[dict]:
return result
-def _finish(execution_id: str, *, error: Optional[str]) -> bool:
- status = "failed" if error else "delivered"
+def _finish(execution_id: str, *, error: Optional[str], suppressed: bool = False) -> bool:
+ status = "failed" if error else "suppressed" if suppressed else "delivered"
safe_error = (
redact_sensitive_text(str(error), force=True, redact_url_credentials=True)
if error
@@ -306,11 +323,14 @@ def drain(
)
except BaseException as exc:
error = f"{type(exc).__name__}: {exc}"
- _finish(row["execution_id"], error=error)
+ _finish(row["execution_id"], error=error,
+ suppressed=bool(row["job"].get("_notification_all_targets_suppressed")))
finally:
with _lock:
_ACTIVE_DELIVERIES.discard(row["execution_id"])
processed += 1
+ from cron.executions import reconcile_delivery_projections
+ reconcile_delivery_projections()
return processed
@@ -353,7 +373,7 @@ def _terminalize_wait_timeout(execution_id: str) -> str:
_prune_terminal_unlocked(conn)
if row is None:
return "timed out waiting for live gateway delivery"
- if row["status"] == "delivered":
+ if row["status"] in {"delivered", "suppressed"}:
return ""
return str(row["error"] or f"delivery {row['status']}")
@@ -369,7 +389,7 @@ def enqueue_and_wait(
"""Queue delivery and wait for a gateway's terminal at-most-once outcome."""
queued = enqueue(execution_id, job, content, for_failure=for_failure)
if queued["status"] in _TERMINAL:
- return None if queued["status"] == "delivered" else str(
+ return None if queued["status"] in {"delivered", "suppressed"} else str(
queued.get("error") or f"delivery {queued['status']}"
)
wait_timeout = (
@@ -379,7 +399,7 @@ def enqueue_and_wait(
while time.monotonic() < deadline:
row = get_status(execution_id)
if row and row["status"] in _TERMINAL:
- return None if row["status"] == "delivered" else str(
+ return None if row["status"] in {"delivered", "suppressed"} else str(
row.get("error") or f"delivery {row['status']}"
)
time.sleep(1.0)
diff --git a/cron/executions.py b/cron/executions.py
index 35dd8b5b607..8de6c3bd149 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -8,6 +8,8 @@ immutable.
from __future__ import annotations
import os
+import json
+import logging
import sqlite3
import threading
import time
@@ -80,12 +82,158 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
"CREATE INDEX IF NOT EXISTS idx_executions_status_claimed "
"ON executions(status, claimed_at DESC, id DESC)"
)
+ add_column_if_missing(conn, "executions", "delivery_manifest", "delivery_manifest TEXT")
+ add_column_if_missing(conn, "executions", "incident_id", "incident_id TEXT")
+ add_column_if_missing(conn, "executions", "incident_generation", "incident_generation INTEGER")
+ add_column_if_missing(conn, "executions", "delivery_projection_settled", "delivery_projection_settled INTEGER NOT NULL DEFAULT 0")
+ # Durable intent written BEFORE any deferred (Bot Chat) send: while set, the row's manifest is
+ # incomplete and no reader may project/settle/prune from it. Cleared by the manifest write itself.
+ add_column_if_missing(conn, "executions", "delivery_manifest_pending", "delivery_manifest_pending INTEGER NOT NULL DEFAULT 0")
add_column_if_missing(conn, "executions", "delivery_outcome", "delivery_outcome TEXT")
add_column_if_missing(conn, "executions", "scheduled_instant", "scheduled_instant TEXT")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_executions_occurrence "
"ON executions(job_id, scheduled_instant) WHERE status='completed'"
)
+ conn.execute("CREATE TABLE IF NOT EXISTS schema_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
+ # Column existence is NOT the migration authority (DDL commits on its own). The fence row
+ # below is: until it exists, readers hold pre-flag rows conservatively and every
+ # initialization retries adoption.
+ _try_adopt_legacy_intent(conn)
+
+
+_ADOPTION_KEY = "manifest_intent_adopted"
+_adoption_complete: set = set() # ledger paths whose fence row was observed (monotonic: it never disappears)
+
+
+def _ledger_key() -> str:
+ return str(EXECUTIONS_FILE or (get_hermes_home().resolve() / "cron" / "executions.db"))
+
+
+def _legacy_intent_adopted(conn: Optional[sqlite3.Connection] = None) -> bool:
+ """True once the one-time adoption of pre-flag journaled intent has durably completed."""
+ key = _ledger_key()
+ if key in _adoption_complete:
+ return True
+ if conn is None:
+ with _transaction() as own:
+ return _legacy_intent_adopted(own)
+ row = conn.execute("SELECT 1 FROM schema_meta WHERE key=?", (_ADOPTION_KEY,)).fetchone()
+ if row is not None:
+ _adoption_complete.add(key)
+ return row is not None
+
+
+def _journal_inventory_strict() -> Dict[str, dict]:
+ """Journal inventory that RAISES on any unreadable directory or entry.
+
+ Adoption must distinguish a genuinely empty journal from one it could not read: an
+ incomplete inventory is not proof that no outstanding intent exists.
+ """
+ root = _journal_root()
+ if not root.exists():
+ return {}
+ out: Dict[str, dict] = {}
+ for path in sorted(root.iterdir()): # raises PermissionError on an unreadable directory
+ if path.suffix != ".json":
+ continue
+ record = json.loads(path.read_text(encoding="utf-8")) # raises on an unreadable entry
+ if record.get("execution_id") and record.get("manifest"):
+ out[record["execution_id"]] = record["manifest"]
+ return out
+
+
+def _try_adopt_legacy_intent(conn: sqlite3.Connection) -> bool:
+ """One-time, retryable, atomic adoption of pre-flag outstanding journals.
+
+ In ONE write transaction: every row whose real manifest is still only journaled gets
+ ``delivery_manifest_pending=1``, then the fence row is written. Any failure (unreadable
+ journal, rejected write) rolls back everything, logs, and leaves the fence absent so the
+ next initialization retries and readers keep holding legacy rows conservatively.
+ """
+ if _legacy_intent_adopted(conn):
+ return True
+ if conn.in_transaction:
+ # A caller (e.g. incident upsert) owns an open transaction; adoption must not nest a
+ # BEGIN inside it nor piggyback on its commit. Defer to the next ordinary ledger open.
+ logging.getLogger(__name__).debug("Cron ledger: legacy intent adoption deferred (caller transaction open)")
+ return False
+ try:
+ inventory = _journal_inventory_strict()
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ if conn.execute("SELECT 1 FROM schema_meta WHERE key=?", (_ADOPTION_KEY,)).fetchone():
+ conn.execute("ROLLBACK") # a concurrent initializer won the race
+ _adoption_complete.add(_ledger_key())
+ return True
+ for execution_id in inventory:
+ conn.execute(
+ "UPDATE executions SET delivery_manifest_pending=1 WHERE id=? AND "
+ "(delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
+ (execution_id,))
+ conn.execute("INSERT INTO schema_meta(key, value) VALUES (?, ?)", (_ADOPTION_KEY, _hermes_now().isoformat()))
+ conn.execute("COMMIT")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
+ except Exception:
+ logging.getLogger(__name__).error(
+ "Cron ledger: legacy delivery-intent adoption incomplete; pre-flag rows are held until it succeeds",
+ exc_info=True)
+ return False
+ _adoption_complete.add(_ledger_key())
+ return True
+
+
+def _placeholder_only(record: Optional[dict]) -> bool:
+ manifest = record.get("delivery_manifest") if record else None
+ return bool(manifest) and "bot" not in json.loads(manifest)
+
+
+def _journal_entry_state(execution_id: str) -> Optional[bool]:
+ """True: this row has a journal entry. False: verified absent. None: could not tell."""
+ path = _journal_root() / f"{execution_id}.json"
+ try:
+ return path.is_file()
+ except OSError:
+ return None
+
+
+def _held_by_incomplete_adoption(record: Optional[dict], conn: Optional[sqlite3.Connection] = None) -> bool:
+ """Conservative fence while adoption is incomplete: a row carrying only the external
+ placeholder may still have an outstanding journaled child we cannot see."""
+ if not record or _legacy_intent_adopted(conn):
+ return False
+ return _placeholder_only(record)
+
+
+def _late_legacy_intent(record: Optional[dict], conn: Optional[sqlite3.Connection] = None) -> bool:
+ """Old-writer accounting at terminalization (K2c).
+
+ A pre-flag process that outlives adoption publishes its child manifest only to the
+ journal. A placeholder-only row with pending=0 is therefore complete ONLY if its own
+ journal entry is verifiably absent. When present, the intent is adopted here (in the
+ caller's transaction when given) so every later reader sees the flag; when unknowable,
+ the row is held. Rows that already carry "bot" are past this window and never probed.
+ """
+ if not record or record.get("delivery_manifest_pending") or not _placeholder_only(record):
+ return False
+ state = _journal_entry_state(record["id"])
+ if state is False:
+ return False
+ if state is True and conn is not None:
+ # Write-time recheck: `record` is a snapshot taken before the stat. A replay that landed
+ # the complete manifest in between must not be re-armed with a flag nothing can clear.
+ cur = conn.execute(
+ "UPDATE executions SET delivery_manifest_pending=1 WHERE id=? AND delivery_manifest_pending=0 "
+ "AND delivery_manifest IS NOT NULL AND instr(delivery_manifest, '\"bot\"')=0",
+ (record["id"],))
+ if cur.rowcount == 0:
+ # The row moved on (complete manifest landed, or already flagged): defer to the
+ # authoritative row state rather than the stale snapshot.
+ current = _fetch(conn, record["id"])
+ return bool(current and (current.get("delivery_manifest_pending") or _placeholder_only(current)))
+ return True
@contextmanager
@@ -135,10 +283,16 @@ def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:
def _prune_unlocked(conn: sqlite3.Connection) -> None:
+ # While legacy-intent adoption is incomplete, rows carrying only a placeholder manifest may
+ # still anchor an unseen journaled child: never prune them.
+ hold = "" if _legacy_intent_adopted(conn) else " AND (delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')>0)"
conn.execute(
- """DELETE FROM executions WHERE id IN (
+ f"""DELETE FROM executions WHERE id IN (
SELECT id FROM executions
WHERE status IN ('completed','failed','unknown')
+ AND (delivery_outcome IS NULL OR delivery_outcome != 'queued')
+ AND (delivery_manifest IS NULL OR delivery_projection_settled=1)
+ AND delivery_manifest_pending=0{hold}
ORDER BY finished_at DESC, claimed_at DESC, id DESC LIMIT -1 OFFSET ?
)""",
(max(0, int(MAX_TERMINAL_EXECUTIONS)),),
@@ -252,23 +406,312 @@ def finish_execution(
now = _hermes_now().isoformat()
status = "completed" if success else "failed"
detail = None if success else (str(error) if error else "unknown failure")
+ # A worker may observe a terminal receipt during its wait. Use the same durable
+ # classification as restart reconciliation, in particular unknown != failed.
+ caller_outcome = delivery_outcome
with _transaction() as conn:
- cur = conn.execute(
- """UPDATE executions
- SET status=?, finished_at=?, error=?, handoff_pending=0,
- handoff_started_at=NULL, delivery_outcome=?
- WHERE id=? AND status IN ('claimed','running')
- AND process_id=? AND pid=?""",
- (status, now, detail, delivery_outcome, execution_id, _PROCESS_ID, os.getpid()),
- )
- if cur.rowcount != 1:
+ cur = None
+ for _attempt in range(2):
+ # Derive the terminal delivery decision from the AUTHORITATIVE row contents and
+ # write it with a CAS on the exact manifest it was derived from. A concurrent
+ # replay that lands the complete manifest between derivation and write fails the
+ # CAS; the second pass derives again from what is there now. The row is ours
+ # (process/pid), so this never double-terminalizes.
+ row = _fetch(conn, execution_id)
+ derived_from = row.get("delivery_manifest") if row else None
+ delivery_outcome = caller_outcome
+ if row and (row.get("delivery_manifest_pending") or _held_by_incomplete_adoption(row, conn)
+ or _late_legacy_intent(row, conn)):
+ # Deferred children were sent but their manifest is not in the ledger yet: the
+ # caller's classification (and any placeholder) is incomplete by construction.
+ delivery_outcome = "queued"
+ elif row and derived_from:
+ projection = _delivery_projection(row)
+ if projection is not None:
+ delivery_outcome = projection[0]
+ elif manifest_pending(row):
+ delivery_outcome = "queued"
+ cur = conn.execute(
+ """UPDATE executions
+ SET status=?, finished_at=?, error=?, handoff_pending=0,
+ handoff_started_at=NULL, delivery_outcome=?
+ WHERE id=? AND status IN ('claimed','running')
+ AND process_id=? AND pid=? AND delivery_manifest IS ?""",
+ (status, now, detail, delivery_outcome, execution_id, _PROCESS_ID, os.getpid(), derived_from),
+ )
+ if cur.rowcount == 1:
+ break
+ if cur is None or cur.rowcount != 1:
return None
_prune_unlocked(conn)
record = _fetch(conn, execution_id)
_emit_execution_state(record, delivery_outcome=delivery_outcome)
+ if record and record.get("delivery_manifest"):
+ reconcile_delivery_projections()
return record
+def bind_delivery_incident(execution_id: Optional[str], incident_id: str) -> None:
+ """Persist the producer's actual incident association, never infer it from errors."""
+ if execution_id:
+ with _transaction() as conn:
+ from cron.incidents import _initialize_schema as init_incidents
+ init_incidents(conn)
+ _bind_delivery_incident_unlocked(conn, execution_id, incident_id)
+
+
+def _bind_delivery_incident_unlocked(conn, execution_id: str, incident_id: str) -> None:
+ """Called in the producer's incident upsert transaction; no later generation lookup."""
+ conn.execute("UPDATE executions SET incident_id=?, incident_generation="
+ "(SELECT generation FROM cron_incidents WHERE id=?) "
+ "WHERE id=? AND incident_id IS NULL "
+ "AND status IN ('claimed','running') AND process_id=? AND pid=?",
+ (incident_id, incident_id, execution_id, _PROCESS_ID, os.getpid()))
+
+
+def record_delivery_manifest(execution_id: Optional[str], manifest: dict) -> None:
+ """Retain receipt identities and sibling disposition separately from the run result.
+
+ The worker may first bind the external handoff; its gateway replaces that placeholder
+ with the resolved target receipts. No payload or raw output is copied here.
+ """
+ if not execution_id:
+ return
+ with _transaction() as conn:
+ _store_manifest(conn, execution_id, manifest)
+
+
+def _store_manifest(conn, execution_id: str, manifest: dict) -> None:
+ """CAS the manifest onto a row that has none (or only the external placeholder).
+
+ Clearing ``delivery_manifest_pending`` is part of the SAME statement: a storage fault that
+ rejects the manifest leaves the intent flag set, so no reader can misread the placeholder.
+ """
+ row = _fetch(conn, execution_id)
+ existing = row.get("delivery_manifest") if row else None
+ if existing and "bot" not in json.loads(existing):
+ # Any placeholder-only manifest (canonical or not) is incomplete by the same predicate
+ # every reader uses; the complete manifest replaces it and keeps its external marker.
+ manifest = {**manifest, "external": True}
+ conn.execute("UPDATE executions SET delivery_manifest=?, delivery_manifest_pending=0 WHERE id=? AND "
+ "(delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
+ (json.dumps(manifest, sort_keys=True), execution_id))
+
+
+def mark_delivery_manifest_pending(execution_id: Optional[str]) -> None:
+ """Record, BEFORE any deferred send, that this run will own child receipts.
+
+ Raises when the ledger cannot take the write: nothing has been sent yet, so the caller
+ may truthfully report a pre-send failure instead of sending without durable intent.
+ """
+ if not execution_id:
+ return
+ with _transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=?", (execution_id,))
+
+
+def manifest_pending(record: Optional[dict]) -> bool:
+ """True while the row's deferred-child manifest is not yet in the ledger."""
+ if not record or not record.get("delivery_manifest_pending"):
+ return False
+ manifest = record.get("delivery_manifest")
+ return not (manifest and "bot" in json.loads(manifest))
+
+
+def _journal_root() -> Path:
+ return (EXECUTIONS_FILE.parent if EXECUTIONS_FILE else get_hermes_home().resolve() / "cron") / "manifest_journal"
+
+
+def journal_manifest(execution_id: str, manifest: dict) -> bool:
+ """Best-effort durable copy of a manifest the ledger could not store (post-send fault).
+
+ The row's ``delivery_manifest_pending`` flag is the authoritative invariant; this journal
+ only lets the reconciler recover the manifest once the ledger accepts writes again.
+ Never raises: a second storage failure is logged, and the row simply stays pending.
+ """
+ try:
+ # The row flag is the authoritative fence; re-assert it here (idempotent) so a journal
+ # entry never exists for a row that readers would treat as complete.
+ with _transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=?", (execution_id,))
+ except Exception:
+ logging.getLogger(__name__).debug("Could not re-assert manifest intent for %s", execution_id, exc_info=True)
+ try:
+ from utils import atomic_json_write
+ root = _journal_root()
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
+ atomic_json_write(root / f"{execution_id}.json", {"execution_id": execution_id, "manifest": manifest},
+ fsync_dir=True, mode=0o600)
+ return True
+ except Exception:
+ logging.getLogger(__name__).exception(
+ "Cron delivery manifest for %s could not be journaled; row stays pending", execution_id)
+ return False
+
+
+def journaled_manifests() -> Dict[str, dict]:
+ root = _journal_root()
+ if not root.is_dir():
+ return {}
+ out: Dict[str, dict] = {}
+ for path in root.glob("*.json"):
+ try:
+ record = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
+ logging.getLogger(__name__).error("Unreadable cron manifest journal entry %s", path)
+ continue
+ if record.get("execution_id") and record.get("manifest"):
+ out[record["execution_id"]] = record["manifest"]
+ return out
+
+
+def _recover_unrecorded_manifests() -> Dict[str, dict]:
+ """Replay journaled manifests into the ledger; return what is STILL outstanding.
+
+ Idempotent through the same CAS as the primary write (which also clears the row's pending
+ flag). An entry is removed only once the ledger row actually carries the children.
+ Callers must NOT use the return value as an authority: the row flag is authoritative.
+ """
+ outstanding: Dict[str, dict] = {}
+ for execution_id, manifest in journaled_manifests().items():
+ try:
+ # A journal entry IS outstanding intent (legacy rows predating the flag, or a mark
+ # whose re-assert failed). Assert it in its OWN committed transaction first: if the
+ # replay below is rejected by storage, the fence must survive the rollback.
+ with _transaction() as conn:
+ row = _fetch(conn, execution_id)
+ if row is None:
+ outstanding[execution_id] = manifest
+ continue
+ conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=? AND "
+ "(delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
+ (execution_id,))
+ # A terminal classification derived from a placeholder-only manifest was, by
+ # construction, computed without the children this journal now supplies (a
+ # pre-flag writer publishing late). Reopen exactly that row, in the same
+ # transaction as the intent, so the real manifest is projected once it lands.
+ conn.execute("UPDATE executions SET delivery_outcome='queued', delivery_projection_settled=0 "
+ "WHERE id=? AND delivery_manifest_pending=1 AND delivery_outcome IN ('delivered','failed') "
+ "AND (delivery_manifest IS NULL OR instr(delivery_manifest, '\"bot\"')=0)",
+ (execution_id,))
+ with _transaction() as conn:
+ _store_manifest(conn, execution_id, manifest)
+ row = _fetch(conn, execution_id)
+ stored = json.loads(row["delivery_manifest"]) if row and row.get("delivery_manifest") else {}
+ if stored.get("bot") == manifest.get("bot"):
+ (_journal_root() / f"{execution_id}.json").unlink(missing_ok=True)
+ else:
+ outstanding[execution_id] = manifest
+ except Exception:
+ logging.getLogger(__name__).exception("Could not replay journaled cron manifest %s", execution_id)
+ outstanding[execution_id] = manifest
+ return outstanding
+
+
+def _delivery_projection(record: dict) -> Optional[tuple[str, dict]]:
+ from cron import delivery_queue, bot_chat_delivery
+ from tools.bot_live_delivery import read_delivery_result
+
+ if manifest_pending(record) or _held_by_incomplete_adoption(record) or _late_legacy_intent(record):
+ return None # children were sent; their manifest is not in the ledger yet
+ manifest = json.loads(record["delivery_manifest"])
+ external_outcome = None
+ external_error = None
+ if manifest.get("external"):
+ receipt = delivery_queue.get_status(record["id"])
+ if not receipt or receipt["status"] in ("pending", "delivering"):
+ return None
+ outcome = receipt["status"]
+ external_outcome, external_error = outcome, receipt.get("error")
+ if not manifest.get("bot"):
+ return outcome, {"last_delivery_queued": None, "last_delivery_unverified": None,
+ "last_delivery_error": receipt.get("error")}
+
+ queued = {}
+ states = []
+ for target, ref in manifest.get("bot", {}).items():
+ receipt = read_delivery_result(Path(ref["home"]), ref["delivery_id"])
+ if receipt is None:
+ receipt = bot_chat_delivery.read_pending(ref["delivery_id"])
+ status = (receipt or ref)["status"]
+ if status in ("queued", "claimed", "transferred"):
+ queued[target] = {**ref, "status": status}
+ states.append(status)
+ error = manifest.get("error") or external_error
+ unverified = manifest.get("unverified")
+ if queued:
+ outcome = "queued"
+ elif external_outcome == "unknown" or "ambiguous" in states or "unknown" in states or unverified:
+ outcome = "unknown"
+ elif external_outcome == "failed" or "failed" in states or error:
+ outcome = "failed"
+ elif manifest.get("delivered") or "settled" in states:
+ outcome = "delivered"
+ else:
+ outcome = "suppressed"
+ if outcome in ("failed", "unknown") and not error:
+ error = "Deferred delivery completion unverified; do not resend"
+ return outcome, {"last_delivery_queued": queued or None,
+ "last_delivery_unverified": unverified or None,
+ "last_delivery_error": error}
+
+
+def reconcile_delivery_projections() -> None:
+ """Replay durable receipts, never sends. Safe after either store write or restart.
+
+ Only delivery_outcome can change after run completion. The queued CAS and manifest
+ comparison fence racing reconcilers; execution status/error/timestamps are untouched.
+ Retaining manifests also repairs a crash between the ledger and jobs/incident writes.
+ """
+ import logging
+ from cron.jobs import update_delivery_projection
+ from cron.incidents import _initialize_schema as init_incidents
+
+ try:
+ _recover_unrecorded_manifests()
+ except Exception:
+ logging.getLogger(__name__).exception("Could not replay journaled cron delivery manifests")
+ with _transaction() as conn:
+ records = [dict(row) for row in conn.execute(
+ "SELECT * FROM executions WHERE delivery_manifest IS NOT NULL "
+ "AND status IN ('completed','failed','unknown')").fetchall()]
+ for record in records:
+ try:
+ # A pending row (children sent, manifest not yet in the ledger) projects to None
+ # inside _delivery_projection; the CAS below re-checks the flag at write time so a
+ # reader that loaded the row before the flag flipped cannot settle it either.
+ projection = _delivery_projection(record)
+ if projection is None:
+ continue
+ outcome, values = projection
+ with _transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_outcome=? WHERE id=? "
+ "AND delivery_outcome='queued' AND delivery_manifest=? "
+ "AND delivery_manifest_pending=0",
+ (outcome, record["id"], record["delivery_manifest"]))
+ current = _fetch(conn, record["id"])
+ if not current or current["delivery_outcome"] != outcome:
+ continue
+ if outcome == "delivered" and record.get("incident_id"):
+ init_incidents(conn)
+ # Late completion cannot resurrect resolved/acked incidents.
+ conn.execute("UPDATE cron_incidents SET state='alerted' WHERE id=? "
+ "AND state='detected' AND generation=?",
+ (record["incident_id"], record.get("incident_generation")))
+ update_delivery_projection(record["job_id"], record["id"], values)
+ if outcome != "queued":
+ # Pin the receipt association until BOTH durable projections have
+ # completed. A crash above leaves it replayable even under retention.
+ with _transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_projection_settled=1 "
+ "WHERE id=? AND delivery_outcome=? AND delivery_manifest=? "
+ "AND delivery_manifest_pending=0",
+ (record["id"], outcome, record["delivery_manifest"]))
+ except Exception:
+ logging.getLogger(__name__).exception(
+ "Could not reconcile cron delivery %s; durable receipt retained", record["id"])
+
+
def recover_interrupted_executions() -> int:
"""Mark provably abandoned attempts unknown without scheduling retries."""
now = _hermes_now().isoformat()
@@ -297,13 +740,17 @@ def recover_interrupted_executions() -> int:
cur = conn.execute(
"""UPDATE executions
SET status='unknown', finished_at=?, error=?,
- handoff_pending=0, handoff_started_at=NULL
+ handoff_pending=0, handoff_started_at=NULL,
+ delivery_outcome=CASE WHEN delivery_manifest_pending=1 OR (? AND delivery_manifest IS NOT NULL
+ AND instr(delivery_manifest, '"bot"')=0)
+ THEN 'queued' ELSE delivery_outcome END
WHERE id=? AND status=? AND process_id=? AND pid=?
AND handoff_pending=?
AND handoff_started_at IS ?""",
(now,
"Scheduler restarted after this execution's owner exited before a durable "
"terminal state; whether side effects ran is unknown.",
+ 0 if _legacy_intent_adopted(conn) else 1,
row["id"], row["status"], row["process_id"], row["pid"],
row["handoff_pending"], row["handoff_started_at"]),
)
diff --git a/cron/incidents.py b/cron/incidents.py
index 623012f1394..65c494fc124 100644
--- a/cron/incidents.py
+++ b/cron/incidents.py
@@ -81,6 +81,18 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
output_file TEXT
)"""
)
+ from hermes_cli.sqlite_util import add_column_if_missing
+ add_column_if_missing(conn, "cron_incidents", "generation", "generation INTEGER NOT NULL DEFAULT 1")
+ # Enforce recurrence at storage level: old daemons may still update state
+ # without knowing about generations. Avoid double increment for an
+ # intermediate writer which already advanced generation in its UPDATE.
+ conn.execute("""CREATE TRIGGER IF NOT EXISTS cron_incident_recurrence_generation
+ AFTER UPDATE OF state ON cron_incidents
+ WHEN OLD.state='resolved' AND NEW.state='detected'
+ AND NEW.generation=OLD.generation
+ BEGIN
+ UPDATE cron_incidents SET generation=OLD.generation+1 WHERE id=NEW.id;
+ END""")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_cron_incidents_job "
"ON cron_incidents(job_id)"
@@ -143,7 +155,7 @@ def _classify_failure_type(error: str) -> str:
def upsert_incident(
job_id: str, error: str, *, job_name: Optional[str] = None, failure_type: Optional[str] = None,
- output_file: Optional[str] = None,
+ output_file: Optional[str] = None, execution_id: Optional[str] = None,
) -> tuple[str, bool]:
"""Record (or refresh) the incident for ``job_id`` + ``error``; returns ``(incident_id,
is_new)``. An existing row for the signature refreshes
@@ -172,6 +184,9 @@ def upsert_incident(
WHERE id=?""",
(now, stored_error, output_file, incident_id),
)
+ if execution_id:
+ _executions._initialize_schema(conn)
+ _executions._bind_delivery_incident_unlocked(conn, execution_id, incident_id)
return incident_id, reopen
conn.execute(
"""INSERT INTO cron_incidents
@@ -181,9 +196,29 @@ def upsert_incident(
(incident_id, job_id, sig, failure_type, now, now,
stored_error, output_file),
)
+ if execution_id:
+ _executions._initialize_schema(conn)
+ _executions._bind_delivery_incident_unlocked(conn, execution_id, incident_id)
return incident_id, True
+def mark_alerted_for_execution(incident_id: str, execution_id: str) -> bool:
+ """Mark ``alerted`` only if the incident is still on the occurrence this execution bound.
+
+ A run whose failure ping went out for occurrence N must not mark occurrence N+1 (the job
+ recovered and reopened with the same signature meanwhile). Returns whether it changed.
+ """
+ with _transaction() as conn:
+ _executions._initialize_schema(conn)
+ cur = conn.execute(
+ """UPDATE cron_incidents SET state='alerted'
+ WHERE id=? AND state='detected'
+ AND generation=(SELECT incident_generation FROM executions WHERE id=? AND incident_id=?)""",
+ (incident_id, execution_id, incident_id),
+ )
+ return cur.rowcount == 1
+
+
def set_incident_state(incident_id: str, state: str) -> bool:
"""Transition an incident's lifecycle state; return whether it changed. ``closed`` is terminal
for that signature (re-open happens by a changed error minting a NEW incident). Unknown states
diff --git a/cron/jobs.py b/cron/jobs.py
index 98e26aa0b24..f8f95d59263 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -2030,6 +2030,44 @@ def _fill_missing_next_run(updated: Dict[str, Any]) -> None:
updated["next_run_at"] = next_run
+def bind_delivery_execution(job_id: str, execution_id: str) -> None:
+ """Fence asynchronous job projections at run start, under the store lock."""
+ from cron.executions import latest_execution
+
+ def apply(records, _i, job):
+ latest = latest_execution(job_id)
+ if latest and latest["id"] == execution_id:
+ job["delivery_execution_id"] = execution_id
+ save_jobs(records)
+ _with_job(job_id, apply)
+
+
+def update_delivery_projection(job_id: str, execution_id: str, values: dict) -> bool:
+ """CAS delivery-only fields; an older drain cannot clobber a newer run."""
+ allowed = {"last_delivery_queued", "last_delivery_unverified", "last_delivery_error"}
+ if not set(values) <= allowed:
+ raise ValueError("Not a delivery projection")
+
+ def apply(records, _i, job):
+ if job.get("delivery_execution_id") != execution_id:
+ return False
+ # The new execution can have been claimed before it binds its projection.
+ from cron.executions import latest_execution
+ latest = latest_execution(job_id)
+ if not latest or latest["id"] != execution_id:
+ return False
+ # Projection freshness: a 'queued' projection computed by a slower reconciler must
+ # not resurrect job pending after the SAME execution settled terminally in the ledger.
+ if values.get("last_delivery_queued") and latest.get("delivery_outcome") not in (None, "queued"):
+ return False
+ job.update(values)
+ if job.get("last_status") == "delivery_queued" and not job.get("last_delivery_queued"):
+ job["last_status"] = "delivery_failed" if job.get("last_delivery_error") else "ok"
+ save_jobs(records)
+ return True
+ return bool(_with_job(job_id, apply))
+
+
def update_job(job_id: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Update a job by ID, refreshing derived schedule fields when needed."""
# ``id`` is a path component under OUTPUT_DIR — changing it would leak path-escape values.
diff --git a/cron/scheduler.py b/cron/scheduler.py
index eac5bad9f84..070fa56b1cd 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -295,7 +295,8 @@ def _upsert_incident_for_failure(
from cron.incidents import get_incident, upsert_incident
incident_id, _is_new = upsert_incident(
- job["id"], str(error or ""), job_name=job.get("name"), output_file=output_file)
+ job["id"], str(error or ""), job_name=job.get("name"), output_file=output_file,
+ execution_id=job.get("execution_id"))
incident = get_incident(incident_id)
acked = bool(incident and incident.get("state") == "closed")
return acked, incident_id
@@ -317,14 +318,21 @@ def _resolve_incidents_for_recovered_job(job: dict) -> None:
logger.debug("Incident store unavailable for job %s (delivery unaffected): %s", job["id"], exc)
-def _mark_incident_alerted(incident_id: Optional[str]) -> None:
- """Best-effort: mark incident ``alerted`` (no-op for closed; never resurrects an acked one)."""
+def _mark_incident_alerted(incident_id: Optional[str], execution_id: Optional[str] = None) -> None:
+ """Best-effort: mark incident ``alerted`` (no-op for closed; never resurrects an acked one).
+
+ Fenced to the occurrence THIS execution bound: a native alert whose run belongs to an
+ older occurrence (the incident recovered and reopened meanwhile) must not mark the new one.
+ """
if not incident_id:
return
try:
- from cron.incidents import set_incident_state
+ from cron.incidents import mark_alerted_for_execution, set_incident_state
- set_incident_state(incident_id, "alerted")
+ if execution_id:
+ mark_alerted_for_execution(incident_id, execution_id)
+ else:
+ set_incident_state(incident_id, "alerted")
except Exception as exc:
logger.debug("Failed marking incident %s alerted: %s", incident_id, exc)
@@ -2474,6 +2482,8 @@ def run_one_job(
job["execution_id"] = execution["id"]
execution_id = str(job["execution_id"])
+ from cron.jobs import bind_delivery_execution
+ bind_delivery_execution(job["id"], execution_id)
external_owner = os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_id
if not external_owner:
try:
@@ -2548,12 +2558,14 @@ def _record_fire_ownership_lost(job_id: str, fire_owner: Optional[str], executio
def _classify_delivery_outcome(
*, delivery_error, should_deliver: bool, unresolved_origin: bool,
normalized_deliver: str, incident_acked: bool, success: bool,
- delivery_queued=None,
+ delivery_queued=None, notification_suppressed: bool = False,
) -> str:
- if delivery_error:
- return "failed"
if should_deliver and delivery_queued:
return "queued"
+ if delivery_error:
+ return "failed"
+ if notification_suppressed:
+ return "suppressed"
if should_deliver and unresolved_origin:
return "not_configured"
if should_deliver and normalized_deliver != "local":
@@ -2788,8 +2800,8 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_
"""mark_job_run (owner-fenced) + execution ledger row for a run that reached delivery."""
job = d.job
if not d.should_deliver and job.get("last_delivery_queued"):
- from cron.jobs import update_job
- update_job(job["id"], {"last_delivery_queued": None})
+ from cron.jobs import update_delivery_projection
+ update_delivery_projection(job["id"], execution_id, {"last_delivery_queued": None})
job["last_delivery_queued"] = None
mark_kwargs: dict = {"delivery_error": d.delivery_error}
if not d.success and job.pop("_model_unreachable", False):
@@ -2813,6 +2825,7 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_
delivery_outcome = _classify_delivery_outcome(
delivery_error=d.delivery_error,
delivery_queued=job.get("last_delivery_queued"),
+ notification_suppressed=bool(job.get("_notification_all_targets_suppressed")),
should_deliver=d.should_deliver,
unresolved_origin=d.unresolved_origin,
# Read the lane the notice was actually routed through (failure_deliver on failure).
@@ -2822,7 +2835,7 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_
)
if delivery_outcome in ("delivered", "not_configured") and not d.success:
# Failure ping left the process (or had a configured target): mark the incident alerted.
- _mark_incident_alerted(d.failure_incident_id)
+ _mark_incident_alerted(d.failure_incident_id, execution_id)
finish_execution(
execution_id, success=d.success, error=d.error, delivery_outcome=delivery_outcome)
return True
@@ -2859,9 +2872,10 @@ def _deliver_crash_failure(
delivery_outcome = _classify_delivery_outcome(
delivery_error=delivery_error, should_deliver=True, unresolved_origin=unresolved_origin,
normalized_deliver=normalized_deliver, incident_acked=False, success=False,
- delivery_queued=job.get("last_delivery_queued"))
+ delivery_queued=job.get("last_delivery_queued"),
+ notification_suppressed=bool(job.get("_notification_all_targets_suppressed")))
if delivery_outcome in ("delivered", "not_configured"):
- _mark_incident_alerted(failure_incident_id)
+ _mark_incident_alerted(failure_incident_id, job.get("execution_id"))
return delivery_error, delivery_outcome
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index dee1741b225..945cc3b1c88 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -663,6 +663,18 @@ def _get_bot_chat_delivery_timeout() -> int:
return 600
+def _mark_manifest_intent(job: dict) -> None:
+ """Durable intent before ANY send of a run that has deferred (Bot Chat) targets.
+
+ Raises: nothing has been sent yet, so the caller reports a truthful pre-send failure and
+ sends nothing. Every exit after a successful mark settles a manifest (_settle_manifest).
+ """
+ if job.get("execution_id") and not job.get("_manifest_intent_marked"):
+ from cron.executions import mark_delivery_manifest_pending
+ mark_delivery_manifest_pending(str(job["execution_id"]))
+ job["_manifest_intent_marked"] = True
+
+
_BOT_CHAT_STDERR_TAIL = 500
# stdout is the model's answer; only a short tail is persisted (jobs.json / ledger).
_BOT_CHAT_STDOUT_TAIL = 200
@@ -697,7 +709,9 @@ def _format_failure_streams(result) -> str:
return redact_sensitive_text(" | ".join(parts), force=True, redact_url_credentials=True)
-def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Optional[dict] = None) -> Optional[str]:
+
+def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Optional[dict] = None,
+ for_failure: bool = False) -> Optional[str]:
"""Hand output to the live Bot Chat owner, or use the legacy unowned CLI lane.
None means completed; a queued/claimed receipt returns an explicit unverified status
@@ -716,6 +730,7 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
job_id = job.get("id", "?")
profile_label = profile or "(own)"
+ job.pop("_notification_all_targets_suppressed", None)
message = (
f'[Cronjob "{job.get("name", job_id)}" output — scheduled job, not the user. '
f"Review it, act on anything that needs action, and summarize "
@@ -726,6 +741,10 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
from pathlib import Path
home = (Path(deferred["home"]) if deferred is not None else
get_profile_dir(profile) if profile else source_home).resolve()
+ for_failure = for_failure or bool((deferred or {}).get("for_failure"))
+ from gateway.warning_notifications import warning_notifications_enabled
+ from hermes_cli.config_effective import load_user_config_effective
+ suppress_notification = for_failure and not warning_notifications_enabled("tui", load_user_config_effective(home / "config.yaml"))
if deferred is not None and not (home / "state.db").is_file():
return f"bot-chat delivery target no longer exists: {home}; do not resend"
# run_one_job/claim_fire attach the durable execution id before delivery. The
@@ -748,27 +767,33 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
from tools.bot_live_delivery import find_canonical_owner
pending = read_pending(key)
- if pending is None and find_canonical_live_owner(home) is None and find_canonical_owner(home):
- pending = defer(key, dict(job), content, profile, home)
+ # Validate existing identity and settle only never-started requests under
+ # the producer lock. Suppression is a durable disposition, not a send.
+ if (pending is not None or suppress_notification
+ or (find_canonical_live_owner(home) is None and find_canonical_owner(home))):
+ pending = defer(key, dict(job), content, profile, home,
+ for_failure=for_failure, suppressed=suppress_notification)
if pending is not None:
- if pending["content"] != content or pending["home"] != str(home):
- raise ValueError("delivery id already belongs to a different payload")
status = pending["status"]
target = f"bot-chat:{profile_label}"
job.setdefault("_bot_chat_delivery_receipts", {})[target] = {
- "status": status, "delivery_id": key}
- return None if status == "settled" else f"{target} {status} (receipt {key}): completion unverified; do not resend"
+ "status": status, "delivery_id": key, "home": str(home)}
+ if status == "suppressed":
+ job["_notification_all_targets_suppressed"] = True
+ return None if status in ("settled", "suppressed") else f"{target} {status} (receipt {key}): completion unverified; do not resend"
if receipt is None:
owner = find_canonical_live_owner(home)
if owner is not None:
- receipt = deliver_to_live_owner(home, owner, message, delivery_id=key)
+ receipt = deliver_to_live_owner(home, owner, message, delivery_id=key,
+ **({"notification_category": "diagnostic"} if for_failure else {}))
if receipt is not None:
- if receipt["message"] != message:
+ if (receipt["message"] != message
+ or receipt.get("notification_category", "result") != ("diagnostic" if for_failure else "result")):
raise ValueError("delivery id already belongs to a different payload")
status = receipt["status"]
target = f"bot-chat:{profile_label}"
receipts = job.setdefault("_bot_chat_delivery_receipts", {})
- receipts[target] = {"status": status, "delivery_id": key}
+ receipts[target] = {"status": status, "delivery_id": key, "home": str(home)}
logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",
job_id, profile_label, key, status)
if status == "settled":
@@ -1151,8 +1176,11 @@ def _record_delivery_verification(job: dict, unverified_targets: list) -> None:
return
job.update(values)
try:
- from cron.jobs import update_job
- update_job(job["id"], values)
+ from cron.jobs import update_delivery_projection, update_job
+ if job.get("execution_id"):
+ update_delivery_projection(job["id"], job["execution_id"], values)
+ else:
+ update_job(job["id"], values)
except Exception as exc: # pragma: no cover - defensive
logger.debug("Job '%s': could not record delivery verification: %s", job.get("id"), exc)
@@ -1762,6 +1790,10 @@ def _deliver_result(
standalone fallback. ``for_failure=True`` routes failure-category notices through the job's
``failure_deliver`` override when present (NS-788). Returns None on success, else an error."""
job.pop("_bot_chat_delivery_receipts", None)
+ job.pop("_notification_suppressed_targets", None)
+ job.pop("_notification_all_targets_suppressed", None)
+ job.pop("_manifest_intent_marked", None)
+ job.pop("_policy_drop_errors", None)
targets = _resolve_delivery_targets(job, for_failure=for_failure)
if not targets:
_record_delivery_verification(job, [])
@@ -1778,11 +1810,25 @@ def _deliver_result(
and any(target["platform"] != BOT_CHAT_PLATFORM for target in targets)):
from cron.delivery_queue import enqueue_and_wait
+ from cron.executions import record_delivery_manifest
+ record_delivery_manifest(job.get("execution_id"), {"external": True})
_record_delivery_verification(job, [])
error = enqueue_and_wait(external_execution, job, content, for_failure=for_failure)
- from cron.jobs import get_job
- refreshed = get_job(job["id"]) or {}
- job["last_delivery_queued"] = refreshed.get("last_delivery_queued")
+ from cron.delivery_queue import get_status
+ delivery_status = get_status(external_execution)
+ if delivery_status and delivery_status["status"] == "suppressed":
+ job["_notification_all_targets_suppressed"] = True
+ from cron.executions import get_execution, _delivery_projection, manifest_pending
+ execution = get_execution(external_execution)
+ projection = _delivery_projection(execution) if execution and execution.get("delivery_manifest") else None
+ job["last_delivery_queued"] = (
+ {"gateway": {"status": "queued", "delivery_id": external_execution}}
+ if (delivery_status and delivery_status["status"] in ("pending", "delivering"))
+ or manifest_pending(execution) # gateway sent children; their manifest is not recorded yet
+ else projection[1]["last_delivery_queued"] if projection else None)
+ from cron.jobs import update_delivery_projection
+ update_delivery_projection(job["id"], external_execution,
+ {"last_delivery_queued": job["last_delivery_queued"]})
return error
from gateway.config import load_gateway_config
@@ -1826,6 +1872,7 @@ def _deliver_result(
"policy (missing file, denied prefix, or strict-mode miss); "
"see gateway.strict / media_delivery_allow_dirs in config.yaml"
] if _policy_dropped > 0 else []
+ job["_policy_drop_errors"] = policy_drop_errors
# Resolve the mirror gate ONCE (default off): successful deliveries are appended to the target
# chat's session transcript. Mirror the CLEAN, unwrapped output (not the header/footer).
@@ -1846,10 +1893,49 @@ def _deliver_result(
return msg
delivery_errors = []
+ unverified_targets: list = []
+ if any(t["platform"] == BOT_CHAT_PLATFORM for t in targets) and job.get("execution_id"):
+ # Durable intent BEFORE any send in this run: until the manifest lands, no reader may
+ # treat this run's placeholder/absence of a manifest as terminal. Nothing has been sent,
+ # so a ledger fault here is a truthful pre-send failure and nothing is sent at all.
+ try:
+ _mark_manifest_intent(job)
+ except Exception as exc:
+ msg = f"delivery ledger unavailable before send: {exc}"
+ logger.error("Job '%s': %s", job["id"], msg)
+ return msg
+ try:
+ _deliver_targets(job, targets, content, cleaned_delivery_content, media_files, adapters, loop,
+ config, user_cfg, notify_delivery, mirror_enabled, mirror_text,
+ for_failure, delivery_errors, unverified_targets)
+ except BaseException as exc:
+ # Any exit after the mark MUST settle the manifest (possibly with no children), else the
+ # row is pending forever. The exception itself is retained in the manifest error, and a
+ # second failure inside settlement never masks it (the row simply stays pending).
+ try:
+ _settle_manifest(job, targets, delivery_errors + [f"{type(exc).__name__}: {exc}"], unverified_targets)
+ except BaseException as settle_exc: # noqa: BLE001 - deliberate: preserve the original
+ logger.error("Job '%s': manifest settlement interrupted (%r); row stays pending",
+ job.get("id"), settle_exc)
+ raise
+ return _settle_manifest(job, targets, delivery_errors, unverified_targets)
+
+
+def _deliver_targets(job, targets, content, cleaned_delivery_content, media_files, adapters, loop,
+ config, user_cfg, notify_delivery, mirror_enabled, mirror_text,
+ for_failure, delivery_errors, unverified_targets) -> None:
for target in targets:
+ from gateway.warning_notifications import warning_notifications_enabled
+ if (for_failure and target["platform"] != BOT_CHAT_PLATFORM
+ and not warning_notifications_enabled(target["platform"], user_cfg)):
+ job.setdefault("_notification_suppressed_targets", []).append(dict(target))
+ continue
# Bot Chat owns admission; never concurrently resume a live owner's transcript.
if target["platform"] == BOT_CHAT_PLATFORM:
- bot_chat_error = _deliver_to_bot_chat(job, content, target["chat_id"])
+ bot_chat_error = _deliver_to_bot_chat(job, content, target["chat_id"],
+ **({"for_failure": True} if for_failure else {}))
+ if job.pop("_notification_all_targets_suppressed", False):
+ job.setdefault("_notification_suppressed_targets", []).append(dict(target))
if bot_chat_error:
receipt_target = f"bot-chat:{target['chat_id'] or '(own)'}"
receipt = job.get("_bot_chat_delivery_receipts", {}).get(receipt_target)
@@ -1876,8 +1962,57 @@ def _deliver_result(
t, cleaned_delivery_content, media_files, target_errors, delivery_errors)
# Filter-time drops apply to every target; report them once.
- delivery_errors.extend(policy_drop_errors)
+ if len(job.get("_notification_suppressed_targets", [])) == len(targets):
+ job["_notification_all_targets_suppressed"] = True
+ if not job.get("_notification_all_targets_suppressed"):
+ delivery_errors.extend(job.get("_policy_drop_errors", []))
+
+
+def _settle_manifest(job: dict, targets: list, delivery_errors: list, unverified_targets: list) -> Optional[str]:
+ """Record this run's child manifest (possibly empty) and return the legacy error string.
+
+ Called on EVERY exit of the delivery loop once intent may have been marked: a run that
+ marked intent but ends with no receipt settles through the same durable, replayable
+ manifest path as one with children, so it never stays pending forever.
+ """
_record_delivery_verification(job, unverified_targets)
+ from cron.executions import record_delivery_manifest
+ bot_receipts = job.get("_bot_chat_delivery_receipts", {})
+ native_count = sum(t["platform"] != BOT_CHAT_PLATFORM for t in targets)
+ native_suppressed = sum(t["platform"] != BOT_CHAT_PLATFORM for t in job.get("_notification_suppressed_targets", []))
+ # Only deferred receipts need mutable terminal projections. Direct native
+ # sends retain legacy delivered-plus-unverified behavior when default-off.
+ if bot_receipts:
+ manifest = {
+ "bot": bot_receipts,
+ "delivered": native_count > native_suppressed or (not bot_receipts and not job.get("_notification_all_targets_suppressed")),
+ "error": "; ".join(delivery_errors) if delivery_errors else None,
+ "unverified": unverified_targets,
+ }
+ try:
+ record_delivery_manifest(job.get("execution_id"), manifest)
+ except Exception:
+ # Post-send bookkeeping: the sends above already happened and the receipts are
+ # durable. The row's pending flag (set before the first send) keeps it queued and
+ # unprunable; the journal is a best-effort copy for the reconciler. Never report a
+ # transport failure, which would discard the pending sibling or invite a resend.
+ logger.exception("Job '%s': delivery manifest not recorded; row stays pending", job.get("id"))
+ if job.get("execution_id"):
+ from cron.executions import journal_manifest
+ journal_manifest(str(job["execution_id"]), manifest) # never raises
+ elif job.get("_manifest_intent_marked") and job.get("execution_id"):
+ # Intent was marked but no child receipt exists (rejected pre-admission, filtered, or an
+ # exception on the way). Settle through the same durable, replayable manifest path so
+ # the row leaves pending with its errors retained; transient ledger faults replay later.
+ manifest = {"bot": {}, "delivered": native_count > native_suppressed,
+ "error": "; ".join(delivery_errors) if delivery_errors else None,
+ "unverified": unverified_targets}
+ try:
+ record_delivery_manifest(job.get("execution_id"), manifest)
+ except Exception:
+ logger.exception("Job '%s': no-receipt manifest not recorded; row stays pending", job.get("id"))
+ from cron.executions import journal_manifest
+ journal_manifest(str(job["execution_id"]), manifest) # never raises
return "; ".join(delivery_errors) if delivery_errors else None
diff --git a/gateway/display_config.py b/gateway/display_config.py
index db6907734ca..52c398884a9 100644
--- a/gateway/display_config.py
+++ b/gateway/display_config.py
@@ -21,6 +21,7 @@ _GLOBAL_DEFAULTS: dict[str, Any] = {
"streaming": None, # None = follow top-level streaming config
# Gateway-only assistant/status chatter; mobile platforms opt down to final-answer-first.
"interim_assistant_messages": True,
+ "suppress_warning_notifications": False,
"long_running_notifications": True,
"busy_ack_detail": True,
"busy_steer_ack_enabled": True, # busy_input_mode=steer echo; the text still lands in the run
@@ -95,8 +96,11 @@ def resolve_display_setting(user_config: dict, platform_key: str, setting: str,
def _configured_display_value(user_config: dict, platform_key: str, setting: str) -> Any:
"""First non-None operator value, without introducing tier defaults."""
- display_cfg = user_config.get("display") or {}
- plat_overrides = (display_cfg.get("platforms") or {}).get(platform_key)
+ display_cfg = user_config.get("display")
+ if not isinstance(display_cfg, dict):
+ return None
+ platforms = display_cfg.get("platforms")
+ plat_overrides = platforms.get(platform_key) if isinstance(platforms, dict) else None
if isinstance(plat_overrides, dict) and plat_overrides.get(setting) is not None:
return plat_overrides[setting]
if setting == "tool_progress":
@@ -150,6 +154,15 @@ def _norm_long_running(value: Any) -> Any:
return "generic" if isinstance(value, str) and value.strip().lower() == "generic" else _norm_bool(value)
+def _norm_suppress_warning_notifications(value: Any) -> bool:
+ # Only an explicit, recognized opt-in may hide engine diagnostics.
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ return value.strip().lower() in _TRUTHY
+ return False
+
+
def _norm_cleanup_progress(value: Any) -> bool:
return value.lower() in _TRUTHY if isinstance(value, str) else bool(value)
@@ -174,6 +187,7 @@ _NORMALISERS: dict[str, Any] = {
"show_reasoning": _norm_bool,
"streaming": _norm_bool,
"interim_assistant_messages": _norm_bool,
+ "suppress_warning_notifications": _norm_suppress_warning_notifications,
"long_running_notifications": _norm_long_running,
"busy_ack_detail": _norm_bool,
"busy_steer_ack_enabled": _norm_bool,
diff --git a/gateway/kanban_watchers_notifier.py b/gateway/kanban_watchers_notifier.py
index 9be3d05c584..f159519ed4f 100644
--- a/gateway/kanban_watchers_notifier.py
+++ b/gateway/kanban_watchers_notifier.py
@@ -35,6 +35,15 @@ TERMINAL_KINDS = ("completed", "blocked", "gave_up", "crashed", "timed_out", "st
# Kinds that hand a decision back to the origin, which must take a turn.
# status/archived/unblocked are bookkeeping.
_WAKE_KINDS = ("completed", "gave_up", "crashed", "timed_out", "blocked", "review_requested", "changes_requested", "block_loop_detected")
+
+
+def diagnostic_event(ev) -> bool:
+ """Infrastructure attention is distinct from an explicit owner decision."""
+ if ev.kind in {"crashed", "timed_out", "gave_up"}:
+ return True
+ if ev.kind in {"blocked", "block_loop_detected"}:
+ return (ev.payload or {}).get("kind") != "needs_input"
+ return ev.kind == "status" and (ev.payload or {}).get("status") in {"blocked", "triage"}
# Consecutive send failures (adapter raised OR reported SendResult(success=False))
# before a sub is dropped as a dead chat. 12 ≈ 60s at the 5s cadence: a transient
# API outage must not permanently unsubscribe a live review-gate channel.
@@ -515,6 +524,7 @@ class _KanbanNotification:
"""Set ``wake_kinds`` / ``session_key`` / ``synth`` for the wake paths."""
task, sub = self.task, self.sub
self.wake_kinds = {ev.kind for ev in self.d["events"] if ev.kind in _WAKE_KINDS} if self.wake_agent else set()
+ self.wake_diagnostic = all(diagnostic_event(ev) for ev in self.d["events"] if ev.kind in self.wake_kinds)
if not self.wake_kinds:
return
if self.is_push_adapter:
@@ -559,7 +569,8 @@ class _KanbanNotification:
from gateway.wake import deliver_wake
sub = self.sub
if not self.is_push_adapter:
- await deliver_wake(self.adapter, text=self.synth, session_id=self.session_key)
+ await deliver_wake(self.adapter, text=self.synth, session_id=self.session_key,
+ notification_category="diagnostic" if self.wake_diagnostic else "result")
self._log_woke()
return
from gateway.session import SessionSource
@@ -587,17 +598,24 @@ class _KanbanNotification:
if not profile_exists(self.sub_profile):
raise RuntimeError(f"Kanban wake profile {self.sub_profile!r} no longer exists")
async with _async_profile_runtime_scope(self.runner._resolve_profile_home_for_source(_source)):
- await deliver_wake(self.adapter, text=self.synth, session_id=self.session_key, source=_source)
+ await deliver_wake(self.adapter, text=self.synth, session_id=self.session_key, source=_source,
+ notification_category="diagnostic" if self.wake_diagnostic else "result")
self._log_woke()
- async def _send_event(self, ev: Any, msg: str) -> None:
+ async def _send_event(self, ev: Any, msg: str) -> bool:
"""Send one text ping; raises on adapter exception or SendResult(success=False)."""
+ from gateway.warning_notifications import present_notification
sub, adapter = self.sub, self.adapter
delivery_metadata = sub.get("delivery_metadata")
metadata: dict[str, Any] = dict(delivery_metadata) if isinstance(delivery_metadata, dict) else {}
if sub.get("thread_id") and not metadata.get("thread_id"):
metadata["thread_id"] = sub["thread_id"]
- _send_res = await adapter.send(sub["chat_id"], msg, metadata=metadata)
+ _send_res = None
+ async def send_ping():
+ nonlocal _send_res
+ _send_res = await adapter.send(sub["chat_id"], msg, metadata=metadata)
+ if not await present_notification(send_ping, platform=self.platform_str, diagnostic=diagnostic_event(ev)):
+ return False
# SendResult(success=False) without an exception is a FAILED delivery
# (else the event is lost); None / non-SendResult keeps the
# "no exception == delivered" contract.
@@ -618,6 +636,7 @@ class _KanbanNotification:
)
except Exception as art_exc:
logger.debug("kanban notifier: artifact delivery for %s failed: %s", self.task_id, art_exc)
+ return True
async def _send_pings(self) -> bool:
"""Send every text ping; False when a send failed (claim already rewound/dropped)."""
@@ -641,7 +660,8 @@ class _KanbanNotification:
if ev.id <= self.sub.get("last_ping_event_id", 0):
continue
try:
- await self._send_event(ev, msg)
+ if await self._send_event(ev, msg) is False:
+ continue
await _to_thread_process_service(partial(
self.runner._kanban_sub_op, self.board_slug, "record_notify_ping", self.sub,
event_id=ev.id,
@@ -678,14 +698,33 @@ class _KanbanNotification:
if not await self._send_pings():
return
# All text pings delivered (or skipped for non-push / wake-only).
- self.build_wake_text()
+ original_events = self.d["events"]
+ from gateway.warning_notifications import warning_notifications_enabled
+ split = not warning_notifications_enabled(self.platform_str)
+ wake_groups = ([original_events] if not split else [
+ [ev for ev in original_events if diagnostic_event(ev)],
+ [ev for ev in original_events if not diagnostic_event(ev)],
+ ])
+ wake_payloads = []
+ for events in wake_groups:
+ if not events:
+ continue
+ self.d = {**self.d, "events": events}
+ self.wake_handoff = self.wake_review_detail = ""
+ for ev in events:
+ self.format_event(ev)
+ self.build_wake_text()
+ if self.wake_kinds:
+ wake_payloads.append((self.synth, self.wake_diagnostic, self.wake_kinds))
+ self.d = {**self.d, "events": original_events}
wake_kinds, is_push = self.wake_kinds, self.is_push_adapter
from gateway.wake import WakeNotAccepted
# A requested wake is required even when its passive ping already landed.
- if wake_kinds:
+ if wake_payloads:
try:
- await self.wake()
+ for self.synth, self.wake_diagnostic, self.wake_kinds in wake_payloads:
+ await self.wake()
self.clear_failures()
except WakeNotAccepted:
# Startup / full queue is not a dead destination. Keep the durable
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index df5725c9155..721b6d9f50b 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -372,6 +372,12 @@ def _project_client_message(message: Dict[str, Any]) -> Dict[str, Any]:
ids), merged handoffs keep only the real prior-tail content; inherited tool calls dropped."""
from agent.compaction_display import (
_COMPACTION_INTERNAL_FIELDS, project_compaction_message_for_display)
+ if (message.get("display_kind") == "hidden"
+ and (message.get("display_metadata") or {}).get("notification_category") == "diagnostic"):
+ # Retain row identity and execution evidence in storage, not in the notification UI.
+ return {k: v for k, v in message.items() if k in {
+ "id", "session_id", "role", "timestamp", "display_kind", "platform_message_id",
+ }} | {"content": ""}
projected = project_compaction_message_for_display(message)
if projected is None:
projected = {k: v for k, v in message.items() if k not in _COMPACTION_INTERNAL_FIELDS}
@@ -3703,7 +3709,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
requested_runtime: Optional[Dict[str, Any]] = None, route_source: str = "global",
confirmed_runtime_lock: bool = False, bind_declared_conversation: bool = False,
session_history_delivery: str = "", turn_author: Optional[Dict[str, Any]] = None,
- relay_metadata: Optional[Dict[str, Any]] = None) -> tuple:
+ relay_metadata: Optional[Dict[str, Any]] = None, notification_category: str = "result") -> tuple:
"""Create an agent and run one turn in a thread executor -> ``(result, usage)``.
``agent_ref[0]`` receives the agent so SSE writers can interrupt it; ``active_run_id``
registers it in ``_active_run_agents``. Under a confirmed model lock the actual
@@ -3728,6 +3734,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
browser_control_transport_family=request_browser_control_transport_family,
session_history_delivery=session_history_delivery)
agent = None
+ from agent.notification_presentation import notification_turn
+ from gateway.warning_notifications import diagnostic_turn_muted
+ muted = diagnostic_turn_muted({"notification_category": notification_category}, "api_server")
try:
agent = self._create_agent(
ephemeral_system_prompt=ephemeral_system_prompt, session_id=session_id,
@@ -3765,10 +3774,16 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
)
if relay_metadata:
conversation_kwargs["relay_metadata"] = relay_metadata
- result = agent.run_conversation(**conversation_kwargs)
- return self._finish_turn_result(
+ with notification_turn(agent, muted=muted, session_id=session_id or ""):
+ result = agent.run_conversation(**conversation_kwargs)
+ result, usage = self._finish_turn_result(
agent, result, session_id, route=route, requested_runtime=requested_runtime,
route_source=route_source, confirmed_runtime_lock=confirmed_runtime_lock)
+ if muted and isinstance(result, dict):
+ # Project presentation only after finishing the source outcome. Keep
+ # the agent's result, transcript, failure flags and usage intact.
+ result = {**result, "_notification_presentation_suppressed": True}
+ return result, usage
except _ProviderAuthResolutionError as exc:
# Typed provider-auth failure only, handled once for every caller in
# run.py's response shape (text, no HTTP error).
@@ -3776,8 +3791,15 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
session_id or "", exc)
return (
{"final_response": f"⚠️ Provider authentication failed: {exc}", "messages": [],
- "api_calls": 0, "tools": []},
+ "api_calls": 0, "tools": [],
+ **({"_notification_presentation_suppressed": True} if muted else {})},
{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0})
+ except Exception as exc:
+ if muted:
+ # Keep the original exception/traceback for logs and failure
+ # handling; the HTTP/SSE boundary suppresses its presentation.
+ setattr(exc, "_notification_presentation_suppressed", True)
+ raise
finally:
# Turn over (any outcome): clear ownership so a late disconnect can't reap
# background work this turn deliberately left running.
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.py
index 6da8690fa55..96adfa5753b 100644
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@ -511,6 +511,10 @@ class OpenAICompatRoutesMixin:
# id from a header-less client is NOT: delegate_task keeps its forced-sync fallback
# there — the wake would hard-fail or land in history that client never reloads.
session_history_delivery=("1" if provided_session_id else ""))
+ # This is presentation only. The ordinary API-key/session authorization
+ # above still applies; it grants no internal ingress or control authority.
+ if provided_session_id and body.get("hermes_notification_category") == "diagnostic":
+ run_kwargs["notification_category"] = "diagnostic"
if stream:
_stream_q = ThreadSafeAsyncQueue()
# tool_call_ids with an emitted "running": a "completed" without one (internal/
@@ -554,12 +558,14 @@ class OpenAICompatRoutesMixin:
return await self._run_agent(**run_kwargs)
outcome, err = await self._run_idempotent(
request, body, _compute_completion, log_label="chat completions",
- fingerprint_keys=["model", "provider", "model_options", "messages", "tools", "tool_choice", "stream"],
+ fingerprint_keys=["model", "provider", "model_options", "messages", "tools", "tool_choice", "stream",
+ "hermes_notification_category"],
route="chat_completions",
)
if err is not None:
return err
result, usage = outcome
+ presentation_muted = result.get("_notification_presentation_suppressed") is True
final_response = _resolve_media_to_data_urls(result.get("final_response") or "")
completed, is_partial, is_failed, err_msg = _result_flags(result)
if err_msg:
@@ -575,7 +581,7 @@ class OpenAICompatRoutesMixin:
# clients raise instead of rendering the failure string as message.content.
if not final_response and (is_failed or is_partial):
err_body = _openai_error(
- err_msg or "Agent run did not produce a response.", err_type="server_error",
+ "" if presentation_muted else (err_msg or "Agent run did not produce a response."), err_type="server_error",
code="agent_incomplete")
err_body["error"]["hermes"] = {
"completed": completed, "partial": is_partial, "failed": is_failed}
@@ -586,15 +592,15 @@ class OpenAICompatRoutesMixin:
response_data = {
"id": completion_id, "object": "chat.completion", "created": created,
"model": model_name,
- "choices": [{"index": 0, "message": {"role": "assistant", "content": final_response},
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "" if presentation_muted else final_response},
"finish_reason": finish_reason}],
"usage": _chat_usage_payload(usage)}
if is_partial or is_failed or not completed:
response_data["hermes"] = _hermes_extras(
- completed, is_partial, is_failed, err_msg, finish_reason)
+ completed, is_partial, is_failed, "" if presentation_muted else err_msg, finish_reason)
response_headers["X-Hermes-Completed"] = "false"
response_headers["X-Hermes-Partial"] = "true" if is_partial else "false"
- if err_msg:
+ if err_msg and not presentation_muted:
response_headers["X-Hermes-Error"] = _redact_api_error_text(err_msg, limit=200)
return web.json_response(response_data, headers=response_headers)
@@ -624,7 +630,8 @@ class OpenAICompatRoutesMixin:
return (result, usage), None
except Exception as e:
logger.error("Error running agent for %s: %s", log_label, e, exc_info=True)
- return None, _error_response(f"Internal server error: {e}", 500, err_type="server_error")
+ message = "" if getattr(e, "_notification_presentation_suppressed", False) is True else f"Internal server error: {e}"
+ return None, _error_response(message, 500, err_type="server_error")
async def _prepare_sse_response(
self, request: "web.Request", session_id: Optional[str], gateway_session_key: Optional[str],
@@ -684,13 +691,17 @@ class OpenAICompatRoutesMixin:
err_msg = err_msg or str(agent_error)
finish_reason = _finish_reason(completed, is_partial, is_failed, err_msg, agent_error)
finish_chunk = _chunk({}, finish_reason, usage=_chat_usage_payload(usage))
+ presentation_muted = (
+ (isinstance(result, dict) and result.get("_notification_presentation_suppressed") is True)
+ or getattr(agent_error, "_notification_presentation_suppressed", False) is True
+ )
if finish_reason != "stop":
- if err_msg:
+ if err_msg and not presentation_muted:
finish_chunk["error"] = {
"message": err_msg,
"type": type(agent_error).__name__ if agent_error else "agent_error"}
finish_chunk["hermes"] = _hermes_extras(
- completed, is_partial, is_failed, err_msg, finish_reason)
+ completed, is_partial, is_failed, "" if presentation_muted else err_msg, finish_reason)
await response.write(_sse_frame(finish_chunk))
await response.write(b"data: [DONE]\n\n")
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError):
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 3bf7d2990b2..d4c4865ef4b 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -2841,8 +2841,55 @@ class BasePlatformAdapter(ABC):
shown."""
logger.warning("[%s] %s fallback: native %s send unavailable for %s", self.name, method, kind, path)
text = _media_failure_text(kind, file_name)
- text = f"{caption}\n{text}" if caption else text
- return await self.send(chat_id=chat_id, content=text, reply_to=reply_to, metadata=metadata)
+ return await self.emit_media_warning(chat_id, text, caption=caption, reply_to=reply_to, metadata=metadata,
+ shown_metadata=metadata)
+
+ async def emit_warning(
+ self, chat_id: str, content: str, *, reply_to=None, metadata=None, logical_platform=None,
+ ) -> Optional[SendResult]:
+ """Present a classified channel diagnostic in the caller's owning scope.
+
+ None means suppressed, NOT successfully sent. Transport receipts/exceptions
+ pass through unchanged; logs and producer state belong outside this boundary.
+ Existing routing/stream metadata is preserved, never inferred from text.
+ """
+ if not self.warning_notifications_enabled(logical_platform, chat_id=chat_id, metadata=metadata):
+ return None
+ return await self.send(chat_id, content, reply_to=reply_to, metadata=metadata)
+
+ async def emit_media_warning(
+ self, chat_id: str, notice: str, *, caption=None, reply_to=None, metadata=None,
+ shown_metadata=None,
+ ) -> SendResult:
+ """Present an optional media diagnostic without losing the requested caption.
+
+ Preserve the legacy fallback-text receipt when shown (``shown_metadata`` is the exact
+ metadata the legacy shown path passed; default None keeps callers that sent none
+ byte-identical). When hidden, preserve the media failure even if the independent
+ caption itself was delivered.
+ """
+ result = await self.emit_warning(chat_id, f"{caption}\n{notice}" if caption else notice,
+ reply_to=reply_to, metadata=shown_metadata)
+ if result is not None:
+ return result
+ if caption:
+ await self.send(chat_id, caption, reply_to=reply_to, metadata=metadata)
+ return SendResult(success=False, error=notice)
+
+ def warning_text(self, visible: str, hidden: Optional[str] = "", *, logical_platform=None, chat_id=None, metadata=None) -> Optional[str]:
+ """Project mixed content: the diagnostic variant when visible, else the requested remainder.
+
+ For payloads that combine a requested result (caption, answer) with an automatic
+ diagnostic. The requested part must be present in BOTH variants; never hide it.
+ """
+ if self.warning_notifications_enabled(logical_platform, chat_id=chat_id, metadata=metadata):
+ return visible
+ return hidden
+
+ def warning_notifications_enabled(self, logical_platform=None, *, chat_id=None, metadata=None) -> bool:
+ """Presentation policy under the caller's owning profile; old plugins inherit it."""
+ from gateway.warning_notifications import warning_notifications_enabled
+ return warning_notifications_enabled(logical_platform or self.platform)
def prepare_tts_text(self, text: str) -> str:
"""Chat Markdown -> transcript-like spoken script (reasoning blocks removed,
@@ -2933,8 +2980,9 @@ class BasePlatformAdapter(ABC):
else:
text = _media_failure_text("file", os.path.basename(media_path))
try:
- notice = await self.send(chat_id=chat_id, content=text, metadata=metadata)
- problem = None if notice.success else notice.error
+ notice = await self.emit_warning(chat_id, text,
+ metadata={**(metadata or {}), "_interim_send": True})
+ problem = None if notice is None or notice.success else notice.error
except Exception as notify_err:
problem = notify_err
if problem is not None:
@@ -3310,8 +3358,8 @@ class BasePlatformAdapter(ABC):
self._schedule_ephemeral_delete(event.source.chat_id, result.message_id, eph_ttl)
def _media_delivery_scope(self, source: Optional[SessionSource]):
- """The runner's ``_media_delivery_scope_for_source`` (routed profile's home + terminal
- policy) for validating outbound paths; a no-op without a runner or outside multiplexing."""
+ """Routed home + terminal policy for post-handler text, media and error delivery;
+ a no-op without a runner or outside multiplexing."""
resolve = getattr(self.gateway_runner, "_media_delivery_scope_for_source", None)
if not callable(resolve) or source is None:
return contextlib.nullcontext()
@@ -3424,9 +3472,12 @@ class BasePlatformAdapter(ABC):
)
return result
logger.error("[%s] Failed to deliver response after %d retries: %s", self.name, max_retries, error_str)
- notice = (
+ notice = self.warning_text(
"\u26a0\ufe0f Message delivery failed after multiple attempts. "
- "Please try again \u2014 your request was processed but the response could not be sent.")
+ "Please try again \u2014 your request was processed but the response could not be sent.",
+ chat_id=chat_id, metadata=metadata)
+ if not notice:
+ return result
try:
await _send(notice)
except Exception as notify_err:
@@ -3451,7 +3502,9 @@ class BasePlatformAdapter(ABC):
"""Last-resort send after a non-transient failure; platforms whose markup is not the
likely culprit override it (Photon drops rich links instead of adding the banner)."""
return await self.send(
- chat_id=chat_id, content=f"(Response formatting failed, plain text:)\n\n{content[:3500]}",
+ chat_id=chat_id, content=self.warning_text(
+ f"(Response formatting failed, plain text:)\n\n{content[:3500]}", content[:3500],
+ chat_id=chat_id, metadata=metadata),
reply_to=reply_to, metadata=metadata)
@staticmethod
@@ -4030,13 +4083,21 @@ class BasePlatformAdapter(ABC):
"""Tell the user a turn failed rather than leaving radio silence (last resort:
a failing notice is logged, never raised). Returns the thread metadata used."""
_thread_metadata = None
+ from gateway.warning_notifications import diagnostic_wake_muted
try:
- error_detail = str(e)[:300] if str(e) else "no details available"
- _thread_metadata = _thread_metadata_for_event(event)
- await self.send(
- chat_id=event.source.chat_id,
- content=(f"Sorry, I encountered an error ({type(e).__name__}).\n{error_detail}\n"
- "Try again or use /reset to start a fresh session."), metadata=_thread_metadata)
+ with self._media_delivery_scope(event.source):
+ _thread_metadata = _thread_metadata_for_event(event)
+ if diagnostic_wake_muted(event):
+ return _thread_metadata
+ error_detail = str(e)[:300] if str(e) else "no details available"
+ await self.send(
+ chat_id=event.source.chat_id,
+ content=self.warning_text(
+ f"Sorry, I encountered an error ({type(e).__name__}).\n{error_detail}\n"
+ "Try again or use /reset to start a fresh session.",
+ "Sorry, I encountered an error.",
+ logical_platform=event.source.platform, chat_id=event.source.chat_id, metadata=_thread_metadata),
+ metadata=_thread_metadata)
except Exception as notify_err:
logger.error(
"[%s] Failed to send error notification to user: %s", self.name, notify_err, exc_info=True)
@@ -4178,47 +4239,53 @@ class BasePlatformAdapter(ABC):
try:
await self._run_processing_hook("on_processing_start", event)
response = await self._message_handler(event)
- is_ephemeral_response = isinstance(response, EphemeralReply)
- # Unwrap EphemeralReply for downstream text processing; TTL applies after send.
- response, _ephemeral_ttl = self._unwrap_ephemeral(response)
- # None/empty is normal (streamed/queued). Suppress a stale response after an interrupt.
- if response and interrupt_event.is_set() and session_key in self._pending_messages:
- logger.info("[%s] Suppressing stale response for interrupted session %s", self.name,
- session_key)
- response = None
- if not response:
- logger.debug("[%s] Handler returned empty/None response for %s", self.name, event.source.chat_id)
- else:
- extracted = await self._extract_response_content(
- response, event, session_key, is_ephemeral_response=is_ephemeral_response)
- text_content, media_files = extracted.text_content, extracted.media_files
- # Final content gets notify=True; typing metadata stays unmarked (thread-strict).
- _final_thread_metadata = _mark_notify_metadata(_thread_metadata)
- _tts_paths, _tts_requested_path = [], None
- if self._wants_auto_tts(
- event, session_key, interrupt_event, text_content, media_files):
- _tts_paths, _tts_requested_path = await self._synthesize_auto_tts(text_content)
- # TTS plays before text; generated files are removed afterwards.
- _tts_caption_delivered = False
- for _tts_index, _tts_path in enumerate(_tts_paths):
- try:
- _tts_caption_delivered |= await self._play_tts_file(
- event, text_content, _tts_path, _tts_index == 0, _final_thread_metadata,
- _record_delivery)
- finally:
+ from gateway.warning_notifications import diagnostic_wake_muted
+ # The handler has left the owner scope. Keep it for the whole delivery,
+ # including transport fallbacks, but exit before draining another turn.
+ with self._media_delivery_scope(event.source):
+ if diagnostic_wake_muted(event):
+ response = None
+ is_ephemeral_response = isinstance(response, EphemeralReply)
+ # Unwrap EphemeralReply for downstream text processing; TTL applies after send.
+ response, _ephemeral_ttl = self._unwrap_ephemeral(response)
+ # None/empty is normal (streamed/queued). Suppress a stale response after an interrupt.
+ if response and interrupt_event.is_set() and session_key in self._pending_messages:
+ logger.info("[%s] Suppressing stale response for interrupted session %s", self.name,
+ session_key)
+ response = None
+ if not response:
+ logger.debug("[%s] Handler returned empty/None response for %s", self.name, event.source.chat_id)
+ else:
+ extracted = await self._extract_response_content(
+ response, event, session_key, is_ephemeral_response=is_ephemeral_response)
+ text_content, media_files = extracted.text_content, extracted.media_files
+ # Final content gets notify=True; typing metadata stays unmarked (thread-strict).
+ _final_thread_metadata = _mark_notify_metadata(_thread_metadata)
+ _tts_paths, _tts_requested_path = [], None
+ if self._wants_auto_tts(
+ event, session_key, interrupt_event, text_content, media_files):
+ _tts_paths, _tts_requested_path = await self._synthesize_auto_tts(text_content)
+ # TTS plays before text; generated files are removed afterwards.
+ _tts_caption_delivered = False
+ for _tts_index, _tts_path in enumerate(_tts_paths):
+ try:
+ _tts_caption_delivered |= await self._play_tts_file(
+ event, text_content, _tts_path, _tts_index == 0, _final_thread_metadata,
+ _record_delivery)
+ finally:
+ with contextlib.suppress(OSError):
+ os.remove(_tts_path)
+ if not _tts_paths and _tts_requested_path is not None:
with contextlib.suppress(OSError):
- os.remove(_tts_path)
- if not _tts_paths and _tts_requested_path is not None:
- with contextlib.suppress(OSError):
- os.remove(_tts_requested_path)
- if text_content and not _tts_caption_delivered:
- await self._send_final_text(
- event, session_key, text_content, _final_thread_metadata,
- is_ephemeral_response, _ephemeral_ttl, _record_delivery)
- await self._deliver_attachments(
- event, extracted, _final_thread_metadata,
- anything_sent=delivery_attempted or _tts_caption_delivered,
- record_delivery=_record_delivery)
+ os.remove(_tts_requested_path)
+ if text_content and not _tts_caption_delivered:
+ await self._send_final_text(
+ event, session_key, text_content, _final_thread_metadata,
+ is_ephemeral_response, _ephemeral_ttl, _record_delivery)
+ await self._deliver_attachments(
+ event, extracted, _final_thread_metadata,
+ anything_sent=delivery_attempted or _tts_caption_delivered,
+ record_delivery=_record_delivery)
processing_ok = delivery_succeeded if delivery_attempted else not bool(response)
# Clean up the per-turn streaming-TTS flag.
self._streaming_tts_completed_turns.discard(self._streaming_tts_turn_key(
diff --git a/gateway/platforms/event.py b/gateway/platforms/event.py
index d5353e3a48c..ccc84ebc67e 100644
--- a/gateway/platforms/event.py
+++ b/gateway/platforms/event.py
@@ -86,6 +86,8 @@ class MessageEvent:
# Process-local admission receipt, never routing metadata or execution acknowledgement.
_gateway_accepted: bool = field(default=False, init=False, repr=False, compare=False)
+ # Run-owned final presentation snapshot; never deserialized from ingress metadata.
+ _notification_reply_muted: Optional[bool] = field(default=None, init=False, repr=False, compare=False)
def is_command(self) -> bool:
"""Check if this is a command message (e.g., /new, /reset)."""
diff --git a/gateway/platforms/signal.py b/gateway/platforms/signal.py
index 611cd74da78..f763db86f71 100644
--- a/gateway/platforms/signal.py
+++ b/gateway/platforms/signal.py
@@ -856,7 +856,7 @@ class SignalAdapter(BasePlatformAdapter):
async def _notify_batch_pacing(self, chat_id: str, next_batch_idx: int, total_batches: int, wait_s: float) -> None:
"""Tell the user about an inter-batch pacing wait over the notice threshold (best-effort)."""
try:
- await self.send(chat_id, f"(More images coming — pausing ~{_format_wait(wait_s)} for Signal rate limit, "
+ await self.emit_warning(chat_id, f"(More images coming — pausing ~{_format_wait(wait_s)} for Signal rate limit, "
f"batch {next_batch_idx}/{total_batches}.)")
except Exception as e:
logger.warning("Signal: failed to send pacing notice: %s", e)
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.py
index d65c1005837..eedb8abe0f0 100644
--- a/gateway/platforms/weixin.py
+++ b/gateway/platforms/weixin.py
@@ -1114,7 +1114,7 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
async def send_voice(self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to=None, metadata=None) -> SendResult:
# Native outbound voice bubbles are not proven-working upstream; a file attachment at least plays (even .silk).
- return await self._send_file_result(chat_id, audio_path, caption or "[voice message as attachment]", "send_voice", force_file_attachment=True)
+ return await self._send_file_result(chat_id, audio_path, caption or self.warning_text("[voice message as attachment]"), "send_voice", force_file_attachment=True)
async def _download_remote_media(self, url: str) -> str:
from tools.url_safety import is_safe_url
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.py
index fe7afc5d6d8..c22db5020da 100644
--- a/gateway/relay/adapter.py
+++ b/gateway/relay/adapter.py
@@ -213,6 +213,11 @@ class RelayAdapter(BasePlatformAdapter):
"""The chat's underlying platform as seen inbound, else the primary's."""
return self._platform_by_chat.get(str(chat_id)) or self.descriptor.platform
+ def warning_notifications_enabled(self, logical_platform=None, *, chat_id=None, metadata=None) -> bool:
+ platform = (logical_platform or (metadata or {}).get("_relay_logical_platform")
+ or self._chat_platform(chat_id))
+ return super().warning_notifications_enabled(platform)
+
def _descriptor_for_chat(self, chat_id: str) -> CapabilityDescriptor:
"""The descriptor governing a specific chat. Platform caps genuinely differ
(Discord 2000 / Telegram 4096 / Slack 39000), so the primary's scalar cap
@@ -1420,6 +1425,8 @@ class RelayAdapter(BasePlatformAdapter):
if seal is not None:
return seal
if explicit_platform:
+ if _interim:
+ send_metadata["_interim_send"] = True
return await self.send_for_platform(
explicit_platform, chat_id, content, reply_to=reply_to, metadata=send_metadata or None
)
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index 0753e76591b..344c7ad2494 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -310,6 +310,7 @@ class GatewayBusySessionMixin:
_SECURITY_METADATA_KEYS = (
"hermes_plugin_id", "hermes_plugin_injection", "gateway_session_key",
"gateway_session_id", "gateway_session_strict",
+ "notification_category",
)
def _queue_or_replace_pending_event(self, session_key: str, event: MessageEvent) -> None:
diff --git a/gateway/run_inbound_unauthorized.py b/gateway/run_inbound_unauthorized.py
index 4276d81a49a..28425157fee 100644
--- a/gateway/run_inbound_unauthorized.py
+++ b/gateway/run_inbound_unauthorized.py
@@ -112,7 +112,12 @@ class UnauthorizedOwnerNotifier:
# The stranger's DM *is* the home channel (misconfiguration); posting there would
# answer the unauthorized user, which the ignore behaviour exists to prevent.
return
- await runner._send_home_channel_message(
- platform, home, transport, f"⚠️ {hint}", "unauthorized-sender notice failed for %s:%s: %s",
+ # Automatic operator diagnostic on the home channel; same boundary as the state.db warning.
+ from gateway.warning_notifications import present_notification
+ await present_notification(
+ lambda: runner._send_home_channel_message(
+ platform, home, transport, f"⚠️ {hint}", "unauthorized-sender notice failed for %s:%s: %s",
+ ),
+ platform=platform,
)
return
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 3dc5f1a9d5e..3e8ba18e3e0 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -68,7 +68,7 @@ class GatewayNotificationsMixin:
# Coalescing keys: process completions (short-window fan-in) and async delegations (+ parent session).
_COMPLETION_BATCH_KEY_FIELDS = ("session_key", "platform", "chat_type", "chat_id", "thread_id", "user_id")
- _ASYNC_GROUP_KEY_FIELDS = ("session_key", "parent_session_id", *_COMPLETION_BATCH_KEY_FIELDS[1:])
+ _ASYNC_GROUP_KEY_FIELDS = ("session_key", "parent_session_id", "task_failure_notice", *_COMPLETION_BATCH_KEY_FIELDS[1:])
@dataclasses.dataclass
class _UpdatePaths:
@@ -934,10 +934,12 @@ class GatewayNotificationsMixin:
f"gateway machine, then `hermes {profile_arg}gateway restart`."
)
logger.warning("Broadcasting state.db failure warning to home channels: %s", error)
+ from gateway.warning_notifications import present_notification
for platform, _platform_cfg, home, transport in self._home_channel_transports():
- await self._send_home_channel_message(
- platform, home, transport, message, "state.db warning notification failed for %s:%s: %s",
- )
+ await present_notification(
+ lambda: self._send_home_channel_message(
+ platform, home, transport, message, "state.db warning notification failed for %s:%s: %s"),
+ platform=platform)
def _build_process_event_source(self, evt: dict):
"""Resolve the canonical source for a synthetic background-process event.
@@ -1054,7 +1056,9 @@ class GatewayNotificationsMixin:
else:
info = "Watch pattern notification — waking api_server session %s via self-post"
fail = "Watch notification self-post wake failed for session %s: %s"
- deliver = lambda: deliver_wake(adapter, text=synth_text, session_id=raw_sid) # noqa: E731
+ from agent.notification_presentation import diagnostic_process_event
+ deliver = lambda: deliver_wake(adapter, text=synth_text, session_id=raw_sid,
+ notification_category="diagnostic" if diagnostic_process_event(evt) else "result") # noqa: E731
try:
logger.info(info, raw_sid)
await deliver()
@@ -1125,6 +1129,9 @@ class GatewayNotificationsMixin:
try:
metadata = {}
session_key = str(evt.get("session_key") or "").strip()
+ from agent.notification_presentation import diagnostic_process_event
+ if diagnostic_process_event(evt):
+ metadata["notification_category"] = "diagnostic"
if session_key.startswith("agent:"):
metadata["gateway_session_key"] = session_key
parent_session_id = str(evt.get("parent_session_id") or "").strip()
@@ -1876,7 +1883,12 @@ class GatewayNotificationsMixin:
notify_mode == "error" and session.exit_code not in {0, None}
):
message_text = self._format_process_final_message(session_id, session, notify_mode)
- await self._send_watcher_message(platform_name, chat_id, thread_id, message_text, watcher)
+ from gateway.warning_notifications import present_notification
+ async with self._completion_event_scope(watcher):
+ # Non-zero exit is the automatic diagnostic; a clean completion is the requested result.
+ await present_notification(
+ lambda: self._send_watcher_message(platform_name, chat_id, thread_id, message_text, watcher),
+ platform=platform_name, diagnostic=session.exit_code not in {0, None})
break
elif has_new_output and notify_mode == "all" and not agent_notify:
# New output — deliver a status update (only in "all" mode; agent_notify watchers
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index 4e68091527e..b8c4091fe6b 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -16,7 +16,7 @@ import shlex
import sys
import threading
import time
-from contextlib import contextmanager, suppress
+from contextlib import contextmanager, nullcontext, suppress
from pathlib import Path
from typing import Any, Callable, Dict, Optional
@@ -868,11 +868,14 @@ class GatewayShutdownMixin:
continue
with _log_suppressed(logging.DEBUG, "Cron interrupt notice to %s:%s raised: %s", platform.value, chat_id):
metadata = self._thread_metadata_for_target(platform, chat_id, thread_id, adapter=adapter)
- if await self._send_notice_logged(
- adapter, chat_id, msg, platform.value, "Cron interrupt notice to %s:%s failed: %s",
- "Cron interrupt notice to %s:%s raised: %s", metadata=metadata,
- ):
- notified.add(dedup_key)
+ async def send_notice():
+ if await self._send_notice_logged(
+ adapter, chat_id, msg, platform.value, "Cron interrupt notice to %s:%s failed: %s",
+ "Cron interrupt notice to %s:%s raised: %s", metadata=metadata,
+ ):
+ notified.add(dedup_key)
+ from gateway.warning_notifications import present_notification
+ await present_notification(send_notice, platform=platform)
if notified:
logger.info("Shutdown: delivered %d interrupted-cron-job notice(s)", len(notified))
return len(notified)
@@ -978,8 +981,21 @@ class GatewayShutdownMixin:
except Exception as e:
logger.debug("Failed to send shutdown notification to %s:%s: %s", platform_str, chat_id, e)
continue
- if await self._send_shutdown_notice(adapter, chat_id, msg, "active chat", platform_str, metadata=metadata):
- notified.add(dedup_key)
+ # Automatic interrupt diagnostic, resolved under the session's own profile scope (same
+ # shape as the stall watcher). The requester's own chat on an in-chat /restart is the
+ # requested outcome of that command and is never suppressed.
+ async def _send_active(adapter=adapter, chat_id=chat_id, platform_str=platform_str,
+ metadata=metadata, dedup_key=dedup_key):
+ if await self._send_shutdown_notice(adapter, chat_id, msg, "active chat", platform_str, metadata=metadata):
+ notified.add(dedup_key)
+ from gateway.warning_notifications import present_notification
+ from gateway.run import _async_profile_runtime_scope
+ scope = (_async_profile_runtime_scope(self._resolve_profile_home_for_source(source))
+ if source is not None else nullcontext())
+ async with scope:
+ presented = await present_notification(_send_active, platform=platform, diagnostic=restart_key != dedup_key)
+ if not presented:
+ notified.add(dedup_key) # suppressed: latch so the home-channel pass does not re-target it
if self._restart_requested and restart_source is not None:
logger.debug("Skipping home-channel shutdown notifications for in-chat restart")
return
@@ -1011,11 +1027,14 @@ class GatewayShutdownMixin:
)
continue
# Home channels omit ``metadata=`` when empty (adapter doubles may not accept the kwarg).
- if await self._send_shutdown_notice(
- adapter, str(home.chat_id), msg, "home channel", platform.value,
- **({"metadata": metadata} if metadata else {}),
- ):
- notified.add(dedup_key)
+ async def _send_home(adapter=adapter, home=home, platform=platform, metadata=metadata):
+ if await self._send_shutdown_notice(
+ adapter, str(home.chat_id), msg, "home channel", platform.value,
+ **({"metadata": metadata} if metadata else {}),
+ ):
+ notified.add(dedup_key)
+ from gateway.warning_notifications import present_notification
+ await present_notification(_send_home, platform=platform)
# Agent finalization / resource cleanup
@staticmethod
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 2c01323b32f..84a7279b962 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -822,7 +822,8 @@ class GatewayTurnMixin:
try:
_adapter = self._adapter_for_source(source)
if _adapter and source.chat_id:
- await _adapter.send(source.chat_id, message, metadata=meta)
+ await _adapter.emit_warning(source.chat_id, message, metadata=meta,
+ logical_platform=source.platform)
except Exception as _werr:
logger.warning("Failed to deliver %s to user: %s", what, _werr)
@@ -1842,6 +1843,9 @@ class GatewayTurnMixin:
):
"""Final delivery decisions: intentional silence, voice reply, streamed-turn media/footer.
Returns the text for the adapter to send, or ``None`` when already delivered."""
+ from gateway.warning_notifications import diagnostic_wake_muted
+ if diagnostic_wake_muted(event):
+ return None
# Intentional silence is a delivery decision: the [SILENT] turn stays persisted (alternation).
if _intentional_silence:
logger.info("Suppressing intentional silence marker for session %s", session_entry.session_id)
@@ -2104,7 +2108,11 @@ class GatewayTurnMixin:
persist_user_message=prepared.persist_user_message,
persist_user_timestamp=prepared.persist_user_timestamp,
persist_user_display_kind=prepared.persist_user_display_kind,
- persist_user_display_metadata={"gateway_input_owner": prepared.persistence_owner},
+ persist_user_display_metadata={
+ "gateway_input_owner": prepared.persistence_owner,
+ **({"notification_category": "diagnostic"}
+ if event.internal and (event.metadata or {}).get("notification_category") == "diagnostic" else {}),
+ },
message_type=event.message_type,
scheduled_heartbeat=bool(getattr(event, "_heartbeat_session_id", None)),
)
@@ -2118,6 +2126,10 @@ class GatewayTurnMixin:
_terminal_inbound = agent_result.get("queued_terminal_inbound_id")
if _terminal_inbound:
event.ledger_message_id = str(_terminal_inbound)
+ if "queued_terminal_notification_category" in agent_result:
+ event.metadata["notification_category"] = agent_result["queued_terminal_notification_category"]
+ if isinstance(agent_result.get("_notification_reply_muted"), bool):
+ event._notification_reply_muted = agent_result["_notification_reply_muted"]
await self._hmwa_stop_typing_for_turn(event, source)
@@ -2417,12 +2429,13 @@ class GatewayTurnMixin:
except Exception as e:
logger.exception("Background task %s failed", task_id)
+ # Automatic failure diagnostic (the task produced no requested result to deliver).
with suppress(Exception):
- await adapter.send(
- chat_id=source.chat_id,
- content=(f"❌ Your background task \"{_bg_prompt_preview(prompt)}\" failed before finishing. "
- "Send /bg again to retry, or /agents to see what is still running."),
- metadata=_thread_metadata,
+ await adapter.emit_warning(
+ source.chat_id,
+ (f"❌ Your background task \"{_bg_prompt_preview(prompt)}\" failed before finishing. "
+ "Send /bg again to retry, or /agents to see what is still running."),
+ metadata=_thread_metadata, logical_platform=source.platform,
)
def _mcp_reload_refresh_cached_agents(self, multiplex: bool, profile) -> None:
@@ -2977,6 +2990,9 @@ class GatewayTurnMixin:
**{name: getattr(disp, name) for name in self._DISPLAY_TO_TURN_CTX}, **turn_params,
)
turn_runner = TurnRunner(self, turn_ctx)
+ from gateway.warning_notifications import diagnostic_turn_muted
+ turn_ctx.mute_notification_reply = diagnostic_turn_muted(
+ turn_ctx.persist_user_display_metadata, source.platform, turn_ctx.user_config)
# Agent tool-lifecycle callbacks live on the runner (bound methods, same signatures).
turn_ctx.progress_callback = turn_runner.progress_callback
turn_ctx.voice_ack_callback = turn_runner.voice_ack_callback
@@ -3385,12 +3401,12 @@ class GatewayTurnMixin:
if not _warn_adapter:
return
try:
- await _warn_adapter.send(
+ await _warn_adapter.emit_warning(
source.chat_id, f"⚠️ I seem to be stuck (no activity for {int(worker.agent_warning // 60) or 1} min). "
"If nothing happens in the next "
f"{int((worker.agent_timeout - worker.agent_warning) // 60) or 1} min I'll give up on this task. "
"You can keep waiting, send /stop to cancel it, or /new to start a fresh conversation.",
- metadata=_interim_metadata(_status_thread_metadata),
+ metadata=_interim_metadata(_status_thread_metadata), logical_platform=source.platform,
)
except Exception as _warn_err:
logger.debug("Inactivity warning send error: %s", _warn_err)
@@ -3590,6 +3606,8 @@ class GatewayTurnMixin:
self, turn_ctx: TurnContext, adapter: Any, response: Any, result: Any, stream_task: Any,
) -> None:
"""Deliver the first response before a queued follow-up runs, unless streaming already did."""
+ if turn_ctx.mute_notification_reply:
+ return
session_key = turn_ctx.session_key
_sc = turn_ctx.stream_consumer_holder[0]
if _sc and stream_task:
@@ -3765,6 +3783,10 @@ class GatewayTurnMixin:
event_message_id=next_message_id, inbound_message_id=next_inbound_id,
channel_prompt=next_channel_prompt, message_type=next_message_type,
persist_user_display_kind=next_display_kind,
+ persist_user_display_metadata=(
+ {"notification_category": "diagnostic"}
+ if pending_event is not None and pending_event.internal
+ and (pending_event.metadata or {}).get("notification_category") == "diagnostic" else None),
)
except asyncio.CancelledError:
await _run_followup_processing_hook(
@@ -3788,6 +3810,9 @@ class GatewayTurnMixin:
**merged,
"queued_terminal_inbound_id": next_inbound_id,
"queued_terminal_display_kind": next_display_kind,
+ "queued_terminal_notification_category": (
+ (pending_event.metadata or {}).get("notification_category", "result")
+ if pending_event is not None and pending_event.internal else "result"),
}
return merged
@@ -4126,7 +4151,8 @@ class GatewayTurnMixin:
_status_thread_metadata = self._run_agent_bind_turn_wiring(
turn_ctx, turn_runner, source, event_message_id, disp._native_slack_task_cards,
)
- if not scheduled_heartbeat:
+ # Two independent quiet reasons: a muted diagnostic wake (ours) and a scheduled heartbeat.
+ if not (scheduled_heartbeat or turn_ctx.mute_notification_reply):
self._run_agent_start_streaming_tts(
source, message_type, _status_thread_metadata, turn_ctx.streaming_tts_consumer_holder,
)
@@ -4143,7 +4169,7 @@ class GatewayTurnMixin:
# Periodic "still working" notifications so the user knows the agent hasn't died.
_executor_task_holder: list = [None] # bound once the executor future exists (see below)
_notify_task = (
- None if scheduled_heartbeat
+ None if (scheduled_heartbeat or turn_ctx.mute_notification_reply)
else spawn(self._run_agent_notify_long_running(disp, turn_ctx, _executor_task_holder))
)
@@ -4152,6 +4178,8 @@ class GatewayTurnMixin:
worker = self._run_agent_start_turn_worker(turn_ctx, turn_runner.run_sync)
_executor_task_holder[0] = worker.executor_task # read late by _notify_long_running
response = await self._run_agent_await_turn_worker(worker, turn_ctx, _interrupt_detected, interrupt_monitor)
+ if isinstance(response, dict):
+ response["_notification_reply_muted"] = turn_ctx.mute_notification_reply
self._run_agent_evict_on_fallback(turn_ctx)
# Interrupted OR queued message (/queue)?
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 3b8a8f78961..dbce9ad8547 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -175,6 +175,7 @@ class TurnRunner:
def _progress_subagent_notice(self, preview, kwargs: dict) -> None:
"""Only terminal failure statuses render (same notice rail as credit warnings)."""
ctx = self._ctx
+ from gateway.warning_notifications import render_notification
status = kwargs.get("status")
try:
from tools.delegate_tool import SUBAGENT_FAILURE_STATUSES, format_subagent_failure_line
@@ -183,7 +184,9 @@ class TurnRunner:
kwargs.get("goal"), status, error=kwargs.get("summary") or preview,
duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
)
- self._schedule(self._runner._deliver_platform_notice(ctx.source, line), "subagent failure notice scheduling error")
+ render_notification(
+ lambda: self._schedule(self._runner._deliver_platform_notice(ctx.source, line), "subagent failure notice scheduling error"),
+ platform=ctx.source.platform, user_config=ctx.user_config)
except Exception:
logger.debug("subagent failure notice failed", exc_info=True)
@@ -876,8 +879,9 @@ class TurnRunner:
def _status_callback_sync(self, event_type: str, message: str) -> None:
from gateway.run import _prepare_gateway_status_message, _redact_gateway_user_facing_secrets, _send_or_update_status_coro
+ from gateway.warning_notifications import is_warning_status, render_notification
ctx = self._ctx
- if not self._status_live():
+ if ctx.mute_notification_reply or not self._status_live():
return
prepared = _prepare_gateway_status_message(ctx.source.platform, event_type, message)
if prepared is None:
@@ -887,17 +891,25 @@ class TurnRunner:
_redact_gateway_user_facing_secrets(str(message or ""))[:160],
)
return
- fut = self._schedule(
- _send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared, ctx._status_thread_metadata),
- f"status_callback ({event_type}) scheduling error",
- )
- if fut is not None and ctx._cleanup_progress:
- fut.add_done_callback(self._track_future_cleanup_id)
+ metadata = ctx._status_thread_metadata
+ if is_warning_status(event_type, message):
+ metadata = {**(metadata or {}), "_interim_send": True}
+ def present():
+ fut = self._schedule(
+ _send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared, metadata),
+ f"status_callback ({event_type}) scheduling error",
+ )
+ if fut is not None and ctx._cleanup_progress:
+ fut.add_done_callback(self._track_future_cleanup_id)
+ render_notification(present, platform=ctx.source.platform, user_config=ctx.user_config,
+ diagnostic=is_warning_status(event_type, message))
# ── stream consumer / interim commentary wiring ─────────────────────────────────────────
def _setup_stream_consumer(self, platform_key):
ctx = self._ctx
+ if ctx.mute_notification_reply:
+ return None, None, None, False
stream_consumer = None
# The streaming-TTS consumer is created on the outer loop thread before run_sync launches;
# run_sync only reads it via the holder for delta-callback wiring.
@@ -1147,15 +1159,21 @@ class TurnRunner:
"""Credits / out-of-band notices (usage bands, depletion, restored) fire from the agent's
sync worker thread; hop onto the gateway loop. Fired-once latch lives on the cached agent."""
from gateway.run import render_notice_line
- if not self._status_live():
- return
- try:
- line = render_notice_line(notice)
- except Exception:
- logger.debug("render_notice_line failed", exc_info=True)
+ from gateway.warning_notifications import render_notification
+ if self._ctx.mute_notification_reply or not self._status_live():
return
- if line:
- self._schedule(self._runner._deliver_platform_notice(self._ctx.source, line), "notice_callback delivery scheduling error")
+ diagnostic = (getattr(notice, "level", None) in {"warn", "error"}
+ or str(getattr(notice, "key", "") or "").startswith("credits."))
+ def present():
+ try:
+ line = render_notice_line(notice)
+ except Exception:
+ logger.debug("render_notice_line failed", exc_info=True)
+ return
+ if line:
+ self._schedule(self._runner._deliver_platform_notice(self._ctx.source, line), "notice_callback delivery scheduling error")
+ render_notification(present, platform=self._ctx.source.platform,
+ user_config=self._ctx.user_config, diagnostic=diagnostic)
def _make_bg_review_callbacks(self):
"""(send, release): background-review messages ("💾 Memory updated") are held until the
@@ -1214,6 +1232,8 @@ class TurnRunner:
baked into the cached agent."""
ctx = self._ctx
runner = self._runner
+ agent._notification_config = ctx.user_config
+ agent._notification_platform = ctx.source.platform
# ALWAYS attached (never gated to None): its body gates each event class, and subagent-
# failure notices must fire even with tool_progress/thinking off.
agent.tool_progress_callback = ctx.progress_callback
@@ -1256,6 +1276,16 @@ class TurnRunner:
# Thinking between tool calls is independent of tool_progress mode (Mattermost opts in
# per platform so global scratch-text doesn't leak into threads).
agent.thinking_progress = ctx._thinking_enabled
+ if ctx.mute_notification_reply:
+ # Controls and operational event/step callbacks remain wired. These
+ # presentation callbacks are rebound on every next turn.
+ agent.tool_progress_callback = None
+ agent.tool_start_callback = None
+ agent.tool_complete_callback = None
+ # Keep diagnostic observers installed; concrete sinks veto display.
+ agent.stream_delta_callback = None
+ agent.interim_assistant_callback = None
+ agent.thinking_progress = False
ctx.agent_holder[0] = agent # interrupt support
# The titler fires from the turn prologue, so attach the rename lane before the run.
self._attach_session_title_callback(agent, ctx)
@@ -1666,7 +1696,9 @@ class TurnRunner:
# turn so a restart-interrupted turn is recorded WITH its id for drain-window dedup.
if ctx.inbound_message_id is not None:
kwargs["persist_user_platform_id"] = str(ctx.inbound_message_id)
- return agent.run_conversation(api_message, **kwargs)
+ from agent.notification_presentation import notification_turn
+ with notification_turn(agent, muted=ctx.mute_notification_reply, session_id=ctx.session_id or ""):
+ return agent.run_conversation(api_message, **kwargs)
finally:
unregister_gateway_notify(session_key)
# Cancel pending clarify entries so blocked agent threads don't hang past the end of the
diff --git a/gateway/run_watchers.py b/gateway/run_watchers.py
index 3d9bc78f51e..bb197698403 100644
--- a/gateway/run_watchers.py
+++ b/gateway/run_watchers.py
@@ -177,15 +177,25 @@ class GatewaySessionWatchersMixin:
"fresh_idle=%s", session_key, still_pending, fresh_idle)
notified_map.pop(session_key, None) # re-arm so a FUTURE genuine stall notifies again
return False
+ from gateway.warning_notifications import present_notification
+ from gateway.run import _async_profile_runtime_scope
try:
metadata = self._thread_metadata_for_source(source)
notice = format_session_stall_notification(idle_seconds)
- # Bound the send: a wedged adapter transport (network hang, dead websocket) must not
- # block the watcher pass — siblings would go unevaluated and the watcher stop.
- result = await asyncio.wait_for(
- adapter.send(str(source.chat_id), notice, metadata=metadata),
- timeout=_STALL_NOTIFY_SEND_TIMEOUT_SECONDS,
- )
+ result = None
+ async def send_notice():
+ nonlocal result
+ # Bound the send: a wedged adapter transport (network hang, dead websocket) must not
+ # block the watcher pass — siblings would go unevaluated and the watcher stop.
+ result = await asyncio.wait_for(
+ adapter.send(str(source.chat_id), notice, metadata=metadata),
+ timeout=_STALL_NOTIFY_SEND_TIMEOUT_SECONDS,
+ )
+ async with _async_profile_runtime_scope(self._resolve_profile_home_for_source(source)):
+ presented = await present_notification(send_notice, platform=source.platform)
+ if not presented:
+ notified_map[session_key] = True # suppressed: latch so the stall is not re-evaluated every tick
+ return False
# Adapters often return SendResult(success=False) instead of raising.
if result is not None and getattr(result, "success", True) is False:
raise RuntimeError(getattr(result, "error", "send returned success=False"))
diff --git a/gateway/turn_context.py b/gateway/turn_context.py
index 664f1abb249..a85f2036222 100644
--- a/gateway/turn_context.py
+++ b/gateway/turn_context.py
@@ -61,6 +61,7 @@ class TurnContext:
persist_user_display_kind: Optional[str] = None
persist_user_display_metadata: Optional[dict] = None
user_config: Any = None
+ mute_notification_reply: bool = False
enabled_toolsets: Any = None
disabled_toolsets: Any = None
log_mode_enabled: bool = False
diff --git a/gateway/wake.py b/gateway/wake.py
index 6d05c11ccd2..17e4196524a 100644
--- a/gateway/wake.py
+++ b/gateway/wake.py
@@ -51,7 +51,8 @@ async def admit_internal_event(adapter: Any, event: Any) -> None:
raise WakeNotAccepted("internal wake not accepted by adapter")
-async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source: Any = None) -> None:
+async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source: Any = None,
+ notification_category: str = "result") -> None:
"""Deliver a wake turn to the session behind ``adapter``. ``session_id`` is the RAW session id
(``X-Hermes-Session-Id`` / state.db key) — required for non-push adapters. ``source`` is the
``SessionSource`` for the synthetic event — required for push-capable adapters. Raises on
@@ -60,13 +61,16 @@ async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source:
if source is None:
raise ValueError("deliver_wake: push-capable adapter requires a SessionSource")
from gateway.platforms.event import MessageEvent, MessageType
- synth_event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=True)
+ synth_event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=True,
+ metadata={"notification_category": notification_category})
await admit_internal_event(adapter, synth_event)
return
if not session_id:
raise ValueError("deliver_wake: non-push adapter (supports_async_delivery=False) "
"requires the raw session id to self-post the wake turn")
- await _self_post_chat_completion(adapter, text=text, session_id=session_id)
+ await _self_post_chat_completion(adapter, text=text, session_id=session_id,
+ **({"notification_category": notification_category}
+ if notification_category == "diagnostic" else {}))
def _delegation_display_metadata(evt: dict) -> dict:
@@ -83,6 +87,10 @@ def _delegation_display_metadata(evt: dict) -> dict:
"failed_count": failed_count}
if evt.get("task_failure_notice"):
metadata["delivery_notice"] = f"task_failure:{results[0].get('task_index', '') if results else ''}"
+ metadata["notification_category"] = "diagnostic"
+ from gateway.warning_notifications import warning_notifications_enabled
+ if not warning_notifications_enabled("api_server"):
+ metadata["presentation_suppressed"] = True
duration = evt.get("total_duration_seconds") or evt.get("duration_seconds")
if isinstance(duration, (int, float)):
metadata["duration_seconds"] = duration
@@ -132,7 +140,8 @@ async def persist_delegation_delivery(adapter: Any, *, text: str, session_id: st
)
-async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: str) -> None:
+async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: str,
+ notification_category: str = "result") -> None:
"""POST the wake text to the in-pod API server as a normal session turn, using the adapter's
own bind host/port/key. Session continuation via ``X-Hermes-Session-Id`` is 403-gated on
``API_SERVER_KEY``, so a missing key is a hard error rather than a wake in a fresh session
@@ -153,6 +162,8 @@ async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: str
headers = {"Authorization": f"Bearer {api_key}", "X-Hermes-Session-Id": session_id}
payload = {"model": str(getattr(adapter, "_model_name", "") or "hermes-agent"),
"messages": [{"role": "user", "content": text}], "stream": False}
+ if notification_category == "diagnostic":
+ payload["hermes_notification_category"] = "diagnostic"
last_err: Optional[BaseException] = None
attempts = 1 + len(_RETRY_DELAYS_SECONDS)
for attempt in range(attempts):
diff --git a/gateway/warning_notifications.py b/gateway/warning_notifications.py
new file mode 100644
index 00000000000..1c32dca88b6
--- /dev/null
+++ b/gateway/warning_notifications.py
@@ -0,0 +1,74 @@
+"""Delivery policy for engine diagnostics, never assistant or command responses."""
+
+from gateway.display_config import resolve_display_setting
+
+
+class DiagnosticText(str):
+ """Producer-owned classification on the legacy two-argument status callback.
+
+ String behavior and event kind stay unchanged for existing plugin renderers.
+ Durable carriers must serialize their own category, not this in-memory marker.
+ """
+
+
+def is_warning_status(event_type: str, message: str) -> bool:
+ return event_type == "warn" or isinstance(message, DiagnosticText)
+
+
+def diagnostic_turn_muted(display_metadata, platform, user_config=None) -> bool:
+ """One admission rule for every surface: a diagnostic-category wake mutes its turn's
+ presentation only when the owning policy hides diagnostics. Human content never mutes."""
+ return ((display_metadata or {}).get("notification_category") == "diagnostic"
+ and not warning_notifications_enabled(platform, user_config))
+
+
+def diagnostic_wake_muted(event, user_config=None) -> bool:
+ """Only trusted diagnostic-only wakes can mute a turn, never human content."""
+ snapshot = getattr(event, "_notification_reply_muted", None)
+ if isinstance(snapshot, bool):
+ return snapshot
+ return bool(getattr(event, "internal", False)) and diagnostic_turn_muted(
+ getattr(event, "metadata", None), event.source.platform, user_config)
+
+
+def render_notification(render, *, platform, diagnostic=True, user_config=None) -> bool:
+ """Invoke a synchronous UI renderer only when its classified content is visible.
+
+ Return whether the renderer ran, not whether a transport delivered anything.
+ Call only at a presentation sink, never around producer callbacks or persistence.
+ The caller supplies the owning scope/turn snapshot; exceptions remain its policy.
+ """
+ if diagnostic and not warning_notifications_enabled(platform, user_config):
+ return False
+ render()
+ return True
+
+
+async def present_notification(present, *, platform, diagnostic=True, user_config=None) -> bool:
+ """Async twin of :func:`render_notification` for lifecycle emitters that await a send.
+
+ Return whether the presenter ran; its own receipt/exception is the caller's to interpret.
+ The caller binds the owning profile scope BEFORE calling (watchers/shutdown fan-outs).
+ """
+ if diagnostic and not warning_notifications_enabled(platform, user_config):
+ return False
+ await present()
+ return True
+
+
+def warning_notifications_enabled(platform, user_config=None) -> bool:
+ """Use the turn snapshot when supplied, otherwise the active profile's effective config.
+
+ No surface exemption: direct command/API outcomes are not notifications.
+ Unknown values never opt in; null inherits via the canonical display resolver.
+ """
+ if user_config is None:
+ from hermes_cli.config_effective import load_user_config_effective
+ try:
+ user_config = load_user_config_effective()
+ except Exception:
+ user_config = {}
+ if not isinstance(user_config, dict):
+ user_config = {}
+ platform_key = getattr(platform, "value", platform)
+ return not resolve_display_setting(user_config, platform_key, "suppress_warning_notifications", False)
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 717da2d6b76..ec8e0cd91b0 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -320,7 +320,10 @@ class CLIAgentSetupMixin:
logger.warning(
"Primary provider auth failed (%s). Falling through to fallback: %s/%s",
primary_exc, _fb_provider, _fb_model)
- _cprint(f"⚠️ Primary auth failed — switching to fallback: {_fb_provider} / {_fb_model}")
+ from gateway.warning_notifications import render_notification
+ render_notification(
+ lambda: _cprint(f"⚠️ Primary auth failed — switching to fallback: {_fb_provider} / {_fb_model}"),
+ platform="cli")
self.requested_provider = _fb_provider
self.model = _fb_model
return runtime
diff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.py
index 739a54341ac..4aaa1a27dd1 100644
--- a/hermes_cli/cli_chat_turn_mixin.py
+++ b/hermes_cli/cli_chat_turn_mixin.py
@@ -77,27 +77,32 @@ class CLIChatTurnMixin:
ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")
print(flush=True)
- turn = _ChatTurn()
- try:
- self._reset_stream_state()
- # Not part of _reset_stream_state: must persist across intermediate turn
- # boundaries (tool-calling loops), reset once per user turn.
- self._reasoning_shown_this_turn = False
- self._chat_setup_turn_audio(turn, message, voice_input)
- # Per-prompt elapsed timer — frozen when the agent thread finishes.
- self._prompt_start_time = time.time()
- self._prompt_duration = 0.0
- # Daemon: closing the terminal tab (SIGHUP) must not be kept alive by it.
- agent_thread = threading.Thread(target=self._chat_run_agent, args=(turn, message), daemon=True)
- agent_thread.start()
- interrupt_msg = self._chat_monitor_agent_thread(turn, agent_thread)
- self._chat_settle_turn(turn)
- return self._chat_render_turn(turn, agent_thread, interrupt_msg)
- except Exception as e:
- print(f"Error: {e}")
- return None
- finally:
- self._chat_release_turn_audio(turn)
+ from agent.notification_presentation import notification_config_snapshot, notification_policy_snapshot
+ with notification_policy_snapshot(agent, "cli", notification_config_snapshot()):
+ turn = _ChatTurn()
+ from gateway.warning_notifications import diagnostic_turn_muted
+ turn.mute_notification_reply = diagnostic_turn_muted(
+ agent._pending_cli_user_message.get("display_metadata"), "cli", agent._notification_config)
+ try:
+ self._reset_stream_state()
+ # Not part of _reset_stream_state: must persist across intermediate turn
+ # boundaries (tool-calling loops), reset once per user turn.
+ self._reasoning_shown_this_turn = False
+ self._chat_setup_turn_audio(turn, message, voice_input)
+ # Per-prompt elapsed timer — frozen when the agent thread finishes.
+ self._prompt_start_time = time.time()
+ self._prompt_duration = 0.0
+ # Daemon: closing the terminal tab (SIGHUP) must not be kept alive by it.
+ agent_thread = threading.Thread(target=self._chat_run_agent, args=(turn, message), daemon=True)
+ agent_thread.start()
+ interrupt_msg = self._chat_monitor_agent_thread(turn, agent_thread)
+ self._chat_settle_turn(turn)
+ return self._chat_render_turn(turn, agent_thread, interrupt_msg)
+ except Exception as e:
+ print(f"Error: {e}")
+ return None
+ finally:
+ self._chat_release_turn_audio(turn)
def _chat_release_turn_audio(self, turn):
"""Every exit path: stop the thinking sound, send the TTS sentinel, cut TTS only if abnormal."""
@@ -215,13 +220,16 @@ class CLIChatTurnMixin:
from tools.process_registry_notifications import TimelineNotification
if isinstance(message, TimelineNotification):
staged_user_message.update(content=str(message), display_kind=message.display_kind,
- display_metadata={"display_text": message.display_text})
+ display_metadata={"display_text": message.display_text,
+ "notification_category": message.notification_category})
agent._pending_cli_user_message = staged_user_message
self.conversation_history.append(staged_user_message)
def _chat_setup_turn_audio(self, turn, message, voice_input):
"""Arm the full-duplex listener and the streaming-TTS pipeline for this turn (voice mode only)."""
from cli import _ACCENT, _RST, _STREAM_PAD, _cprint, datetime
+ if getattr(turn, "mute_notification_reply", False):
+ return
# Continuous voice mode: arm the mic NOW (utterance-submit), not at TTS playback —
# it spans generation (speech interrupts the turn) and playback (speech cuts TTS)
# and disarms itself when the turn is done. See _voice_full_duplex_listener.
@@ -319,12 +327,15 @@ class CLIChatTurnMixin:
_one_turn_model_restore = getattr(self, "_pending_one_turn_model_restore", None)
self._pending_one_turn_model_restore = None
try:
- turn.result = self.agent.run_conversation(
- user_message=agent_message,
- conversation_history=self.conversation_history[:-1], # exclude the message just staged
- stream_callback=turn.stream_callback, task_id=self.session_id,
- persist_user_message=_persist_clean_user_message, moa_config=_moa_cfg,
- )
+ from agent.notification_presentation import notification_turn
+ muted = getattr(turn, "mute_notification_reply", False)
+ with notification_turn(self.agent, muted=muted, session_id=self.session_id):
+ turn.result = self.agent.run_conversation(
+ user_message=agent_message,
+ conversation_history=self.conversation_history[:-1],
+ stream_callback=None if muted else turn.stream_callback, task_id=self.session_id,
+ persist_user_message=_persist_clean_user_message, moa_config=_moa_cfg,
+ )
if getattr(self, "_pending_moa_disable_after_turn", False):
_restore = getattr(self, "_pending_moa_restore_model", None) or {}
for _key, _value in _restore.items():
@@ -484,6 +495,11 @@ class CLIChatTurnMixin:
"""
from cli import _DIM, _RST, _cprint, _suspend_output_history
response = turn.result.get("final_response", "") if turn.result else ""
+ if getattr(turn, "mute_notification_reply", False):
+ pending, _ = self._chat_resolve_interrupt(turn, agent_thread, interrupt_msg, response)
+ if pending:
+ self._pending_input.put(pending)
+ return None
# "failed"/"partial" with an empty final_response: no usable answer.
if turn.result and (turn.result.get("failed") or turn.result.get("partial")) and not response:
from hermes_cli.cli_chat_error_copy import chat_error_response
@@ -519,10 +535,13 @@ class CLIChatTurnMixin:
_api_calls = turn.result.get("api_calls", 0)
_max_iter = getattr(self.agent, "max_iterations", 500)
if _api_calls >= _max_iter:
- _cprint(
- f"\n{_DIM}⚠ Iteration budget reached ({_api_calls}/{_max_iter}) — "
- f"response may be incomplete{_RST}"
- )
+ from gateway.warning_notifications import render_notification
+ render_notification(
+ lambda: _cprint(
+ f"\n{_DIM}⚠ Iteration budget reached ({_api_calls}/{_max_iter}) — "
+ f"response may be incomplete{_RST}"
+ ),
+ platform="cli", user_config=getattr(self.agent, "_notification_config", None))
# Batch TTS unless streaming TTS already spoke the response.
if self._voice_tts and response and not turn.use_streaming_tts:
diff --git a/hermes_cli/cli_process_notifications.py b/hermes_cli/cli_process_notifications.py
index 0c16b4a2d4a..6f30310c565 100644
--- a/hermes_cli/cli_process_notifications.py
+++ b/hermes_cli/cli_process_notifications.py
@@ -40,6 +40,9 @@ class CLIProcessNotificationsMixin:
pending = ProcessNotificationBatch(notifications)
else:
pending = TimelineNotification.for_delegation(text, event) if event.get("type") == "async_delegation" else text
+ from agent.notification_presentation import diagnostic_process_event
+ if diagnostic_process_event(event) and not isinstance(pending, TimelineNotification):
+ pending = TimelineNotification(text, text, "internal_notification", "diagnostic")
self._pending_input.put(pending)
def _tui_unwrap_input(self, user_input):
diff --git a/hermes_cli/cli_stream_mixin.py b/hermes_cli/cli_stream_mixin.py
index 36f651acfbf..9bad5695e95 100644
--- a/hermes_cli/cli_stream_mixin.py
+++ b/hermes_cli/cli_stream_mixin.py
@@ -48,11 +48,17 @@ class CLIStreamMixin:
def _on_thinking(self, text: str) -> None:
"""Called by agent when thinking starts/stops. Updates TUI spinner."""
- if not text:
- self._flush_reasoning_preview(force=True)
- self._spinner_text = text or ""
- self._tool_start_time = 0.0 # clear tool timer when switching to thinking
- self._invalidate()
+ if getattr(getattr(self, "agent", None), "_mute_notification_reply", False):
+ return
+ from gateway.warning_notifications import DiagnosticText, render_notification
+ def show():
+ if not text:
+ self._flush_reasoning_preview(force=True)
+ self._spinner_text = text or ""
+ self._tool_start_time = 0.0 # clear tool timer when switching to thinking
+ self._invalidate()
+ render_notification(show, platform="cli", diagnostic=isinstance(text, DiagnosticText),
+ user_config=getattr(getattr(self, "agent", None), "_notification_config", None))
def _on_notice(self, notice) -> None:
"""Queue an out-of-band AgentNotice for rendering at the next clean boundary.
@@ -63,12 +69,18 @@ class CLIStreamMixin:
"""
try:
text = getattr(notice, "text", "") or ""
+ if getattr(getattr(self, "agent", None), "_mute_notification_reply", False):
+ return
if not text:
return
level = getattr(notice, "level", "info") or "info"
- if not hasattr(self, "_pending_credit_notices"):
- self._pending_credit_notices = []
- self._pending_credit_notices.append((level, text))
+ from gateway.warning_notifications import render_notification
+ def queue_notice():
+ if not hasattr(self, "_pending_credit_notices"):
+ self._pending_credit_notices = []
+ self._pending_credit_notices.append((level, text))
+ render_notification(queue_notice, platform="cli", diagnostic=level in {"warn", "error"},
+ user_config=getattr(getattr(self, "agent", None), "_notification_config", None))
except Exception:
pass
@@ -212,7 +224,9 @@ class CLIStreamMixin:
from cli import ChatConsole, _accent_hex
from tools.process_registry_notifications import TimelineNotification
if isinstance(user_input, TimelineNotification):
- ChatConsole().print(f"[dim]◈ {_escape(user_input.display_text)}[/dim]")
+ from gateway.warning_notifications import render_notification
+ render_notification(lambda: ChatConsole().print(f"[dim]◈ {_escape(user_input.display_text)}[/dim]"),
+ platform="cli", diagnostic=user_input.notification_category == "diagnostic")
return
ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")
text = str(user_input or "")
@@ -569,6 +583,7 @@ class CLIStreamMixin:
local path is included so the agent can re-examine via ``vision_analyze``."""
from cli import _DIM, _RST, _cprint
import asyncio as _asyncio
+ from gateway.warning_notifications import render_notification
from tools.vision_tools import vision_analyze_tool
analysis_prompt = (
"Describe everything visible in this image in thorough detail. "
@@ -599,14 +614,16 @@ class CLIStreamMixin:
f"You can try examining it with vision_analyze using "
f"image_url: {img_path}]")
if announce:
- _cprint(f" {_DIM}⚠ vision analysis failed — path included for retry{_RST}")
+ render_notification(lambda: _cprint(f" {_DIM}⚠ vision analysis failed — path included for retry{_RST}"),
+ platform="cli", user_config=getattr(getattr(self, "agent", None), "_notification_config", None))
except Exception as e:
enriched_parts.append(
f"[The user attached an image but analysis failed ({e}). "
f"You can try examining it with vision_analyze using "
f"image_url: {img_path}]")
if announce:
- _cprint(f" {_DIM}⚠ vision analysis error — path included for retry{_RST}")
+ render_notification(lambda: _cprint(f" {_DIM}⚠ vision analysis error — path included for retry{_RST}"),
+ platform="cli", user_config=getattr(getattr(self, "agent", None), "_notification_config", None))
# Vision descriptions first, then the user's original text
user_text = text if isinstance(text, str) and text else ""
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index ff127fdd0a7..1927ee07a17 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -855,6 +855,9 @@ DEFAULT_CONFIG = {
# Gateway: natural mid-turn assistant status messages. Desktop: keep mid-turn narration
# between tool calls instead of collapsing to the final message.
"interim_assistant_messages": True,
+ # Engine warning/failure notifications stay visible unless an operator opts in.
+ # Does not suppress task results, manual commands, or existing logs.
+ "suppress_warning_notifications": False,
# Codex Responses commentary channel: true delivers completed commentary as mid-turn interim
# updates; false routes it to reasoning (visible only with show_reasoning).
"show_commentary": True,
diff --git a/hermes_cli/quiet_single_query.py b/hermes_cli/quiet_single_query.py
index a228da6b014..736f671f8e5 100644
--- a/hermes_cli/quiet_single_query.py
+++ b/hermes_cli/quiet_single_query.py
@@ -31,6 +31,16 @@ def bind_quiet_session_key(session_id: str):
reset_current_session_key(token)
+def _diagnostic_only_wake_muted(events) -> bool:
+ """True when every drained event is an automatic diagnostic AND the CLI policy suppresses them."""
+ from agent.notification_presentation import diagnostic_process_event
+ from gateway.warning_notifications import warning_notifications_enabled
+
+ if not events or not all(diagnostic_process_event(e) for e in events if isinstance(e, dict)):
+ return False
+ return not warning_notifications_enabled("cli")
+
+
def quiet_notify_linger_seconds() -> float:
"""Total linger budget for one quiet run: the shared ``terminal.oneshot_completion_wait_seconds``.
@@ -86,7 +96,12 @@ def continue_quiet_notify_completions(
# async_delegation results. Keep everything that rendered.
texts = [text for _event, text in drained if text]
if texts:
- last = run_turn("\n\n".join(texts))
+ follow = run_turn("\n\n".join(texts))
+ # Same admission rule as the interactive CLI turn: a wake made ONLY of automatic
+ # diagnostics (early failure / watch notices) still runs, but under suppression its
+ # reply never displaces the requested one-shot answer on stdout.
+ if not _diagnostic_only_wake_muted([event for event, text in drained if text]):
+ last = follow
if wait.get("timed_out"):
break
if not texts:
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 29e5faa82d0..d19b819a6fb 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -314,7 +314,9 @@ class SessionMessagesMixin:
delegation_id = metadata.get("delegation_id")
if not delegation_id:
raise ValueError("Delegation delivery requires a stable delegation_id")
- msg = {"content": content, "display_kind": "async_delegation_complete", "display_metadata": metadata}
+ msg = {"content": content,
+ "display_kind": "hidden" if metadata.get("presentation_suppressed") else "async_delegation_complete",
+ "display_metadata": metadata}
params = self._message_row_params(session_id, "user", msg, None, time.time(), keep_reasoning=True)
def _do(conn):
@@ -324,7 +326,7 @@ class SessionMessagesMixin:
SELECT s.parent_session_id FROM sessions s JOIN lineage l ON s.id = l.id
JOIN sessions p ON p.id = s.parent_session_id WHERE p.end_reason = 'compression'
) SELECT m.id FROM messages m JOIN lineage l ON m.session_id = l.id
- WHERE m.display_kind = 'async_delegation_complete'
+ WHERE m.display_kind IN ('async_delegation_complete', 'hidden')
AND json_extract(m.display_metadata, '$.delegation_id') = ?
AND coalesce(json_extract(m.display_metadata, '$.delivery_notice'), '') = ? LIMIT 1""",
(session_id, delegation_id, metadata.get("delivery_notice", ""))).fetchone()
diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.py
index e2364aeea35..3147bb5a0cd 100644
--- a/plugins/memory/hindsight/__init__.py
+++ b/plugins/memory/hindsight/__init__.py
@@ -676,6 +676,9 @@ class HindsightMemoryProvider(MemoryProvider):
# Status channel for the retain indicator (recall reports via recall_status()).
if callable(kwargs.get("status_callback")):
self._status_callback = kwargs["status_callback"]
+ # Gated presentation for automatic startup warnings (agent._emit_warning on CLI).
+ self._warning_callback = kwargs.get("warning_callback") if callable(kwargs.get("warning_callback")) else None
+ self._platform = str(kwargs.get("platform") or "cli")
# session_id stays in tags so processes for one session remain filterable together.
self._document_id = _mint_document_id(self._session_id)
_maybe_upgrade_client()
@@ -810,11 +813,18 @@ class HindsightMemoryProvider(MemoryProvider):
"memory daemon. Run Hermes as a non-root user, or switch "
"to cloud / local_external mode via 'hermes memory setup'.")
logger.warning(msg)
- # Also print: otherwise the user would only see Hermes get sluggish.
+ # Surface to the terminal too — a daemon that never starts would otherwise fail silently and
+ # the user would only see Hermes get sluggish (issue #13125). This is an automatic
+ # startup diagnostic: it goes through the agent's gated warning sink when wired,
+ # otherwise through the shared render boundary; the log line above never does.
with contextlib.suppress(Exception):
- # Surface to the terminal too — a daemon that never starts would otherwise fail silently and
- # the user would only see Hermes get sluggish. (issue #13125)
- print(f" ⚠ {msg}", file=sys.stderr, flush=True)
+ cb = getattr(self, "_warning_callback", None)
+ if cb is not None:
+ cb(msg)
+ else:
+ from gateway.warning_notifications import render_notification
+ render_notification(lambda: print(f" ⚠ {msg}", file=sys.stderr, flush=True),
+ platform=getattr(self, "_platform", "cli"))
self._mode = "disabled"
return
spawn_context_thread(self._daemon_start_worker, name="hindsight-daemon-start").start()
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 3f1d24261e6..36cb224533f 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -2894,7 +2894,8 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
f"{dropped_chars} characters were not delivered; the full "
f"response is in the session logs."
)
- kept.append(notice)
+ if self.warning_text(notice):
+ kept.append(notice)
return kept
async def send(
@@ -4029,6 +4030,23 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
if not runner:
return
profile = getattr(self, "_owner_profile", None)
+ try:
+ if profile:
+ from gateway.run import _async_profile_runtime_scope
+ from hermes_cli.profiles import get_profile_dir
+ async with _async_profile_runtime_scope(get_profile_dir(profile)):
+ await self._deliver_unauthorized_slash_alert(
+ runner, profile, user_name, user_id, chan_id, guild_id, command_text, reason)
+ else:
+ await self._deliver_unauthorized_slash_alert(
+ runner, profile, user_name, user_id, chan_id, guild_id, command_text, reason)
+ except Exception as e:
+ logger.debug("[Discord] Admin notify: profile %r scope failed: %s", profile, e)
+
+ async def _deliver_unauthorized_slash_alert(
+ self, runner, profile, user_name, user_id, chan_id, guild_id, command_text, reason,
+ ) -> None:
+ # Discovery, policy, and transport must share the same owning profile scope.
try:
adapters, config = await self._alert_adapters_and_config(runner, profile)
except Exception as e:
@@ -4049,7 +4067,16 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
f"Command: {command_text}\n"
f"Reason: {reason}"
)
- result = await adapter.send(str(home.chat_id), msg)
+ # Policy is the DISCORD owner's (self) evaluated for the foreign target lane; a veto
+ # is not transport failure or permission to reroute to the next target.
+ from gateway.warning_notifications import present_notification
+ result = None
+ async def send_alert():
+ nonlocal result
+ result = await adapter.send(str(home.chat_id), msg)
+ if not await present_notification(send_alert, platform=target,
+ diagnostic=True):
+ return
# Only return on confirmed delivery.
if getattr(result, "success", None) is False:
logger.debug(
@@ -5884,8 +5911,10 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
# channel. Surface a short visible error so the user can retry once Discord
# recovers, and skip agent invocation for this message. See #20243.
await message.channel.send(
- "⚠️ Hermes could not create a Discord thread for "
- "this message, so the request was not processed. Please retry."
+ self.warning_text(
+ "⚠️ Hermes could not create a Discord thread for "
+ "this message, so the request was not processed. Please retry.",
+ "The request was not processed. Please retry.")
)
except Exception as notify_error:
logger.warning(
diff --git a/plugins/platforms/discord/adapter_media.py b/plugins/platforms/discord/adapter_media.py
index 21482aff5a3..6afa16630dc 100644
--- a/plugins/platforms/discord/adapter_media.py
+++ b/plugins/platforms/discord/adapter_media.py
@@ -39,7 +39,9 @@ class DiscordMediaMixin:
return max(limit, _DISCORD_DEFAULT_UPLOAD_LIMIT_BYTES)
return _DISCORD_DEFAULT_UPLOAD_LIMIT_BYTES
- async def _reject_oversized_upload(self, channel: Any, file_path: str, filename: str) -> Optional[SendResult]:
+ async def _reject_oversized_upload(
+ self, channel: Any, file_path: str, filename: str, *, caption: Optional[str] = None,
+ ) -> Optional[SendResult]:
"""Preflight ``file_path`` against the channel's upload cap (#50846): a doomed
``413`` round-trip is skipped and the user gets a notice naming the size and the
limit. Returns the failed result, or ``None`` when the file may be uploaded."""
@@ -59,8 +61,17 @@ class DiscordMediaMixin:
f"{limit_mb:.0f} MB upload limit for this channel. Compress the file or share a link instead."
)
try:
- if not self._is_forum_parent(channel):
- await channel.send(content=notice)
+ shown = self.warning_notifications_enabled()
+ if shown:
+ # Legacy: the notice is posted in-channel only (forum parents get no bare notice).
+ if not self._is_forum_parent(channel):
+ await channel.send(content=notice)
+ elif caption:
+ # Hidden: the requested caption still travels, on the channel's native shape.
+ if self._is_forum_parent(channel):
+ await self._send_to_forum(channel, caption)
+ else:
+ await channel.send(content=caption)
except Exception:
logger.debug("[%s] Failed to send oversized-file notice for %s", self.name, filename, exc_info=True)
return SendResult(success=False, error=error)
@@ -85,7 +96,7 @@ class DiscordMediaMixin:
if not channel:
return SendResult(success=False, error=f"Channel {chat_id} not found")
filename = file_name or os.path.basename(file_path)
- rejected = await self._reject_oversized_upload(channel, file_path, filename)
+ rejected = await self._reject_oversized_upload(channel, file_path, filename, caption=caption)
if rejected is not None:
return rejected
logger.info(
@@ -217,7 +228,13 @@ class DiscordMediaMixin:
if not files:
# Everything in this chunk was skipped. Still surface any
# oversized-file notices so the drop is not silent.
- if skip_notices and not self._is_forum_parent(channel):
+ shown = self.warning_notifications_enabled()
+ if not shown and captions:
+ if self._is_forum_parent(channel):
+ await self._send_to_forum(channel, captions[0])
+ else:
+ await channel.send(content=captions[0])
+ if skip_notices and shown and not self._is_forum_parent(channel):
try:
await channel.send(content="\n".join(skip_notices))
except Exception:
@@ -229,7 +246,7 @@ class DiscordMediaMixin:
# Use the first caption if any (Discord only has one message body for the group)
content = captions[0] if captions else None
if skip_notices:
- content = "\n".join(([content] if content else []) + skip_notices)
+ content = self.warning_text("\n".join(([content] if content else []) + skip_notices), content)
logger.info(
"[%s] Sending %d image(s) as single Discord message (chunk %d/%d)",
self.name, len(files), chunk_idx + 1, len(chunks),
@@ -272,7 +289,7 @@ class DiscordMediaMixin:
if not os.path.exists(audio_path):
return SendResult(success=False, error=f"Audio file not found: {audio_path}")
filename = os.path.basename(audio_path)
- rejected = await self._reject_oversized_upload(channel, audio_path, filename)
+ rejected = await self._reject_oversized_upload(channel, audio_path, filename, caption=caption)
if rejected is not None:
return rejected
reference = self._reply_reference_for_send(reply_to, channel)
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py
index 3d14cd64a8c..d5a1727a9d9 100644
--- a/plugins/platforms/feishu/adapter.py
+++ b/plugins/platforms/feishu/adapter.py
@@ -1855,7 +1855,8 @@ class FeishuAdapter(BasePlatformAdapter):
return await super().send_animation(
chat_id=chat_id, animation_url=animation_url, caption=caption, reply_to=reply_to, metadata=metadata,
)
- degraded_caption = f"[GIF downgraded to file]\n{caption}" if caption else "[GIF downgraded to file]"
+ degraded_caption = self.warning_text(
+ f"[GIF downgraded to file]\n{caption}" if caption else "[GIF downgraded to file]", caption)
return await self.send_document(
chat_id=chat_id, file_path=file_path, file_name=file_name, caption=degraded_caption,
reply_to=reply_to, metadata=metadata,
diff --git a/plugins/platforms/google_chat/adapter.py b/plugins/platforms/google_chat/adapter.py
index 30c34531166..99ca27c6047 100644
--- a/plugins/platforms/google_chat/adapter.py
+++ b/plugins/platforms/google_chat/adapter.py
@@ -1509,16 +1509,17 @@ class GoogleChatAdapter(BasePlatformAdapter):
thread_id: Optional[str]) -> SendResult:
"""Post the ``/setup-files`` notice (plus host path) when native delivery is
unavailable. Always returns ``success=False``."""
- lines = [caption] if caption else []
- lines.extend([
+ notice = "\n".join([
f"⚠️ No he podido adjuntar **{filename}**.",
"Google Chat sólo permite adjuntar archivos cuando el bot tiene permiso explícito tuyo (OAuth de usuario). "
"Es un consentimiento único que se hace desde este chat.",
"**Para activarlo:** envía `/setup-files` y sigue las instrucciones.",
f"Mientras tanto el archivo está en el host: `{path}`",
])
+ body = self.warning_text(f"{caption}\n{notice}" if caption else notice, caption or "")
try:
- await self._create_message(chat_id, _thread_body("\n".join(lines), thread_id))
+ if body:
+ await self._create_message(chat_id, _thread_body(body, thread_id))
except Exception:
logger.debug("[GoogleChat] attachment fallback notice send failed", exc_info=True)
return SendResult(
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 3917b788dc8..3a715ba2ab9 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -1496,7 +1496,7 @@ class MatrixAdapter(BasePlatformAdapter):
logger.warning("Matrix: failed to download image %s: %s", _redact_url_for_log(image_url), exc)
fallback = ("I couldn't download and upload the image to Matrix. "
"The source URL was not shown because it may contain private tokens.")
- return await self.send(chat_id, f"{caption}\n{fallback}" if caption else fallback, reply_to)
+ return await self.emit_media_warning(chat_id, fallback, caption=caption, reply_to=reply_to, metadata=metadata)
return await self._upload_and_send(chat_id, data, fname, ct, "m.image", caption, reply_to, metadata)
async def _download_external_media_with_cap(self, url: str) -> tuple[bytes, str, str]:
@@ -1809,7 +1809,7 @@ class MatrixAdapter(BasePlatformAdapter):
# file_path is host-local; never echo it into chat.
logger.warning("[%s] upload fallback: media file not found for %s", self.name, file_path)
text = "⚠️ Couldn't deliver the attachment."
- return await self.send(room_id, f"{caption}\n{text}" if caption else text, reply_to)
+ return await self.emit_media_warning(room_id, text, caption=caption, reply_to=reply_to, metadata=metadata)
try:
file_size = p.stat().st_size
except OSError:
diff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.py
index a4f68c16404..94f9822f145 100644
--- a/plugins/platforms/mattermost/adapter.py
+++ b/plugins/platforms/mattermost/adapter.py
@@ -185,8 +185,9 @@ class MattermostAdapter(BasePlatformAdapter):
or not self._last_post_failure_is_broken_thread_root()):
return data
flat_payload = {k: v for k, v in payload.items() if k != "root_id"}
- flat_payload["message"] = ("⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n"
- + str(flat_payload.get("message") or "")).strip()
+ body = str(flat_payload.get("message") or "")
+ flat_payload["message"] = self.warning_text(
+ ("⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n" + body).strip(), body)
logger.warning("Mattermost: falling back to flat channel delivery for notify-worthy post in %s", chat_id)
return await self._api_post("posts", flat_payload)
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py
index e98309bfd27..7349ef80e28 100644
--- a/plugins/platforms/slack/adapter.py
+++ b/plugins/platforms/slack/adapter.py
@@ -2165,10 +2165,12 @@ class SlackAdapter(BasePlatformAdapter):
if slash_ctx:
return await self._send_slash_reply(chat_id, slash_ctx, content, metadata)
# An active native stream that this content finalizes IS the final
- # message: seal it instead of posting a duplicate.
- stream_result = await self._try_finalize_stream(chat_id, content)
- if stream_result is not None:
- return stream_result
+ # message: seal it instead of posting a duplicate. Explicit interim sends
+ # (classified warnings beside the stream) never finalize, whatever their text.
+ if not (metadata or {}).get("_interim_send"):
+ stream_result = await self._try_finalize_stream(chat_id, content)
+ if stream_result is not None:
+ return stream_result
formatted = self.format_message(content)
if not formatted or not formatted.strip():
# Slack returns ``no_text`` for blank posts; still the end of a
@@ -3276,8 +3278,8 @@ class SlackAdapter(BasePlatformAdapter):
metadata: Optional[Dict[str, Any]]) -> SendResult:
"""Post ``notice`` (prefixed by the caption) in place of a failed media delivery; the
host-local path is never echoed into chat."""
- text = f"{caption}\n{notice}" if caption else notice
- return await self.send(chat_id, text, reply_to=reply_to, metadata=metadata)
+ return await self.emit_media_warning(chat_id, notice, caption=caption,
+ reply_to=reply_to, metadata=metadata, shown_metadata=metadata)
async def send_image(
self, chat_id: str, image_url: str, caption: Optional[str] = None,
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 937a4770302..ad9dca59ad2 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -5845,16 +5845,22 @@ class TelegramAdapter(BasePlatformAdapter):
attempted and failed — never a silent empty turn. No new event fields (the structured-event refactor
is out of scope per #23045).
"""
- named = f" ({display_name})" if display_name else ""
- try:
- await msg.reply_text(
+ # Inbound media fails before handle_message binds the routed profile.
+ with self._media_delivery_scope(event.source):
+ named = f" ({display_name})" if display_name else ""
+ notice = self.warning_text(
f"\u26a0\ufe0f Couldn't download your {kind}{named} ({exc.__class__.__name__}). Please try sending it again.")
- except Exception as reply_err:
- logger.warning("[Telegram] Failed to notify user about %s cache failure: %s", kind, reply_err, exc_info=True)
- event.text = self._append_observed_note(
- event.text,
- f"[The user attempted to send a {kind}{named} but it could not be downloaded ({exc.__class__.__name__}); they have been asked to retry.]",
- )
+ if notice:
+ try:
+ await msg.reply_text(notice)
+ except Exception as reply_err:
+ logger.warning("[Telegram] Failed to notify user about %s cache failure: %s", kind, reply_err, exc_info=True)
+ # The agent-visible note is execution evidence, not a channel diagnostic; it stays in both modes.
+ event.text = self._append_observed_note(
+ event.text,
+ f"[The user attempted to send a {kind}{named} but it could not be downloaded ({exc.__class__.__name__}); they have been asked to retry.]"
+ if notice else f"[The user attempted to send a {kind}{named} but it could not be downloaded.]",
+ )
def _observe_unmentioned_group_message(
self, message: Message, msg_type: MessageType, update_id: Optional[int] = None, event: Optional[MessageEvent] = None) -> None:
diff --git a/plugins/platforms/wecom/media.py b/plugins/platforms/wecom/media.py
index 09ae4cc4d55..6b457860a3a 100644
--- a/plugins/platforms/wecom/media.py
+++ b/plugins/platforms/wecom/media.py
@@ -300,7 +300,9 @@ class WeComMediaMixin:
logger.error("[%s] Failed to prepare outbound media %s: %s", self.name, media_source, exc)
return SendResult(success=False, error=str(exc))
if prepared["rejected"]:
- await self._send_followup_markdown(chat_id, f"⚠️ {prepared['reject_reason']}", reply_to=reply_to)
+ text = self.warning_text(f"⚠️ {prepared['reject_reason']}", caption or "")
+ if text:
+ await self._send_followup_markdown(chat_id, text, reply_to=reply_to)
return SendResult(success=False, error=prepared["reject_reason"])
reply_req_id = self._cached_reply_req_id(chat_id, reply_to)
# Active/expired stream owns the req_id (passive replyMedia is never acked): go proactive.
@@ -322,7 +324,8 @@ class WeComMediaMixin:
logger.error("[%s] Failed to send media %s: %s", self.name, media_source, exc)
return SendResult(success=False, error=str(exc))
raw: Dict[str, Any] = {"upload": upload_result, "media": media_response}
- for key, text in (("caption", caption), ("downgrade", f"ℹ️ {prepared['downgrade_note']}" if prepared["downgraded"] and prepared["downgrade_note"] else None)):
+ downgrade = self.warning_text(f"ℹ️ {prepared['downgrade_note']}") if prepared["downgraded"] and prepared["downgrade_note"] else None
+ for key, text in (("caption", caption), ("downgrade", downgrade or None)):
followup = await self._send_followup_markdown(chat_id, text, reply_to=reply_to) if text else None
raw[key] = followup.raw_response if followup else None
raw[f"{key}_error"] = followup.error if followup and not followup.success else None
diff --git a/tests/agent/test_grid_sweep_cli_tui_stream_diagnostics.py b/tests/agent/test_grid_sweep_cli_tui_stream_diagnostics.py
new file mode 100644
index 00000000000..2fb8a520cd1
--- /dev/null
+++ b/tests/agent/test_grid_sweep_cli_tui_stream_diagnostics.py
@@ -0,0 +1,278 @@
+"""Code-flow grid sweep (NOUS-368, wave 2): pre-existing automatic diagnostics on the CLI/TUI/stream
+rails that bypassed the warning boundary. Each cell: absent/false = legacy bytes, true = only the
+diagnostic disappears; source logs, model-facing bookkeeping and requested results are untouched."""
+from __future__ import annotations
+
+import json
+import types
+from unittest.mock import MagicMock
+
+import pytest
+
+MODES = (None, False, True)
+
+
+def _policy(tmp_path, monkeypatch, setting):
+ home = tmp_path / f"home-{setting}"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ display = {} if setting is None else {"suppress_warning_notifications": setting}
+ (home / "config.yaml").write_text(json.dumps({"display": display}))
+ return home
+
+
+def _visible(setting):
+ return setting is not True
+
+
+# --- agent/conversation_compression.py replay_compression_warning -> DiagnosticText ------------
+
+def test_compression_replay_is_classified_diagnostic():
+ from agent.conversation_compression import replay_compression_warning
+ from gateway.warning_notifications import DiagnosticText, is_warning_status
+ seen = []
+ agent = types.SimpleNamespace(_compression_warning="ℹ Codex caps context at 272K, so auto-compaction was raised",
+ status_callback=lambda kind, msg: seen.append((kind, msg)))
+ replay_compression_warning(agent)
+ assert len(seen) == 1 and seen[0][0] == "lifecycle"
+ assert isinstance(seen[0][1], DiagnosticText) and str(seen[0][1]) == agent._compression_warning
+ assert is_warning_status("lifecycle", seen[0][1])
+
+
[email protected]("setting", MODES)
+def test_compression_replay_reaches_gateway_status_sink_only_when_visible(tmp_path, monkeypatch, setting):
+ """Composed: replay -> the gateway status callback's own gate (render_notification + is_warning_status)."""
+ _policy(tmp_path, monkeypatch, setting)
+ from agent.conversation_compression import replay_compression_warning
+ from gateway.warning_notifications import is_warning_status, render_notification
+ rendered = []
+
+ def gateway_status_callback(kind, msg): # mirrors gateway/run_turn_runner._status_callback_sync
+ render_notification(lambda: rendered.append(str(msg)), platform="slack", diagnostic=is_warning_status(kind, msg))
+
+ agent = types.SimpleNamespace(_compression_warning="⚠️ Session compressed 3 times — accuracy may degrade",
+ status_callback=gateway_status_callback)
+ replay_compression_warning(agent)
+ assert (len(rendered) == 1) is _visible(setting)
+
+
+# --- agent/chat_completion_helpers.py stream-drop / stall deltas ----------------------------------
+
+def _stream_attempt_stub(enabled):
+ from agent import chat_completion_helpers as cch
+ fired = []
+ agent = MagicMock()
+ agent._warning_presentation_enabled = lambda: enabled
+ agent._fire_stream_delta = lambda text: fired.append(text)
+ return cch, agent, fired
+
+
[email protected]("enabled", (True, False))
+def test_stream_reconnect_marker_delta_honors_policy(enabled):
+ """The '⚠ Connection dropped mid tool-call; reconnecting…' delta is presentation only; the
+ tracking reset and retry bookkeeping run regardless."""
+ import inspect
+ from agent import chat_completion_helpers as cch
+ src = inspect.getsource(cch)
+ i = src.index("Connection dropped mid tool-call; reconnecting")
+ window = src[i - 400:i]
+ assert "_warning_presentation_enabled()" in window, "reconnect marker must be behind the presentation gate"
+ j = src.index("_reset_stream_delivery_tracking", i)
+ assert "if self.agent._warning_presentation_enabled()" not in src[i:j], "tracking reset must stay unconditional"
+
+
+def test_stream_stall_warning_kept_in_result_but_delta_gated():
+ import inspect
+ from agent import chat_completion_helpers as cch
+ src = inspect.getsource(cch)
+ i = src.index("Stream stalled mid tool-call")
+ seg = src[i:i + 700]
+ assert "_partial_text = (_partial_text or \"\") + _warn" in seg, "model/result bookkeeping stays"
+ assert "if self.agent._warning_presentation_enabled():" in seg
+ assert seg.index("_partial_text = (_partial_text or \"\") + _warn") < seg.index("if self.agent._warning_presentation_enabled():")
+ assert "logger.warning(" in seg
+
+
+# --- agent/agent_init.py invalid config int + autoraise notice ---------------------------------
+
[email protected]("setting", MODES)
+def test_invalid_config_int_print_honors_policy_log_always(tmp_path, monkeypatch, setting, capsys, caplog):
+ _policy(tmp_path, monkeypatch, setting)
+ import logging
+ from agent import agent_init
+ agent = types.SimpleNamespace(platform="cli", _notification_config=None)
+ with caplog.at_level(logging.WARNING):
+ agent_init._warn_invalid_config_int("model.context_length in config.yaml", "256K",
+ "must be a plain integer", "auto-detection", agent=agent)
+ err = capsys.readouterr().err
+ assert ("⚠ Invalid model.context_length" in err) is _visible(setting)
+ assert any("Invalid model.context_length" in rec.getMessage() for rec in caplog.records)
+
+
+def test_autoraise_notice_uses_diagnostic_safe_print():
+ import inspect
+ from agent import agent_init
+ src = inspect.getsource(agent_init)
+ i = src.index("if _autoraise_notice:\n agent._safe_print(_autoraise_notice, diagnostic=True)")
+ assert i > 0
+
+
+# --- agent/turn_tool_validation.py auto-repair notice ------------------------------------------
+
+def test_tool_name_repair_notice_is_diagnostic_vprint():
+ from agent import turn_tool_validation as ttv
+ printed = []
+ agent = MagicMock()
+ agent.log_prefix = ""
+ agent._repair_tool_call = lambda name: "read_file"
+ agent._vprint = lambda *a, **kw: printed.append((a, kw))
+ tc = types.SimpleNamespace(function=types.SimpleNamespace(name="reed_file", arguments="{}"))
+ # Only the repair loop is under test; call the module-level helper through the smallest surface.
+ import inspect
+ src = inspect.getsource(ttv)
+ assert "agent._vprint(f\"{agent.log_prefix}🔧 Auto-repaired tool name" in src
+ assert "force=True, diagnostic=True" in src[src.index("Auto-repaired tool name"):][:200]
+
+
+# --- CLI mixins -------------------------------------------------------------------------------
+
+def _cli_block(module, start_marker, end_marker, extra):
+ """Execute one guarded statement block from a CLI mixin with the module's real bound names
+ (``_cprint`` etc. come from ``cli`` at call time, so we bind them explicitly)."""
+ import inspect, textwrap
+ import cli as climod
+ src = inspect.getsource(module)
+ i = src.index(start_marker); j = src.index(end_marker, i)
+ i = src.rfind("\n", 0, i) + 1 # back up to the line start so dedent sees uniform indentation
+ j = src.rfind("\n", 0, j) + 1
+ block = textwrap.dedent(src[i:j])
+ ns = dict(module.__dict__); ns.update({"_cprint": climod._cprint, "_DIM": "", "_RST": ""}); ns.update(extra)
+ exec(compile(block, f"<{module.__name__}-block>", "exec"), ns)
+
+
[email protected]("setting", MODES)
+def test_cli_iteration_budget_notice_honors_policy(tmp_path, monkeypatch, setting):
+ _policy(tmp_path, monkeypatch, setting)
+ import cli as climod
+ from hermes_cli import cli_chat_turn_mixin as m
+ out = []
+ monkeypatch.setattr(climod, "_cprint", lambda s: out.append(s))
+ self = types.SimpleNamespace(agent=types.SimpleNamespace(max_iterations=3, _notification_config=None))
+ turn = types.SimpleNamespace(result={"completed": False, "interrupted": False, "api_calls": 3})
+ _cli_block(m, "if turn.result and not turn.result.get(\"completed\")", "# Batch TTS", {"turn": turn, "self": self})
+ assert (len(out) == 1 and "Iteration budget reached" in out[0]) is _visible(setting)
+
+
[email protected]("setting", MODES)
+def test_cli_provider_fallback_notice_honors_policy(tmp_path, monkeypatch, setting):
+ _policy(tmp_path, monkeypatch, setting)
+ import cli as climod
+ from hermes_cli import cli_agent_setup_mixin as m
+ out = []
+ monkeypatch.setattr(climod, "_cprint", lambda s: out.append(s))
+ _cli_block(m, "from gateway.warning_notifications import render_notification\n render_notification(\n lambda: _cprint(f\"⚠️ Primary auth failed",
+ "self.requested_provider = _fb_provider", {"_fb_provider": "p", "_fb_model": "m"})
+ assert (len(out) == 1 and "Primary auth failed" in out[0]) is _visible(setting)
+
+
[email protected]("setting", MODES)
+def test_cli_session_store_unavailable_banner_honors_policy(tmp_path, monkeypatch, setting, capsys):
+ _policy(tmp_path, monkeypatch, setting)
+ import cli as climod
+ from hermes_state_user_copy import describe_storage_failure, storage_failure_details
+ from rich.console import Console
+ _cli_block(climod, "failure = describe_storage_failure(e)", "_run_state_db_auto_maintenance(self._session_db)",
+ {"e": RuntimeError("disk I/O error"), "describe_storage_failure": describe_storage_failure,
+ "storage_failure_details": storage_failure_details, "Console": Console})
+ err = capsys.readouterr().err
+ assert ("Session store unavailable" in err) is _visible(setting)
+
+
[email protected]("setting", MODES)
+def test_cli_browser_downgrade_notice_honors_policy(tmp_path, monkeypatch, setting):
+ _policy(tmp_path, monkeypatch, setting)
+ import cli as climod
+ from tools import browser_use_cli
+ monkeypatch.setattr(browser_use_cli, "default_downgrade_notice", lambda: "Browser Use backend unavailable; using built-in tools")
+ out = []
+ self = types.SimpleNamespace(_console_print=lambda s: out.append(s))
+ fn = next(v for v in vars(climod.HermesCLI).values()
+ if callable(v) and "Once-per-24h hint when the default Browser Use backend" in (getattr(v, "__doc__", "") or ""))
+ fn(self)
+ assert (len(out) == 1 and "⚠" in out[0]) is _visible(setting)
+
+
+# --- TUI (functions are rebound onto tui_gateway.server by bind_module) -------------------------
+
[email protected]("setting", MODES)
+def test_tui_goal_compression_recovery_notice_honors_policy(tmp_path, monkeypatch, setting):
+ _policy(tmp_path, monkeypatch, setting)
+ from tui_gateway import server
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda ev, sid, payload: emitted.append((ev, payload)))
+ monkeypatch.setattr(server, "_plan_goal_compression_recovery",
+ lambda session, result, status, raw: ("retry prompt", "Context compression was exhausted. Retrying the active goal once."))
+ monkeypatch.setattr(server, "_is_successful_goal_turn", lambda *a: False)
+ session = {"agent": types.SimpleNamespace(_notification_config=None)}
+ followup = server._goal_followup_after_turn("sid", session, {"compression_exhausted": True}, "error", None)
+ assert followup == "retry prompt", "recovery itself is never suppressed"
+ assert (len(emitted) == 1) is _visible(setting)
+
+
[email protected]("setting", MODES)
+def test_tui_configured_model_adoption_failure_honors_policy(tmp_path, monkeypatch, setting):
+ _policy(tmp_path, monkeypatch, setting)
+ from tui_gateway import server, model_switch as ms
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda ev, sid, payload: emitted.append((ev, payload)))
+ import inspect, textwrap
+ src = inspect.getsource(ms)
+ i = src.index("except Exception as e:\n logger.warning(\"Configured model %s could not be adopted")
+ j = src.index("def _pending_switch_selection_warning", i)
+ block = "try:\n raise RuntimeError('boom')\n" + textwrap.dedent(src[i:j])
+ ns = dict(vars(server)); ns.update({"model": "gpt-x", "sid": "s1", "session": {"agent": types.SimpleNamespace(_notification_config=None)}})
+ exec(compile(block, "<adopt-block>", "exec"), ns)
+ assert (len(emitted) == 1 and emitted[0][0] == "error") is _visible(setting)
+
+
[email protected]("setting", MODES)
+def test_tui_preview_restart_status_warning_honors_policy(tmp_path, monkeypatch, setting):
+ """The preview-restart progress panel's status_callback: warning rows follow the TUI policy;
+ ordinary status rows and tool progress always render."""
+ _policy(tmp_path, monkeypatch, setting)
+ from tui_gateway import server
+ emitted = []
+ monkeypatch.setattr(server, "_emit", lambda ev, sid, payload: emitted.append(payload["text"]))
+ monkeypatch.setattr(server, "_session_get", lambda sid: {"agent": types.SimpleNamespace(_notification_config=None)}, raising=False)
+ from gateway.warning_notifications import DiagnosticText
+ cbs = server._preview_restart_callbacks("parent-1", "task-1")
+ cbs["status_callback"]("lifecycle", "Starting preview")
+ cbs["status_callback"]("warn", "⚠ provider fallback engaged")
+ cbs["status_callback"]("lifecycle", DiagnosticText("⚠ compression model unavailable"))
+ cbs["tool_gen_callback"]("terminal")
+ assert "Starting preview" in emitted and "Preparing terminal" in emitted
+ assert ("⚠ provider fallback engaged" in emitted) is _visible(setting)
+ assert ("⚠ compression model unavailable" in emitted) is _visible(setting)
+
+
[email protected]("setting", MODES)
[email protected]("failure", ("returns_error", "raises"))
+def test_cli_vision_fallback_notice_honors_policy(tmp_path, monkeypatch, setting, failure):
+ """Real call through _preprocess_images_with_vision: the model-facing retry text (with the path)
+ is always produced; only the console ⚠ notice follows policy."""
+ _policy(tmp_path, monkeypatch, setting)
+ import cli as climod
+ from unittest.mock import patch as _patch
+ out = []
+ monkeypatch.setattr(climod, "_cprint", lambda s: out.append(s))
+ img = tmp_path / "shot.png"; img.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 16)
+ if failure == "raises":
+ async def _vision(**kwargs): raise RuntimeError("API down")
+ else:
+ async def _vision(**kwargs): return json.dumps({"error": "vision unavailable"})
+ cli_obj = climod.HermesCLI.__new__(climod.HermesCLI)
+ cli_obj.agent = types.SimpleNamespace(_notification_config=None)
+ with _patch("tools.vision_tools.vision_analyze_tool", side_effect=_vision):
+ result = cli_obj._preprocess_images_with_vision("check this", [img])
+ assert str(img) in result and "check this" in result
+ assert (any("vision analysis" in s for s in out)) is _visible(setting)
diff --git a/tests/agent/test_notification_persistence.py b/tests/agent/test_notification_persistence.py
new file mode 100644
index 00000000000..c5b7434e900
--- /dev/null
+++ b/tests/agent/test_notification_persistence.py
@@ -0,0 +1,29 @@
+"""A muted wake keeps durable evidence while hiding only its new presentation rows."""
+from types import SimpleNamespace
+
+from agent.notification_presentation import notification_turn
+from agent.session_persistence import _db_flush_collect
+from hermes_state import SessionDB
+from tui_gateway.server import _history_to_messages
+
+
+def test_muted_wake_preserves_history_and_new_evidence(tmp_path):
+ old = {"role": "user", "content": "human request"}
+ diagnostic = {"role": "user", "content": "worker failed"}
+ reply = {"role": "assistant", "content": "model diagnostic echo"}
+ messages = [old, diagnostic, reply]
+ agent = SimpleNamespace(session_id="session", _last_flushed_db_idx=0)
+ with notification_turn(agent, muted=True):
+ rows, _ = _db_flush_collect(agent, messages, [old])
+ assert "display_kind" not in old
+ assert [row["content"] for row in rows] == ["worker failed", "model diagnostic echo"]
+ assert all(row["display_kind"] == "hidden" for row in rows)
+ with SessionDB(tmp_path / "state.db") as db:
+ db.create_session("session", source="tui")
+ db.append_messages_batch("session", rows)
+ stored = db.get_messages("session")
+ assert [row["content"] for row in stored] == ["worker failed", "model diagnostic echo"]
+ assert _history_to_messages(stored) == []
+ next_result = {"role": "assistant", "content": "requested result"}
+ rows, _ = _db_flush_collect(agent, [next_result], [])
+ assert rows[0]["display_kind"] is None
diff --git a/tests/agent/test_nous_rate_guard.py b/tests/agent/test_nous_rate_guard.py
index dfd78194698..38014c27375 100644
--- a/tests/agent/test_nous_rate_guard.py
+++ b/tests/agent/test_nous_rate_guard.py
@@ -286,6 +286,8 @@ class TestWelcomeRouteCopy:
_flush_status_buffer=lambda: None,
_persist_session=lambda *_args: None,
)
+ from agent.status_output import StatusOutputMixin
+ agent._buffer_diagnostic_status = StatusOutputMixin._buffer_diagnostic_status.__get__(agent)
verdict = nous_rate_limit_guard(
agent,
_retry=None,
diff --git a/tests/agent/test_overflow_overhead_aware_tokens.py b/tests/agent/test_overflow_overhead_aware_tokens.py
index cbcb0837637..436a7cfbcde 100644
--- a/tests/agent/test_overflow_overhead_aware_tokens.py
+++ b/tests/agent/test_overflow_overhead_aware_tokens.py
@@ -403,3 +403,36 @@ class TestLongContextTierOverheadAwareTokens:
"during long-context-tier recovery. All calls: "
+ str([c["tools"] for c in estimate_calls])
)
+
+
[email protected]("muted", [False, True])
+def test_long_context_retry_carrier_survives_failure_flush(agent, muted, monkeypatch):
+ from gateway.warning_notifications import DiagnosticText
+ agent._notification_config = {"display": {"suppress_warning_notifications": muted}}
+ err = TestLongContextTierOverheadAwareTokens._make_long_context_tier_error()
+ agent.client.chat.completions.create.side_effect = [err, _mock_response(content="Recovered")]
+ captured = []
+ original = agent._buffer_retry_message
+ def capture(kind, text):
+ captured.append((kind, text))
+ original(kind, text)
+ monkeypatch.setattr(agent, "_buffer_retry_message", capture)
+ with (patch("agent.model_metadata.estimate_request_tokens_rough", return_value=_SENTINEL_TOKENS),
+ patch.object(agent, "_compress_context", return_value=([{"role": "user", "content": "compressed"}], "compressed prompt")),
+ patch.object(agent, "_persist_session"), patch.object(agent, "_save_trajectory"),
+ patch.object(agent, "_cleanup_task_resources")):
+ result = agent.run_conversation("hello", conversation_history=_prefill())
+ assert result["final_response"] == "Recovered"
+ assert captured
+ assert any(kind == "status" for kind, _ in captured)
+ assert all(kind == "vprint" or isinstance(text, DiagnosticText) for kind, text in captured), captured
+ # Recovery clears buffered diagnostics; the same carriers must also work on
+ # the terminal-failure flush instead of leaking their retry sibling copy.
+ assert not agent._retry_status_buffer
+ agent._retry_status_buffer = list(captured)
+ printed, observed = [], []
+ agent._print_fn = lambda *a, **k: printed.append(a)
+ agent.status_callback = lambda *a: observed.append(a)
+ agent._flush_status_buffer()
+ assert bool(printed) is not muted
+ assert observed
diff --git a/tests/agent/test_recovery_diagnostic_producers.py b/tests/agent/test_recovery_diagnostic_producers.py
new file mode 100644
index 00000000000..f5e508ab566
--- /dev/null
+++ b/tests/agent/test_recovery_diagnostic_producers.py
@@ -0,0 +1,114 @@
+"""Real recovery producers retain work/evidence while hiding diagnostic copies."""
+import json
+from unittest.mock import patch
+
+import pytest
+from agent.status_output import StatusOutputMixin
+from agent.turn_overflow import _Recovery, _recover_payload_too_large
+from agent.turn_retry_state import TurnRetryState
+
+
+class Agent(StatusOutputMixin):
+ log_prefix = ""
+ platform = "cli"
+ suppress_status_output = False
+ _mute_post_response = False
+ _executing_tools = False
+ model = "fixture"
+ tools = []
+ max_iterations = 1
+
+ def __init__(self):
+ self.printed, self.observed, self.persisted = [], [], []
+ self._print_fn = lambda *a, **k: self.printed.append(" ".join(map(str, a)))
+ self.status_callback = lambda k, t: self.observed.append((k, t))
+
+ def _has_stream_consumers(self):
+ return False
+
+ def _compress_context(self, messages, *a, **k):
+ return self.compressed, "system"
+
+ def _persist_session(self, *args):
+ self.persisted.append(args)
+
+
[email protected](params=[None, False, True])
+def policy(request, tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ config = {} if request.param is None else {"display": {"suppress_warning_notifications": request.param}}
+ (tmp_path / "config.yaml").write_text(json.dumps(config))
+ return request.param is True
+
+
[email protected]("local", [False, True])
+def test_outer_loop_diagnostic_preserves_verdict_and_trace(policy, local, capsys, caplog):
+ from agent.turn_loop_errors import handle_outer_loop_error
+ import agent.conversation_loop as loop
+ agent = Agent()
+ # Traceback classification executes normally using a real frame filename.
+ with patch.object(loop, "_LOCAL_PROCESSING_MODULES", {"test_recovery_diagnostic_producers"} if local else set()):
+ try:
+ raise RuntimeError("raw engine diagnostic detail")
+ except RuntimeError as exc:
+ verdict = handle_outer_loop_error(agent, e=exc, _outer_error_count=0,
+ api_call_count=1, messages=[], conversation_history=[],
+ _turn_exit_reason=None, failed=False, final_response="")
+ output = capsys.readouterr().out + "\n".join(agent.printed)
+ assert ("raw engine diagnostic detail" in output) is not policy
+ assert verdict.action == "break"
+ assert bool(verdict.final_response)
+ assert verdict.failed is (not local)
+ assert "Outer loop error" in caplog.text
+ assert "raw engine diagnostic detail" in caplog.text
+
+
+def test_missing_requirements_keeps_tool_inventory(policy, monkeypatch, capsys):
+ from agent.agent_init import _load_tools
+ import model_tools
+ agent = Agent()
+ agent.quiet_mode = agent.save_trajectories = agent._use_prompt_caching = False
+ agent.ephemeral_system_prompt = None
+ monkeypatch.setattr("hermes_cli.plugins.discover_plugins", lambda: None)
+ monkeypatch.setattr(model_tools, "get_tool_definitions", lambda **kw: [{"function": {"name": "offline_tool"}}])
+ monkeypatch.setattr(model_tools, "check_toolset_requirements", lambda: {"fixture_dependency": False})
+ _load_tools(agent, None, None)
+ output = capsys.readouterr().out + "\n".join(agent.printed)
+ assert ("Some tools may not work due to missing requirements" in output) is not policy
+ assert "Loaded 1 tools" in output
+ assert agent.valid_tool_names == {"offline_tool"}
+
+
[email protected]("shape", ["message_count", "token_count", "payload_bytes"])
+def test_retry_buffer_classification_survives_terminal_flush(policy, shape, monkeypatch):
+ from gateway.warning_notifications import DiagnosticText
+ agent = Agent()
+ messages = [{"role": "user", "content": "a" * 4000}, {"role": "assistant", "content": "b" * 4000}]
+ agent.compressed = messages[:1] if shape == "message_count" else [
+ {"role": m["role"], "content": m["content"][:10]} for m in messages]
+ st = _Recovery(agent=agent, messages=messages, api_messages=messages,
+ system_message="system", active_system_prompt="system", conversation_history=[],
+ approx_tokens=2000, compression_attempts=0, effective_task_id="offline",
+ api_call_count=1, max_compression_attempts=3)
+ retry = TurnRetryState()
+ monkeypatch.setattr("agent.conversation_compression.conversation_history_after_compression", lambda a, m, h: h)
+ monkeypatch.setattr("agent.turn_overflow.time.sleep", lambda _: None)
+ if shape == "payload_bytes":
+ _recover_payload_too_large(st, retry)
+ assert retry.restart_with_compressed_messages
+ else:
+ _, shrank, _ = st.compress_scored_by_tokens(2000)
+ assert shrank
+ assert agent._retry_status_buffer
+ assert all(isinstance(text, DiagnosticText) for _, text in agent._retry_status_buffer)
+ outcome = st.fail_turn("Requested task failed.", notices=("diagnostic terminal detail",), log=("offline terminal failure",))
+ assert outcome.result["failed"] is True
+ assert outcome.result["final_response"] == "Requested task failed."
+ assert len(agent.persisted) == 1
+ assert not agent._retry_status_buffer
+ assert bool(agent.printed) is not policy
+ assert agent.observed # operator callback retained even when presentation hides
+ agent.printed.clear()
+ agent._emit_status("ordinary compaction progress")
+ assert agent.printed == ["ordinary compaction progress"]
diff --git a/tests/agent/test_turn_finalizer_cleanup_guard.py b/tests/agent/test_turn_finalizer_cleanup_guard.py
index 25a76a079f9..1e27f476b99 100644
--- a/tests/agent/test_turn_finalizer_cleanup_guard.py
+++ b/tests/agent/test_turn_finalizer_cleanup_guard.py
@@ -25,7 +25,10 @@ class _StubCompressor:
last_prompt_tokens = 0
-class _StubAgent:
+from agent.status_output import StatusOutputMixin
+
+
+class _StubAgent(StatusOutputMixin):
"""Minimal agent surface that ``finalize_turn`` reads from."""
def __init__(self, *, raise_in):
diff --git a/tests/agent/test_turn_recovery_retry_notice.py b/tests/agent/test_turn_recovery_retry_notice.py
index 3488e9908f1..0c298dfb23b 100644
--- a/tests/agent/test_turn_recovery_retry_notice.py
+++ b/tests/agent/test_turn_recovery_retry_notice.py
@@ -17,6 +17,9 @@ from agent.turn_recovery import compute_error_backoff
@pytest.mark.real_retry_backoff
def test_retry_backoff_names_the_wait_on_the_live_status_line():
agent = MagicMock()
+ from agent.status_output import StatusOutputMixin
+ for name in ("_emit_diagnostic_wait", "_buffer_diagnostic_status"):
+ setattr(agent, name, getattr(StatusOutputMixin, name).__get__(agent))
agent._client_log_context.return_value = ""
wait = compute_error_backoff(
diff --git a/tests/agent/test_warning_presentation.py b/tests/agent/test_warning_presentation.py
new file mode 100644
index 00000000000..a2c928023d5
--- /dev/null
+++ b/tests/agent/test_warning_presentation.py
@@ -0,0 +1,152 @@
+"""Notification policy changes presentation, not diagnostic state or task content."""
+from agent.status_output import StatusOutputMixin
+import pytest
+
+
+class Emitter(StatusOutputMixin):
+ log_prefix = ""
+ platform = "cli"
+ suppress_status_output = False
+ _mute_post_response = False
+ _executing_tools = False
+
+ def _has_stream_consumers(self):
+ return False
+
+
[email protected]("setting", [None, False, True, "typo", [], {}])
+def test_warning_policy_at_real_presentation_boundary(tmp_path, monkeypatch, setting):
+ import yaml
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ config = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump(config))
+ printed, callbacks = [], []
+ emitter = Emitter()
+ emitter._print_fn = lambda *args, **kwargs: printed.append(args)
+ emitter.status_callback = lambda *args: callbacks.append(args)
+ emitter._emit_warning("arbitrary diagnostic wording")
+ # Generic callbacks may write operator logs; only the concrete print sink is muted.
+ assert callbacks == [("warn", "arbitrary diagnostic wording")]
+ assert len(printed) == (0 if setting is True else 1)
+ emitter._emit_status("⚠ quoted error in ordinary progress")
+ assert callbacks[-1] == ("lifecycle", "⚠ quoted error in ordinary progress")
+ emitter._pending_fallback_notice = "unrecognized fallback wording"
+ emitter._emit_pending_fallback_notice()
+ assert emitter._pending_fallback_notice is None
+ assert len(callbacks) == 3
+
+
[email protected]("platform", ["cli", "tui", "api_server", "slack", "telegram"])
+def test_canonical_policy_has_no_raw_surface_exemption(platform):
+ from gateway.warning_notifications import warning_notifications_enabled
+ assert not warning_notifications_enabled(platform, {"display": {"suppress_warning_notifications": True}})
+ assert warning_notifications_enabled(platform, {"display": {"warning_notifications": False}})
+ assert warning_notifications_enabled(platform, {"display": {"suppress_warning_notifications": True, "platforms": {platform: {"suppress_warning_notifications": False}}}})
+
+
+def test_destination_snapshot_owns_policy_and_reader_failure_never_breaks_emission(monkeypatch):
+ from gateway import warning_notifications
+ emitter = Emitter()
+ emitted = []
+ emitter._print_fn = lambda *a, **k: None
+ emitter.status_callback = lambda *a: emitted.append(a)
+ emitter._notification_platform = "slack"
+ emitter._notification_config = {"display": {"suppress_warning_notifications": True,
+ "platforms": {"slack": {"suppress_warning_notifications": False}}}}
+ emitter._emit_warning("destination allows this diagnostic")
+ assert emitted == [("warn", "destination allows this diagnostic")]
+ def unavailable(*a, **k):
+ raise RuntimeError("configuration unavailable")
+ monkeypatch.setattr(warning_notifications, "warning_notifications_enabled", unavailable)
+ emitter._emit_warning("still observable when configuration fails")
+ assert emitted[-1] == ("warn", "still observable when configuration fails")
+
+
[email protected]("suppress", [False, True])
+def test_direct_print_diagnostics_preserve_content_and_muted_turn_has_no_prints(tmp_path, monkeypatch, suppress):
+ from agent.notification_presentation import notification_turn
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}")
+ agent = Emitter()
+ printed = []
+ agent._print_fn = lambda *a, **k: printed.append(a)
+ agent._safe_print("diagnostic", diagnostic=True)
+ agent._vprint("retry diagnostic", force=True, diagnostic=True)
+ assert len(printed) == (0 if suppress else 2)
+ agent._safe_print("requested error explanation")
+ assert printed[-1] == ("requested error explanation",)
+ with notification_turn(agent, muted=True):
+ agent._safe_print("model echo")
+ assert printed[-1] == ("requested error explanation",)
+
+
[email protected]("suppress", [None, False, True])
+def test_operator_callbacks_keep_diagnostics_and_logs(tmp_path, monkeypatch, caplog, suppress):
+ import logging
+ from types import SimpleNamespace
+ import yaml
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump(
+ {} if suppress is None else {"display": {"suppress_warning_notifications": suppress}}))
+ agent = Emitter()
+ agent._print_fn = lambda *a, **k: None
+ agent._touch_activity = lambda *a: None
+ seen = []
+ def record(*args):
+ seen.append(args)
+ logging.getLogger("operator").warning("observed %s", args)
+ agent.status_callback = agent.notice_callback = agent.thinking_callback = record
+ notice = SimpleNamespace(level="error", text="notice detail")
+ with caplog.at_level(logging.WARNING, logger="operator"):
+ agent._emit_warning("warning detail")
+ agent._emit_diagnostic_status("fallback detail")
+ agent._emit_notice(notice)
+ agent._emit_diagnostic_wait("retry detail")
+ assert seen == [("warn", "warning detail"), ("lifecycle", "fallback detail"),
+ (notice,), ("retry detail",)]
+ assert len([r for r in caplog.records if r.name == "operator"]) == 4
+ # Diagnostic-only wakes also leave operator observers installed.
+ from agent.notification_presentation import notification_turn
+ with notification_turn(agent, muted=True):
+ agent._emit_warning("wake diagnostic")
+ agent._emit_notice(notice)
+ agent._emit_diagnostic_wait("wake retry")
+ assert seen[-3:] == [("warn", "wake diagnostic"), (notice,), ("wake retry",)]
+
+
[email protected]("suppress", [None, False, True])
+def test_entitlement_guidance_is_classified_at_direct_print(tmp_path, monkeypatch, suppress):
+ import yaml
+ from agent import conversation_loop
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump(
+ {} if suppress is None else {"display": {"suppress_warning_notifications": suppress}}))
+ monkeypatch.setattr(conversation_loop, "_nous_entitlement_message", lambda capability: "entitlement detail\nnext step")
+ agent = Emitter()
+ printed = []
+ agent._print_fn = lambda *a, **k: printed.append(a)
+ assert conversation_loop._print_nous_entitlement_guidance(agent, "model access") is True
+ assert printed == ([] if suppress is True else [(" 💡 entitlement detail",), (" 💡 next step",)])
+
+
[email protected]("suppress", [None, False, True])
+def test_missing_key_banner_is_classified_without_hiding_initialization(tmp_path, monkeypatch, capsys, suppress):
+ from agent import agent_init
+ import yaml
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump(
+ {} if suppress is None else {"display": {"suppress_warning_notifications": suppress}}))
+ agent = Emitter()
+ agent.provider, agent.model, agent.base_url = "custom", "fixture", "http://localhost:1/v1"
+ agent.quiet_mode = False
+ client = object()
+ agent._create_openai_client = lambda *a, **k: client
+ monkeypatch.setattr(agent_init, "_explicit_client_kwargs",
+ lambda *a: {"api_key": "dummy-key", "base_url": agent.base_url})
+ monkeypatch.setattr(agent_init, "_apply_openai_header_policy", lambda *a: None)
+ monkeypatch.setattr("agent.ssl_guard.verify_ca_bundle", lambda: None)
+ agent_init._init_openai_client(agent, "dummy-key", agent.base_url, None, 30)
+ output = capsys.readouterr().out
+ assert ("API key appears invalid or missing" in output) is (suppress is not True)
+ assert "AI Agent initialized with model: fixture" in output
+ assert agent.client is client and agent.api_key == "dummy-key"
diff --git a/tests/agent/test_welcome_error_identity.py b/tests/agent/test_welcome_error_identity.py
index d247ce67bd2..447e284e985 100644
--- a/tests/agent/test_welcome_error_identity.py
+++ b/tests/agent/test_welcome_error_identity.py
@@ -21,6 +21,7 @@ def agent_for(api_key, base_url):
_summarize_api_error=lambda e: str(e), _emit_status=lambda *a, **kw: None,
_persist_session=lambda *a, **kw: None, _plines=lambda *a, **kw: None, _vprint=lambda *a, **kw: None,
_buffer_status=lambda *a, **kw: None, _buffer_vprint=lambda *a, **kw: None,
+ _emit_diagnostic_status=lambda *a, **kw: None, _buffer_diagnostic_status=lambda *a, **kw: None,
_try_activate_fallback=lambda: False,
)
diff --git a/tests/agent/test_welcome_tier_recovery.py b/tests/agent/test_welcome_tier_recovery.py
index 64124139b68..360a8d99241 100644
--- a/tests/agent/test_welcome_tier_recovery.py
+++ b/tests/agent/test_welcome_tier_recovery.py
@@ -78,7 +78,7 @@ def _agent(**overrides):
lines = []
agent = SimpleNamespace(
provider="nous", api_key=make_jwt(), model="gpt-5", base_url=WELCOME, log_prefix="", _rate_limit_state=None,
- _vprint=lambda text, force=False: lines.append(text),
+ _vprint=lambda text, force=False, diagnostic=False: lines.append(text),
_try_refresh_nous_client_credentials=lambda **kw: True,
)
for k, v in overrides.items():
@@ -206,6 +206,8 @@ class TestTerminalResultsCarryTheFreeTierBlock:
_summarize_api_error=lambda e: "HTTP 403: no permissions", _emit_status=lambda *a: None,
_persist_session=lambda *a: None, _plines=lambda *a: None, _buffer_status=lambda *a: None,
_rate_limit_state=None, _has_pending_fallback=lambda: False)
+ from agent.status_output import StatusOutputMixin
+ agent._emit_diagnostic_status = StatusOutputMixin._emit_diagnostic_status.__get__(agent)
return agent
def test_a_dark_tier_403_is_stamped_disabled_with_the_chat_sentence(self):
diff --git a/tests/cron/_r4_reconcile_child.py b/tests/cron/_r4_reconcile_child.py
new file mode 100644
index 00000000000..26b917e1ddf
--- /dev/null
+++ b/tests/cron/_r4_reconcile_child.py
@@ -0,0 +1,4 @@
+from cron.executions import reconcile_delivery_projections
+for _ in range(3):
+ reconcile_delivery_projections()
+print('reconciled')
diff --git a/tests/cron/_r4_restart.py b/tests/cron/_r4_restart.py
new file mode 100644
index 00000000000..516ef463a7f
--- /dev/null
+++ b/tests/cron/_r4_restart.py
@@ -0,0 +1,11 @@
+"""Fresh-process bookkeeping only; never sends."""
+import sys
+from cron import executions
+if int(sys.argv[1]):
+ original=executions._store_manifest
+ def failed(conn,eid,manifest):
+ if 'bot' in manifest:raise OSError('injected persistent SQLite manifest write failure after restart')
+ return original(conn,eid,manifest)
+ executions._store_manifest=failed
+for _ in range(int(sys.argv[2])):executions.reconcile_delivery_projections()
+print('RECONCILED')
diff --git a/tests/cron/_r5_nested_driver.py b/tests/cron/_r5_nested_driver.py
new file mode 100644
index 00000000000..eb7961b7f69
--- /dev/null
+++ b/tests/cron/_r5_nested_driver.py
@@ -0,0 +1,16 @@
+"""Called by actual outer job script; inner executes through manual-run API."""
+import json, os, sys
+from pathlib import Path
+REPO=str(next(p for p in Path(__file__).resolve().parents if (p/'cron'/'executions.py').exists()))
+sys.path.insert(0,REPO)
+os.environ['PYTHONPATH']=REPO
+from cron import jobs, executions
+assert Path(executions.__file__).is_relative_to(REPO), executions.__file__
+from tools.cronjob_tools import _execute_job_now
+home=Path(os.environ['HERMES_HOME'])
+inner=jobs.create_job(prompt=None,schedule='every 1h',script='fail.sh',no_agent=True,deliver='bot-chat')
+with executions._transaction() as conn:
+ conn.execute('''CREATE TRIGGER nested_reject_manifest BEFORE UPDATE OF delivery_manifest ON executions
+ WHEN NEW.delivery_manifest LIKE '%"bot"%' BEGIN SELECT RAISE(ABORT,'nested manifest fault'); END''')
+result=_execute_job_now(inner)
+(home/'inner-proof.json').write_text(json.dumps({'outer_env':os.environ.get('_HERMES_CRON_EXTERNAL_WORKER'),'inner':executions.latest_execution(inner['id']),'result':result}))
diff --git a/tests/cron/_r5_prior_executions.py b/tests/cron/_r5_prior_executions.py
new file mode 100644
index 00000000000..62e7f7f8f1f
--- /dev/null
+++ b/tests/cron/_r5_prior_executions.py
@@ -0,0 +1,598 @@
+"""Profile-local durable audit ledger for cron execution attempts.
+
+The ledger records what is known about each attempt; it is not a retry queue. Interrupted attempts
+become ``unknown`` only after their exact owner process is proved gone. Terminal states are
+immutable.
+"""
+
+from __future__ import annotations
+
+import os
+import json
+import logging
+import sqlite3
+import threading
+import time
+import uuid
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+from hermes_constants import get_hermes_home
+from hermes_time import now as _hermes_now
+
+# Optional test override. Production resolves the path at transaction time so dashboard operations
+# that temporarily enter another profile cannot leak that profile's records into the import-time
+# home.
+EXECUTIONS_FILE: Optional[Path] = None
+MAX_TERMINAL_EXECUTIONS = 1000
+HANDOFF_ADOPTION_GRACE_SECONDS = 30.0
+_TERMINAL_STATES = ("completed", "failed", "unknown")
+_lock = threading.RLock()
+_PROCESS_ID = uuid.uuid4().hex
+
+
+# --- executions ledger --------------------------------------------------------------------------
+
+def _connect() -> sqlite3.Connection:
+ # Late imports: a scheduler daemon that outlives an on-disk upgrade already has the OLD
+ # ``hermes_cli.sqlite_util`` / ``cron.jobs`` cached, so new names must be resolved at call time,
+ # not at import time (the guarantee cron/ledger.py used to carry, see e24c8499).
+ from cron.jobs import _ensure_cron_dir
+ from hermes_cli.sqlite_util import open_db
+
+ path = EXECUTIONS_FILE or (get_hermes_home().resolve() / "cron" / "executions.db")
+ _ensure_cron_dir(path.parent)
+ return open_db(path, db_label="cron/executions.db", synchronous_full=True, initialize=_initialize_schema)
+
+
+def _initialize_schema(conn: sqlite3.Connection) -> None:
+ from hermes_cli.sqlite_util import add_column_if_missing
+
+ conn.execute(
+ """CREATE TABLE IF NOT EXISTS executions (
+ id TEXT PRIMARY KEY,
+ job_id TEXT NOT NULL,
+ source TEXT NOT NULL,
+ process_id TEXT NOT NULL,
+ pid INTEGER NOT NULL,
+ process_started_at INTEGER,
+ status TEXT NOT NULL CHECK(status IN
+ ('claimed','running','completed','failed','unknown')),
+ handoff_pending INTEGER NOT NULL DEFAULT 0,
+ handoff_started_at REAL,
+ claimed_at TEXT NOT NULL,
+ started_at TEXT,
+ finished_at TEXT,
+ error TEXT
+ )"""
+ )
+ add_column_if_missing(
+ conn, "executions", "handoff_pending",
+ "handoff_pending INTEGER NOT NULL DEFAULT 0",
+ )
+ add_column_if_missing(
+ conn, "executions", "handoff_started_at", "handoff_started_at REAL"
+ )
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_executions_job_claimed "
+ "ON executions(job_id, claimed_at DESC, id DESC)"
+ )
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_executions_status_claimed "
+ "ON executions(status, claimed_at DESC, id DESC)"
+ )
+ add_column_if_missing(conn, "executions", "delivery_manifest", "delivery_manifest TEXT")
+ add_column_if_missing(conn, "executions", "incident_id", "incident_id TEXT")
+ add_column_if_missing(conn, "executions", "incident_generation", "incident_generation INTEGER")
+ add_column_if_missing(conn, "executions", "delivery_projection_settled", "delivery_projection_settled INTEGER NOT NULL DEFAULT 0")
+ add_column_if_missing(conn, "executions", "delivery_outcome", "delivery_outcome TEXT")
+ add_column_if_missing(conn, "executions", "scheduled_instant", "scheduled_instant TEXT")
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_executions_occurrence "
+ "ON executions(job_id, scheduled_instant) WHERE status='completed'"
+ )
+
+
+@contextmanager
+def _transaction() -> Iterator[sqlite3.Connection]:
+ from hermes_cli.sqlite_util import transaction
+
+ with _lock, transaction(_connect()) as conn:
+ yield conn
+
+
+def _fetch(conn: sqlite3.Connection, execution_id: str) -> Optional[Dict[str, Any]]:
+ row = conn.execute("SELECT * FROM executions WHERE id=?", (execution_id,)).fetchone()
+ return dict(row) if row is not None else None
+
+
+def _emit_execution_state(
+ record: Optional[Dict[str, Any]], *, delivery_outcome: Optional[str] = None
+) -> None:
+ """Project durable state to monitoring without affecting ledger behavior."""
+ try:
+ from agent.monitoring.cron_health import emit_execution_state
+
+ emit_execution_state(record, delivery_outcome=delivery_outcome)
+ except Exception:
+ pass
+
+
+def _process_start_time(pid: int) -> Optional[int]:
+ try:
+ from gateway.status import get_process_start_time
+ return get_process_start_time(pid)
+ except Exception:
+ return None
+
+
+def _owner_is_live(pid: int, started_at: Optional[int]) -> bool:
+ try:
+ from gateway.status import _pid_exists
+ if not _pid_exists(pid):
+ return False
+ except Exception:
+ return True # fail safe: inability to prove death must not rewrite state
+ if started_at is None:
+ return pid == os.getpid()
+ current = _process_start_time(pid)
+ return current is not None and current == started_at
+
+
+def _prune_unlocked(conn: sqlite3.Connection) -> None:
+ conn.execute(
+ """DELETE FROM executions WHERE id IN (
+ SELECT id FROM executions
+ WHERE status IN ('completed','failed','unknown')
+ AND (delivery_outcome IS NULL OR delivery_outcome != 'queued')
+ AND (delivery_manifest IS NULL OR delivery_projection_settled=1)
+ ORDER BY finished_at DESC, claimed_at DESC, id DESC LIMIT -1 OFFSET ?
+ )""",
+ (max(0, int(MAX_TERMINAL_EXECUTIONS)),),
+ )
+
+
+def create_execution(
+ job_id: str, *, source: str, scheduled_instant: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Persist a claimed attempt before executor/provider dispatch."""
+ from cron.occurrences import scheduled_instant as canonical_instant
+
+ now = _hermes_now().isoformat()
+ execution_id = uuid.uuid4().hex
+ pid = os.getpid()
+ with _transaction() as conn:
+ conn.execute(
+ """INSERT INTO executions
+ (id, job_id, source, process_id, pid, process_started_at,
+ status, claimed_at, scheduled_instant)
+ VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?, ?)""",
+ (execution_id, str(job_id), str(source), _PROCESS_ID, pid,
+ _process_start_time(pid), now, canonical_instant(scheduled_instant)),
+ )
+ record = _fetch(conn, execution_id)
+ _emit_execution_state(record)
+ return record # type: ignore[return-value]
+
+
+def set_execution_occurrence(execution_id: str, instant: Optional[str]) -> None:
+ """Bind the store-claimed snapshot before a provider hands it to a worker."""
+ from cron.occurrences import scheduled_instant
+
+ with _transaction() as conn:
+ cur = conn.execute(
+ "UPDATE executions SET scheduled_instant=? WHERE id=? AND status='claimed' "
+ "AND handoff_pending=0 AND process_id=? AND pid=?",
+ (scheduled_instant(instant), execution_id, _PROCESS_ID, os.getpid()),
+ )
+ if cur.rowcount != 1:
+ raise RuntimeError("Cron occurrence could not be bound before dispatch")
+
+
+def mark_execution_handoff_pending(execution_id: str) -> Optional[Dict[str, Any]]:
+ """Fence restart recovery while an external worker is adopting a claim."""
+ with _transaction() as conn:
+ cur = conn.execute(
+ """UPDATE executions
+ SET handoff_pending=1, handoff_started_at=?
+ WHERE id=? AND status='claimed'
+ AND process_id=? AND pid=?""",
+ (time.time(), execution_id, _PROCESS_ID, os.getpid()),
+ )
+ if cur.rowcount != 1:
+ return None
+ record = _fetch(conn, execution_id)
+ _emit_execution_state(record)
+ return record
+
+
+def adopt_claimed_execution(execution_id: str) -> Optional[Dict[str, Any]]:
+ """Atomically transfer and start an attempt in its worker process.
+
+ The dispatching gateway creates the row before spawning a restart-safe
+ worker. Adoption is the single ``claimed`` → ``running`` gate: only the
+ winner may acknowledge ownership or run side effects.
+ """
+ pid = os.getpid()
+ process_started_at = _process_start_time(pid)
+ now = _hermes_now().isoformat()
+ with _transaction() as conn:
+ cur = conn.execute(
+ """UPDATE executions
+ SET process_id=?, pid=?, process_started_at=?,
+ status='running', started_at=?, handoff_pending=0,
+ handoff_started_at=NULL
+ WHERE id=? AND status='claimed' AND handoff_pending=1""",
+ (_PROCESS_ID, pid, process_started_at, now, execution_id),
+ )
+ if cur.rowcount != 1:
+ return None
+ record = _fetch(conn, execution_id)
+ _emit_execution_state(record)
+ return record
+
+
+def mark_execution_running(execution_id: str) -> Optional[Dict[str, Any]]:
+ """Transition one claimed attempt to running exactly once."""
+ now = _hermes_now().isoformat()
+ with _transaction() as conn:
+ cur = conn.execute(
+ """UPDATE executions
+ SET status='running', started_at=?, handoff_pending=0,
+ handoff_started_at=NULL
+ WHERE id=? AND status='claimed' AND handoff_pending=0
+ AND process_id=? AND pid=?""",
+ (now, execution_id, _PROCESS_ID, os.getpid()),
+ )
+ if cur.rowcount != 1:
+ return None
+ record = _fetch(conn, execution_id)
+ _emit_execution_state(record)
+ return record
+
+
+def finish_execution(
+ execution_id: str, *, success: bool, error: Optional[str] = None,
+ delivery_outcome: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ """Write a terminal result once; terminal attempts cannot be rewritten."""
+ now = _hermes_now().isoformat()
+ status = "completed" if success else "failed"
+ detail = None if success else (str(error) if error else "unknown failure")
+ # A worker may observe a terminal receipt during its wait. Use the same durable
+ # classification as restart reconciliation, in particular unknown != failed.
+ with _transaction() as conn:
+ pending = _fetch(conn, execution_id)
+ if pending and pending.get("delivery_manifest"):
+ projection = _delivery_projection(pending)
+ if projection is not None:
+ delivery_outcome = projection[0]
+ cur = conn.execute(
+ """UPDATE executions
+ SET status=?, finished_at=?, error=?, handoff_pending=0,
+ handoff_started_at=NULL, delivery_outcome=?
+ WHERE id=? AND status IN ('claimed','running')
+ AND process_id=? AND pid=?""",
+ (status, now, detail, delivery_outcome, execution_id, _PROCESS_ID, os.getpid()),
+ )
+ if cur.rowcount != 1:
+ return None
+ _prune_unlocked(conn)
+ record = _fetch(conn, execution_id)
+ _emit_execution_state(record, delivery_outcome=delivery_outcome)
+ if record and record.get("delivery_manifest"):
+ reconcile_delivery_projections()
+ return record
+
+
+def bind_delivery_incident(execution_id: Optional[str], incident_id: str) -> None:
+ """Persist the producer's actual incident association, never infer it from errors."""
+ if execution_id:
+ with _transaction() as conn:
+ from cron.incidents import _initialize_schema as init_incidents
+ init_incidents(conn)
+ _bind_delivery_incident_unlocked(conn, execution_id, incident_id)
+
+
+def _bind_delivery_incident_unlocked(conn, execution_id: str, incident_id: str) -> None:
+ """Called in the producer's incident upsert transaction; no later generation lookup."""
+ conn.execute("UPDATE executions SET incident_id=?, incident_generation="
+ "(SELECT generation FROM cron_incidents WHERE id=?) "
+ "WHERE id=? AND incident_id IS NULL "
+ "AND status IN ('claimed','running') AND process_id=? AND pid=?",
+ (incident_id, incident_id, execution_id, _PROCESS_ID, os.getpid()))
+
+
+def record_delivery_manifest(execution_id: Optional[str], manifest: dict) -> None:
+ """Retain receipt identities and sibling disposition separately from the run result.
+
+ The worker may first bind the external handoff; its gateway replaces that placeholder
+ with the resolved target receipts. No payload or raw output is copied here.
+ """
+ if not execution_id:
+ return
+ with _transaction() as conn:
+ _store_manifest(conn, execution_id, manifest)
+
+
+def _store_manifest(conn, execution_id: str, manifest: dict) -> None:
+ """CAS the manifest onto a row that has none (or only the external placeholder)."""
+ placeholder = json.dumps({"external": True}, sort_keys=True)
+ row = _fetch(conn, execution_id)
+ if row and row.get("delivery_manifest") == placeholder:
+ manifest = {**manifest, "external": True}
+ conn.execute("UPDATE executions SET delivery_manifest=? WHERE id=? AND "
+ "(delivery_manifest IS NULL OR delivery_manifest=?)",
+ (json.dumps(manifest, sort_keys=True), execution_id, placeholder))
+
+
+def _journal_root() -> Path:
+ return (EXECUTIONS_FILE.parent if EXECUTIONS_FILE else get_hermes_home().resolve() / "cron") / "manifest_journal"
+
+
+def journal_manifest(execution_id: str, manifest: dict) -> None:
+ """Durably record a delivery manifest the ledger could not store (post-send fault).
+
+ Source-owned: independent of which receipt store (deferred file or live-owner mailbox)
+ holds the children, and never mutated by receipt consumers. Replayed by
+ :func:`_recover_unrecorded_manifests`; deleted only after the ledger holds it.
+ """
+ from utils import atomic_json_write
+ root = _journal_root()
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
+ atomic_json_write(root / f"{execution_id}.json", {"execution_id": execution_id, "manifest": manifest},
+ fsync_dir=True, mode=0o600)
+
+
+def journaled_manifests() -> Dict[str, dict]:
+ root = _journal_root()
+ if not root.is_dir():
+ return {}
+ out: Dict[str, dict] = {}
+ for path in root.glob("*.json"):
+ try:
+ record = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError, UnicodeDecodeError):
+ logging.getLogger(__name__).error("Unreadable cron manifest journal entry %s", path)
+ continue
+ if record.get("execution_id") and record.get("manifest"):
+ out[record["execution_id"]] = record["manifest"]
+ return out
+
+
+def _recover_unrecorded_manifests() -> Dict[str, dict]:
+ """Replay journaled manifests into the ledger; return what is STILL outstanding.
+
+ Idempotent through the same CAS as the primary write. An entry is removed only once
+ the ledger row actually carries a manifest with the children; while outstanding, the
+ row's placeholder manifest must not be projected or pruned (see callers).
+ """
+ outstanding: Dict[str, dict] = {}
+ for execution_id, manifest in journaled_manifests().items():
+ try:
+ with _transaction() as conn:
+ row = _fetch(conn, execution_id)
+ if row is None:
+ outstanding[execution_id] = manifest
+ continue
+ _store_manifest(conn, execution_id, manifest)
+ row = _fetch(conn, execution_id)
+ stored = json.loads(row["delivery_manifest"]) if row and row.get("delivery_manifest") else {}
+ if stored.get("bot") == manifest.get("bot"):
+ (_journal_root() / f"{execution_id}.json").unlink(missing_ok=True)
+ else:
+ outstanding[execution_id] = manifest
+ except Exception:
+ logging.getLogger(__name__).exception("Could not replay journaled cron manifest %s", execution_id)
+ outstanding[execution_id] = manifest
+ return outstanding
+
+
+def _delivery_projection(record: dict) -> Optional[tuple[str, dict]]:
+ from cron import delivery_queue, bot_chat_delivery
+ from tools.bot_live_delivery import read_delivery_result
+
+ manifest = json.loads(record["delivery_manifest"])
+ external_outcome = None
+ external_error = None
+ if manifest.get("external"):
+ receipt = delivery_queue.get_status(record["id"])
+ if not receipt or receipt["status"] in ("pending", "delivering"):
+ return None
+ outcome = receipt["status"]
+ external_outcome, external_error = outcome, receipt.get("error")
+ if not manifest.get("bot"):
+ return outcome, {"last_delivery_queued": None, "last_delivery_unverified": None,
+ "last_delivery_error": receipt.get("error")}
+
+ queued = {}
+ states = []
+ for target, ref in manifest.get("bot", {}).items():
+ receipt = read_delivery_result(Path(ref["home"]), ref["delivery_id"])
+ if receipt is None:
+ receipt = bot_chat_delivery.read_pending(ref["delivery_id"])
+ status = (receipt or ref)["status"]
+ if status in ("queued", "claimed", "transferred"):
+ queued[target] = {**ref, "status": status}
+ states.append(status)
+ error = manifest.get("error") or external_error
+ unverified = manifest.get("unverified")
+ if queued:
+ outcome = "queued"
+ elif external_outcome == "unknown" or "ambiguous" in states or "unknown" in states or unverified:
+ outcome = "unknown"
+ elif external_outcome == "failed" or "failed" in states or error:
+ outcome = "failed"
+ elif manifest.get("delivered") or "settled" in states:
+ outcome = "delivered"
+ else:
+ outcome = "suppressed"
+ if outcome in ("failed", "unknown") and not error:
+ error = "Deferred delivery completion unverified; do not resend"
+ return outcome, {"last_delivery_queued": queued or None,
+ "last_delivery_unverified": unverified or None,
+ "last_delivery_error": error}
+
+
+def reconcile_delivery_projections() -> None:
+ """Replay durable receipts, never sends. Safe after either store write or restart.
+
+ Only delivery_outcome can change after run completion. The queued CAS and manifest
+ comparison fence racing reconcilers; execution status/error/timestamps are untouched.
+ Retaining manifests also repairs a crash between the ledger and jobs/incident writes.
+ """
+ import logging
+ from cron.jobs import update_delivery_projection
+ from cron.incidents import _initialize_schema as init_incidents
+
+ try:
+ outstanding = _recover_unrecorded_manifests()
+ except Exception:
+ logging.getLogger(__name__).exception("Could not replay journaled cron delivery manifests")
+ outstanding = journaled_manifests()
+ with _transaction() as conn:
+ records = [dict(row) for row in conn.execute(
+ "SELECT * FROM executions WHERE delivery_manifest IS NOT NULL "
+ "AND status IN ('completed','failed','unknown')").fetchall()]
+ for record in records:
+ if record["id"] in outstanding:
+ # The ledger holds at most the external placeholder for this run while its real
+ # manifest (with pending children) is journaled: an incomplete manifest must not be
+ # projected as a terminal disposition. Stay queued until the replay succeeds.
+ continue
+ try:
+ projection = _delivery_projection(record)
+ if projection is None:
+ continue
+ outcome, values = projection
+ with _transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_outcome=? WHERE id=? "
+ "AND delivery_outcome='queued' AND delivery_manifest=?",
+ (outcome, record["id"], record["delivery_manifest"]))
+ current = _fetch(conn, record["id"])
+ if not current or current["delivery_outcome"] != outcome:
+ continue
+ if outcome == "delivered" and record.get("incident_id"):
+ init_incidents(conn)
+ # Late completion cannot resurrect resolved/acked incidents.
+ conn.execute("UPDATE cron_incidents SET state='alerted' WHERE id=? "
+ "AND state='detected' AND generation=?",
+ (record["incident_id"], record.get("incident_generation")))
+ update_delivery_projection(record["job_id"], record["id"], values)
+ if outcome != "queued":
+ # Pin the receipt association until BOTH durable projections have
+ # completed. A crash above leaves it replayable even under retention.
+ with _transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_projection_settled=1 "
+ "WHERE id=? AND delivery_outcome=? AND delivery_manifest=?",
+ (record["id"], outcome, record["delivery_manifest"]))
+ except Exception:
+ logging.getLogger(__name__).exception(
+ "Could not reconcile cron delivery %s; durable receipt retained", record["id"])
+
+
+def recover_interrupted_executions() -> int:
+ """Mark provably abandoned attempts unknown without scheduling retries."""
+ now = _hermes_now().isoformat()
+ changed = 0
+ recovered: List[Dict[str, Any]] = []
+ with _transaction() as conn:
+ rows = conn.execute(
+ """SELECT id, status, process_id, pid, process_started_at,
+ handoff_pending, handoff_started_at
+ FROM executions
+ WHERE status IN ('claimed','running')"""
+ ).fetchall()
+ for row in rows:
+ if row["process_id"] == _PROCESS_ID:
+ continue
+ if _owner_is_live(int(row["pid"]), row["process_started_at"]):
+ continue
+ handoff_started_at = row["handoff_started_at"]
+ if (
+ row["handoff_pending"]
+ and handoff_started_at is not None
+ and time.time() - float(handoff_started_at)
+ < HANDOFF_ADOPTION_GRACE_SECONDS
+ ):
+ continue
+ cur = conn.execute(
+ """UPDATE executions
+ SET status='unknown', finished_at=?, error=?,
+ handoff_pending=0, handoff_started_at=NULL
+ WHERE id=? AND status=? AND process_id=? AND pid=?
+ AND handoff_pending=?
+ AND handoff_started_at IS ?""",
+ (now,
+ "Scheduler restarted after this execution's owner exited before a durable "
+ "terminal state; whether side effects ran is unknown.",
+ row["id"], row["status"], row["process_id"], row["pid"],
+ row["handoff_pending"], row["handoff_started_at"]),
+ )
+ changed += cur.rowcount
+ if cur.rowcount:
+ record = _fetch(conn, row["id"])
+ if record is not None:
+ recovered.append(record)
+ if changed:
+ _prune_unlocked(conn)
+ for record in recovered:
+ _emit_execution_state(record)
+ return changed
+
+
+def list_executions(
+ *, job_id: Optional[str] = None, limit: int = 50, before_claimed_at: Optional[str] = None,
+) -> List[Dict[str, Any]]:
+ """Return indexed, newest-first execution history with cursor pagination."""
+ clauses: List[str] = []
+ params: List[Any] = []
+ if job_id is not None:
+ clauses.append("job_id=?")
+ params.append(str(job_id))
+ if before_claimed_at is not None:
+ clauses.append("claimed_at < ?")
+ params.append(str(before_claimed_at))
+ where = " WHERE " + " AND ".join(clauses) if clauses else ""
+ params.append(max(1, min(int(limit), 500)))
+ with _transaction() as conn:
+ rows = conn.execute(
+ "SELECT * FROM executions" + where
+ + " ORDER BY claimed_at DESC, id DESC LIMIT ?",
+ params,
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+
+def get_execution(execution_id: str) -> Optional[Dict[str, Any]]:
+ """Return one exact execution attempt, or ``None`` when it is absent."""
+ with _transaction() as conn:
+ row = conn.execute(
+ "SELECT * FROM executions WHERE id=?",
+ (str(execution_id),),
+ ).fetchone()
+ return dict(row) if row is not None else None
+
+
+def latest_execution(job_id: str) -> Optional[Dict[str, Any]]:
+ rows = list_executions(job_id=job_id, limit=1)
+ return rows[0] if rows else None
+
+
+def latest_executions(job_ids: List[str]) -> Dict[str, Dict[str, Any]]:
+ """Load latest execution for many jobs in one indexed query."""
+ clean = [str(job_id) for job_id in dict.fromkeys(job_ids) if job_id]
+ if not clean:
+ return {}
+ placeholders = ",".join("?" for _ in clean)
+ with _transaction() as conn:
+ rows = conn.execute(
+ f"""SELECT e.* FROM executions e
+ WHERE e.job_id IN ({placeholders})
+ AND e.id=(SELECT e2.id FROM executions e2
+ WHERE e2.job_id=e.job_id
+ ORDER BY e2.claimed_at DESC, e2.id DESC LIMIT 1)""",
+ clean,
+ ).fetchall()
+ return {row["job_id"]: dict(row) for row in rows}
diff --git a/tests/cron/_r7_exit_child.py b/tests/cron/_r7_exit_child.py
new file mode 100644
index 00000000000..b47aee7efe6
--- /dev/null
+++ b/tests/cron/_r7_exit_child.py
@@ -0,0 +1 @@
+"""Intentionally exit immediately for real dead-owner probes."""
diff --git a/tests/cron/_r7_initializer_worker.py b/tests/cron/_r7_initializer_worker.py
new file mode 100644
index 00000000000..502731b0a68
--- /dev/null
+++ b/tests/cron/_r7_initializer_worker.py
@@ -0,0 +1,25 @@
+"""Independent initializer process, synchronization only at inventory boundary."""
+import json, os, sys, time
+from pathlib import Path
+from cron import executions as ex
+home, barrier, name = map(Path, sys.argv[1:])
+ex.EXECUTIONS_FILE=home/'cron'/'executions.db'
+real_inventory=ex._journal_inventory_strict
+real_adopt=ex._try_adopt_legacy_intent
+trace=[]; entry=[]
+def inventory():
+ result=real_inventory()
+ (barrier/(str(name)+'.ready')).write_text('ready')
+ deadline=time.monotonic()+20
+ while not (barrier/'go').exists():
+ if time.monotonic()>deadline: raise TimeoutError('barrier')
+ time.sleep(.01)
+ return result
+def adopt(conn):
+ entry.append({'in_transaction':conn.in_transaction,'isolation_level':conn.isolation_level,'journal_mode':conn.execute('PRAGMA journal_mode').fetchone()[0]})
+ conn.set_trace_callback(trace.append)
+ return real_adopt(conn)
+ex._journal_inventory_strict=inventory
+ex._try_adopt_legacy_intent=adopt
+rows=ex.list_executions()
+print(json.dumps({'name':str(name),'entry':entry,'trace':trace,'pending':[r['delivery_manifest_pending'] for r in rows],'adopted':ex._legacy_intent_adopted()}))
diff --git a/tests/cron/_r7_old_writer.py b/tests/cron/_r7_old_writer.py
new file mode 100644
index 00000000000..5d2e75bc142
--- /dev/null
+++ b/tests/cron/_r7_old_writer.py
@@ -0,0 +1,19 @@
+"""Load exact R4 fixture before upgrade; publish only on parent signal."""
+import json, sys, time
+from pathlib import Path
+from tests.cron.test_r5_salt_legacy_and_races import prior, receipt
+from cron import delivery_queue as dq
+home=Path(sys.argv[1]);eid=sys.argv[2];barrier=Path(sys.argv[3])
+old=prior();old.EXECUTIONS_FILE=home/'cron'/'executions.db'
+dq.DELIVERY_DB=home/'cron'/'deliveries.db'
+assert old.get_execution(eid)['delivery_manifest']=='{"external": true}'
+assert dq.claim_next()['execution_id']==eid
+(barrier/'ready').write_text('loaded old module')
+deadline=time.monotonic()+20
+while not (barrier/'go').exists():
+ if time.monotonic()>deadline: raise TimeoutError('writer release')
+ time.sleep(.01)
+manifest=receipt(home,eid)
+old.journal_manifest(eid,manifest)
+assert dq._finish(eid,error=None)
+print(json.dumps({'manifest':manifest,'external':dq.get_status(eid)}))
diff --git a/tests/cron/_r7_restart_read.py b/tests/cron/_r7_restart_read.py
new file mode 100644
index 00000000000..0513cc9132a
--- /dev/null
+++ b/tests/cron/_r7_restart_read.py
@@ -0,0 +1,7 @@
+import json, sys
+from pathlib import Path
+from cron import executions as ex, delivery_queue as dq, jobs
+home=Path(sys.argv[1]);eid=sys.argv[2]
+ex.EXECUTIONS_FILE=home/'cron'/'executions.db';dq.DELIVERY_DB=home/'cron'/'deliveries.db'
+ex.reconcile_delivery_projections()
+print(json.dumps({'execution':ex.get_execution(eid),'job':jobs.get_job('child-job'),'journal':ex.journaled_manifests()}))
diff --git a/tests/cron/_r8_child.py b/tests/cron/_r8_child.py
new file mode 100644
index 00000000000..9aa1e5cb602
--- /dev/null
+++ b/tests/cron/_r8_child.py
@@ -0,0 +1,34 @@
+"""Evidence subprocess: real old journal writer / current replay / fresh read."""
+import json, os, sys, time
+from pathlib import Path
+from cron import executions as ex, delivery_queue as dq
+from tests.cron.test_r5_salt_legacy_and_races import prior, receipt, snap
+home=Path(sys.argv[2]); eid=sys.argv[3]
+ex.EXECUTIONS_FILE=home/'cron'/'executions.db'
+dq.DELIVERY_DB=home/'cron'/'deliveries.db'
+mode=sys.argv[1]
+if mode=='replay':
+ ex._recover_unrecorded_manifests()
+ print(json.dumps(snap(eid)))
+elif mode=='read':
+ ex.reconcile_delivery_projections()
+ print(json.dumps(snap(eid)))
+elif mode=='writer':
+ barrier=Path(sys.argv[4]); old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ assert old.get_execution(eid)
+ assert dq.claim_next()['execution_id']==eid
+ (barrier/'ready').write_text('old module loaded, external claimed')
+ deadline=time.monotonic()+25
+ while not (barrier/'publish').exists():
+ assert time.monotonic()<deadline
+ time.sleep(.005)
+ manifest=receipt(home,eid)
+ old.journal_manifest(eid,manifest)
+ assert (old._journal_root()/f'{eid}.json').is_file()
+ (barrier/'published').write_text(json.dumps(manifest))
+ while not (barrier/'complete').exists():
+ assert time.monotonic()<deadline
+ time.sleep(.005)
+ assert dq._finish(eid,error=None)
+ print(json.dumps({'manifest':manifest,'external':dq.get_status(eid)}))
+else: raise ValueError(mode)
diff --git a/tests/cron/test_bot_chat_pending.py b/tests/cron/test_bot_chat_pending.py
index 3f1aefca7ca..6c7b8c2e6e4 100644
--- a/tests/cron/test_bot_chat_pending.py
+++ b/tests/cron/test_bot_chat_pending.py
@@ -106,6 +106,50 @@ def test_pending_queue_uses_admission_order_and_keeps_claims(tmp_path, monkeypat
assert seen == ["older", "newer"]
+def test_policy_change_settles_diagnostic_without_waiting_for_cli_owner(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session(session_id="chat", source="cli")
+ db.set_session_title("chat", "Bot Chat")
+ lease, refusal = try_acquire_active_session(session_id="chat", surface="cli", config={}, registry_home=tmp_path)
+ assert refusal is None
+ run = Mock()
+ monkeypatch.setattr(delivery.subprocess, "run", run)
+ job = {"id": "failure", "execution_id": "run"}
+ try:
+ assert "queued" in delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True)
+ key = job["_bot_chat_delivery_receipts"]["bot-chat:(own)"]["delivery_id"]
+ assert queue.read_pending(key)["for_failure"] is True
+ with pytest.raises(ValueError, match="different payload"):
+ queue.defer(key, job, "diagnostic", "", tmp_path, for_failure=False)
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}")
+ queue.drain()
+ assert queue.read_pending(key)["status"] == "suppressed"
+ queue.drain()
+ run.assert_not_called()
+ finally:
+ lease.release()
+ db.close()
+
+
+def test_live_receipt_outcome_survives_later_suppression(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session(session_id="chat", source="tui")
+ db.set_session_title("chat", "Bot Chat")
+ lease, refusal = try_acquire_active_session(session_id="chat", surface="desktop", config={}, registry_home=tmp_path,
+ metadata={"bot_live_delivery_consumer": True, "live_session_id": "live"})
+ assert refusal is None
+ job = {"id": "failure", "execution_id": "run"}
+ try:
+ assert "queued" in delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True)
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}")
+ assert "queued" in delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True)
+ assert not job.get("_notification_all_targets_suppressed")
+ finally:
+ lease.release()
+ db.close()
+
@pytest.mark.skipif(not hasattr(__import__("os"), "geteuid") or __import__("os").geteuid() == 0,
reason="needs POSIX file permissions for an unreadable receipt")
def test_unreadable_deferred_receipt_does_not_block_siblings(tmp_path, monkeypatch, caplog):
diff --git a/tests/cron/test_bot_chat_warning_replay.py b/tests/cron/test_bot_chat_warning_replay.py
new file mode 100644
index 00000000000..f4805461a12
--- /dev/null
+++ b/tests/cron/test_bot_chat_warning_replay.py
@@ -0,0 +1,168 @@
+"""Warning policy cannot change the identity or outcome of a Bot Chat handoff."""
+import json
+from unittest.mock import Mock
+
+import pytest
+
+from cron import bot_chat_delivery as pending
+from cron import scheduler_delivery as delivery
+from hermes_cli.active_sessions import try_acquire_active_session
+from hermes_state import SessionDB
+from tools import bot_live_delivery as mailbox
+
+
+def owner(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session(session_id="chat", source="tui")
+ db.set_session_title("chat", "Bot Chat")
+ leases = []
+ run = Mock(side_effect=AssertionError("must not launch a second owner"))
+ monkeypatch.setattr(delivery.subprocess, "run", run)
+
+ def acquire(live):
+ lease, refusal = try_acquire_active_session(
+ session_id="chat", surface="desktop" if live else "cli", config={},
+ registry_home=tmp_path,
+ metadata={"bot_live_delivery_consumer": True, "live_session_id": "live"} if live else {},
+ )
+ assert refusal is None
+ leases.append(lease)
+ return lease
+
+ yield tmp_path, acquire, run
+ for lease in leases:
+ lease.release()
+ db.close()
+
+
+def policy(home, suppress):
+ (home / "config.yaml").write_text(
+ f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}\n"
+ )
+
+
+def receipt_key(job):
+ return job["_bot_chat_delivery_receipts"]["bot-chat:(own)"]["delivery_id"]
+
+
[email protected]("live", [False, True])
[email protected]("first_failure", [False, True])
[email protected]("suppress_retry", [False, True])
+def test_admitted_identity_rejects_category_changing_retry(owner, live, first_failure, suppress_retry):
+ home, acquire, run = owner
+ acquire(live)
+ job = {"id": "job", "execution_id": "run"}
+ assert "queued" in delivery._deliver_to_bot_chat(job, "same payload", "", for_failure=first_failure)
+ key = receipt_key(job)
+ before = mailbox.read_delivery_result(home, key) if live else pending.read_pending(key)
+ policy(home, suppress_retry)
+ result = delivery._deliver_to_bot_chat(job, "same payload", "", for_failure=not first_failure)
+ assert result and "different payload" in result
+ assert not job.get("_notification_all_targets_suppressed")
+ after = mailbox.read_delivery_result(home, key) if live else pending.read_pending(key)
+ assert after == before
+ run.assert_not_called()
+
+
[email protected]("status", ["queued", "claimed", "settled", "ambiguous"])
[email protected]("live", [False, True])
+def test_admitted_outcome_survives_suppressed_retry(owner, live, status):
+ home, acquire, run = owner
+ acquire(live)
+ job = {"id": "job", "execution_id": "run"}
+ assert "queued" in delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True)
+ key = receipt_key(job)
+ if live:
+ if status != "queued":
+ mailbox.claim_pending_delivery(home, mailbox.find_canonical_live_owner(home))
+ if status not in ("queued", "claimed"):
+ mailbox.complete_delivery(home, key, status=status, reply="retained result")
+ before = mailbox.read_delivery_result(home, key)
+ else:
+ path = home / "cron" / "bot_chat_pending" / f"{key}.json"
+ record = pending.read_pending(key)
+ record["status"] = status
+ path.write_text(json.dumps(record))
+ before = pending.read_pending(key)
+ policy(home, True)
+ result = delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True)
+ if not live and status == "queued":
+ assert result is None
+ assert pending.read_pending(key)["status"] == "suppressed"
+ assert job.get("_notification_all_targets_suppressed")
+ else:
+ assert result is None if status == "settled" else status in result
+ assert not job.get("_notification_all_targets_suppressed")
+ assert (mailbox.read_delivery_result(home, key) if live else pending.read_pending(key)) == before
+ run.assert_not_called()
+
+
[email protected]("live", [False, True])
+def test_suppressed_admission_is_durable_across_policy_changes(owner, live):
+ home, acquire, run = owner
+ acquire(live)
+ policy(home, True)
+ job = {"id": "job", "execution_id": "run"}
+ assert delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True) is None
+ assert job.get("_notification_all_targets_suppressed")
+ policy(home, False)
+ assert delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True) is None
+ assert job.get("_notification_all_targets_suppressed")
+ key = receipt_key(job)
+ assert pending.read_pending(key)["status"] == "suppressed"
+ assert pending.read_pending(key)["content"] == "diagnostic"
+ assert mailbox.read_delivery_result(home, key) is None
+ pending.drain()
+ run.assert_not_called()
+
+
[email protected]("owner_suppressed", [False, True])
+def test_named_bot_chat_uses_recipient_policy_not_launch_home(owner, monkeypatch, owner_suppressed):
+ home, acquire, run = owner
+ acquire(True)
+ launch = home / "launch"
+ launch.mkdir()
+ policy(home, owner_suppressed)
+ policy(launch, not owner_suppressed)
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setattr("hermes_cli.profiles.get_profile_dir", lambda name: home)
+ job = {"id": "job", "execution_id": "recipient-run"}
+ result = delivery._deliver_to_bot_chat(job, "diagnostic", "recipient", for_failure=True)
+ if owner_suppressed:
+ assert result is None and job.get("_notification_all_targets_suppressed")
+ else:
+ assert result and "queued" in result
+ key = job["_bot_chat_delivery_receipts"]["bot-chat:recipient"]["delivery_id"]
+ assert mailbox.read_delivery_result(home, key)["notification_category"] == "diagnostic"
+ assert mailbox.read_delivery_result(launch, key) is None
+ # Return to the launch home's own policy, proving recipient lookup did not leak.
+ own = {"id": "own", "execution_id": "own-run"}
+ if not owner_suppressed:
+ assert delivery._deliver_to_bot_chat(own, "diagnostic", "", for_failure=True) is None
+ assert own.get("_notification_all_targets_suppressed")
+ run.assert_not_called()
+
+
+def test_deferred_diagnostic_transfers_category_to_real_live_mailbox(owner):
+ home, acquire, run = owner
+ cli = acquire(False)
+ job = {"id": "job", "execution_id": "run"}
+ assert "queued" in delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True)
+ key = receipt_key(job)
+ cli.release()
+ acquire(True)
+ pending.drain()
+ assert pending.read_pending(key)["status"] == "transferred"
+ record = mailbox.claim_pending_delivery(home, mailbox.find_canonical_live_owner(home))
+ assert record["delivery_id"] == key
+ assert record["notification_category"] == "diagnostic"
+ assert "diagnostic" in record["message"]
+ mailbox.complete_delivery(home, key, status="settled", reply="handled")
+ policy(home, True)
+ assert delivery._deliver_to_bot_chat(job, "diagnostic", "", for_failure=True) is None
+ assert not job.get("_notification_all_targets_suppressed")
+ pending.drain()
+ assert mailbox.claim_pending_delivery(home, mailbox.find_canonical_live_owner(home)) is None
+ run.assert_not_called()
diff --git a/tests/cron/test_cron_failure_deliver.py b/tests/cron/test_cron_failure_deliver.py
index 3bbb9226c9c..da2dbbce57e 100644
--- a/tests/cron/test_cron_failure_deliver.py
+++ b/tests/cron/test_cron_failure_deliver.py
@@ -380,7 +380,7 @@ class TestOutcomeBookkeeping:
"""deliver=origin (unresolvable) + failure_deliver=explicit target:
the notice IS delivered — outcome must say so, not 'not_configured'."""
alerted = []
- monkeypatch.setattr(s, "_mark_incident_alerted", alerted.append)
+ monkeypatch.setattr(s, "_mark_incident_alerted", lambda incident_id, execution_id=None: alerted.append(incident_id))
monkeypatch.setattr(
s, "_upsert_incident_for_failure", lambda *_a, **_kw: (False, "inc-b1")
)
diff --git a/tests/cron/test_cron_live_bot_delivery.py b/tests/cron/test_cron_live_bot_delivery.py
index 70fbd6ccc78..4889a267c6a 100644
--- a/tests/cron/test_cron_live_bot_delivery.py
+++ b/tests/cron/test_cron_live_bot_delivery.py
@@ -42,7 +42,7 @@ def test_live_delivery_retry_keeps_receipt_across_owner_loss(tmp_path, monkeypat
def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):
- from cron import jobs
+ from cron import jobs, executions
from gateway import config
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -53,18 +53,23 @@ def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):
monkeypatch.setattr(delivery._sched, "load_config", lambda: {})
monkeypatch.setattr(config, "load_gateway_config", lambda: None)
monkeypatch.setattr(delivery.subprocess, "run", Mock(side_effect=AssertionError("CLI")))
- updates = []
- monkeypatch.setattr(jobs, "update_job", lambda key, values: updates.append(values))
- job = dict(id="digest", execution_id="run", deliver="bot-chat")
+ job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="bot-chat")
+ execution = executions.create_execution(job["id"], source="test")
+ job["execution_id"] = execution["id"]
+ jobs.bind_delivery_execution(job["id"], execution["id"])
error = delivery._deliver_result(job, "payload")
assert error is None
- queued = updates[-1]["last_delivery_queued"]
+ queued = jobs.get_job(job["id"])["last_delivery_queued"]
assert queued and next(iter(queued.values()))["status"] == "queued"
assert delivery._sched._classify_delivery_outcome(
delivery_error=error, delivery_queued=queued, should_deliver=True, unresolved_origin=False,
normalized_deliver="bot-chat", incident_acked=False, success=True) == "queued"
+ executions.finish_execution(execution["id"], success=True, delivery_outcome="queued")
record = mailbox.claim_pending_delivery(tmp_path, owner)
assert record is not None
mailbox.complete_delivery(tmp_path, record["delivery_id"], status="settled", reply="done")
+ from cron.bot_chat_delivery import drain
+ drain() # housekeeping, not another delivery attempt, refreshes the durable projection
+ assert jobs.get_job(job["id"])["last_delivery_queued"] is None
+ assert executions.get_execution(execution["id"])["delivery_outcome"] == "delivered"
assert delivery._deliver_result(job, "payload") is None
- assert updates[-1]["last_delivery_queued"] is None
diff --git a/tests/cron/test_deferred_warning_projection.py b/tests/cron/test_deferred_warning_projection.py
new file mode 100644
index 00000000000..93424637835
--- /dev/null
+++ b/tests/cron/test_deferred_warning_projection.py
@@ -0,0 +1,219 @@
+"""Queue admission is not delivery; late suppression updates exact projections."""
+import json
+
+import pytest
+from cron import executions, incidents, jobs, scheduler, delivery_queue
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+
+
[email protected]("setting", [None, False, True])
[email protected]("exit_code", [0, 7])
+def test_external_timeout_then_drain_reconciles_exact_failed_execution(tmp_path, monkeypatch, setting, exit_code):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ cfg = {"cron": {"wrap_response": False, "preflight": False}}
+ if setting is not None:
+ cfg["display"] = {"suppress_warning_notifications": setting}
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+ config = GatewayConfig()
+ config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)
+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
+ sent = []
+ async def send(platform, pconfig, chat_id, text, **kwargs):
+ sent.append(text)
+ return {"success": True, "message_id": "recorded-send"}
+ monkeypatch.setattr("tools.send_message_tool._send_to_platform", send)
+ scripts = tmp_path / "scripts"
+ scripts.mkdir()
+ (scripts / "failure.sh").write_text("#!/bin/sh\nprintf 'retained stdout\\n'\nprintf 'diagnostic stderr\\n' >&2\nexit 7\n")
+ script = scripts / "failure.sh"
+ script.write_text(script.read_text().replace("exit 7", f"exit {exit_code}"))
+ job = jobs.create_job(prompt=None, schedule="every 1h", script="failure.sh", no_agent=True, deliver="telegram:fixture")
+ execution = executions.create_execution(job["id"], source="test-external")
+ job["execution_id"] = execution["id"]
+ monkeypatch.setenv("_HERMES_CRON_EXTERNAL_WORKER", execution["id"])
+ wait = delivery_queue.enqueue_and_wait
+ monkeypatch.setattr(delivery_queue, "enqueue_and_wait",
+ lambda execution_id, job, content, for_failure=False: wait(execution_id, job, content, for_failure=for_failure, timeout=0))
+ scheduler.run_one_job(job)
+ before = executions.get_execution(execution["id"])
+ assert delivery_queue.get_status(execution["id"])["status"] == "pending"
+ assert not sent
+ assert before["status"] == ("failed" if exit_code else "completed")
+ assert before["delivery_outcome"] == "queued"
+ if exit_code:
+ incident = next(i for i in incidents.list_incidents() if i["job_id"] == job["id"])
+ assert incident["state"] == "detected"
+ assert scheduler.drain_delivery_queue({}, None) == 1
+ assert scheduler.drain_delivery_queue({}, None) == 0
+ after = executions.get_execution(execution["id"])
+ muted = setting is True and exit_code != 0
+ expected = "suppressed" if muted else "delivered"
+ assert delivery_queue.get_status(execution["id"])["status"] == expected
+ assert after["delivery_outcome"] == expected
+ assert after["status"] == before["status"]
+ assert after["error"] == before["error"]
+ assert len(sent) == (0 if muted else 1)
+ if exit_code:
+ incident = next(i for i in incidents.list_incidents() if i["job_id"] == job["id"])
+ assert incident["state"] == ("detected" if muted else "alerted")
+ outputs = list((tmp_path / "cron" / "output" / job["id"]).glob("*.md"))
+ assert outputs and "retained stdout" in outputs[0].read_text()
+ assert not jobs.get_job(job["id"]).get("last_delivery_queued")
+
+
+
[email protected]("sibling", ["none", "delivered", "ambiguous"])
+def test_bot_chat_late_suppression_reconciles_after_reopen(tmp_path, monkeypatch, sibling):
+ from cron import bot_chat_delivery
+ from hermes_state import SessionDB
+ from hermes_cli.active_sessions import try_acquire_active_session
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: false}\n")
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session(session_id="bot", source="cli")
+ db.set_session_title("bot", "Bot Chat")
+ lease, refusal = try_acquire_active_session(session_id="bot", surface="cli", config={}, registry_home=tmp_path)
+ assert refusal is None
+ try:
+ monkeypatch.setattr(scheduler, "run_job", lambda *a, **k: (False, "raw evidence", "", "failure evidence"))
+ job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="bot-chat")
+ scheduler.run_one_job(job)
+ before = executions.latest_execution(job["id"])
+ assert before["delivery_outcome"] == "queued"
+ key = next(iter(jobs.get_job(job["id"])["last_delivery_queued"].values()))["delivery_id"]
+ if sibling != "none":
+ # A sibling's durable disposition must survive this target's suppression.
+ with executions._transaction() as conn:
+ manifest = json.loads(conn.execute("SELECT delivery_manifest FROM executions WHERE id=?", (before["id"],)).fetchone()[0])
+ manifest["delivered"] = sibling == "delivered"
+ manifest["unverified"] = ["ambiguous sibling"] if sibling == "ambiguous" else []
+ conn.execute("UPDATE executions SET delivery_manifest=? WHERE id=?", (json.dumps(manifest), before["id"]))
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}\n")
+ bot_chat_delivery.drain()
+ bot_chat_delivery.drain()
+ assert bot_chat_delivery.read_pending(key)["status"] == "suppressed"
+ after = executions.get_execution(before["id"])
+ assert after["delivery_outcome"] == {"none": "suppressed", "delivered": "delivered", "ambiguous": "unknown"}[sibling]
+ assert after["error"] == before["error"]
+ assert after["finished_at"] == before["finished_at"]
+ assert not jobs.get_job(job["id"]).get("last_delivery_queued")
+ finally:
+ lease.release()
+ db.close()
+
+
+def _queued_execution(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="telegram:test")
+ execution = executions.create_execution(job["id"], source="test")
+ job["execution_id"] = execution["id"]
+ jobs.bind_delivery_execution(job["id"], execution["id"])
+ incident_id, _ = incidents.upsert_incident(job["id"], "raw failure")
+ executions.bind_delivery_incident(execution["id"], incident_id)
+ executions.record_delivery_manifest(execution["id"], {"external": True})
+ delivery_queue.enqueue(execution["id"], job, "diagnostic", for_failure=True)
+ jobs.update_delivery_projection(job["id"], execution["id"], {"last_delivery_queued": {"gateway": {"status": "queued"}}})
+ executions.finish_execution(execution["id"], success=False, error="raw failure", delivery_outcome="queued")
+ return job, execution, incident_id
+
+
[email protected]("terminal", ["delivered", "suppressed", "failed", "unknown"])
[email protected]("newer", [False, True])
+def test_restart_repairs_exact_execution_without_replay(tmp_path, monkeypatch, terminal, newer):
+ import os
+ import subprocess
+ import sys
+ job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
+ before = executions.get_execution(execution["id"])
+ if newer:
+ latest = executions.create_execution(job["id"], source="newer")
+ jobs.bind_delivery_execution(job["id"], latest["id"])
+ jobs.update_delivery_projection(job["id"], latest["id"], {
+ "last_delivery_queued": {"newer-target": {"status": "queued"}},
+ "last_delivery_unverified": ["newer-ambiguity"], "last_delivery_error": "newer-error"})
+ saved = jobs.get_job(job["id"])
+ # Kill-window simulation: persist terminal receipt, omit projection callback.
+ monkeypatch.setattr(executions, "reconcile_delivery_projections", lambda: None)
+ if terminal == "unknown":
+ delivery_queue.claim_next()
+ delivery_queue._terminalize_wait_timeout(execution["id"])
+ else:
+ def send(queued_job, *args):
+ queued_job["_notification_all_targets_suppressed"] = terminal == "suppressed"
+ return "wire failure" if terminal == "failed" else None
+ assert delivery_queue.drain(send) == 1
+ assert executions.get_execution(execution["id"])["delivery_outcome"] == "queued"
+ # All connections reopened in a fresh interpreter. A terminal receipt never sends.
+ code = "from cron.delivery_queue import drain; assert drain(lambda *a: (_ for _ in ()).throw(AssertionError('REPLAY'))) == 0"
+ subprocess.run([sys.executable, "-c", code], env=os.environ.copy(), check=True)
+ after = executions.get_execution(execution["id"])
+ assert after["delivery_outcome"] == terminal
+ assert {k: after[k] for k in ("status", "error", "finished_at")} == {k: before[k] for k in ("status", "error", "finished_at")}
+ assert incidents.get_incident(incident_id)["state"] == ("alerted" if terminal == "delivered" else "detected")
+ if newer:
+ assert jobs.get_job(job["id"]) == saved
+ else:
+ assert not jobs.get_job(job["id"])["last_delivery_queued"]
+
+
+def test_external_claimed_timeout_reports_unknown_immediately(tmp_path, monkeypatch):
+ from cron import scheduler_delivery
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(scheduler, "run_job", lambda *a, **k: (False, "raw", "", "failed script"))
+ job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="telegram:test")
+ execution = executions.create_execution(job["id"], source="test")
+ job["execution_id"] = execution["id"]
+ monkeypatch.setenv("_HERMES_CRON_EXTERNAL_WORKER", execution["id"])
+ wait = delivery_queue.enqueue_and_wait
+ def claim_then_wait(key, job, content, *, for_failure=False):
+ delivery_queue.enqueue(key, job, content, for_failure=for_failure)
+ assert delivery_queue.claim_next()
+ return wait(key, job, content, for_failure=for_failure, timeout=0)
+ monkeypatch.setattr(delivery_queue, "enqueue_and_wait", claim_then_wait)
+ scheduler.run_one_job(job)
+ assert delivery_queue.get_status(execution["id"])["status"] == "unknown"
+ assert executions.get_execution(execution["id"])["delivery_outcome"] == "unknown"
+
+
+def test_late_gateway_result_cannot_override_unknown_send(tmp_path, monkeypatch):
+ job, execution, _ = _queued_execution(tmp_path, monkeypatch)
+ assert delivery_queue.claim_next()
+ delivery_queue._terminalize_wait_timeout(execution["id"])
+ # The late sender finishes target bookkeeping after the worker fenced the claim.
+ executions.record_delivery_manifest(execution["id"], {"bot": {}, "delivered": True})
+ assert not delivery_queue._finish(execution["id"], error=None)
+ delivery_queue.drain(lambda *a: pytest.fail("must not replay"))
+ assert delivery_queue.get_status(execution["id"])["status"] == "unknown"
+ assert executions.get_execution(execution["id"])["delivery_outcome"] == "unknown"
+
+
+
+def test_direct_unverified_native_send_retains_legacy_outcome(tmp_path, monkeypatch):
+ import asyncio
+ from concurrent.futures import Future
+ from types import SimpleNamespace
+ from unittest.mock import MagicMock
+ from gateway.platforms.base import SendResult
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: false}")
+ monkeypatch.setattr(scheduler, "run_job", lambda *a, **k: (True, "raw", "requested result", None))
+ config = GatewayConfig()
+ config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)
+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
+ async def send(*args, **kwargs):
+ return SendResult(success=True)
+ router = SimpleNamespace(_deliver_to_platform=send)
+ monkeypatch.setattr("gateway.delivery.DeliveryRouter", lambda *a, **k: router)
+ def run_coro(coro, loop):
+ future = Future()
+ future.set_result(asyncio.run(coro))
+ return future
+ monkeypatch.setattr("asyncio.run_coroutine_threadsafe", run_coro)
+ job = jobs.create_job(prompt="fixture", schedule="every 1h", deliver="telegram:test")
+ loop = MagicMock()
+ loop.is_running.return_value = True
+ scheduler.run_one_job(job, adapters={Platform.TELEGRAM: MagicMock()}, loop=loop)
+ assert executions.latest_execution(job["id"])["delivery_outcome"] == "delivered"
+ assert jobs.get_job(job["id"])["last_delivery_unverified"]
diff --git a/tests/cron/test_delivery_incident_generation.py b/tests/cron/test_delivery_incident_generation.py
new file mode 100644
index 00000000000..02bc81988aa
--- /dev/null
+++ b/tests/cron/test_delivery_incident_generation.py
@@ -0,0 +1,68 @@
+"""A receipt belongs to one incident occurrence, not every reuse of its ID."""
+import pytest
+from cron import executions, incidents, delivery_queue
+from tests.cron.test_deferred_warning_projection import _queued_execution
+
+
[email protected]("finish_before_recovery", [False, True])
+def test_old_receipt_cannot_alert_reopened_incident(tmp_path, monkeypatch, finish_before_recovery):
+ job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
+ if finish_before_recovery:
+ delivery_queue.drain(lambda *a: None)
+ assert incidents.get_incident(incident_id)["state"] == "alerted"
+ assert incidents.close_incidents_for_recovered_job(job["id"]) == 1
+ reopened, is_new = incidents.upsert_incident(job["id"], "raw failure")
+ assert reopened == incident_id and is_new
+ if not finish_before_recovery:
+ delivery_queue.drain(lambda *a: None)
+ executions.reconcile_delivery_projections()
+ executions.reconcile_delivery_projections()
+ assert executions.get_execution(execution["id"])["delivery_outcome"] == "delivered"
+ assert incidents.get_incident(incident_id)["state"] == "detected"
+
+
+def test_receipt_for_current_reopened_occurrence_can_alert(tmp_path, monkeypatch):
+ job, old, incident_id = _queued_execution(tmp_path, monkeypatch)
+ incidents.close_incidents_for_recovered_job(job["id"])
+ incidents.upsert_incident(job["id"], "raw failure")
+ current = executions.create_execution(job["id"], source="new failure")
+ executions.bind_delivery_incident(current["id"], incident_id)
+ executions.record_delivery_manifest(current["id"], {"external": True})
+ delivery_queue.enqueue(current["id"], dict(job, execution_id=current["id"]), "diagnostic", for_failure=True)
+ executions.finish_execution(current["id"], success=False, error="raw failure", delivery_outcome="queued")
+ delivery_queue.drain(lambda *a: None)
+ assert incidents.get_incident(incident_id)["state"] == "alerted"
+
+
+def test_upgrade_does_not_invent_old_receipts_incident_generation(tmp_path, monkeypatch):
+ import sqlite3
+ job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
+ before = executions.get_execution(execution["id"])
+ # Exact pre-generation schema shape, with a pending receipt already persisted.
+ with sqlite3.connect(tmp_path / "cron" / "executions.db") as conn:
+ conn.execute("ALTER TABLE executions DROP COLUMN incident_generation")
+ conn.execute("DROP TRIGGER IF EXISTS cron_incident_recurrence_generation")
+ conn.execute("ALTER TABLE cron_incidents DROP COLUMN generation")
+ delivery_queue.drain(lambda *a: None)
+ after = executions.get_execution(execution["id"])
+ assert after["delivery_outcome"] == "delivered"
+ assert after["incident_generation"] is None
+ assert after["error"] == before["error"]
+ assert incidents.get_incident(incident_id)["state"] == "detected"
+ assert incidents.get_incident(incident_id)["generation"] == 1
+
+
+def test_concurrent_reconcilers_cannot_alert_reopened_occurrence(tmp_path, monkeypatch):
+ import os
+ import subprocess
+ import sys
+ job, execution, incident_id = _queued_execution(tmp_path, monkeypatch)
+ delivery_queue.drain(lambda *a: None)
+ incidents.close_incidents_for_recovered_job(job["id"])
+ incidents.upsert_incident(job["id"], "raw failure")
+ code = "from cron.executions import reconcile_delivery_projections; reconcile_delivery_projections()"
+ children = [subprocess.Popen([sys.executable, "-c", code], env=os.environ.copy()) for _ in range(4)]
+ for child in children:
+ assert child.wait(timeout=30) == 0
+ assert incidents.get_incident(incident_id)["state"] == "detected"
+ assert executions.get_execution(execution["id"])["delivery_outcome"] == "delivered"
diff --git a/tests/cron/test_incident_binding_atomicity.py b/tests/cron/test_incident_binding_atomicity.py
new file mode 100644
index 00000000000..e07f4b54c15
--- /dev/null
+++ b/tests/cron/test_incident_binding_atomicity.py
@@ -0,0 +1,64 @@
+"""An execution owns the occurrence created in its incident transaction."""
+import os
+import subprocess
+import sys
+
+import pytest
+
+from cron import executions, incidents, scheduler
+from tests.cron.test_mixed_delivery_retention import setup
+
+
+def test_reopen_after_upsert_return_cannot_rebind_old_execution(setup, monkeypatch):
+ home, cfg, run, sent = setup
+ original = incidents.upsert_incident
+ def interleave(*args, **kwargs):
+ result = original(*args, **kwargs)
+ iid = result[0]
+ script = home / "reopen.py"
+ script.write_text('from cron import incidents\nimport sys\ni=incidents.get_incident(sys.argv[1])\nassert incidents.close_incidents_for_recovered_job(i["job_id"])==1\nincidents.upsert_incident(i["job_id"],i["error"])\n')
+ subprocess.run([sys.executable, str(script), iid], env={**os.environ, "PYTHONPATH": os.getcwd()}, check=True, timeout=20)
+ return result
+ monkeypatch.setattr(incidents, "upsert_incident", interleave)
+ job, before = run(True, deliver="telegram:test")
+ assert before["incident_generation"] == 1
+ assert scheduler.drain_delivery_queue({}, None) == 1
+ incident = incidents.get_incident(before["incident_id"])
+ assert incident["generation"] == 2
+ assert incident["state"] == "detected"
+ assert len(sent) == 1
+
+
+def test_pre_generation_writer_cannot_reuse_occurrence(setup):
+ home, cfg, run, sent = setup
+ job, before = run(True, deliver="telegram:test")
+ assert scheduler.drain_delivery_queue({}, None) == 1
+ iid = before["incident_id"]
+ assert incidents.get_incident(iid)["state"] == "alerted"
+ incidents.close_incidents_for_recovered_job(job["id"])
+ # Exact old writer, not a replacement approximation of its SQL.
+ source = subprocess.check_output(['git', 'show', 'd738176e09d65a58252d5c4f2110e95f43570602:cron/incidents.py'], text=True)
+ (home / "old_incidents.py").write_text(source)
+ script = home / "old_writer.py"
+ script.write_text('import old_incidents as old\nimport sys\ni=old.get_incident(sys.argv[1])\nassert old.upsert_incident(i["job_id"],i["error"])[1]\n')
+ subprocess.run([sys.executable, str(script), iid], env={**os.environ, "PYTHONPATH": os.getcwd()}, check=True, timeout=20)
+ executions.reconcile_delivery_projections()
+ assert incidents.get_incident(iid)["generation"] == 2
+ assert incidents.get_incident(iid)["state"] == "detected"
+
+
+def test_incident_and_execution_bind_roll_back_together(setup, monkeypatch):
+ home, cfg, run, sent = setup
+ execution = executions.create_execution("bind-rollback", source="fixture")
+ def fail(*args):
+ raise OSError("fixture bind failure")
+ with monkeypatch.context() as scoped:
+ scoped.setattr(executions, "_bind_delivery_incident_unlocked", fail)
+ with pytest.raises(OSError, match="fixture bind failure"):
+ incidents.upsert_incident("bind-rollback", "fixture", execution_id=execution["id"])
+ assert not [i for i in incidents.list_incidents() if i["job_id"] == "bind-rollback"]
+ assert executions.get_execution(execution["id"])["incident_id"] is None
+ iid, new = incidents.upsert_incident("bind-rollback", "fixture", execution_id=execution["id"])
+ assert new
+ assert executions.get_execution(execution["id"])["incident_id"] == iid
+ assert executions.get_execution(execution["id"])["incident_generation"] == 1
diff --git a/tests/cron/test_incident_native_alert_generation.py b/tests/cron/test_incident_native_alert_generation.py
new file mode 100644
index 00000000000..46fcb386d28
--- /dev/null
+++ b/tests/cron/test_incident_native_alert_generation.py
@@ -0,0 +1,32 @@
+"""Salt R3 S4: an immediate native alert for occurrence N must not mark a reopened occurrence N+1."""
+import json
+import os
+import subprocess
+import sys
+from cron import incidents, executions
+from tests.cron.test_mixed_delivery_retention import setup
+
+
+def test_direct_native_old_output_does_not_alert_reopened_occurrence(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ original=incidents.upsert_incident
+ hits=[]
+ def after_commit(*args,**kw):
+ result=original(*args,**kw)
+ iid=result[0]
+ hits.append(iid)
+ subprocess.run([sys.executable,'-c', '''
+from cron import incidents
+import sys
+i=incidents.get_incident(sys.argv[1])
+assert incidents.close_incidents_for_recovered_job(i['job_id'])==1
+incidents.upsert_incident(i['job_id'],i['error'])
+''',iid],env={**os.environ,'PYTHONPATH':os.getcwd()},check=True,timeout=30)
+ return result
+ monkeypatch.setattr(incidents,'upsert_incident',after_commit)
+ job,execution=run(False,deliver='telegram:test')
+ assert len(hits)==1 and len(sent)==1
+ i=incidents.get_incident(execution['incident_id'])
+ assert execution['incident_generation']==1 and i['generation']==2
+ print('DIRECT_SIBLING',json.dumps({'execution':execution,'incident':i,'wire_count':len(sent)}))
+ assert i['state']=='detected'
diff --git a/tests/cron/test_late_legacy_intent_layers.py b/tests/cron/test_late_legacy_intent_layers.py
new file mode 100644
index 00000000000..4df5c921ebd
--- /dev/null
+++ b/tests/cron/test_late_legacy_intent_layers.py
@@ -0,0 +1,77 @@
+"""K2c layers isolated. Salt R7's late-writer schedules are recovered by any one of three layers
+(finish accounting, projection accounting, replay reopen); each cell here disables the others so
+a single missing layer fails."""
+import json, sqlite3
+from cron import executions as ex, jobs
+from tests.cron.test_r5_salt_legacy_and_races import store, prior, receipt, snap
+from tests.cron.test_r6_salt_migration_authority import legacy_running
+
+
+def _adopted_with_no_journal(store):
+ """Fence committed while the legacy row's journal did not exist yet (the K2c window)."""
+ eid, manifest = legacy_running(store)
+ (ex._journal_root() / f"{eid}.json").unlink()
+ assert ex.get_execution(eid)["delivery_manifest_pending"] == 0 and ex._legacy_intent_adopted()
+ old = prior(); old.EXECUTIONS_FILE = ex.EXECUTIONS_FILE
+ return eid, manifest, old
+
+
+def test_finish_accounts_for_late_journal_without_replay(store, monkeypatch):
+ eid, manifest, old = _adopted_with_no_journal(store)
+ old.journal_manifest(eid, manifest) # pre-flag writer publishes late
+ monkeypatch.setattr(ex, "_recover_unrecorded_manifests", lambda: {}) # no replay layer
+ finished = ex.finish_execution(eid, success=True, delivery_outcome="queued")
+ assert finished["delivery_outcome"] == "queued"
+ assert finished["delivery_manifest_pending"] == 1 # intent adopted in finish's transaction
+
+
+def test_projection_accounts_for_late_journal_without_replay(store, monkeypatch):
+ eid, manifest, old = _adopted_with_no_journal(store)
+ # Row is terminal-queued with only the placeholder: its external queue child is still
+ # pending when the OLD module finishes it (healthy legacy contract), then the old writer
+ # publishes the journal. The reconciler must not settle the placeholder as delivered.
+ from cron import delivery_queue as dq
+ with dq._transaction() as conn:
+ conn.execute("UPDATE deliveries SET status='pending', finished_at=NULL WHERE execution_id=?", (eid,))
+ with old._transaction() as conn:
+ conn.execute("UPDATE executions SET process_id=? WHERE id=?", (old._PROCESS_ID, eid))
+ assert old.finish_execution(eid, success=True, delivery_outcome="queued")["delivery_outcome"] == "queued"
+ old.journal_manifest(eid, manifest)
+ with dq._transaction() as conn:
+ conn.execute("UPDATE deliveries SET status='delivered', finished_at=? WHERE execution_id=?",
+ (dq._hermes_now().isoformat(), eid))
+ monkeypatch.setattr(ex, "_recover_unrecorded_manifests", lambda: {})
+ ex.reconcile_delivery_projections()
+ row = ex.get_execution(eid)
+ assert row["delivery_outcome"] == "queued", "placeholder settled as delivered although its journal exists"
+ assert row["delivery_projection_settled"] == 0
+
+
+def test_replay_reopens_row_terminalized_by_old_code(store):
+ """The OLD module (no accounting layers) finished the row as delivered from the placeholder,
+ then published its journal. Only the replay's reopen can correct the ledger."""
+ eid, manifest, old = _adopted_with_no_journal(store)
+ with old._transaction() as conn:
+ conn.execute("UPDATE executions SET process_id=? WHERE id=?", (old._PROCESS_ID, eid))
+ finished = old.finish_execution(eid, success=True, delivery_outcome="queued")
+ assert finished["delivery_outcome"] == "delivered" # the pre-flag defect, reproduced
+ old.journal_manifest(eid, manifest)
+ ex.reconcile_delivery_projections()
+ row = ex.get_execution(eid)
+ assert row["delivery_outcome"] == "queued"
+ assert '"bot"' in row["delivery_manifest"]
+ assert jobs.get_job("child-job")["last_delivery_queued"]
+
+
+def test_unknowable_journal_state_holds_after_adoption(store):
+ """Adoption complete, journal directory later unreadable: a placeholder-only row cannot be
+ proven journal-free, so it is held rather than terminalized."""
+ eid, manifest, old = _adopted_with_no_journal(store)
+ root = ex._journal_root(); mode = root.stat().st_mode & 0o777
+ root.chmod(0)
+ try:
+ finished = ex.finish_execution(eid, success=True, delivery_outcome="queued")
+ finally:
+ root.chmod(mode)
+ assert finished["delivery_outcome"] == "queued"
+ assert finished["delivery_manifest_pending"] == 0 # nothing adopted: state was unknown, not present
diff --git a/tests/cron/test_manifest_intent_fence.py b/tests/cron/test_manifest_intent_fence.py
new file mode 100644
index 00000000000..af7c3766b70
--- /dev/null
+++ b/tests/cron/test_manifest_intent_fence.py
@@ -0,0 +1,68 @@
+"""Salt R4 closure: the pre-send intent flag is the authoritative fence on every reader.
+
+Each cell here kills one specific mutant that the ported J1-J4 probes do not:
+pre-send mark when the journal is also unwritable; prune predicate; reconcile CAS re-check.
+"""
+import json, threading
+from cron import executions, scheduler, jobs, bot_chat_delivery
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r4_salt_journal_edges import reject_manifest, repaired, fast_gateway
+from tests.cron.test_r4_salt_recovery_probes import restart
+
+
+def test_presend_intent_alone_keeps_queued_when_ledger_and_journal_both_fault(setup, monkeypatch):
+ """Ledger rejects the manifest AND the journal is entirely unavailable (its re-assert of the
+ flag included): only the PRE-SEND flag can keep the run queued. Native sent once; no
+ transport failure reported."""
+ home, cfg, run, sent = setup
+ reject_manifest()
+ monkeypatch.setattr(executions, 'journal_manifest', lambda eid, manifest: False)
+ root = home / 'cron' / 'manifest_journal'; root.mkdir(); root.chmod(0o500)
+ try:
+ job, row = run(False)
+ finally:
+ root.chmod(0o700)
+ assert len(sent) == 1
+ assert row['delivery_outcome'] == 'queued'
+ assert row['delivery_manifest_pending'] == 1
+ assert jobs.get_job(job['id']).get('last_delivery_queued')
+ assert not jobs.get_job(job['id']).get('last_delivery_error')
+ # Retention pressure with nothing else protecting the row.
+ monkeypatch.setattr(executions, 'MAX_TERMINAL_EXECUTIONS', 0)
+ with executions._transaction() as conn:
+ executions._prune_unlocked(conn)
+ assert executions.get_execution(row['id']) is not None
+
+
+def test_prune_predicate_honours_pending_even_when_outcome_is_not_queued(setup, monkeypatch):
+ """Direct-DB corruption of the outcome must not make a pending row prunable."""
+ home, cfg, run, sent = setup
+ reject_manifest()
+ job, row = run(False)
+ with executions._transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_outcome='delivered' WHERE id=?", (row['id'],))
+ monkeypatch.setattr(executions, 'MAX_TERMINAL_EXECUTIONS', 0)
+ with executions._transaction() as conn:
+ executions._prune_unlocked(conn)
+ assert executions.get_execution(row['id']) is not None
+
+
+def test_reconcile_cas_rechecks_pending_at_write_time(setup, monkeypatch):
+ """A reconciler that loaded the row BEFORE the pending flag flipped must not settle it."""
+ home, cfg, run, sent = setup
+ fast_gateway(monkeypatch)
+ job, row = run(True) # healthy: external placeholder + real bot receipt, manifest recorded
+ assert row['delivery_outcome'] == 'queued'
+ # Stale reader: its projection was computed from a snapshot with pending=0 and returns
+ # 'delivered' unconditionally (no projection-time recheck); intent flips underneath it
+ # before the write. Only the CAS predicate can refuse the settle.
+ def stale(record):
+ with executions._transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_manifest_pending=1 WHERE id=?", (record['id'],))
+ return ('delivered', {'last_delivery_queued': None, 'last_delivery_unverified': None, 'last_delivery_error': None})
+ monkeypatch.setattr(executions, '_delivery_projection', stale)
+ executions.reconcile_delivery_projections()
+ after = executions.get_execution(row['id'])
+ assert after['delivery_outcome'] == 'queued'
+ assert after['delivery_projection_settled'] == 0
+ assert jobs.get_job(job['id']).get('last_delivery_queued')
diff --git a/tests/cron/test_manifest_intent_upgrade.py b/tests/cron/test_manifest_intent_upgrade.py
new file mode 100644
index 00000000000..4d9c734cce0
--- /dev/null
+++ b/tests/cron/test_manifest_intent_upgrade.py
@@ -0,0 +1,73 @@
+"""K2 mechanisms isolated: migration adoption and replay re-assert each carry cases the other cannot."""
+import json, sqlite3
+from pathlib import Path
+import pytest
+from cron import executions as ex, jobs, delivery_queue as dq, bot_chat_delivery as bot
+from tests.cron.test_r5_salt_legacy_and_races import store, seed, receipt, set_receipt, snap
+
+
+def _reject_bot_manifest(conn):
+ conn.execute("CREATE TRIGGER k2_reject BEFORE UPDATE OF delivery_manifest ON executions "
+ "WHEN instr(NEW.delivery_manifest, '\"bot\"')>0 BEGIN SELECT RAISE(ABORT,'k2 manifest fault'); END")
+
+
+def test_replay_reasserts_intent_on_already_migrated_row(store):
+ """Schema already has the column (pending=0 default) and a journal entry appears later
+ (e.g. copied from a backup, or a mark whose re-assert failed). Migration adoption cannot
+ run again; only the replay's own intent assertion fences the placeholder."""
+ eid = seed(store) # current schema: pending column exists, value 0
+ manifest = receipt(store, eid)
+ ex.journal_manifest(eid, manifest) # journal written; simulate the flag being lost
+ with ex._transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_manifest_pending=0 WHERE id=?", (eid,))
+ _reject_bot_manifest(conn)
+ ex.reconcile_delivery_projections()
+ state = snap(eid)
+ assert state['execution']['delivery_outcome'] == 'queued'
+ assert state['execution']['delivery_manifest_pending'] == 1
+ assert state['execution']['delivery_projection_settled'] == 0
+
+
+def test_migration_adopts_journal_before_any_reader_even_without_replay(store, monkeypatch):
+ """Old schema + outstanding journal. A reader that touches the row BEFORE any reconcile
+ (finish_execution of a late worker, or prune) must already see the intent: the migration
+ step, not the replay, is what fences it."""
+ from tests.cron.test_r5_salt_legacy_and_races import prior
+ old = prior(); eid = seed(store, old); manifest = receipt(store, eid)
+ old.journal_manifest(eid, manifest)
+ with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
+ assert 'delivery_manifest_pending' not in [r[1] for r in conn.execute('PRAGMA table_info(executions)')]
+ # Make replay a no-op so only migration adoption can fence the row.
+ monkeypatch.setattr(ex, '_recover_unrecorded_manifests', lambda: {})
+ with ex._transaction() as conn: # triggers schema init (migration) on the current module
+ pass
+ row = ex.get_execution(eid)
+ assert row['delivery_manifest_pending'] == 1
+ monkeypatch.setattr(ex, 'MAX_TERMINAL_EXECUTIONS', 0)
+ with ex._transaction() as conn:
+ ex._prune_unlocked(conn)
+ assert ex.get_execution(eid) is not None
+ ex.reconcile_delivery_projections()
+ assert ex.get_execution(eid)['delivery_outcome'] == 'queued'
+
+
+def test_finish_holds_placeholder_row_regardless_of_caller_outcome_while_adoption_incomplete(store, monkeypatch):
+ """K2a finish path isolated: the caller says 'failed' (its own classification) for a legacy
+ placeholder-only row while adoption is incomplete. finish must write queued, not trust the
+ caller — the projection fence alone cannot do this because a None projection keeps the
+ caller's value."""
+ from tests.cron.test_r6_salt_migration_authority import legacy_running
+ eid, manifest = legacy_running(store)
+ root = store / 'cron' / 'manifest_journal'
+ mode = root.stat().st_mode & 0o777
+ root.chmod(0)
+ try:
+ ex.get_execution(eid) # initialization: adoption fails, fence row absent
+ assert not ex._legacy_intent_adopted()
+ finished = ex.finish_execution(eid, success=False, error='worker failure', delivery_outcome='failed')
+ finally:
+ root.chmod(mode)
+ assert finished['delivery_outcome'] == 'queued'
+ ex.reconcile_delivery_projections()
+ after = ex.get_execution(eid)
+ assert after['delivery_outcome'] == 'queued' and '"bot"' in after['delivery_manifest']
diff --git a/tests/cron/test_manifest_recording_recovery.py b/tests/cron/test_manifest_recording_recovery.py
new file mode 100644
index 00000000000..e841cc7a88d
--- /dev/null
+++ b/tests/cron/test_manifest_recording_recovery.py
@@ -0,0 +1,42 @@
+"""A post-send ledger fault must never become transport failure or trigger resend."""
+import pytest
+from cron import executions, scheduler, delivery_queue, bot_chat_delivery, jobs
+from tests.cron.test_mixed_delivery_retention import setup
+
+
[email protected]("external", [False, True])
[email protected]("persistent_fault", [False, True])
+def test_manifest_fault_retains_child_and_real_send_outcome(setup, monkeypatch, external, persistent_fault):
+ home, cfg, run, sent = setup
+ original = executions.record_delivery_manifest
+ failures = []
+ def fail(eid, manifest):
+ if "bot" in manifest:
+ failures.append(eid)
+ raise OSError("fixture ledger recorder unavailable")
+ return original(eid, manifest)
+ monkeypatch.setattr(executions, "record_delivery_manifest", fail)
+ job, before = run(external)
+ if external:
+ scheduler.drain_delivery_queue({}, None)
+ assert delivery_queue.get_status(before["id"])["status"] == "delivered"
+ assert len(sent) == 1
+ assert failures
+ mid = executions.get_execution(before["id"])
+ assert mid["delivery_outcome"] == "queued"
+ assert jobs.get_job(job["id"])["last_delivery_queued"]
+ if not persistent_fault:
+ monkeypatch.setattr(executions, "record_delivery_manifest", original)
+ cfg(True)
+ bot_chat_delivery.drain()
+ executions.reconcile_delivery_projections()
+ after = executions.get_execution(before["id"])
+ assert after["delivery_outcome"] == "delivered"
+ assert after["error"] == before["error"]
+ assert after["finished_at"] == before["finished_at"]
+ assert not jobs.get_job(job["id"])["last_delivery_queued"]
+ assert len(sent) == 1
+ monkeypatch.setattr(executions, "record_delivery_manifest", original)
+ executions.reconcile_delivery_projections()
+ executions.reconcile_delivery_projections()
+ assert len(sent) == 1
diff --git a/tests/cron/test_mixed_delivery_retention.py b/tests/cron/test_mixed_delivery_retention.py
new file mode 100644
index 00000000000..bc7dd266b16
--- /dev/null
+++ b/tests/cron/test_mixed_delivery_retention.py
@@ -0,0 +1,107 @@
+"""Independent product-path falsification; vendor edges only are fake."""
+import json
+from pathlib import Path
+import pytest
+from cron import executions, incidents, jobs, scheduler, delivery_queue, bot_chat_delivery
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from hermes_state import SessionDB
+from hermes_cli.active_sessions import try_acquire_active_session
+
+def setup(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME',str(tmp_path))
+ monkeypatch.setenv('HERMES_MANAGED_DIR',str(tmp_path/'managed'))
+ def cfg(muted=False):
+ (tmp_path/'config.yaml').write_text(json.dumps({'cron':{'wrap_response':False,'preflight':False},'display':{'suppress_warning_notifications':muted}}))
+ cfg()
+ config=GatewayConfig(); config.platforms[Platform.TELEGRAM]=PlatformConfig(enabled=True)
+ monkeypatch.setattr('gateway.config.load_gateway_config',lambda:config)
+ (tmp_path/'scripts').mkdir()
+ (tmp_path/'scripts'/'fail.sh').write_text("#!/bin/sh\nprintf 'preserved shell stdout\\n'\nprintf 'preserved stderr\\n' >&2\nexit 7\n")
+ db=SessionDB(db_path=tmp_path/'state.db'); db.create_session(session_id='bot',source='cli'); db.set_session_title('bot','Bot Chat')
+ lease, refusal=try_acquire_active_session(session_id='bot',surface='cli',config={},registry_home=tmp_path)
+ assert refusal is None
+ sent=[]
+ async def send(platform,pconfig,chat_id,text,**kwargs):
+ sent.append(text)
+ return {'success':True,'message_id':'recorded'}
+ monkeypatch.setattr('tools.send_message_tool._send_to_platform',send)
+ def run(external=False, deliver='bot-chat,telegram:test'):
+ job=jobs.create_job(prompt=None,schedule='every 1h',script='fail.sh',no_agent=True,deliver=deliver)
+ if external:
+ ex=executions.create_execution(job['id'],source='test-external'); job['execution_id']=ex['id']
+ monkeypatch.setenv('_HERMES_CRON_EXTERNAL_WORKER',ex['id'])
+ wait=delivery_queue.enqueue_and_wait
+ monkeypatch.setattr(delivery_queue,'enqueue_and_wait',lambda eid,j,c,for_failure=False: wait(eid,j,c,for_failure=for_failure,timeout=0))
+ scheduler.run_one_job(job)
+ return job, executions.latest_execution(job['id'])
+ yield tmp_path,cfg,run,sent
+ lease.release(); db.close()
+
[email protected]('external',[False,True])
[email protected]('native_fails',[False,True])
+def test_real_mixed_router_preserves_pending_and_terminal(setup,monkeypatch,external,native_fails):
+ home,cfg,run,sent=setup
+ if native_fails:
+ async def fail(*a,**k): return {'success':False,'error':'native rejected'}
+ monkeypatch.setattr('tools.send_message_tool._send_to_platform',fail)
+ job,before=run(external)
+ if external:
+ assert before['delivery_outcome']=='queued'
+ assert scheduler.drain_delivery_queue({},None)==1
+ middle=executions.get_execution(before['id']); saved=jobs.get_job(job['id'])
+ print('MIXED',external,native_fails,'MID',json.dumps({'execution':middle,'queued':saved.get('last_delivery_queued')},default=str))
+ # The bot has NOT been attempted; native failure must not erase its pending state.
+ assert middle['delivery_outcome']=='queued'
+ assert saved.get('last_delivery_queued')
+ cfg(True); bot_chat_delivery.drain(); bot_chat_delivery.drain()
+ after=executions.get_execution(before['id'])
+ assert after['delivery_outcome']==('failed' if native_fails else 'delivered')
+ assert after['error']==before['error'] and after['finished_at']==before['finished_at']
+ assert not jobs.get_job(job['id']).get('last_delivery_queued')
+
+
+def test_execution_retention_does_not_erase_pending_projection(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ job,before=run(True,deliver='telegram:test')
+ # Use the production retention implementation with a small deterministic limit.
+ monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',1)
+ newer=executions.create_execution('unrelated-job',source='retention-pressure')
+ executions.finish_execution(newer['id'],success=True,delivery_outcome='not_configured')
+ print('PRUNE',before['id'],executions.get_execution(before['id']))
+ cfg(True); scheduler.drain_delivery_queue({},None)
+ assert delivery_queue.get_status(before['id'])['status']=='suppressed'
+ print('PRUNE JOB',json.dumps(jobs.get_job(job['id']),default=str))
+ assert not jobs.get_job(job['id']).get('last_delivery_queued')
+
+
[email protected]("drop_settlement_column", [False, True])
+def test_projection_write_failure_pins_receipt_until_replay_then_prunes(setup, monkeypatch, drop_settlement_column):
+ import sqlite3
+ home, cfg, run, sent = setup
+ job, before = run(True, deliver="telegram:test")
+ if drop_settlement_column:
+ with sqlite3.connect(home / "cron" / "executions.db") as conn:
+ conn.execute("ALTER TABLE executions DROP COLUMN delivery_projection_settled")
+ original = jobs.update_delivery_projection
+ def fail(*args, **kwargs):
+ raise OSError("fixture jobs projection write failure")
+ monkeypatch.setattr(jobs, "update_delivery_projection", fail)
+ cfg(True)
+ scheduler.drain_delivery_queue({}, None)
+ assert executions.get_execution(before["id"])["delivery_outcome"] == "suppressed"
+ assert not executions.get_execution(before["id"])["delivery_projection_settled"]
+ monkeypatch.setattr(executions, "MAX_TERMINAL_EXECUTIONS", 0)
+ with executions._transaction() as conn:
+ executions._prune_unlocked(conn)
+ assert executions.get_execution(before["id"]) is not None
+ assert jobs.get_job(job["id"])["last_delivery_queued"]
+ monkeypatch.setattr(jobs, "update_delivery_projection", original)
+ executions.reconcile_delivery_projections()
+ assert not jobs.get_job(job["id"])["last_delivery_queued"]
+ assert executions.get_execution(before["id"])["delivery_projection_settled"]
+ with executions._transaction() as conn:
+ executions._prune_unlocked(conn)
+ assert executions.get_execution(before["id"]) is None
+ assert not sent # never retry delivery to repair bookkeeping
+
diff --git a/tests/cron/test_r4_salt_composed_probes.py b/tests/cron/test_r4_salt_composed_probes.py
new file mode 100644
index 00000000000..9fcfefd0f0e
--- /dev/null
+++ b/tests/cron/test_r4_salt_composed_probes.py
@@ -0,0 +1,81 @@
+"""Salt R3 composed R4 probes (B2/B3), ported as regression cells."""
+import json, threading
+import pytest
+from cron import executions, scheduler, bot_chat_delivery, jobs
+from tools import bot_live_delivery as mailbox
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r4_salt_recovery_probes import restart, fail_bot_store
+
+
+def test_real_scheduler_manifest_park_races_active_drain(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ entered=threading.Event();release=threading.Event();threads=[];errors=[]
+ # Consumer edge only, not a real model launch; receipt claim/completion is production.
+ def consume(job,content,profile,*,deferred):
+ entered.set();assert release.wait(10);return None
+ from cron import scheduler_delivery
+ original_delivery=scheduler_delivery._deliver_to_bot_chat
+ def route(job,content,profile,**kwargs):
+ if kwargs.get('deferred') is not None:return consume(job,content,profile,**kwargs)
+ return original_delivery(job,content,profile,**kwargs)
+ monkeypatch.setattr('cron.scheduler_delivery._deliver_to_bot_chat',route)
+ orig_record=executions.record_delivery_manifest
+ def fail(eid,manifest):
+ if 'bot' not in manifest:return orig_record(eid,manifest)
+ monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
+ def drain():
+ try:bot_chat_delivery.drain()
+ except Exception as e:errors.append(e)
+ t=threading.Thread(target=drain);threads.append(t);t.start()
+ assert entered.wait(10)
+ raise OSError('recorder unavailable while receipt consumer active')
+ monkeypatch.setattr(executions,'record_delivery_manifest',fail)
+ original_attach=executions.journal_manifest
+ def attach(eid,manifest):
+ original_attach(eid,manifest)
+ assert executions.journaled_manifests()[eid]==manifest
+ release.set()
+ for t in threads:t.join(10)
+ assert not errors and all(not t.is_alive() for t in threads)
+ monkeypatch.setattr(executions,'journal_manifest',attach)
+ job,before=run(False)
+ monkeypatch.setattr(executions,'record_delivery_manifest',orig_record)
+ records=bot_chat_delivery._records(bot_chat_delivery._root())
+ restart(home)
+ after=executions.get_execution(before['id'])
+ print('COMPOSED_RACE',json.dumps({'receipt':records[0][1],'execution':after,'queued':jobs.get_job(job['id']).get('last_delivery_queued'),'native_sends':len(sent)}))
+ assert after['delivery_outcome']=='delivered'
+ assert not jobs.get_job(job['id']).get('last_delivery_queued')
+
+
+def test_external_store_fault_recovers_after_bot_failure_without_false_delivery(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ original=fail_bot_store(monkeypatch)
+ job,before=run(True);scheduler.drain_delivery_queue({},None)
+ mid=executions.get_execution(before['id'])
+ restart(home,fault=True)
+ # Drive the pending receipt to an actual failed attempt through production drain.
+ monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
+ monkeypatch.setattr('cron.scheduler_delivery._deliver_to_bot_chat',lambda *a,**k:'consumer failed')
+ bot_chat_delivery.drain()
+ monkeypatch.setattr(executions,'_store_manifest',original)
+ restart(home)
+ after=executions.get_execution(before['id'])
+ receipt=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
+ print('FAULT_RECOVERY',json.dumps({'mid':mid,'after':after,'receipt_status':receipt['status'],'queued':jobs.get_job(job['id']).get('last_delivery_queued'),'native_sends':len(sent)}))
+ assert after['delivery_outcome']=='unknown'
+
+
+def test_pruned_row_cannot_be_reconstructed_from_parked_manifest(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ original=fail_bot_store(monkeypatch)
+ job,before=run(True);scheduler.drain_delivery_queue({},None)
+ monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
+ with executions._transaction() as conn:executions._prune_unlocked(conn)
+ # Fixed contract: a journaled (outstanding-manifest) run is fenced from retention.
+ assert executions.get_execution(before['id']) is not None
+ monkeypatch.setattr(executions,'_store_manifest',original)
+ cfg(True);bot_chat_delivery.drain();restart(home)
+ receipt=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
+ print('PRUNED_REPLAY',json.dumps({'execution':executions.get_execution(before['id']),'receipt_status':receipt['status'],'journaled':before['id'] in executions.journaled_manifests(),'job':jobs.get_job(job['id'])}))
+ assert executions.get_execution(before['id']) is not None
diff --git a/tests/cron/test_r4_salt_journal_composed.py b/tests/cron/test_r4_salt_journal_composed.py
new file mode 100644
index 00000000000..2bdec611a52
--- /dev/null
+++ b/tests/cron/test_r4_salt_journal_composed.py
@@ -0,0 +1,79 @@
+"""Salt R4 J1/J3 composed probes, ported as regression cells."""
+import json, subprocess, sys, os
+import pytest
+from cron import executions, scheduler, scheduler_delivery, delivery_queue, jobs, bot_chat_delivery
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r4_salt_journal_edges import reject_manifest, repaired, fast_gateway
+from tests.cron.test_r4_salt_recovery_probes import restart
+
+
+def test_finish_alone_overrides_correct_queued_input(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest();fast_gateway(monkeypatch)
+ original=scheduler.finish_execution
+ seen=[]
+ def finish(eid,**kwargs):
+ kwargs['delivery_outcome']='queued'
+ result=original(eid,**kwargs)
+ seen.append({'input':'queued','result':result})
+ return result
+ monkeypatch.setattr(scheduler,'finish_execution',finish)
+ job,row=run(True)
+ print('FINISH_ALONE',json.dumps({'calls':seen,'journal':executions.journaled_manifests(),'native_sends':len(sent)}))
+ assert row['delivery_outcome']=='queued'
+
+
+def test_interrupted_scheduler_journal_row_pruned_by_next_completion(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest()
+ original=executions.journal_manifest
+ def journal_then_shutdown(eid,manifest):
+ original(eid,manifest)
+ assert scheduler.mark_running_jobs_interrupted('probe shutdown')
+ monkeypatch.setattr(executions,'journal_manifest',journal_then_shutdown)
+ job,row=run(False)
+ assert row and row['delivery_outcome']=='queued' # fixed contract: pre-send intent keeps the interrupted run queued
+ assert executions.journaled_manifests().get(row['id'])
+ assert len(sent)==1
+ monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',1)
+ another=executions.create_execution('retention-pressure',source='direct')
+ executions.finish_execution(another['id'],success=True,delivery_outcome='not_configured')
+ snapshot={'before':row,'after_retention':executions.get_execution(row['id']),'journal':executions.journaled_manifests(),'job':jobs.get_job(job['id']),'native_sends':len(sent)}
+ repaired();cfg(True);bot_chat_delivery.drain();restart(home)
+ snapshot['after_restart']=executions.get_execution(row['id']);snapshot['receipt']=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
+ print('COMPOSED_SHUTDOWN_PRUNE',json.dumps(snapshot))
+ assert snapshot['after_retention'] is not None
+
+
+def test_normal_wait_repaired_manifest_still_pins_false_outcome(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest();fast_gateway(monkeypatch)
+ job,row=run(True)
+ # Pending Bot Chat truly fails; no fabricated terminal receipt.
+ from tools import bot_live_delivery as mailbox
+ monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
+ monkeypatch.setattr(scheduler_delivery,'_deliver_to_bot_chat',lambda *a,**k:'consumer failure')
+ bot_chat_delivery.drain()
+ repaired();restart(home)
+ after=executions.get_execution(row['id'])
+ print('WAIT_BOT_FAILED',json.dumps({'before':row,'after':after,'job':jobs.get_job(job['id']),'receipt':bot_chat_delivery._records(bot_chat_delivery._root())[0][1],'sends':len(sent)}))
+ assert after['delivery_outcome']=='unknown'
+
+
+def test_abandoned_direct_owner_recovery_prunes_outstanding_journal(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest()
+ original=scheduler.finish_execution
+ def lose_terminal_write(*a,**kwargs):
+ raise OSError('terminal write unavailable until owner dies')
+ monkeypatch.setattr(scheduler,'finish_execution',lose_terminal_write)
+ job,row=run(False)
+ assert row['status']=='running'
+ assert executions.journaled_manifests().get(row['id'])
+ # Real recovery decisions need a provably absent owner; set the durable pid to a dead pid.
+ with executions._transaction() as conn:
+ conn.execute('UPDATE executions SET process_id=?,pid=?,process_started_at=? WHERE id=?',('dead-test-owner',99999999,0,row['id']))
+ monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
+ assert executions.recover_interrupted_executions()==1
+ print('ABANDONED_JOURNAL',json.dumps({'after':executions.get_execution(row['id']),'journal':executions.journaled_manifests(),'sends':len(sent)}))
+ assert executions.get_execution(row['id']) is not None
diff --git a/tests/cron/test_r4_salt_journal_edges.py b/tests/cron/test_r4_salt_journal_edges.py
new file mode 100644
index 00000000000..1a7f03c8846
--- /dev/null
+++ b/tests/cron/test_r4_salt_journal_edges.py
@@ -0,0 +1,125 @@
+"""Salt R4 J1-J4 journal-boundary probes, ported as regression cells (real stores; scheduling/fault edges only)."""
+import json, os, subprocess, sys, threading
+from pathlib import Path
+import pytest
+from cron import executions, scheduler, scheduler_delivery, delivery_queue, jobs, bot_chat_delivery
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r4_salt_recovery_probes import restart
+
+
+def reject_manifest():
+ with executions._transaction() as conn:
+ conn.execute('''CREATE TRIGGER salt_r4_reject BEFORE UPDATE OF delivery_manifest ON executions
+ WHEN NEW.delivery_manifest LIKE '%"bot"%'
+ BEGIN SELECT RAISE(ABORT, 'persistent ledger fault'); END''')
+
+
+def repaired():
+ with executions._transaction() as conn:
+ conn.execute('DROP TRIGGER salt_r4_reject')
+
+
+def fast_gateway(monkeypatch):
+ wait=delivery_queue.enqueue_and_wait
+ def synchronous(eid,job,content,*,for_failure=False,**kwargs):
+ delivery_queue.enqueue(eid,job,content,for_failure=for_failure)
+ scheduler.drain_delivery_queue({},None)
+ return wait(eid,job,content,for_failure=for_failure,timeout=0)
+ monkeypatch.setattr(delivery_queue,'enqueue_and_wait',synchronous)
+
+
+def test_worker_wait_with_outstanding_journal_keeps_queued(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest();fast_gateway(monkeypatch)
+ job,row=run(True)
+ snapshot={'execution':row,'saved_job':jobs.get_job(job['id']),'journal':executions.journaled_manifests(),'queue':delivery_queue.get_status(row['id']),'native_sends':len(sent)}
+ print('WAIT_BEFORE_REPAIR',json.dumps(snapshot))
+ repaired();cfg(True);bot_chat_delivery.drain();restart(home)
+ print('WAIT_AFTER_REPAIR',json.dumps(executions.get_execution(row['id'])))
+ assert row['delivery_outcome']=='queued'
+ assert snapshot['saved_job']['last_delivery_queued']
+
+
+def test_finish_projection_cannot_override_queued_with_placeholder(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest()
+ original=executions._delivery_projection
+ observed=[]
+ def recording(record):
+ result=original(record)
+ observed.append((record['id'],result))
+ return result
+ monkeypatch.setattr(executions,'_delivery_projection',recording)
+ fast_gateway(monkeypatch)
+ job,row=run(True)
+ print('FINISH_PROJECTIONS',json.dumps({'observed':observed,'outcome':row['delivery_outcome'],'outstanding':list(executions.journaled_manifests())}))
+ # This row is terminal but falsely delivered while a real Bot Chat receipt remains queued.
+ assert not any(result and result[0]=='delivered' for eid,result in observed)
+
+
[email protected]('external',[False,True])
+def test_unwritable_journal_after_real_send_is_not_transport_failure(setup,monkeypatch,external):
+ home,cfg,run,sent=setup
+ reject_manifest()
+ root=home/'cron'/'manifest_journal';root.mkdir();root.chmod(0o500)
+ try:
+ job,row=run(external)
+ if external:scheduler.drain_delivery_queue({},None)
+ snapshot={'execution':executions.get_execution(row['id']),'job':jobs.get_job(job['id']),'queue':delivery_queue.get_status(row['id']) if external else None,'native_sends':len(sent),'receipts':[r for p,r in bot_chat_delivery._records(bot_chat_delivery._root())]}
+ print('UNWRITABLE_JOURNAL',json.dumps(snapshot))
+ assert len(sent)==1
+ if external:assert snapshot['queue']['status']!='failed'
+ else:assert not snapshot['job'].get('last_delivery_error')
+ finally:root.chmod(0o700)
+
+
+def test_retention_after_interrupted_direct_run_preserves_journal(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest()
+ ex=executions.create_execution('interrupted',source='direct')
+ executions.mark_execution_running(ex['id'])
+ manifest={'bot':{'bot-chat:':{'home':str(home),'delivery_id':'receipt','status':'queued'}}}
+ executions.journal_manifest(ex['id'],manifest)
+ # _finish_interrupted_run calls finish_execution without delivery_outcome.
+ monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
+ scheduler._finish_interrupted_run({'id':'interrupted'},ex['id'],None)
+ print('INTERRUPTED_RETENTION',json.dumps({'row':executions.get_execution(ex['id']),'journal':executions.journaled_manifests()}))
+ assert executions.get_execution(ex['id']) is not None
+
+
+def test_journal_without_row_is_retained_not_resurrected(setup):
+ home,cfg,run,sent=setup
+ manifest={'bot':{'bot-chat:':{'home':str(home),'delivery_id':'missing','status':'queued'}}}
+ executions.journal_manifest('never-created',manifest)
+ restart(home,count=2)
+ assert executions.get_execution('never-created') is None
+ assert executions.journaled_manifests()['never-created']==manifest
+ print('ORPHAN_RETAINED',json.dumps(executions.journaled_manifests()))
+
+
[email protected]('terminal',['settled','ambiguous','suppressed'])
+def test_two_reconcilers_terminal_receipt_replay(setup,monkeypatch,terminal):
+ home,cfg,run,sent=setup
+ reject_manifest();job,row=run(True);scheduler.drain_delivery_queue({},None)
+ from tools import bot_live_delivery as mailbox
+ monkeypatch.setattr(mailbox,'find_canonical_owner',lambda h:None)
+ if terminal=='suppressed':cfg(True)
+ else:monkeypatch.setattr(scheduler_delivery,'_deliver_to_bot_chat',lambda *a,**k: None if terminal=='settled' else 'consumer failed')
+ bot_chat_delivery.drain()
+ records=bot_chat_delivery._records(bot_chat_delivery._root())
+ assert records[0][1]['status']==terminal
+ repaired()
+ REPO=next(p for p in Path(__file__).resolve().parents if (p/'cron'/'executions.py').exists())
+ env={k:v for k,v in os.environ.items() if k in ('PATH','LANG','LC_ALL','PYTHONDONTWRITEBYTECODE')}
+ env.update(HOME=str(home),HERMES_HOME=str(home),HERMES_MANAGED_DIR=str(home/'managed'),TMPDIR=str(home),PYTHONPATH=str(REPO))
+ script=Path(__file__).parent/'_r4_reconcile_child.py'
+ children=[subprocess.Popen([sys.executable,str(script)],env=env,cwd=str(next(p for p in Path(__file__).resolve().parents if (p/'cron'/'executions.py').exists())),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) for _ in range(2)]
+ for p in children:
+ out,err=p.communicate(timeout=30);print('CONCURRENT_REPLAY',p.returncode,out,err);assert p.returncode==0
+ after=executions.get_execution(row['id'])
+ assert after['delivery_outcome']==('unknown' if terminal=='ambiguous' else 'delivered')
+ assert after['delivery_projection_settled']==1
+ assert not executions.journaled_manifests()
+ assert not jobs.get_job(job['id']).get('last_delivery_queued')
+ assert len(sent)==1
+ print('CONCURRENT_FINAL',json.dumps(after))
diff --git a/tests/cron/test_r4_salt_journal_race.py b/tests/cron/test_r4_salt_journal_race.py
new file mode 100644
index 00000000000..58741a3aa0c
--- /dev/null
+++ b/tests/cron/test_r4_salt_journal_race.py
@@ -0,0 +1,46 @@
+"""Salt R4 J2: reconciler that started before journal creation must not settle the placeholder."""
+import json, threading
+from cron import executions, scheduler, jobs, bot_chat_delivery
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r4_salt_journal_edges import reject_manifest, fast_gateway
+
+
+def test_reconciler_started_before_journal_creation_does_not_settle_placeholder(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ reject_manifest()
+ job,row=run(True)
+ entered=threading.Event();release=threading.Event();errors=[]
+ original=executions._recover_unrecorded_manifests
+ def paused():
+ outstanding=original()
+ if threading.current_thread().name=='early-reconciler':
+ assert not outstanding
+ entered.set();assert release.wait(15)
+ return outstanding
+ monkeypatch.setattr(executions,'_recover_unrecorded_manifests',paused)
+ def reconcile():
+ try:executions.reconcile_delivery_projections()
+ except BaseException as e:errors.append(str(e))
+ thread=threading.Thread(target=reconcile,name='early-reconciler');thread.start()
+ assert entered.wait(15)
+ scheduler.drain_delivery_queue({},None)
+ assert executions.journaled_manifests().get(row['id'])
+ assert executions.get_execution(row['id'])['delivery_outcome']=='queued'
+ release.set();thread.join(15)
+ assert not thread.is_alive() and not errors
+ after=executions.get_execution(row['id'])
+ print('STALE_OUTSTANDING',json.dumps({'row':after,'journal':executions.journaled_manifests(),'job':jobs.get_job(job['id']),'native_sends':len(sent)}))
+ assert after['delivery_outcome']=='queued'
+ assert after['delivery_projection_settled']==0
+
+
+def test_fast_gateway_without_fault_keeps_bot_queued(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ fast_gateway(monkeypatch)
+ job,row=run(True)
+ assert row['delivery_outcome']=='queued'
+ assert jobs.get_job(job['id'])['last_delivery_queued']
+ cfg(True);bot_chat_delivery.drain()
+ assert executions.get_execution(row['id'])['delivery_outcome']=='delivered'
+ assert len(sent)==1
+ print('HEALTHY_FAST_WAIT',json.dumps(executions.get_execution(row['id'])))
diff --git a/tests/cron/test_r4_salt_recovery_probes.py b/tests/cron/test_r4_salt_recovery_probes.py
new file mode 100644
index 00000000000..18aeca52c04
--- /dev/null
+++ b/tests/cron/test_r4_salt_recovery_probes.py
@@ -0,0 +1,93 @@
+"""Salt R3 (B1-B3) recovery probes, ported verbatim as regression cells. Real stores/router; network and ledger edges injected."""
+import json, os, subprocess, sys, threading
+from pathlib import Path
+import pytest
+from cron import executions, scheduler, bot_chat_delivery, jobs, delivery_queue
+from tools import bot_live_delivery as mailbox
+from tests.cron.test_mixed_delivery_retention import setup
+
+ROOT=Path(__file__).resolve().parent
+
+def restart(home, *, fault=False, count=1):
+ REPO=next(p for p in ROOT.parents if (p/'cron'/'executions.py').exists())
+ env={k:v for k,v in os.environ.items() if k in ('PATH','LANG','LC_ALL','PYTHONDONTWRITEBYTECODE')}
+ env['PYTHONPATH']=str(REPO)
+ env.update(HOME=str(home), HERMES_HOME=str(home), HERMES_MANAGED_DIR=str(home/'managed'), TMPDIR=str(home))
+ cmd=[sys.executable,str(ROOT/'_r4_restart.py'),str(int(fault)),str(count)]
+ p=subprocess.run(cmd,env=env,cwd=str(REPO),capture_output=True,text=True,timeout=30)
+ print('RESTART',p.returncode,p.stdout,p.stderr)
+ assert p.returncode==0
+ return p
+
+def fail_bot_store(monkeypatch):
+ orig=executions._store_manifest
+ def fail(conn,eid,manifest):
+ if 'bot' in manifest: raise OSError('injected persistent SQLite manifest write failure')
+ return orig(conn,eid,manifest)
+ monkeypatch.setattr(executions,'_store_manifest',fail)
+ return orig
+
[email protected]('external',[False,True])
+def test_live_mailbox_recorder_fault_recovers(setup,monkeypatch,external):
+ from hermes_cli.active_sessions import try_acquire_active_session
+ from hermes_state import SessionDB
+ home,cfg,run,sent=setup
+ db=SessionDB(db_path=home/'state.db');db.create_session(session_id='live-bot',source='tui');db.set_session_title('bot','old bot');db.set_session_title('live-bot','Bot Chat')
+ lease,refusal=try_acquire_active_session(session_id='live-bot',surface='tui',config={},registry_home=home,metadata={'bot_live_delivery_consumer':True,'live_session_id':'salt-live'})
+ assert refusal is None
+ try:
+ owner=mailbox.find_canonical_live_owner(home);assert owner
+ orig=executions.record_delivery_manifest
+ def fail(eid,manifest):
+ if 'bot' in manifest: raise OSError('injected recorder fault')
+ return orig(eid,manifest)
+ monkeypatch.setattr(executions,'record_delivery_manifest',fail)
+ job,before=run(external)
+ if external: scheduler.drain_delivery_queue({},None)
+ records=list((home/'runtime/bot_live_delivery').glob('*.json'));assert len(records)==1
+ key=records[0].stem
+ mid=executions.get_execution(before['id'])
+ print('LIVE_MID',external,json.dumps(mid), 'pending',bot_chat_delivery.read_pending(key))
+ assert len(sent)==1
+ claimed=mailbox.claim_pending_delivery(home,owner);assert claimed
+ mailbox.complete_delivery(home,key,status='settled',reply='done')
+ monkeypatch.setattr(executions,'record_delivery_manifest',orig)
+ restart(home)
+ after=executions.get_execution(before['id']);saved=jobs.get_job(job['id'])
+ print('LIVE_FINAL',external,json.dumps(after),'queued',saved.get('last_delivery_queued'))
+ assert after['delivery_outcome']=='delivered'
+ assert not saved.get('last_delivery_queued')
+ assert after['delivery_manifest'] and 'bot' in json.loads(after['delivery_manifest'])
+ finally: lease.release();db.close()
+
[email protected]('external',[False,True])
+def test_persistent_real_manifest_store_fault_across_restart(setup,monkeypatch,external):
+ home,cfg,run,sent=setup
+ orig=fail_bot_store(monkeypatch)
+ job,before=run(external)
+ if external: scheduler.drain_delivery_queue({},None)
+ assert executions.journaled_manifests().get(before['id'])
+ restart(home,fault=True,count=2)
+ mid=executions.get_execution(before['id']);saved=jobs.get_job(job['id'])
+ print('PERSISTENT_MID',external,json.dumps(mid),'queued',saved.get('last_delivery_queued'))
+ assert mid['delivery_outcome']=='queued'
+ assert saved.get('last_delivery_queued')
+ monkeypatch.setattr(executions,'_store_manifest',orig)
+ cfg(True);bot_chat_delivery.drain();restart(home)
+ after=executions.get_execution(before['id'])
+ assert after['delivery_outcome']=='delivered'
+ assert not jobs.get_job(job['id']).get('last_delivery_queued')
+ assert len(sent)==1
+
+
+
+
+def test_parked_manifest_execution_is_not_pruned_during_store_fault(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ fail_bot_store(monkeypatch)
+ job,before=run(True);scheduler.drain_delivery_queue({},None)
+ assert executions.journaled_manifests().get(before['id'])
+ monkeypatch.setattr(executions,'MAX_TERMINAL_EXECUTIONS',0)
+ with executions._transaction() as conn:executions._prune_unlocked(conn)
+ print('PARKED_PRUNE',executions.get_execution(before['id']))
+ assert executions.get_execution(before['id']) is not None
diff --git a/tests/cron/test_r4_salt_sqlite_probe.py b/tests/cron/test_r4_salt_sqlite_probe.py
new file mode 100644
index 00000000000..85d2f71e7f8
--- /dev/null
+++ b/tests/cron/test_r4_salt_sqlite_probe.py
@@ -0,0 +1,25 @@
+"""Salt R3 B2: actual SQLite write rejection persists across fresh reconcilers."""
+import json, sqlite3
+from cron import executions, scheduler, jobs, bot_chat_delivery
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r4_salt_recovery_probes import restart
+
+
+def test_actual_sqlite_manifest_update_failure_keeps_pending_sibling(setup):
+ home,cfg,run,sent=setup
+ # Initialize real database; reject ONLY full-manifest updates, not placeholder/projection.
+ with executions._transaction() as conn:
+ conn.execute('''CREATE TRIGGER salt_reject_manifest BEFORE UPDATE OF delivery_manifest ON executions
+ WHEN NEW.delivery_manifest LIKE '%"bot"%'
+ BEGIN SELECT RAISE(ABORT, 'salt persistent manifest storage fault'); END''')
+ job,before=run(True);scheduler.drain_delivery_queue({},None)
+ restart(home,count=2) # no Python fault hook: SQLite itself rejects replay after restart.
+ mid=executions.get_execution(before['id'])
+ receipt=bot_chat_delivery._records(bot_chat_delivery._root())[0][1]
+ print('SQLITE_FAULT',json.dumps({'execution':mid,'receipt_status':receipt['status'],'journaled':before['id'] in executions.journaled_manifests(),'queued':jobs.get_job(job['id']).get('last_delivery_queued'),'native_sends':len(sent)}))
+ with sqlite3.connect(home/'cron/executions.db') as conn:conn.execute('DROP TRIGGER salt_reject_manifest')
+ restart(home)
+ recovered=executions.get_execution(before['id'])
+ print('SQLITE_REPAIRED',json.dumps({'execution':recovered,'queued':jobs.get_job(job['id']).get('last_delivery_queued')}))
+ assert mid['delivery_outcome']=='queued'
+ assert recovered['delivery_outcome']=='queued'
diff --git a/tests/cron/test_r5_salt_intent_lifecycle.py b/tests/cron/test_r5_salt_intent_lifecycle.py
new file mode 100644
index 00000000000..8f9f15ec8db
--- /dev/null
+++ b/tests/cron/test_r5_salt_intent_lifecycle.py
@@ -0,0 +1,93 @@
+"""Salt R5 K1 intent-lifecycle probes, ported as regression cells (production stores/scheduler; fault edges only)."""
+import json, os, subprocess, sys
+from pathlib import Path
+import pytest
+from cron import executions, scheduler, scheduler_delivery, jobs, bot_chat_delivery
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r4_salt_recovery_probes import restart
+
+
+def snapshot(home, job, row, sent):
+ return {'row':executions.get_execution(row['id']), 'job':jobs.get_job(job['id']),
+ 'receipts':bot_chat_delivery._records(bot_chat_delivery._root()),
+ 'journal':executions.journaled_manifests(),'native_sends':len(sent)}
+
+
+def test_all_suppressed_real_receipt_clears_intent(setup):
+ home,cfg,run,sent=setup
+ cfg(True)
+ job,row=run(False,deliver='bot-chat')
+ result=snapshot(home,job,row,sent)
+ print('ALL_SUPPRESSED',json.dumps(result,default=str))
+ assert row['delivery_manifest_pending']==0
+ assert row['delivery_outcome']=='suppressed'
+ assert not sent
+
+
+def test_rejected_before_receipt_clears_intent(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ from tools import bot_live_delivery
+ def fail(*a,**k): raise OSError('discovery unavailable before admission')
+ monkeypatch.setattr(bot_live_delivery,'read_delivery_result',fail)
+ job,row=run(False,deliver='bot-chat')
+ print('PRE_RECEIPT_REJECT',json.dumps(snapshot(home,job,row,sent),default=str))
+ assert row['delivery_manifest_pending']==0
+ assert row['delivery_outcome']=='failed'
+ assert not bot_chat_delivery._records(bot_chat_delivery._root())
+
+
+def test_presend_ledger_refusal_sends_nothing(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ with executions._transaction() as conn:
+ conn.execute("CREATE TRIGGER reject_intent BEFORE UPDATE OF delivery_manifest_pending ON executions WHEN NEW.delivery_manifest_pending=1 BEGIN SELECT RAISE(ABORT,'intent unavailable'); END")
+ job,row=run(False)
+ print('PRE_SEND_REFUSAL',json.dumps(snapshot(home,job,row,sent),default=str))
+ assert not sent and not bot_chat_delivery._records(bot_chat_delivery._root())
+ assert row['delivery_outcome']=='failed' and row['delivery_manifest_pending']==0
+
+
+def test_exception_before_first_send_does_not_pin_forever(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ def fail(*a,**k): raise OSError('transport discovery failed before any send')
+ monkeypatch.setattr(scheduler_delivery,'_resolve_target_transport',fail)
+ job,row=run(False,deliver='telegram:test,bot-chat')
+ restart(home,count=2)
+ result=snapshot(home,job,row,sent)
+ print('NO_RECEIPT_EXCEPTION',json.dumps(result,default=str))
+ assert not sent and not result['receipts'] and not result['journal']
+ assert result['row']['delivery_manifest_pending']==0, 'Known pre-send exception has no recovery source yet remains permanently pending'
+
+
+def test_transient_release_fault_recovers_no_receipt(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ from tools import bot_live_delivery
+ def fail(*a,**k): raise OSError('discovery unavailable before admission')
+ monkeypatch.setattr(bot_live_delivery,'read_delivery_result',fail)
+ with executions._transaction() as conn:
+ conn.execute("CREATE TRIGGER reject_release BEFORE UPDATE OF delivery_manifest_pending ON executions WHEN NEW.delivery_manifest_pending=0 BEGIN SELECT RAISE(ABORT,'transient intent release fault'); END")
+ job,row=run(False,deliver='bot-chat')
+ with executions._transaction() as conn: conn.execute('DROP TRIGGER reject_release')
+ restart(home,count=2)
+ result=snapshot(home,job,row,sent)
+ print('NO_RECEIPT_RELEASE_FAULT',json.dumps(result,default=str))
+ assert not sent and not result['receipts'] and not result['journal']
+ assert result['row']['delivery_manifest_pending']==0, 'Storage repaired but no deferred release exists; permanently queued'
+
+
+def test_nested_script_inner_intent_does_not_mark_outer(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ driver=Path(__file__).with_name('_r5_nested_driver.py')
+ (home/'scripts'/'outer.sh').write_text('#!/bin/sh\n'+sys.executable+' '+str(driver)+'\n')
+ outer=jobs.create_job(prompt=None,schedule='every 1h',script='outer.sh',no_agent=True,deliver='local')
+ row=executions.create_execution(outer['id'],source='external-outer')
+ outer['execution_id']=row['id']
+ monkeypatch.setenv('_HERMES_CRON_EXTERNAL_WORKER',row['id'])
+ assert scheduler.run_one_job(outer)
+ receipt=json.loads((home/'inner-proof.json').read_text())
+ after=executions.get_execution(row['id'])
+ print('NESTED_SCRIPT',json.dumps({'outer':after,'inner':receipt}))
+ assert receipt['outer_env']==row['id']
+ assert receipt['inner']['id'] != row['id']
+ assert receipt['inner']['delivery_manifest_pending']==1
+ assert after['delivery_manifest_pending']==0 and after['delivery_outcome']=='suppressed' # outer script emits no output
+ assert receipt['inner']['delivery_outcome']=='queued'
diff --git a/tests/cron/test_r5_salt_legacy_and_races.py b/tests/cron/test_r5_salt_legacy_and_races.py
new file mode 100644
index 00000000000..68a16322cc3
--- /dev/null
+++ b/tests/cron/test_r5_salt_legacy_and_races.py
@@ -0,0 +1,145 @@
+"""Salt R5 K2/S5 probes (legacy upgrade + reconciler races), ported as regression cells."""
+import importlib.util, json, sqlite3, threading
+from pathlib import Path
+import pytest
+from cron import executions as ex, jobs, delivery_queue as dq, bot_chat_delivery as bot
+from utils import atomic_json_write
+ROOT=Path(__file__).resolve().parent
+SALT=Path('/home/deploy/work/nous368-full-audit/salt-r5-review')
+
+def store(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME',str(tmp_path))
+ monkeypatch.setenv('HERMES_MANAGED_DIR',str(tmp_path/'managed'))
+ monkeypatch.setattr(ex,'EXECUTIONS_FILE',tmp_path/'cron'/'executions.db')
+ monkeypatch.setattr(dq,'DELIVERY_DB',tmp_path/'cron'/'deliveries.db')
+ return tmp_path
+
+def prior():
+ spec=importlib.util.spec_from_file_location('child_prior',ROOT/'_r5_prior_executions.py')
+ mod=importlib.util.module_from_spec(spec);spec.loader.exec_module(mod)
+ return mod
+
+def seed(home, module=ex, placeholder=True):
+ module.EXECUTIONS_FILE=home/'cron'/'executions.db'
+ row=module.create_execution('child-job',source='evidence')
+ eid=row['id']
+ module.record_delivery_manifest(eid,{'external':True} if placeholder else {'bot':{}})
+ module.finish_execution(eid,success=True,delivery_outcome='queued')
+ # Actual durable jobs store, no scheduler/model/transport.
+ jobs.save_jobs([{'id':'child-job','name':'child probe','prompt':'probe','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_status':'delivery_queued','last_delivery_queued':{'gateway':{'status':'queued'}}}])
+ dq.enqueue(eid,{'id':'child-job'},'evidence')
+ assert dq.claim_next()['execution_id']==eid
+ assert dq._finish(eid,error=None)
+ return eid
+
+def receipt(home,eid):
+ key=eid+'b07'
+ bot.defer(key,{'id':'child-job'},'evidence','',home)
+ return {'bot':{'bot-chat:(own)':{'home':str(home),'delivery_id':key,'status':'queued'}},'delivered':True}
+
+def set_receipt(manifest,status):
+ ref=next(iter(manifest['bot'].values()))
+ row=bot.read_pending(ref['delivery_id']);row['status']=status
+ atomic_json_write(bot._root()/(ref['delivery_id']+'.json'),row,fsync_dir=True,mode=0o600)
+
+def snap(eid):
+ return {'execution':ex.get_execution(eid),'job':jobs.get_job('child-job'),'journal':ex.journaled_manifests()}
+
+def save(name,data):
+ print(name,json.dumps(data))
+
[email protected]('version',['prior','head'])
+def test_legacy_failed_replay_must_not_project_placeholder(store,version):
+ old=prior();eid=seed(store,old);manifest=receipt(store,eid)
+ old.journal_manifest(eid,manifest)
+ with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
+ assert 'delivery_manifest_pending' not in [r[1] for r in conn.execute('PRAGMA table_info(executions)')]
+ conn.execute("CREATE TRIGGER child_reject_manifest BEFORE UPDATE OF delivery_manifest ON executions WHEN instr(NEW.delivery_manifest, '\"bot\"')>0 BEGIN SELECT RAISE(ABORT,'child persistent manifest fault'); END")
+ target=old if version=='prior' else ex
+ target.reconcile_delivery_projections()
+ state=snap(eid)
+ with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
+ conn.execute('DROP TRIGGER child_reject_manifest')
+ set_receipt(manifest,'ambiguous')
+ target.reconcile_delivery_projections()
+ repaired=snap(eid)
+ save('legacy-'+version,{'after_failed_replay':state,'after_repair':repaired})
+ assert state['execution']['delivery_outcome']=='queued'
+ assert state['execution']['delivery_projection_settled']==0
+ assert state['job']['last_delivery_queued']
+
[email protected]('kind',['no_manifest','external_only','healthy_replay'])
+def test_legacy_default_zero_parity_controls(store,kind):
+ old=prior()
+ if kind=='no_manifest':
+ eid=old.create_execution('child-job',source='evidence')['id']
+ old.finish_execution(eid,success=True,delivery_outcome='not_configured')
+ before=old.get_execution(eid)
+ ex.reconcile_delivery_projections();after=ex.get_execution(eid)
+ assert after['delivery_outcome']==before['delivery_outcome']
+ else:
+ eid=seed(store,old)
+ if kind=='healthy_replay':old.journal_manifest(eid,receipt(store,eid))
+ ex.reconcile_delivery_projections();after=ex.get_execution(eid)
+ assert after['delivery_outcome']==('queued' if kind=='healthy_replay' else 'delivered')
+ assert after['delivery_manifest_pending']==0
+ save('parity-'+kind,after)
+
+
+def test_two_reconcilers_repair_before_stale_projection_write(store,monkeypatch):
+ eid=seed(store);manifest=receipt(store,eid)
+ ex.mark_delivery_manifest_pending(eid)
+ assert ex.journal_manifest(eid,manifest)
+ reached=threading.Event();release=threading.Event();errors=[]
+ original=ex._delivery_projection
+ def barrier(record):
+ result=original(record)
+ if threading.current_thread().name=='child-stale':
+ reached.set();assert release.wait(15)
+ return result
+ monkeypatch.setattr(ex,'_delivery_projection',barrier)
+ def run():
+ try:ex.reconcile_delivery_projections()
+ except BaseException as err:errors.append(repr(err))
+ t=threading.Thread(target=run,name='child-stale');t.start()
+ assert reached.wait(15)
+ repaired=ex.get_execution(eid)
+ assert repaired['delivery_manifest_pending']==0
+ set_receipt(manifest,'settled');ex.reconcile_delivery_projections()
+ winner=snap(eid)
+ release.set();t.join(15);assert not t.is_alive() and not errors
+ after=snap(eid)
+ save('race-before-ledger',{'winner':winner,'after':after})
+ assert after['execution']['delivery_outcome']=='delivered'
+ assert not after['job']['last_delivery_queued']
+ assert not after['journal']
+
+
+def test_two_reconcilers_repair_and_settle_between_ledger_and_jobs(store,monkeypatch):
+ eid=seed(store);manifest=receipt(store,eid)
+ ex.mark_delivery_manifest_pending(eid);assert ex.journal_manifest(eid,manifest)
+ reached=threading.Event();release=threading.Event();errors=[]
+ original=jobs.update_delivery_projection
+ def barrier(*args,**kwargs):
+ if threading.current_thread().name=='child-stale':
+ reached.set();assert release.wait(15)
+ return original(*args,**kwargs)
+ monkeypatch.setattr(jobs,'update_delivery_projection',barrier)
+ def run():
+ try:ex.reconcile_delivery_projections()
+ except BaseException as err:errors.append(repr(err))
+ t=threading.Thread(target=run,name='child-stale');t.start()
+ assert reached.wait(15)
+ assert ex.get_execution(eid)['delivery_manifest_pending']==0
+ set_receipt(manifest,'settled');ex.reconcile_delivery_projections()
+ winner=snap(eid)
+ release.set();t.join(15);assert not t.is_alive() and not errors
+ after=snap(eid)
+ monkeypatch.setattr(ex,'MAX_TERMINAL_EXECUTIONS',0)
+ with ex._transaction() as conn:ex._prune_unlocked(conn)
+ ex.reconcile_delivery_projections()
+ pruned=snap(eid)
+ save('race-after-ledger',{'winner':winner,'after':after,'after_prune':pruned})
+ assert not after['job']['last_delivery_queued'], 'stale queued projection resurrected after winning terminal projection'
+ assert not pruned['job']['last_delivery_queued']
diff --git a/tests/cron/test_r6_salt_controls.py b/tests/cron/test_r6_salt_controls.py
new file mode 100644
index 00000000000..af9ade16184
--- /dev/null
+++ b/tests/cron/test_r6_salt_controls.py
@@ -0,0 +1,80 @@
+"""Salt R6 controls, ported: healthy adoption, freshness, settlement durability; Q1 secondary-exception contract now FIXED (original wins)."""
+import json
+import sqlite3
+import sys
+from pathlib import Path
+import pytest
+from tests.cron.test_r6_salt_migration_authority import legacy_running
+from tests.cron.test_r5_salt_legacy_and_races import store, seed
+from tests.cron.test_mixed_delivery_retention import setup
+from cron import executions as ex, jobs, scheduler_delivery as sd
+
+
+def test_healthy_adoption_precedes_late_finish(store):
+ eid,manifest=legacy_running(store)
+ row=ex.get_execution(eid)
+ assert row['delivery_manifest_pending']==1
+ row=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ assert row['delivery_outcome']=='queued'
+ assert ex.get_execution(eid)['delivery_outcome']=='queued'
+
+
+def test_new_execution_after_unknown_accepts_queued(store):
+ eid=seed(store)
+ with ex._transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_outcome='unknown' WHERE id=?",(eid,))
+ newer=ex.create_execution('child-job',source='r6-explicit-new-run')
+ jobs.bind_delivery_execution('child-job',newer['id'])
+ values={'last_delivery_queued':{'bot-chat:test':{'status':'queued'}}}
+ assert jobs.update_delivery_projection('child-job',newer['id'],values)
+ assert jobs.get_job('child-job')['last_delivery_queued']==values['last_delivery_queued']
+
+
+def test_original_exception_survives_all_ordinary_bookkeeping_faults(setup,monkeypatch):
+ home,cfg,run,sent=setup
+ job=jobs.create_job(prompt='probe',schedule='every 1h',deliver='telegram:test,bot-chat')
+ row=ex.create_execution(job['id'],source='r6');job['execution_id']=row['id']
+ jobs.bind_delivery_execution(job['id'],row['id'])
+ original=sd._deliver_targets
+ error=RuntimeError('original post-admission fault')
+ def fail_after(*a,**k):
+ original(*a,**k)
+ raise error
+ monkeypatch.setattr(sd,'_deliver_targets',fail_after)
+ def fail_jobs(*a,**k): raise OSError('jobs write refused')
+ monkeypatch.setattr(jobs,'update_delivery_projection',fail_jobs)
+ with ex._transaction() as conn:
+ conn.execute("CREATE TRIGGER r6_settle_fault BEFORE UPDATE OF delivery_manifest ON executions BEGIN SELECT RAISE(ABORT,'manifest write refused'); END")
+ root=ex._journal_root();root.mkdir();root.chmod(0)
+ try:
+ with pytest.raises(RuntimeError) as caught: sd._deliver_result(job,'r6 payload')
+ assert caught.value is error
+ assert len(sent)==1 and job['_bot_chat_delivery_receipts']
+ assert ex.get_execution(row['id'])['delivery_manifest_pending']==1
+ finally:
+ root.chmod(0o700)
+
+
+def test_secondary_baseexception_does_not_mask_original(setup,monkeypatch):
+ import asyncio
+ home,cfg,run,sent=setup
+ job=jobs.create_job(prompt='probe',schedule='every 1h',deliver='bot-chat')
+ row=ex.create_execution(job['id'],source='r6');job['execution_id']=row['id']
+ original=OSError('original transport discovery failure')
+ secondary=asyncio.CancelledError('second interruption during manifest persistence')
+ def fail_targets(*a,**k): raise original
+ def fail_record(*a,**k): raise secondary
+ monkeypatch.setattr(sd,'_deliver_targets',fail_targets)
+ monkeypatch.setattr(ex,'record_delivery_manifest',fail_record)
+ with pytest.raises(OSError) as caught: sd._deliver_result(job,'r6 payload')
+ assert caught.value is original
+ assert ex.get_execution(row['id'])['delivery_manifest_pending']==1 # uncertainty preserved
+
+
+def test_column_presence_is_not_the_authority_fence_row_is(store):
+ """DDL commits on its own; the schema_meta fence row is what readers trust."""
+ eid,manifest=legacy_running(store)
+ assert ex.get_execution(eid)['delivery_manifest_pending']==1
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as other:
+ assert other.execute("SELECT 1 FROM schema_meta WHERE key=?",(ex._ADOPTION_KEY,)).fetchone()
+ assert ex._legacy_intent_adopted()
diff --git a/tests/cron/test_r6_salt_migration_authority.py b/tests/cron/test_r6_salt_migration_authority.py
new file mode 100644
index 00000000000..48091f293ad
--- /dev/null
+++ b/tests/cron/test_r6_salt_migration_authority.py
@@ -0,0 +1,128 @@
+"""Salt R6 probes (partial-exception settle, empty-bot outcomes, jobs freshness, K2a/K2b migration authority), ported as regression cells."""
+import asyncio
+import json
+import os
+import sqlite3
+from pathlib import Path
+import pytest
+from cron import executions as ex, jobs, scheduler_delivery as sd, bot_chat_delivery as bot, delivery_queue as dq
+from tests.cron.test_mixed_delivery_retention import setup
+from tests.cron.test_r5_salt_legacy_and_races import store, prior, seed, receipt, snap
+
[email protected]('exception_type',[OSError, asyncio.CancelledError, KeyboardInterrupt])
[email protected]('persist_fault',[False,True])
+def test_partial_native_and_bot_then_exception(setup,monkeypatch,exception_type,persist_fault):
+ home,cfg,run,sent=setup
+ job=jobs.create_job(prompt='probe',schedule='every 1h',deliver='telegram:test,bot-chat')
+ row=ex.create_execution(job['id'],source='r6'); job['execution_id']=row['id']
+ jobs.bind_delivery_execution(job['id'],row['id'])
+ original=sd._deliver_targets
+ error=exception_type('r6 post-admission exception')
+ def fail_after(*args,**kwargs):
+ original(*args,**kwargs)
+ assert len(sent)==1 and job['_bot_chat_delivery_receipts']
+ raise error
+ monkeypatch.setattr(sd,'_deliver_targets',fail_after)
+ if persist_fault:
+ with ex._transaction() as conn:
+ conn.execute("CREATE TRIGGER r6_fault BEFORE UPDATE OF delivery_manifest ON executions BEGIN SELECT RAISE(ABORT,'r6 ledger fault'); END")
+ with pytest.raises(exception_type) as caught:
+ sd._deliver_result(job,'r6 payload')
+ assert caught.value is error
+ state=ex.get_execution(row['id'])
+ manifest=ex.journaled_manifests()[row['id']] if persist_fault else json.loads(state['delivery_manifest'])
+ assert manifest['bot'] and manifest['delivered'] and 'r6 post-admission exception' in manifest['error']
+ if persist_fault:
+ with ex._transaction() as conn: conn.execute('DROP TRIGGER r6_fault')
+ ex._recover_unrecorded_manifests()
+ finished=ex.finish_execution(row['id'],success=False,error='original run failure',delivery_outcome='failed')
+ assert finished['delivery_outcome']=='queued'
+ assert jobs.get_job(job['id'])['last_delivery_queued']
+ print('PARTIAL',exception_type.__name__,persist_fault,json.dumps(ex.get_execution(row['id'])))
+
[email protected]('error,expected',[(None,'delivered'),('bot discovery failed','failed')])
+def test_empty_bot_manifest_native_outcome(setup,monkeypatch,error,expected):
+ home,cfg,run,sent=setup
+ monkeypatch.setattr(sd,'_deliver_to_bot_chat',lambda *a,**k:error)
+ job,row=run(False,deliver='telegram:test,bot-chat')
+ assert len(sent)==1
+ manifest=json.loads(row['delivery_manifest'])
+ assert manifest['bot']=={} and manifest['delivered'] is True
+ assert row['delivery_manifest_pending']==0 and row['delivery_outcome']==expected
+ print('EMPTY_BOT',expected,json.dumps(row))
+
[email protected]('outcome,accepted',[(None,True),('queued',True),('delivered',False),('failed',False),('unknown',False),('suppressed',False),('not_configured',False)])
+def test_jobs_freshness_outcomes(store,outcome,accepted):
+ eid=seed(store)
+ with ex._transaction() as conn:
+ conn.execute('UPDATE executions SET delivery_outcome=? WHERE id=?',(outcome,eid))
+ values={'last_delivery_queued':{'bot-chat:test':{'status':'queued'}}}
+ assert jobs.update_delivery_projection('child-job',eid,values) is accepted
+ assert jobs.update_delivery_projection('child-job',eid,{'last_delivery_queued':None}) is True
+ assert jobs.get_job('child-job')['last_delivery_queued'] is None
+ print('FRESHNESS',outcome,accepted)
+
+
+def legacy_running(home):
+ old=prior(); old.EXECUTIONS_FILE=home/'cron'/'executions.db'
+ row=old.create_execution('child-job',source='r6-upgrade'); eid=row['id']
+ # Model a surviving process importing upgraded code: retain its ownership.
+ with old._transaction() as conn:
+ conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
+ old.record_delivery_manifest(eid,{'external':True})
+ jobs.save_jobs([{'id':'child-job','name':'r6','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_delivery_queued':{'gateway':{'status':'queued'}}}])
+ dq.enqueue(eid,{'id':'child-job'},'evidence'); assert dq.claim_next(); assert dq._finish(eid,error=None)
+ manifest=receipt(home,eid); old.journal_manifest(eid,manifest)
+ with sqlite3.connect(old.EXECUTIONS_FILE) as conn:
+ assert 'delivery_manifest_pending' not in [r[1] for r in conn.execute('PRAGMA table_info(executions)')]
+ return eid,manifest
+
[email protected]('inaccessible',['directory','entry'])
+def test_unreadable_upgrade_must_not_terminalize_placeholder(store,inaccessible):
+ eid,manifest=legacy_running(store)
+ root=store/'cron'/'manifest_journal'
+ target=root if inaccessible=='directory' else root/(eid+'.json')
+ original_mode=target.stat().st_mode & 0o777
+ target.chmod(0)
+ try:
+ # Real permission fault: no monkeypatch of journal enumeration or projection.
+ after_init=ex.get_execution(eid)
+ adopted_while_unreadable=ex._legacy_intent_adopted()
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ while_unreadable=ex.get_execution(eid)
+ finally:
+ target.chmod(original_mode)
+ ex.reconcile_delivery_projections()
+ repaired=ex.get_execution(eid)
+ print('UNREADABLE_UPGRADE',inaccessible,json.dumps({'after_init':after_init,'finished':finished,'unreadable':while_unreadable,'restored':repaired,'job':jobs.get_job('child-job')}))
+ # Contract (Salt R6 K2a): an unreadable inventory is NOT proof of no outstanding intent. The
+ # mechanism here is the migration-completion fence row (absent until adoption succeeds), so
+ # every reader holds placeholder-only rows conservatively; the flag itself lands on retry.
+ assert not adopted_while_unreadable, 'unreadable adoption must not be recorded as complete'
+ assert finished['delivery_outcome']=='queued', 'late finish projected the placeholder while adoption incomplete'
+ assert while_unreadable['delivery_projection_settled']==0
+ assert repaired['delivery_outcome']=='queued', 'readable journal restoration cannot repair falsely terminal ledger'
+ assert '"bot"' in repaired['delivery_manifest'] and jobs.get_job('child-job')['last_delivery_queued']
+ assert ex._legacy_intent_adopted(), 'adoption retried and completed once the journal became readable'
+
+
+def test_failed_adoption_must_retry_before_finish(store):
+ eid,manifest=legacy_running(store)
+ # Trigger can reference the to-be-added column, as a restored old-schema DB can.
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ conn.execute("CREATE TRIGGER r6_adoption_fault BEFORE UPDATE ON executions WHEN NEW.delivery_manifest_pending=1 BEGIN SELECT RAISE(ABORT,'r6 adoption fault'); END")
+ # Adoption fails (rolled back, logged) but initialization degrades to a fenced state rather
+ # than blocking every cron operation; the fence row is absent so readers hold the row.
+ ex.get_execution(eid)
+ assert not ex._legacy_intent_adopted()
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ columns=[r[1] for r in conn.execute('PRAGMA table_info(executions)')]
+ raw=conn.execute('SELECT delivery_manifest_pending FROM executions WHERE id=?',(eid,)).fetchone()[0]
+ conn.execute('DROP TRIGGER r6_adoption_fault')
+ # The first retry is a legitimate late worker finish, not a reconciler.
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ after=ex.get_execution(eid)
+ print('ADOPTION_RETRY',json.dumps({'pending_column_survives': 'delivery_manifest_pending' in columns,'raw_pending':raw,'finished':finished,'after':after,'job':jobs.get_job('child-job')}))
+ assert after['delivery_outcome']=='queued', 'schema ALTER survived adoption rollback; next finish projects placeholder before replay'
+ assert ex._legacy_intent_adopted(), 'adoption retried on the next initialization'
+ assert '"bot"' in after['delivery_manifest'], 'replay landed the real manifest after adoption fenced the row'
diff --git a/tests/cron/test_r7_salt_edges.py b/tests/cron/test_r7_salt_edges.py
new file mode 100644
index 00000000000..6805fee03b1
--- /dev/null
+++ b/tests/cron/test_r7_salt_edges.py
@@ -0,0 +1,149 @@
+"""Salt R7 probes (late legacy journal K2c, concurrent initializers, interrupted CASE matrix), ported as regression cells."""
+import json, os, os, sqlite3, subprocess, sys, time
+from pathlib import Path
+import pytest
+from cron import executions as ex, jobs
+from tests.cron.test_r5_salt_legacy_and_races import store, prior, receipt, snap
+from tests.cron.test_r6_salt_migration_authority import legacy_running
+from tests.cron.test_manifest_intent_upgrade import _reject_bot_manifest
+HERE=Path(__file__).resolve().parent
+REPO=next(p for p in HERE.parents if (p/'cron'/'executions.py').exists())
+def _env(**extra):
+ env=dict(os.environ); env['PYTHONPATH']=str(REPO); env.update(extra); return env
+
[email protected]('window',['after_commit','after_inventory'])
[email protected]('replay_first',[False,True])
+def test_late_old_journal_before_finish(store,monkeypatch,window,replay_first):
+ eid,manifest=legacy_running(store)
+ journal=ex._journal_root()/(eid+'.json'); journal.unlink()
+ old=prior(); old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ if window=='after_inventory':
+ original=ex._journal_inventory_strict
+ def after_snapshot():
+ result=original()
+ old.journal_manifest(eid,manifest)
+ return result
+ monkeypatch.setattr(ex,'_journal_inventory_strict',after_snapshot)
+ initial=ex.get_execution(eid)
+ assert ex._legacy_intent_adopted() and initial['delivery_manifest_pending']==0
+ if window=='after_commit': old.journal_manifest(eid,manifest)
+ # No pending reset or production-projection stub. Actual old journal writer lacks preflag.
+ if replay_first:
+ with ex._transaction() as conn: _reject_bot_manifest(conn)
+ ex._recover_unrecorded_manifests()
+ assert ex.get_execution(eid)['delivery_manifest_pending']==1
+ with ex._transaction() as conn: conn.execute('DROP TRIGGER k2_reject')
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ after=snap(eid)
+ print('LATE_JOURNAL',json.dumps({'window':window,'replay_first':replay_first,'initial':initial,'finished':finished,'after':after}))
+ assert after['execution']['delivery_outcome']=='queued', 'late old journal escaped adoption; replay cannot undo false terminal outcome'
+ assert jobs.get_job('child-job')['last_delivery_queued']
+
[email protected]('iteration',range(3))
+def test_two_concurrent_old_schema_initializers(store,iteration):
+ eid,manifest=legacy_running(store)
+ barrier=store/'barrier'; barrier.mkdir()
+ processes=[]
+ try:
+ for name in ('a','b'):
+ env=_env(HERMES_HOME=str(store))
+ p=subprocess.Popen([sys.executable,str(HERE/'_r7_initializer_worker.py'),str(store),str(barrier),name],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
+ processes.append(p)
+ deadline=time.monotonic()+20
+ while not all((barrier/(name+'.ready')).exists() for name in ('a','b')):
+ assert time.monotonic()<deadline, 'concurrent initialization never reached inventory boundary'
+ assert all(p.poll() is None for p in processes), 'initializer exited early'
+ time.sleep(.01)
+ (barrier/'go').write_text('go')
+ results=[]
+ for p in processes:
+ stdout,stderr=p.communicate(timeout=25)
+ assert p.returncode==0,(stdout,stderr)
+ result=json.loads(stdout.strip().splitlines()[-1]);results.append(result)
+ assert result['adopted'] and result['pending']==[1]
+ assert result['entry'][0]['in_transaction'] is False
+ # Journal mode is runtime policy (hermes_state_wal gates WAL by SQLite build), not the
+ # contract under test; the atomicity evidence below is what one adoption must satisfy.
+ assert result['entry'][0]['journal_mode'] in ('wal','delete')
+ assert sum('COMMIT' in r['trace'] for r in results)==1
+ assert sum('ROLLBACK' in r['trace'] for r in results)==1
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ assert conn.execute('SELECT count(*) FROM schema_meta WHERE key=?',(ex._ADOPTION_KEY,)).fetchone()[0]==1
+ assert conn.execute('SELECT delivery_manifest_pending FROM executions WHERE id=?',(eid,)).fetchone()[0]==1
+ print('TWO_INITIALIZERS',iteration,json.dumps(results))
+ finally:
+ for p in processes:
+ if p.poll() is None: p.kill();p.wait()
+
[email protected]('adoption_complete',[False,True])
[email protected]('manifest',[None,{'external':True},{'bot':{}}],ids=['null','placeholder','bot'])
[email protected]('flag',[0,1])
+def test_interrupted_case_matrix(store,monkeypatch,adoption_complete,manifest,flag):
+ old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ eid=old.create_execution('matrix',source='r7')['id']
+ if manifest is not None: old.record_delivery_manifest(eid,manifest)
+ root=ex._journal_root();root.mkdir(exist_ok=True)
+ if not adoption_complete: root.chmod(0)
+ try:
+ ex.get_execution(eid)
+ assert ex._legacy_intent_adopted() is adoption_complete
+ # Real exited process identity, not a monkeypatched liveness result.
+ # pid selected from a Popen whose exit was waited, not guessed.
+ p=subprocess.Popen([sys.executable,str(HERE/'_r7_exit_child.py')],env=_env());p.wait()
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ conn.execute("UPDATE executions SET process_id='gone-r7',pid=?,process_started_at=NULL,delivery_manifest_pending=?,delivery_outcome=NULL WHERE id=?",(p.pid,flag,eid))
+ assert ex.recover_interrupted_executions()==1
+ row=ex.get_execution(eid)
+ expected='queued' if flag or (not adoption_complete and manifest is not None and 'bot' not in manifest) else None
+ print('RECOVERY_CASE',json.dumps({'adopted':adoption_complete,'manifest':manifest,'flag':flag,'outcome':row['delivery_outcome']}))
+ assert row['status']=='unknown' and row['delivery_outcome']==expected
+ finally: root.chmod(0o700)
+
+
+def test_external_only_liveness_and_prune_connection(store,monkeypatch):
+ old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ eid=old.create_execution('external-only',source='r7')['id']
+ old.record_delivery_manifest(eid,{'external':True})
+ with old._transaction() as conn: conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
+ root=ex._journal_root();root.mkdir(exist_ok=True);root.chmod(0)
+ try:
+ row=ex.finish_execution(eid,success=False,delivery_outcome='failed')
+ assert row['delivery_outcome']=='queued'
+ assert ex._delivery_projection(row) is None
+ with ex._transaction() as conn:
+ conn.execute("UPDATE executions SET delivery_outcome='delivered',delivery_projection_settled=1 WHERE id=?",(eid,))
+ statements=[];conn.set_trace_callback(statements.append)
+ def no_new_connection(): raise AssertionError('nested connection opened by prune')
+ with monkeypatch.context() as m:
+ m.setattr(ex,'MAX_TERMINAL_EXECUTIONS',0)
+ m.setattr(ex,'_connect',no_new_connection)
+ ex._prune_unlocked(conn)
+ assert ex._fetch(conn,eid) is not None
+ assert not any(s.startswith('BEGIN') for s in statements)
+ print('PRUNE_CONNECTION',json.dumps(statements))
+ assert not ex._legacy_intent_adopted()
+ finally: root.chmod(0o700)
+ assert ex._legacy_intent_adopted()
+ with ex._transaction() as conn:
+ with monkeypatch.context() as m:
+ m.setattr(ex,'MAX_TERMINAL_EXECUTIONS',0);ex._prune_unlocked(conn)
+ assert ex.get_execution(eid) is None
+
+
+def test_multirow_adoption_rolls_back_all_and_retries(store):
+ eid,manifest=legacy_running(store)
+ old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ second=old.create_execution('second',source='r7')['id'];old.record_delivery_manifest(second,{'external':True});old.journal_manifest(second,receipt(store,second))
+ last=max(eid,second)
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ conn.execute(f"CREATE TRIGGER r7_partial BEFORE UPDATE ON executions WHEN NEW.id='{last}' AND NEW.delivery_manifest_pending=1 BEGIN SELECT RAISE(ABORT,'second row fault'); END")
+ ex.get_execution(eid)
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ assert conn.execute('SELECT count(*) FROM schema_meta').fetchone()[0]==0
+ assert conn.execute('SELECT sum(delivery_manifest_pending) FROM executions').fetchone()[0]==0
+ conn.execute('DROP TRIGGER r7_partial')
+ ex.get_execution(eid)
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ assert conn.execute('SELECT count(*) FROM schema_meta').fetchone()[0]==1
+ assert conn.execute('SELECT sum(delivery_manifest_pending) FROM executions').fetchone()[0]==2
+ print('ATOMIC_ADOPTION','rollback all rows and fence, retry both rows')
diff --git a/tests/cron/test_r7_salt_late_process.py b/tests/cron/test_r7_salt_late_process.py
new file mode 100644
index 00000000000..33f7de1527a
--- /dev/null
+++ b/tests/cron/test_r7_salt_late_process.py
@@ -0,0 +1,45 @@
+"""Salt R7 K2c: real separate pre-flag writer publishing after adoption, ported as regression cell."""
+import json, os, os, sqlite3, subprocess, sys, time
+from pathlib import Path
+import pytest
+from cron import executions as ex, delivery_queue as dq, jobs
+from tests.cron.test_r5_salt_legacy_and_races import store, prior, snap
+HERE=Path(__file__).resolve().parent
+REPO=next(p for p in HERE.parents if (p/'cron'/'executions.py').exists())
+def _env(**extra):
+ env=dict(os.environ); env['PYTHONPATH']=str(REPO); env.update(extra); return env
+
[email protected]('replay_first',[False,True])
+def test_old_process_publishes_after_adoption(store,replay_first):
+ old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ eid=old.create_execution('child-job',source='r7-late-process')['id']
+ old.record_delivery_manifest(eid,{'external':True})
+ with old._transaction() as conn: conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
+ jobs.save_jobs([{'id':'child-job','name':'r7','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_delivery_queued':{'gateway':{'status':'queued'}}}])
+ dq.enqueue(eid,{'id':'child-job'},'evidence')
+ barrier=store/'writer';barrier.mkdir()
+ p=subprocess.Popen([sys.executable,str(HERE/'_r7_old_writer.py'),str(store),eid,str(barrier)],env=_env(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
+ try:
+ deadline=time.monotonic()+20
+ while not (barrier/'ready').exists():
+ assert time.monotonic()<deadline and p.poll() is None
+ time.sleep(.01)
+ initial=ex.get_execution(eid)
+ assert ex._legacy_intent_adopted() and initial['delivery_manifest_pending']==0
+ assert dq.get_status(eid)['status']=='delivering'
+ (barrier/'go').write_text('publish')
+ stdout,stderr=p.communicate(timeout=20);assert p.returncode==0,(stdout,stderr)
+ writer=json.loads(stdout.strip().splitlines()[-1])
+ assert dq.get_status(eid)['status']=='delivered'
+ assert ex.journaled_manifests()[eid]['bot']
+ if replay_first: ex._recover_unrecorded_manifests()
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ after=snap(eid)
+ # Another fresh reader performs restart reconciliation; no cached authority helps.
+ p2=subprocess.run([sys.executable,str(HERE/'_r7_restart_read.py'),str(store),eid],env=_env(),capture_output=True,text=True,timeout=20)
+ assert p2.returncode==0,(p2.stdout,p2.stderr)
+ restarted=json.loads(p2.stdout.strip().splitlines()[-1])
+ print('LATE_PROCESS',json.dumps({'replay_first':replay_first,'writer':writer,'finished':finished,'after':after,'restarted':restarted}))
+ assert restarted['execution']['delivery_outcome']=='queued', 'replayed queued child cannot correct terminal delivered'
+ finally:
+ if p.poll() is None:p.kill();p.wait()
diff --git a/tests/cron/test_r7_salt_transaction_controls.py b/tests/cron/test_r7_salt_transaction_controls.py
new file mode 100644
index 00000000000..36b234f91c4
--- /dev/null
+++ b/tests/cron/test_r7_salt_transaction_controls.py
@@ -0,0 +1,41 @@
+"""Salt R7 transaction/RLock/Q2 controls, ported as regression cells."""
+import json, sqlite3, subprocess, sys
+from pathlib import Path
+import os
+HERE=Path(__file__).resolve().parent
+REPO=next(p for p in HERE.parents if (p/"cron"/"executions.py").exists())
+def _env(**extra):
+ env=dict(os.environ); env["PYTHONPATH"]=str(REPO); env.update(extra); return env
+from cron import executions as ex, incidents
+from tests.cron.test_r5_salt_legacy_and_races import store
+from tests.cron.test_r6_salt_migration_authority import legacy_running
+
+
+def test_incident_upsert_cold_adoption_preserves_outer_transaction(store,monkeypatch,caplog):
+ eid,manifest=legacy_running(store)
+ incident,is_new=incidents.upsert_incident('child-job','r7 script failure',execution_id=eid)
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ binding=conn.execute('SELECT incident_id,incident_generation FROM executions WHERE id=?',(eid,)).fetchone()
+ assert binding[0]==incident and binding[1] is not None
+ assert conn.execute('SELECT count(*) FROM cron_incidents WHERE id=?',(incident,)).fetchone()[0]==1
+ assert conn.execute('SELECT count(*) FROM schema_meta').fetchone()[0]==0
+ # Q2 FIXED: adoption is deferred quietly when the caller owns the transaction (no nested BEGIN attempt).
+ assert 'cannot start a transaction within a transaction' not in caplog.text
+ row=ex.get_execution(eid)
+ assert ex._legacy_intent_adopted() and row['delivery_manifest_pending']==1
+ print('INCIDENT_OUTER_TRANSACTION',json.dumps({'binding':binding,'new':is_new,'adopted_on_next_open':True}))
+
+
+def test_pending_with_null_manifest_is_reachable_and_must_stay_queued(store):
+ # Modern producer marks BEFORE it can store any manifest.
+ row=ex.create_execution('null-pending',source='r7');eid=row['id']
+ ex.mark_delivery_manifest_pending(eid)
+ assert ex.get_execution(eid)['delivery_manifest'] is None
+ p=subprocess.Popen([sys.executable,str(Path(__file__).with_name('_r7_exit_child.py'))],env=_env());p.wait()
+ with sqlite3.connect(ex.EXECUTIONS_FILE) as conn:
+ conn.execute("UPDATE executions SET process_id='exited-r7',pid=?,process_started_at=NULL WHERE id=?",(p.pid,eid))
+ assert ex.recover_interrupted_executions()==1
+ row=ex.get_execution(eid)
+ print('NULL_PENDING',json.dumps(row))
+ assert row['delivery_manifest'] is None and row['delivery_manifest_pending']==1
+ assert row['delivery_outcome']=='queued' and row['status']=='unknown'
diff --git a/tests/cron/test_r8_salt_race_probes.py b/tests/cron/test_r8_salt_race_probes.py
new file mode 100644
index 00000000000..b4445c63c82
--- /dev/null
+++ b/tests/cron/test_r8_salt_race_probes.py
@@ -0,0 +1,174 @@
+"""Salt R8 probes (after-stat writer barriers, K2d replay-between-stat-and-write, stat failure matrix, reopen predicate, CAS), ported as regression cells."""
+import errno, json, os, sqlite3, subprocess, sys, time
+from pathlib import Path
+import pytest
+from cron import executions as ex, delivery_queue as dq, jobs
+from tests.cron.test_r5_salt_legacy_and_races import store, prior, receipt, snap, set_receipt
+from tests.cron.test_r6_salt_migration_authority import legacy_running
+HERE=Path(__file__).resolve().parent
+REPO=next(p for p in HERE.parents if (p/'cron'/'executions.py').exists())
+def _env(**extra):
+ env=dict(os.environ); env['PYTHONPATH']=str(REPO); env.update(extra); return env
+
+def child(mode,store,eid):
+ p=subprocess.run([sys.executable,str(HERE/'_r8_child.py'),mode,str(store),eid],env=_env(),capture_output=True,text=True,timeout=25)
+ assert p.returncode==0,(p.stdout,p.stderr)
+ return json.loads(p.stdout.strip().splitlines()[-1])
+
+def adopted(store):
+ eid,manifest=legacy_running(store)
+ (ex._journal_root()/f'{eid}.json').unlink()
+ assert ex.get_execution(eid)['delivery_manifest_pending']==0
+ assert ex._legacy_intent_adopted()
+ old=prior(); old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ return eid,manifest,old
+
+def wait(path,p):
+ deadline=time.monotonic()+20
+ while not path.exists():
+ assert p.poll() is None and time.monotonic()<deadline
+ time.sleep(.005)
+
[email protected]('publish_at',[1,2])
+def test_writer_after_absent_stat_before_external_completes(store,monkeypatch,publish_at):
+ old=prior();old.EXECUTIONS_FILE=ex.EXECUTIONS_FILE
+ eid=old.create_execution('child-job',source='r8-barrier')['id']
+ old.record_delivery_manifest(eid,{'external':True})
+ with old._transaction() as conn:conn.execute('UPDATE executions SET process_id=? WHERE id=?',(ex._PROCESS_ID,eid))
+ jobs.save_jobs([{'id':'child-job','enabled':False,'schedule':{'kind':'interval','minutes':60},'delivery_execution_id':eid,'last_delivery_queued':{'gateway':{'status':'queued'}}}])
+ dq.enqueue(eid,{'id':'child-job'},'evidence')
+ barrier=store/'barrier';barrier.mkdir()
+ p=subprocess.Popen([sys.executable,str(HERE/'_r8_child.py'),'writer',str(store),eid,str(barrier)],env=_env(),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
+ try:
+ wait(barrier/'ready',p)
+ assert ex.get_execution(eid)['delivery_manifest_pending']==0
+ original=ex._journal_entry_state;calls=[]
+ def stat_then_publish(key):
+ state=original(key); calls.append(state)
+ if len(calls)==publish_at:
+ assert state is False
+ (barrier/'publish').write_text('go');wait(barrier/'published',p)
+ assert dq.get_status(eid)['status']=='delivering'
+ return state
+ with monkeypatch.context() as m:
+ m.setattr(ex,'_journal_entry_state',stat_then_publish)
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ assert finished['delivery_outcome']=='queued'
+ (barrier/'complete').write_text('go')
+ stdout,stderr=p.communicate(timeout=20);assert p.returncode==0,(stdout,stderr)
+ restarted=child('read',store,eid)
+ print('AFTER_STAT',json.dumps({'publish_at':publish_at,'stats':calls,'finished':finished,'restart':restarted}))
+ assert restarted['execution']['delivery_outcome']=='queued'
+ assert restarted['execution']['delivery_projection_settled']==0
+ assert restarted['job']['last_delivery_queued']
+ finally:
+ if p.poll() is None:p.kill();p.wait()
+
+
[email protected]('schedule',['before_stat','during_stat'])
+def test_replay_between_stat_and_finish_intent_does_not_strand_complete_manifest(store,monkeypatch,schedule):
+ eid,manifest,old=adopted(store)
+ old.journal_manifest(eid,manifest)
+ if schedule=='before_stat': child('replay',store,eid)
+ original=ex._journal_entry_state; observed=[]; transaction_states=[]
+ original_fetch=ex._fetch
+ def traced_fetch(conn,key):
+ transaction_states.append(conn.in_transaction)
+ return original_fetch(conn,key)
+ monkeypatch.setattr(ex,'_fetch',traced_fetch)
+ def after_stat(key):
+ result=original(key)
+ if not observed:
+ assert result is True
+ replay=child('replay',store,eid)
+ assert replay['execution']['delivery_manifest_pending']==0
+ assert json.loads(replay['execution']['delivery_manifest'])['bot']
+ observed.append(replay)
+ return result
+ with monkeypatch.context() as m:
+ m.setattr(ex,'_journal_entry_state',after_stat)
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ before=snap(eid)
+ # Actual queue claim/settle implementation; only owner discovery and final turn are doubles.
+ from cron import bot_chat_delivery as bot, scheduler_delivery as sd
+ from tools import bot_live_delivery as live
+ sends=[]
+ with monkeypatch.context() as m:
+ m.setattr(live,'find_canonical_owner',lambda home:None)
+ def delivered(*args,**kwargs):sends.append(kwargs['deferred']['id']);return None
+ m.setattr(sd,'_deliver_to_bot_chat',delivered)
+ bot._drain(bot._root())
+ assert len(sends)==1
+ assert bot.read_pending(next(iter(manifest['bot'].values()))['delivery_id'])['status']=='settled'
+ restarted=child('read',store,eid)
+ print('REPLAY_DURING_STAT',json.dumps({'schedule':schedule,'transaction_states':transaction_states,'replay':observed,'finished':finished,'before':before,'restart':restarted}))
+ assert restarted['execution']['delivery_outcome']=='delivered', 'late adoption reasserted pending on a complete manifest and stranded settlement'
+ assert restarted['execution']['delivery_manifest_pending']==0
+ assert restarted['execution']['delivery_projection_settled']==1
+
[email protected]('shape',['directory_no_search','entry_no_read','missing_root','eio','bot_no_probe'])
+def test_stat_failure_matrix(store,monkeypatch,shape):
+ eid,manifest,old=adopted(store)
+ root=ex._journal_root(); path=root/f'{eid}.json'
+ expected={'directory_no_search':None,'entry_no_read':True,'missing_root':False,'eio':None}
+ old.journal_manifest(eid,manifest)
+ try:
+ if shape=='directory_no_search':root.chmod(0o600)
+ elif shape=='entry_no_read':path.chmod(0)
+ elif shape=='missing_root':path.unlink();root.rmdir()
+ elif shape=='eio':
+ original=Path.stat
+ def fail(p,*a,**kw):
+ if p==path:raise OSError(errno.EIO,'injected stat I/O error')
+ return original(p,*a,**kw)
+ monkeypatch.setattr(Path,'stat',fail)
+ else:
+ ex.record_delivery_manifest(eid,manifest)
+ def forbidden(*a):raise AssertionError('bot-complete row probed journal')
+ monkeypatch.setattr(ex,'_journal_entry_state',forbidden)
+ assert ex._late_legacy_intent(ex.get_execution(eid)) is False
+ return
+ state=ex._journal_entry_state(eid)
+ assert state is expected[shape]
+ with monkeypatch.context() as m:
+ m.setattr(ex,'_recover_unrecorded_manifests',lambda:{})
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ print('STAT_MATRIX',shape,json.dumps({'state':state,'finished':finished}))
+ assert finished['delivery_outcome']==('delivered' if state is False else 'queued')
+ assert finished['delivery_manifest_pending']==int(state is True)
+ finally:
+ if shape=='directory_no_search':root.chmod(0o700)
+ if shape=='entry_no_read':path.chmod(0o600)
+
[email protected]('outcome',['suppressed','not_configured','unknown','delivered','failed'])
[email protected]('complete',[False,True])
+def test_reopen_predicate(store,outcome,complete):
+ eid,manifest,old=adopted(store)
+ if complete:ex.record_delivery_manifest(eid,{'bot':{},'delivered':True})
+ with ex._transaction() as conn:
+ conn.execute("UPDATE executions SET status='completed',delivery_outcome=?,delivery_projection_settled=1 WHERE id=?",(outcome,eid))
+ old.journal_manifest(eid,manifest)
+ ex._recover_unrecorded_manifests()
+ row=ex.get_execution(eid)
+ should_reopen=not complete and outcome in ('delivered','failed')
+ print('REOPEN_PREDICATE',outcome,complete,json.dumps(row))
+ assert row['delivery_outcome']==('queued' if should_reopen else outcome)
+ assert row['delivery_projection_settled']==(0 if should_reopen else 1)
+
+
+def test_finish_adopted_flag_blocks_stale_reconciler_before_replay(store,monkeypatch):
+ eid,manifest,old=adopted(store)
+ stale=ex.get_execution(eid)
+ projection=ex._delivery_projection(stale);assert projection[0]=='delivered'
+ old.journal_manifest(eid,manifest)
+ with monkeypatch.context() as m:
+ m.setattr(ex,'_recover_unrecorded_manifests',lambda:{})
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ assert finished['delivery_manifest_pending']==1
+ m.setattr(ex,'_delivery_projection',lambda record: projection)
+ ex.reconcile_delivery_projections()
+ row=ex.get_execution(eid)
+ print('CAS_AFTER_FINISH',json.dumps(row))
+ assert row['delivery_outcome']=='queued' and row['delivery_projection_settled']==0
+ assert row['delivery_manifest_pending']==1
+ assert jobs.get_job('child-job')['last_delivery_queued']
diff --git a/tests/cron/test_r9_salt_finish_truth.py b/tests/cron/test_r9_salt_finish_truth.py
new file mode 100644
index 00000000000..5746f797c32
--- /dev/null
+++ b/tests/cron/test_r9_salt_finish_truth.py
@@ -0,0 +1,87 @@
+"""Salt R9 probes (K2e finish truth after lost adoption, S7 non-canonical placeholder replay convergence), ported as regression cells."""
+import json, os, subprocess, sys
+from pathlib import Path
+import pytest
+from cron import executions as ex, jobs, bot_chat_delivery as bot
+from tests.cron.test_r5_salt_legacy_and_races import store, snap
+from tests.cron.test_r8_salt_race_probes import adopted, child
+
+def drain(monkeypatch, error=None):
+ from cron import scheduler_delivery as sd
+ from tools import bot_live_delivery as live
+ calls=[]
+ with monkeypatch.context() as m:
+ m.setattr(live,'find_canonical_owner',lambda home:None)
+ def send(*args,**kwargs):calls.append(kwargs['deferred']['id']);return error
+ m.setattr(sd,'_deliver_to_bot_chat',send)
+ bot._drain(bot._root())
+ assert len(calls)==1
+
[email protected]('schedule',['before_stat','during_stat'])
[email protected]('error',[None,'independent downstream failure'])
+def test_complete_row_fallback_truth(store,monkeypatch,schedule,error):
+ eid,manifest,old=adopted(store);old.journal_manifest(eid,manifest)
+ if schedule=='before_stat':child('replay',store,eid)
+ original=ex._journal_entry_state;seen=[]
+ def barrier(key):
+ state=original(key)
+ if not seen:
+ assert state is True
+ seen.append(child('replay',store,eid))
+ return state
+ with monkeypatch.context() as m:
+ m.setattr(ex,'_journal_entry_state',barrier)
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ before=snap(eid)
+ assert before['execution']['delivery_manifest_pending']==0
+ assert 'bot' in json.loads(before['execution']['delivery_manifest'])
+ assert bot.read_pending(next(iter(manifest['bot'].values()))['delivery_id'])['status']=='queued'
+ drain(monkeypatch,error)
+ restarted=child('read',store,eid)
+ expected='unknown' if error else 'delivered'
+ print('FALLBACK_TRUTH',json.dumps(dict(schedule=schedule,error=error,finished=finished,before=before,restart=restarted,expected=expected)))
+ checks={'queued_before_child':before['execution']['delivery_outcome']=='queued',
+ 'truth_after_restart':restarted['execution']['delivery_outcome']==expected,
+ 'projection_settled':restarted['execution']['delivery_projection_settled']==1}
+ assert all(checks.values()), checks
+
[email protected]('replacement',[{'external':True},{'external':True,'delivered':False}])
+def test_replaced_placeholder_adoption_and_replay(store,monkeypatch,replacement):
+ eid,manifest,old=adopted(store);old.journal_manifest(eid,manifest)
+ original=ex._journal_entry_state;seen=[]
+ def barrier(key):
+ state=original(key)
+ if not seen:
+ ex.record_delivery_manifest(eid,replacement)
+ seen.append(ex.get_execution(eid))
+ return state
+ with monkeypatch.context() as m:
+ m.setattr(ex,'_journal_entry_state',barrier)
+ m.setattr(ex,'_recover_unrecorded_manifests',lambda:{})
+ finished=ex.finish_execution(eid,success=True,delivery_outcome='queued')
+ assert finished['delivery_manifest_pending']==1
+ drain(monkeypatch)
+ restarts=[child('read',store,eid) for _ in range(2)]
+ print('REPLACEMENT',json.dumps(dict(replacement=replacement,seen=seen,finished=finished,restarts=restarts)))
+ assert restarts[-1]['execution']['delivery_outcome']=='delivered', 'shape accepted for adoption is rejected by manifest replacement CAS'
+ assert restarts[-1]['execution']['delivery_manifest_pending']==0
+ assert restarts[-1]['execution']['delivery_projection_settled']==1
+
[email protected]('existing',[{'external':True},{'external':True,'delivered':False}])
+def test_projection_only_replay_converges(store,monkeypatch,existing):
+ eid,manifest,old=adopted(store)
+ ex.record_delivery_manifest(eid,existing)
+ old.journal_manifest(eid,manifest)
+ row=ex.get_execution(eid)
+ assert row['delivery_manifest_pending']==0
+ assert ex._delivery_projection(row) is None
+ assert ex.get_execution(eid)['delivery_manifest_pending']==0
+ # Fixture terminal run, not a projection stub: projection is a read-only function.
+ with ex._transaction() as conn:
+ conn.execute("UPDATE executions SET status='completed', delivery_outcome='queued' WHERE id=?",(eid,))
+ drain(monkeypatch)
+ first=child('read',store,eid);second=child('read',store,eid)
+ print('PROJECTION_REPLAY',json.dumps(dict(existing=existing,first=first,second=second)))
+ assert second['execution']['delivery_manifest_pending']==0
+ assert second['execution']['delivery_outcome']=='delivered'
+ assert second['execution']['delivery_projection_settled']==1
diff --git a/tests/cron/test_warning_delivery_policy.py b/tests/cron/test_warning_delivery_policy.py
new file mode 100644
index 00000000000..0db63f5d42d
--- /dev/null
+++ b/tests/cron/test_warning_delivery_policy.py
@@ -0,0 +1,54 @@
+"""Failure classification survives durable delivery and drain-time policy changes."""
+from unittest.mock import patch
+
+import pytest
+
+from cron import delivery_queue, scheduler
+from cron.scheduler_delivery import _deliver_result
+
+
[email protected](autouse=True)
+def configured_transport():
+ from gateway.config import GatewayConfig, Platform, PlatformConfig
+ config = GatewayConfig()
+ config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)
+ with patch("gateway.config.load_gateway_config", return_value=config):
+ yield
+
+
[email protected]("suppress", [False, True])
+def test_failure_queue_settles_without_claiming_a_suppressed_send(tmp_path, monkeypatch, suppress):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(delivery_queue, "DELIVERY_DB", tmp_path / "queue.db")
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: false}\n")
+ job = {"id": "fixture", "name": "fixture", "deliver": "telegram:chat", "execution_id": "run"}
+ delivery_queue.enqueue("run", job, "arbitrary diagnostic", for_failure=True)
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}\n")
+ with patch("cron.scheduler_delivery._deliver_standalone") as send:
+ assert scheduler.drain_delivery_queue({}, None) == 1
+ row = delivery_queue.get_status("run")
+ assert row["status"] == ("suppressed" if suppress else "delivered")
+ assert send.call_count == (0 if suppress else 1)
+ assert scheduler.drain_delivery_queue({}, None) == 0
+
+
+def test_success_content_and_explicit_destination_override_survive(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("display:\n suppress_warning_notifications: true\n platforms:\n telegram:\n suppress_warning_notifications: false\n")
+ job = {"id": "fixture", "deliver": "telegram:chat"}
+ with patch("cron.scheduler_delivery._deliver_standalone") as send:
+ assert _deliver_result(job, "warning quoted in requested result", for_failure=False) is None
+ assert _deliver_result(job, "diagnostic", for_failure=True) is None
+ assert send.call_count == 2
+
+
+def test_mixed_target_queue_is_not_reported_wholly_suppressed(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(delivery_queue, "DELIVERY_DB", tmp_path / "queue.db")
+ (tmp_path / "config.yaml").write_text("display:\n suppress_warning_notifications: true\n platforms:\n telegram:\n suppress_warning_notifications: false\n")
+ job = {"id": "fixture", "deliver": ["slack:muted", "telegram:allowed"]}
+ delivery_queue.enqueue("mixed", job, "diagnostic", for_failure=True)
+ with patch("cron.scheduler_delivery._deliver_standalone") as send:
+ assert scheduler.drain_delivery_queue({}, None) == 1
+ assert send.call_count == 1
+ assert delivery_queue.get_status("mixed")["status"] == "delivered"
diff --git a/tests/cron/test_warning_execution_outcome.py b/tests/cron/test_warning_execution_outcome.py
new file mode 100644
index 00000000000..fd362912393
--- /dev/null
+++ b/tests/cron/test_warning_execution_outcome.py
@@ -0,0 +1,60 @@
+"""Suppressed automatic diagnostics retain failed jobs without invented delivery receipts."""
+import pytest
+
+from cron import executions, incidents, jobs, scheduler
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+
+
[email protected]("mode", ["failure", "crash", "success"])
[email protected]("suppress", [False, True])
[email protected]("external_worker", [False, True])
+def test_real_run_ledger_and_incident_match_actual_presentation(tmp_path, monkeypatch, mode, suppress, external_worker):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(
+ f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}\n"
+ )
+ config = GatewayConfig()
+ config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)
+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
+ sent = []
+
+ async def send(platform, pconfig, chat_id, text, **kwargs):
+ sent.append(text)
+ return {"success": True, "message_id": "receipt"}
+
+ monkeypatch.setattr("tools.send_message_tool._send_to_platform", send)
+
+ def run(job, **kwargs):
+ if mode == "crash":
+ raise RuntimeError("isolated provider failure")
+ return (mode == "success", "retained raw output", "required result", None if mode == "success" else "isolated provider failure")
+
+ monkeypatch.setattr(scheduler, "run_job", run)
+ job = jobs.create_job(prompt="fixture only", schedule="every 1h", deliver="telegram:fixture")
+ if external_worker:
+ from cron import delivery_queue
+ execution = executions.create_execution(job["id"], source="fixture")
+ job["execution_id"] = execution["id"]
+ monkeypatch.setenv("_HERMES_CRON_EXTERNAL_WORKER", execution["id"])
+ original_wait = delivery_queue.enqueue_and_wait
+
+ def drain_before_wait(execution_id, job, content, *, for_failure=False):
+ delivery_queue.enqueue(execution_id, job, content, for_failure=for_failure)
+ assert scheduler.drain_delivery_queue({}, None) == 1
+ return original_wait(execution_id, job, content, for_failure=for_failure)
+
+ monkeypatch.setattr(delivery_queue, "enqueue_and_wait", drain_before_wait)
+ scheduler.run_one_job(job)
+ row = executions.latest_execution(job["id"])
+ expected_suppression = suppress and mode != "success"
+ assert len(sent) == (0 if expected_suppression else 1)
+ assert row["delivery_outcome"] == ("suppressed" if expected_suppression else "delivered")
+ saved = jobs.get_job(job["id"])
+ assert saved["last_status"] == ("ok" if mode == "success" else "error")
+ if mode != "success":
+ assert "isolated provider failure" in saved["last_error"]
+ incident = next(i for i in incidents.list_incidents() if i["job_id"] == job["id"])
+ assert incident["state"] == ("detected" if suppress else "alerted")
+ if mode != "crash":
+ outputs = list((tmp_path / "cron" / "output" / job["id"]).glob("*.md"))
+ assert outputs and "retained raw output" in outputs[0].read_text()
diff --git a/tests/cron/test_warning_transport_contract.py b/tests/cron/test_warning_transport_contract.py
new file mode 100644
index 00000000000..f46b3f955ec
--- /dev/null
+++ b/tests/cron/test_warning_transport_contract.py
@@ -0,0 +1,92 @@
+"""Real cron router/queue with local transport doubles; no external network."""
+import asyncio
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from cron import delivery_queue, scheduler
+from cron.scheduler_delivery import _deliver_result
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+
+
+def loop_thread():
+ loop = asyncio.new_event_loop()
+ started = threading.Event()
+
+ def run():
+ asyncio.set_event_loop(loop)
+ loop.call_soon(started.set)
+ loop.run_forever()
+
+ thread = threading.Thread(target=run)
+ thread.start()
+ assert started.wait(5)
+ yield loop
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join(5)
+ assert not thread.is_alive()
+ loop.close()
+
+
[email protected]("lane", ["native", "relay", "native-fallback", "relay-failure", "standalone", "standalone-async"])
[email protected]("setting,for_failure", [(None, True), (False, True), (True, True), (True, False)])
+def test_warning_policy_at_real_transport_boundary(tmp_path, monkeypatch, loop_thread, lane, setting, for_failure):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(delivery_queue, "DELIVERY_DB", tmp_path / "delivery.db")
+ config_text = "cron: {wrap_response: false}\n"
+ if setting is not None:
+ config_text += f"display: {{suppress_warning_notifications: {str(setting).lower()}}}\n"
+ (tmp_path / "config.yaml").write_text(config_text)
+ config = GatewayConfig()
+ config.platforms[Platform.DISCORD] = PlatformConfig(enabled=True)
+ config.platforms[Platform.RELAY] = PlatformConfig(enabled=True)
+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
+ sent = []
+ fallbacks = []
+
+ async def send(chat_id, content, metadata=None):
+ sent.append(("discord", chat_id, content))
+ if lane == "native-fallback":
+ raise RuntimeError("isolated live failure")
+ return {"success": True, "message_id": "native-id"}
+
+ async def relay_send(platform, chat_id, content, metadata=None):
+ sent.append((platform.value, chat_id, content))
+ if lane == "relay-failure":
+ raise RuntimeError("isolated relay failure")
+ return {"success": True, "message_id": "relay-id"}
+
+ async def standalone(platform, pconfig, chat_id, content, **kwargs):
+ fallbacks.append((platform.value, chat_id, content))
+ return {"success": True, "message_id": "direct-id"}
+
+ monkeypatch.setattr("tools.send_message_tool._send_to_platform", standalone)
+ adapter = SimpleNamespace(send=send, send_for_platform=relay_send,
+ fronts_platform=lambda p: p == Platform.DISCORD)
+ adapters = {} if lane.startswith("standalone") else {
+ Platform.RELAY if lane.startswith("relay") else Platform.DISCORD: adapter}
+ job = {"id": "fixture", "execution_id": "run", "deliver": "discord:fixture"}
+ payload = "Requested warning quotation" if not for_failure else "Automatic failure notice"
+ delivery_queue.enqueue("run", job, payload, for_failure=for_failure)
+
+ def drain():
+ assert scheduler.drain_delivery_queue(adapters, loop_thread) == 1
+
+ if lane == "standalone-async":
+ async def inside_loop():
+ drain()
+ asyncio.run(inside_loop())
+ else:
+ drain()
+ muted = setting is True and for_failure
+ assert sent == ([] if muted or lane.startswith("standalone") else [("discord", "fixture", payload)])
+ assert fallbacks == ([] if muted or lane not in ("standalone", "standalone-async", "native-fallback") else [("discord", "fixture", payload)])
+ expected = "suppressed" if muted else "failed" if lane == "relay-failure" else "delivered"
+ assert delivery_queue.get_status("run")["status"] == expected
+ # Duplicate category and policy changes cannot overwrite durable SQL queue outcomes.
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: false}\n")
+ delivery_queue.enqueue("run", job, payload, for_failure=not for_failure)
+ assert scheduler.drain_delivery_queue(adapters, loop_thread) == 0
+ assert delivery_queue.get_status("run")["status"] == expected
diff --git a/tests/gateway/relay/test_relay_prompt_ack_stream_isolation.py b/tests/gateway/relay/test_relay_prompt_ack_stream_isolation.py
index 515ee39f312..304b706569c 100644
--- a/tests/gateway/relay/test_relay_prompt_ack_stream_isolation.py
+++ b/tests/gateway/relay/test_relay_prompt_ack_stream_isolation.py
@@ -87,6 +87,17 @@ async def _open_turn_draft(a, chat_id="D01", draft_id=7):
class TestPromptAckDoesNotSealDraft:
+ @pytest.mark.asyncio
+ async def test_explicit_destination_diagnostic_is_interim_at_both_egress_doors(self):
+ a = _adapter()
+ key = await _open_turn_draft(a)
+ await a.send("D01", "diagnostic", metadata={
+ "_interim_send": True, "_relay_logical_platform": "slack"})
+ assert key in a._open_draft_by_chat
+ assert a._transport.frames[-1][0]["op"] == "send"
+ await a.send("D01", "requested final")
+ assert key not in a._open_draft_by_chat
+
@pytest.mark.asyncio
async def test_prompt_response_handler_does_not_block_on_ack_send(self):
"""Live finding round 2 (rc.4): _consume_prompt_response runs ON the
diff --git a/tests/gateway/test_api_notification_outcomes.py b/tests/gateway/test_api_notification_outcomes.py
new file mode 100644
index 00000000000..30e17ab50f1
--- /dev/null
+++ b/tests/gateway/test_api_notification_outcomes.py
@@ -0,0 +1,200 @@
+"""Diagnostic presentation does not rewrite execution evidence or next-turn callbacks."""
+import copy
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from gateway.config import PlatformConfig
+from gateway.platforms.api_server import APIServerAdapter, _ProviderAuthResolutionError
+
+
[email protected]("setting", [None, False, True])
[email protected]("category", ["diagnostic", "result"])
+async def test_notification_projection_preserves_source_outcome(tmp_path, monkeypatch, setting, category):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("{}" if setting is None else
+ f"display: {{suppress_warning_notifications: {str(setting).lower()}}}\n")
+ adapter = APIServerAdapter(PlatformConfig(enabled=True))
+ source = {"final_response": "execution evidence", "completed": False, "failed": True,
+ "error": "failure details", "messages": [{"role": "assistant", "content": "execution evidence"}]}
+ expected = copy.deepcopy(source)
+ agent = MagicMock()
+ agent.session_id = "session"
+ agent._last_compaction_in_place = False
+ agent.session_prompt_tokens = 3
+ agent.session_completion_tokens = 4
+ agent.session_total_tokens = 7
+ delivered = []
+ callback = lambda text: delivered.append(text)
+ agent.stream_delta_callback = callback
+
+ def run(**kwargs):
+ if agent.stream_delta_callback:
+ agent.stream_delta_callback("execution evidence")
+ return source
+
+ agent.run_conversation.side_effect = run
+ finished = []
+ finish = adapter._finish_turn_result
+
+ def record_finish(agent, result, *args, **kwargs):
+ finished.append(copy.deepcopy(result))
+ return finish(agent, result, *args, **kwargs)
+
+ with patch.object(adapter, "_create_agent", return_value=agent), patch.object(adapter, "_finish_turn_result", side_effect=record_finish):
+ result, usage = await adapter._run_agent("internal event", [], session_id="session", notification_category=category)
+ muted = setting is True and category == "diagnostic"
+ assert finished == [expected]
+ assert source["final_response"] == expected["final_response"]
+ assert result["final_response"] == "execution evidence"
+ assert bool(result.get("_notification_presentation_suppressed")) is muted
+ assert result["failed"] is True and result["error"] == "failure details"
+ assert result["messages"] == expected["messages"]
+ assert usage == {"input_tokens": 3, "output_tokens": 4, "total_tokens": 7}
+ assert delivered == ([] if muted else ["execution evidence"])
+ assert agent.stream_delta_callback is callback
+ assert adapter._inflight_agent_runs == 0
+ assert adapter._shutdown_interruptible_agents == {}
+
+
[email protected]("setting", [None, False, True])
+async def test_pre_agent_auth_diagnostic_obeys_policy_without_losing_logs(tmp_path, monkeypatch, caplog, setting):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("{}" if setting is None else
+ f"display: {{suppress_warning_notifications: {str(setting).lower()}}}\n")
+ adapter = APIServerAdapter(PlatformConfig(enabled=True))
+ with patch.object(adapter, "_create_agent", side_effect=_ProviderAuthResolutionError("fixture unavailable")):
+ result, usage = await adapter._run_agent("internal event", [], session_id="session", notification_category="diagnostic")
+ assert "fixture unavailable" in result["final_response"]
+ assert bool(result.get("_notification_presentation_suppressed")) is (setting is True)
+ assert "fixture unavailable" in caplog.text
+ assert result["api_calls"] == 0 and usage["total_tokens"] == 0
+ assert adapter._inflight_agent_runs == 0
+
+
[email protected]("stream", [False, True])
[email protected]("setting", [None, False, True])
+async def test_http_diagnostic_projection_keeps_source_and_terminal_flags(tmp_path, monkeypatch, stream, setting):
+ from aiohttp import web
+ from aiohttp.test_utils import TestClient, TestServer
+ import json
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("{}" if setting is None else
+ f"display: {{suppress_warning_notifications: {str(setting).lower()}}}\n")
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={"key": "test-local-key"}))
+ app = web.Application()
+ app.router.add_post("/v1/chat/completions", adapter._handle_chat_completions)
+ source = {"final_response": "private diagnostic evidence", "completed": False, "partial": True,
+ "failed": False, "error": "private diagnostic detail", "messages": []}
+ agent = MagicMock()
+ agent.session_id = "session"
+ agent._last_compaction_in_place = False
+ agent.session_prompt_tokens = 3
+ agent.session_completion_tokens = 4
+ agent.session_total_tokens = 7
+
+ def create(**kwargs):
+ agent.stream_delta_callback = kwargs.get("stream_delta_callback")
+ return agent
+
+ def run(**kwargs):
+ if agent.stream_delta_callback:
+ agent.stream_delta_callback("private diagnostic evidence")
+ return source
+
+ agent.run_conversation.side_effect = run
+ with patch.object(adapter, "_create_agent", side_effect=create):
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post("/v1/chat/completions", headers={
+ "Authorization": "Bearer test-local-key", "X-Hermes-Session-Id": "session"}, json={
+ "messages": [{"role": "user", "content": "background diagnostic"}],
+ "stream": stream, "hermes_notification_category": "diagnostic"})
+ wire = await response.text()
+ assert response.status == 200, wire
+ assert source["final_response"] == "private diagnostic evidence"
+ assert source["error"] == "private diagnostic detail"
+ if setting is True:
+ assert "private diagnostic" not in wire
+ else:
+ assert "private diagnostic evidence" in wire
+ if stream:
+ frames = [json.loads(line[6:]) for line in wire.splitlines()
+ if line.startswith("data: ") and line != "data: [DONE]"]
+ terminal = frames[-1]
+ assert terminal["choices"][0]["finish_reason"] == "error"
+ assert terminal["hermes"]["partial"] is True
+ assert terminal["usage"]["total_tokens"] == 7
+ else:
+ body = json.loads(wire)
+ assert body["choices"][0]["finish_reason"] == "error"
+ assert body["hermes"]["partial"] is True
+ assert body["usage"]["total_tokens"] == 7
+
+
[email protected]("stream", [False, True])
[email protected]("setting", [None, False, True])
+async def test_http_unhandled_diagnostic_error_is_quiet_but_failed(tmp_path, monkeypatch, caplog, stream, setting):
+ from aiohttp import web
+ from aiohttp.test_utils import TestClient, TestServer
+ import json
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("{}" if setting is None else
+ f"display: {{suppress_warning_notifications: {str(setting).lower()}}}\n")
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={"key": "test-local-key"}))
+ app = web.Application()
+ app.router.add_post("/v1/chat/completions", adapter._handle_chat_completions)
+ with patch.object(adapter, "_create_agent", side_effect=RuntimeError("private constructor failure")):
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post("/v1/chat/completions", headers={
+ "Authorization": "Bearer test-local-key", "X-Hermes-Session-Id": "session"}, json={
+ "messages": [{"role": "user", "content": "background diagnostic"}],
+ "stream": stream, "hermes_notification_category": "diagnostic"})
+ wire = await response.text()
+ assert response.status == (200 if stream else 500), wire
+ assert "private constructor failure" in caplog.text
+ assert ("private constructor failure" in wire) is (setting is not True)
+ if stream:
+ frames = [json.loads(line[6:]) for line in wire.splitlines()
+ if line.startswith("data: ") and line != "data: [DONE]"]
+ assert frames[-1]["choices"][0]["finish_reason"] == "error"
+ assert frames[-1]["hermes"]["failed"] is True
+ assert adapter._inflight_agent_runs == 0
+
+
[email protected]("categories", [("diagnostic", "result"), ("result", "diagnostic")])
+async def test_http_idempotency_does_not_replay_opposite_presentation(tmp_path, monkeypatch, categories):
+ from aiohttp import web
+ from aiohttp.test_utils import TestClient, TestServer
+ from gateway.platforms.api_server import _IdempotencyCache
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr("gateway.platforms.api_server._idem_cache", _IdempotencyCache())
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}\n")
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={"key": "test-local-key"}))
+ app = web.Application()
+ app.router.add_post("/v1/chat/completions", adapter._handle_chat_completions)
+ agent = MagicMock()
+ agent.session_id = "session"
+ agent._last_compaction_in_place = False
+ agent.session_prompt_tokens = agent.session_completion_tokens = agent.session_total_tokens = 0
+ agent.run_conversation.side_effect = lambda **kwargs: {"final_response": "required result", "messages": []}
+ with patch.object(adapter, "_create_agent", return_value=agent):
+ async with TestClient(TestServer(app)) as client:
+ for category in categories:
+ body = {"messages": [{"role": "user", "content": "event"}],
+ "hermes_notification_category": category}
+ for repeat in range(2):
+ response = await client.post("/v1/chat/completions", headers={
+ "Authorization": "Bearer test-local-key", "X-Hermes-Session-Id": "session",
+ "Idempotency-Key": "same-key"}, json=body)
+ wire = await response.json()
+ assert response.status == 200, wire
+ assert wire["choices"][0]["message"]["content"] == ("" if category == "diagnostic" else "required result")
+ assert agent.run_conversation.call_count == 2
diff --git a/tests/gateway/test_api_server_compaction_projection.py b/tests/gateway/test_api_server_compaction_projection.py
index 8a45d5410f7..b38534d4149 100644
--- a/tests/gateway/test_api_server_compaction_projection.py
+++ b/tests/gateway/test_api_server_compaction_projection.py
@@ -192,6 +192,26 @@ class TestTurnTranscriptProjection:
class TestMessagesEndpointProjection:
+ @pytest.mark.asyncio
+ async def test_suppressed_delegation_row_keeps_evidence_but_not_presentation(self, adapter, session_db, tmp_path, monkeypatch):
+ from gateway.wake import persist_delegation_delivery
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}")
+ sid = session_db.create_session("diagnostic-projection", "api_server")
+ event = {"delegation_id": "early-failure", "task_failure_notice": True,
+ "results": [{"task_index": 0, "status": "failed"}]}
+ await persist_delegation_delivery(adapter, text="recorded worker failure", session_id=sid, evt=event)
+ await persist_delegation_delivery(adapter, text="recorded worker failure", session_id=sid, evt=event)
+ stored = session_db.get_messages(sid)
+ assert len(stored) == 1 and stored[0]["content"] == "recorded worker failure"
+ async with TestClient(TestServer(_messages_app(adapter))) as client:
+ response = await client.get(f"/api/sessions/{sid}/messages")
+ assert response.status == 200
+ payload = await response.json()
+ assert len(payload["data"]) == 1
+ assert payload["data"][0]["content"] == ""
+ assert payload["data"][0]["display_kind"] == "hidden"
+
@pytest.mark.asyncio
async def test_messages_endpoint_never_serves_compaction_scaffolding(
self,
diff --git a/tests/gateway/test_base_warning_owner_scope.py b/tests/gateway/test_base_warning_owner_scope.py
new file mode 100644
index 00000000000..d3adf41199d
--- /dev/null
+++ b/tests/gateway/test_base_warning_owner_scope.py
@@ -0,0 +1,267 @@
+"""Composed delivery policy: real profile files, runner scopes and adapter transport."""
+import asyncio
+import sys
+import threading
+import types
+from pathlib import Path
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, ProcessingOutcome, SendResult
+from gateway.platforms.event import MessageEvent
+from gateway.run import GatewayRunner
+from hermes_constants import get_hermes_home
+
+
+class RecordingAdapter(BasePlatformAdapter):
+ def __init__(self):
+ super().__init__(PlatformConfig(enabled=True, typing_indicator=False), Platform.TELEGRAM)
+ self.wire = []
+ self.attempts = []
+ self.completed = []
+ self.fail_text_once = False
+ self.fail_media = False
+
+ async def connect(self, *, is_reconnect=False):
+ return True
+
+ async def disconnect(self):
+ pass
+
+ async def get_chat_info(self, chat_id):
+ return {"id": chat_id}
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ self.attempts.append((content, get_hermes_home()))
+ if self.fail_text_once:
+ self.fail_text_once = False
+ return SendResult(success=False, error="invalid markup")
+ self.wire.append((content, get_hermes_home(), metadata))
+ return SendResult(success=True, message_id=f"sent-{len(self.wire)}")
+
+ async def send_document(self, chat_id, file_path, **kwargs):
+ self.attempts.append((file_path, get_hermes_home()))
+ if self.fail_media:
+ return SendResult(success=False, error="transport rejected attachment")
+ return await super().send_document(chat_id, file_path, **kwargs)
+
+ async def on_processing_complete(self, event, outcome):
+ self.completed.append((event.text, outcome))
+
+
+def profiles(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ root = tmp_path / ".hermes"
+ homes = {name: root / "profiles" / name for name in ("a", "b")}
+ root.mkdir()
+ # Opposite to the routed opt-in profile; ambient reads must not decide delivery.
+ (root / "config.yaml").write_text("display: {suppress_warning_notifications: false}\n")
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ for home in homes.values():
+ home.mkdir(parents=True)
+ return root, homes
+
+
[email protected]("setting", [None, False, True])
[email protected]("lane", ["text", "media", "error"])
+async def test_post_handler_delivery_uses_owner_profile(profiles, monkeypatch, setting, lane, caplog):
+ import agent.secret_scope as secret_scope
+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)
+ root, homes = profiles
+ for name, home in homes.items():
+ value = setting if name == "a" else not bool(setting)
+ config = "{}\n" if value is None else (
+ f"display: {{suppress_warning_notifications: {str(value).lower()}}}\n")
+ (home / "config.yaml").write_text(config)
+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=True))
+ adapter = RecordingAdapter()
+ adapter.gateway_runner = runner
+ runner.adapters = {Platform.TELEGRAM: adapter}
+ artifact = root / "result.pdf"
+ artifact.write_bytes(b"test attachment")
+ observed = []
+
+ async def handler(event):
+ # The real runner scope exits before BasePlatformAdapter delivers the result.
+ with runner._media_delivery_scope_for_source(event.source):
+ observed.append(get_hermes_home())
+ if lane == "error":
+ raise RuntimeError("provider detail retained in logs")
+ if lane == "media":
+ return f"MEDIA:{artifact}"
+ return "⚠️ Error budget is the requested task result"
+
+ adapter.set_message_handler(handler)
+ for name in ("a", "b", "a"):
+ suppressed = (setting is True) if name == "a" else not bool(setting)
+ source = adapter.build_source(chat_id="42", user_id="42")
+ source.profile = name
+ event = MessageEvent(text=f"request-{name}", source=source, message_id=f"{lane}-{len(observed)}")
+ adapter.wire.clear()
+ adapter.attempts.clear()
+ adapter.fail_text_once = lane == "text"
+ adapter.fail_media = lane == "media"
+ await adapter._process_message_background(event, f"agent:{name}:telegram:dm:42")
+ assert get_hermes_home() == root
+ assert event.internal is False
+ assert event.allow_gateway_control is True
+ assert observed[-1] == homes[name]
+ if lane == "text":
+ expected = "⚠️ Error budget is the requested task result"
+ if not suppressed:
+ expected = "(Response formatting failed, plain text:)\n\n" + expected
+ assert [row[0] for row in adapter.wire] == [expected]
+ assert adapter.completed[-1][1] is ProcessingOutcome.SUCCESS
+ elif lane == "error":
+ assert len(adapter.wire) == 1 # requested task still has a truthful outcome
+ text = adapter.wire[0][0]
+ if suppressed:
+ assert text == "Sorry, I encountered an error."
+ else:
+ assert "provider detail retained in logs" in text
+ assert adapter.completed[-1][1] is ProcessingOutcome.FAILURE
+ else:
+ assert bool(adapter.wire) is not suppressed
+ assert adapter.completed[-1][1] is ProcessingOutcome.FAILURE
+ assert all(home == homes[name] for _, home in adapter.attempts)
+ assert all(row[1] == homes[name] for row in adapter.wire)
+ assert len(observed) == 3
+ assert {"text": "trying plain-text fallback", "media": "transport rejected attachment",
+ "error": "provider detail retained in logs"}[lane] in caplog.text
+
+
[email protected]("diagnostic_first", [False, True])
[email protected]("setting", [None, False, True])
+async def test_recursive_three_turn_chain_then_human(profiles, monkeypatch, diagnostic_first, setting):
+ """Real runner recursion and final-event handoff, not a copied mute snapshot."""
+ import gateway.run as gateway_run
+ from gateway.session import SessionSource
+
+ root, _ = profiles
+ monkeypatch.setattr(gateway_run, "_hermes_home", root)
+ (root / "config.yaml").write_text(
+ "display: {tool_progress: off, streaming: false" +
+ ("}" if setting is None else f", suppress_warning_notifications: {str(setting).lower()}}}")
+ )
+ from gateway.config import HomeChannel
+ config = GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(
+ enabled=True, home_channel=HomeChannel(platform=Platform.TELEGRAM, chat_id="42", name="test"))})
+ runner = GatewayRunner(config)
+ adapter = RecordingAdapter()
+ adapter.gateway_runner = runner
+ runner.adapters = {Platform.TELEGRAM: adapter}
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="42", user_id="42")
+ key = runner._session_key_for_source(source)
+ events = [MessageEvent(
+ text=f"turn-{i}", source=source, message_id=f"inbound-{i}",
+ internal=(diagnostic_first if i % 2 == 0 else not diagnostic_first),
+ metadata={"notification_category": "diagnostic"},
+ ) for i in range(3)]
+ # An untrusted category in metadata is deliberately present on human inputs.
+ events.append(MessageEvent(text="next human", source=source, message_id="inbound-next",
+ metadata={"notification_category": "diagnostic"}))
+ original_authority = [(e.internal, e.allow_gateway_control) for e in events]
+ calls = []
+ loop = asyncio.get_running_loop()
+
+ class ScriptedAgent:
+ def __init__(self, **kwargs):
+ self.tools = []
+
+ def run_conversation(self, message, conversation_history=None, task_id=None, **kwargs):
+ calls.append(message)
+ index = len(calls) - 1
+ if index < 2:
+ ready = threading.Event()
+ def enqueue():
+ adapter._pending_messages[key] = events[index + 1]
+ ready.set()
+ loop.call_soon_threadsafe(enqueue)
+ assert ready.wait(5), "event loop did not admit queued turn"
+ return {"final_response": f"result-{index}", "messages": [], "api_calls": 1}
+
+ fake = types.ModuleType("run_agent")
+ fake.AIAgent = ScriptedAgent
+ monkeypatch.setitem(sys.modules, "run_agent", fake)
+ monkeypatch.setattr(gateway_run, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "test-key"})
+ # No platform credentials: authorize the fixture identity at the auth backend,
+ # retaining admission, generation/lease lifecycle and queued-result handoff.
+ authorized = []
+ def authorize(source, **kwargs):
+ authorized.append(source.user_id)
+ return source.user_id == "42"
+ runner._is_user_authorized_for_source = authorize
+ adapter.set_message_handler(runner._handle_message)
+ try:
+ await adapter._process_message_background(events[0], key)
+ assert len(calls) == 3, (calls, adapter.wire)
+ expected = [f"result-{i}" for i in range(3)
+ if not (setting is True and original_authority[i][0])]
+ assert [row[0] for row in adapter.wire] == expected
+ await adapter._process_message_background(events[3], key)
+ assert len(calls) == 4
+ assert [row[0] for row in adapter.wire] == expected + ["result-3"]
+ assert [(e.internal, e.allow_gateway_control) for e in events] == original_authority
+ assert authorized[-1] == "42" # next human still crosses authorization
+ denied = MessageEvent(
+ text="⚠️ diagnostic-looking human input", internal=False,
+ source=SessionSource(platform=Platform.TELEGRAM, chat_id="group", chat_type="group",
+ user_id="denied"),
+ metadata={"notification_category": "diagnostic", "_notification_reply_muted": True})
+ before = list(adapter.wire)
+ await adapter._process_message_background(denied, runner._session_key_for_source(denied.source))
+ assert authorized[-1] == "denied"
+ assert len(calls) == 4 and adapter.wire == before
+ assert denied.internal is False and denied.allow_gateway_control is True
+ assert get_hermes_home() == root
+ finally:
+ await adapter.cancel_background_tasks()
+
+
[email protected]("setting", [None, False, True])
[email protected]("diagnostic", [False, True])
+async def test_turn_error_preserves_diagnostic_bridge_and_failed_outcome(
+ profiles, monkeypatch, setting, diagnostic, caplog):
+ import logging
+ from types import SimpleNamespace
+ from agent.monitoring import gateway_health
+ root, _ = profiles
+ (root / "config.yaml").write_text(
+ "{}" if setting is None else
+ f"display: {{suppress_warning_notifications: {str(setting).lower()}}}")
+ emitted = []
+ monkeypatch.setattr(gateway_health.emitter, "get_emitter",
+ lambda: SimpleNamespace(emit=emitted.append))
+ logger = logging.getLogger("gateway.platforms.base")
+ bridge = gateway_health.GatewayDiagnosticLogHandler(profile="fixture", version="fixture")
+ logger.addHandler(bridge)
+ adapter = RecordingAdapter()
+ async def handler(event):
+ raise RuntimeError("same source failure")
+ adapter.set_message_handler(handler)
+ source = adapter.build_source(chat_id="42", user_id="42")
+ event = MessageEvent(text="work", source=source, internal=diagnostic,
+ metadata={"notification_category": "diagnostic"})
+ try:
+ key = "agent:default:telegram:dm:42"
+ assert adapter._start_session_processing(event, key)
+ await adapter._session_tasks[key]
+ assert adapter.completed[-1][1] is ProcessingOutcome.FAILURE
+ assert "same source failure" in caplog.text
+ errors = [e for e in emitted if e.name == "gateway.log.error"]
+ assert len(errors) == 1
+ assert errors[0].severity == "error" and errors[0].profile == "fixture"
+ if diagnostic and setting is True:
+ assert adapter.wire == []
+ else:
+ assert len(adapter.wire) == 1
+ assert ("same source failure" in adapter.wire[0][0]) is (setting is not True)
+ assert not adapter._active_sessions
+ finally:
+ logger.removeHandler(bridge)
+ await adapter.cancel_background_tasks()
diff --git a/tests/gateway/test_compress_command.py b/tests/gateway/test_compress_command.py
index 7797f232df1..bc82ec3aad2 100644
--- a/tests/gateway/test_compress_command.py
+++ b/tests/gateway/test_compress_command.py
@@ -105,11 +105,15 @@ async def test_compress_command_works_when_auto_compaction_disabled():
@pytest.mark.asyncio
-async def test_compress_command_surfaces_aux_model_failure_even_when_recovered():
[email protected]("warning_notifications", [True, False])
+async def test_compress_command_surfaces_aux_model_failure_even_when_recovered(tmp_path, monkeypatch, warning_notifications):
"""When the user's configured ``auxiliary.compression.model`` errors out
but compression recovers by retrying on the main model, /compress must
STILL inform the user. Silent recovery hides broken config the user
needs to fix."""
+ import gateway.run as gateway_run
+ (tmp_path / "config.yaml").write_text(f"display: {{warning_notifications: {str(warning_notifications).lower()}}}")
+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)
history = _make_history()
# Compressed transcript — normal successful compression, no placeholder.
compressed = [
diff --git a/tests/gateway/test_cron_interrupt_notification.py b/tests/gateway/test_cron_interrupt_notification.py
index 0784d7bf9ed..f2d6c56fecd 100644
--- a/tests/gateway/test_cron_interrupt_notification.py
+++ b/tests/gateway/test_cron_interrupt_notification.py
@@ -77,6 +77,25 @@ class TestNotifyInterruptedCronJobs:
assert "hermes cron run daily-digest" in body
assert adapter.sent_calls[0][0] == "123456"
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("setting", [None, False, True])
+ async def test_interrupt_notice_is_a_suppressible_diagnostic(self, tmp_path, monkeypatch, setting):
+ import json
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ cfg = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+ runner, adapter = make_restart_runner()
+ _bind_notifier(runner)
+ job = _telegram_job()
+ with patch("cron.jobs.get_job", return_value=job), \
+ patch("cron.scheduler._resolve_delivery_targets",
+ return_value=[_telegram_target()]):
+ sent = await runner._notify_interrupted_cron_jobs([job["id"]])
+ expected = 0 if setting is True else 1
+ assert sent == expected
+ assert len(adapter.sent) == expected
+
@pytest.mark.asyncio
async def test_says_restarting_when_restart_was_requested(self):
runner, adapter = make_restart_runner()
diff --git a/tests/gateway/test_diagnostic_wake_presentation.py b/tests/gateway/test_diagnostic_wake_presentation.py
new file mode 100644
index 00000000000..6894c451083
--- /dev/null
+++ b/tests/gateway/test_diagnostic_wake_presentation.py
@@ -0,0 +1,52 @@
+"""Diagnostic-only wakes execute while their unsolicited free-form reply stays private."""
+import asyncio
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, SendResult
+from gateway.platforms.event import MessageEvent
+from gateway.session import SessionSource
+
+
+class Adapter(BasePlatformAdapter):
+ async def connect(self, **kwargs):
+ return True
+
+ async def disconnect(self):
+ pass
+
+ async def get_chat_info(self, chat_id):
+ return {"name": "fixture", "type": "dm"}
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ self.sent.append(content)
+ return SendResult(success=True, message_id="sent")
+
+
[email protected]("suppressed", [False, True])
+async def test_diagnostic_wake_executes_without_final_or_error_echo(tmp_path, monkeypatch, suppressed):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(suppressed).lower()}}}")
+ adapter = Adapter(PlatformConfig(enabled=True), Platform.TELEGRAM)
+ adapter.sent = []
+ adapter._start_typing_refresh = lambda *a: None
+ adapter._stop_typing_refresh = AsyncMock()
+ adapter._run_processing_hook = AsyncMock()
+ adapter._fire_post_delivery_callback = AsyncMock()
+ adapter._flush_text_debounce_now = AsyncMock()
+ adapter._finish_session_task = lambda *a: None
+ adapter.send_final_ledgered = AsyncMock(return_value=(SendResult(success=True), adapter))
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="chat")
+ event = MessageEvent(text="internal diagnostic", source=source, internal=True,
+ metadata={"notification_category": "diagnostic"})
+ adapter._message_handler = AsyncMock(return_value="I repeat the technical diagnostic")
+ await adapter._process_message_background(event, "session")
+ assert adapter._message_handler.await_count == 1
+ assert adapter.send_final_ledgered.await_count == (0 if suppressed else 1)
+ adapter._message_handler = AsyncMock(side_effect=RuntimeError("provider detail"))
+ await adapter._process_message_background(event, "session")
+ assert bool(adapter.sent) is not suppressed
+ assert adapter._run_processing_hook.await_args.args[-1].value == "failure"
diff --git a/tests/gateway/test_display_null_turn_wiring.py b/tests/gateway/test_display_null_turn_wiring.py
index 19bcec8145f..33cbaefed90 100644
--- a/tests/gateway/test_display_null_turn_wiring.py
+++ b/tests/gateway/test_display_null_turn_wiring.py
@@ -32,6 +32,8 @@ def _wire(user_config):
_status_adapter=None,
session_key="",
user_config=user_config,
+ source=types.SimpleNamespace(platform="telegram"),
+ mute_notification_reply=False,
_thinking_enabled=False,
agent_holder=[None],
tools_holder=[None],
diff --git a/tests/gateway/test_exec_approval_timeout_notice.py b/tests/gateway/test_exec_approval_timeout_notice.py
index 14dcb3a2af6..952a25fb914 100644
--- a/tests/gateway/test_exec_approval_timeout_notice.py
+++ b/tests/gateway/test_exec_approval_timeout_notice.py
@@ -77,7 +77,11 @@ def pending_entry(monkeypatch):
_approval._gateway_queues.pop(SESSION, None)
-def test_timeout_edits_the_card_to_say_the_command_did_not_run(pending_entry):
[email protected]("warning_notifications", [True, False])
+def test_timeout_edits_the_card_to_say_the_command_did_not_run(pending_entry, tmp_path, monkeypatch, warning_notifications):
+ import gateway.run as gateway_run
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(not warning_notifications).lower()}}}")
+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)
adapter = _ButtonAdapter()
_runner(adapter)._approval_notify_sync(dict(pending_entry.data)) # what notify_cb receives
diff --git a/tests/gateway/test_gateway_silence_tokens.py b/tests/gateway/test_gateway_silence_tokens.py
index 1242d98afa9..4f5a6c8bd64 100644
--- a/tests/gateway/test_gateway_silence_tokens.py
+++ b/tests/gateway/test_gateway_silence_tokens.py
@@ -171,6 +171,7 @@ async def test_queued_human_turn_also_gets_the_visible_fallback():
turn_ctx = SimpleNamespace(
session_key="agent:main:telegram:group:-1001:12345",
stream_consumer_holder=[None],
+ mute_notification_reply=False,
persist_user_display_kind=None,
source=_source(),
_status_thread_metadata=None,
@@ -203,7 +204,7 @@ async def test_queued_terminal_turn_owns_the_silence_verdict(monkeypatch, tmp_pa
run_generation=1, _interrupt_depth=0, history=[], _status_thread_metadata=None,
context_prompt=None, result_holder=[None])
pending_event = SimpleNamespace(source=_source(), message_id="43", channel_prompt=None,
- message_type=None, internal=True)
+ message_type=None, internal=True, metadata={})
merged = await gateway_run.GatewayRunner._run_agent_queued_followup(
runner, turn_ctx, adapter=None, pending="hi again", pending_event=pending_event,
diff --git a/tests/gateway/test_grid_sweep_gateway_diagnostics.py b/tests/gateway/test_grid_sweep_gateway_diagnostics.py
new file mode 100644
index 00000000000..786180ee836
--- /dev/null
+++ b/tests/gateway/test_grid_sweep_gateway_diagnostics.py
@@ -0,0 +1,135 @@
+"""Code-flow grid sweep (NOUS-368, wave 1): three pre-existing automatic gateway diagnostics that
+bypassed the warning boundary. absent/false = legacy bytes; true suppresses ONLY the diagnostic;
+requested outcomes (an in-chat /restart's own ack, the requested background result) are untouched."""
+from __future__ import annotations
+
+import json
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from gateway.config import HomeChannel, Platform
+from gateway.pairing import PairingStore
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource, build_session_key
+from tests.gateway.restart_test_helpers import make_restart_runner, make_restart_source
+
+
+def _configure(tmp_path, monkeypatch, setting):
+ home = tmp_path / f"home-{setting}"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ display = {} if setting is None else {"suppress_warning_notifications": setting}
+ (home / "config.yaml").write_text(json.dumps({"display": display}))
+ return home
+
+
+MODES = (None, False, True)
+
+
[email protected]("setting", MODES)
+async def test_shutdown_notice_to_active_chats_and_home_channel_honors_policy(tmp_path, monkeypatch, setting):
+ _configure(tmp_path, monkeypatch, setting)
+ runner, adapter = make_restart_runner()
+ source = make_restart_source(thread_id="42")
+ session_key = build_session_key(source)
+ runner._running_agents = {session_key: MagicMock()}
+ runner._cache_session_source(session_key, source)
+ runner.config.platforms[Platform.TELEGRAM].home_channel = HomeChannel(
+ platform=Platform.TELEGRAM, chat_id="home-chat", name="Telegram Home")
+
+ await runner._notify_active_sessions_of_shutdown()
+
+ chats = [c for c, _m, _meta in adapter.sent_calls]
+ if setting is True:
+ assert chats == [], adapter.sent_calls
+ else:
+ assert sorted(chats) == sorted([source.chat_id, "home-chat"])
+ assert all("Hermes is shutting down" in m for _c, m, _meta in adapter.sent_calls)
+
+
+async def test_in_chat_restart_ack_to_requester_is_never_suppressed(tmp_path, monkeypatch):
+ _configure(tmp_path, monkeypatch, True)
+ runner, adapter = make_restart_runner()
+ source = make_restart_source(thread_id="42")
+ session_key = build_session_key(source)
+ runner._running_agents = {session_key: MagicMock()}
+ runner._cache_session_source(session_key, source)
+ restart_source = make_restart_source(thread_id="42")
+ restart_source.message_id = "restart-command"
+ runner._restart_requested = True
+ runner._restart_command_source = restart_source
+ runner.config.platforms[Platform.TELEGRAM].home_channel = HomeChannel(
+ platform=Platform.TELEGRAM, chat_id="home-chat", name="Telegram Home")
+
+ await runner._notify_active_sessions_of_shutdown()
+
+ assert len(adapter.sent_calls) == 1
+ chat_id, message, metadata = adapter.sent_calls[0]
+ assert chat_id == source.chat_id and "Hermes is restarting" in message
+ assert metadata["telegram_reply_to_message_id"] == "restart-command"
+
+
[email protected]("setting", MODES)
+async def test_unauthorized_owner_hint_honors_policy_and_stranger_stays_silent(tmp_path, monkeypatch, setting):
+ _configure(tmp_path, monkeypatch, setting)
+ runner, adapter = make_restart_runner()
+ runner.pairing_store = PairingStore()
+ runner.pairing_stores = {}
+ runner.config.platforms[Platform.TELEGRAM].home_channel = HomeChannel(
+ platform=Platform.TELEGRAM, chat_id="home-1", name="Ops")
+ runner._hm_report_ignored_dm = GatewayRunner._hm_report_ignored_dm.__get__(runner, GatewayRunner)
+ stranger = SessionSource(platform=Platform.TELEGRAM, chat_id="dm-777", user_id="777", user_name="Eve", chat_type="dm")
+
+ await runner._hm_report_ignored_dm(stranger)
+ await runner._hm_report_ignored_dm(stranger)
+
+ chats = [c for c, _m, _meta in adapter.sent_calls]
+ assert "dm-777" not in chats
+ assert chats.count("home-1") == (0 if setting is True else 1)
+ assert runner.pairing_store.list_pending("telegram") == []
+
+
+def _bg_runner():
+ from tests.gateway.test_background_command import _make_runner
+ return _make_runner()
+
+
[email protected]("setting", MODES)
+async def test_background_task_failure_notice_honors_policy(tmp_path, monkeypatch, setting):
+ _configure(tmp_path, monkeypatch, setting)
+ runner = _bg_runner()
+ from gateway.platforms.base import BasePlatformAdapter
+ adapter = MagicMock(spec=BasePlatformAdapter)
+ adapter.send = AsyncMock()
+ adapter.emit_warning = BasePlatformAdapter.emit_warning.__get__(adapter, BasePlatformAdapter)
+ adapter.warning_notifications_enabled = BasePlatformAdapter.warning_notifications_enabled.__get__(adapter, BasePlatformAdapter)
+ adapter.platform = Platform.TELEGRAM
+ runner.adapters[Platform.TELEGRAM] = adapter
+ source = SessionSource(platform=Platform.TELEGRAM, user_id="1", chat_id="c1", user_name="u")
+
+ with patch("gateway.run._resolve_runtime_agent_kwargs", return_value={"api_key": "k"}), \
+ patch.object(runner, "_resolve_session_agent_runtime", side_effect=RuntimeError("BG_REAL_CRASH")):
+ await runner._run_background_task("do the thing", source, "bg_test")
+
+ if setting is True:
+ adapter.send.assert_not_called()
+ else:
+ adapter.send.assert_called_once()
+ args, kwargs = adapter.send.call_args
+ content = kwargs.get("content") or (args[1] if len(args) > 1 else "")
+ assert "failed before finishing" in content
+
+
+async def test_background_task_requested_result_is_never_suppressed(tmp_path, monkeypatch):
+ """Control: a successful background task's requested result is delivered under true."""
+ _configure(tmp_path, monkeypatch, True)
+ from tests.gateway import test_background_command as tbc
+ # Reuse the existing success-path test body under the suppressing config.
+ t = tbc.TestRunBackgroundTask()
+ await t.test_successful_task_sends_result()
diff --git a/tests/gateway/test_hygiene_warning_lifecycle.py b/tests/gateway/test_hygiene_warning_lifecycle.py
new file mode 100644
index 00000000000..bed4657b5d0
--- /dev/null
+++ b/tests/gateway/test_hygiene_warning_lifecycle.py
@@ -0,0 +1,74 @@
+"""Real hygiene turn admission, durable cooldown and notice sink in three modes."""
+import json
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from hermes_state import SessionDB
+from tests.gateway.test_session_hygiene import _make_cooldown_runner
+
+
[email protected]("setting", [None, False, True])
+async def test_aborted_hygiene_retains_cooldown_across_restart_and_final_result(tmp_path, monkeypatch, caplog, setting):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ sid = "hygiene-policy"
+ calls = []
+ recovering = False
+ class CompressorAgent:
+ def __init__(self, **kwargs):
+ self.session_id = kwargs["session_id"]
+ self._session_db = kwargs.get("session_db")
+ self._last_compaction_in_place = False
+ self.context_compressor = SimpleNamespace(
+ bind_session_state=MagicMock(), _last_compress_aborted=True,
+ _last_summary_error="fixture auxiliary failure", _last_aux_model_failure_model=None)
+ self.shutdown_memory_provider = MagicMock()
+ self.close = MagicMock()
+ def _compress_context(self, messages, *args, **kwargs):
+ calls.append(list(messages))
+ if recovering:
+ compacted = [{"role": "user", "content": "retained summary"}]
+ self._session_db.archive_and_compact(self.session_id, compacted)
+ self._session_db.clear_compression_failure_cooldown(self.session_id)
+ self._last_compaction_in_place = True
+ self.context_compressor._last_compress_aborted = False
+ self.context_compressor._last_aux_model_failure_model = "fixture-aux"
+ self.context_compressor._last_aux_model_failure_error = "fixture auxiliary failure"
+ return compacted, None
+ return messages, None
+ db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ db.create_session(sid, "telegram")
+ for iteration in range(2):
+ runner, adapter, event = _make_cooldown_runner(monkeypatch, tmp_path, CompressorAgent, db, sid)
+ cfg = {"compression": {"enabled": True, "hygiene_failure_cooldown_seconds": 300}}
+ if setting is not None:
+ cfg["display"] = {"suppress_warning_notifications": setting}
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+ assert await runner._handle_message(event) == "ok"
+ assert runner._run_agent.await_count == 1
+ warnings = [sent for sent in adapter.sent if "Shortening the conversation history failed" in sent["content"]]
+ assert len(warnings) == (1 if iteration == 0 and setting is not True else 0)
+ assert len(calls) == 1 # fresh runner still obeys persisted cooldown
+ cooldown = db.get_compression_failure_cooldown(sid)
+ assert cooldown and cooldown["remaining_seconds"] > 0
+ runner.session_store.rewrite_transcript.assert_not_called()
+ assert "Session hygiene compression aborted: fixture auxiliary failure" in caplog.text
+ # Let the durable cooldown expire, then exercise actual gateway adoption
+ # of a committed fallback summary (provider compression is the fake edge).
+ recovering = True
+ db.clear_compression_failure_cooldown(sid)
+ runner, adapter, event = _make_cooldown_runner(monkeypatch, tmp_path, CompressorAgent, db, sid)
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+ assert await runner._handle_message(event) == "ok"
+ assert len(calls) == 2
+ assert db.get_compression_failure_cooldown(sid) is None
+ assert all(state.persistent.hygiene_failure_streak == 0 for state in runner._sessions.values())
+ warnings = [sent for sent in adapter.sent if "Configured compression model" in sent["content"]]
+ assert len(warnings) == (0 if setting is True else 1)
+ assert db.get_messages(sid)[-1]["content"] == "retained summary"
+ runner.session_store.rewrite_transcript.assert_not_called()
+ finally:
+ db.close()
diff --git a/tests/gateway/test_kanban_wake_acceptance.py b/tests/gateway/test_kanban_wake_acceptance.py
index c7cb61ac20e..b3046f20a5a 100644
--- a/tests/gateway/test_kanban_wake_acceptance.py
+++ b/tests/gateway/test_kanban_wake_acceptance.py
@@ -148,3 +148,44 @@ async def test_notifier_retries_unaccepted_wake_without_repeating_pings(tmp_path
assert len(adapter.wire) == 2
assert not any(unseen(mode) for mode in tids)
await adapter.disconnect()
+
+
+async def test_suppressed_ping_has_no_sent_receipt_but_wake_executes(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "board.db"))
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}")
+ runner, adapter, source, key = setup_route()
+ conn = kbc.connect()
+ try:
+ tid = kb.create_task(conn, title="failure", assignee="worker", session_id=key)
+ kbn.add_notify_sub(conn, task_id=tid, platform="telegram", chat_id="42",
+ user_id="42", chat_type="dm", delivery_mode="notify+wake")
+ kb.block_task(conn, tid, reason="worker failure", kind="transient")
+ finally:
+ conn.close()
+ work = []
+ async def handler(event):
+ work.append(event)
+ return "technical diagnostic echo"
+ adapter.set_message_handler(handler)
+ await adapter.connect()
+ try:
+ deliveries = await asyncio.to_thread(_notifier_collect, runner, kb,
+ notifier_profile=None, gc_due=False, gc_retention_days=30)
+ for delivery in deliveries:
+ await _KanbanNotification(runner, delivery, platform_cls=Platform,
+ sub_fail_counts={}).deliver()
+ await drain(adapter)
+ assert len(work) == 1
+ assert work[0].metadata["notification_category"] == "diagnostic"
+ assert adapter.wire == []
+ conn = kbc.connect()
+ try:
+ row = conn.execute("SELECT last_ping_event_id, last_event_id FROM kanban_notify_subs WHERE task_id=?", (tid,)).fetchone()
+ assert row["last_ping_event_id"] == 0
+ assert row["last_event_id"] > 0
+ finally:
+ conn.close()
+ finally:
+ await adapter.disconnect()
diff --git a/tests/gateway/test_media_warning_policy.py b/tests/gateway/test_media_warning_policy.py
new file mode 100644
index 00000000000..2587ba8d63c
--- /dev/null
+++ b/tests/gateway/test_media_warning_policy.py
@@ -0,0 +1,92 @@
+"""Adapter warnings are separate from captions, attachment receipts and failed state."""
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, SendResult
+from plugins.platforms.discord.adapter import DiscordAdapter
+from plugins.platforms.slack.adapter import SlackAdapter
+from plugins.platforms.matrix.adapter import MatrixAdapter
+
+
+class LegacyAdapter(BasePlatformAdapter):
+ async def connect(self, **kwargs):
+ return True
+
+ async def disconnect(self):
+ pass
+
+ async def get_chat_info(self, chat_id):
+ return {"name": "fixture", "type": "dm"}
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ self.sent.append((content, reply_to, metadata))
+ return SendResult(success=True, message_id="actual-text-send")
+
+
[email protected]("setting", [None, False, True])
+async def test_media_fallbacks_preserve_default_receipts_and_caption(tmp_path, monkeypatch, setting, caplog):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ if setting is not None:
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(setting).lower()}}}")
+ base = LegacyAdapter(PlatformConfig(), Platform.TELEGRAM)
+ base.sent = []
+ result = await base.send_document("chat", str(tmp_path / "missing"), caption="caption", reply_to="reply", metadata={"thread_id": "thread"})
+ assert result.success is (setting is not True)
+ assert result.message_id == (None if setting is True else "actual-text-send")
+ assert base.sent[0][0] == ("caption" if setting is True else "caption\n⚠️ Couldn't deliver the file attachment.")
+ assert "native file send unavailable" in caplog.text
+ for adapter, invoke in (
+ (SlackAdapter(PlatformConfig()), lambda a: a._send_failure_notice("chat", "caption", "diagnostic", "reply", {"thread_id": "thread"})),
+ (MatrixAdapter(PlatformConfig()), lambda a: a._send_local_file("chat", str(tmp_path / "missing"), "m.file", "caption", "reply")),
+ ):
+ adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="actual-text-send"))
+ outcome = await invoke(adapter)
+ assert outcome.success is (setting is not True)
+ if setting is True:
+ assert adapter.send.call_args.args[1] == "caption"
+ await base._notify_media_delivery_failure("chat", "missing")
+ assert len(base.sent) == (1 if setting is True else 2)
+
+
[email protected]("suppress", [False, True])
+async def test_discord_oversize_and_plain_fallback_keep_material_content(tmp_path, monkeypatch, suppress):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}")
+ adapter = DiscordAdapter(PlatformConfig())
+ adapter._discord_upload_limit_bytes = lambda channel: 1
+ adapter._is_forum_parent = lambda channel: False
+ channel = type("Channel", (), {"send": AsyncMock()})()
+ path = tmp_path / "upload.txt"
+ path.write_bytes(b"too large")
+ result = await adapter._reject_oversized_upload(channel, str(path), path.name)
+ assert not result.success and "too large" in result.error.lower()
+ assert channel.send.await_count == int(not suppress)
+ base = LegacyAdapter(PlatformConfig(), Platform.TELEGRAM)
+ base.sent = []
+ outcome = await base._send_plain_fallback("chat", "requested content", reply_to=None, metadata=None)
+ assert outcome.success
+ assert base.sent[0][0] == ("requested content" if suppress else "(Response formatting failed, plain text:)\n\nrequested content")
+
+
[email protected]("explicit", [False, True])
+async def test_relay_media_diagnostic_uses_logical_destination_without_sealing(tmp_path, monkeypatch, explicit):
+ from tests.gateway.relay.test_relay_prompt_ack_stream_isolation import _adapter, _open_turn_draft
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("display:\n suppress_warning_notifications: false\n platforms:\n slack: {suppress_warning_notifications: true}\n")
+ adapter = _adapter()
+ adapter._platform_by_chat["D01"] = "telegram" if explicit else "slack"
+ metadata = {"_relay_logical_platform": "slack"} if explicit else None
+ key = await _open_turn_draft(adapter)
+ before = list(adapter._transport.frames)
+ await adapter._notify_media_delivery_failure("D01", "missing.pdf", metadata=metadata)
+ assert adapter._transport.frames == before
+ assert key in adapter._open_draft_by_chat
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: false}")
+ await adapter._notify_media_delivery_failure("D01", "missing.pdf", metadata=metadata)
+ assert adapter._transport.frames[-1][0]["op"] == "send"
+ assert key in adapter._open_draft_by_chat
diff --git a/tests/gateway/test_native_producer_owner_matrix.py b/tests/gateway/test_native_producer_owner_matrix.py
new file mode 100644
index 00000000000..8bdeb6104c0
--- /dev/null
+++ b/tests/gateway/test_native_producer_owner_matrix.py
@@ -0,0 +1,117 @@
+"""Native media producers keep routed owner decisions across alternating homes."""
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from gateway.config import GatewayConfig, PlatformConfig
+from gateway.run import GatewayRunner
+from gateway.platforms.base import SendResult
+from hermes_constants import get_hermes_home
+
+
[email protected](params=[None, False, True, "override", "managed", "null"])
+def owners(request, tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ root = tmp_path / ".hermes"
+ root.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ managed = tmp_path / "managed"
+ managed.mkdir()
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))
+ (root / "config.yaml").write_text('display: {suppress_warning_notifications: true}')
+ mode = request.param
+ if mode == "managed":
+ (managed / "config.yaml").write_text('display: {suppress_warning_notifications: true}')
+ for name in ("a", "b"):
+ home = root / "profiles" / name
+ home.mkdir(parents=True)
+ value = mode if name == "a" else not bool(mode)
+ cfg = {} if value is None else {"display": {"suppress_warning_notifications": value is True}}
+ if name == "a" and mode in ("override", "null"):
+ cfg = {"display": {"suppress_warning_notifications": True, "platforms": {
+ p: {"suppress_warning_notifications": False if mode == "override" else None}
+ for p in ("slack", "signal")}}}
+ (home / "config.yaml").write_text(json.dumps(cfg))
+ def suppressed(name):
+ return mode == "managed" or (mode in (True, "null") if name == "a" else not bool(mode))
+ return root, suppressed
+
+
[email protected]("kind", ["image_file", "video", "document"])
+async def test_slack_upload_failure_owner_scope_keeps_caption_and_result(owners, tmp_path, caplog, kind):
+ from plugins.platforms.slack.adapter import SlackAdapter
+ root, suppressed = owners
+ adapter = SlackAdapter(PlatformConfig())
+ adapter.gateway_runner = GatewayRunner(GatewayConfig(multiplex_profiles=True))
+ attempts, wire = [], []
+ async def upload(**kwargs):
+ attempts.append((get_hermes_home(), kwargs))
+ raise RuntimeError("upload rejected")
+ client = SimpleNamespace(files_upload_v2=upload)
+ adapter._app = SimpleNamespace(client=client)
+ adapter._client_for = lambda chat_id, metadata: client
+ adapter._dm_target = AsyncMock(return_value="C123")
+ async def send(chat_id, content, **kwargs):
+ wire.append((get_hermes_home(), content, kwargs))
+ return SendResult(success=True, message_id="fallback")
+ adapter.send = send
+ path = tmp_path / "media.bin"
+ path.write_bytes(b"local bytes")
+ for name in ("a", "b", "a"):
+ source = adapter.build_source(chat_id="C123", user_id="U123")
+ source.profile = name
+ before = len(attempts)
+ with adapter._media_delivery_scope(source):
+ result = await getattr(adapter, "send_" + kind)("C123", str(path), caption="Warning: requested caption", metadata={"thread_id": "123.456"})
+ assert len(attempts) > before
+ assert all(home == root / "profiles" / name for home, _ in attempts[before:])
+ assert wire[-1][0] == root / "profiles" / name
+ assert wire[-1][2]["metadata"] == {"thread_id": "123.456"}
+ assert ("Couldn't deliver" in wire[-1][1]) is not suppressed(name)
+ assert "Warning: requested caption" in wire[-1][1]
+ assert result.success is not suppressed(name)
+ assert result.message_id == (None if suppressed(name) else "fallback")
+ assert get_hermes_home() == root
+ assert "upload rejected" in caplog.text
+
+
+async def test_signal_pacing_owner_scope_keeps_acquisition_and_upload(owners, tmp_path, monkeypatch):
+ import gateway.platforms.signal as module
+ root, suppressed = owners
+ adapter = module.SignalAdapter(PlatformConfig())
+ adapter.gateway_runner = GatewayRunner(GatewayConfig(multiplex_profiles=True))
+ scheduler = SimpleNamespace(state=lambda: {}, estimate_wait=lambda n: 120,
+ acquire=AsyncMock(), report_rpc_duration=AsyncMock())
+ monkeypatch.setattr(module, "get_scheduler", lambda: scheduler)
+ adapter._stop_typing_indicator = AsyncMock()
+ path = tmp_path / "image.png"
+ path.write_bytes(b"image")
+ adapter._resolve_image_path = AsyncMock(return_value=(str(path), None, None))
+ adapter._with_target = AsyncMock(side_effect=lambda params, chat: params)
+ uploads, warnings = [], []
+ async def rpc(method, params, **kwargs):
+ uploads.append((get_hermes_home(), params))
+ return {"timestamp": 123}
+ async def send(*args, **kwargs):
+ warnings.append(get_hermes_home())
+ return SendResult(success=True)
+ adapter._rpc, adapter.send = rpc, send
+ for name in ("a", "b", "a"):
+ source = adapter.build_source(chat_id="recipient", user_id="human")
+ source.profile = name
+ before = len(warnings)
+ with adapter._media_delivery_scope(source):
+ result = await adapter.send_multiple_images("recipient", [(path.as_uri(), "caption")])
+ assert result.success
+ assert len(warnings) - before == (0 if suppressed(name) else 1)
+ if not suppressed(name):
+ assert warnings[-1] == root / "profiles" / name
+ assert uploads[-1][0] == root / "profiles" / name
+ assert uploads[-1][1]["attachments"] == [str(path)]
+ assert get_hermes_home() == root
+ assert scheduler.acquire.await_count == 3
+ assert scheduler.report_rpc_duration.await_count == 3
diff --git a/tests/gateway/test_native_stream_warning_composition.py b/tests/gateway/test_native_stream_warning_composition.py
new file mode 100644
index 00000000000..8215296b9b9
--- /dev/null
+++ b/tests/gateway/test_native_stream_warning_composition.py
@@ -0,0 +1,62 @@
+"""Actual warning callback and media producer beside an armed native Slack stream."""
+import asyncio
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from agent.status_output import StatusOutputMixin
+from gateway.run_turn_runner import TurnRunner
+from gateway.turn_context import TurnContext
+from gateway.session import SessionSource
+from gateway.config import Platform
+from tests.gateway.test_slack_native_streaming import _make_adapter, META
+
+
[email protected]("setting", [None, False, True])
+async def test_warning_and_media_failure_do_not_seal_requested_final(tmp_path, monkeypatch, setting):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ cfg = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+ adapter, client = _make_adapter()
+ first = await adapter.send_draft("D1", 7, "Requested", metadata=META)
+ assert first.success
+ source = SessionSource(platform=Platform.SLACK, chat_id="D1", chat_type="dm", thread_id=META["thread_id"])
+ ctx = TurnContext(source=source, user_config=cfg, _run_still_current=lambda: True,
+ _status_adapter=adapter, _status_chat_id="D1", _status_thread_metadata=dict(META))
+ turn = TurnRunner(SimpleNamespace(), ctx)
+ loop = asyncio.get_running_loop()
+ scheduled = []
+ def schedule(coro, *args):
+ future = asyncio.run_coroutine_threadsafe(coro, loop)
+ scheduled.append(future)
+ return future
+ turn._schedule = schedule
+ agent = StatusOutputMixin()
+ agent.suppress_status_output = True
+ agent.status_callback = turn._status_callback_sync
+ await asyncio.to_thread(agent._warn_uncompressed_context_overflow, 200, 100)
+ await asyncio.gather(*(asyncio.wrap_future(f) for f in scheduled))
+ assert bool(agent._last_ctx_overflow_warn)
+ assert client.chat_postMessage.await_count == (0 if setting is True else 1)
+ assert client.chat_stopStream.await_count == 0
+ # Actual upload producer; only Slack SDK rejects the local file.
+ client.files_upload_v2 = AsyncMock(side_effect=RuntimeError("fixture upload failure"))
+ adapter._client_for = lambda *args: client
+ adapter._dm_target = AsyncMock(return_value="D1")
+ document = tmp_path / "fixture.pdf"
+ document.write_bytes(b"fixture document")
+ media = await adapter.send_document("D1", str(document), metadata={**META, "_interim_send": True})
+ assert media.success is not (setting is True) # legacy text fallback receipt
+ assert client.chat_postMessage.await_count == (0 if setting is True else 2)
+ assert client.chat_stopStream.await_count == 0
+ assert "D1" in adapter._active_streams
+ await adapter.send_draft("D1", 7, "Requested final", metadata=META)
+ result = await adapter.send("D1", "Requested final", metadata=META)
+ assert result.success
+ assert client.chat_startStream.await_count == 1
+ assert client.chat_stopStream.await_count == 1
+ assert "D1" not in adapter._active_streams
+ assert client.chat_postMessage.await_count == (0 if setting is True else 2)
diff --git a/tests/gateway/test_native_warning_coverage.py b/tests/gateway/test_native_warning_coverage.py
new file mode 100644
index 00000000000..8fc180e41aa
--- /dev/null
+++ b/tests/gateway/test_native_warning_coverage.py
@@ -0,0 +1,316 @@
+"""Native diagnostic producers keep captions, controls and truthful receipts.
+
+No live platform connections: actual adapters run against recording transports.
+"""
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import PlatformConfig
+from gateway.platforms.base import SendResult
+from plugins.platforms.buzz.adapter import BuzzAdapter
+from plugins.platforms.discord.adapter import DiscordAdapter
+from plugins.platforms.google_chat.adapter import GoogleChatAdapter
+from plugins.platforms.matrix.adapter import MatrixAdapter
+from plugins.platforms.wecom.adapter import WeComAdapter
+
+
[email protected](params=[None, False, True, "override"])
+def policy(request, tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ setting = request.param
+ if setting is not None:
+ display = {"suppress_warning_notifications": setting is True}
+ if setting == "override":
+ display["platforms"] = {
+ name: {"suppress_warning_notifications": True}
+ for name in ("matrix", "google_chat", "discord", "wecom", "buzz", "mattermost", "feishu", "telegram")
+ }
+ (tmp_path / "config.yaml").write_text(json.dumps({"display": display}))
+ return setting is True or setting == "override"
+
+
[email protected]("caption", [None, "Error: this is the requested caption"])
+async def test_matrix_download_diagnostic_not_caption_is_suppressed(policy, caption, monkeypatch, caplog):
+ adapter = MatrixAdapter(PlatformConfig())
+ frames = []
+
+ async def record(room, event_type, content):
+ frames.append(content)
+ return "$sent"
+
+ adapter._client = SimpleNamespace(send_message_event=record)
+ adapter._download_external_media_with_cap = AsyncMock(side_effect=RuntimeError("download fixture"))
+ monkeypatch.setattr("tools.url_safety.is_safe_url", lambda url: True)
+ result = await adapter.send_image("!room", "https://example.invalid/image?token=private", caption, "$reply", {"thread_id": "$thread"})
+ if policy:
+ assert [f["body"] for f in frames] == ([caption] if caption else [])
+ assert not result.success and result.message_id is None
+ if frames:
+ assert frames[0]["m.relates_to"]["event_id"] == "$thread"
+ else:
+ notice = "I couldn't download and upload the image to Matrix. The source URL was not shown because it may contain private tokens."
+ assert [f["body"] for f in frames] == [f"{caption}\n{notice}" if caption else notice]
+ assert result.success and result.message_id == "$sent"
+ assert "failed to download image" in caplog.text
+
+
[email protected]("caption", [None, "Warning: requested document caption"])
+async def test_google_chat_oauth_fallback_only_hides_diagnostic(policy, caption, tmp_path):
+ adapter = GoogleChatAdapter(PlatformConfig())
+ frames = []
+
+ async def record(chat, body):
+ frames.append(body)
+ return SendResult(success=True, message_id="spaces/test/messages/sent")
+
+ adapter._create_message = record
+ adapter._acquire_user_chat_api = AsyncMock(return_value=(None, None))
+ path = tmp_path / "report.pdf"
+ path.write_bytes(b"fixture")
+ result = await adapter.send_document("spaces/test", str(path), caption=caption, metadata={"thread_id": "spaces/test/threads/thread"})
+ assert not result.success and "OAuth" in result.error
+ if policy:
+ assert [f["text"] for f in frames] == ([caption] if caption else [])
+ else:
+ assert len(frames) == 1 and "/setup-files" in frames[0]["text"]
+ assert str(path) in frames[0]["text"]
+ if caption:
+ assert frames[0]["text"].startswith(caption + "\n")
+ if frames:
+ assert frames[0]["thread"]["name"] == "spaces/test/threads/thread"
+ # An explicit control request must still use the same transport.
+ await adapter.send_clarify("spaces/test", "Continue?", ["yes", "no"], "clarify", "session")
+ assert "cardsV2" in frames[-1]
+
+
[email protected]("method", ["send_document", "send_voice", "send_multiple_images"])
[email protected]("forum", [False, True])
+async def test_discord_rejected_media_preserves_caption_without_fake_receipt(policy, method, forum, tmp_path, caplog):
+ adapter = DiscordAdapter(PlatformConfig())
+ frames = []
+
+ async def record(**payload):
+ frames.append(payload)
+ return SimpleNamespace(id=123, attachments=[])
+
+ async def create_thread(**payload):
+ frames.append(payload)
+ return SimpleNamespace(thread=SimpleNamespace(id=101), message=SimpleNamespace(id=102))
+
+ channel = SimpleNamespace(send=record, id=99, create_thread=create_thread)
+ adapter._client = SimpleNamespace()
+ adapter._resolve_channel = AsyncMock(return_value=channel)
+ adapter._is_forum_parent = lambda channel: forum
+ adapter._discord_upload_limit_bytes = lambda channel: 1
+ path = tmp_path / "large.png"
+ path.write_bytes(b"too large")
+ caption = "Warning: requested caption"
+ if method == "send_multiple_images":
+ result = await adapter.send_multiple_images("99", [(path.as_uri(), caption)])
+ else:
+ result = await getattr(adapter, method)("99", str(path), caption=caption)
+ assert not result.success and result.message_id is None
+ if policy:
+ assert [f["content"] for f in frames] == [caption]
+ elif forum:
+ assert frames == [] # legacy forum rejection sends no notice
+ else:
+ assert len(frames) == 1 and "⚠️" in frames[0]["content"]
+ assert caption not in frames[0]["content"] # preserve legacy default
+ assert "large" in caplog.text
+
+
+async def test_wecom_rejected_media_keeps_caption_and_failed_result(policy):
+ adapter = WeComAdapter(PlatformConfig())
+ frames = []
+
+ async def record(command, body, **kwargs):
+ frames.append(body)
+ return {"errcode": 0, "headers": {"req_id": "sent"}}
+
+ adapter._send_request = record
+ adapter._prepare_outbound_media = AsyncMock(return_value={"rejected": True, "reject_reason": "fixture rejection"})
+ result = await adapter.send_document("chat", "fixture.pdf", caption="Error: requested caption")
+ assert not result.success and result.error == "fixture rejection"
+ assert [f["markdown"]["content"] for f in frames] == (["Error: requested caption"] if policy else ["⚠️ fixture rejection"])
+
+
+async def test_buzz_missing_upload_fallback_and_real_upload_receipts(policy, tmp_path):
+ adapter = BuzzAdapter(PlatformConfig(extra={"cli_path": "fixture-buzz"}))
+ adapter._mention_pubkeys_for = AsyncMock(return_value=[])
+ frames = []
+
+ async def record(args, content, *extra):
+ frames.append((args, content))
+ return 0, json.dumps({"event_id": "a" * 64, "accepted": True}), ""
+
+ adapter._run_message_send = record
+ result = await adapter.send_image_file("chat", str(tmp_path / "missing.png"), caption="requested caption")
+ assert frames[0][1] == ("requested caption" if policy else "requested caption\n⚠️ Couldn't deliver the image attachment.")
+ assert result.success is (not policy)
+ path = tmp_path / "image.png"
+ path.write_bytes(b"fixture")
+ result = await adapter.send_image_file("chat", str(path), caption="⚠️ user caption")
+ assert result.success and result.message_id == "a" * 64
+ assert "--file" in frames[-1][0] and frames[-1][1] == "⚠️ user caption"
+
+
[email protected]("lane", ["send", "edit"])
+async def test_discord_truncation_warning_covers_send_and_final_edit(policy, lane):
+ adapter = DiscordAdapter(PlatformConfig())
+ frames = []
+
+ async def record(**payload):
+ frames.append(payload["content"])
+ return SimpleNamespace(id=123, to_reference=lambda **kwargs: None)
+
+ message = SimpleNamespace(id=123, edit=record, to_reference=lambda **kwargs: None)
+ channel = SimpleNamespace(send=record, get_partial_message=lambda ident: message, id=99)
+ adapter._client = SimpleNamespace()
+ adapter._resolve_channel = AsyncMock(return_value=channel)
+ adapter._is_forum_parent = lambda channel: False
+ adapter._record_response_async = AsyncMock()
+ adapter.MAX_MESSAGE_LENGTH = 80
+ adapter.MAX_SPLIT_MESSAGES = 3
+ text = "Warning: requested result. " * 40
+ if lane == "send":
+ result = await adapter.send("99", text)
+ else:
+ result = await adapter.edit_message("99", "123", text, finalize=True)
+ assert result.success
+ assert frames[0].startswith("Warning: requested result.")
+ assert any("Response truncated" in frame for frame in frames) is (not policy)
+ assert len(frames) == (2 if policy else 3)
+
+
+async def test_wecom_downgrade_preserves_native_upload_and_caption(policy):
+ adapter = WeComAdapter(PlatformConfig())
+ frames = []
+
+ async def record(cmd, body, **kwargs):
+ frames.append((cmd, body))
+ return {"errcode": 0, "body": {"upload_id": "upload", "media_id": "media"}, "headers": {"req_id": "sent"}}
+
+ adapter._send_request = record
+ adapter._load_outbound_media = AsyncMock(return_value=(b"fixture", "audio/ogg", "voice.ogg"))
+ result = await adapter.send_voice("chat", "voice.ogg", caption="Error: user caption")
+ assert result.success
+ assert any(body.get("file", {}).get("media_id") == "media" for _, body in frames)
+ text = [body["markdown"]["content"] for _, body in frames if "markdown" in body]
+ assert text[0] == "Error: user caption"
+ assert len(text) == (1 if policy else 2)
+
+
+async def test_google_chat_revoked_oauth_fallback_uses_same_policy(policy, tmp_path, monkeypatch, caplog):
+ from plugins.platforms.google_chat import adapter as google
+
+ class Revoked(Exception):
+ resp = SimpleNamespace(status=403)
+
+ def fail(**kwargs):
+ raise Revoked("token revoked")
+
+ adapter = GoogleChatAdapter(PlatformConfig())
+ adapter._acquire_user_chat_api = AsyncMock(return_value=(SimpleNamespace(media=lambda: SimpleNamespace(upload=fail)), "owner"))
+ adapter._user_creds_by_email["owner"] = object()
+ adapter._user_chat_api_by_email["owner"] = object()
+ monkeypatch.setattr(google, "HttpError", Revoked)
+ monkeypatch.setattr(google, "MediaFileUpload", lambda *args, **kwargs: object())
+ frames = []
+
+ async def record(chat_id, body):
+ frames.append(body)
+ return SendResult(success=True, message_id="sent")
+
+ adapter._create_message = record
+ path = tmp_path / "file.pdf"
+ path.write_bytes(b"fixture")
+ result = await adapter.send_document("chat", str(path), caption="requested caption")
+ assert not result.success
+ assert "owner" not in adapter._user_creds_by_email
+ assert "owner" not in adapter._user_chat_api_by_email
+ assert "media.upload auth failure" in caplog.text
+ assert frames[0]["text"] == "requested caption" if policy else "/setup-files" in frames[0]["text"]
+
+
+async def test_mattermost_thread_fallback_keeps_requested_result(policy, caplog):
+ from plugins.platforms.mattermost.adapter import MattermostAdapter
+
+ adapter = MattermostAdapter(PlatformConfig(extra={"reply_mode": "thread"}))
+ frames = []
+
+ async def api(method, path, payload=None):
+ frames.append(dict(payload))
+ if "root_id" in payload:
+ adapter._last_post_status = 404
+ adapter._last_post_error = "root_id not found"
+ return {}
+ return {"id": "sent"}
+
+ adapter._api = api
+ adapter._resolve_root_id = AsyncMock(return_value="root")
+ result = await adapter.send("chat", "Error: requested result", metadata={"thread_id": "root", "notify": True})
+ assert result.success
+ assert frames[0]["root_id"] == "root" and "root_id" not in frames[1]
+ expected = "Error: requested result"
+ if not policy:
+ expected = "⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n" + expected
+ assert frames[1]["message"] == expected
+ assert "falling back to flat channel" in caplog.text
+
+
+async def test_feishu_downgrade_keeps_attachment_and_caption(policy, tmp_path):
+ from plugins.platforms.feishu.adapter import FeishuAdapter
+
+ adapter = FeishuAdapter(PlatformConfig())
+ frames = []
+ path = tmp_path / "animation.gif"
+ path.write_bytes(b"fixture")
+ adapter._download_remote_document = AsyncMock(return_value=(str(path), path.name))
+
+ def upload(request):
+ return SimpleNamespace(success=lambda: True, code=0, data=SimpleNamespace(file_key="file-key"))
+
+ async def send_raw(**kwargs):
+ frames.append(kwargs)
+ return SimpleNamespace(success=lambda: True, code=0, data=SimpleNamespace(message_id="sent"))
+
+ adapter._client = SimpleNamespace(im=SimpleNamespace(v1=SimpleNamespace(file=SimpleNamespace(create=upload))))
+ adapter._send_raw_message = send_raw
+ result = await adapter.send_animation("chat", "https://example.invalid/animation.gif", caption="Warning: requested caption")
+ assert result.success
+ assert "file-key" in frames[0]["payload"]
+ assert "Warning: requested caption" in frames[0]["payload"]
+ assert ("GIF downgraded to file" in frames[0]["payload"]) is (not policy)
+
+
+async def test_telegram_cache_warning_does_not_hide_inbound_context(policy):
+ from plugins.platforms.telegram.adapter import TelegramAdapter
+
+ adapter = TelegramAdapter(PlatformConfig())
+ frames = []
+
+ async def reply_text(text):
+ frames.append(text)
+
+ from gateway.platforms.event import MessageEvent
+ event = MessageEvent(text="Requested content", source=adapter.build_source(chat_id="42", user_id="42"))
+ await adapter._surface_media_cache_failure(SimpleNamespace(reply_text=reply_text), event, "photo", RuntimeError("fixture"))
+ assert bool(frames) is (not policy)
+ assert event.text.startswith("Requested content")
+ assert "could not be downloaded" in event.text
+ assert ("asked to retry" in event.text) is (not policy)
diff --git a/tests/gateway/test_queued_final_ledger.py b/tests/gateway/test_queued_final_ledger.py
index 24dc9fbd8c5..22877916331 100644
--- a/tests/gateway/test_queued_final_ledger.py
+++ b/tests/gateway/test_queued_final_ledger.py
@@ -212,7 +212,8 @@ def _chain_runner_and_ctx(followup_return):
_interrupt_depth=0, history=[], _status_thread_metadata={"thread_id": "7"},
context_prompt=None, result_holder=[None])
pending_event = SimpleNamespace(
- source=topic, message_id="6002", channel_prompt=None, message_type=None)
+ source=topic, message_id="6002", channel_prompt=None, message_type=None,
+ internal=False, metadata={})
return GatewayRunner, runner, turn_ctx, pending_event
@@ -239,7 +240,8 @@ async def test_a_chained_queued_turn_carries_its_own_inbound_id():
_interrupt_depth=0, history=[], _status_thread_metadata={"thread_id": "7"},
context_prompt=None, result_holder=[None])
pending_event = SimpleNamespace(
- source=topic, message_id="6002", channel_prompt=None, message_type=None)
+ source=topic, message_id="6002", channel_prompt=None, message_type=None,
+ internal=False, metadata={})
await GatewayRunner._run_agent_queued_followup(
runner, turn_ctx, adapter=None, pending="hi again", pending_event=pending_event,
diff --git a/tests/gateway/test_queued_followup_processing_hooks.py b/tests/gateway/test_queued_followup_processing_hooks.py
index f4c07cbbc8e..0fe2d44993d 100644
--- a/tests/gateway/test_queued_followup_processing_hooks.py
+++ b/tests/gateway/test_queued_followup_processing_hooks.py
@@ -136,6 +136,30 @@ def _install_fake_agent(monkeypatch, tmp_path, agent_cls):
SESSION_KEY = "agent:main:telegram:dm:4242"
[email protected]("diagnostic_last", [False, True])
+async def test_queue_terminal_presentation_belongs_to_last_turn(monkeypatch, tmp_path, diagnostic_last):
+ _TwoTurnAgent.calls = []
+ _install_fake_agent(monkeypatch, tmp_path, _TwoTurnAgent)
+ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ adapter = HookRecordingAdapter()
+ runner = _make_runner(adapter)
+ adapter._pending_messages[SESSION_KEY] = MessageEvent(
+ text="follow-up", source=_source(), internal=diagnostic_last,
+ metadata={"notification_category": "diagnostic"} if diagnostic_last else {}, message_id="queued")
+ result = await runner._run_agent(message="first", context_prompt="", history=[], source=_source(),
+ session_id="queue-policy", session_key=SESSION_KEY,
+ persist_user_display_metadata=None if diagnostic_last else {"notification_category": "diagnostic"})
+ assert _TwoTurnAgent.calls == ["first", "follow-up"]
+ assert result["final_response"] == "done-2"
+ assert result["_notification_reply_muted"] is diagnostic_last
+ from gateway.warning_notifications import diagnostic_wake_muted
+ outer = MessageEvent(text="first", source=_source(), internal=not diagnostic_last)
+ outer._notification_reply_muted = result["_notification_reply_muted"]
+ assert diagnostic_wake_muted(outer) is diagnostic_last
+
+
def _source():
return SessionSource(platform=Platform.TELEGRAM, chat_id="4242", chat_type="dm")
diff --git a/tests/gateway/test_salt_r3_refactor_regressions.py b/tests/gateway/test_salt_r3_refactor_regressions.py
new file mode 100644
index 00000000000..cb76377aac3
--- /dev/null
+++ b/tests/gateway/test_salt_r3_refactor_regressions.py
@@ -0,0 +1,81 @@
+"""Salt R3 B4/S1/S3: refactor regressions reproduced as behavior contracts."""
+import json
+from unittest.mock import AsyncMock, MagicMock
+import pytest
+from gateway.config import Platform
+
+
+def _cfg(tmp_path, monkeypatch, setting):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path)); monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ cfg = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+
+
[email protected]("setting", [None, False, True])
+async def test_discord_forum_caption_identical_to_notice_still_posts(tmp_path, monkeypatch, setting):
+ """B4: text equality is not a policy signal; a requested caption equal to the generated notice travels when hidden."""
+ _cfg(tmp_path, monkeypatch, setting)
+ from plugins.platforms.discord.adapter_media import DiscordMediaMixin
+ from gateway.platforms.base import BasePlatformAdapter
+ class A(DiscordMediaMixin):
+ name = "discord"; platform = Platform.DISCORD
+ warning_notifications_enabled = BasePlatformAdapter.warning_notifications_enabled
+ _discord_upload_limit_bytes = staticmethod(lambda ch: 1)
+ _is_forum_parent = staticmethod(lambda ch: True)
+ _send_to_forum = AsyncMock()
+ a = A(); channel = MagicMock(); channel.send = AsyncMock()
+ big = tmp_path / "big.bin"; big.write_bytes(b"xx")
+ limit_mb = 1 / (1024 * 1024)
+ notice = (f"⚠️ Could not attach `big.bin` — {2/(1024*1024):.1f} MB exceeds Discord's "
+ f"{limit_mb:.0f} MB upload limit for this channel. Compress the file or share a link instead.")
+ res = await a._reject_oversized_upload(channel, str(big), "big.bin", caption=notice)
+ assert res.success is False
+ if setting is True:
+ A._send_to_forum.assert_awaited_once_with(channel, notice) # the CAPTION (identical text) is requested content
+ else:
+ A._send_to_forum.assert_not_awaited(); channel.send.assert_not_awaited() # legacy: no bare notice on forum parents
+
+
+async def test_slack_interim_send_never_seals_prefix_matching_stream(tmp_path, monkeypatch):
+ """S3: an explicit interim warning whose text extends the streamed prefix leaves the final stream open."""
+ _cfg(tmp_path, monkeypatch, None)
+ from plugins.platforms.slack.adapter import SlackAdapter
+ a = SlackAdapter.__new__(SlackAdapter)
+ a._active_streams = {"C1": {"ts": "1.0", "sent": "⚠️"}}
+ a._seal_stream = AsyncMock(return_value=True)
+ a._outbound_blocked = lambda *args: None
+ a._dm_target = AsyncMock(return_value="C1")
+ a._metadata_team_id = lambda m: None
+ a._pop_slash_context = lambda c, t: None
+ a.format_message = lambda c: c
+ a._post_message = AsyncMock(return_value={"ok": True, "ts": "2.0"})
+ a._clear_thread_status_quietly = AsyncMock()
+ a._send_plain = AsyncMock(return_value=MagicMock(success=True))
+ try:
+ await a.send("C1", "⚠️ Couldn't deliver the image attachment.", metadata={"_interim_send": True})
+ except Exception:
+ pass # transport internals beyond the seal decision are not under test
+ a._seal_stream.assert_not_awaited()
+ assert "C1" in a._active_streams
+
+
[email protected]("setting", [None, False])
+async def test_matrix_shown_fallback_routing_is_legacy_bytes(tmp_path, monkeypatch, setting):
+ """S1: legacy shown fallback passed NO metadata; the shared helper must not add thread routing."""
+ _cfg(tmp_path, monkeypatch, setting)
+ from gateway.platforms.base import BasePlatformAdapter, SendResult
+ calls = []
+ class A(BasePlatformAdapter):
+ name = "matrix"; platform = Platform.MATRIX
+ def __init__(self): pass
+ async def connect(self): pass
+ async def disconnect(self): pass
+ async def get_chat_info(self, chat_id): return {}
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ calls.append((content, reply_to, metadata)); return SendResult(success=True)
+ a = A()
+ await a.emit_media_warning("!r", "⚠️ Couldn't deliver the attachment.", caption="cap", reply_to="$e", metadata={"thread_id": "$t"})
+ assert calls == [("cap\n⚠️ Couldn't deliver the attachment.", "$e", None)]
diff --git a/tests/gateway/test_session_db_warning_recheck.py b/tests/gateway/test_session_db_warning_recheck.py
index 973db27e869..dd997a0852f 100644
--- a/tests/gateway/test_session_db_warning_recheck.py
+++ b/tests/gateway/test_session_db_warning_recheck.py
@@ -58,7 +58,10 @@ def _runner_with_startup_failure(monkeypatch, clock: _Clock, *, heals: bool):
return runner, sent
-def test_lock_that_cleared_before_connect_is_not_broadcast(monkeypatch):
[email protected]("warning_notifications", [True, False])
+def test_lock_that_cleared_before_connect_is_not_broadcast(monkeypatch, tmp_path, warning_notifications):
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(not warning_notifications).lower()}}}")
+ monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)
clock = _Clock()
runner, sent = _runner_with_startup_failure(monkeypatch, clock, heals=True)
asyncio.run(runner._send_session_db_warning_notifications())
diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.py
index 19d2e6f1227..440bc54a98f 100644
--- a/tests/gateway/test_session_hygiene.py
+++ b/tests/gateway/test_session_hygiene.py
@@ -493,13 +493,15 @@ async def test_session_hygiene_preserves_transcript_when_in_place_configured_but
@pytest.mark.asyncio
-async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monkeypatch, tmp_path):
[email protected]("warning_notifications", [True, False])
+async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monkeypatch, tmp_path, warning_notifications):
"""A timed-out SessionDB-bound worker cannot compact after the live turn starts.
The worker remains alive long enough to cross the old race window. The
timeout must fence its eventual commit, continue to the live agent, and
clean up the temporary agent only after the worker actually returns.
"""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
fake_dotenv = types.ModuleType("dotenv")
fake_dotenv.load_dotenv = lambda *args, **kwargs: None
monkeypatch.setitem(sys.modules, "dotenv", fake_dotenv)
@@ -559,6 +561,7 @@ async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monk
" enabled: true\n"
" hygiene_timeout_seconds: 0.01\n"
" hygiene_failure_cooldown_seconds: 120\n"
+ f"display: {{suppress_warning_notifications: {str(not warning_notifications).lower()}}}\n"
)
gateway_run = importlib.import_module("gateway.run")
@@ -631,7 +634,7 @@ async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monk
assert _cd_args[0] == "sess-timeout"
assert _cd_args[1] > time.time()
timeout_warnings = [s for s in adapter.sent if "took too long" in s["content"]]
- assert len(timeout_warnings) == 1
+ assert len(timeout_warnings) == int(warning_notifications)
fake_db.archive_and_compact.assert_not_called()
assert lease_released.is_set()
# Event/state assertions prove the host returned before the detached
diff --git a/tests/gateway/test_session_stall_watchdog.py b/tests/gateway/test_session_stall_watchdog.py
index 2a49893a465..6e57ab80efe 100644
--- a/tests/gateway/test_session_stall_watchdog.py
+++ b/tests/gateway/test_session_stall_watchdog.py
@@ -165,7 +165,9 @@ def _runner_for_stall(adapter: _FakeAdapter) -> GatewayRunner:
def _pending_event(chat_id: str = "chat-1", thread_id: str | None = None):
- source = SimpleNamespace(chat_id=chat_id, thread_id=thread_id, platform=None)
+ from gateway.session import SessionSource
+ from gateway.config import Platform
+ source = SessionSource(chat_id=chat_id, thread_id=thread_id, platform=Platform.TELEGRAM)
return SimpleNamespace(text="follow-up", source=source, timestamp=time.time())
@@ -528,3 +530,33 @@ async def test_check_session_stalls_bounds_wedged_send(monkeypatch):
assert sent2 == 0 # healthy already latched; wedged timed out again
assert wedged.send_attempts == 2
assert wedged_key not in runner._session_stall_notified
+
+
[email protected]("setting", [None, False, True])
+async def test_stall_policy_owner_latch_and_source_log_conservation(tmp_path, monkeypatch, caplog, setting):
+ import yaml
+ from gateway.profile_routing import ProfileRouteRejected
+ owner, launch = tmp_path / "owner", tmp_path / "launch"
+ owner.mkdir(); launch.mkdir()
+ (owner / "config.yaml").write_text(yaml.safe_dump({} if setting is None else {"display": {"suppress_warning_notifications": setting}}))
+ (launch / "config.yaml").write_text(yaml.safe_dump({"display": {"suppress_warning_notifications": setting is not True}}))
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ for home, muted in [(owner, setting is True), (launch, setting is not True), (owner, setting is True)]:
+ adapter = _FakeAdapter()
+ runner = _runner_for_stall(adapter)
+ runner._resolve_profile_home_for_source = lambda source: home
+ key = "agent:default:telegram:dm:policy"
+ adapter._pending_messages[key] = _pending_event()
+ agent = _FakeAgent(time.time() - 120)
+ runner._running_agents[key] = agent
+ assert await runner._check_session_stalls(60) == (0 if muted else 1)
+ assert runner._session_stall_notified[key] is True
+ assert await runner._check_session_stalls(60) == 0
+ assert "Session stall detected" in caplog.text
+ agent._last_activity_ts = time.time()
+ assert await runner._check_session_stalls(60) == 0
+ assert key not in runner._session_stall_notified
+ agent._last_activity_ts = time.time() - 120
+ assert await runner._check_session_stalls(60) == (0 if muted else 1)
+ assert len(adapter.sent) == (0 if muted else 2)
diff --git a/tests/gateway/test_telegram_inbound_warning_owner.py b/tests/gateway/test_telegram_inbound_warning_owner.py
new file mode 100644
index 00000000000..49398da659d
--- /dev/null
+++ b/tests/gateway/test_telegram_inbound_warning_owner.py
@@ -0,0 +1,64 @@
+"""Inbound cache diagnostics use the routed owner before agent admission."""
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import GatewayConfig, PlatformConfig
+from gateway.profile_routing import ProfileRoute
+from gateway.run import GatewayRunner
+from hermes_constants import get_hermes_home
+from plugins.platforms.telegram.adapter import TelegramAdapter
+from tests.gateway.test_telegram_documents import _make_document, _make_message, _make_update
+
+
[email protected]("ambient", [False, True])
[email protected]("setting", [None, False, True])
[email protected]("kind", ["document", "photo", "voice", "audio", "video"])
+async def test_inbound_cache_failure_keeps_owner_policy_and_context(
+ tmp_path, monkeypatch, caplog, ambient, setting, kind):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ root = tmp_path / ".hermes"
+ root.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ (root / "config.yaml").write_text(json.dumps({"display": {"suppress_warning_notifications": ambient}}))
+ for name, value in (("a", setting), ("b", not bool(setting))):
+ home = root / "profiles" / name
+ home.mkdir(parents=True)
+ config = {} if value is None else {"display": {"suppress_warning_notifications": value}}
+ (home / "config.yaml").write_text(json.dumps(config))
+ adapter = TelegramAdapter(PlatformConfig(enabled=True))
+ adapter._is_callback_user_authorized = lambda *a, **k: True
+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=True))
+ runner.config.profile_routes = [
+ ProfileRoute(name=name, platform="telegram", profile=name, chat_id=chat)
+ for name, chat in (("a", "100"), ("b", "200"))]
+ adapter.gateway_runner = runner
+ adapter.handle_message = AsyncMock()
+ for name, chat_id in (("a", 100), ("b", 200), ("a", 100)):
+ media = _make_document()
+ media.get_file = AsyncMock(side_effect=RuntimeError("download failure retained"))
+ msg = _make_message()
+ setattr(msg, kind, [media] if kind == "photo" else media)
+ msg.chat.id = chat_id
+ msg.reply_to_message = msg.quote = None
+ sent_homes = []
+ async def reply(*args, **kwargs):
+ sent_homes.append(get_hermes_home())
+ msg.reply_text = AsyncMock(side_effect=reply)
+ await adapter._handle_media_message(_make_update(msg), SimpleNamespace())
+ event = adapter.handle_message.call_args.args[0]
+ suppressed = setting is True if name == "a" else not bool(setting)
+ assert event.source.profile == name
+ assert msg.reply_text.await_count == (0 if suppressed else 1)
+ assert sent_homes == ([] if suppressed else [root / "profiles" / name])
+ assert "could not be downloaded" in event.text
+ assert ("asked to retry" in event.text) is not suppressed
+ assert not event.media_urls
+ assert get_hermes_home() == root
+ assert "download failure retained" in caplog.text
+ assert adapter.handle_message.await_count == 3
diff --git a/tests/gateway/test_warning_delivery_real_producers.py b/tests/gateway/test_warning_delivery_real_producers.py
new file mode 100644
index 00000000000..56d6dfffd1a
--- /dev/null
+++ b/tests/gateway/test_warning_delivery_real_producers.py
@@ -0,0 +1,113 @@
+"""Actual adapter producers; only vendor transport and pacing clocks replaced."""
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+import json
+
+import pytest
+from gateway.config import PlatformConfig
+from gateway.platforms.base import SendResult
+
+
[email protected](params=[None, False, True, "override"])
+def policy(request, monkeypatch, tmp_path):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ value = request.param
+ config: dict = {} if value is None else {"display": {"suppress_warning_notifications": value is True}}
+ if value == "override":
+ config["display"]["platforms"] = {p: {"suppress_warning_notifications": True} for p in ("slack", "signal")}
+ (tmp_path / "config.yaml").write_text(json.dumps(config))
+ return value in (True, "override")
+
+
+async def test_signal_pacing_producer_keeps_actual_image_delivery(policy, monkeypatch, tmp_path):
+ import gateway.platforms.signal as module
+ adapter = module.SignalAdapter(PlatformConfig())
+ scheduler = SimpleNamespace(state=lambda: {}, estimate_wait=lambda n: 120,
+ acquire=AsyncMock(), report_rpc_duration=AsyncMock())
+ monkeypatch.setattr(module, "get_scheduler", lambda: scheduler)
+ adapter._stop_typing_indicator = AsyncMock()
+ path = tmp_path / "image.png"
+ path.write_bytes(b"image")
+ adapter._resolve_image_path = AsyncMock(return_value=(str(path), None, None))
+ adapter._with_target = AsyncMock(side_effect=lambda params, chat: params)
+ adapter._rpc = AsyncMock(return_value={"timestamp": 123})
+ adapter.send = AsyncMock(return_value=SendResult(success=True))
+ result = await adapter.send_multiple_images("recipient", [(path.as_uri(), "caption")])
+ assert result.success
+ assert adapter.send.await_count == (0 if policy else 1)
+ if not policy:
+ assert "rate limit" in adapter.send.call_args.args[1]
+ assert adapter._rpc.call_args.args[1]["attachments"] == [str(path)]
+ scheduler.acquire.assert_awaited_once_with(1)
+ scheduler.report_rpc_duration.assert_awaited_once()
+
+
[email protected]("caption", [None, "Warning: requested caption"])
+async def test_slack_actual_upload_failure_keeps_caption_and_source_log(policy, tmp_path, caption, caplog):
+ from plugins.platforms.slack.adapter import SlackAdapter
+ adapter = SlackAdapter(PlatformConfig())
+ client = SimpleNamespace(files_upload_v2=AsyncMock(side_effect=RuntimeError("upload rejected")))
+ adapter._app = SimpleNamespace(client=client)
+ adapter._client_for = lambda chat_id, metadata: client
+ adapter._dm_target = AsyncMock(return_value="C123")
+ adapter.send = AsyncMock(return_value=SendResult(success=True, message_id="fallback"))
+ path = tmp_path / "report.pdf"
+ path.write_bytes(b"report")
+ result = await adapter.send_document("C123", str(path), caption=caption, metadata={"thread_id": "123.456"})
+ client.files_upload_v2.assert_awaited_once()
+ assert "upload rejected" in caplog.text
+ if policy:
+ assert not result.success and result.message_id is None
+ assert adapter.send.await_count == bool(caption)
+ if caption:
+ assert adapter.send.call_args.args[1] == caption
+ else:
+ assert result.success and result.message_id == "fallback" # legacy return semantics
+ assert "Couldn't deliver" in adapter.send.call_args.args[1]
+ if adapter.send.await_count:
+ assert adapter.send.call_args.kwargs["metadata"] == {"thread_id": "123.456"}
+
+
[email protected]("setting", [None, False, True])
+async def test_discord_admin_alert_uses_owner_and_logical_destination(tmp_path, monkeypatch, setting):
+ from pathlib import Path
+ from gateway.config import Platform
+ from plugins.platforms.discord.adapter import DiscordAdapter
+ from hermes_constants import get_hermes_home
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ root = tmp_path / ".hermes"
+ root.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ (root / "config.yaml").write_text("display: {suppress_warning_notifications: false}")
+ for name, muted in [("a", setting), ("b", not bool(setting))]:
+ home = root / "profiles" / name
+ home.mkdir(parents=True)
+ display = {} if muted is None else {"suppress_warning_notifications": muted}
+ # Discord's own setting is deliberately the opposite of the alert target.
+ display["platforms"] = {"discord": {"suppress_warning_notifications": not bool(muted)}}
+ config = {"display": display, "platforms": {"telegram": {"enabled": True,
+ "home_channel": {"platform": "telegram", "chat_id": "admin-" + name, "name": "test"}}}}
+ (home / "config.yaml").write_text(json.dumps(config))
+ wire = []
+ async def send(chat_id, text):
+ wire.append((chat_id, text, get_hermes_home()))
+ return SendResult(success=True)
+ maps = {n: {Platform.TELEGRAM: SimpleNamespace(send=send),
+ Platform.SLACK: SimpleNamespace(send=AsyncMock())} for n in ("a", "b")}
+ runner = SimpleNamespace(adapters={}, _adapters_for_profile=maps.get)
+ for name in ("a", "b", "a"):
+ adapter = DiscordAdapter(PlatformConfig())
+ adapter._owner_profile = name
+ adapter.gateway_runner = runner
+ before = len(wire)
+ await adapter._notify_unauthorized_slash("user", "123", "chan", "guild", "/test", "denied")
+ suppressed = setting is True if name == "a" else not bool(setting)
+ assert len(wire) - before == (0 if suppressed else 1)
+ if not suppressed:
+ assert wire[-1][0] == "admin-" + name
+ assert wire[-1][2] == root / "profiles" / name
+ maps[name][Platform.SLACK].send.assert_not_awaited()
+ assert get_hermes_home() == root
diff --git a/tests/gateway/test_warning_emission_boundary.py b/tests/gateway/test_warning_emission_boundary.py
new file mode 100644
index 00000000000..7724784b858
--- /dev/null
+++ b/tests/gateway/test_warning_emission_boundary.py
@@ -0,0 +1,42 @@
+"""Shared channel warning boundary: policy, actual receipt, and stream isolation."""
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+from gateway.platforms.base import SendResult
+from tests.gateway.test_session_hygiene import HygieneCaptureAdapter
+
+
[email protected]("setting", [None, False, True])
+async def test_emit_warning_preserves_transport_receipt_and_input_metadata(tmp_path, monkeypatch, setting):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ cfg = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+ adapter = HygieneCaptureAdapter()
+ failure = SendResult(success=False, error="fixture transport rejection")
+ adapter.send = AsyncMock(return_value=failure)
+ metadata = {"thread_id": "123"}
+ result = await adapter.emit_warning("chat", "diagnostic", reply_to="456", metadata=metadata)
+ assert metadata == {"thread_id": "123"}
+ if setting is True:
+ assert result is None # explicitly not a successful transport receipt
+ adapter.send.assert_not_awaited()
+ else:
+ assert result is failure
+ assert adapter.send.await_args.kwargs["metadata"] == {"thread_id": "123"}
+ assert adapter.send.await_args.kwargs["reply_to"] == "456"
+
+
+async def test_emit_warning_uses_logical_override_and_does_not_swallow_send_error(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ (tmp_path / "config.yaml").write_text(json.dumps({"display": {
+ "suppress_warning_notifications": True,
+ "platforms": {"slack": {"suppress_warning_notifications": False}}}}))
+ adapter = HygieneCaptureAdapter()
+ adapter.send = AsyncMock(side_effect=RuntimeError("fixture transport failure"))
+ with pytest.raises(RuntimeError, match="fixture transport failure"):
+ await adapter.emit_warning("chat", "diagnostic", logical_platform="slack")
diff --git a/tests/gateway/test_warning_notification_contracts.py b/tests/gateway/test_warning_notification_contracts.py
new file mode 100644
index 00000000000..0eb7d482c2b
--- /dev/null
+++ b/tests/gateway/test_warning_notification_contracts.py
@@ -0,0 +1,103 @@
+"""Diagnostic suppression preserves real producer outcomes and control paths."""
+
+import asyncio
+from decimal import Decimal
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from agent import empty_response_guard
+from agent.status_output import StatusOutputMixin
+from agent.turn_api_call import nous_rate_limit_guard
+from agent.turn_empty_response import _terminal_empty
+from gateway.config import Platform
+from gateway.run import GatewayRunner, _load_gateway_config
+from gateway.run_turn_runner import TurnRunner
+from gateway.session import SessionSource
+from gateway.turn_context import TurnContext
+
+
+class Agent(StatusOutputMixin):
+ suppress_status_output = True
+ log_prefix = ""
+ provider = "nous"
+ model = "model"
+ base_url = "https://example.invalid/v1"
+ _fallback_chain = []
+ _empty_content_retries = 3
+
+ def _try_activate_fallback(self):
+ return False
+
+ def _persist_session(self, *args):
+ self.persisted = True
+
+ def _extract_reasoning(self, *args):
+ return ""
+
+ def _drop_trailing_empty_response_scaffolding(self, *args):
+ pass
+
+ def _build_assistant_message(self, *args):
+ return {"role": "assistant"}
+
+
[email protected]("enabled", [False, True])
+def test_real_retry_producers_keep_final_failure_and_persistence(tmp_path, monkeypatch, caplog, enabled):
+ from gateway import run
+
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(not enabled).lower()}}}")
+ monkeypatch.setattr(run, "_hermes_home", tmp_path)
+ sent = []
+ async def send(chat_id, text, **kwargs):
+ sent.append(text)
+ return SimpleNamespace(success=True)
+ adapter = SimpleNamespace(send=send)
+ source = SessionSource(platform=Platform.SLACK, chat_id="D1", user_id="U1")
+ gateway = object.__new__(GatewayRunner)
+ ctx = TurnContext(source=source, user_config=_load_gateway_config(), _run_still_current=lambda: True,
+ _status_adapter=adapter, _status_chat_id="D1", _status_thread_metadata={})
+ agent = Agent()
+ agent.status_callback = TurnRunner(gateway, ctx)._status_callback_sync
+ monkeypatch.setattr(run, "safe_schedule_threadsafe", lambda coro, *a, **k: asyncio.run(coro))
+ setattr(agent, empty_response_guard._STREAK_COST_ATTR, Decimal("1.25"))
+ messages = []
+ final = _terminal_empty(agent, SimpleNamespace(), "stop", messages)
+ assert bool(sent) is enabled
+ assert messages[-1]["_empty_terminal_sentinel"] is True
+ assert "Empty response" in caplog.text
+ result = {"final_response": final, "messages": messages, "failed": True}
+ response, silent, _ = asyncio.run(gateway._hmwa_shape_agent_response(
+ result, source, [], SimpleNamespace(session_id="session"), None, None, None, "session", "slack", 0))
+ assert response and response != "(empty)" and not silent
+ sent.clear()
+ with patch("agent.nous_rate_guard.nous_rate_limit_remaining", return_value=60), \
+ patch("hermes_cli.anon_auth.apply_model_switch"), \
+ patch("hermes_cli.anon_auth.route_is_welcome_host", return_value=False):
+ verdict = nous_rate_limit_guard(agent, _retry=SimpleNamespace(), api_messages=[], messages=[],
+ conversation_history=[], active_system_prompt="", retry_count=0, compression_attempts=0, api_call_count=0)
+ assert bool(sent) is enabled
+ assert verdict.result["failed"] and agent.persisted
+ assert "/retry" in verdict.result["final_response"]
+ assert not agent._retry_status_buffer
+
+
[email protected]("yaml_text,expected", [
+ ("display: broken", True), ("display: [broken]", True),
+ ("display: {platforms: broken}", True),
+ ("display: {suppress_warning_notifications: true, platforms: broken}", False),
+])
+def test_bad_config_containers_do_not_abort_startup_warning(tmp_path, monkeypatch, yaml_text, expected):
+ from gateway import run
+
+ (tmp_path / "config.yaml").write_text(yaml_text)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(run, "_hermes_home", tmp_path)
+ gateway = object.__new__(GatewayRunner)
+ gateway._session_db_init_error = "database is locked"
+ gateway._session_db_handle_cache = None
+ gateway._home_channel_transports = lambda: [(Platform.SLACK, None, None, None)]
+ gateway._send_home_channel_message = AsyncMock()
+ asyncio.run(gateway._send_session_db_warning_notifications())
+ assert gateway._send_home_channel_message.await_count == int(expected)
diff --git a/tests/gateway/test_warning_notifications.py b/tests/gateway/test_warning_notifications.py
new file mode 100644
index 00000000000..46b06bef01b
--- /dev/null
+++ b/tests/gateway/test_warning_notifications.py
@@ -0,0 +1,128 @@
+"""Warning delivery is independent of normal replies and operational state."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from agent.credits_tracker import AgentNotice
+from agent.status_output import StatusOutputMixin
+from gateway.config import Platform
+from gateway.run import GatewayRunner, _load_gateway_config
+from gateway.run_turn_runner import TurnRunner
+from gateway.session import SessionSource
+from gateway.turn_context import TurnContext
+
+
+from tests.gateway.test_session_hygiene import HygieneCaptureAdapter
+
+
+class RecordingAdapter(HygieneCaptureAdapter):
+ config = SimpleNamespace(extra={})
+
+ def __init__(self):
+ super().__init__()
+ self.sent = []
+
+ async def send(self, chat_id, content, **kwargs):
+ self.sent.append((chat_id, content, kwargs))
+ return SimpleNamespace(success=True, message_id=str(len(self.sent)))
+
+
+class Emitter(StatusOutputMixin):
+ suppress_status_output = True
+ log_prefix = ""
+
+
[email protected]("platform", [Platform.SLACK, Platform.TELEGRAM, Platform.LOCAL])
[email protected]("thread_id", [None, "1700.1"])
[email protected]("configured,enabled", [
+ ("", True), ("display: null", True),
+ ("display: {suppress_warning_notifications: null}", True),
+ ("display: {suppress_warning_notifications: true}", False),
+ ('display: {suppress_warning_notifications: "true"}', False),
+ ("display: {suppress_warning_notifications: typo}", True),
+ ("display: {suppress_warning_notifications: []}", True),
+ ("display: broken", True),
+ ("display: [broken]", True),
+ ("display: {platforms: broken}", True),
+ ("display: {suppress_warning_notifications: true, platforms: {slack: {suppress_warning_notifications: false}}}", True),
+])
+def test_warning_opt_out_preserves_other_delivery(tmp_path, monkeypatch, platform, thread_id, configured, enabled):
+ from gateway import run
+
+ (tmp_path / "config.yaml").write_text(configured)
+ monkeypatch.setattr(run, "_hermes_home", tmp_path)
+ config = _load_gateway_config()
+ if "platforms: {slack" in configured and platform != Platform.SLACK:
+ enabled = False
+
+ adapter = RecordingAdapter()
+ source = SessionSource(platform=platform, chat_id="chat", user_id="user", thread_id=thread_id)
+ gateway = object.__new__(GatewayRunner)
+ gateway.config = None
+ gateway._adapter_for_source = lambda source: adapter
+ gateway._thread_metadata_for_source = lambda source: {"thread_id": source.thread_id} if source.thread_id else {}
+ ctx = TurnContext(source=source, user_config=config, _run_still_current=lambda: True,
+ _status_adapter=adapter, _status_chat_id=source.chat_id,
+ _status_thread_metadata=gateway._thread_metadata_for_source(source))
+ turn = TurnRunner(gateway, ctx)
+ monkeypatch.setattr(run, "safe_schedule_threadsafe", lambda coro, *a, **k: asyncio.run(coro))
+ emitter = Emitter()
+ emitter.status_callback = turn._status_callback_sync
+ emitter.notice_callback = turn._notice_callback_sync
+
+ # These are engine rails, not text filtering on the adapter's general send.
+ diagnostics = [
+ ("warn", "Context overflow blocked; use /compress"),
+ ("lifecycle", "⚠ Compression aborted: summary failed; history preserved"),
+ ("lifecycle", "↻ Switched to fallback: secondary (provider)"),
+ ("lifecycle", "Content filter terminated stream; switching to fallback..."),
+ ("lifecycle", "🔐 Authentication failed and could not be refreshed — switching to fallback provider..."),
+ ("lifecycle", "ℹ️ Estimated cost of these empty attempts: ~$1.25"),
+ ("lifecycle", "⏳ Your Nous account has hit its rate limit; it resets in 1m."),
+ ("lifecycle", "📐 Compression could not reduce the request further — removed retained vision payloads and retrying..."),
+ ]
+ for kind, text in diagnostics:
+ if kind == "warn":
+ emitter._emit_warning(text)
+ else:
+ emitter._emit_diagnostic_status(text)
+ emitter._pending_fallback_notice = "↻ Switched to fallback: secondary (provider)"
+ emitter._emit_pending_fallback_notice()
+ assert emitter._pending_fallback_notice is None
+ emitter._emit_notice(AgentNotice("Credit access paused", level="error", key="credits.depleted"))
+ turn.progress_callback("subagent.complete", status="failed", goal="research", summary="provider unavailable")
+ warning_count = len(diagnostics) + 3
+ assert len(adapter.sent) == (warning_count if enabled else 0)
+
+ emitter._emit_status("still on it")
+ asyncio.run(gateway._deliver_platform_notice(source, "No home channel is set"))
+ for text in ("⚠ The requested analysis", "Approval required", "Compression aborted: manual command result", "The task failed"):
+ asyncio.run(adapter.send(source.chat_id, text))
+ assert len(adapter.sent) == (warning_count if enabled else 0) + 6
+ assert all(row[0] == source.chat_id for row in adapter.sent)
+
+
[email protected]("enabled", [True, False])
+def test_direct_warning_delivery_keeps_failure_state(tmp_path, monkeypatch, enabled):
+ from gateway import run
+
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(not enabled).lower()}}}")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(run, "_hermes_home", tmp_path)
+ adapter = RecordingAdapter()
+ source = SessionSource(platform=Platform.SLACK, chat_id="chat", user_id="user")
+ gateway = object.__new__(GatewayRunner)
+ gateway._adapter_for_source = lambda source: adapter
+ gateway._session_db_init_error = "database is locked"
+ gateway._session_db_handle_cache = None
+ gateway._home_channel_transports = lambda: [(Platform.SLACK, None, SimpleNamespace(chat_id="chat"), adapter)]
+ gateway._send_home_channel_message = AsyncMock()
+ asyncio.run(gateway._hmwa_hygiene_notify(source, {}, "Compression failed", "failure"))
+ asyncio.run(gateway._run_agent_inactivity_warning(SimpleNamespace(agent_warning=60, agent_timeout=120), source, {}))
+ asyncio.run(gateway._send_session_db_warning_notifications())
+ assert len(adapter.sent) == (2 if enabled else 0)
+ assert gateway._send_home_channel_message.await_count == int(enabled)
+ assert gateway._session_db_init_error == "database is locked"
diff --git a/tests/gateway/test_warning_notifications_transport.py b/tests/gateway/test_warning_notifications_transport.py
new file mode 100644
index 00000000000..f296c28c6fe
--- /dev/null
+++ b/tests/gateway/test_warning_notifications_transport.py
@@ -0,0 +1,102 @@
+"""Real native/relay send paths and profile-scoped effective warning policy.
+
+Only external Slack SDK/relay transport I/O is replaced; config, agent emission,
+callback classification, presentation and adapter send/edit are production code.
+"""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from agent.status_output import StatusOutputMixin
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.event import MessageEvent, MessageType
+from gateway.relay.adapter import RelayAdapter
+from gateway.relay.descriptor import CONTRACT_VERSION, CapabilityDescriptor
+from gateway.run import GatewayRunner, _load_gateway_config, _profile_runtime_scope
+from gateway.run_turn_runner import TurnRunner
+from gateway.session import SessionSource
+from gateway.turn_context import TurnContext
+from plugins.platforms.slack.adapter import SlackAdapter
+from tests.gateway.relay.stub_connector import StubConnector
+
+
[email protected]("relay", [False, True])
[email protected]("thread_id", [None, "1700.1"])
[email protected]("enabled", [False, True])
+def test_warning_policy_reaches_slack_transport(tmp_path, monkeypatch, relay, thread_id, enabled):
+ from gateway import run
+
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(not enabled).lower()}}}")
+ monkeypatch.setattr(run, "_hermes_home", tmp_path)
+ source = SessionSource(platform=Platform.SLACK, chat_id="D1", chat_type="dm", user_id="U1", thread_id=thread_id)
+ metadata = {"thread_id": thread_id} if thread_id else {}
+ pc = PlatformConfig(extra={"reply_in_thread": bool(thread_id)})
+ if relay:
+ desc = CapabilityDescriptor(contract_version=CONTRACT_VERSION, platform="slack", label="Slack",
+ max_message_length=4000, supports_edit=True, supports_threads=True, supports_draft_streaming=False,
+ markdown_dialect="mrkdwn", len_unit="chars", emoji="", platform_hint="", pii_safe=False)
+ transport = StubConnector(desc)
+ adapter = RelayAdapter(pc, desc, transport=transport)
+ adapter._capture_scope(MessageEvent(text="hello", source=source, message_type=MessageType.TEXT))
+ sent = transport.sent
+ else:
+ adapter = SlackAdapter(pc)
+ client = AsyncMock()
+ client.chat_postMessage.return_value = {"ok": True, "ts": "1700.2"}
+ client.chat_update.return_value = {"ok": True, "ts": "1700.2"}
+ adapter._app = SimpleNamespace(client=client)
+ sent = []
+ async def post(**kwargs):
+ sent.append(kwargs)
+ return {"ok": True, "ts": "1700.2"}
+ client.chat_postMessage.side_effect = post
+ client.chat_update.side_effect = post
+ gateway = object.__new__(GatewayRunner)
+ gateway.config = None
+ gateway._adapter_for_source = lambda source: adapter
+ gateway._thread_metadata_for_source = lambda source: metadata
+ ctx = TurnContext(source=source, user_config=_load_gateway_config(), _run_still_current=lambda: True,
+ _status_adapter=adapter, _status_chat_id="D1", _status_thread_metadata=metadata)
+ turn = TurnRunner(gateway, ctx)
+ monkeypatch.setattr(run, "safe_schedule_threadsafe", lambda coro, *a, **k: asyncio.run(coro))
+ agent = StatusOutputMixin()
+ agent.suppress_status_output = True
+ agent.status_callback = turn._status_callback_sync
+ for _ in range(2):
+ agent._emit_warning("⚠ Context is over the limit; compression blocked")
+ assert len(sent) == (2 if enabled else 0)
+ # A warning-looking real answer remains deliverable through the identical adapter.
+ result = asyncio.run(adapter.send("D1", "⚠ The requested task failed", metadata=metadata))
+ assert result.success
+ assert len(sent) == (2 if enabled else 0) + 1
+ if relay:
+ assert sent[-1]["metadata"].get("thread_id") == thread_id
+ else:
+ assert sent[-1].get("thread_ts") == thread_id
+
+
+def test_profile_config_isolated_for_callbacks_and_direct_warnings(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.warning_notifications import warning_notifications_enabled
+
+ homes = [tmp_path / name for name in ("a", "b")]
+ for home, value in zip(homes, ("true", "false")):
+ home.mkdir()
+ (home / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {value}}}")
+ # The ambient default must never override the context-bound owner.
+ monkeypatch.setattr(run, "_hermes_home", homes[1])
+ source = SessionSource(platform=Platform.SLACK, chat_id="D1", chat_type="dm", user_id="U1")
+ for home, expected in ((homes[0], False), (homes[1], True), (homes[0], False)):
+ with _profile_runtime_scope(home, prepared_secret_scope={}):
+ config = _load_gateway_config()
+ assert warning_notifications_enabled(source.platform, config) is expected
+ from tests.gateway.test_warning_notifications import RecordingAdapter
+ adapter = RecordingAdapter()
+ adapter.send = AsyncMock()
+ gateway = object.__new__(GatewayRunner)
+ gateway._adapter_for_source = lambda source: adapter
+ asyncio.run(gateway._hmwa_hygiene_notify(source, {}, "Compression failed", "failure"))
+ assert adapter.send.await_count == int(expected)
diff --git a/tests/gateway/test_warning_render_boundary.py b/tests/gateway/test_warning_render_boundary.py
new file mode 100644
index 00000000000..2fd69cf156e
--- /dev/null
+++ b/tests/gateway/test_warning_render_boundary.py
@@ -0,0 +1,25 @@
+"""UI sink gating never suppresses the producer or interprets its return value."""
+import pytest
+from gateway import warning_notifications as policy
+
+
[email protected]("setting", [None, False, True])
[email protected]("diagnostic", [False, True])
+def test_render_notification_calls_renderer_only_when_visible(setting, diagnostic):
+ cfg = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ observed = ["producer ran"]
+ def renderer():
+ observed.append("rendered")
+ return False # not a delivery receipt
+ presented = policy.render_notification(renderer, platform="cli", user_config=cfg, diagnostic=diagnostic)
+ expected = not (diagnostic and setting is True)
+ assert presented is expected
+ assert observed == (["producer ran", "rendered"] if expected else ["producer ran"])
+
+
+def test_render_failure_propagates_and_requested_result_does_not_read_policy(monkeypatch):
+ def fail():
+ raise RuntimeError("renderer failed")
+ monkeypatch.setattr(policy, "warning_notifications_enabled", lambda *a: pytest.fail("must not consult policy for result"))
+ with pytest.raises(RuntimeError, match="renderer failed"):
+ policy.render_notification(fail, platform="tui", diagnostic=False)
diff --git a/tests/gateway/test_warning_wiring_conservation.py b/tests/gateway/test_warning_wiring_conservation.py
new file mode 100644
index 00000000000..6544350e712
--- /dev/null
+++ b/tests/gateway/test_warning_wiring_conservation.py
@@ -0,0 +1,52 @@
+"""Actual per-turn wiring must retain observers before presentation scope binds."""
+from types import SimpleNamespace as NS
+from unittest.mock import patch
+
+from agent.status_output import StatusOutputMixin
+from agent.notification_presentation import notification_turn
+from gateway.run_turn_runner import TurnRunner
+from gateway.turn_context import TurnContext
+from gateway.config import Platform
+from gateway.session import SessionSource
+
+
+def test_actual_wiring_retains_observers_and_controls_across_muted_turn():
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="offline", chat_type="dm")
+ for muted in (False, True, False):
+ observed = []
+ ctx = TurnContext(source=source, user_config={"display": {"suppress_warning_notifications": True}},
+ mute_notification_reply=muted, _hooks_ref=NS(loaded_hooks=[]),
+ _status_callback_sync=lambda *a: observed.append(("status", a)))
+ holder = NS(_ctx=ctx, _runner=NS(_service_tier=None, _consume_pending_turn_sidecar_notes=lambda _: []),
+ _make_bg_review_callbacks=lambda: (lambda _: None, lambda: None),
+ _merge_turn_request_overrides=TurnRunner._merge_turn_request_overrides,
+ _clarify_callback_sync=lambda *a: "yes",
+ _notice_callback_sync=lambda *a: observed.append(("notice", a)),
+ _attach_session_title_callback=lambda *a: None)
+ agent = StatusOutputMixin()
+ agent.suppress_status_output = True
+ TurnRunner._wire_turn_agent_callbacks(holder, agent, {}, None, None, None, False)
+ with notification_turn(agent, muted=muted, session_id="offline"):
+ agent._emit_warning("real warning source")
+ agent._emit_notice(NS(level="warn", text="structured diagnostic"))
+ assert agent.clarify_callback("Continue?") == "yes"
+ assert len(observed) == 2
+ assert callable(agent.status_callback) and callable(agent.notice_callback)
+
+
+def test_concrete_gateway_sinks_hide_all_freeform_muted_turn_output():
+ for muted in (False, True, False):
+ scheduled = []
+ ctx = TurnContext(source=SessionSource(platform=Platform.TELEGRAM, chat_id="offline"),
+ user_config={}, mute_notification_reply=muted)
+ holder = NS(_ctx=ctx, _status_live=lambda: True,
+ _schedule=lambda coro, *args: scheduled.append(coro),
+ _runner=NS(_deliver_platform_notice=lambda *args: "notice-send"))
+ with patch("gateway.run._prepare_gateway_status_message", lambda *args: "prepared"), \
+ patch("gateway.run._send_or_update_status_coro", lambda *args: "status-send"), \
+ patch("gateway.run.render_notice_line", lambda notice: notice.text):
+ TurnRunner._status_callback_sync(holder, "lifecycle", "ordinary progress")
+ TurnRunner._status_callback_sync(holder, "warn", "warning")
+ TurnRunner._notice_callback_sync(holder, NS(level="info", text="info"))
+ TurnRunner._notice_callback_sync(holder, NS(level="warn", text="warning"))
+ assert len(scheduled) == (0 if muted else 4)
diff --git a/tests/gateway/test_watchdog_review.py b/tests/gateway/test_watchdog_review.py
index bd9afe5d2c9..0a65cfbbed0 100644
--- a/tests/gateway/test_watchdog_review.py
+++ b/tests/gateway/test_watchdog_review.py
@@ -163,7 +163,9 @@ def _runner_for_stall(adapter):
def _pending_event(chat_id="chat-1"):
- source = SimpleNamespace(chat_id=chat_id, thread_id=None, platform=None)
+ from gateway.session import SessionSource
+ from gateway.config import Platform
+ source = SessionSource(chat_id=chat_id, thread_id=None, platform=Platform.TELEGRAM)
return SimpleNamespace(text="follow-up", source=source, timestamp=time.time())
diff --git a/tests/gateway/test_weixin_voice_warning_policy.py b/tests/gateway/test_weixin_voice_warning_policy.py
new file mode 100644
index 00000000000..7c0835b202d
--- /dev/null
+++ b/tests/gateway/test_weixin_voice_warning_policy.py
@@ -0,0 +1,36 @@
+"""Voice downgrade diagnostic is optional; the actual attachment is not."""
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+from gateway.config import PlatformConfig
+from gateway.platforms import weixin as wx
+
+
[email protected]("setting", [None, False, True])
[email protected]("caption", [None, "Warning: requested caption"])
+async def test_real_voice_file_send_filters_only_generated_caption(tmp_path, monkeypatch, setting, caption):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ config = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ (tmp_path / "config.yaml").write_text(json.dumps(config))
+ adapter = wx.WeixinAdapter(PlatformConfig(token="fixture-token", extra={"account_id": "fixture"}))
+ adapter._send_session = object()
+ audio = tmp_path / "voice.ogg"
+ audio.write_bytes(b"fixture bytes")
+ posts = []
+ async def post(*args, **kwargs):
+ posts.append(kwargs["payload"])
+ return {"ret": 0}
+ monkeypatch.setattr(wx, "_get_upload_url", AsyncMock(return_value={"upload_full_url": "https://example.invalid/upload"}))
+ upload = AsyncMock(return_value="upload-reference")
+ monkeypatch.setattr(wx, "_upload_ciphertext", upload)
+ monkeypatch.setattr(wx, "_api_post", post)
+ result = await adapter.send_voice("recipient", str(audio), caption=caption)
+ assert result.success and result.message_id
+ upload.assert_awaited_once()
+ items = [item for payload in posts for item in payload["msg"]["item_list"]]
+ text = [item["text_item"]["text"] for item in items if "text_item" in item]
+ assert text == ([caption] if caption else [] if setting is True else ["[voice message as attachment]"])
+ assert len([item for item in items if "file_item" in item]) == 1
diff --git a/tests/hermes_cli/test_interrupt_requeue_image_payload.py b/tests/hermes_cli/test_interrupt_requeue_image_payload.py
index ba76575d379..d163a9a9472 100644
--- a/tests/hermes_cli/test_interrupt_requeue_image_payload.py
+++ b/tests/hermes_cli/test_interrupt_requeue_image_payload.py
@@ -24,6 +24,7 @@ class _Stub(CLIChatTurnMixin):
def _interrupted_turn(payload):
turn = MagicMock()
+ turn.mute_notification_reply = False
turn.result = {"interrupted": True, "interrupt_message": payload, "final_response": ""}
turn.use_streaming_tts = False
return turn
diff --git a/tests/hermes_cli/test_quiet_turn_author.py b/tests/hermes_cli/test_quiet_turn_author.py
index 19a6cbbbdc5..a1aa7dc3659 100644
--- a/tests/hermes_cli/test_quiet_turn_author.py
+++ b/tests/hermes_cli/test_quiet_turn_author.py
@@ -214,3 +214,47 @@ def test_quiet_notify_loop_injects_owned_async_delegation_events(monkeypatch):
)
assert seen == ["[IMPORTANT: delegated reply from C]"]
assert result == {"final_response": "[IMPORTANT: delegated reply from C]"}
+
+
+def _quiet_drain(monkeypatch, events):
+ from tools import process_registry as pr
+ monkeypatch.setattr(pr.process_registry, "wait_for_pending_completions",
+ lambda *a, **k: {"waited": [], "completed": [], "timed_out": []})
+ queue = list(events)
+ monkeypatch.setattr(pr.process_registry, "drain_notifications",
+ lambda *a, **k: [queue.pop(0)] if queue else [])
+
+
+def _quiet_policy(tmp_path, monkeypatch, setting):
+ import json
+ home = tmp_path / f"home-{setting}"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ display = {} if setting is None else {"suppress_warning_notifications": setting}
+ (home / "config.yaml").write_text(json.dumps({"display": display}))
+
+
[email protected]("setting", (None, False, True))
+def test_quiet_diagnostic_only_wake_runs_but_reply_displaces_result_only_when_visible(tmp_path, monkeypatch, setting):
+ """Grid sweep: -Q linger had no diagnostic admission rule. A wake made only of automatic early
+ failure notices still runs (the agent may act on it) but under suppression its reply must not
+ replace the requested one-shot answer; absent/false keep legacy displacement."""
+ from hermes_cli import quiet_single_query as qsq
+ _quiet_policy(tmp_path, monkeypatch, setting)
+ _quiet_drain(monkeypatch, [({"type": "completion", "task_failure_notice": True, "session_key": "s"},
+ "[Background process failed early: exit 7]")])
+ seen = []
+ result = qsq.continue_quiet_notify_completions(
+ "s", lambda text: seen.append(text) or {"final_response": "DIAG_REPLY"}, linger_budget=0.0)
+ assert seen == ["[Background process failed early: exit 7]"], "the wake always runs"
+ assert result == (None if setting is True else {"final_response": "DIAG_REPLY"})
+
+
+def test_quiet_requested_completion_wake_never_muted(tmp_path, monkeypatch):
+ from hermes_cli import quiet_single_query as qsq
+ _quiet_policy(tmp_path, monkeypatch, True)
+ _quiet_drain(monkeypatch, [({"type": "completion", "session_key": "s"}, "[Background process finished: OK]"),
+ ({"type": "completion", "task_failure_notice": True, "session_key": "s"}, "[failed early]")])
+ result = qsq.continue_quiet_notify_completions(
+ "s", lambda text: {"final_response": "REQUESTED_REPLY"}, linger_budget=0.0)
+ assert result == {"final_response": "REQUESTED_REPLY"}
diff --git a/tests/hermes_cli/test_warning_callback_conservation.py b/tests/hermes_cli/test_warning_callback_conservation.py
new file mode 100644
index 00000000000..fb6d7a7c841
--- /dev/null
+++ b/tests/hermes_cli/test_warning_callback_conservation.py
@@ -0,0 +1,48 @@
+"""Concrete CLI sinks own filtering; generic agent callbacks remain observable."""
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+from agent.status_output import StatusOutputMixin
+from hermes_cli.cli_stream_mixin import CLIStreamMixin
+
+
+class Agent(StatusOutputMixin):
+ suppress_status_output = True
+ platform = "cli"
+
+ def _touch_activity(self, *args):
+ pass
+
+
+class CLI(CLIStreamMixin):
+ _spinner_text = ""
+
+ def _invalidate(self):
+ pass
+
+
[email protected]("setting", [None, False, True])
+def test_cli_notice_and_wait_callbacks_keep_default_output(tmp_path, monkeypatch, setting):
+ import cli
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump(
+ {} if setting is None else {"display": {"suppress_warning_notifications": setting}}))
+ printed = []
+ monkeypatch.setattr(cli, "_cprint", printed.append)
+ surface = CLI()
+ agent = Agent()
+ surface.agent = agent
+ agent.notice_callback = surface._on_notice
+ agent.thinking_callback = surface._on_thinking
+ agent._emit_notice(SimpleNamespace(level="warn", text="arbitrary warning wording"))
+ agent._emit_diagnostic_wait("arbitrary retry wording")
+ surface._flush_credit_notices()
+ assert bool(printed) is not (setting is True)
+ assert surface._spinner_text == ("" if setting is True else "arbitrary retry wording")
+ agent._emit_notice(SimpleNamespace(level="info", text="ordinary progress"))
+ agent._emit_wait_notice("⚠ requested progress")
+ surface._flush_credit_notices()
+ assert "ordinary progress" in printed[-1]
+ assert surface._spinner_text == "⚠ requested progress"
diff --git a/tests/plugins/test_hindsight_root_guard.py b/tests/plugins/test_hindsight_root_guard.py
index 0e8c69bd467..18db639ceac 100644
--- a/tests/plugins/test_hindsight_root_guard.py
+++ b/tests/plugins/test_hindsight_root_guard.py
@@ -74,3 +74,29 @@ def _fake_thread_factory(started: threading.Event):
return real_thread(*args, **kwargs)
return _factory
+
+
+def test_root_warning_uses_gated_warning_callback_when_wired(monkeypatch, capsys):
+ """CLI wiring passes agent._emit_warning: the notice goes through that gated sink, not raw stderr."""
+ provider = _make_local_embedded_provider(monkeypatch)
+ monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)
+ seen = []
+ provider.initialize(session_id="s1", warning_callback=seen.append, platform="cli")
+ assert provider._mode == "disabled"
+ assert len(seen) == 1 and "cannot run as root" in seen[0]
+ assert "cannot run as root" not in capsys.readouterr().err
+
+
[email protected]("setting", (None, False, True))
+def test_root_warning_stderr_fallback_honors_policy(tmp_path, monkeypatch, capsys, setting):
+ """No warning_callback (gateway/TUI wiring): the stderr fallback follows the shared boundary;
+ the logger.warning is always recorded."""
+ import json
+ home = tmp_path / f"home-{setting}"; home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ (home / "config.yaml").write_text(json.dumps({"display": {} if setting is None else {"suppress_warning_notifications": setting}}))
+ provider = _make_local_embedded_provider(monkeypatch)
+ monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)
+ provider.initialize(session_id="s1", platform="cli")
+ assert provider._mode == "disabled"
+ assert ("cannot run as root" in capsys.readouterr().err) is (setting is not True)
diff --git a/tests/tools/test_delegate_sync_failure_echo_policy.py b/tests/tools/test_delegate_sync_failure_echo_policy.py
new file mode 100644
index 00000000000..7b7a9e88204
--- /dev/null
+++ b/tests/tools/test_delegate_sync_failure_echo_policy.py
@@ -0,0 +1,47 @@
+"""Salt R11-B1: synchronous child failure echo above the CLI spinner is an automatic diagnostic presentation
+and honors display.suppress_warning_notifications under the parent's turn snapshot; the child result and the
+relayed subagent.complete event are never gated."""
+import json
+import pytest
+
+
+def configure(home, setting, monkeypatch):
+ home.mkdir(exist_ok=True)
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ (home/'config.yaml').write_text(json.dumps({'display': {} if setting is None else {'suppress_warning_notifications':setting}}))
+
+
+
+def test_sync_failure_real_run_to_spinner_three_modes(tmp_path, monkeypatch):
+ from tools.delegate_tool import _run_single_child
+ from tools.delegate_tool_progress import _build_child_progress_callback
+ from agent.notification_presentation import notification_policy_snapshot
+ from tests.tools.test_delegate_output_schema import _StubChild, _StubParent
+ rows=[]
+ for setting in (None,False,True):
+ configure(tmp_path/f'sync-{setting}',setting,monkeypatch)
+ import io
+ from contextlib import redirect_stdout
+ from agent.display import KawaiiSpinner
+ from agent.notification_presentation import notification_config_snapshot
+ buffer=io.StringIO();events=[]
+ parent=_StubParent();parent.session_id='parent'
+ with redirect_stdout(buffer):parent._delegate_spinner=KawaiiSpinner('delegating')
+ parent.tool_progress_callback=lambda *a,**kw:events.append({'args':a,'kwargs':kw})
+ child=_StubChild([])
+ def fail(**kwargs):raise RuntimeError('SYNC_REAL_CHILD_CRASH')
+ child.run_conversation=fail
+ child.tool_progress_callback=_build_child_progress_callback(0,'actual failing child',parent)
+ config=notification_config_snapshot()
+ assert config['display'].get('suppress_warning_notifications') is setting
+ with notification_policy_snapshot(parent,'cli',config):
+ result=_run_single_child(0,'actual failing child',child,parent)
+ assert result['status'] in ('error','failed') and 'SYNC_REAL_CHILD_CRASH' in str(result)
+ rows.append({'setting':setting,'lines':buffer.getvalue().splitlines(),'events':events,'result':result})
+ # absent/false: legacy echo present; true: echo suppressed. Result and relayed event untouched in all modes.
+ assert any('SYNC_REAL_CHILD_CRASH' in s for s in rows[0]['lines']), rows[0]
+ assert any('SYNC_REAL_CHILD_CRASH' in s for s in rows[1]['lines']), rows[1]
+ assert not any('SYNC_REAL_CHILD_CRASH' in s for s in rows[2]['lines']), rows[2]
+ for row in rows:
+ assert any(e['args'][0] == 'subagent.complete' for e in row['events']), row['events']
+
diff --git a/tests/tui_gateway/test_bot_live_owner_delivery.py b/tests/tui_gateway/test_bot_live_owner_delivery.py
index 3c294b6f037..638972b7ac9 100644
--- a/tests/tui_gateway/test_bot_live_owner_delivery.py
+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py
@@ -30,6 +30,7 @@ def test_refused_input_commits_failed_mailbox_receipt(tmp_path):
"_start_session_work": _start_session_work,
"_sessions_lock": threading.RLock(), "_sessions": {},
"_admit_prompt_turn": lambda *args: ([], agent),
+ "_session_profile_runtime_scope": lambda session: contextlib.nullcontext(),
"_emit": noop, "bind_transport": noop, "reset_transport": noop,
"_current_runtime_session_record": contextvars.ContextVar("refused_turn"),
"_TurnRun": prompt_turn._TurnRun,
diff --git a/tests/tui_gateway/test_credit_producer_suppression.py b/tests/tui_gateway/test_credit_producer_suppression.py
new file mode 100644
index 00000000000..9aa25a5d789
--- /dev/null
+++ b/tests/tui_gateway/test_credit_producer_suppression.py
@@ -0,0 +1,57 @@
+"""Actual response-header capture -> credit latches -> CLI/TUI presentation."""
+import json
+import time
+from types import SimpleNamespace
+
+import pytest
+from run_agent import AIAgent
+from tui_gateway import server
+from hermes_cli.cli_stream_mixin import CLIStreamMixin
+from tests.agent.test_credits_tracker import HEALTHY_HEADERS, DEPLETED_HEADERS
+
+
+class CLI(CLIStreamMixin):
+ def _invalidate(self):
+ pass
+
+
[email protected]("setting", [None, False, True])
[email protected]("surface", ["cli", "tui"])
+def test_actual_credit_capture_depletion_and_recovery(tmp_path, monkeypatch, setting, surface):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ cfg = {} if setting is None else {"display": {"suppress_warning_notifications": setting}}
+ (tmp_path / "config.yaml").write_text(json.dumps(cfg))
+ agent = object.__new__(AIAgent)
+ agent.provider = "nous"
+ agent.model = "paid-model"
+ agent.base_url = ""
+ agent._credits_state = agent._credits_session_start_micros = None
+ agent._credits_notices_enabled_cache = True
+ agent._notification_config = cfg
+ observed, clears, frames = [], [], []
+ cli = CLI()
+ cli.agent = agent
+ monkeypatch.setattr(server, "write_json", lambda frame: frames.append(frame) or True)
+ monkeypatch.setitem(server._sessions, "credit", {"agent": agent, "profile_home": str(tmp_path)})
+ callback = cli._on_notice if surface == "cli" else server._agent_cbs("credit")["notice_callback"]
+ def observe(notice):
+ observed.append(notice)
+ callback(notice)
+ agent.notice_callback = observe
+ agent.notice_clear_callback = clears.append
+ for headers in (HEALTHY_HEADERS, DEPLETED_HEADERS, DEPLETED_HEADERS, HEALTHY_HEADERS):
+ current = dict(headers)
+ current['x-nous-credits-as-of-ms'] = str(int(time.time() * 1000))
+ agent._capture_credits(SimpleNamespace(headers=current))
+ assert sum(n.key == "credits.depleted" for n in observed) == 1
+ assert "credits.depleted" in clears
+ assert agent.get_credits_state().paid_access is True
+ assert agent.get_credits_state().remaining_micros == int(HEALTHY_HEADERS['x-nous-credits-remaining-micros'])
+ projected = getattr(cli, "_pending_credit_notices", []) if surface == "cli" else [
+ f for f in frames if f.get("params", {}).get("type") == "notification.show"]
+ levels = [row[0] for row in projected] if surface == "cli" else [
+ frame["params"]["payload"]["level"] for frame in projected]
+ assert ("error" in levels) is not (setting is True)
+ assert "success" in levels # recovery is informational, not a warning
+ assert sum(n.key == "credits.restored" for n in observed) == 1
diff --git a/tests/tui_gateway/test_diagnostic_notification_presentation.py b/tests/tui_gateway/test_diagnostic_notification_presentation.py
new file mode 100644
index 00000000000..a94a4b29545
--- /dev/null
+++ b/tests/tui_gateway/test_diagnostic_notification_presentation.py
@@ -0,0 +1,56 @@
+"""Diagnostic wake execution and structured controls survive a presentation veto."""
+import threading
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from agent.notification_presentation import notification_turn
+from tui_gateway import server
+
+
[email protected]("muted", [False, True])
+def test_real_tui_emitter_keeps_control_frames_and_restores_callbacks(monkeypatch, muted):
+ frames = []
+ monkeypatch.setattr(server, "write_json", lambda frame: frames.append(frame) or True)
+ callback = Mock()
+ agent = SimpleNamespace(status_callback=callback, clarify_callback=callback)
+ with notification_turn(agent, muted=muted, session_id="session"):
+ server._emit("message.delta", "session", {"text": "diagnostic echoed by model"})
+ server._emit("message.complete", "session", {"text": "diagnostic echoed by model"})
+ agent.clarify_callback("question", ["choice"])
+ server._emit("notification.clear", "session", {"key": "cleared"})
+ assert [frame["params"]["type"] for frame in frames] == (
+ ["notification.clear"] if muted else ["message.delta", "message.complete", "notification.clear"])
+ assert agent.status_callback is callback
+ callback.assert_called_once_with("question", ["choice"])
+ server._emit("message.delta", "session", {"text": "next human result"})
+ assert frames[-1]["params"]["payload"]["text"] == "next human result"
+
+
[email protected]("suppress", [False, True])
+def test_tui_kanban_splits_diagnostics_from_results_before_wake(tmp_path, monkeypatch, suppress):
+ from gateway.warning_notifications import DiagnosticText
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(not suppress).lower()}}}")
+ owner = tmp_path / "owner"
+ owner.mkdir()
+ (owner / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}")
+ monkeypatch.setattr(server, "_collect_kanban_notifications", lambda session: [])
+ emitted, submitted = [], []
+ monkeypatch.setattr(server, "_emit", lambda *args: emitted.append(args))
+ monkeypatch.setattr(server, "_notif_submit", lambda *args, **kwargs: submitted.append((args, kwargs)))
+ session = {"profile_home": str(owner), "history_lock": threading.RLock(), "_kanban_pending": [DiagnosticText("worker crash"), "requested result"]}
+ server._notif_poll_kanban("session", session)
+ if not suppress:
+ assert submitted[0][0][3] == "worker crash\nrequested result"
+ assert submitted[0][1] == {}
+ assert session["_kanban_pending"] == []
+ return
+ assert submitted[0][0][3] == "worker crash"
+ assert submitted[0][1]["display_metadata"]["notification_category"] == "diagnostic"
+ assert session["_kanban_pending"] == ["requested result"]
+ session["running"] = False
+ server._notif_poll_kanban("session", session)
+ assert submitted[1][0][3] == "requested result"
+ assert submitted[1][1] == {}
diff --git a/tests/tui_gateway/test_diagnostic_turn_end_to_end.py b/tests/tui_gateway/test_diagnostic_turn_end_to_end.py
new file mode 100644
index 00000000000..db03d75af5e
--- /dev/null
+++ b/tests/tui_gateway/test_diagnostic_turn_end_to_end.py
@@ -0,0 +1,74 @@
+"""Diagnostic wake exercises the actual TUI turn, event transport, and control callback."""
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from tui_gateway import server
+from tests.tui_gateway.test_auto_continue import turn_env, marker_home, _session
+
+
[email protected]("suppress", [False, True])
+def test_diagnostic_turn_runs_but_never_echoes_on_wire(turn_env, marker_home, monkeypatch, suppress):
+ monkeypatch.setenv("HERMES_HOME", str(marker_home))
+ (marker_home / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(not suppress).lower()}}}")
+ owner = marker_home / "owner"
+ owner.mkdir()
+ (owner / "config.yaml").write_text(f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}")
+ frames, work, controls = [], [], []
+ monkeypatch.setattr(server, "write_json", lambda frame: frames.append(frame) or True)
+ monkeypatch.setattr(server, "_start_usage_ticker", lambda *a: (threading.Event(), SimpleNamespace(join=lambda: None)))
+ agent = SimpleNamespace(session_id="session-key", clear_interrupt=lambda: None,
+ clarify_callback=lambda *a: controls.append(a))
+ def run(message, **kwargs):
+ work.append(message)
+ kwargs["stream_callback"]("technical diagnostic echo")
+ if agent.interim_assistant_callback:
+ agent.interim_assistant_callback("technical interim")
+ agent.clarify_callback("Recovery approval?", ["yes", "no"])
+ return {"final_response": "technical final", "messages": []}
+ agent.run_conversation = run
+ session = _session(agent=agent, running=True)
+ session["profile_home"] = str(owner)
+ server._run_prompt_submit("request", "session", session, "engine failure",
+ display_metadata={"notification_category": "diagnostic"})
+ assert work == ["engine failure"]
+ assert controls == [("Recovery approval?", ["yes", "no"])]
+ content_frames = [f for f in frames if (f.get("params") or {}).get("type") in {"message.delta", "message.interim", "message.complete", "error"}]
+ assert bool(content_frames) is not suppress
+ assert session["running"] is False
+
+
+def test_restart_preserves_diagnostic_category_through_marker(turn_env, marker_home, monkeypatch):
+ from tui_gateway.turn_marker import read_turn_marker
+ session = _session()
+ server._record_turn_marker(session, "engine diagnostic",
+ notification_category="diagnostic")
+ marker = read_turn_marker(marker_home, "session-key")
+ assert marker["notification_category"] == "diagnostic"
+ calls = []
+ monkeypatch.setattr(server, "_start_agent_build", lambda *a: None)
+ monkeypatch.setattr(server, "_wait_agent", lambda *a, **k: None)
+ monkeypatch.setattr(server, "_ensure_active_session_slot", lambda *a: None)
+ monkeypatch.setattr(server, "_auto_continue_config", lambda: (True, 3600, 2))
+ monkeypatch.setattr(server, "_run_prompt_submit", lambda *a, **k: calls.append(k))
+ server._maybe_schedule_auto_continue("session", session, "session-key")
+ assert calls[0]["display_metadata"]["notification_category"] == "diagnostic"
+
+
+def test_next_human_followup_is_outside_diagnostic_presentation_scope(turn_env, marker_home, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(marker_home))
+ (marker_home / "config.yaml").write_text("display: {suppress_warning_notifications: true}")
+ frames = []
+ monkeypatch.setattr(server, "write_json", lambda frame: frames.append(frame) or True)
+ monkeypatch.setattr(server, "_start_usage_ticker", lambda *a: (threading.Event(), SimpleNamespace(join=lambda: None)))
+ agent = SimpleNamespace(session_id="session-key", clear_interrupt=lambda: None,
+ run_conversation=lambda *a, **k: {"final_response": "diagnostic echo", "messages": []})
+ session = _session(agent=agent, running=True)
+ def followups(*a):
+ server._emit("message.complete", "session", {"text": "next requested result"})
+ monkeypatch.setattr(server, "_run_post_turn_followups", followups)
+ server._run_prompt_submit("request", "session", session, "engine failure",
+ display_metadata={"notification_category": "diagnostic"})
+ finals = [f["params"]["payload"]["text"] for f in frames if f.get("params", {}).get("type") == "message.complete"]
+ assert finals == ["next requested result"]
diff --git a/tests/tui_gateway/test_foreground_notification_snapshot.py b/tests/tui_gateway/test_foreground_notification_snapshot.py
new file mode 100644
index 00000000000..047fcd88a25
--- /dev/null
+++ b/tests/tui_gateway/test_foreground_notification_snapshot.py
@@ -0,0 +1,129 @@
+"""Foreground decisions stay stable through file changes and child callbacks."""
+import threading
+from types import SimpleNamespace
+
+import pytest
+import yaml
+from agent.status_output import StatusOutputMixin
+from hermes_cli.cli_stream_mixin import CLIStreamMixin
+from tui_gateway import server
+from tests.tui_gateway.test_auto_continue import turn_env, marker_home, _session
+
+
+class Agent(StatusOutputMixin):
+ suppress_status_output = True
+ platform = "tui"
+ session_id = "session-key"
+ def clear_interrupt(self):
+ pass
+
+
+class CLI(CLIStreamMixin):
+ def _invalidate(self):
+ pass
+
+
[email protected]("initial", [False, True])
[email protected]("fail", [False, True])
+def test_tui_real_turn_snapshot_next_turn_and_child_threads(turn_env, marker_home, monkeypatch, initial, fail):
+ home = marker_home / "snapshot-owner"
+ home.mkdir()
+ cfg = home / "config.yaml"
+ def configure(value):
+ cfg.write_text(yaml.safe_dump({"display": {"suppress_warning_notifications": value}}))
+ configure(initial)
+ frames, seen, errors = [], [], []
+ monkeypatch.setattr(server, "write_json", lambda f: frames.append(f) or True)
+ monkeypatch.setattr(server.threading, "Thread", server._RealThread)
+ monkeypatch.setattr(server, "_start_usage_ticker", lambda *a: (threading.Event(), SimpleNamespace(join=lambda: None)))
+ agent = Agent()
+ session = _session(agent=agent, profile_home=str(home))
+ monkeypatch.setitem(server._sessions, "snapshot", session)
+ for name, cb in server._agent_cbs("snapshot").items():
+ setattr(agent, name, cb)
+ expected = [initial, not initial]
+ def run(message, **kwargs):
+ snapshot = expected[len(seen)]
+ configure(not snapshot)
+ before = len(frames)
+ def child():
+ try:
+ agent._emit_warning("same foreground warning")
+ except BaseException as exc:
+ errors.append(exc)
+ worker = server._RealThread(target=child)
+ worker.start()
+ worker.join(5)
+ assert not worker.is_alive()
+ warnings = [f for f in frames[before:] if f.get("params", {}).get("type") == "status.update"]
+ seen.append(len(warnings))
+ if fail:
+ raise RuntimeError("fixture turn failure")
+ return {"final_response": "requested result", "messages": []}
+ agent.run_conversation = run
+ for _ in expected:
+ assert server._run_prompt_submit("r", "snapshot", session, "human request")
+ session["_run_thread"].join(10)
+ assert not session["_run_thread"].is_alive()
+ assert not hasattr(agent, "_notification_config")
+ assert not errors
+ assert seen == [0 if value else 1 for value in expected]
+
+
[email protected]("initial", [False, True])
+def test_cli_callbacks_honor_bound_snapshot_not_file(tmp_path, monkeypatch, initial):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ agent = Agent()
+ agent._notification_config = {"display": {"suppress_warning_notifications": initial}}
+ surface = CLI()
+ surface.agent = agent
+ for changed in (not initial, initial, not initial):
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({"display": {"suppress_warning_notifications": changed}}))
+ surface._pending_credit_notices = []
+ surface._on_notice(SimpleNamespace(level="warn", text="same warning"))
+ assert bool(surface._pending_credit_notices) is not initial
+
+
[email protected]("initial", [False, True])
[email protected]("fail", [False, True])
+def test_cli_real_chat_binds_refreshes_and_restores_snapshot(tmp_path, monkeypatch, initial, fail):
+ from hermes_cli.cli_chat_turn_mixin import CLIChatTurnMixin
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_MANAGED_DIR", str(tmp_path / "managed"))
+ cfg = tmp_path / "config.yaml"
+ def configure(value):
+ cfg.write_text(yaml.safe_dump({"display": {"suppress_warning_notifications": value}}))
+ configure(initial)
+ seen = []
+ class Surface(CLIChatTurnMixin, CLI):
+ _active_agent_route_signature = "fixed"
+ _secret_capture_callback = None
+ def _ensure_runtime_credentials(self): return True
+ def _resolve_turn_agent_config(self, message): return {"signature": "fixed", "model": "fixture", "runtime": {}}
+ def _init_agent(self, **kwargs): return True
+ def _chat_route_images(self, message, images): return message
+ def _chat_expand_context_references(self, message): return message, None
+ def _chat_stage_user_message(self, agent, message): agent._pending_cli_user_message = {}
+ def _reset_stream_state(self): pass
+ def _chat_setup_turn_audio(self, *args): pass
+ def _chat_release_turn_audio(self, *args): pass
+ def _chat_settle_turn(self, turn):
+ if fail: raise RuntimeError("fixture settle error")
+ def _chat_render_turn(self, *args): return "requested result"
+ def _chat_monitor_agent_thread(self, turn, worker):
+ worker.join(5)
+ assert not worker.is_alive()
+ def _chat_run_agent(self, turn, message):
+ expected = [initial, not initial][len(seen)]
+ configure(not expected)
+ self._pending_credit_notices = []
+ self._on_notice(SimpleNamespace(level="warn", text="worker warning"))
+ seen.append(bool(self._pending_credit_notices))
+ surface = Surface()
+ surface.agent = Agent()
+ for _ in range(2):
+ result = surface.chat("human request")
+ assert result == (None if fail else "requested result")
+ assert not hasattr(surface.agent, "_notification_config")
+ assert not hasattr(surface.agent, "_notification_platform")
+ assert seen == [not initial, initial]
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index aecab10b4b6..af16c4cf30a 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -21016,6 +21016,7 @@ def test_prompt_submit_passes_persist_user_message_to_agent(monkeypatch):
def test_prompt_submit_releases_old_history_before_heap_trim(monkeypatch, tmp_path):
"""The trim boundary must not retain the just-pruned history snapshots."""
+ import contextlib
observed = {}
cleanup_order = []
@@ -21072,6 +21073,10 @@ def test_prompt_submit_releases_old_history_before_heap_trim(monkeypatch, tmp_pa
"reset_hermes_home_override",
lambda _token: cleanup_order.append("reset_home"),
)
+ # This test observes the worker's history-release scope, not the
+ # separate notification-policy and post-turn scopes (covered elsewhere).
+ monkeypatch.setattr(server, "_session_profile_runtime_scope",
+ lambda _session: contextlib.nullcontext())
monkeypatch.setattr("hermes_cli.mem_trim.trim_memory", _inspect_trim_frame)
resp = server.handle_request(
diff --git a/tests/tui_gateway/test_warning_callback_conservation.py b/tests/tui_gateway/test_warning_callback_conservation.py
new file mode 100644
index 00000000000..79b1a80932e
--- /dev/null
+++ b/tests/tui_gateway/test_warning_callback_conservation.py
@@ -0,0 +1,152 @@
+"""Real callback and queue boundaries; renderer preference never hides operator logs."""
+import logging
+import queue
+from types import SimpleNamespace
+
+import pytest
+import yaml
+
+from agent.status_output import StatusOutputMixin
+from tui_gateway import server
+from tests.tui_gateway.test_auto_continue import turn_env, marker_home, _session
+
+
+class Agent(StatusOutputMixin):
+ log_prefix = ""
+ suppress_status_output = True
+ platform = "tui"
+ _print_fn = None
+
+ def _touch_activity(self, *args):
+ pass
+
+
[email protected]("setting", [None, False, True])
+def test_real_tui_callbacks_filter_only_diagnostics_at_owner_sink(tmp_path, monkeypatch, setting):
+ launch, owner = tmp_path / "launch", tmp_path / "owner"
+ launch.mkdir()
+ owner.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ (launch / "config.yaml").write_text(yaml.safe_dump({"display": {"suppress_warning_notifications": setting is not True}}))
+ (owner / "config.yaml").write_text(yaml.safe_dump({} if setting is None else {"display": {"suppress_warning_notifications": setting}}))
+ frames = []
+ monkeypatch.setattr(server, "write_json", lambda frame: frames.append(frame) or True)
+ for home, muted in [(owner, setting is True), (launch, setting is not True), (owner, setting is True)]:
+ session = _session(profile_home=str(home))
+ monkeypatch.setitem(server._sessions, "warning-callback", session)
+ agent = Agent()
+ for key, callback in server._agent_cbs("warning-callback").items():
+ setattr(agent, key, callback)
+ # Intentionally invoke outside the owning context, like a callback worker.
+ frames.clear()
+ agent._emit_warning("unfamiliar warning wording")
+ agent._emit_diagnostic_status("unfamiliar fallback wording")
+ agent._emit_diagnostic_wait("unfamiliar retry wording")
+ agent._emit_notice(SimpleNamespace(level="error", text="notice detail", kind="custom", ttl_ms=0, key="custom", id="n"))
+ diagnostic_frames = list(frames)
+ agent._emit_status("⚠ user-requested progress with warning punctuation")
+ assert bool(diagnostic_frames) is not muted
+ assert len(diagnostic_frames) == (0 if muted else 4)
+ assert frames[-1]["params"]["payload"]["text"] == "⚠ user-requested progress with warning punctuation"
+
+
[email protected]("setting", [None, False, True])
+def test_post_turn_drain_uses_owner_and_preserves_real_clarify(turn_env, marker_home, monkeypatch, setting, caplog):
+ from tools.process_registry import process_registry
+ from tui_gateway import server_requests
+ owner = marker_home / "owner"
+ owner.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(marker_home))
+ (marker_home / "config.yaml").write_text(yaml.safe_dump({"display": {"suppress_warning_notifications": setting is not True}}))
+ (owner / "config.yaml").write_text(yaml.safe_dump({} if setting is None else {"display": {"suppress_warning_notifications": setting}}))
+ frames, work, controls = [], [], []
+ def wire(frame):
+ frames.append(frame)
+ if frame.get("method") == "clarify":
+ assert server_requests.resolve_response({"id": frame["id"], "result": {"answer": "yes"}})
+ return True
+ monkeypatch.setattr(server, "write_json", wire)
+ monkeypatch.setattr(server_requests, "_write", wire)
+ monkeypatch.setattr(server, "_start_usage_ticker", lambda *a: (server.threading.Event(), SimpleNamespace(join=lambda: None)))
+ monkeypatch.setattr(process_registry, "completion_queue", queue.Queue())
+ agent = SimpleNamespace(session_id="session-key", clear_interrupt=lambda: None)
+ agent.clarify_callback = server._agent_cbs("drain-owner")["clarify_callback"]
+ def run(message, **kwargs):
+ work.append(message)
+ controls.append(agent.clarify_callback("Continue recovery?", ["yes", "no"]))
+ logging.getLogger("operator").warning("watch diagnostic retained")
+ return {"final_response": "diagnostic final", "messages": []}
+ agent.run_conversation = run
+ session = _session(agent=agent, profile_home=str(owner))
+ monkeypatch.setitem(server._sessions, "drain-owner", session)
+ process_registry.completion_queue.put({"type": "watch_disabled", "session_id": "proc", "session_key": "session-key",
+ "origin_ui_session_id": "drain-owner", "message": "watch diagnostic"})
+ with caplog.at_level(logging.WARNING, logger="operator"):
+ server._run_post_turn_followups("request", "drain-owner", session, {}, None)
+ assert len(work) == 1
+ assert controls == ["yes"]
+ assert process_registry.completion_queue.empty()
+ assert "watch diagnostic retained" in caplog.text
+ presentation = [f for f in frames if f.get("params", {}).get("type") in {"status.update", "message.complete", "message.start", "error"}]
+ assert bool(presentation) is not (setting is True)
+ assert len([f for f in frames if f.get("method") == "clarify"]) == 1
+
+
[email protected]("setting", [None, False, True])
+def test_diagnostic_turn_callbacks_from_real_worker_keep_controls_and_logs(turn_env, marker_home, monkeypatch, setting, caplog):
+ from tui_gateway import server_requests
+ monkeypatch.setenv("HERMES_HOME", str(marker_home))
+ (marker_home / "config.yaml").write_text(yaml.safe_dump(
+ {} if setting is None else {"display": {"suppress_warning_notifications": setting}}))
+ frames, controls, failures = [], [], []
+ def wire(frame):
+ frames.append(frame)
+ if frame.get("method") == "clarify":
+ assert server_requests.resolve_response({"id": frame["id"], "result": {"answer": "yes"}})
+ return True
+ monkeypatch.setattr(server, "write_json", wire)
+ monkeypatch.setattr(server_requests, "_write", wire)
+ monkeypatch.setattr(server, "_start_usage_ticker", lambda *a: (server.threading.Event(), SimpleNamespace(join=lambda: None)))
+ # The normal worker starts after the submitter releases _sessions_lock.
+ # The shared inline-thread fixture instead holds that lock while joining
+ # this real callback thread, creating a fixture-only deadlock.
+ monkeypatch.setattr(server.threading, "Thread", server._RealThread)
+ agent = Agent()
+ agent.session_id = "session-key"
+ agent.clear_interrupt = lambda: None
+ session = _session(agent=agent, profile_home=str(marker_home), running=True)
+ monkeypatch.setitem(server._sessions, "thread-owner", session)
+ for key, callback in server._agent_cbs("thread-owner").items():
+ setattr(agent, key, callback)
+ def run(message, **kwargs):
+ def worker():
+ try:
+ # Concrete callbacks can be retained by provider/helper workers.
+ agent._emit_status("plain wake progress")
+ agent._emit_wait_notice("plain wake thinking")
+ agent._emit_notice(SimpleNamespace(level="info", text="wake notice", kind="custom", ttl_ms=0, key="custom", id="n"))
+ kwargs["stream_callback"]("wake stream")
+ controls.append(agent.clarify_callback("Continue recovery?", ["yes", "no"]))
+ logging.getLogger("operator").warning("worker diagnostic retained")
+ except BaseException as exc:
+ failures.append(exc)
+ thread = server._RealThread(target=worker)
+ thread.start()
+ thread.join(timeout=5)
+ assert not thread.is_alive()
+ return {"final_response": "wake result", "messages": []}
+ agent.run_conversation = run
+ with caplog.at_level(logging.WARNING, logger="operator"):
+ server._run_prompt_submit("request", "thread-owner", session, "engine failure",
+ display_metadata={"notification_category": "diagnostic"})
+ session["_run_thread"].join(timeout=10)
+ assert not session["_run_thread"].is_alive()
+ assert not failures
+ assert controls == ["yes"]
+ assert "worker diagnostic retained" in caplog.text
+ presentation = [f for f in frames if f.get("params", {}).get("type") in
+ {"status.update", "thinking.delta", "notification.show", "message.delta", "message.complete"}]
+ assert len(presentation) == (0 if setting is True else 5)
+ # Once the turn completes, the same sink must present the next requested progress.
+ agent._emit_status("next requested progress")
+ assert frames[-1]["params"]["payload"]["text"] == "next requested progress"
diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.py
index eecb329dc4b..104f03b4561 100644
--- a/tools/bot_live_delivery.py
+++ b/tools/bot_live_delivery.py
@@ -163,6 +163,7 @@ def _write(path: Path, record: dict[str, Any]) -> None:
def deliver_to_live_owner(
profile_home: Path | str, owner: dict[str, Any], message: str,
*, delivery_id: str | None = None, author: dict[str, Any] | None = None,
+ notification_category: str = "result",
) -> dict[str, Any]:
"""Return durable admission immediately, without waiting for the owner.
@@ -177,12 +178,15 @@ def deliver_to_live_owner(
path = root / f"{key}.json"
existing = _read(path)
if existing is not None:
- if existing["owner"] != pinned or existing["message"] != message or existing.get("author") != author:
+ if (existing["owner"] != pinned or existing["message"] != message or existing.get("author") != author
+ or existing.get("notification_category", "result") != notification_category):
raise ValueError("delivery id already belongs to a different payload")
return existing
record = dict(delivery_id=key, id=key, owner=pinned, **pinned,
message=message, status="queued", created_at=time.time_ns(),
sequence=_next_sequence(root), **({"author": dict(author)} if author else {}))
+ if notification_category == "diagnostic":
+ record["notification_category"] = notification_category
_write(path, record)
return record
diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.py
index cf0121876d9..5c10e3fa503 100644
--- a/tools/delegate_tool_progress.py
+++ b/tools/delegate_tool_progress.py
@@ -298,6 +298,7 @@ class _ChildProgressRelay:
subagent_id, parent_id, depth, model, toolsets
)
self.batch: List[str] = []
+ self.parent_scope: Any = None # owning parent agent; set by _build_child_progress_callback
self.tool_count = 0 # per-subagent running counter
def _prefix(self) -> str:
@@ -349,11 +350,20 @@ class _ChildProgressRelay:
def _on_complete(self, tool_name, preview, args, kwargs):
# Failed child: echo one clean reason line into the CLI tree so the human
# sees WHY, not just a vanished branch (gateway renders off the relayed event).
+ # The echo is an automatic diagnostic presentation: it goes through the warning
+ # boundary under the parent's turn snapshot. The relayed event (the gateway's
+ # producer, which classifies it) and the child result are never gated here.
if kwargs.get("status") in SUBAGENT_FAILURE_STATUSES:
- self._tree_line(format_subagent_failure_line(
- self.goal_label, kwargs.get("status"), error=kwargs.get("summary") or preview,
- duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
- ))
+ from gateway.warning_notifications import render_notification
+ parent = self.parent_scope
+ render_notification(
+ lambda: self._tree_line(format_subagent_failure_line(
+ self.goal_label, kwargs.get("status"), error=kwargs.get("summary") or preview,
+ duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
+ )),
+ platform=getattr(parent, "_notification_platform", getattr(parent, "platform", "cli")),
+ user_config=getattr(parent, "_notification_config", None),
+ )
self._relay("subagent.complete", preview=preview, **kwargs)
def _on_text(self, tool_name, preview, args, kwargs):
@@ -416,6 +426,8 @@ def _build_child_progress_callback(
if session_ref is not None:
# Not an identity kwarg (underscore-prefixed, never relayed); only scopes the batch ordinal.
session_ref["_parent_scope"] = parent_agent
- return _ChildProgressRelay(
+ relay = _ChildProgressRelay(
task_index, goal, spinner, parent_cb, task_count, subagent_id, parent_id, depth, model, toolsets, session_ref,
)
+ relay.parent_scope = parent_agent
+ return relay
diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.py
index cf9576b7b86..02288733ed9 100644
--- a/tools/process_registry_notifications.py
+++ b/tools/process_registry_notifications.py
@@ -336,16 +336,20 @@ class TimelineNotification(str):
display_text: str
display_kind: str
+ notification_category: str
- def __new__(cls, text: str, display_text: str, display_kind: str):
+ def __new__(cls, text: str, display_text: str, display_kind: str, notification_category: str = "result"):
instance = super().__new__(cls, text)
instance.display_text = display_text
instance.display_kind = display_kind
+ instance.notification_category = notification_category
return instance
@classmethod
def for_delegation(cls, text: str, event: dict) -> "TimelineNotification":
- return cls(text, async_delegation_display_text(event), "async_delegation_complete")
+ from agent.notification_presentation import diagnostic_process_event
+ return cls(text, async_delegation_display_text(event), "async_delegation_complete",
+ "diagnostic" if diagnostic_process_event(event) else "result")
def _delegation_attribution_line(evt: dict) -> "str | None":
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
index c30dc362265..96468334eb6 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -78,6 +78,43 @@ def _mirror_subagent_to_child(event_type: str, payload: dict) -> None:
_child_mirrors.pop(child_key, None)
+def _agent_presentation_enabled(sid: str, *, diagnostic: bool) -> bool:
+ from gateway.warning_notifications import warning_notifications_enabled
+ with _sessions_lock:
+ session = _sessions.get(sid)
+ # Callback workers do not necessarily inherit the turn's ContextVars. The
+ # existing agent latch follows the same serialized turn across those threads.
+ if getattr((session or {}).get("agent"), "_mute_notification_reply", False):
+ return False
+ if not diagnostic:
+ return True
+ with _session_profile_runtime_scope(session or {}):
+ # Sole TUI policy read for agent callbacks; sinks below call this instead of re-deriving it.
+ return warning_notifications_enabled("tui", getattr((session or {}).get("agent"), "_notification_config", None))
+
+
+def _agent_status_update(sid: str, kind: str, text: str | None = None) -> None:
+ from gateway.warning_notifications import is_warning_status
+ if not _agent_presentation_enabled(sid, diagnostic=is_warning_status(kind, text if text is not None else kind)):
+ return
+ _status_update(sid, str(kind), None if text is None else str(text))
+
+
+def _agent_thinking_update(sid: str, text: str) -> None:
+ from gateway.warning_notifications import DiagnosticText
+ if not _agent_presentation_enabled(sid, diagnostic=isinstance(text, DiagnosticText)):
+ return
+ _emit("thinking.delta", sid, {"text": text})
+
+
+def _agent_notice_update(sid: str, notice) -> None:
+ if not _agent_presentation_enabled(sid, diagnostic=notice.level in {"warn", "error"}):
+ return
+ _emit("notification.show", sid,
+ {"text": notice.text, "level": notice.level, "kind": notice.kind,
+ "ttl_ms": notice.ttl_ms, "key": notice.key, "id": notice.id})
+
+
def _agent_cbs(sid: str) -> dict:
def _read_block(method: str, timeout: int):
# read_terminal / read_preview (desktop GUI): server request like clarify; the preview
@@ -92,16 +129,14 @@ def _agent_cbs(sid: str) -> dict:
"tool_progress_callback": lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
sid, event_type, name, preview, args, **kwargs),
"tool_gen_callback": lambda name: _tool_progress_enabled(sid) and _emit("tool.generating", sid, {"name": name}),
- "thinking_callback": lambda text: _emit("thinking.delta", sid, {"text": text}),
+ "thinking_callback": lambda text: _agent_thinking_update(sid, text),
# Affection reaction (ily / <3 / good bot) → hearts; core-detected so TUI/desktop share it.
"reaction_callback": lambda kind: _emit("reaction", sid, {"kind": kind}),
"reasoning_callback": lambda text: _emit(
"reasoning.delta", sid, {"text": text, **({"verbose": True} if _session_verbose(sid) else {})}),
- "status_callback": lambda kind, text=None: _status_update(sid, str(kind), None if text is None else str(text)),
+ "status_callback": lambda kind, text=None: _agent_status_update(sid, kind, text),
# Credits/notice spine: AgentNotice → notification.show; recovery → notification.clear.
- "notice_callback": lambda n: _emit(
- "notification.show", sid,
- {"text": n.text, "level": n.level, "kind": n.kind, "ttl_ms": n.ttl_ms, "key": n.key, "id": n.id}),
+ "notice_callback": lambda n: _agent_notice_update(sid, n),
"notice_clear_callback": lambda key: _emit("notification.clear", sid, {"key": key}),
"clarify_callback": lambda q, c, multi_select=False, questions=None: (
_clarify_block(sid, q, c, multi_select=multi_select, questions=questions)),
@@ -395,11 +430,23 @@ def _preview_restart_callbacks(parent: str, task_id: str) -> dict:
if preview or name:
progress(str(preview) if preview else f"{event_type.replace('.', ' ')}: {name}")
+ _restart_status = _restart_status_factory(parent, progress)
return {
"tool_start_callback": tool_start, "tool_complete_callback": tool_complete,
"tool_progress_callback": tool_progress,
"tool_gen_callback": lambda name: progress(f"Preparing {name}"),
- "status_callback": lambda kind, text=None: progress(text if text is not None else kind)}
+ "status_callback": _restart_status}
+
+
+def _restart_status_factory(parent: str, progress):
+ """Restart-panel status rows: automatic warnings honor the TUI policy like the main agent's sink."""
+ def _restart_status(kind, text=None):
+ from gateway.warning_notifications import is_warning_status
+ message = text if text is not None else kind
+ if is_warning_status(kind, message) and not _agent_presentation_enabled(parent, diagnostic=True):
+ return
+ progress(message)
+ return _restart_status
def _rebuild_session_agent(sid: str, session: dict, **kwargs):
diff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.py
index 0bf80e54c95..37d57766942 100644
--- a/tui_gateway/model_switch.py
+++ b/tui_gateway/model_switch.py
@@ -390,7 +390,11 @@ def _sync_agent_model_with_config(sid: str, session: dict) -> None:
sid, session, raw, confirm_expensive_model=True, pin_session_override=False,
persist_override=False)
except Exception as e:
- _emit("error", sid, {"message": f"Could not switch to configured model {model}: {e}"})
+ logger.warning("Configured model %s could not be adopted for session %s: %s", model, sid, e)
+ from gateway.warning_notifications import render_notification
+ render_notification(
+ lambda: _emit("error", sid, {"message": f"Could not switch to configured model {model}: {e}"}),
+ platform="tui", user_config=getattr(session.get("agent"), "_notification_config", None))
def _pending_switch_selection_warning(model: str, provider: str) -> str | None:
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index d04de58ecf9..c39d5378763 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -160,7 +160,8 @@ def _admit_prompt_turn(
return images, agent
-def _record_turn_marker(session: dict, text: Any, *, auto_continue: bool = True) -> str:
+def _record_turn_marker(session: dict, text: Any, *, auto_continue: bool = True,
+ notification_category: str | None = None) -> str:
"""Write the durable crash marker; returns the session key it was written under (compression
can rotate session_key mid-turn). A surviving marker means the process died mid-turn.
The key is published before the disk write so an interrupt racing startup can retire
@@ -173,7 +174,9 @@ def _record_turn_marker(session: dict, text: Any, *, auto_continue: bool = True)
with session["history_lock"]:
session["_active_turn_marker_key"] = marker_key
record_turn_start(marker_home, marker_key, marker_text, attempts=marker_attempt,
- auto_continue=auto_continue)
+ auto_continue=auto_continue,
+ **({"notification_category": "diagnostic"}
+ if notification_category == "diagnostic" else {}))
with session["history_lock"]:
marker_cancelled = bool(session.get("_turn_cancel_requested"))
if marker_cancelled:
@@ -331,7 +334,10 @@ def _goal_followup_after_turn(
recovery_prompt, recovery_notice = _plan_goal_compression_recovery(
session, result, status=status, raw=raw)
if recovery_notice:
- _emit("status.update", sid, {"kind": "goal", "text": recovery_notice})
+ from gateway.warning_notifications import render_notification
+ render_notification(
+ lambda: _emit("status.update", sid, {"kind": "goal", "text": recovery_notice}),
+ platform="tui", user_config=getattr(session.get("agent"), "_notification_config", None))
goal_followup = recovery_prompt or None
except Exception as _goal_recovery_exc:
_hook_failure("goal compression recovery", _goal_recovery_exc)
@@ -438,18 +444,21 @@ def _run_post_turn_followups(
# not consume session A's event. Unclaimable events are requeued for the poller.
try:
from tools.process_registry import process_registry
- drained = process_registry.drain_notifications(
- session_key=session.get("session_key", ""),
- owns_event=lambda e: _session_owns_notification_event(sid, session, e),
- skip_poll_observed=False)
- from tools.process_registry_notifications import format_process_notification
- deferred = []
- _notif_handle_ready(
- sid, session, [event for event, _text in drained],
- session.setdefault("_notification_emitted", set()), process_registry,
- format_process_notification, deferred, owned=True)
- for event in deferred:
- process_registry.completion_queue.put(event)
+ # _finish_turn has released the worker's runtime scope. Queue ownership,
+ # notification policy and nested dispatch still belong to this session.
+ with _session_profile_runtime_scope(session):
+ drained = process_registry.drain_notifications(
+ session_key=session.get("session_key", ""),
+ owns_event=lambda e: _session_owns_notification_event(sid, session, e),
+ skip_poll_observed=False)
+ from tools.process_registry_notifications import format_process_notification
+ deferred = []
+ _notif_handle_ready(
+ sid, session, [event for event, _text in drained],
+ session.setdefault("_notification_emitted", set()), process_registry,
+ format_process_notification, deferred, owned=True)
+ for event in deferred:
+ process_registry.completion_queue.put(event)
except Exception as _drain_exc:
_hook_failure("completion queue drain", _drain_exc)
@@ -539,7 +548,9 @@ def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, images
prompt = ctx.message
st.prompt_text = prompt if isinstance(prompt, str) else ""
run_message: Any = _route_turn_images(agent, prompt, images) if images else prompt
- st.tts_queue, st.thinking_started = _start_turn_voice()
+ from agent.notification_presentation import event_presentation_muted
+ if not event_presentation_muted("message.delta", sid):
+ st.tts_queue, st.thinking_started = _start_turn_voice()
# Per-turn API-message notes: barge mid-speech, reactions, HUD surface (per-turn state
# that must not touch the byte-stable system prompt).
from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE, take_speech_interrupted
@@ -562,6 +573,8 @@ def _invoke_agent(
hold = {"buf": "", "held": ""} if _is_bot_mode_session(session) else None
def _stream(delta):
+ if getattr(agent, "_mute_notification_reply", False):
+ return
if hold is not None and isinstance(delta, str):
from gateway.response_filters import is_partial_silence_marker
hold["buf"] += delta
@@ -581,6 +594,8 @@ def _invoke_agent(
# Interim assistant text (commentary beside tool calls, pre-nudge final answer) is sealed
# by the desktop as its own segment instead of being lost to message.complete.
def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
+ if getattr(agent, "_mute_notification_reply", False):
+ return
_emit("message.interim", sid, {"text": text, "already_streamed": already_streamed})
agent.interim_assistant_callback = (
_interim_assistant_cb if _load_interim_assistant_messages() else None)
@@ -609,7 +624,9 @@ def _invoke_agent(
"session.title", sid, {"session_id": _k, "title": t})
_usage_stop, _usage_thread = _start_usage_ticker(sid, agent)
try:
- st.result = agent.run_conversation(run_message, **st.run_kwargs)
+ from agent.notification_presentation import notification_turn, event_presentation_muted
+ with notification_turn(agent, muted=event_presentation_muted("message.delta", sid), session_id=sid):
+ st.result = agent.run_conversation(run_message, **st.run_kwargs)
finally:
# Stop AND join before anything emits: a tick surviving past message.complete would
# roll the client's usage back to a stale snapshot (unbounded join: same worst case).
@@ -863,6 +880,13 @@ def _run_prompt_submit(
if admitted is None:
return False
images, agent = admitted
+ from gateway.warning_notifications import diagnostic_turn_muted
+ from agent.notification_presentation import notification_config_snapshot
+ with _session_profile_runtime_scope(session):
+ notification_config = notification_config_snapshot()
+ muted = diagnostic_turn_muted(display_metadata, "tui", notification_config)
+ if muted:
+ display_kind = "hidden"
# The ONE INFO record proving a prompt was accepted by THIS process; ties ui sid,
# session_key and the agent's live session_id together. No prompt content is logged.
_turn_started_monotonic = time.monotonic()
@@ -877,9 +901,10 @@ def _run_prompt_submit(
"kind=%s chars=%s images=%d",
sid, session.get("session_key") or "", getattr(agent, "session_id", "") or "",
display_kind or "user", len(text) if isinstance(text, str) else "-", len(images))
- _emit("message.start", sid)
+ if not muted:
+ _emit("message.start", sid)
- def run():
+ def run_body():
# RPC-dispatcher ContextVars do not follow onto this thread: rebind the transport
# before any tool can commission a child (delegate_task captures it as authority).
transport_token = bind_transport(session.get("transport"))
@@ -887,7 +912,8 @@ def _run_prompt_submit(
st = _TurnRun(
session["agent"], session.pop("one_turn_model_restore", None), terminal_callback,
receipt_committed=terminal_callback is None)
- st.marker_key = _record_turn_marker(session, text, auto_continue=terminal_callback is None)
+ st.marker_key = _record_turn_marker(session, text, auto_continue=terminal_callback is None,
+ notification_category=(display_metadata or {}).get("notification_category"))
goal_followup = None
try:
prepared = _prepare_turn_input(sid, session, st, text, images)
@@ -948,7 +974,17 @@ def _run_prompt_submit(
session.pop("_hosted_room_task", None)
session.pop("_auto_continue_scheduled", None)
_emit_settled_session_info(sid, session, st.agent)
- _run_post_turn_followups(rid, sid, session, st.result, goal_followup)
+ return st.result, goal_followup
+ def run():
+ from agent.notification_presentation import notification_turn
+ # _prepare_turn_input owns profile binding for the worker. The context
+ # here only gates presentation; do not introduce a second runtime scope.
+ from agent.notification_presentation import notification_policy_snapshot
+ with notification_policy_snapshot(agent, "tui", notification_config), notification_turn(agent, muted=muted, session_id=sid):
+ followup = run_body()
+ if followup is not None:
+ _run_post_turn_followups(rid, sid, session, *followup)
+ run_thread = threading.Thread(target=run, daemon=True)
# The handle is resolved BEFORE _sessions_lock: a profile session opens its own SessionDB through the
# state registry, and _sessions_lock gates every create/close/prompt on this backend.
with _routing_provenance_db(session) as routing_db, _sessions_lock:
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index aee995607cb..ba503989d82 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -635,6 +635,9 @@ def _event_frame(event: str, sid: str, payload: dict | None = None) -> dict:
def _emit(event: str, sid: str, payload: dict | None = None) -> bool:
+ from agent.notification_presentation import event_presentation_muted
+ if event_presentation_muted(event, sid):
+ return False
return write_json(_event_frame(event, sid, payload))
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index 9a82ca0568d..442038b0741 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -109,9 +109,15 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->
# nested notes). Set here, not at schedule time, so a bail above leaves nothing for a racing user turn.
session["_auto_continue_attempt"], session["_auto_continue_prompt"] = attempt, marker["prompt"]
try:
- _emit("status.update", sid, {"kind": "process", "text": "Resuming interrupted turn…"})
- _emit("message.start", sid)
- _run_prompt_submit(rid, sid, session, text, display_kind="auto_continue")
+ from gateway.warning_notifications import render_notification
+ diagnostic = marker.get("notification_category") == "diagnostic"
+ with _session_profile_runtime_scope(session):
+ def announce():
+ _emit("status.update", sid, {"kind": "process", "text": "Resuming interrupted turn…"})
+ _emit("message.start", sid)
+ render_notification(announce, platform="tui", diagnostic=diagnostic)
+ _run_prompt_submit(rid, sid, session, text, display_kind="auto_continue",
+ **({"display_metadata": {"notification_category": "diagnostic"}} if diagnostic else {}))
except Exception as exc:
_notif_log_failure("auto-continue dispatch failed", exc)
_notif_release_turn(session) # rebound from session_notifications
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index d31f5e18419..a261db1fb6c 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -158,7 +158,10 @@ def _notif_log_failure(what: str, exc: BaseException) -> None:
def _notif_submit(rid: str, sid: str, session: dict, text: str, what: str, **kwargs) -> None:
"""message.start + _run_prompt_submit for a claimed (running=True) turn; releases on failure."""
try:
- _emit("message.start", sid)
+ from gateway.warning_notifications import render_notification
+ with _session_profile_runtime_scope(session):
+ render_notification(lambda: _emit("message.start", sid), platform="tui",
+ diagnostic=(kwargs.get("display_metadata") or {}).get("notification_category") == "diagnostic")
_run_prompt_submit(rid, sid, session, text, **kwargs)
except Exception as exc:
_notif_log_failure(what, exc)
@@ -374,7 +377,12 @@ def _kb_poll_board(_kb, slug: str, session_key: str) -> list:
if not events:
continue
task = _kb.get_task(conn, sub["task_id"])
- texts.extend(t for t in (_format_kanban_event_text(sub, task, ev, slug) for ev in events) if t)
+ from gateway.kanban_watchers_notifier import diagnostic_event
+ from gateway.warning_notifications import DiagnosticText
+ for ev in events:
+ text = _format_kanban_event_text(sub, task, ev, slug)
+ if text:
+ texts.append(DiagnosticText(text) if diagnostic_event(ev) else text)
# Unsubscribe only on archive: ``done`` is reversible in review/controller flows, so keeping the sub lets a
# later reopen notify the same session. The claimed cursor prevents replay.
if task and getattr(task, "status", "") == "archived":
@@ -412,6 +420,11 @@ def _collect_kanban_notifications(session: dict) -> list:
def _notif_poll_kanban(sid: str, session: dict) -> None:
+ with _session_profile_runtime_scope(session):
+ _notif_poll_kanban_scoped(sid, session)
+
+
+def _notif_poll_kanban_scoped(sid: str, session: dict) -> None:
"""One kanban poll: emit new texts, buffer them, and run the buffered batch as a turn if idle. Events are
cursor-claimed (never re-queued), so they wait in the buffer instead of dropping the agent turn."""
try:
@@ -420,15 +433,24 @@ def _notif_poll_kanban(sid: str, session: dict) -> None:
_notif_log_failure("kanban notification poll failed", exc)
texts = []
for text in texts:
- _emit("status.update", sid, {"kind": "process", "text": text})
+ from gateway.warning_notifications import DiagnosticText, render_notification
+ render_notification(lambda: _emit("status.update", sid, {"kind": "process", "text": text}),
+ platform="tui", diagnostic=isinstance(text, DiagnosticText))
if texts:
session.setdefault("_kanban_pending", []).extend(texts)
if not session.get("_kanban_pending") or not _notif_claim_turn(session):
return
with session["history_lock"]:
- batch, session["_kanban_pending"] = list(session.get("_kanban_pending") or []), []
+ pending = session.get("_kanban_pending") or []
+ from gateway.warning_notifications import DiagnosticText, warning_notifications_enabled
+ split = not warning_notifications_enabled("tui")
+ diagnostic = split and isinstance(pending[0], DiagnosticText)
+ batch = [text for text in pending if not split or isinstance(text, DiagnosticText) == diagnostic]
+ session["_kanban_pending"] = [text for text in pending if split and isinstance(text, DiagnosticText) != diagnostic]
with contextlib.suppress(Exception):
- _notif_submit(f"__notif__{int(time.time() * 1000)}", sid, session, "\n".join(batch), "kanban notification dispatch failed")
+ _notif_submit(f"__notif__{int(time.time() * 1000)}", sid, session, "\n".join(batch),
+ "kanban notification dispatch failed",
+ **({"display_metadata": {"notification_category": "diagnostic"}} if diagnostic else {}))
def _notif_dispatch_event(sid: str, session: dict, evt: dict, text: str) -> None:
@@ -438,6 +460,9 @@ def _notif_dispatch_event(sid: str, session: dict, evt: dict, text: str) -> None
return
kwargs = ({"display_kind": "async_delegation_complete", "display_metadata": _async_delegation_display_metadata(evt)}
if evt.get("type") == "async_delegation" else {})
+ from agent.notification_presentation import diagnostic_process_event
+ if diagnostic_process_event(evt):
+ kwargs.setdefault("display_metadata", {})["notification_category"] = "diagnostic"
try:
_notif_submit(f"__notif__{int(time.time() * 1000)}", sid, session, text, "notification poller dispatch failed", **kwargs)
except Exception:
@@ -484,7 +509,10 @@ def _notif_handle_event(sid, session, evt, emitted, registry, fmt, deferred, com
from tools.process_registry_notifications import async_delegation_display_text, process_completion_display_text
display_text = (async_delegation_display_text(evt) if is_delegation
else process_completion_display_text([evt]) if evt_type == "completion" else text)
- _emit("status.update", sid, {"kind": "process", "text": display_text})
+ from agent.notification_presentation import diagnostic_process_event
+ from gateway.warning_notifications import render_notification
+ render_notification(lambda: _emit("status.update", sid, {"kind": "process", "text": display_text}),
+ platform="tui", diagnostic=diagnostic_process_event(evt))
emitted.add(dedup_key)
if evt_type == "completion" and completions is not None:
completions.append((evt, text))
@@ -589,7 +617,9 @@ def _poll_bot_live_delivery_once(sid: str, session: dict) -> bool:
try:
started = _run_prompt_submit(f"__bot_dm__{delivery_id}", sid, session, claimed["message"],
image_paths=[], terminal_callback=terminal_receipt,
- turn_author=claimed.get("author") or None)
+ turn_author=claimed.get("author") or None,
+ **({"display_metadata": {"notification_category": "diagnostic"}}
+ if claimed.get("notification_category") == "diagnostic" else {}))
except Exception as exc:
_notif_release_turn(session)
terminal_receipt({"status": "failed", "error": str(exc)})
@@ -630,6 +660,11 @@ def _poll_bot_live_delivery_guarded(sid: str, session: dict, now: float) -> None
def _notification_poller_loop(stop_event: threading.Event, sid: str, session: dict) -> None:
+ with _session_profile_runtime_scope(session):
+ _notification_poller_scoped_loop(stop_event, sid, session)
+
+
+def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, session: dict) -> None:
"""Daemon thread (started by _init_session()) that drains the process-global completion_queue for this session
(ownership routing: _notif_handle_event) and polls ``kanban_notify_subs`` every ``_KANBAN_POLL_SECONDS`` — the
delivery path for platform="tui" rows.
diff --git a/tui_gateway/turn_marker.py b/tui_gateway/turn_marker.py
index 81830e07ea7..d23b92c4dd1 100644
--- a/tui_gateway/turn_marker.py
+++ b/tui_gateway/turn_marker.py
@@ -73,7 +73,7 @@ def _update(home: Path | str, session_key: str, mutate, what: str) -> None:
def record_turn_start(home: Path | str, session_key: str, prompt: str, *, attempts: int = 0,
- auto_continue: bool = True) -> None:
+ auto_continue: bool = True, notification_category: str | None = None) -> None:
"""Persist the marker for a turn that is about to run. ``attempts`` = how many auto-continues led to
this run (0 for a user-initiated turn); the crash-loop breaker reads it back on the next resume."""
if not session_key or not prompt:
@@ -81,6 +81,8 @@ def record_turn_start(home: Path | str, session_key: str, prompt: str, *, attemp
now = time.time()
entry = {"attempts": max(0, int(attempts)), "prompt": prompt[:_MAX_PROMPT_CHARS], "started_at": now,
"auto_continue": bool(auto_continue)}
+ if notification_category == "diagnostic":
+ entry["notification_category"] = notification_category
_update(home, session_key, lambda entries: {**_prune(entries, now), session_key: entry}, "record")
@@ -101,6 +103,8 @@ def read_turn_marker(home: Path | str, session_key: str) -> dict[str, Any] | Non
if not prompt.strip():
return None
return {"attempts": max(0, int(entry.get("attempts") or 0)), "prompt": prompt, "started_at": _started_at(entry),
- "auto_continue": bool(entry.get("auto_continue", True))}
+ "auto_continue": bool(entry.get("auto_continue", True)),
+ **({"notification_category": "diagnostic"}
+ if entry.get("notification_category") == "diagnostic" else {})}
except Exception:
return None
diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.md
index d65eae3ae7a..b32be955656 100644
--- a/website/docs/user-guide/messaging/index.md
+++ b/website/docs/user-guide/messaging/index.md
@@ -811,6 +811,50 @@ display:
long_running_notifications: false
```
+### Warning and error notifications (opt-in suppression)
+
+Automatic warning and error notifications are shown by default. To suppress
+these notifications, enable `suppress_warning_notifications` globally or for
+an individual surface:
+
+```yaml
+display:
+ suppress_warning_notifications: true
+ platforms:
+ telegram:
+ suppress_warning_notifications: false
+```
+
+This example suppresses notifications globally while keeping them visible on
+Telegram. Omit the setting or use `false` to preserve normal delivery. Platform
+overrides take precedence; `null` inherits. Invalid values do not enable
+suppression.
+
+The setting controls automatic engine warnings, retry/fallback diagnostics,
+watchdog and database notices, cron failure notifications, Kanban failure
+notifications, background/delegation diagnostics, and adapter-generated error
+notices. It applies to messaging platforms, CLI/TUI presentation and API
+notification presentation. Classification belongs to the producer: warning-like
+text in a user request or an ordinary result is not filtered by its wording.
+
+Suppression changes presentation, not execution. Existing logs, stored diagnostic
+content, retry decisions, failure state, scheduler bookkeeping and notification
+cursors remain available. A diagnostic-only internal wake can still execute, but
+its unsolicited text, media and streaming presentation are muted. Structured
+approval and clarification controls, direct command/API outcomes and requested
+results are not converted into success or discarded. API failure flags, status
+codes and usage remain truthful even when diagnostic text is hidden.
+
+Cron `failure_deliver` still selects the destination; the destination's warning
+policy determines whether an automatic failure notice is presented there.
+Suppressed deliveries are settled without claiming a successful send. Already
+admitted deliveries retain their delivery identity and outcome.
+
+Policy is resolved for the owning profile and logical destination. Agent turns
+use their turn policy; independent notifications and deferred deliveries evaluate
+policy at their own delivery boundary. Already delivered messages are not removed.
+Suppression does not fix an underlying failure or add another logging destination.
+
### Progress bubble cleanup (opt-in)
Tool-progress messages, the "still working…" heartbeat, and status-callback bubbles can also be auto-deleted after the final response lands. Enable per-platform via `display.platforms.<platform>.cleanup_progress`: