Skip to content

The agent that grows with you

fix(cron): trim script-mode context_from archives and share frame labels

kshitijk4poor3114c527014b
diff --git a/cron/scheduler.py b/cron/scheduler.py
index daee7d20cbb..bb9439a433c 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2154,14 +2154,13 @@ 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, *, frame_prompt: bool = False) -> str:
+def _normalize_newlines(text: str) -> str:
+ """CRLF/CR -> LF, matching what text-mode reads of the archive return."""
+ return text.replace("\r\n", "\n").replace("\r", "\n")
+
+
+def _run_doc_header(job: dict, title: str, job_id: str, prompt: str, *, prompt_stamp: str = "") -> 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"
@@ -2545,11 +2544,14 @@ def run_job(
final_response = f"{setup.fallback_notice}\n\n{final_response}"
# Keep final_response clean for delivery logic (empty = no delivery).
logged_response = final_response if final_response else "(No response generated)"
- # Readers normalize line endings; count the same characters they read.
- logged_response = logged_response.replace("\r\n", "\n").replace("\r", "\n")
+ # Text-file reads normalize newlines; count the same characters the
+ # context_from reader sees so quoted markers can never become boundaries.
+ framed_prompt = _normalize_newlines(prompt)
+ logged_response = _normalize_newlines(logged_response)
output = (
- _run_doc_header(job, job_name, job_id, prompt, frame_prompt=True)
- + f"**Response Characters:** {len(logged_response)}\n## Response\n\n"
+ _run_doc_header(job, job_name, job_id, framed_prompt,
+ prompt_stamp=f"{_PROMPT_FRAME}{len(framed_prompt)}\n")
+ + f"{_RESPONSE_FRAME}{len(logged_response)}\n## Response\n\n"
+ f"{logged_response}\n"
)
logger.info("Job '%s' completed successfully", job_name)
@@ -4293,7 +4295,8 @@ from cron.scheduler_script import ( # noqa: E402
_get_session_db_timeout, _run_job_script_with_claim_heartbeat, _start_heartbeat_thread,
)
from cron.scheduler_prompt import ( # noqa: E402
- _block_and_pause_job, _build_job_prompt, _guard_job_credential_exfil, _parse_wake_gate,
+ _PROMPT_FRAME, _RESPONSE_FRAME, _block_and_pause_job, _build_job_prompt,
+ _guard_job_credential_exfil, _parse_wake_gate,
)
from cron.scheduler_preflight import ( # noqa: E402
BLOCKED_CONFIG_MARKER, BLOCKED_CONFIG_SILENT_MARKER, _cron_preflight_enabled,
diff --git a/cron/scheduler_prompt.py b/cron/scheduler_prompt.py
index dd5ef185a7c..98f2497b456 100644
--- a/cron/scheduler_prompt.py
+++ b/cron/scheduler_prompt.py
@@ -63,16 +63,33 @@ _UPSTREAM_CONTEXT_INTRO = (
"your analysis."
)
+# Run-document length frames. The writer (``cron.scheduler.run_job``) stamps
+# these labels; the reader below parses them. Defined here (not in scheduler.py)
+# because this module binds ``_sched`` only at import tail, so module-level
+# patterns cannot be built from scheduler attributes without an import cycle.
+_PROMPT_FRAME = "**Prompt Characters:** "
+_RESPONSE_FRAME = "**Response Characters:** "
+_PROMPT_HEADING = "## Prompt\n\n"
+_RESPONSE_HEADING = "## Response\n\n"
+_PROMPT_SEPARATOR = "\n\n" # writer's blank line after the prompt body
+_RESPONSE_TERMINATOR = "\n" # writer's trailing newline after the response body
+_PROMPT_FRAME_RE = re.compile(
+ rf"(?m)^{re.escape(_PROMPT_FRAME)}(\d+)\n{re.escape(_PROMPT_HEADING)}")
+_RESPONSE_FRAME_RE = re.compile(
+ rf"(?m)^{re.escape(_RESPONSE_FRAME)}(\d+)\n{re.escape(_RESPONSE_HEADING)}")
+
def _archive_answer(archive: str) -> str | None:
- """The reusable answer of a stored run, using its frame when available.
-
- Framed runs validate the response length before whitespace normalization.
- Archives without the heading (script-mode runs) stay whole-document. For legacy
- archives without a frame, the LAST
- occurrence is the writer's boundary — the assembled prompt half can itself carry
- the literal heading (a skill documenting its response format, an injected previous
- answer quoting it), so an early split would re-inject the prompt noise this
+ """The reusable answer of a stored run, using its length frame when available.
+
+ Framed runs (``_PROMPT_FRAME``/``_RESPONSE_FRAME`` stamps) validate the
+ response length before whitespace normalization, so quoted frames inside the
+ prompt or answer can never become boundaries and a truncated write is
+ rejected. Archives without the heading (script-mode runs) stay whole-document.
+ For legacy unframed archives the LAST ``## Response`` occurrence is the
+ writer's boundary — the assembled prompt half can itself carry the literal
+ heading (a skill documenting its response format, an injected previous answer
+ quoting it), so an early split would re-inject the prompt noise this
extraction exists to drop.
``None`` marks "no usable answer" — a blank or silent response (any form the
delivery lane itself suppresses) — so the caller falls through to an older
@@ -80,19 +97,19 @@ def _archive_answer(archive: str) -> str | None:
"""
# 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)
+ prompt_frame = _PROMPT_FRAME_RE.search(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 = re.compile(r"(?m)^\*\*Response Characters:\*\* (\d+)\n## Response\n\n").match(
- archive, response_start)
+ and archive.find(_PROMPT_HEADING) == prompt_frame.end() - len(_PROMPT_HEADING)):
+ response_start = prompt_frame.end() + int(prompt_frame.group(1)) + len(_PROMPT_SEPARATOR)
+ frame = _RESPONSE_FRAME_RE.match(archive, response_start)
tail = archive[frame.end():] if frame is not None else ""
# A missing or truncated writer-owned boundary is unusable.
- if frame is None or len(tail) != int(frame.group(1)) + 1 or not tail.endswith("\n"):
+ if (frame is None or len(tail) != int(frame.group(1)) + len(_RESPONSE_TERMINATOR)
+ or not tail.endswith(_RESPONSE_TERMINATOR)):
return None
- answer = tail[:-1].strip()
+ answer = tail[:-len(_RESPONSE_TERMINATOR)].strip()
elif "## Response" not in archive:
- return archive
+ return archive.strip()
else:
answer = archive.rpartition("## Response")[2].strip()
if not answer or _sched._is_cron_silence_response(answer):
@@ -148,7 +165,7 @@ def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]:
"Script gate returned `wakeAgent=false`"))
for line in header.splitlines()
)
- if not candidate.strip() or silent_audit:
+ if not candidate or candidate.isspace() or silent_audit:
continue
answer = _archive_answer(candidate)
if answer is None:
diff --git a/tests/cron/test_context_from_response_extraction.py b/tests/cron/test_context_from_response_extraction.py
index 15dada32d81..a86bfb4e983 100644
--- a/tests/cron/test_context_from_response_extraction.py
+++ b/tests/cron/test_context_from_response_extraction.py
@@ -42,6 +42,21 @@ def _write_archive(cron_env, job_id: str, filename: str, body: str) -> None:
(out_dir / filename).write_text(body, encoding="utf-8")
+def _run_stub_job(monkeypatch, job, answer):
+ """Run ``job`` through the real writer with a stub agent returning ``answer``."""
+ 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"})
+ return cron.scheduler.run_job(job)
+
+
class TestResponseSurvivesLongPrompt:
"""The answer, not the prompt, is the part continuity needs."""
@@ -93,13 +108,14 @@ class TestScriptModeArchives:
from cron.scheduler_prompt import _inject_context_from
job = create_job(prompt="Report", schedule="0 8 * * *", context_from="self")
- _write_archive(cron_env, job["id"], "2026-09-19_08-00-00.md", "plain script payload\nline two")
+ _write_archive(cron_env, job["id"], "2026-09-19_08-00-00.md",
+ "\n\nplain script payload\nline two\n\n")
prompt, injected = _inject_context_from(job, "Report")
assert injected is True
- assert "plain script payload" in prompt
- assert "line two" in prompt
+ # Whole document, but trimmed like every other archive answer.
+ assert "```\nplain script payload\nline two\n```" in prompt
def test_writer_reader_preserve_response_with_nested_frames(cron_env, monkeypatch):
@@ -108,19 +124,9 @@ def test_writer_reader_preserve_response_with_nested_frames(cron_env, monkeypatc
answer = "摘要 before heading\r\n\r\n## Response\nsubsection\n**Response Characters:** 4\n## Response\n\nbody\n\n "
- 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="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)
+ success, archive, final, error = _run_stub_job(monkeypatch, job, answer)
assert success, error
assert final == answer
save_job_output(job["id"], archive)
@@ -141,18 +147,8 @@ def test_truncated_outer_frame_cannot_promote_a_quoted_inner_frame(cron_env, mon
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)
+ success, archive, final, error = _run_stub_job(monkeypatch, job, answer)
assert success, error
assert final == answer
save_job_output(job["id"], archive)