Skip to content

The agent that grows with you

feat(system_prompt): two-line conversation clock — anchored start + rebuild-day line (salvages #96224) (#97930)

Teknium11b98a142921
diff --git a/agent/system_prompt.py b/agent/system_prompt.py
index a765b7ccf5e..c129cd67367 100644
--- a/agent/system_prompt.py
+++ b/agent/system_prompt.py
@@ -273,6 +273,70 @@ def _plugin_section_blocks(sections: tuple, position: str) -> List[str]:
return [block] if block else []
+def _session_start_like(agent: Any, now: Any) -> Any:
+ """Best-known conversation start time, or ``now`` as a fallback.
+
+ ``Conversation started:`` must reference when the conversation actually
+ began, not when the system prompt was last (re)built. The prompt is
+ rebuilt on compression, fresh-agent gateway turns, and resume paths, and
+ stamping build time made the date drift forward across midnight (a chat
+ that started on Wednesday read as "Conversation started: Thursday" after
+ a Thursday-morning resume), contradicting the fresh per-turn time hint.
+ Prefer, in order:
+
+ 1. the timestamp embedded in ``session_id`` (``YYYYMMDD_HHMMSS_...``) —
+ immutable for the life of the session, so the line is byte-stable
+ across every rebuild boundary (preserving prefix-cache KV);
+ 2. ``agent.session_start`` (session-creation stamp);
+ 3. ``now`` (initial/legacy build without either).
+
+ Session-id and ``session_start`` stamps are recorded in the box's local
+ wall-clock; attach that zone first, then convert to the configured /
+ rendered zone (``now``'s tzinfo) so the displayed date is consistent with
+ the per-turn clock even when the box's TZ differs from the configured one.
+ """
+ from datetime import datetime
+
+ try:
+ machine_local_tz = datetime.now().astimezone().tzinfo
+ except (ValueError, OSError):
+ machine_local_tz = None
+
+ def _to_display_tz(dt: Any) -> Any:
+ if machine_local_tz is not None and dt.tzinfo is None:
+ try:
+ dt = dt.replace(tzinfo=machine_local_tz)
+ except ValueError:
+ pass
+ if getattr(now, "tzinfo", None) is not None and dt.tzinfo is not None:
+ try:
+ dt = dt.astimezone(now.tzinfo)
+ except (ValueError, OSError):
+ pass
+ return dt
+
+ # 1. Session id embeds the true start as YYYYMMDD_HHMMSS.
+ session_id = getattr(agent, "session_id", None)
+ if isinstance(session_id, str) and session_id:
+ m = re.match(r"^(\d{8})_(\d{6})", session_id)
+ if m:
+ try:
+ embedded = datetime.strptime(
+ f"{m.group(1)}_{m.group(2)}", "%Y%m%d_%H%M%S"
+ )
+ return _to_display_tz(embedded)
+ except ValueError:
+ pass
+
+ # 2. Session-creation stamp set by the runner.
+ session_start = getattr(agent, "session_start", None)
+ if hasattr(session_start, "astimezone"):
+ return _to_display_tz(session_start)
+
+ # 3. Fallback: build time.
+ return now
+
+
def _agent_home(agent: Any) -> Optional[Path]:
"""The agent's OWN profile home.
@@ -888,9 +952,26 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)
if _offset: # '-0400' -> 'UTC-04:00'
_zone_bits.append(f"UTC{_offset[:3]}:{_offset[3:]}")
_zone_suffix = f" ({', '.join(_zone_bits)})" if _zone_bits else ""
+ _start = _session_start_like(agent, now)
timestamp_line = (
- f"Conversation started: {now.strftime('%A, %B %d, %Y')}{_zone_suffix}"
+ f"Conversation started: {_start.strftime('%A, %B %d, %Y')}{_zone_suffix}"
)
+ # Second line (maintainer design, salvaging #96224's anchor): long-lived
+ # sessions — Bot Mode forever-chats, messenger channels people never
+ # close — span many days and many compactions. A lone birth date leads
+ # the model to believe it is still living in that old day. The prompt is
+ # rebuilt at every compaction boundary, so stamp the rebuild day too:
+ # 'started' stays anchored and byte-stable, 'as of' refreshes exactly
+ # when the cache prefix is already being invalidated (compaction), so
+ # the added line costs no extra cache churn. Same-day sessions skip the
+ # second line entirely — nothing to correct, and the single-line shape
+ # stays byte-identical for the day (prefix-cache safe).
+ if now.strftime("%Y%m%d") != _start.strftime("%Y%m%d"):
+ timestamp_line += (
+ f"\nToday's date (as of the last context rebuild): "
+ f"{now.strftime('%A, %B %d, %Y')} — trust this over the start "
+ f"date for what day it is now; query tools for exact time."
+ )
# Bot Chat sessions are effectively eternal — a birth date frozen in the
# prompt becomes confidently-wrong misinformation within days. Timeless
# prompts keep the identity lines but drop the date (the timezone still
diff --git a/tests/agent/test_system_prompt.py b/tests/agent/test_system_prompt.py
index dc7e7efba99..62f93731653 100644
--- a/tests/agent/test_system_prompt.py
+++ b/tests/agent/test_system_prompt.py
@@ -4,6 +4,7 @@ from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
+from zoneinfo import ZoneInfo
from agent.system_prompt import build_system_prompt, build_system_prompt_parts
@@ -290,9 +291,13 @@ def test_coding_prompt_preserves_legacy_workspace_order(monkeypatch):
monkeypatch.setattr(system_prompt, "STEER_CHANNEL_NOTE", "STEER")
monkeypatch.setattr(system_prompt, "get_hermes_home", lambda: Path("/hermes"))
+ # Production renders this as str(get_hermes_home()) + "/profiles/<name>/",
+ # and str(Path("/hermes")) is platform-dependent (backslash on Windows) —
+ # build the expectation the same way instead of hardcoding "/hermes".
+ _home_str = str(Path("/hermes"))
expected_profile = (
"Active Hermes profile: default. Other profiles (if any) live "
- "under /hermes/profiles/<name>/. Each profile has its own skills/, "
+ f"under {_home_str}/profiles/<name>/. Each profile has its own skills/, "
"plugins/, cron/, and memories/ that affect a different session than "
"this one. Do not modify another profile's skills/plugins/cron/memories "
"unless the user explicitly directs you to."
@@ -542,3 +547,120 @@ class TestMemoryProviderSystemPromptGating:
full = _build(build_system_prompt, _memory_manager=agent._memory_manager,
enabled_toolsets=["web_search"], disabled_toolsets=None)
assert block not in full
+
+
+class TestSessionStartLike:
+ """'Conversation started:' must reference the session's real start, not
+ the date the system prompt was (re)built. Builds happen on compression,
+ fresh-agent gateway turns, and resume paths; stamping build time made a
+ chat drift 'started' forward across midnight."""
+
+ def test_uses_session_id_embedded_timestamp(self):
+ from agent.system_prompt import _session_start_like
+
+ now = datetime(2026, 1, 2, 9, 0, tzinfo=ZoneInfo("UTC"))
+ agent = SimpleNamespace(
+ session_id="20260101_120000_abc123",
+ session_start=datetime(2026, 1, 1, 12, 0),
+ )
+ start = _session_start_like(agent, now)
+ assert start.strftime("%Y-%m-%d") == "2026-01-01"
+ assert start.tzinfo is not None
+
+ def test_falls_back_to_session_start(self):
+ from agent.system_prompt import _session_start_like
+
+ now = datetime(2026, 1, 2, 9, 0, tzinfo=ZoneInfo("UTC"))
+ agent = SimpleNamespace(session_id="", session_start=datetime(2026, 1, 1, 12, 0))
+ start = _session_start_like(agent, now)
+ assert start.strftime("%Y-%m-%d") == "2026-01-01"
+
+ def test_falls_back_to_now_when_no_start_known(self):
+ from agent.system_prompt import _session_start_like
+
+ now = datetime(2026, 1, 2, 9, 0, tzinfo=ZoneInfo("UTC"))
+ assert _session_start_like(SimpleNamespace(session_id=""), now) == now
+
+ def test_nonmatching_session_id_uses_session_start(self):
+ from agent.system_prompt import _session_start_like
+
+ now = datetime(2026, 1, 2, 9, 0, tzinfo=ZoneInfo("UTC"))
+ agent = SimpleNamespace(
+ session_id="plugin-section-test",
+ session_start=datetime(2026, 1, 1, 7, 30),
+ )
+ start = _session_start_like(agent, now)
+ assert start.strftime("%Y-%m-%d") == "2026-01-01"
+
+
+def test_conversation_start_uses_session_start_not_build_time(monkeypatch):
+ """Regression: a session that started on Jan 1 must still read
+ 'Conversation started: Thursday, January 01' even when the prompt is
+ rebuilt on Jan 2 (the rebuild-drift bug)."""
+ import agent.system_prompt as system_prompt
+
+ agent = _make_agent(
+ valid_tool_names=["read_file"],
+ _parallel_tool_call_guidance=False,
+ session_id="20260101_120000_abc123",
+ )
+ monkeypatch.setattr(system_prompt, "DEFAULT_AGENT_IDENTITY", "IDENTITY")
+ monkeypatch.setattr(system_prompt, "HERMES_AGENT_HELP_GUIDANCE", "HELP")
+ monkeypatch.setattr(system_prompt, "HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS", "HELP")
+ monkeypatch.setattr(system_prompt, "STEER_CHANNEL_NOTE", "STEER")
+ monkeypatch.setattr(system_prompt, "get_hermes_home", lambda: Path("/hermes"))
+
+ with (
+ patch("run_agent.load_soul_md", return_value=""),
+ patch("run_agent.build_environment_hints", return_value=""),
+ patch("run_agent.build_context_files_prompt", return_value="CONTEXT_FILES"),
+ patch(
+ "agent.coding_context.coding_system_prompt_parts",
+ return_value=([], [], []),
+ ),
+ patch("agent.file_safety._resolve_active_profile_name", return_value="default"),
+ # The system prompt is rebuilt a day LATER than the session start.
+ patch("hermes_time.now", return_value=datetime(2026, 1, 2, 9, 0)),
+ ):
+ prompt = build_system_prompt(agent, system_message="SYSTEM_MESSAGE")
+
+ assert "Conversation started: Thursday, January 01, 2026" in prompt
+ assert "Conversation started: Friday" not in prompt
+
+class TestConversationStartedTwoLine:
+ """Maintainer design on top of #96224's anchor: long-lived sessions get a
+ second 'as of the last context rebuild' line so a model in a forever-chat
+ (Bot Mode, messenger channels) is not led to believe it still lives on
+ the session's birth day. Same-day sessions keep the one-line shape."""
+
+ def _agent(self, session_id):
+ return _make_agent(
+ session_id=session_id, session_start=None,
+ _bot_chat_timeless_prompt=False,
+ )
+
+ def _volatile(self, agent):
+ import agent.system_prompt as sp
+ parts = sp.build_system_prompt_parts(agent)
+ return parts["volatile"]
+
+ def test_old_session_gets_rebuild_date_line(self):
+ vol = self._volatile(self._agent("20200110_090000_old"))
+ assert "Conversation started:" in vol
+ assert "as of the last context rebuild" in vol
+ assert "trust this over the start date" in vol
+
+ def test_same_day_session_keeps_single_line(self):
+ from hermes_time import now as hermes_now
+ sid = hermes_now().strftime("%Y%m%d_%H%M%S_fresh")
+ vol = self._volatile(self._agent(sid))
+ assert "Conversation started:" in vol
+ assert "as of the last context rebuild" not in vol
+
+ def test_timeless_bot_chat_unaffected(self):
+ agent = self._agent("20200110_090000_old")
+ agent._bot_chat_timeless_prompt = True
+ vol = self._volatile(agent)
+ assert "Conversation started:" not in vol
+ assert "as of the last context rebuild" not in vol
+