ReMe/tests/unit/test_codex_capture_recovery.py
star-nebula 838fa7d6d1
fix(codex): tolerate delayed transcript capture (#681)
* fix(codex): tolerate delayed transcript capture

* fix(codex): avoid capturing intermediate transcript replies

* test(codex): cover late final transcript materialization

Refactor tests to improve clarity on assistant message handling and session ID preservation.

* fix(codex): require final phase for mismatched capture fallback

Do not persist phase-less progress when the transcript settle window expires. Preserve exact Stop-text matching and cover incomplete final JSON at EOF through capture().
2026-11-06 11:09:47 +08:00

196 lines
8.7 KiB
Python

"""Recovery behavior for Codex Stop hooks when transcript writes settle late."""
# pylint: disable=redefined-outer-name
import importlib.util
import json
from pathlib import Path
import pytest
PLUGIN = Path(__file__).resolve().parents[2] / "integrations/codex/plugins/reme"
@pytest.fixture
def codex_hook(tmp_path, monkeypatch):
"""Load the Codex hook against an isolated host configuration."""
spec = importlib.util.spec_from_file_location("codex_capture_recovery", PLUGIN / "hooks/auto_memory.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
monkeypatch.setenv(module.HOME_ENV, str(tmp_path / "host"))
monkeypatch.setattr(module, "CAPTURE_SETTLE_SECONDS", 0)
return module
def completed(turn_id, item_type, text):
"""Build one completed Codex transcript item."""
return {
"type": "event_msg",
"timestamp": "2026-10-26T01:00:00Z",
"payload": {
"type": "item_completed",
"turn_id": turn_id,
"item": {
"type": item_type,
"content": [{"type": "text" if item_type == "UserMessage" else "Text", "text": text}],
},
},
}
def test_accepts_unterminated_final_transcript_line(codex_hook, tmp_path):
"""Accept a final row that is complete JSON but has no trailing newline."""
path = tmp_path / "rollout.jsonl"
rows = [completed("turn-one", "UserMessage", "question"), completed("turn-one", "AgentMessage", "answer")]
path.write_text("\n".join(json.dumps(row) for row in rows), encoding="utf-8")
payload = {"transcript_path": str(path), "last_assistant_message": "answer", "turn_id": "turn-one"}
pair = codex_hook.completed_turn(payload, "session")
assert [message["content"][0]["text"] for message in pair] == ["question", "answer"]
def test_uses_last_same_turn_final_answer_when_stop_text_differs(codex_hook, tmp_path):
"""Fall back to an explicitly final item after the retry window when Stop text differs."""
path = tmp_path / "rollout.jsonl"
rows = [
completed("turn-one", "UserMessage", "question"),
completed("turn-one", "AgentMessage", "progress"),
completed("turn-one", "AgentMessage", "final answer"),
]
rows[-1]["payload"]["item"]["phase"] = "final_answer"
rows.append(completed("turn-one", "AgentMessage", "later phase-less progress"))
path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
payload = {
"transcript_path": str(path),
"last_assistant_message": "rendered final answer",
"turn_id": "turn-one",
}
assert codex_hook.completed_turn(payload, "session") == []
pair = codex_hook.completed_turn_with_retry(payload, "session", timeout=0)
assert [message["content"][0]["text"] for message in pair] == ["question", "final answer"]
payload["last_assistant_message"] = None
assert codex_hook.completed_turn_with_retry(payload, "session", timeout=0) == []
@pytest.mark.parametrize("final_turn", ["turn-one", "other-turn"])
def test_capture_rejects_mismatched_phase_less_reply(codex_hook, tmp_path, final_turn):
"""A complete phase-less row or another turn's final phase cannot authorize a fallback."""
path = tmp_path / "rollout.jsonl"
rows = [
completed("turn-one", "UserMessage", "question"),
completed("turn-one", "AgentMessage", "progress"),
completed(final_turn, "AgentMessage", "final answer"),
]
if final_turn == "other-turn":
rows[-1]["payload"]["item"]["phase"] = "final_answer"
path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
payload = {
"session_id": "session",
"transcript_path": str(path),
"last_assistant_message": "rendered final answer",
"turn_id": "turn-one",
}
config = codex_hook.load_config()
assert codex_hook.capture(config, payload) is None
assert not list(codex_hook.queue_root(config).rglob("*.json"))
@pytest.mark.parametrize("progress_phase", [None, "commentary"])
def test_capture_skips_unfinished_final_record_after_retry_expires(codex_hook, tmp_path, monkeypatch, progress_phase):
"""An expired retry window must not persist progress while the final JSON is incomplete at EOF."""
path = tmp_path / "rollout.jsonl"
question = completed("turn-one", "UserMessage", "question")
progress = completed("turn-one", "AgentMessage", "progress")
if progress_phase is not None:
progress["payload"]["item"]["phase"] = progress_phase
final = completed("turn-one", "AgentMessage", "final answer")
final["payload"]["item"]["phase"] = "final_answer"
prefix = "".join(json.dumps(row) + "\n" for row in (question, progress))
final_json = json.dumps(final)
path.write_text(prefix + final_json[:-2], encoding="utf-8")
payload = {
"session_id": "session",
"transcript_path": str(path),
"last_assistant_message": "final answer",
"turn_id": "turn-one",
}
monkeypatch.setattr(codex_hook, "CAPTURE_SETTLE_SECONDS", 3.0)
clock = iter([0.0, 3.0, 3.0])
monkeypatch.setattr(codex_hook.time, "monotonic", lambda: next(clock))
config = codex_hook.load_config()
assert codex_hook.capture(config, payload) is None
assert not list(codex_hook.queue_root(config).rglob("*.json"))
assert not list(codex_hook.queue_root(config).rglob("*.done"))
path.write_text(prefix + final_json, encoding="utf-8")
root = codex_hook.capture(config, payload)
queued = json.loads(next(root.glob("*.json")).read_text(encoding="utf-8"))
assert [message["content"][0]["text"] for message in queued["messages"]] == ["question", "final answer"]
def test_does_not_cross_turns_when_turn_id_is_unknown(codex_hook, tmp_path):
"""Never capture messages from another turn."""
path = tmp_path / "rollout.jsonl"
rows = [completed("turn-one", "UserMessage", "question"), completed("turn-one", "AgentMessage", "answer")]
path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
payload = {"transcript_path": str(path), "last_assistant_message": "answer", "turn_id": "unknown"}
assert codex_hook.completed_turn(payload, "session") == []
def test_capture_retries_turn_materialization(codex_hook, monkeypatch):
"""Retry until the current turn is fully materialized."""
pair = [
{
"id": "codex-1",
"role": "user",
"content": [{"type": "text", "text": "question"}],
"created_at": "2026-10-26T01:00:00+00:00",
},
{
"id": "codex-2",
"role": "assistant",
"content": [{"type": "text", "text": "answer"}],
"created_at": "2026-10-26T01:00:01+00:00",
},
]
responses = iter([[], pair])
monkeypatch.setattr(codex_hook, "completed_turn", lambda *_args, **_kwargs: next(responses))
assert codex_hook.completed_turn_with_retry({}, "session", timeout=0.2) == pair
def test_capture_waits_for_final_item_instead_of_accepting_phase_less_progress(codex_hook, tmp_path, monkeypatch):
"""Do not accept a phase-less intermediate item while the final reply may still be pending."""
path = tmp_path / "rollout.jsonl"
question = completed("turn-one", "UserMessage", "question")
progress = completed("turn-one", "AgentMessage", "progress")
final = completed("turn-one", "AgentMessage", "final answer")
path.write_text("".join(json.dumps(row) + "\n" for row in (question, progress)), encoding="utf-8")
payload = {
"transcript_path": str(path),
"last_assistant_message": "final answer",
"turn_id": "turn-one",
}
def append_final(_seconds):
path.write_text("".join(json.dumps(row) + "\n" for row in (question, progress, final)), encoding="utf-8")
monkeypatch.setattr(codex_hook.time, "sleep", append_final)
pair = codex_hook.completed_turn_with_retry(payload, "session", timeout=0.2)
assert [message["content"][0]["text"] for message in pair] == ["question", "final answer"]
def test_capture_preserves_queue_session_id(codex_hook, tmp_path):
"""Keep the queue hash as the delivered session identity."""
path = tmp_path / "rollout.jsonl"
rows = [completed("turn-one", "UserMessage", "question"), completed("turn-one", "AgentMessage", "answer")]
path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
payload = {
"hook_event_name": "Stop",
"session_id": "01a1766c-4b23-7df3-914c-32d0020e7285",
"transcript_path": str(path),
"last_assistant_message": "answer",
"turn_id": "turn-one",
}
root = codex_hook.capture(codex_hook.load_config(), payload)
queued = json.loads(next(root.glob("*.json")).read_text(encoding="utf-8"))
assert queued["session_id"] == root.name