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 native prompt baseline with live overlays (#1956)
Call White4a504f375b73
diff --git a/docs/plans/codex-native-prompt-baseline.md b/docs/plans/codex-native-prompt-baseline.mdnew file mode 100644index 000000000..8fec45c40--- /dev/null+++ b/docs/plans/codex-native-prompt-baseline.md@@ -0,0 +1,87 @@+# Codex native prompt baseline++## Decision and scope++Restore a complete Avibe prompt baseline through native `developerInstructions`+at thread creation, fork, and resume. Keep the existing durable, at-most-once+developer-message injection path for changes on already-loaded threads.+This is an explicitly limited compatibility mode, not lossless hot replacement.+It does not depend on an unmerged Codex change.++The upstream contribution policy at `openai/codex@5a65fd87d842` accepts issues,+not external code PRs. Prepare a minimal reproduction and source analysis for+that supported channel; do not submit an unsolicited code PR.++## Boundary contract++- Render Avibe instructions once at the dispatch boundary, before a new native+ thread needs them. Reuse those exact bytes for native configuration and any+ necessary history injection, including transport recovery.+- Preserve independently configured Codex developer instructions when setting+ the native baseline. Do not change model, reasoning, permissions, user/project+ instructions, or shared production/export/Studio composition.+- On a genuinely new thread, native configuration is enough: record the current+ Avibe fingerprint using the existing durable marker and do not also append it.+- On resume or fork, retain the last model-visible fingerprint. Supplying a new+ native configuration does not prove that restored history already contains it.+ Changed Avibe instructions still use the existing injection path.+- Unchanged instructions do not generate additional injected messages on normal+ turns or restart. Ambiguous injection, persistence failure, legacy collaboration+ markers, and fork ownership retain their existing recovery semantics.+- Do not call resume to refresh prompts on a cached thread, force compaction,+ unload a thread, restart a transport, or terminate background resources merely+ because prompt content changes.++## Known-by-design ledger++1. Injection changes model-visible history, not the loaded native configuration.+ Automatic compaction reconstructs the last native baseline. A newer injected+ overlay can be retained, truncated, or evicted under the provider's policy.+ Its loss can expose the older baseline; this change does not guarantee that+ revoked prompt wording can never reappear.+2. Resume overrides take effect in native configuration only on a cold load.+ Existing history can retain the old baseline until context reconstruction.+ No warm-resume acknowledgement is interpreted as successful prompt refresh.+3. Cold promotion and later compaction can leave both a native copy and retained+ injected copies. Historical cleanup requires upstream lifecycle support; do+ not rewrite rollouts or silently discard other developer messages.+ Loss of the initial durable delivery marker can likewise require an injected+ copy on recovery; native creation and application storage are not atomic.+4. There is no new marker schema or strategy, deployment, Studio source change,+ saved-draft modification, or cross-backend prompt change.++## Acceptance and evidence++- Unit coverage: native creation, resume, fork, one render, preservation of+ configured instructions, durable marker recovery, unchanged-state deduplication,+ and existing legacy/ambiguous-outcome cases.+- Native contract: an isolated Codex home and loopback Responses server, with no+ model credentials. Inspect actual outbound requests before/after changes,+ process restart, ordinary compaction, and automatic compaction under more than+ 64K retained-history pressure. Include non-ASCII prompt text.+- The pressure case must show a complete native baseline surviving, and must+ explicitly characterize loss of a newer overlay instead of asserting a false+ latest-version guarantee.+- Run focused Codex tests and changed-file Ruff before push; require exact-head+ Codex review, all lint checks, and zero unresolved review threads before delivery.+ No existing scenario catalog owns this transport contract.++## Verified native behavior++The isolated contract passes on Codex CLI 0.153.2 with actual outbound Responses+requests, including non-ASCII instructions and separately configured native text.+The table counts complete Avibe prompt copies, not RPC acknowledgements:++| Stage | Native A | Native B | Injected B |+| --- | ---: | ---: | ---: |+| New thread and unchanged restart | 1 | 0 | 0 |+| Live update | 1 | 0 | 1 |+| Automatic compaction, ordinary retained history | 1 | 0 | 1 |+| Automatic compaction, over-budget recent user history | 1 | 0 | 0 |+| Cold resume with B, ordinary retained history | 1 | 0 | 1 |+| Subsequent compaction after cold resume | 0 | 1 | 1 |++Fork tests also verify that the first target turn receives B through injection+and later compaction reconstructs its B baseline. Existing native user preferences+remain present. These results verify transport and context composition, not model+obedience or live UI behavior.diff --git a/docs/plans/codex-prompt-delivery.md b/docs/plans/codex-prompt-delivery.mdindex ac51b0193..c114d5a76 100644--- a/docs/plans/codex-prompt-delivery.md+++ b/docs/plans/codex-prompt-delivery.md@@ -3,11 +3,13 @@## ContractAvibe-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.+of model-owned collaboration text. A complete native baseline must survive+context reconstruction. Changed prompts on loaded threads use an injected+snapshot that instructs the model to supersede earlier Avibe snapshots; this is+not a guarantee of history cleanup or latest-version retention. Unchanged+instructions must not accumulate on normal turns 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@@ -17,8 +19,14 @@ Codex 0.153.2 prefers a model catalog's collaboration instructions overBoth quick-reply and session-title rules can be present in the turn parameterswhile 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,+Avibe sets native `developerInstructions` at thread creation, fork, and resume,+preserving independently configured native instructions. A fresh thread records+its initial fingerprint without also injecting a copy. Resume and fork preserve+the last delivered fingerprint because restored history may still contain an+older baseline, even when the new native configuration was accepted.++Avibe uses `thread/inject_items` with explicit developer messages for changes on+loaded threads. Each message declares complete-snapshot replacement semantics,including superseding legacy untagged snapshots. History is retained, but removedrules and capability, Agent, and Skill declarations must not remain active. Userand project instructions are outside this replacement boundary.@@ -36,27 +44,37 @@ attempt after API compatibility is repaired. Transport failures and internalserver errors remain ambiguous and retain the write-ahead marker. If restoringthe 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+`features.retain_client_developer_messages=true` makes these messages eligible+for budget-limited retention during Codex remote compaction v2. It does not pin+them: recent user history can exhaust the 64K retained-message budget and evict+an older injected snapshot. Native configuration, not that budgeted history,+provides the reconstructed baseline. This replaces the collaboration-based deliverydescribed in the earlier managed-Skills implementation plan; Skill discovery andprompt composition are unchanged.## Evidence and Limits-- Unit tests cover injection deduplication, changed instructions, model routing,- legacy migration, persistence failures, ambiguous RPCs, and restart recovery.+- Unit tests cover native start/resume/fork, one render per dispatch, configured+ instruction preservation, injection deduplication, changed instructions, model+ routing, legacy migration, persistence failures, ambiguous RPCs, and recovery.- `tests/test_codex_prompt_delivery_contract.py` drives the real Codex executablethrough Avibe's agent and transport into a loopback Responses server. It usesthe actual quick-reply and session-title templates and a model catalog thatoverrides collaboration text. It covers new and legacy threads, prompt changes,- process restart, and remote compaction v2.+ process restart, remote compaction v2, and automatic compaction with retained+ history exceeding the 64K budget. It explicitly demonstrates both native+ baseline survival and newer-overlay eviction.- Run the native contract with `CODEX_PROMPT_CONTRACT_BINARY` set to the selectedexecutable and pytest targeting that file. It is opt-in, requires no modelcredentials, and was verified with Codex 0.153.2. Ordinary CI runs the unitcontract 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.+- Neither the retention flag nor this hybrid path guarantees the latest prompt+ after compaction. A loaded thread retains its last native baseline; an injected+ update does not change it. Cold resume can promote new native configuration,+ but restored history remains unchanged until context reconstruction. That+ reconstruction can also retain an injected duplicate. Older compaction and+ third-party local summarization have additional limitations. See+ [the native-baseline contract](codex-native-prompt-baseline.md).- This verifies transport delivery, not whether a real model follows every rule.Live Workbench button rendering and automatic title changes require the localIncus integration pass; no running developer service is restarted by this fix.diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 26c05daf5..ac750bc69 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -461,12 +461,18 @@ class CodexAgent(BaseAgent):self._turn_registry.remember_request(request)developer_instructions: Optional[str] = None+ prompt_rendered = Falsetry:# Get or create thread (with resume support)thread_id = self._session_mgr.get_thread_id(request.base_session_id)if not thread_id:- thread_id = await self._start_or_resume_thread(transport, request)+ self.ensure_agent_session_id(request)+ developer_instructions = await self._build_thread_developer_instructions(request)+ prompt_rendered = True+ thread_id = await self._start_or_resume_thread(+ transport, request, developer_instructions=developer_instructions+ )# If a turn is active, interrupt it firstactive_turn = self._turn_registry.get_active_turn(request.base_session_id)@@ -499,7 +505,9 @@ class CodexAgent(BaseAgent):# payload byte-stable, this avoids repeating Memory admission# side effects while the same request refreshes and starts.self.ensure_agent_session_id(request)- developer_instructions = await self._build_thread_developer_instructions(request)+ if not prompt_rendered:+ developer_instructions = await self._build_thread_developer_instructions(request)+ prompt_rendered = Trueawait self._refresh_thread_developer_instructions_if_needed(transport,request,@@ -530,9 +538,13 @@ class CodexAgent(BaseAgent):else:transport = await self._get_or_create_transport(request.working_path, launch)self._touch_transport_activity(request.working_path)- thread_id = await self._start_or_resume_thread(transport, request)- if developer_instructions is None:+ if not prompt_rendered:+ self.ensure_agent_session_id(request)developer_instructions = await self._build_thread_developer_instructions(request)+ prompt_rendered = True+ thread_id = await self._start_or_resume_thread(+ transport, request, developer_instructions=developer_instructions+ )self._bind_runtime_agent_session_id(request)await self._start_turn(transport,@@ -1956,6 +1968,8 @@ class CodexAgent(BaseAgent):self,transport: CodexTransport,request: AgentRequest,+ *,+ developer_instructions: Optional[str] = None,) -> str:"""Create a new Codex thread and return its threadId."""params: Dict[str, Any] = {@@ -1964,6 +1978,10 @@ class CodexAgent(BaseAgent):"sandbox": "danger-full-access",}self.ensure_agent_session_id(request)+ if developer_instructions:+ params["developerInstructions"] = await self._native_thread_prompt(+ transport, request, developer_instructions+ )git_path_state, git_path_managed = self._inject_caller_env_config(params, request)resp = await transport.send_request("thread/start", params)@@ -1979,6 +1997,34 @@ class CodexAgent(BaseAgent):self._session_mgr.set_thread_id(request.base_session_id, thread_id)# Also persist for resume supportself.bind_agent_session_id(request, thread_id)+ if developer_instructions:+ from core.skill_observability import accept_catalog++ accept_catalog(+ self.controller,+ request.context,+ getattr(request, "skill_catalog_observation", None),+ backend="codex",+ )+ # Only a genuinely new thread can establish its first model-visible+ # prompt from native configuration alone. Resume/fork still carry+ # history, so they must not advance this delivery fingerprint.+ self._remember_thread_developer_instructions(+ request.base_session_id, thread_id, developer_instructions+ )+ self._remember_thread_prompt_strategy(+ request.base_session_id, thread_id, "injected_pending_persist"+ )+ if not hasattr(self, "_thread_unpersisted_prompts"):+ self._thread_unpersisted_prompts = {}+ self._thread_unpersisted_prompts[request.base_session_id] = (+ thread_id,+ developer_instructions,+ "fallback",+ )+ self._repair_unpersisted_prompt_strategy(+ request, thread_id, agent_session_id=self._prompt_state_agent_session_id(request)+ )self._remember_thread_model_settings_from_response(request.base_session_id,thread_id,@@ -2002,6 +2048,8 @@ class CodexAgent(BaseAgent):transport: CodexTransport,request: AgentRequest,fork: dict[str, Any],+ *,+ developer_instructions: Optional[str] = None,) -> str:"""Fork an existing Codex thread and bind the new thread id."""target_agent_session_id = self.ensure_agent_session_id(request)@@ -2048,7 +2096,11 @@ class CodexAgent(BaseAgent):"approvalPolicy": "never","sandbox": "danger-full-access",}- if source_prompt_strategy is None and callable(+ if developer_instructions:+ params["developerInstructions"] = await self._native_thread_prompt(+ transport, request, developer_instructions+ )+ elif source_prompt_strategy is None and callable(getattr(getattr(self, "sessions", None),"get_agent_session_runtime_marker",@@ -2302,6 +2354,8 @@ class CodexAgent(BaseAgent):self,transport: CodexTransport,request: AgentRequest,+ *,+ developer_instructions: Optional[str] = None,) -> str:"""Try to resume a persisted thread, fall back to creating a new one."""# Resume the native thread bound to the RESERVED workbench row (by PK): the@@ -2326,6 +2380,10 @@ class CodexAgent(BaseAgent):resume_params: Dict[str, Any] = {"threadId": persisted,}+ if developer_instructions:+ resume_params["developerInstructions"] = await self._native_thread_prompt(+ transport, request, developer_instructions+ )marker_getter = getattr(getattr(self, "sessions", None),"get_agent_session_runtime_marker",@@ -2336,7 +2394,7 @@ class CodexAgent(BaseAgent):persisted,agent_session_id=self._prompt_state_agent_session_id(request),)- if marker is None:+ if marker is None and not developer_instructions:# Older Avibe releases persisted their prompt as thread# configuration. Clear it before the first Turn selects# one of the new prompt-delivery strategies.@@ -2408,10 +2466,42 @@ class CodexAgent(BaseAgent):fork = pending_native_fork(request.context, self.name)if fork:- return await self._fork_thread(transport, request, fork)+ return await self._fork_thread(+ transport, request, fork, developer_instructions=developer_instructions+ )# No associated thread yet (genuinely first turn) — start fresh.- return await self._start_thread(transport, request)+ return await self._start_thread(+ transport, request, developer_instructions=developer_instructions+ )++ async def _native_thread_prompt(+ self,+ transport: CodexTransport,+ request: AgentRequest,+ developer_instructions: str,+ ) -> str:+ """Keep user-configured native instructions before Avibe's baseline.++ Native configuration is reconstructed after compaction, whereas injected+ items are budgeted history. Never claim that an overlay updates this+ configuration, or advance the history fingerprint on resume/fork.+ """+ params: Dict[str, Any] = {"includeLayers": False}+ if getattr(request, "working_path", None):+ params["cwd"] = request.working_path+ response = await transport.send_request("config/read", params)+ config = response.get("config") if isinstance(response, dict) else None+ if not isinstance(config, dict):+ raise CodexPromptRefreshUnavailableError(+ "Could not read configured Codex instructions before setting the native baseline"+ )+ configured = config.get("developer_instructions")+ if configured is not None and not isinstance(configured, str):+ raise CodexPromptRefreshUnavailableError(+ "Configured Codex developer instructions must be text"+ )+ return f"{configured}\n\n{developer_instructions}" if configured else developer_instructionsasync def _resolve_resume_model_provider_override(self,diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.pyindex 5019f92e4..6a6cbf743 100644--- a/modules/agents/codex/transport.py+++ b/modules/agents/codex/transport.py@@ -46,7 +46,7 @@ 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.+ # Opt injected updates into budgeted retention, not guaranteed persistence."features.retain_client_developer_messages=true","features.skill_mcp_dependency_install=false","features.terminal_visualization_instructions=false",diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 25e217fab..3b3b7d832 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -1684,7 +1684,9 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):{"threadId": "thread-old", "turnId": "turn-1"},)agent._event_handler.clear_pending.assert_not_called()- agent._start_or_resume_thread.assert_awaited_once_with(fresh_transport, request)+ agent._start_or_resume_thread.assert_awaited_once_with(+ fresh_transport, request, developer_instructions="stable prompt"+ )agent._start_thread.assert_not_awaited()agent.controller.emit_agent_message.assert_not_awaited()diff --git a/tests/test_codex_native_prompt_baseline.py b/tests/test_codex_native_prompt_baseline.pynew file mode 100644index 000000000..5ff3e5f65--- /dev/null+++ b/tests/test_codex_native_prompt_baseline.py@@ -0,0 +1,213 @@+"""Native-baseline lifecycle boundaries, using the production agent."""++from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock, call, patch++import pytest++from modules.agents.codex.agent import CodexAgent, CodexPromptRefreshUnavailableError+++PROMPT_A = "完整的 Avibe baseline A.\nKeep the user's preferences."+PROMPT_B = "完整的 Avibe baseline B.\nA removed capability is unavailable."+++def _request():+ return SimpleNamespace(+ session_key="contract",+ base_session_id="contract",+ composite_session_id="avibe:contract",+ working_path="/tmp/contract",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ ack_message_id=None,+ context=SimpleNamespace(platform_specific={}),+ )+++def _agent(marker):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace(get_codex_overrides=Mock(return_value=(None, None, None)))+ agent.codex_config = SimpleNamespace(default_model=None)+ native_binding = {}++ def persist(*_args, **kwargs):+ marker.clear()+ marker.update(kwargs["value"] or {})+ return True++ agent.sessions = SimpleNamespace(+ get_agent_session_id=lambda *_: native_binding.get("id"),+ get_agent_session_runtime_marker=lambda *_args, **_kwargs: dict(marker) or None,+ set_agent_session_runtime_marker=Mock(side_effect=persist),+ )+ agent.ensure_agent_session_id = Mock(return_value="contract-session")+ agent.bind_agent_session_id = Mock(+ side_effect=lambda _request, thread: native_binding.update(id=thread) or "contract-session"+ )+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent._inject_caller_env_config = Mock(return_value=("", False))+ agent._caller_env_for_request = Mock(return_value={})+ 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 _transport(config=None):+ async def rpc(method, params):+ if method == "config/read":+ return {"config": config or {}}+ if method in {"thread/start", "thread/resume", "thread/fork"}:+ return {"thread": {"id": "thread-contract"}}+ if method == "turn/start":+ return {"turn": {"id": "turn-contract"}}+ assert method == "thread/inject_items", method+ return {}++ return SimpleNamespace(send_request=AsyncMock(side_effect=rpc))+++async def test_new_thread_native_baseline_deduplicates_and_records_catalog():+ marker = {}+ agent = _agent(marker)+ request = _request()+ request.skill_catalog_observation = {"catalog": "candidate"}+ transport = _transport({"developer_instructions": "User's native instructions.\n"})+ with patch("core.skill_observability.accept_catalog") as accept:+ thread_id = await agent._start_or_resume_thread(transport, request, developer_instructions=PROMPT_A)+ await agent._start_turn(transport, request, thread_id, developer_instructions=PROMPT_A)+ await agent._start_turn(transport, request, thread_id, developer_instructions=PROMPT_A)+ calls = transport.send_request.await_args_list+ assert [item.args[0] for item in calls] == ["config/read", "thread/start", "turn/start", "turn/start"]+ assert calls[0] == call("config/read", {"includeLayers": False, "cwd": request.working_path})+ assert calls[1].args[1]["developerInstructions"] == "User's native instructions.\n\n\n" + PROMPT_A+ assert marker == {+ "thread_id": thread_id,+ "strategy": "fallback",+ "sha256": agent._prompt_fingerprint(PROMPT_A),+ }+ accept.assert_called_once_with(+ agent.controller, request.context, request.skill_catalog_observation, backend="codex"+ )++[email protected]("config", [None, [], {"developer_instructions": ["invalid"]}])+async def test_unreadable_native_configuration_fails_before_thread_mutation(config):+ agent = _agent({})+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"config": config}))+ with pytest.raises(CodexPromptRefreshUnavailableError):+ await agent._start_thread(transport, _request(), developer_instructions=PROMPT_A)+ assert [item.args[0] for item in transport.send_request.await_args_list] == ["config/read"]+ agent.bind_agent_session_id.assert_not_called()+ agent.sessions.set_agent_session_runtime_marker.assert_not_called()+++async def test_native_marker_failure_repairs_before_dispatch_without_duplicate_injection():+ marker = {}+ agent = _agent(marker)+ persist = agent.sessions.set_agent_session_runtime_marker.side_effect+ agent.sessions.set_agent_session_runtime_marker.side_effect = RuntimeError("storage unavailable")+ request = _request()+ transport = _transport()+ with pytest.raises(CodexPromptRefreshUnavailableError, match="Could not persist"):+ await agent._start_thread(transport, request, developer_instructions=PROMPT_A)+ assert not marker+ assert agent._thread_prompt_strategies[request.base_session_id][1] == "injected_pending_persist"++ agent.sessions.set_agent_session_runtime_marker.side_effect = persist+ await agent._start_turn(transport, request, "thread-contract", developer_instructions=PROMPT_A)+ assert [item.args[0] for item in transport.send_request.await_args_list] == [+ "config/read", "thread/start", "turn/start"+ ]+ assert marker["sha256"] == agent._prompt_fingerprint(PROMPT_A)+ assert not agent._thread_unpersisted_prompts++[email protected]("changed", [False, True])+async def test_resume_preserves_history_fingerprint_even_after_native_override(changed):+ marker = {"thread_id": "thread-contract", "strategy": "fallback", "sha256": CodexAgent._prompt_fingerprint(PROMPT_A)}+ agent = _agent(marker)+ agent.sessions.get_agent_session_id = Mock(return_value="thread-contract")+ agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)+ request = _request()+ transport = _transport()+ current = PROMPT_B if changed else PROMPT_A++ thread_id = await agent._start_or_resume_thread(transport, request, developer_instructions=current)+ assert marker["sha256"] == agent._prompt_fingerprint(PROMPT_A)+ assert not getattr(agent, "_thread_developer_instructions", {})+ assert transport.send_request.await_args.args[1]["developerInstructions"] == current+ await agent._start_turn(transport, request, thread_id, developer_instructions=current)+ methods = [item.args[0] for item in transport.send_request.await_args_list]+ assert methods.count("thread/inject_items") == int(changed)+ assert marker["sha256"] == agent._prompt_fingerprint(current)+++async def test_fork_sets_target_baseline_but_inherits_source_history_identity():+ marker = {}+ agent = _agent(marker)+ agent._fork_source_prompt_state = Mock(return_value=("fallback", agent._prompt_fingerprint(PROMPT_A), PROMPT_A))+ agent._should_rollback_forked_running_turn = AsyncMock(return_value=False)+ agent._inject_forked_session_correction = AsyncMock()+ agent._mark_fork_correction_pending = Mock()+ agent._clear_fork_correction_pending = Mock()+ request = _request()+ transport = _transport()+ thread_id = await agent._fork_thread(+ transport, request, {"source_native_session_id": "source"}, developer_instructions=PROMPT_B+ )+ assert marker["sha256"] == agent._prompt_fingerprint(PROMPT_A)+ assert transport.send_request.await_args.args[1]["developerInstructions"] == PROMPT_B+ await agent._start_turn(transport, request, thread_id, developer_instructions=PROMPT_B)+ assert marker["sha256"] == agent._prompt_fingerprint(PROMPT_B)+ assert [item.args[0] for item in transport.send_request.await_args_list] == [+ "config/read", "thread/fork", "thread/inject_items", "turn/start"+ ]++[email protected]("prompt", [PROMPT_A, None, ""])[email protected]("recover", [False, True])+async def test_dispatch_renders_once_even_for_empty_prompt_and_transport_recovery(prompt, recover):+ agent = _agent({})+ request = _request()+ agent._session_locks = {}+ agent._session_mgr = SimpleNamespace(+ set_session_key=Mock(), set_cwd=Mock(), get_thread_id=Mock(return_value=None)+ )+ agent._turn_registry.remember_request = Mock()+ agent._turn_registry.get_active_turn = Mock(return_value=None)+ agent._delete_ack = AsyncMock()+ agent._touch_transport_activity = Mock()+ transport = _transport()+ fresh = _transport()+ agent._get_or_create_transport = AsyncMock(side_effect=[transport, fresh])+ agent._drop_transport_after_failure = AsyncMock()+ agent._refresh_thread_developer_instructions_if_needed = AsyncMock()+ agent._bind_runtime_agent_session_id = Mock()+ agent._build_thread_developer_instructions = AsyncMock(return_value=prompt)+ agent._start_or_resume_thread = AsyncMock(+ side_effect=[ConnectionError("Codex app-server transport is not available"), "thread-contract"]+ if recover else ["thread-contract"]+ )+ agent._start_turn = AsyncMock()+ await agent.handle_message(request)+ agent._build_thread_developer_instructions.assert_awaited_once_with(request)+ assert agent._start_or_resume_thread.await_args_list == [+ call(transport, request, developer_instructions=prompt),+ *([call(fresh, request, developer_instructions=prompt)] if recover else []),+ ]+ agent._start_turn.assert_awaited_once_with(+ fresh if recover else transport, request, "thread-contract", developer_instructions=prompt+ )diff --git a/tests/test_codex_prompt_delivery_contract.py b/tests/test_codex_prompt_delivery_contract.pyindex f1bd7f05b..0e0e37a63 100644--- a/tests/test_codex_prompt_delivery_contract.py+++ b/tests/test_codex_prompt_delivery_contract.py@@ -10,6 +10,7 @@ import asyncioimport hashlibimport jsonimport os+from contextlib import asynccontextmanagerfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import Mock@@ -42,10 +43,14 @@ def _agent(marker):return Trueagent.sessions = SimpleNamespace(+ get_agent_session_id=lambda *_args: marker.get("thread_id"),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.bind_agent_session_id = Mock(return_value="contract-session")+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent._caller_env_for_request = Mock(return_value={})agent._build_input = Mock(return_value=[{"type": "text", "text": "Hello", "text_elements": []}])agent._write_caller_env_script = Mock()agent._turn_registry = SimpleNamespace(@@ -66,16 +71,18 @@ def _developer_texts(body):][email protected]("legacy", [None, "collaboration", "fallback"])-async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_path, legacy):+@asynccontextmanager+async def _native_server(tmp_path, *, configured_instructions=None):requests = []completed = asyncio.Queue()+ harness = SimpleNamespace(requests=requests, next_input_tokens=10)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"])+ tokens = harness.next_input_tokens+ harness.next_input_tokens = 10events = [{"type": "response.created", "response": {"id": response_id}},{@@ -90,7 +97,10 @@ async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_pa},{"type": "response.completed",- "response": {"id": response_id, "usage": {"input_tokens": 10, "output_tokens": 1, "total_tokens": 11}},+ "response": {+ "id": response_id,+ "usage": {"input_tokens": tokens, "output_tokens": 1, "total_tokens": tokens + 1},+ },},]if compacting:@@ -131,9 +141,15 @@ async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_pa}))+ developer_config = (+ f"developer_instructions = {json.dumps(configured_instructions, ensure_ascii=False)}\n"+ if configured_instructions else ""+ )(codex_home / "config.toml").write_text(f'model = "{MODEL}"\nmodel_provider = "contract"\n'f"model_catalog_json = {json.dumps(str(catalog))}\n"+ "model_auto_compact_token_limit = 100000\n"+ f"{developer_config}"'[model_providers.contract]\nname = "OpenAI"\nwire_api = "responses"\n'f'base_url = "http://127.0.0.1:{port}"\nrequires_openai_auth = false\n')@@ -158,10 +174,46 @@ async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_paevent = await asyncio.wait_for(completed.get(), timeout=30)assert event["turn"]["status"] == "completed", event- native = transport()- native.on_notification(notification)+ harness.native = transport()+ harness.native.on_notification(notification)++ async def restart():+ await harness.native.stop()+ harness.native = transport()+ harness.native.on_notification(notification)+ await harness.native.start()+ return harness.native++ harness.restart = restart+ harness.finish_turn = finish_turntry:- await native.start()+ await harness.native.start()+ yield harness+ finally:+ await harness.native.stop()+ server.close()+ await server.wait_closed()+ await runner.cleanup()+++def _request(tmp_path):+ return SimpleNamespace(+ session_key="contract",+ base_session_id="contract",+ working_path=str(tmp_path),+ composite_session_id="avibe:contract",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ context=SimpleNamespace(platform_specific={"agent_session_id": "contract-session"}),+ )++[email protected]("legacy", [None, "collaboration", "fallback"])+async def test_native_model_receives_injected_prompt_once_across_turns_and_restart(tmp_path, legacy):+ async with _native_server(tmp_path) as harness:+ native, requests, finish_turn = harness.native, harness.requests, harness.finish_turnthread = await native.send_request("thread/start", {"cwd": str(tmp_path), "model": MODEL})thread_id = thread["thread"]["id"]marker = {}@@ -192,15 +244,7 @@ async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_pa})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={}),- )+ request = _request(tmp_path)agent = _agent(marker)for _ in range(2):await agent._start_turn(native, request, thread_id, developer_instructions=PROMPT)@@ -209,10 +253,7 @@ async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_paassert requests[-1]["model"] == MODELassert requests[-1]["reasoning"]["effort"] == "high"- await native.stop()- native = transport()- native.on_notification(notification)- await native.start()+ native = await harness.restart()await native.send_request("thread/resume", {"threadId": thread_id})agent = _agent(marker)await agent._start_turn(native, request, thread_id, developer_instructions=PROMPT)@@ -238,8 +279,118 @@ async def test_native_model_receives_prompt_once_across_turns_and_restart(tmp_pasnapshots = [text for text in _developer_texts(requests[-1]) if text.startswith("<avibe_runtime_instructions>")]assert snapshots.count(changed_snapshot) == 1assert snapshots[-1] == changed_snapshot- finally:- await native.stop()- server.close()- await server.wait_closed()- await runner.cleanup()++[email protected]("retention_pressure", [False, True])+async def test_native_baseline_survives_auto_compaction_and_cold_promotion(tmp_path, retention_pressure):+ configured = "Native user preference: 保留我自己的规则。"+ baseline = "AVIBE_BASELINE_A:完整基线。\n" + PROMPT+ changed = "AVIBE_BASELINE_B:更新后基线。\n" + PROMPT+ snapshot = CodexAgent._render_developer_prompt_snapshot(changed)++ async with _native_server(tmp_path, configured_instructions=configured) as harness:+ native = harness.native+ request = _request(tmp_path)+ marker = {}+ agent = _agent(marker)+ thread_id = await agent._start_or_resume_thread(native, request, developer_instructions=baseline)++ async def turn(prompt):+ await agent._start_turn(native, request, thread_id, developer_instructions=prompt)+ await harness.finish_turn()+ return "\n".join(_developer_texts(harness.requests[-1]))++ for _ in range(2):+ text = await turn(baseline)+ assert text.count(configured) == 1+ assert text.count(baseline) == 1+ assert "<avibe_runtime_instructions>" not in text++ # Restart on unchanged bytes: use Avibe's actual resume path, not only+ # the native RPC, and verify that its durable marker avoids injection.+ native = await harness.restart()+ agent = _agent(marker)+ assert await agent._start_or_resume_thread(native, request, developer_instructions=baseline) == thread_id+ text = await turn(baseline)+ assert text.count(baseline) == 1+ assert "<avibe_runtime_instructions>" not in text++ # Inject the newer overlay before a recent user item. Its reported usage+ # forces automatic pre-turn compaction on the next actual turn/start.+ if retention_pressure:+ agent._build_input.return_value = [+ {"type": "text", "text": "Recent history data. " * 18000, "text_elements": []}+ ]+ harness.next_input_tokens = 200000+ text = await turn(changed)+ assert text.count(baseline) == 1+ assert text.count(snapshot) == 1+ agent._build_input.return_value = [{"type": "text", "text": "Continue", "text_elements": []}]+ prior_requests = len(harness.requests)+ text = await turn(changed)+ assert any(+ item.get("type") == "compaction_trigger"+ for body in harness.requests[prior_requests:]+ for item in body["input"]+ )+ assert text.count(configured) == 1+ assert text.count(baseline) == 1+ # A native baseline survives budget pressure. An injected overlay does+ # not: characterize this limit rather than claim latest-version safety.+ assert text.count(snapshot) == int(not retention_pressure)++ native = await harness.restart()+ agent = _agent(marker)+ assert await agent._start_or_resume_thread(native, request, developer_instructions=changed) == thread_id+ text = await turn(changed)+ assert text.count(baseline) == 1 # Cold configuration does not rewrite restored history.+ assert text.count(snapshot) == int(not retention_pressure)++ await native.send_request("thread/compact/start", {"threadId": thread_id})+ await harness.finish_turn()+ text = await turn(changed)+ assert baseline not in text+ assert text.count(configured) == 1+ assert text.count(changed) == 1 + int(not retention_pressure)+ assert text.count(snapshot) == int(not retention_pressure)+++async def test_native_fork_receives_target_prompt_before_and_after_compaction(tmp_path):+ source_prompt = "SOURCE_AGENT:原会话。"+ target_prompt = "TARGET_AGENT:新会话。"+ configured = "Independently configured native preference."+ async with _native_server(tmp_path, configured_instructions=configured) as harness:+ native = harness.native+ request = _request(tmp_path)+ marker = {}+ source = _agent(marker)+ source_id = await source._start_or_resume_thread(native, request, developer_instructions=source_prompt)+ await source._start_turn(native, request, source_id, developer_instructions=source_prompt)+ await harness.finish_turn()++ target_marker = dict(marker)+ target = _agent(target_marker)+ target_id = await target._fork_thread(+ native,+ request,+ {"source_session_id": "contract-session", "source_native_session_id": source_id},+ developer_instructions=target_prompt,+ )+ assert target_id != source_id+ assert target_marker["sha256"] == source._prompt_fingerprint(source_prompt)+ await target._start_turn(native, request, target_id, developer_instructions=target_prompt)+ await harness.finish_turn()+ text = "\n".join(_developer_texts(harness.requests[-1]))+ assert text.count(source_prompt) == 1+ assert text.count(CodexAgent._render_developer_prompt_snapshot(target_prompt)) == 1++ await native.send_request("thread/compact/start", {"threadId": target_id})+ await harness.finish_turn()+ await target._start_turn(native, request, target_id, developer_instructions=target_prompt)+ await harness.finish_turn()+ text = "\n".join(_developer_texts(harness.requests[-1]))+ assert source_prompt not in text+ assert text.count(configured) == 1+ assert text.count(target_prompt) == 2 # Native baseline plus retained overlay.