"""Persist and deliver the executor's answer before independent final review.""" import hashlib import json from pathlib import Path from uuid import uuid4 def save_execution_report(ctx, report: str) -> dict: from artemis.exploration.store import explorations directory = Path(ctx.data_engine.base_dir) notes = directory / "notes" notes.mkdir(parents=True, exist_ok=True) # The regular report readers use output.md and result.json. Write complete # replacements so a concurrent reader cannot observe half a report. for path, content in ( (notes / "output.md", report), (directory / "result.json", json.dumps({"result": report}, ensure_ascii=False)), ): temporary = path.with_name(f".{path.name}.{uuid4().hex}.tmp") try: temporary.write_text(content, encoding="utf-8") temporary.replace(path) finally: temporary.unlink(missing_ok=True) # Keep the entire answer despite the conversation's per-message size limit. # A repeated settlement of the same answer must not duplicate its delivery. digest = hashlib.sha256(report.encode("utf-8")).hexdigest() sequences = [] for offset in range(0, len(report), 10000): message = explorations.add_message( ctx.exploration_id, report[offset : offset + 10000], f"report:{ctx.exploration_run_id}:{digest}:{offset}", role="assistant", source="exploration", metadata={"run_id": ctx.exploration_run_id, "kind": "execution_report"}, ) sequences.append(message["sequence"]) return { "report_path": "notes/output.md", "result_path": "result.json", "content_sha256": digest, "exploration_message_sequences": sequences, }