Skip to content

The agent that grows with you

fix: preserve Codex command exit status for replay

funky-xamarin2e6ff19ce259
diff --git a/agent/transports/codex_event_projector.py b/agent/transports/codex_event_projector.py
index 3c5912c0455..067f744b2c5 100644
--- a/agent/transports/codex_event_projector.py
+++ b/agent/transports/codex_event_projector.py
@@ -106,8 +106,10 @@ class CodexEventProjector:
args = {"command": item.get("command") or "", "cwd": item.get("cwd") or ""}
output = item.get("aggregatedOutput") or ""
exit_code = item.get("exitCode")
- if exit_code is not None and exit_code != 0:
- output = f"[exit {exit_code}]\n{output}"
+ if exit_code is not None:
+ # Preserve executor status so successful marker-like output is not an interrupt.
+ output = json.dumps({"exit_code": exit_code, "output": output}, ensure_ascii=False)
+ # Unknown exit status keeps the legacy text shape and conservative replay handling.
return "exec", "exec_command", args, output
@staticmethod
diff --git a/tests/agent/transports/test_codex_event_projector.py b/tests/agent/transports/test_codex_event_projector.py
index c9b23a13486..3b6d2ab39e0 100644
--- a/tests/agent/transports/test_codex_event_projector.py
+++ b/tests/agent/transports/test_codex_event_projector.py
@@ -101,6 +101,105 @@ class TestCommandExecutionProjection:
[email protected]("output", [
+ "Documentation example:\n[Command interrupted]\n",
+ "Documentation example:\n[execution interrupted by user]\n",
+ "ordinary command output\n",
+])
+def test_successful_command_survives_persisted_replay(tmp_path, output):
+ """A successful child's output is data, even when it ends with an executor marker."""
+ import subprocess
+ import sys
+ from types import SimpleNamespace
+
+ from agent.codex_runtime import _persist_projected_messages
+ from agent.replay_cleanup import canonicalize_replay_history
+ from agent.session_persistence import SessionPersistenceMixin
+ from agent.transports.chat_completions import ChatCompletionsTransport
+ from hermes_state import SessionDB
+
+ child = subprocess.run(
+ [sys.executable, "-I", "-c", f"print({output!r}, end='')"],
+ capture_output=True, text=True, timeout=10, cwd=tmp_path,
+ )
+ assert child.returncode == 0 and not child.stderr
+ assert child.stdout == output
+ item = {
+ "type": "commandExecution", "id": "child", "command": "print documentation",
+ "cwd": str(tmp_path), "status": "completed",
+ "exitCode": child.returncode, "aggregatedOutput": child.stdout,
+ }
+ projected = CodexEventProjector().project({
+ "method": "item/completed", "params": {"item": item},
+ }).messages
+ store = SessionPersistenceMixin()
+ db_path = tmp_path / "session.db"
+ store._session_db = SessionDB(db_path)
+ store.session_id = "command-replay"
+ store._session_db.create_session(store.session_id, source="cli")
+ store._session_db_created = True
+ store._last_flushed_db_idx = 0
+ messages = [{"role": "user", "content": "Print documentation."}]
+ turn = SimpleNamespace(
+ projected_messages=projected + [{"role": "assistant", "content": "Done."}],
+ submitted_user_text=None,
+ )
+ try:
+ _persist_projected_messages(store, turn, messages)
+ finally:
+ store._session_db.close()
+ reopened = SessionDB(db_path)
+ try:
+ loaded = reopened.get_messages_as_conversation(store.session_id)
+ raw, _display = reopened.get_resume_conversations(store.session_id)
+ finally:
+ reopened.close()
+ persisted_tool = next(m for m in loaded if m["role"] == "tool")
+ assert persisted_tool["content"] == projected[1]["content"]
+ replay = canonicalize_replay_history(raw)
+ wire = ChatCompletionsTransport().convert_messages(replay)
+ wire_tool = next(m for m in wire if m["role"] == "tool")
+ assert wire_tool["content"] == persisted_tool["content"]
+ assert json.loads(wire_tool["content"]) == {"exit_code": child.returncode, "output": child.stdout}
+
+
[email protected]("exit_fields", [{"exitCode": 130}, {}, {"exitCode": None}])
+def test_interrupted_or_unknown_command_remains_conservative(tmp_path, exit_fields):
+ """An actual interrupt, or missing executor status, must not be promoted to success."""
+ import subprocess
+ import sys
+
+ from agent.replay_cleanup import canonicalize_replay_history
+ from agent.transports.chat_completions import ChatCompletionsTransport
+
+ child = subprocess.run(
+ [sys.executable, "-I", "-c",
+ "import sys\ntry:\n raise KeyboardInterrupt\nexcept KeyboardInterrupt:\n"
+ " print('[Command interrupted]')\n sys.exit(130)"],
+ capture_output=True, text=True, timeout=10, cwd=tmp_path,
+ )
+ assert child.returncode == 130 and not child.stderr
+ item = {
+ "type": "commandExecution", "id": "interrupted", "command": "interrupted command",
+ "cwd": str(tmp_path), "status": "failed", "aggregatedOutput": child.stdout,
+ **exit_fields,
+ }
+ projected = CodexEventProjector().project({
+ "method": "item/completed", "params": {"item": item},
+ }).messages
+ if exit_fields.get("exitCode") is None:
+ assert projected[1]["content"] == child.stdout
+ else:
+ assert json.loads(projected[1]["content"]) == {
+ "exit_code": child.returncode, "output": child.stdout,
+ }
+ replay = canonicalize_replay_history(projected)
+ assert replay[1]["effect_disposition"] == "unknown"
+ wire = ChatCompletionsTransport().convert_messages(replay)
+ assert "UNKNOWN" in wire[1]["content"]
+ assert wire[1]["tool_call_id"] == projected[1]["tool_call_id"]
+
+
class TestAgentMessageProjection:
"""assistant text → final_text + assistant message."""