The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): keep the Slack reply-in-thread origin for near one-shots
kokhlo5263bedea1ff
diff --git a/tests/cron/test_cron_origin_synthetic_thread.py b/tests/cron/test_cron_origin_synthetic_thread.pyindex 31733c44c17..3af680df8e1 100644--- a/tests/cron/test_cron_origin_synthetic_thread.py+++ b/tests/cron/test_cron_origin_synthetic_thread.py@@ -12,10 +12,19 @@ The stamp is recognizable at capture time: a Slack session whose thread idequals the triggering message's own id is a synthetic per-message key, not adurable thread. A genuine in-thread creation has thread_id == the parentthread's id != the triggering message's own id, and must keep its thread.++Near-horizon exception (#117306): with ``platforms.slack.extra.reply_in_thread``+at its default ``true`` the assistant answers a top-level message inside a thread+keyed on that same message id, so for a job whose first fire is within the+conversation's remaining lifetime the id is the conversation's location, not a+per-message key — the thread is kept for near one-shots and still dropped for+recurring jobs and one-shots beyond the horizon window."""+from datetime import timedeltafrom unittest.mock import patch+import hermes_timefrom tools.cronjob_tools import _origin_from_env@@ -80,3 +89,65 @@ class TestSlackSyntheticThreadCapture:origin = _origin_from_env()assert origin is not Noneassert origin["thread_id"] == "1755040000.000100"+++_TOP_LEVEL_SLACK = {+ "HERMES_SESSION_PLATFORM": "slack",+ "HERMES_SESSION_CHAT_ID": "C0AGENERAL",+ # reply_in_thread default: the assistant's whole exchange lives in the thread keyed on the+ # asking message's own id (ts == thread_ts on the wire).+ "HERMES_SESSION_THREAD_ID": "1755043010.123456",+ "HERMES_SESSION_MESSAGE_ID": "1755043010.123456",+}+++def _run_at_in(minutes: int) -> str:+ return (hermes_time.now() + timedelta(minutes=minutes)).isoformat()+++class TestNearHorizonSlackThreadKept:+ """#117306 — a one-shot firing within the conversation's remaining lifetime delivers back+ into the thread the assistant opened under the asking message."""++ def test_oneshot_within_thread_horizon_keeps_thread(self):+ with _session_env(_TOP_LEVEL_SLACK):+ origin = _origin_from_env({"kind": "once", "run_at": _run_at_in(1)})+ assert origin is not None+ assert origin["thread_id"] == "1755043010.123456"++ def test_oneshot_at_horizon_boundary_keeps_thread(self):+ """The horizon itself (60 minutes) is inside the conversation's lifetime."""+ with _session_env(_TOP_LEVEL_SLACK):+ origin = _origin_from_env({"kind": "once", "run_at": _run_at_in(60)})+ assert origin is not None+ assert origin["thread_id"] == "1755043010.123456"++ def test_oneshot_beyond_thread_horizon_keeps_drop(self):+ """A one-shot months away belongs in the channel, not a thread from the day it was+ asked — the original rationale still protects this case."""+ with _session_env(_TOP_LEVEL_SLACK):+ origin = _origin_from_env({"kind": "once", "run_at": _run_at_in(61)})+ assert origin is not None+ assert origin["thread_id"] is None++ def test_recurring_schedule_keeps_drop(self):+ """A recurring job outlives any conversation; the per-message key stays synthetic."""+ with _session_env(_TOP_LEVEL_SLACK):+ origin = _origin_from_env({"kind": "interval", "minutes": 1})+ assert origin is not None+ assert origin["thread_id"] is None++ def test_unparseable_run_at_keeps_drop(self):+ """An unparseable horizon must not resurrect the thread (fail-closed to the historical+ behaviour)."""+ with _session_env(_TOP_LEVEL_SLACK):+ origin = _origin_from_env({"kind": "once", "run_at": "not-a-timestamp"})+ assert origin is not None+ assert origin["thread_id"] is None++ def test_no_schedule_falls_back_to_today_drop(self):+ """Legacy callers (no schedule) keep the unconditional drop."""+ with _session_env(_TOP_LEVEL_SLACK):+ origin = _origin_from_env()+ assert origin is not None+ assert origin["thread_id"] is Nonediff --git a/tools/cronjob_job_args.py b/tools/cronjob_job_args.pyindex 5308c65488e..cc11f993456 100644--- a/tools/cronjob_job_args.py+++ b/tools/cronjob_job_args.py@@ -1,16 +1,59 @@"""Cron job argument normalization, validation and result shaping (re-exported bytools/cronjob_tools.py)."""+import contextlibimport logging+from datetime import datetime, timedeltafrom typing import Any, Dict, List, Optional, Unionfrom cron.jobs import effective_job_state+import hermes_time+# Logger parity with the origin module.logger = logging.getLogger("tools.cronjob_tools")--def _origin_from_env() -> Optional[Dict[str, str]]:+# A one-shot firing within this many minutes is still part of the conversation that created it:+# with platforms.slack.extra.reply_in_thread at its default true, the whole exchange under a+# top-level message lives in the thread keyed on that message's own id.+_THREAD_HORIZON_MINUTES = 60+++def _first_fire_within_thread_horizon(+ schedule: Union[str, Dict[str, Any], None],+) -> bool:+ """True when the job's first fire is close enough that the creating conversation is still+ alive when it happens. Only near one-shots qualify; recurring jobs and one-shots beyond the+ horizon outlive the conversation, which is what the synthetic-drop rule protects."""+ if not schedule:+ return False+ parsed: Optional[Dict[str, Any]]+ if isinstance(schedule, dict):+ parsed = schedule+ else:+ parsed = None+ with contextlib.suppress(Exception):+ from cron.jobs import parse_schedule++ parsed = parse_schedule(schedule)+ if not isinstance(parsed, dict) or parsed.get("kind") != "once":+ return False+ run_at = parsed.get("run_at")+ if not run_at:+ return False+ try:+ fire_at = datetime.fromisoformat(str(run_at).replace("Z", "+00:00"))+ except ValueError:+ return False+ now = hermes_time.now()+ if fire_at.tzinfo is None:+ fire_at = fire_at.replace(tzinfo=now.tzinfo)+ return fire_at - now <= timedelta(minutes=_THREAD_HORIZON_MINUTES)+++def _origin_from_env(+ schedule: Union[str, Dict[str, Any], None] = None,+) -> Optional[Dict[str, str]]:from gateway.session_context import async_delivery_supported, get_session_envorigin_platform = get_session_env("HERMES_SESSION_PLATFORM")origin_chat_id = get_session_env("HERMES_SESSION_CHAT_ID")@@ -24,14 +67,26 @@ def _origin_from_env() -> Optional[Dict[str, str]]:thread_id = get_session_env("HERMES_SESSION_THREAD_ID") or None# Slack stamps every TOP-LEVEL message's own id as the session thread (a per-message# KEY, not a location); persisting it would pin all future deliveries inside an- # ephemeral thread, so thread == creating message id is synthetic and dropped.+ # ephemeral thread, so thread == creating message id is synthetic and dropped — unless+ # the job's first fire is within the conversation's remaining lifetime: under the+ # default reply_in_thread the exchange under a top-level message lives in exactly that+ # thread, so a near one-shot must deliver back into it.if thread_id and origin_platform == "slack":message_id = get_session_env("HERMES_SESSION_MESSAGE_ID") or Noneif message_id and str(thread_id) == str(message_id):- logger.debug(- "Cron origin: dropping synthetic per-message Slack "- "thread_id=%s (== creation message id)", thread_id)- thread_id = None+ if _first_fire_within_thread_horizon(schedule):+ logger.debug(+ "Cron origin: keeping synthetic Slack thread_id=%s — first fire is "+ "within the conversation horizon",+ thread_id,+ )+ else:+ logger.debug(+ "Cron origin: dropping synthetic per-message Slack "+ "thread_id=%s (== creation message id)",+ thread_id,+ )+ thread_id = Noneif thread_id:logger.debug("Cron origin captured thread_id=%s for %s:%s",diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex f9fc717fb4e..8606373bd7f 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -600,7 +600,9 @@ def _action_create(a: Dict[str, Any]) -> str:try:job = create_job_with_scheduler_registration(prompt=prompt or "", schedule=a["schedule"], name=a["name"], repeat=a["repeat"],- deliver=_resolve_cron_context_deliver(deliver), origin=_origin_from_env(), skills=canonical_skills,+ deliver=_resolve_cron_context_deliver(deliver),+ origin=_origin_from_env(a["schedule"]),+ skills=canonical_skills,model=_normalize_optional_job_value(a["model"]), provider=_normalize_optional_job_value(a["provider"]),base_url=_normalize_optional_job_value(a["base_url"], strip_trailing_slash=True),script=_normalize_optional_job_value(script), context_from=context_from,