Skip to content

The agent that grows with you

fix(cron): reject invalid enclosing response frames

itsflownium00bbc5b64fc1
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 3d3c3b46879..daee7d20cbb 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2154,14 +2154,20 @@ def _finalize_cron_session(session_db, agent, job_id: str, job_name: str, cron_s
logger.debug("Job '%s': failed to close SQLite session store: %s", job_id, e)
-def _run_doc_header(job: dict, title: str, job_id: str, prompt: str) -> str:
+def _run_doc_header(job: dict, title: str, job_id: str, prompt: str, *, frame_prompt: bool = False) -> str:
"""Header of the persisted run document (title, ids, schedule, prompt)."""
+ prompt_stamp = ""
+ if frame_prompt:
+ # Text-file reads normalize newlines. Count the same logged characters
+ # so quoted response markers inside the prompt cannot become boundaries.
+ prompt = prompt.replace("\r\n", "\n").replace("\r", "\n")
+ prompt_stamp = f"**Prompt Characters:** {len(prompt)}\n"
return (
f"# Cron Job: {title}\n\n"
f"**Job ID:** {job_id}\n"
f"**Run Time:** {_hermes_now().strftime('%Y-%m-%d %H:%M:%S')}\n"
f"**Schedule:** {job.get('schedule_display', 'N/A')}\n\n"
- f"## Prompt\n\n{prompt}\n\n"
+ f"{prompt_stamp}## Prompt\n\n{prompt}\n\n"
)
@@ -2542,7 +2548,7 @@ def run_job(
# Readers normalize line endings; count the same characters they read.
logged_response = logged_response.replace("\r\n", "\n").replace("\r", "\n")
output = (
- _run_doc_header(job, job_name, job_id, prompt)
+ _run_doc_header(job, job_name, job_id, prompt, frame_prompt=True)
+ f"**Response Characters:** {len(logged_response)}\n## Response\n\n"
+ f"{logged_response}\n"
)
diff --git a/cron/scheduler_prompt.py b/cron/scheduler_prompt.py
index 4400b76a5d2..3f98ae7f937 100644
--- a/cron/scheduler_prompt.py
+++ b/cron/scheduler_prompt.py
@@ -78,20 +78,28 @@ def _archive_answer(archive: str) -> str | None:
delivery lane itself suppresses) — so the caller falls through to an older
archive instead of injecting prompt noise the job already has.
"""
- if "## Response" not in archive:
- return archive
- # A frame is valid only when it consumes the document's exact tail (the
- # writer adds one newline). Use the first valid frame: quoted frames in the
- # answer must not replace the enclosing response. Never strip before this.
- framed = list(re.finditer(r"(?m)^\*\*Response Characters:\*\* (\d+)\n^## Response\n\n", archive))
- if framed:
- answer = ""
- for frame in framed:
- length = int(frame.group(1))
- tail = archive[frame.end():]
- if len(tail) == length + 1 and tail.endswith("\n"):
- answer = tail[:-1].strip()
- break
+ frame_pattern = re.compile(r"(?m)^\*\*Response Characters:\*\* (\d+)\n## Response\n\n")
+ # New writers stamp the prompt length outside user-owned text. Jump past
+ # that prompt instead of searching its quoted markers for a response frame.
+ prompt_frame = re.search(r"(?m)^\*\*Prompt Characters:\*\* (\d+)\n## Prompt\n\n", archive)
+ if (prompt_frame is not None
+ and archive.find("## Prompt\n\n") == prompt_frame.end() - len("## Prompt\n\n")):
+ response_start = prompt_frame.end() + int(prompt_frame.group(1)) + 2
+ frame = frame_pattern.match(archive, response_start)
+ if frame is None:
+ return None # The writer-owned boundary is missing or truncated.
+ else:
+ if "## Response" not in archive:
+ return archive
+ # Older framed archives lack a prompt length. Be conservative: validate
+ # only the first frame, never promote a nested frame after a bad boundary.
+ frame = frame_pattern.search(archive)
+ if frame is not None:
+ length = int(frame.group(1))
+ tail = archive[frame.end():]
+ if len(tail) != length + 1 or not tail.endswith("\n"):
+ return None
+ answer = tail[:-1].strip()
else:
answer = archive.rpartition("## Response")[2].strip()
if not answer or _sched._is_cron_silence_response(answer):
diff --git a/tests/cron/test_context_from_response_extraction.py b/tests/cron/test_context_from_response_extraction.py
index 85b886bfae6..f1eaac653db 100644
--- a/tests/cron/test_context_from_response_extraction.py
+++ b/tests/cron/test_context_from_response_extraction.py
@@ -118,7 +118,8 @@ def test_writer_reader_preserve_response_with_nested_frames(cron_env, monkeypatc
monkeypatch.setattr(run_agent, "AIAgent", Agent)
monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider",
lambda **kwargs: {"provider": "openai", "api_key": "fixture"})
- job = create_job(prompt="Original prompt noise", schedule="0 8 * * *", context_from="self")
+ job = create_job(prompt="Original prompt noise\r\n**Response Characters:** 4\n## Response\n\nbody",
+ schedule="0 8 * * *", context_from="self")
success, archive, final, error = cron.scheduler.run_job(job)
assert success, error
assert final == answer
@@ -144,3 +145,64 @@ def test_truncated_framed_archive_falls_back_to_older_answer(cron_env):
assert injected
assert "OLDER ANSWER" in prompt
assert "TRUNCATED" not in prompt
+
+
+def test_truncated_outer_frame_cannot_promote_a_quoted_inner_frame(cron_env, monkeypatch):
+ import os
+ from cron.jobs import create_job, save_job_output, OUTPUT_DIR
+ from cron.scheduler_prompt import _inject_context_from
+
+ quoted = "QUOTED INNER ANSWER"
+ suffix = "\nThis tail will be lost."
+ answer = ("Outer response introduction\n"
+ f"**Response Characters:** {len(quoted)}\n## Response\n\n{quoted}"
+ + suffix)
+
+ class Agent:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def run_conversation(self, *args, **kwargs):
+ return {"final_response": answer, "completed": True, "failed": False}
+
+ monkeypatch.setattr(run_agent, "AIAgent", Agent)
+ monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider",
+ lambda **kwargs: {"provider": "openai", "api_key": "fixture"})
+ job = create_job(prompt="Report", schedule="0 8 * * *", context_from="self")
+ success, archive, final, error = cron.scheduler.run_job(job)
+ assert success, error
+ assert final == answer
+ save_job_output(job["id"], archive)
+ saved = next((OUTPUT_DIR / job["id"]).glob("*.md"))
+ complete = saved.read_text(encoding="utf-8")
+ assert complete.endswith(suffix + "\n")
+ # Simulate a partial write: the quoted inner frame now reaches EOF exactly,
+ # but the enclosing writer-owned response is missing its declared suffix.
+ saved.write_text(complete[:-len(suffix + "\n")] + "\n", encoding="utf-8")
+ os.utime(saved, (2, 2))
+ prompt, injected = _inject_context_from(job, "Next task")
+ assert not injected
+ assert prompt == "Next task"
+
+ _write_archive(cron_env, job["id"], "older.md", "## Response\n\nOLDER COMPLETE ANSWER\n")
+ os.utime(OUTPUT_DIR / job["id"] / "older.md", (1, 1))
+ prompt, injected = _inject_context_from(job, "Next task")
+ assert injected
+ assert "OLDER COMPLETE ANSWER" in prompt
+ assert quoted not in prompt
+
+ # Archives produced before prompt-length framing get the same conservative
+ # treatment: an invalid first response frame never promotes a later one.
+ saved.write_text(f"**Response Characters:** {len(answer)}\n## Response\n\n"
+ + answer[:-len(suffix)] + "\n", encoding="utf-8")
+ os.utime(saved, (2, 2))
+ prompt, injected = _inject_context_from(job, "Next task")
+ assert injected and "OLDER COMPLETE ANSWER" in prompt
+ assert quoted not in prompt
+
+ # Losing the response boundary itself is also unusable, not a script archive.
+ saved.write_text(complete.split("**Response Characters:**", 1)[0], encoding="utf-8")
+ os.utime(saved, (2, 2))
+ prompt, injected = _inject_context_from(job, "Next task")
+ assert injected and "OLDER COMPLETE ANSWER" in prompt
+ assert "## Prompt" not in prompt