Skip to content

The agent that grows with you

fix(cron): validate complete archive frames before normalization

itsflownium39e046e5e402
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 17073f86d5d..3d3c3b46879 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2539,7 +2539,13 @@ 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)"
- output = (_run_doc_header(job, job_name, job_id, prompt) + f"**Response Characters:** {len(logged_response)}\n## Response\n\n" + f"{logged_response}\n")
+ # 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)
+ + f"**Response Characters:** {len(logged_response)}\n## Response\n\n"
+ + f"{logged_response}\n"
+ )
logger.info("Job '%s' completed successfully", job_name)
_audit.write(dict(result, response_silent=_is_cron_silence_response(final_response or "")), None)
return True, output, final_response, None
diff --git a/cron/scheduler_prompt.py b/cron/scheduler_prompt.py
index 8847aa08c5e..4400b76a5d2 100644
--- a/cron/scheduler_prompt.py
+++ b/cron/scheduler_prompt.py
@@ -65,9 +65,11 @@ _UPSTREAM_CONTEXT_INTRO = (
def _archive_answer(archive: str) -> str | None:
- """The reusable answer of a stored run: the text after the last ``## Response``.
+ """The reusable answer of a stored run, using its frame when available.
- Archives without the heading (script-mode runs) stay whole-document. The LAST
+ 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
@@ -78,15 +80,18 @@ def _archive_answer(archive: str) -> str | None:
"""
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:
- boundary = framed[-1].end()
- length = int(framed[-1].group(1))
- answer = archive[boundary:boundary + length]
- if len(answer) == length:
- answer = answer.strip()
- else:
- answer = ""
+ 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
else:
answer = archive.rpartition("## Response")[2].strip()
if not answer or _sched._is_cron_silence_response(answer):
@@ -133,7 +138,7 @@ def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]:
)
latest_output = ""
for output_file in output_files:
- candidate = output_file.read_text(encoding="utf-8-sig").strip()
+ candidate = output_file.read_text(encoding="utf-8-sig")
# Only the run header describes suppression; script/agent payloads can
# quote these markers. Keep error documents useful for recovery context.
header = candidate.split("\n---\n", 1)[0].split("\n## Prompt", 1)[0]
@@ -142,7 +147,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 or silent_audit:
+ if not candidate.strip() 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 e506d8911e7..85b886bfae6 100644
--- a/tests/cron/test_context_from_response_extraction.py
+++ b/tests/cron/test_context_from_response_extraction.py
@@ -10,6 +10,8 @@ import sys
from pathlib import Path
import pytest
+import cron.scheduler
+import run_agent
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
@@ -100,12 +102,45 @@ class TestScriptModeArchives:
assert "line two" in prompt
-
-def test_framed_answer_preserves_embedded_response_heading():
- from cron.scheduler_prompt import _archive_answer
-
- answer = 'Summary before embedded heading\n\n## Response\nThis is an answer subsection.\nConclusion.'
- archive = ('# Cron Job: fixture\n\n## Prompt\nSynthetic prompt.\n\n'
- + f'**Response Characters:** {len(answer)}\n## Response\n\n{answer}\n')
-
- assert _archive_answer(archive) == answer
+def test_writer_reader_preserve_response_with_nested_frames(cron_env, monkeypatch):
+ from cron.jobs import create_job, save_job_output
+ from cron.scheduler_prompt import _inject_context_from
+
+ 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", 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)
+ prompt, injected = _inject_context_from(job, "Next task")
+ assert injected
+ assert answer.replace("\r\n", "\n").strip() in prompt
+ assert "Original prompt noise" not in prompt
+
+
+def test_truncated_framed_archive_falls_back_to_older_answer(cron_env):
+ import os
+ from cron.jobs import create_job, OUTPUT_DIR
+ 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"], "older.md", "## Response\n\nOLDER ANSWER\n")
+ _write_archive(cron_env, job["id"], "newer.md",
+ "**Response Characters:** 80\n## Response\n\nTRUNCATED\n")
+ os.utime(OUTPUT_DIR / job["id"] / "older.md", (1, 1))
+ os.utime(OUTPUT_DIR / job["id"] / "newer.md", (2, 2))
+ prompt, injected = _inject_context_from(job, "Report")
+ assert injected
+ assert "OLDER ANSWER" in prompt
+ assert "TRUNCATED" not in prompt