The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): re-append in-flight job prompt after compaction
Justin Wilson0ed3f9b45be3
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 76123839452..3922dfedb26 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -521,6 +521,16 @@ _SUMMARY_END_MARKER = (_MERGED_PRIOR_CONTEXT_HEADER = "[PRIOR CONTEXT — for reference only; not a new message]"_MERGED_SUMMARY_DELIMITER = "[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW]"+# Prefixes the copy of a still-running user task that compaction re-states after+# the handoff boundary (#100818). A cron run's only user turn is the job prompt+# in the protected head, so compaction leaves it BEFORE the summary — and+# SUMMARY_PREFIX tells the model to do nothing when no user message follows.+_INFLIGHT_TASK_REPLAY_HEADER = (+ "[STILL IN PROGRESS — this is the active request, restated after the "+ "compaction boundary because it was not finished yet. Continue it; do not "+ "start over.]"+)+_SALVAGE_SUMMARY_MAX_CHARS = 8_000_SALVAGE_KEEP_RECENT_TOOLS = 2@@ -6688,6 +6698,129 @@ This compaction should PRIORITISE preserving all information related to the focureturn max(pair_end, head_end + 1)return adjusted+ @classmethod+ def _find_inflight_user_task(+ cls, messages: List[Dict[str, Any]]+ ) -> Optional[Dict[str, Any]]:+ """Return the user turn that is still awaiting completion, or ``None``.++ Scans the WHOLE transcript, not just the compressible region: a cron+ run's only user turn is the job prompt sitting in the protected head+ (``protect_first_n`` keeps system + first user), which is exactly the+ turn ``_find_last_user_message_idx`` cannot see (#100818).++ A turn is in-flight when the transcript does not already end with a+ completed assistant reply — i.e. a text-bearing assistant message with+ no pending ``tool_calls``. A trailing ``tool`` result or an assistant+ message that still has ``tool_calls`` outstanding means the run was+ interrupted mid-task and the instruction is still owed an answer.++ Handoff carriers and synthetic scaffolding rows are excluded via the+ same filter pair as ``_find_last_user_message_idx``, so an idle session+ whose only user-role row is an inherited summary yields ``None`` and is+ never re-animated (#80622).+ """+ last_user_idx = -1+ for i in range(len(messages) - 1, -1, -1):+ msg = messages[i]+ if cls._is_actionable_user_turn(+ msg+ ) and not cls._is_synthetic_compression_user_turn(msg):+ last_user_idx = i+ break+ if last_user_idx < 0:+ return None++ for msg in reversed(messages[last_user_idx + 1:]):+ if not isinstance(msg, dict) or msg.get("role") != "assistant":+ # Trailing tool result (or anything else): still mid-task.+ break+ if msg.get("tool_calls"):+ break+ if _content_text_for_contains(msg.get("content")).strip():+ # Final answer already delivered — replaying the ask would+ # hand the model finished work as a fresh instruction.+ return None+ # Empty assistant row (a bare reasoning/stub turn): keep looking.+ return messages[last_user_idx]++ def _reappend_inflight_user_task(+ self,+ compressed: List[Dict[str, Any]],+ inflight: Optional[Dict[str, Any]],+ ) -> List[Dict[str, Any]]:+ """Restate an unfinished user task after the compaction handoff.++ ``SUMMARY_PREFIX`` instructs the model to act only on a user message+ that appears AFTER the summary, and to do nothing when none does. When+ the single in-flight instruction lived in the protected head, the+ assembled transcript orders it before the handoff and the run ends in a+ ``[SILENT]`` no-op that the scheduler records as success (#100818).++ Re-append a copy of that turn after the surviving tail so the prefix's+ "latest user message" pointer resolves to it again. If the transcript+ already ends on a template-visible user row, appending a second one+ would break user/assistant alternation, so the restatement is merged+ onto the handoff carrier instead — after ``_SUMMARY_END_MARKER``, which+ is the boundary the prefix's rule is written against.+ """+ if inflight is None or not compressed:+ return compressed++ carrier_idx = -1+ for idx in range(len(compressed) - 1, -1, -1):+ if self._is_context_summary_message(compressed[idx]):+ carrier_idx = idx+ break+ if carrier_idx < 0:+ # No handoff was emitted — nothing reordered the instruction.+ return compressed++ for msg in compressed[carrier_idx + 1:]:+ if self._is_actionable_user_turn(+ msg+ ) and not self._is_synthetic_compression_user_turn(msg):+ # A real request already follows the summary.+ return compressed++ carrier = compressed[carrier_idx]+ carrier_text = _content_text_for_contains(carrier.get("content"))+ if _SUMMARY_END_MARKER not in carrier_text:+ return compressed+ if carrier_text.split(_SUMMARY_END_MARKER, 1)[1].strip():+ # The _force_user_leading layout keeps the live request on the+ # carrier itself, after the marker. Already actionable.+ return compressed++ task_text = _content_text_for_contains(inflight.get("content")).strip()+ if not task_text:+ return compressed++ if not self.quiet_mode:+ logger.info(+ "Re-appending the in-flight user task after the compaction "+ "handoff so it stays actionable (#100818)"+ )++ if _template_visible_role(compressed[-1]) == "user":+ carrier["content"] = _append_text_to_content(+ carrier.get("content"),+ "\n\n" + _INFLIGHT_TASK_REPLAY_HEADER + "\n" + task_text,+ )+ drop_stale_api_content(carrier)+ return compressed++ replay = _fresh_compaction_message_copy(inflight)+ replay.pop(_COMPACTION_TAIL_MARKER, None)+ replay["content"] = _append_text_to_content(+ replay.get("content"),+ _INFLIGHT_TASK_REPLAY_HEADER + "\n",+ prepend=True,+ )+ drop_stale_api_content(replay)+ compressed.append(replay)+ return compressed+def _ensure_last_n_user_messages_in_tail(self,messages: List[Dict[str, Any]],@@ -8524,6 +8657,14 @@ This compaction should PRIORITISE preserving all information related to the focu_merge_summary_into_tail = Falsecompressed.append(msg)+ # The assembled list can order the only live instruction BEFORE the+ # handoff (single-prompt cron shape: the job prompt is pinned in the+ # protected head). SUMMARY_PREFIX reads that as "no user message after+ # the summary → do nothing", so restate it past the boundary (#100818).+ compressed = self._reappend_inflight_user_task(+ compressed, self._find_inflight_user_task(messages)+ )+self.compression_count += 1compressed = self._sanitize_tool_pairs(compressed)diff --git a/tests/agent/test_cron_inflight_prompt_reappend_100818.py b/tests/agent/test_cron_inflight_prompt_reappend_100818.pynew file mode 100644index 00000000000..2296e1607c8--- /dev/null+++ b/tests/agent/test_cron_inflight_prompt_reappend_100818.py@@ -0,0 +1,214 @@+"""Regression coverage for #100818: compaction of a single-prompt session+(the cron shape) must not leave the model with nothing to obey.++A cron run is one user message — the job prompt — followed by nothing but+assistant/tool turns. When ContextCompressor fires mid-run, that prompt is+folded into the handoff summary and no user message survives *after* it.+SUMMARY_PREFIX then reads literally:++ If no user message appears AFTER this summary, do nothing.++so the model correctly does nothing, the scheduler sees the ``[SILENT]``+sentinel, and records ``last_status: ok`` — a silent failure.++The fix re-appends the in-flight user task after the handoff so the prefix's+"latest user message" pointer resolves to the job prompt again. The+#80622 contract is unchanged: an idle session with no in-flight task must+still be left with nothing to act on.+"""++from typing import Any, Dict, List+from unittest.mock import MagicMock, patch++from agent.context_compressor import (+ _SUMMARY_END_MARKER,+ SUMMARY_PREFIX,+ ContextCompressor,+)+++JOB_SENTINEL = "CRON_JOB_PROMPT_sentinel_brief_the_inbox_and_write_a_digest"+++def _make_compressor() -> ContextCompressor:+ with patch(+ "agent.context_compressor.get_model_context_length", return_value=100_000+ ):+ compressor = ContextCompressor(+ model="test",+ quiet_mode=True,+ protect_first_n=2,+ protect_last_n=2,+ )+ compressor.tail_token_budget = 500+ return compressor+++def _tool_pairs(count: int, start: int = 0) -> List[Dict[str, Any]]:+ """``count`` assistant(tool_calls) + tool result pairs."""+ turns: List[Dict[str, Any]] = []+ for i in range(start, start + count):+ turns.append(+ {+ "role": "assistant",+ "content": f"step {i}",+ "tool_calls": [+ {"id": f"c{i}", "function": {"name": "terminal", "arguments": "{}"}}+ ],+ }+ )+ turns.append(+ {+ "role": "tool",+ "tool_call_id": f"c{i}",+ "content": ("tool output " * 200) + f" {i}",+ }+ )+ return turns+++def _cron_transcript() -> List[Dict[str, Any]]:+ """system + one user job prompt + many tool turns, NO trailing user."""+ return [+ {+ "role": "system",+ "content": "You are Hermes. Cron preamble: if nothing to report, "+ "return [SILENT].",+ },+ {"role": "user", "content": JOB_SENTINEL},+ *_tool_pairs(40),+ ]+++def _compress(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ response = MagicMock()+ response.choices = [MagicMock()]+ response.choices[0].message.content = (+ "## Historical Task Snapshot\nUser asked: '" + JOB_SENTINEL + "'\n"+ "## Summary\nRan a bunch of terminal steps."+ )+ compressor = _make_compressor()+ with patch("agent.context_compressor.call_llm", return_value=response):+ return compressor.compress(messages, current_tokens=200_000, force=True)+++def _handoff_idx(compressed: List[Dict[str, Any]]) -> int:+ """Index of the handoff row (standalone summary or merged carrier)."""+ for idx in range(len(compressed) - 1, -1, -1):+ content = compressed[idx].get("content")+ text = content if isinstance(content, str) else str(content)+ if SUMMARY_PREFIX[:60] in text or _SUMMARY_END_MARKER in text:+ return idx+ return -1+++def _text(message: Dict[str, Any]) -> str:+ content = message.get("content")+ return content if isinstance(content, str) else str(content)+++def _actionable_user_rows(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ return [+ m+ for m in rows+ if ContextCompressor._is_actionable_user_turn(m)+ and not ContextCompressor._is_synthetic_compression_user_turn(m)+ ]+++def test_cron_job_prompt_survives_after_the_handoff():+ """The in-flight job prompt must be readable AFTER the summary boundary."""+ compressed = _compress(_cron_transcript())++ idx = _handoff_idx(compressed)+ assert idx >= 0, "expected a compaction handoff in the compressed transcript"++ after = compressed[idx + 1:]+ # The re-append may also land inside the handoff carrier itself, after the+ # end marker (the alternation-safe merge layout) — accept either shape.+ carrier_tail = _text(compressed[idx]).split(_SUMMARY_END_MARKER)[-1]++ job_after_summary = any(+ JOB_SENTINEL in _text(m) for m in _actionable_user_rows(after)+ ) or (JOB_SENTINEL in carrier_tail)+ assert job_after_summary, (+ "the in-flight cron job prompt must appear in a user message AFTER the "+ "handoff summary — SUMMARY_PREFIX orders the model to do nothing "+ "otherwise (#100818)"+ )+++def test_model_is_not_left_without_a_user_message_after_the_handoff():+ """The 'no user message after this summary → do nothing' branch of+ SUMMARY_PREFIX must not be what a mid-run cron compaction produces."""+ compressed = _compress(_cron_transcript())++ idx = _handoff_idx(compressed)+ after = compressed[idx + 1:]+ has_user_after = bool(_actionable_user_rows(after)) or bool(+ _text(compressed[idx]).split(_SUMMARY_END_MARKER)[-1].strip()+ )+ assert has_user_after, (+ "compaction left no user message after the handoff; the model is "+ "instructed to do nothing and the cron run fails silently"+ )+++def test_role_alternation_and_head_are_preserved():+ """The re-append must not create two same-role rows in a row, and must+ not disturb the cached head prefix."""+ messages = _cron_transcript()+ compressed = _compress([dict(m) for m in messages])++ assert compressed[0]["role"] == "system"+ visible = [+ m.get("role")+ for m in compressed+ if not (+ m.get("role") == "tool"+ or (m.get("role") == "assistant" and m.get("tool_calls"))+ )+ ]+ for previous, current in zip(visible, visible[1:]):+ assert not (previous == current == "user"), (+ f"consecutive user rows in compressed transcript: {visible}"+ )+++def test_idle_session_without_inflight_task_is_not_reanimated():+ """#80622 must hold: a session whose only user-role row is an inherited+ handoff has no in-flight task, so compaction must not manufacture one."""+ messages: List[Dict[str, Any]] = [+ {"role": "system", "content": "You are Hermes."},+ {+ "role": "user",+ "content": (+ SUMMARY_PREFIX+ + "\n## Historical Task Snapshot\nUser asked: 'a finished task'\n\n"+ + _SUMMARY_END_MARKER+ ),+ },+ *_tool_pairs(40),+ ]+ compressed = _compress(messages)++ assert not _actionable_user_rows(compressed), (+ "no real user turn existed before compaction — none may be invented"+ )+++def test_completed_exchange_is_not_replayed():+ """Only an in-flight task is re-appended. A turn that already produced a+ final assistant reply must not be handed back to the model as a fresh+ instruction."""+ messages = [+ *_cron_transcript(),+ {"role": "assistant", "content": "Digest written. Nothing else to do."},+ ]+ compressed = _compress(messages)++ idx = _handoff_idx(compressed)+ after = compressed[idx + 1:]+ assert not any(+ JOB_SENTINEL in _text(m) for m in _actionable_user_rows(after)+ ), "a completed exchange must not be re-appended as a new user instruction"