Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(codex): restore model-visible Avibe instructions (#1875)
Call Whiteb4215a03fe57
diff --git a/docs/plans/codex-prompt-delivery.md b/docs/plans/codex-prompt-delivery.mdnew file mode 100644index 000000000..ac51b0193--- /dev/null+++ b/docs/plans/codex-prompt-delivery.md@@ -0,0 +1,76 @@+# Codex Prompt Delivery++## Contract++Avibe-owned instructions must enter model-visible developer messages independently+of model-owned collaboration text. Only the latest complete Avibe runtime snapshot+is active; omitted rules and catalog entries revoke their earlier declarations.+Unchanged instructions must not accumulate on+each turn or process restart. Prompt delivery must not change model routing or+reasoning effort, and ambiguous native mutations must retain at-most-once recovery.++## Cause and Delivery++Codex 0.153.2 prefers a model catalog's collaboration instructions over+`collaborationMode.settings.developer_instructions`. A successful+`collaborationMode/list` probe therefore proves API support, not prompt delivery.+Both quick-reply and session-title rules can be present in the turn parameters+while absent from the model request.++Avibe now uses `thread/inject_items` with explicit developer messages for its+instructions. Each message declares complete-snapshot replacement semantics,+including superseding legacy untagged snapshots. History is retained, but removed+rules and capability, Agent, and Skill declarations must not remain active. User+and project instructions are outside this replacement boundary.+The existing durable `fallback` marker name and write-ahead states+remain unchanged. Legacy `collaboration` threads migrate through the existing+pending-clear path, even when their model and prompt fingerprint are unchanged.+Fingerprints cover the rendered snapshot, including its replacement declaration.+Legacy raw-prompt hashes therefore migrate once through resume or fork, while+unchanged current snapshots remain deduplicated across restarts.+Model and reasoning overrides remain top-level turn parameters.++Protocol validation rejections (`-32600`, `-32601`, `-32602`) restore the durable+pre-injection marker and fail the turn before model dispatch, allowing a later+attempt after API compatibility is repaired. Transport failures and internal+server errors remain ambiguous and retain the write-ahead marker. If restoring+the marker itself fails, the turn fails and that unresolved marker is retained.++`features.retain_client_developer_messages=true` preserves these messages through+Codex remote compaction v2. This replaces the collaboration-based delivery+described in the earlier managed-Skills implementation plan; Skill discovery and+prompt composition are unchanged.++## Evidence and Limits++- Unit tests cover injection deduplication, changed instructions, model routing,+ legacy migration, persistence failures, ambiguous RPCs, and restart recovery.+- `tests/test_codex_prompt_delivery_contract.py` drives the real Codex executable+ through Avibe's agent and transport into a loopback Responses server. It uses+ the actual quick-reply and session-title templates and a model catalog that+ overrides collaboration text. It covers new and legacy threads, prompt changes,+ process restart, and remote compaction v2.+- Run the native contract with `CODEX_PROMPT_CONTRACT_BINARY` set to the selected+ executable and pytest targeting that file. It is opt-in, requires no model+ credentials, and was verified with Codex 0.153.2. Ordinary CI runs the unit+ contract without installing a native backend.+- The retention flag only protects native remote compaction v2. Older Codex+ compaction implementations and third-party providers' local summarization may+ still summarize injected messages away. They are not a retention guarantee.+- This verifies transport delivery, not whether a real model follows every rule.+ Live Workbench button rendering and automatic title changes require the local+ Incus integration pass; no running developer service is restarted by this fix.++No existing scenario catalog owns prompt delivery. This change adds a native+contract rather than assigning an unrelated capability's scenario ID.++## Review Scope Decision++Head `22a948af70` had one finding: historical prompt snapshots lacked supersession.+Head `d96c18a115` had two findings: legacy-marker migration in that same class,+and definitive RPC rejections being treated as ambiguous mutations. The repeated+class triggered the orchestrator circuit breaker before the next edit. Inspection+covered marker production, resume, fork, cached recovery, and the native consumer+test. The smallest complete decision is to fingerprint actual snapshot bytes and+restore prior state only for protocol-level rejection. No new thread lifecycle,+marker schema, storage migration, backend routing, or broad retry policy is needed.diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 4bc9b989e..9b0a4087d 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -52,7 +52,7 @@ from modules.agents.base import AgentRequest, BaseAgentfrom modules.agents.subagent_router import SubagentDefinition, load_codex_subagentfrom modules.agents.codex.event_handler import CodexEventHandlerfrom modules.agents.codex.session import CodexSessionManager-from modules.agents.codex.transport import CodexTransport+from modules.agents.codex.transport import CodexRPCError, CodexTransportfrom modules.agents.codex.turn_state import CodexTurnRegistryfrom vibe.codex_config import LEGACY_MANAGED_PROVIDER_IDS, MANAGED_PROVIDER_IDfrom vibe.i18n import t as i18n_t@@ -2791,6 +2791,21 @@ class CodexAgent(BaseAgent):)return names_field and unsupported+ @staticmethod+ def _render_developer_prompt_snapshot(developer_instructions: str) -> str:+ return (+ "<avibe_runtime_instructions>\n"+ "This is the complete current Avibe runtime instruction snapshot. "+ "Only the most recent snapshot is active. It replaces all earlier "+ "Avibe-generated runtime prompt snapshots, including untagged versions. "+ "Rules and capability, Agent, or Skill catalog entries omitted from this "+ "snapshot no longer apply: do not carry them forward from earlier snapshots. "+ "This replacement does not revoke user or project instructions or erase "+ "conversation history.\n\n"+ f"{developer_instructions}\n"+ "</avibe_runtime_instructions>"+ )+async def _inject_thread_developer_instructions(self,transport: CodexTransport,@@ -2801,8 +2816,12 @@ class CodexAgent(BaseAgent):agent_session_id: Optional[str] = None,strategy: str = "fallback",) -> None:- """Fallback for Codex builds without Turn collaboration settings."""+ """Append model-visible instructions, with durable at-most-once recovery."""+ previous_marker = self._read_persisted_prompt_strategy_marker(+ thread_id,+ agent_session_id=agent_session_id,+ )pending_strategy = ("fallback_pending_clear_injection"if strategy == "fallback_pending_clear"@@ -2832,24 +2851,46 @@ class CodexAgent(BaseAgent):thread_id,pending_strategy,)- await transport.send_request(- "thread/inject_items",- {- "threadId": thread_id,- "items": [- {- "type": "message",- "role": "developer",- "content": [- {- "type": "input_text",- "text": developer_instructions,- }- ],- }- ],- },- )+ try:+ await transport.send_request(+ "thread/inject_items",+ {+ "threadId": thread_id,+ "items": [+ {+ "type": "message",+ "role": "developer",+ "content": [+ {+ "type": "input_text",+ "text": self._render_developer_prompt_snapshot(developer_instructions),+ }+ ],+ }+ ],+ },+ )+ except CodexRPCError as exc:+ if not exc.request_rejected:+ raise+ # The server rejected the request before dispatch, so restore the+ # pre-injection state instead of recording an unknowable mutation.+ previous_marker = previous_marker or {}+ if not self._persist_prompt_strategy(+ request,+ thread_id,+ None,+ strategy=previous_marker.get("strategy"),+ prompt_sha256=previous_marker.get("sha256"),+ agent_session_id=agent_session_id,+ ):+ raise CodexPromptRefreshUnavailableError(+ "Could not restore the prompt strategy after rejected injection"+ ) from exc+ self._thread_prompt_strategies.pop(request.base_session_id, None)+ raise CodexPromptRefreshUnavailableError(+ "Codex rejected developer prompt injection; check app-server API compatibility"+ ) from excif not self._persist_prompt_strategy(request,thread_id,@@ -2892,9 +2933,10 @@ class CodexAgent(BaseAgent):strategy,)- @staticmethod- def _prompt_fingerprint(developer_instructions: str) -> str:- return hashlib.sha256(developer_instructions.encode("utf-8")).hexdigest()+ @classmethod+ def _prompt_fingerprint(cls, developer_instructions: str) -> str:+ snapshot = cls._render_developer_prompt_snapshot(developer_instructions)+ return hashlib.sha256(snapshot.encode("utf-8")).hexdigest()def _read_persisted_prompt_strategy_marker(self,@@ -3026,11 +3068,12 @@ class CodexAgent(BaseAgent):thread_id: str,developer_instructions: Optional[str],*,- strategy: str,+ strategy: Optional[str],agent_session_id: Optional[str],prompt_sha256: Optional[str] = None,) -> bool:if strategy not in {+ None,"collaboration","fallback","fallback_pending_clear",@@ -3044,10 +3087,10 @@ class CodexAgent(BaseAgent):or any(character not in "0123456789abcdef" for character in prompt_sha256)):raise ValueError("Codex prompt fingerprint must be lowercase SHA-256")- if strategy == "unavailable" and (+ if strategy in {None, "unavailable"} and (developer_instructions or prompt_sha256 is not None):- raise ValueError("Unavailable prompt strategy cannot carry prompt identity")+ raise ValueError("Absent or unavailable prompt strategy cannot carry prompt identity")if strategy == "fallback" and not developer_instructions and not prompt_sha256:raise ValueError("Fallback prompt strategy requires developer instructions")if not agent_session_id:@@ -3078,7 +3121,7 @@ class CodexAgent(BaseAgent):backend=self.name,native_session_id=thread_id,key=CODEX_PROMPT_STRATEGY_METADATA_KEY,- value=marker,+ value=marker if strategy is not None else None,))@@ -3218,19 +3261,10 @@ class CodexAgent(BaseAgent):)if persisted_prompt_marker is not None:prompt_strategy = persisted_prompt_marker["strategy"]- elif effective_model and getattr(transport, "supports_turn_collaboration_mode", True):- prompt_strategy = (- "collaboration"- if self._persist_prompt_strategy(- request,- thread_id,- developer_instructions,- strategy="collaboration",- agent_session_id=agent_session_id,- )- else "fallback"- )else:+ # Keep the durable name for existing threads. Collaboration+ # settings are not a prompt channel: model catalog messages+ # can override their developer_instructions entirely.prompt_strategy = "fallback"self._remember_thread_prompt_strategy(request.base_session_id,@@ -3264,16 +3298,10 @@ class CodexAgent(BaseAgent):collaboration_mode_is_known = bool(getattr(transport, "supports_turn_collaboration_mode", True))- collaboration_strategy_has_no_model = bool(- developer_instructions- and prompt_strategy == "collaboration"- and not effective_model- )clear_collaboration_mode = collaboration_mode_is_known and bool(prompt_strategy- in {"fallback_pending_clear", "fallback_pending_clear_injection"}+ in {"collaboration", "fallback_pending_clear", "fallback_pending_clear_injection"}or (model_explicit and effective_model is None)- or collaboration_strategy_has_no_model)if clear_collaboration_mode:was_collaboration = prompt_strategy == "collaboration"@@ -3292,26 +3320,7 @@ class CodexAgent(BaseAgent):)if was_collaboration and not fallback_prompt_is_current:prompt_changed = True- use_collaboration_mode = bool(- developer_instructions- and effective_model- and prompt_strategy == "collaboration"- and collaboration_mode_is_known- )- if use_collaboration_mode:- # Codex keeps the collaboration world state across Turns and emits- # a new developer fragment only when these exact bytes change. The- # explicit model and effort preserve the route because the mode- # takes precedence over the sibling turn fields.- turn_params["collaborationMode"] = {- "mode": "default",- "settings": {- "model": effective_model,- "reasoning_effort": effective_effort,- "developer_instructions": developer_instructions,- },- }- elif (+ if (developer_instructionsand prompt_changedand prompt_strategy@@ -3357,23 +3366,10 @@ class CodexAgent(BaseAgent):):raiselogger.warning(- "Codex turn collaboration mode is unavailable; falling back to developer item injection: %s",+ "Codex turn collaboration mode is unavailable; retrying without the model reset field: %s",exc,)transport.supports_turn_collaboration_mode = False- self._remember_thread_prompt_strategy(- request.base_session_id,- thread_id,- "fallback",- )- if developer_instructions and not fallback_prompt_is_current:- await self._inject_thread_developer_instructions(- transport,- request,- thread_id,- developer_instructions,- agent_session_id=agent_session_id,- )fallback_turn_params = dict(turn_params)fallback_turn_params.pop("collaborationMode", None)resp = await transport.send_request("turn/start", fallback_turn_params)@@ -3420,12 +3416,6 @@ class CodexAgent(BaseAgent):"Codex collaboration clear succeeded but the unknown injection marker remains pending")- if use_collaboration_mode and developer_instructions:- self._remember_thread_developer_instructions(- request.base_session_id,- thread_id,- developer_instructions,- )if effective_model:self._thread_model_settings = getattr(self, "_thread_model_settings", {})self._thread_model_settings[request.base_session_id] = (diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.pyindex 9a92228dc..5019f92e4 100644--- a/modules/agents/codex/transport.py+++ b/modules/agents/codex/transport.py@@ -46,6 +46,8 @@ AVIBE_APP_SERVER_CONFIG_OVERRIDES = ("features.plugins=false","features.recommended_plugins=false","features.remote_plugin=false",+ # Preserve Avibe's injected developer items in Codex remote compaction v2.+ "features.retain_client_developer_messages=true","features.skill_mcp_dependency_install=false","features.terminal_visualization_instructions=false","features.tool_call_mcp_elicitation=false",@@ -63,6 +65,20 @@ def _avibe_app_server_config_args() -> list[str]:]+class CodexRPCError(RuntimeError):+ """A structured server error, distinct from an ambiguous transport failure."""++ def __init__(self, error: Any) -> None:+ super().__init__(f"Codex RPC error: {error}")+ self.code = error.get("code") if isinstance(error, dict) else None++ @property+ def request_rejected(self) -> bool:+ # Protocol validation failures precede dispatch. Internal/server errors+ # do not prove that a mutation was rejected before it took effect.+ return self.code in {-32600, -32601, -32602}++class CodexTransport:"""Manages a persistent ``codex app-server`` subprocess.@@ -163,9 +179,9 @@ class CodexTransport:"title": "Avibe","version": "1.0.0",},- # Dynamic developer instructions for an existing native- # thread use turn/start.collaborationMode. Omitted- # server-request capabilities remain disabled.+ # Developer item injection and legacy collaboration-mode+ # cleanup use experimental APIs. Omitted server-request+ # capabilities remain disabled."capabilities": {"experimentalApi": True},},)@@ -174,10 +190,8 @@ class CodexTransport:try:await self.send_request("collaborationMode/list", {})except Exception as exc:- # Older app-servers accept unknown turn fields, so the catalog- # method is the capability probe. Fall back to item injection- # on any inconclusive result rather than risk dropping the- # developer instructions silently.+ # Only legacy-thread cleanup depends on collaboration support.+ # A catalog response does not prove custom prompt delivery.logger.info("Codex turn collaboration mode is unavailable; using developer item injection: %s",exc,@@ -401,7 +415,7 @@ class CodexTransport:fut = self._pending.pop(req_id, None)if fut and not fut.done():if "error" in msg:- fut.set_exception(RuntimeError(f"Codex RPC error: {msg['error']}"))+ fut.set_exception(CodexRPCError(msg["error"]))else:fut.set_result(msg.get("result", {}))returndiff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 3cd04db92..eef3a144f 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -1,4 +1,5 @@import asyncio+import hashlibimport importlib.utilimport jsonimport os@@ -15,6 +16,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.runtime_activation import RuntimeActivationRegistry+from modules.agents.codex.transport import CodexRPCError_AGENT_PATH = Path(__file__).resolve().parents[1] / "modules/agents/codex/agent.py"@@ -89,6 +91,7 @@ setattr(_session_module, "CodexSessionManager", object)_transport_module = types.ModuleType("modules.agents.codex.transport")setattr(_transport_module, "CodexTransport", object)+setattr(_transport_module, "CodexRPCError", CodexRPCError)_turn_state_module = types.ModuleType("modules.agents.codex.turn_state")setattr(_turn_state_module, "CodexTurnRegistry", object)@@ -3687,7 +3690,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(params["modelProvider"], "openai-managed")self.assertNotIn("developerInstructions", params)- async def test_start_turn_applies_stable_developer_instructions_with_collaboration_mode(self):+ async def test_start_turn_injects_stable_developer_instructions_once(self):agent = object.__new__(CodexAgent)agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)),@@ -3735,26 +3738,29 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):developer_instructions="stable prompt",)- first = transport.send_request.await_args_list[0].args[1]- second = transport.send_request.await_args_list[1].args[1]- expected_mode = {- "mode": "default",- "settings": {- "model": "gpt-5.4",- "reasoning_effort": "high",- "developer_instructions": "stable prompt",- },- }- self.assertEqual(first["collaborationMode"], expected_mode)- self.assertEqual(second["collaborationMode"], expected_mode)- agent.sessions.set_agent_session_runtime_marker.assert_called_once_with(+ calls = transport.send_request.await_args_list+ self.assertEqual(+ [entry.args[0] for entry in calls],+ ["thread/inject_items", "turn/start", "turn/start"],+ )+ self.assertEqual(calls[0].args[1]["items"][0]["role"], "developer")+ self.assertEqual(+ calls[0].args[1]["items"][0]["content"][0]["text"],+ agent._render_developer_prompt_snapshot("stable prompt"),+ )+ for entry in calls[1:]:+ self.assertNotIn("collaborationMode", entry.args[1])+ self.assertEqual(entry.args[1]["model"], "gpt-5.4")+ self.assertEqual(entry.args[1]["effort"], "high")+ self.assertEqual(agent.sessions.set_agent_session_runtime_marker.call_count, 2)+ agent.sessions.set_agent_session_runtime_marker.assert_called_with("ses-runtime",backend="codex",native_session_id="thread-1",key="codex_prompt_strategy",value={"thread_id": "thread-1",- "strategy": "collaboration",+ "strategy": "fallback","sha256": agent._prompt_fingerprint("stable prompt"),},)@@ -3808,14 +3814,15 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):"session-1:subagent:reviewer","codex",)- agent.sessions.set_agent_session_runtime_marker.assert_called_once_with(+ self.assertEqual(agent.sessions.set_agent_session_runtime_marker.call_count, 2)+ agent.sessions.set_agent_session_runtime_marker.assert_called_with("ses-backend",backend="codex",native_session_id="thread-subagent",key=CODEX_PROMPT_STRATEGY_METADATA_KEY,value={"thread_id": "thread-subagent",- "strategy": "collaboration",+ "strategy": "fallback","sha256": agent._prompt_fingerprint("stable prompt"),},)@@ -4125,7 +4132,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent_session_id="ses-runtime",)- async def test_start_turn_reuses_persisted_collaboration_after_inconclusive_probe(self):+ async def test_start_turn_migrates_persisted_collaboration_after_inconclusive_probe(self):agent = object.__new__(CodexAgent)agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),@@ -4172,17 +4179,20 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual([call.args[0] for call in transport.send_request.await_args_list],- ["collaborationMode/list", "turn/start"],+ ["collaborationMode/list", "thread/inject_items", "turn/start"],)- params = transport.send_request.await_args_list[1].args[1]+ params = transport.send_request.await_args_list[2].args[1]+ self.assertIsNone(params["collaborationMode"])+ self.assertEqual(params["model"], "gpt-5.4")+ self.assertEqual(params["effort"], "high")self.assertEqual(- params["collaborationMode"]["settings"]["developer_instructions"],- "stable prompt",+ transport.send_request.await_args_list[1].args[1]["items"][0]["content"][0]["text"],+ agent._render_developer_prompt_snapshot("stable prompt"),)- agent.sessions.set_agent_session_runtime_marker.assert_not_called()+ self.assertEqual(agent.sessions.set_agent_session_runtime_marker.call_count, 3)self.assertEqual(agent._thread_prompt_strategies["session-1"],- ("thread-1", "collaboration"),+ ("thread-1", "fallback"),)async def test_start_turn_fails_closed_when_collaboration_reprobe_is_negative(self):@@ -4679,8 +4689,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):params = transport.send_request.await_args.args[1]self.assertEqual(params["model"], "gpt-5.5")self.assertNotIn("effort", params)- self.assertEqual(params["collaborationMode"]["settings"]["model"], "gpt-5.5")- self.assertIsNone(params["collaborationMode"]["settings"]["reasoning_effort"])+ self.assertNotIn("collaborationMode", params)async def test_start_turn_preserves_explicit_effort_while_restoring_cached_model(self):agent = object.__new__(CodexAgent)@@ -4723,10 +4732,9 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):params = transport.send_request.await_args.args[1]self.assertEqual(params["model"], "gpt-5.4")self.assertEqual(params["effort"], "xhigh")- self.assertEqual(params["collaborationMode"]["settings"]["model"], "gpt-5.4")- self.assertEqual(params["collaborationMode"]["settings"]["reasoning_effort"], "xhigh")+ self.assertNotIn("collaborationMode", params)- async def test_start_turn_changes_only_collaboration_instructions_when_prompt_changes(self):+ async def test_start_turn_injects_updated_instructions_when_prompt_changes(self):agent = object.__new__(CodexAgent)agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),@@ -4762,15 +4770,27 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):developer_instructions=prompt,)- first = transport.send_request.await_args_list[0].args[1]- second = transport.send_request.await_args_list[1].args[1]- first_mode = first.pop("collaborationMode")- second_mode = second.pop("collaborationMode")- self.assertEqual(first, second)- self.assertEqual(first_mode["settings"]["developer_instructions"], "prompt one")- self.assertEqual(second_mode["settings"]["developer_instructions"], "prompt two")+ calls = transport.send_request.await_args_list+ self.assertEqual(+ [entry.args[0] for entry in calls],+ ["thread/inject_items", "turn/start", "thread/inject_items", "turn/start"],+ )+ self.assertEqual(calls[1].args[1], calls[3].args[1])+ self.assertEqual(+ calls[0].args[1]["items"][0]["content"][0]["text"],+ agent._render_developer_prompt_snapshot("prompt one"),+ )+ self.assertEqual(+ calls[2].args[1]["items"][0]["content"][0]["text"],+ agent._render_developer_prompt_snapshot("prompt two"),+ )+ latest = calls[2].args[1]["items"][0]["content"][0]["text"]+ self.assertIn("Only the most recent snapshot is active", latest)+ self.assertIn("including untagged versions", latest)+ self.assertIn("omitted from this snapshot no longer apply", latest)+ self.assertNotIn("prompt one", latest)- async def test_start_turn_falls_back_once_when_collaboration_mode_is_unsupported(self):+ async def test_start_turn_does_not_reinject_when_explicit_model_reset_is_unsupported(self):agent = object.__new__(CodexAgent)agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, "gpt-5.4", "high")),@@ -4797,12 +4817,14 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):supports_turn_collaboration_mode=True,send_request=AsyncMock(side_effect=[- RuntimeError("unknown field collaborationMode: experimental API unsupported"),{},+ RuntimeError("unknown field collaborationMode: experimental API unsupported"),{"turn": {"id": "turn-1"}},]),)+ request.vibe_agent_model_explicit = True+ request.vibe_agent_model = Noneawait agent._start_turn(transport,@@ -4812,12 +4834,14 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):)calls = transport.send_request.await_args_list- self.assertIn("collaborationMode", calls[0].args[1])- self.assertEqual(calls[1].args[0], "thread/inject_items")+ self.assertEqual(calls[0].args[0], "thread/inject_items")self.assertEqual(- calls[1].args[1]["items"][0]["content"][0]["text"],- "stable prompt",+ calls[0].args[1]["items"][0]["content"][0]["text"],+ agent._render_developer_prompt_snapshot("stable prompt"),)+ self.assertEqual(calls[1].args[0], "turn/start")+ self.assertIsNone(calls[1].args[1]["collaborationMode"])+ self.assertEqual(calls[2].args[0], "turn/start")self.assertNotIn("collaborationMode", calls[2].args[1])self.assertFalse(transport.supports_turn_collaboration_mode)@@ -4862,7 +4886,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(calls[0].args[0], "thread/inject_items")self.assertEqual(calls[0].args[1]["items"][0]["content"][0]["text"],- "stable prompt",+ agent._render_developer_prompt_snapshot("stable prompt"),)self.assertNotIn("collaborationMode", calls[1].args[1])@@ -5888,5 +5912,128 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):+class CodexPromptSnapshotRecoveryTests(unittest.IsolatedAsyncioTestCase):+ def _setup(self, strategy=None, *, legacy=False):+ self.marker = {}+ if strategy:+ prompt = "stable prompt"+ fingerprint = (+ hashlib.sha256(prompt.encode()).hexdigest()+ if legacy else CodexAgent._prompt_fingerprint(prompt)+ )+ self.marker.update(thread_id="thread-1", strategy=strategy, sha256=fingerprint)+ self.original_marker = dict(self.marker)+ self.request = SimpleNamespace(+ session_key="channel-1", base_session_id="session-1",+ composite_session_id="avibe:session-1", subagent_name=None,+ context=SimpleNamespace(platform_specific={}),+ )+ self.transport = SimpleNamespace(+ supports_turn_collaboration_mode=True,+ send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}),+ )+ return self._agent()++ def _agent(self):+ agent = object.__new__(CodexAgent)++ def persist(*_args, **kwargs):+ self.marker.clear()+ self.marker.update(kwargs["value"] or {})+ return True++ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=lambda *_args, **_kwargs: dict(self.marker) or None,+ set_agent_session_runtime_marker=Mock(side_effect=persist),+ )+ agent.ensure_agent_session_id = Mock(return_value="ses-runtime")+ agent._resolve_codex_agent_settings = Mock(return_value=(None, "gpt-5.4", "high", None))+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(), finalize_turn_start_response=Mock(),+ )+ return agent++ async def test_legacy_fallback_snapshots_migrate_once_including_fork_and_restart(self):+ for strategy in ("fallback", "fallback_pending_clear"):+ for forked in (False, True):+ with self.subTest(strategy=strategy, forked=forked):+ agent = self._setup(strategy, legacy=True)+ thread_id = "thread-1"+ if forked:+ agent._inject_caller_env_config = Mock(return_value=("path", True))+ agent._should_rollback_forked_running_turn = AsyncMock(return_value=False)+ agent._inject_forked_session_correction = AsyncMock()+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent.bind_agent_session_id = Mock(return_value="ses-runtime")+ agent._caller_env_for_request = Mock(return_value={})+ self.request.working_path = "/tmp/work"+ self.transport.send_request.return_value = {"thread": {"id": "thread-fork"}}+ thread_id = await agent._fork_thread(self.transport, self.request, {+ "source_session_id": "source", "source_native_session_id": "thread-1",+ })+ self.assertEqual(self.marker["sha256"], self.original_marker["sha256"])+ self.transport.send_request.reset_mock()+ self.transport.send_request.return_value = {"turn": {"id": "turn-1"}}+ for restart in (False, True):+ if restart:+ agent = self._agent()+ await agent._start_turn(+ self.transport, self.request, thread_id,+ developer_instructions="stable prompt",+ )+ injections = [+ call for call in self.transport.send_request.await_args_list+ if call.args[0] == "thread/inject_items"+ ]+ self.assertEqual(len(injections), 1)+ self.assertEqual(+ injections[0].args[1]["items"][0]["content"][0]["text"],+ CodexAgent._render_developer_prompt_snapshot("stable prompt"),+ )+ self.assertEqual(self.marker["strategy"], "fallback")+ self.assertEqual(self.marker["sha256"], CodexAgent._prompt_fingerprint("stable prompt"))++ async def test_rejected_injection_restores_marker_and_retries_before_dispatch(self):+ for strategy in (None, "fallback", "collaboration", "fallback_pending_clear"):+ for restart in (False, True):+ for code in (-32600, -32601, -32602):+ with self.subTest(strategy=strategy, restart=restart, code=code):+ agent = self._setup(strategy)+ self.transport.send_request.side_effect = CodexRPCError({"code": code, "message": "rejected"})+ with self.assertRaisesRegex(CodexPromptRefreshUnavailableError, "rejected"):+ await agent._start_turn(+ self.transport, self.request, "thread-1",+ developer_instructions="changed prompt",+ )+ self.assertEqual(self.marker, self.original_marker)+ agent._turn_registry.begin_turn_start.assert_not_called()+ if restart:+ agent = self._agent()+ self.transport.send_request.side_effect = None+ await agent._start_turn(+ self.transport, self.request, "thread-1",+ developer_instructions="changed prompt",+ )+ calls = self.transport.send_request.await_args_list+ self.assertEqual([c.args[0] for c in calls], [+ "thread/inject_items", "thread/inject_items", "turn/start",+ ])+ if strategy in {"collaboration", "fallback_pending_clear"}:+ self.assertIsNone(calls[-1].args[1]["collaborationMode"])+ self.assertEqual(self.marker["strategy"], "fallback")++ async def test_internal_rpc_error_keeps_ambiguous_injection_marker(self):+ agent = self._setup()+ self.transport.send_request.side_effect = CodexRPCError({"code": -32603, "message": "internal error"})+ with self.assertRaises(CodexRPCError):+ await agent._start_turn(+ self.transport, self.request, "thread-1", developer_instructions="stable prompt",+ )+ self.assertEqual(self.marker["strategy"], "fallback_pending_injection")+ agent._turn_registry.begin_turn_start.assert_not_called()++if __name__ == "__main__":unittest.main()diff --git a/tests/test_codex_prompt_delivery_contract.py b/tests/test_codex_prompt_delivery_contract.pynew file mode 100644index 000000000..f1bd7f05b--- /dev/null+++ b/tests/test_codex_prompt_delivery_contract.py@@ -0,0 +1,245 @@+"""Native prompt contract; opt in with CODEX_PROMPT_CONTRACT_BINARY.++Uses an isolated Codex home and a loopback Responses server, never credentials+or a real model. The catalog deliberately owns the default collaboration text.+"""++from __future__ import annotations++import asyncio+import hashlib+import json+import os+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++from aiohttp import web+import pytest++from modules.agents.codex.agent import CodexAgent+from modules.agents.codex.transport import CodexTransport+++BINARY = os.environ.get("CODEX_PROMPT_CONTRACT_BINARY")+pytestmark = pytest.mark.skipif(not BINARY, reason="requires an explicitly selected Codex binary")+MODEL = "avibe-prompt-contract"+CATALOG_PROMPT = "CATALOG_OWNS_DEFAULT_COLLABORATION_MODE"+PROMPT = "\n\n".join(+ (Path(__file__).resolve().parents[1] / "core" / "prompts" / name).read_text()+ for name in ("quick-replies.md", "session-title.md")+)+++def _agent(marker):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, MODEL, "high")))+ agent.codex_config = SimpleNamespace(default_model=None)++ def persist(*_args, **kwargs):+ marker.clear()+ marker.update(kwargs["value"])+ return True++ agent.sessions = SimpleNamespace(+ get_agent_session_runtime_marker=lambda *_args, **_kwargs: dict(marker) or None,+ set_agent_session_runtime_marker=persist,+ )+ agent.ensure_agent_session_id = Mock(return_value="contract-session")+ agent._build_input = Mock(return_value=[{"type": "text", "text": "Hello", "text_elements": []}])+ agent._write_caller_env_script = Mock()+ agent._turn_registry = SimpleNamespace(+ begin_turn_start=Mock(),+ get_bootstrapped_turn_id=Mock(return_value=None),+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),+ )+ return agent+++def _developer_texts(body):+ return [+ content["text"]+ for item in body["input"]+ if item.get("role") == "developer"+ for content in item["content"]+ if content.get("type") == "input_text"+ ]++[email protected]("legacy", [None, "collaboration", "fallback"])+async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_path, legacy):+ requests = []+ completed = asyncio.Queue()++ async def responses(request):+ requests.append(await request.json())+ response_id = f"resp-{len(requests)}"+ compacting = any(item.get("type") == "compaction_trigger" for item in requests[-1]["input"])+ events = [+ {"type": "response.created", "response": {"id": response_id}},+ {+ "type": "response.output_item.done",+ "output_index": 0,+ "item": {+ "type": "message",+ "role": "assistant",+ "id": f"msg-{len(requests)}",+ "content": [{"type": "output_text", "text": "OK", "annotations": []}],+ },+ },+ {+ "type": "response.completed",+ "response": {"id": response_id, "usage": {"input_tokens": 10, "output_tokens": 1, "total_tokens": 11}},+ },+ ]+ if compacting:+ events[1]["item"] = {"type": "compaction", "encrypted_content": "CONTRACT_SUMMARY"}+ return web.Response(+ text="".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events),+ content_type="text/event-stream",+ )++ app = web.Application()+ app.router.add_post("/responses", responses)+ runner = web.AppRunner(app)+ await runner.setup()+ server = await asyncio.get_running_loop().create_server(runner.server, "127.0.0.1", 0)+ port = server.sockets[0].getsockname()[1]+ codex_home = tmp_path / "codex"+ codex_home.mkdir()+ catalog = tmp_path / "models.json"+ catalog.write_text(+ json.dumps(+ {+ "models": [+ {+ "slug": MODEL,+ "display_name": MODEL,+ "supported_reasoning_levels": [],+ "shell_type": "unified_exec",+ "visibility": "list",+ "supported_in_api": True,+ "priority": 1,+ "support_verbosity": False,+ "experimental_supported_tools": [],+ "truncation_policy": {"mode": "tokens", "limit": 10000},+ "base_instructions": "You are a test assistant.",+ "model_messages": {"collaboration_modes": {"default": CATALOG_PROMPT}},+ }+ ]+ }+ )+ )+ (codex_home / "config.toml").write_text(+ f'model = "{MODEL}"\nmodel_provider = "contract"\n'+ f"model_catalog_json = {json.dumps(str(catalog))}\n"+ '[model_providers.contract]\nname = "OpenAI"\nwire_api = "responses"\n'+ f'base_url = "http://127.0.0.1:{port}"\nrequires_openai_auth = false\n'+ )++ def transport():+ return CodexTransport(+ binary=BINARY,+ cwd=str(tmp_path),+ runtime_env={+ "PATH": os.environ.get("PATH", ""),+ "HOME": str(tmp_path),+ "CODEX_HOME": str(codex_home),+ "XDG_CONFIG_HOME": str(tmp_path / "config"),+ },+ )++ async def notification(method, params):+ if method == "turn/completed":+ await completed.put(params)++ async def finish_turn():+ event = await asyncio.wait_for(completed.get(), timeout=30)+ assert event["turn"]["status"] == "completed", event++ native = transport()+ native.on_notification(notification)+ try:+ await native.start()+ thread = await native.send_request("thread/start", {"cwd": str(tmp_path), "model": MODEL})+ thread_id = thread["thread"]["id"]+ marker = {}+ if legacy == "collaboration":+ await native.send_request(+ "turn/start",+ {+ "threadId": thread_id,+ "input": [{"type": "text", "text": "Hello", "text_elements": []}],+ "collaborationMode": {+ "mode": "default",+ "settings": {"model": MODEL, "reasoning_effort": "high", "developer_instructions": PROMPT},+ },+ },+ )+ await finish_turn()+ # Characterize the upstream precedence that broke the old route.+ assert any(CATALOG_PROMPT in text for text in _developer_texts(requests[-1]))+ assert PROMPT not in _developer_texts(requests[-1])+ marker.update(thread_id=thread_id, strategy="collaboration", sha256=hashlib.sha256(PROMPT.encode()).hexdigest())+ elif legacy == "fallback":+ await native.send_request("thread/inject_items", {+ "threadId": thread_id,+ "items": [+ {"type": "message", "role": "developer", "content": [{"type": "input_text", "text": text}]}+ for text in ("An obsolete Skill is enabled.", PROMPT)+ ],+ })+ marker.update(thread_id=thread_id, strategy="fallback", sha256=hashlib.sha256(PROMPT.encode()).hexdigest())++ request = SimpleNamespace(+ session_key="contract",+ base_session_id="contract",+ composite_session_id="avibe:contract",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={}),+ )+ agent = _agent(marker)+ for _ in range(2):+ await agent._start_turn(native, request, thread_id, developer_instructions=PROMPT)+ await finish_turn()+ assert _developer_texts(requests[-1]).count(CodexAgent._render_developer_prompt_snapshot(PROMPT)) == 1+ assert requests[-1]["model"] == MODEL+ assert requests[-1]["reasoning"]["effort"] == "high"++ await native.stop()+ native = transport()+ native.on_notification(notification)+ await native.start()+ await native.send_request("thread/resume", {"threadId": thread_id})+ agent = _agent(marker)+ await agent._start_turn(native, request, thread_id, developer_instructions=PROMPT)+ await finish_turn()+ assert _developer_texts(requests[-1]).count(CodexAgent._render_developer_prompt_snapshot(PROMPT)) == 1++ # Removing a prompt source must revoke its earlier positive rules,+ # including when retained history still contains the old snapshot.+ changed = (Path(__file__).resolve().parents[1] / "core/prompts/session-title.md").read_text()+ changed_snapshot = CodexAgent._render_developer_prompt_snapshot(changed)+ await agent._start_turn(native, request, thread_id, developer_instructions=changed)+ await finish_turn()+ assert _developer_texts(requests[-1]).count(changed_snapshot) == 1+ assert "## Quick-reply buttons" not in changed_snapshot+ assert "omitted from this snapshot no longer apply" in changed_snapshot+ assert "including untagged versions" in changed_snapshot++ await native.send_request("thread/compact/start", {"threadId": thread_id})+ await finish_turn()+ assert any(item.get("type") == "compaction_trigger" for item in requests[-1]["input"])+ await agent._start_turn(native, request, thread_id, developer_instructions=changed)+ await finish_turn()+ snapshots = [text for text in _developer_texts(requests[-1]) if text.startswith("<avibe_runtime_instructions>")]+ assert snapshots.count(changed_snapshot) == 1+ assert snapshots[-1] == changed_snapshot+ finally:+ await native.stop()+ server.close()+ await server.wait_closed()+ await runner.cleanup()diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.pyindex 01a09c531..4485036f5 100644--- a/tests/test_codex_transport.py+++ b/tests/test_codex_transport.py@@ -9,6 +9,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from modules.agents.codex.transport import (AVIBE_APP_SERVER_CONFIG_OVERRIDES,+ CodexRPCError,CodexTransport,STREAM_BUFFER_LIMIT,)@@ -23,6 +24,19 @@ def _forced_config_args() -> tuple[str, ...]:class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):+ async def test_rpc_errors_preserve_protocol_rejection_identity(self):+ transport = CodexTransport(binary="codex", cwd="/tmp")+ for code in (-32600, -32601, -32602, -32603, -32000):+ with self.subTest(code=code):+ future = asyncio.get_running_loop().create_future()+ transport._pending[1] = future+ await transport._dispatch({"id": 1, "error": {"code": code, "message": "failure"}})+ with self.assertRaises(CodexRPCError) as caught:+ await future+ self.assertEqual(caught.exception.code, code)+ self.assertEqual(caught.exception.request_rejected, code in {-32600, -32601, -32602})+ self.assertNotIn(1, transport._pending)+async def test_cancelled_initialize_stops_unpublished_transport(self):initialize_started = asyncio.Event()@@ -204,6 +218,12 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):self.assertNotIn("features.shell_tool=false", disabled)self.assertNotIn("web_search=disabled", disabled)+ def test_app_server_policy_preserves_client_developer_messages(self):+ self.assertIn(+ "features.retain_client_developer_messages=true",+ AVIBE_APP_SERVER_CONFIG_OVERRIDES,+ )+async def test_reader_task_failure_marks_transport_not_alive(self):transport = CodexTransport(binary="codex", cwd="/tmp")transport._process = SimpleNamespace(returncode=None)