Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(prompt): place Agent instructions last and trim snapshot prose (#1973)

Call White85c0c655f0d5
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 10f6a88a2..c81380d93 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -1767,6 +1767,7 @@ class SessionHandler(BaseHandler):
system_prompt_injection = await asyncio.to_thread(
build_system_prompt_injection,
+ agent_instructions=base_prompt or "",
include_quick_replies=quick_replies_on and platform != "wechat",
memory_enabled=bool(getattr(getattr(self.config, "memory", None), "enabled", False)),
context=context,
@@ -1779,9 +1780,7 @@ class SessionHandler(BaseHandler):
)
if base_prompt:
- from core.prompt_registry import render_prompt
-
- return render_prompt("agent-instructions", agent_instructions=base_prompt) + system_prompt_injection
+ return system_prompt_injection
return {
"type": "preset",
"preset": "claude_code",
diff --git a/core/prompt_registry.py b/core/prompt_registry.py
index 0e9526139..e90793b0f 100644
--- a/core/prompt_registry.py
+++ b/core/prompt_registry.py
@@ -74,7 +74,6 @@ class PromptModule:
# Change this only to deliberately change prompt order, never for a UI-only sort.
PROMPT_MODULES: tuple[PromptModule, ...] = (
PromptModule("runtime-snapshot-open", "Codex Runtime Snapshot Start", "runtime-snapshot-open.md", trailing_newlines=2),
- PromptModule("agent-instructions", "Agent Custom Instructions", "agent-instructions.md", trailing_newlines=2, placeholders=("agent_instructions",)),
PromptModule("base-capabilities-intro", "Base Capabilities Intro", "base-capabilities-intro.md", trailing_newlines=2),
PromptModule("agent-working-principles", "Agent Working Principles", "agent-working-principles.md", trailing_newlines=2),
PromptModule("session-start-prompt", "Session Start Prompt", "session-start.md", trailing_newlines=2, placeholders=("default_session_id",)),
@@ -95,6 +94,7 @@ PROMPT_MODULES: tuple[PromptModule, ...] = (
PromptModule("skills-catalog", "Available Skills", "skills-catalog.md", placeholders=("skill_rows",)),
PromptModule("skills-more-notice", "Skills Next Page", "skills-more.md", placeholders=("next_page",)),
PromptModule("session-title-prompt", "Session Title Prompt", "session-title.md", leading_newlines=1, trailing_newlines=1),
+ PromptModule("agent-instructions", "Agent Custom Instructions", "agent-instructions.md", leading_newlines=2, placeholders=("agent_instructions",)),
PromptModule("runtime-snapshot-close", "Codex Runtime Snapshot End", "runtime-snapshot-close.md", leading_newlines=1),
)
diff --git a/core/prompt_studio_catalog.py b/core/prompt_studio_catalog.py
index 551d4bdc6..7ee24f7a1 100644
--- a/core/prompt_studio_catalog.py
+++ b/core/prompt_studio_catalog.py
@@ -13,7 +13,7 @@ from markdown_it import MarkdownIt
from pydantic import TypeAdapter, ValidationError
from core.managed_skills import builtin_skills_source, parse_skill_file
-from core.prompt_registry import export_prompt_catalog, join_prompt_blocks, render_prompt_block, runtime_snapshot_blocks
+from core.prompt_registry import export_prompt_catalog, join_prompt_blocks, runtime_snapshot_blocks
PROMPT_STUDIO_CATALOG_SCHEMA = "avibe-prompt-studio-catalog/1"
@@ -197,7 +197,8 @@ def _render_options(raw: object) -> dict[str, Any]:
options: dict[str, Any] = {}
for name, value in raw.items():
field = f"options.{name}"
- if name not in parameters:
+ # Agent text has one JSON owner: the existing top-level field.
+ if name not in parameters or name == "agent_instructions":
raise PromptRenderInputError("unknownField", field=field)
if name == "context" and isinstance(value, dict):
unknown = set(value) - set(MessageContext.__dataclass_fields__)
@@ -238,9 +239,7 @@ def render_prompt_context(request: dict[str, Any]) -> dict[str, Any]:
raise PromptRenderInputError("invalidField", field="agent_instructions")
options = _render_options(request.get("options", {}))
options.setdefault("include_codex_generated_images", backend == "codex")
- blocks = build_system_prompt_blocks(**options)
- if agent_instructions:
- blocks.insert(0, render_prompt_block("agent-instructions", agent_instructions=agent_instructions))
+ blocks = build_system_prompt_blocks(agent_instructions=agent_instructions, **options)
if backend == "codex":
blocks = runtime_snapshot_blocks(blocks)
text = join_prompt_blocks(blocks)
diff --git a/core/prompts/agent-instructions.md b/core/prompts/agent-instructions.md
index f13588b8a..c8bd21246 100644
--- a/core/prompts/agent-instructions.md
+++ b/core/prompts/agent-instructions.md
@@ -1 +1,3 @@
+# Agent
+
{agent_instructions}
diff --git a/core/prompts/runtime-snapshot-open.md b/core/prompts/runtime-snapshot-open.md
index 442c9f51a..97ea538ab 100644
--- a/core/prompts/runtime-snapshot-open.md
+++ b/core/prompts/runtime-snapshot-open.md
@@ -1,2 +1 @@
<avibe_runtime_instructions>
-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.
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index 609f79dc7..d3b674aed 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -33,6 +33,8 @@ logger = logging.getLogger(__name__)
# must consume the same ordered rendered blocks; Studio never assembles prose.
# - The registry owns composition order. Keep static Skill usage guidance after
# the base capabilities and dynamic Skill rows near the end to protect caches.
+# - Agent-authored instructions are the final content block, after all Avibe
+# guidance and catalogs; backends must not prepend or append their own copy.
@dataclass(frozen=True)
@@ -191,6 +193,7 @@ def _context_block(
def build_system_prompt_blocks(
*,
+ agent_instructions: str = "",
include_quick_replies: bool = True,
include_codex_generated_images: bool = False,
include_context_guidance: bool = True,
@@ -263,6 +266,8 @@ def build_system_prompt_blocks(
platform = resolve_context_platform(context, fallback_platform=fallback_platform, default="<platform>")
if _is_web_platform(platform):
blocks.append(render_prompt_block("session-title-prompt"))
+ if agent_instructions:
+ blocks.append(render_prompt_block("agent-instructions", agent_instructions=agent_instructions))
return order_prompt_blocks(blocks)
diff --git a/docs/plans/codex-prompt-delivery.md b/docs/plans/codex-prompt-delivery.md
index c114d5a76..be57185cc 100644
--- a/docs/plans/codex-prompt-delivery.md
+++ b/docs/plans/codex-prompt-delivery.md
@@ -4,9 +4,9 @@
Avibe-owned instructions must enter model-visible developer messages independently
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
+context reconstruction. Changed prompts on loaded threads use a tagged injected
+snapshot without a replacement declaration. Tags delimit Avibe content; they do
+not guarantee rule revocation, 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.
@@ -26,18 +26,29 @@ 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 removed
-rules and capability, Agent, and Skill declarations must not remain active. User
-and project instructions are outside this replacement boundary.
+loaded threads. Each new message contains the current Avibe content between
+`<avibe_runtime_instructions>` tags, with no explanatory preamble. Prior messages
+remain in native history. Removing a rule or catalog entry from the new snapshot
+does not explicitly revoke its old occurrence; this is an intentional wording
+choice, not an implemented replacement API. No user or project history is rewritten.
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
+Fingerprints cover the rendered snapshot, including its envelope.
+Legacy raw-prompt hashes and earlier prose-bearing envelopes therefore migrate
+once through resume or fork, while
unchanged current snapshots remain deduplicated across restarts.
Model and reasoning overrides remain top-level turn parameters.
+All backends use the shared block builder to place Agent custom instructions
+after Avibe guidance, capabilities, Agent/Skill catalogs, and session-title rules.
+Only the Codex closing tag follows that final content block in a live overlay.
+The source registry, debug export, and Studio use this same order. Empty custom
+instructions add no block or separator; nonempty text is preserved verbatim after
+a top-level `# Agent` heading and its boundary newlines, so an unheaded custom
+prompt cannot inherit the preceding Avibe subsection. Other source blocks retain
+their bytes and relative order.
+
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
@@ -82,7 +93,7 @@ prompt composition are unchanged.
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
+## Earlier 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,
@@ -92,3 +103,8 @@ covered marker production, resume, fork, cached recovery, and the native consume
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.
+
+The September 10, 2026 owner-requested removal of the replacement declaration
+supersedes only that wording requirement. Rendered-byte fingerprints and
+at-most-once recovery remain necessary and unchanged. The new format applies on
+future delivery; previously stored snapshots are not edited or removed.
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index ac750bc69..f298fabff 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -27,7 +27,7 @@ from core.managed_skills import (
)
from core.native_dispatch_phase import mark_backend_dispatch_attempted
from core.processing_indicator import STOPPED_REACTION_EMOJI
-from core.prompt_registry import prompt_text, render_prompt
+from core.prompt_registry import prompt_text
from core.services.agent_steering import (
ActiveSteerTarget,
SteerOutcome,
@@ -2595,39 +2595,34 @@ class CodexAgent(BaseAgent):
or self.controller.config.platform
)
- instruction_parts: list[str] = []
- if agent_instructions:
- instruction_parts.append(render_prompt("agent-instructions", agent_instructions=agent_instructions))
-
# Resolve admission once: it associates or clears this turn's Memory CLI
# session scope as a side effect, so a second call per turn would repeat
# that write.
configure_memory_cli_access(self.controller, request.context)
skill_catalog_sink: list[dict] = []
- instruction_parts.append(
- await asyncio.to_thread(
- build_system_prompt_injection,
- include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)
- and platform != "wechat",
- include_codex_generated_images=True,
- memory_enabled=bool(
- getattr(getattr(self.controller.config, "memory", None), "enabled", False)
- ),
- context=request.context,
- fallback_platform=platform,
- enabled_agents=get_enabled_agents_for_prompt(self.controller),
- skills_cwd=getattr(request, "working_path", None),
- skills_project_base=managed_skill_project_base(request.context),
- skills_claude_cli_path=managed_skill_claude_cli_path(
- getattr(getattr(self, "controller", None), "config", None)
- ),
- skill_catalog_sink=skill_catalog_sink,
- )
+ instructions = await asyncio.to_thread(
+ build_system_prompt_injection,
+ agent_instructions=agent_instructions or "",
+ include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)
+ and platform != "wechat",
+ include_codex_generated_images=True,
+ memory_enabled=bool(
+ getattr(getattr(self.controller.config, "memory", None), "enabled", False)
+ ),
+ context=request.context,
+ fallback_platform=platform,
+ enabled_agents=get_enabled_agents_for_prompt(self.controller),
+ skills_cwd=getattr(request, "working_path", None),
+ skills_project_base=managed_skill_project_base(request.context),
+ skills_claude_cli_path=managed_skill_claude_cli_path(
+ getattr(getattr(self, "controller", None), "config", None)
+ ),
+ skill_catalog_sink=skill_catalog_sink,
)
request.skill_catalog_observation = skill_catalog_sink[0] if skill_catalog_sink else None
- return "".join(part for part in instruction_parts if part) or None
+ return instructions or None
async def _inject_forked_session_correction(
self,
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index d0d4fccde..166528a2a 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -1563,6 +1563,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
skill_catalog_sink: list[dict] = []
system_prompt_injection = await asyncio.to_thread(
build_system_prompt_injection,
+ agent_instructions=request.vibe_agent_system_prompt or "",
include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)
and platform != "wechat",
memory_enabled=bool(
@@ -1578,13 +1579,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
),
skill_catalog_sink=skill_catalog_sink,
)
- if request.vibe_agent_system_prompt:
- from core.prompt_registry import render_prompt
-
- system_prompt_injection = render_prompt(
- "agent-instructions", agent_instructions=request.vibe_agent_system_prompt,
- ) + system_prompt_injection
-
raw_settings_key = _raw_settings_key_from_session_key(request.session_key)
platform_payload = request.context.platform_specific or {}
logical_turn_id = str(platform_payload.get("turn_token") or "").strip()
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index b83381168..91bde8a53 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -679,6 +679,8 @@ def test_session_handler_preserves_passed_agent_system_prompt(monkeypatch, tmp_p
prompt = prompt_value["append"] if isinstance(prompt_value, dict) else prompt_value
assert captured["connected"] is True
assert "Use the release-reviewer Vibe Agent policy." in prompt
+ assert prompt.endswith("\n\nUse the release-reviewer Vibe Agent policy.")
+ assert prompt.count("Use the release-reviewer Vibe Agent policy.") == 1
def test_session_handler_includes_show_pages_despite_legacy_opt_out(
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 3b3b7d832..f294a235f 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -1963,6 +1963,8 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
load_subagent.assert_called_once_with("reviewer", project_root=Path("/tmp/work"))
transport.send_request.assert_not_awaited()
self.assertIn("Focus on regressions.", developer_instructions)
+ self.assertTrue(developer_instructions.endswith("\n\nFocus on regressions."))
+ self.assertEqual(developer_instructions.count("Focus on regressions."), 1)
self.assertIn("# Avibe", developer_instructions)
self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)
self.assertNotIn("## Quick-reply buttons", developer_instructions)
@@ -4826,10 +4828,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
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)
+ self.assertEqual(latest, "<avibe_runtime_instructions>\n\nprompt two\n</avibe_runtime_instructions>")
async def test_start_turn_does_not_reinject_when_explicit_model_reset_is_unsupported(self):
agent = object.__new__(CodexAgent)
@@ -6036,6 +6035,32 @@ class CodexPromptSnapshotRecoveryTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(self.marker["strategy"], "fallback")
self.assertEqual(self.marker["sha256"], CodexAgent._prompt_fingerprint("stable prompt"))
+ async def test_previous_envelope_migrates_once_without_changing_prompt_body(self):
+ agent = self._setup("fallback")
+ old_snapshot = (
+ "<avibe_runtime_instructions>\n"
+ "Previous snapshot replacement declaration.\n\n"
+ "stable prompt\n</avibe_runtime_instructions>"
+ )
+ self.marker["sha256"] = hashlib.sha256(old_snapshot.encode()).hexdigest()
+ for restart in (False, False, True):
+ if restart:
+ agent = self._agent()
+ await agent._start_turn(
+ self.transport, self.request, "thread-1",
+ developer_instructions="stable prompt",
+ )
+ injections = [
+ entry for entry in self.transport.send_request.await_args_list
+ if entry.args[0] == "thread/inject_items"
+ ]
+ self.assertEqual(len(injections), 1)
+ self.assertEqual(
+ injections[0].args[1]["items"][0]["content"][0]["text"],
+ "<avibe_runtime_instructions>\n\nstable prompt\n</avibe_runtime_instructions>",
+ )
+ 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):
diff --git a/tests/test_codex_prompt_delivery_contract.py b/tests/test_codex_prompt_delivery_contract.py
index a6e6f7d63..f5fffd0d6 100644
--- a/tests/test_codex_prompt_delivery_contract.py
+++ b/tests/test_codex_prompt_delivery_contract.py
@@ -20,6 +20,7 @@ import pytest
from modules.agents.codex.agent import CodexAgent
from modules.agents.codex.transport import CodexTransport
+from modules.im import MessageContext
BINARY = os.environ.get("CODEX_PROMPT_CONTRACT_BINARY")
@@ -227,7 +228,47 @@ def _request(tmp_path):
@pytest.mark.asyncio
[email protected]("legacy", [None, "collaboration", "fallback"])
+async def test_production_agent_instructions_are_last_in_native_baseline_and_overlay(tmp_path, monkeypatch):
+ monkeypatch.setattr("core.managed_skills.resolve_skills", lambda *_args, **_kwargs: [])
+ async with _native_server(tmp_path) as harness:
+ agent = _agent({})
+ agent.controller.config = SimpleNamespace(platform="avibe", reply_enhancements=True)
+ request = _request(tmp_path)
+ request.context = MessageContext(
+ user_id="reviewer", channel_id="review", platform="avibe",
+ platform_specific={"agent_session_id": "contract-session"},
+ )
+ custom = "Custom Agent:保留 {instructions}。"
+ agent._resolve_codex_agent_settings = Mock(return_value=(None, MODEL, "high", custom))
+ baseline = await agent._build_thread_developer_instructions(request)
+ assert baseline.startswith("# Avibe")
+ assert baseline.endswith("\n\n" + custom)
+ assert baseline.count(custom) == 1
+ assert "## Session Title" in baseline
+ thread_id = await agent._start_or_resume_thread(
+ harness.native, request, developer_instructions=baseline,
+ )
+ await agent._start_turn(harness.native, request, thread_id, developer_instructions=baseline)
+ await harness.finish_turn()
+ native_text = "\n".join(_developer_texts(harness.requests[-1]))
+ assert native_text.count(baseline) == 1
+ assert "<avibe_runtime_instructions>" not in native_text
+
+ updated_custom = "Updated Agent:保留 {new}。"
+ agent._resolve_codex_agent_settings.return_value = (None, MODEL, "high", updated_custom)
+ updated = await agent._build_thread_developer_instructions(request)
+ assert updated == baseline.removesuffix(custom) + updated_custom
+ for _ in range(2):
+ await agent._start_turn(harness.native, request, thread_id, developer_instructions=updated)
+ await harness.finish_turn()
+ text = "\n".join(_developer_texts(harness.requests[-1]))
+ snapshot = "<avibe_runtime_instructions>\n\n" + updated + "\n</avibe_runtime_instructions>"
+ assert text.count(snapshot) == 1
+ assert text.count(baseline) == 1 # Delivery is not destructive history replacement.
+
+
[email protected]("legacy", [None, "collaboration", "fallback", "snapshot"])
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_turn
@@ -260,6 +301,20 @@ async def test_native_model_receives_injected_prompt_once_across_turns_and_resta
],
})
marker.update(thread_id=thread_id, strategy="fallback", sha256=hashlib.sha256(PROMPT.encode()).hexdigest())
+ elif legacy == "snapshot":
+ previous = (
+ "<avibe_runtime_instructions>\n"
+ "Previous snapshot replacement declaration.\n\n"
+ + PROMPT + "\n</avibe_runtime_instructions>"
+ )
+ await native.send_request("thread/inject_items", {
+ "threadId": thread_id,
+ "items": [{
+ "type": "message", "role": "developer",
+ "content": [{"type": "input_text", "text": previous}],
+ }],
+ })
+ marker.update(thread_id=thread_id, strategy="fallback", sha256=hashlib.sha256(previous.encode()).hexdigest())
request = _request(tmp_path)
agent = _agent(marker)
@@ -277,16 +332,15 @@ async def test_native_model_receives_injected_prompt_once_across_turns_and_resta
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.
+ # The new snapshot contains only current source content. Old messages
+ # remain in native history; tags alone do not promise rule revocation.
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
+ assert changed_snapshot == "<avibe_runtime_instructions>\n\n" + changed + "\n</avibe_runtime_instructions>"
await native.send_request("thread/compact/start", {"threadId": thread_id})
await finish_turn()
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 260ee0f2f..6288d21b9 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -836,7 +836,11 @@ def test_opencode_restored_ack_preserves_wechat_typing_context():
assert wechat.sent == [("clear_typing", "wechat", "user-1", "ctx-1")]
-def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch):
[email protected]("custom_prompt", ["", "Custom Agent:保留 {text}。"])
+def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, custom_prompt):
+ from core.system_prompt_injection import build_system_prompt_injection
+
+ monkeypatch.setattr("core.managed_skills.resolve_skills", lambda *_args, **_kwargs: [])
snapshot_id = "f" * 64
snapshot_root = f"/old-avibe-home/builtin-skills/{snapshot_id}"
monkeypatch.setenv("AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID", snapshot_id)
@@ -855,7 +859,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch):
def build_prompt(**kwargs):
prompt_skill_cwds.append(kwargs.get("skills_cwd"))
prompt_memory_modes.append(kwargs.get("memory_enabled"))
- return "system prompt"
+ return build_system_prompt_injection(**kwargs)
monkeypatch.setattr(
"modules.agents.opencode.agent.build_system_prompt_injection",
@@ -1010,12 +1014,17 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch):
base_session_id="base",
composite_session_id="base:/tmp/work",
session_key="avibe::c",
+ vibe_agent_system_prompt=custom_prompt,
)
await agent._process_message(request)
asyncio.run(_run())
assert calls
+ assert calls[0]["system"].startswith("# Avibe")
+ if custom_prompt:
+ assert calls[0]["system"].endswith("\n\n" + custom_prompt)
+ assert calls[0]["system"].count(custom_prompt) == 1
assert calls[0]["tools"] == {"question": False, "skill": False}
assert calls[0]["model"] == {"providerID": "openai", "modelID": "gpt-5.4"}
assert calls[0]["reasoning_effort"] == "high"
diff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.py
index eb031e630..985927e29 100644
--- a/tests/test_prompt_render_export.py
+++ b/tests/test_prompt_render_export.py
@@ -68,7 +68,9 @@ def test_export_reconstructs_production_text_with_source_for_every_block(monkeyp
result = render_prompt_context(request)
options = dict(request["options"])
options["context"] = MessageContext(**options["context"])
- production = request["agent_instructions"] + "\n\n" + build_system_prompt_injection(**options)
+ common = build_system_prompt_injection(**options)
+ production = build_system_prompt_injection(agent_instructions=request["agent_instructions"], **options)
+ assert production == common + "\n\n# Agent\n\n" + request["agent_instructions"]
if backend == "codex":
production = CodexAgent._render_developer_prompt_snapshot(production)
@@ -81,6 +83,7 @@ def test_export_reconstructs_production_text_with_source_for_every_block(monkeyp
catalog = {module.id: module for module in PROMPT_MODULES}
ids = [block["id"] for block in result["blocks"]]
assert ids == [module_id for module_id in catalog if module_id in ids]
+ assert ids[-2 if backend == "codex" else -1] == "agent-instructions"
for block in result["blocks"]:
assert block["source_path"] == catalog[block["id"]].source_path
assert result == render_prompt_context(request)
@@ -95,6 +98,40 @@ def test_export_reconstructs_production_text_with_source_for_every_block(monkeyp
assert ("preferences.md" in production) != memory
[email protected]("backend", ["claude", "codex", "opencode"])
[email protected]("custom", ["", "中文 {verbatim}\n\nKeep my spacing.\n"])
+def test_custom_instructions_only_change_the_final_content_block(monkeypatch, backend, custom):
+ _environment(monkeypatch)
+ request = _inputs(backend)
+ request["agent_instructions"] = ""
+ common = render_prompt_context(request)
+ request["agent_instructions"] = custom
+ rendered = render_prompt_context(request)
+ custom_blocks = [block for block in rendered["blocks"] if block["id"] == "agent-instructions"]
+ assert len(custom_blocks) == bool(custom)
+ assert [block for block in rendered["blocks"] if block["id"] != "agent-instructions"] == common["blocks"]
+ if custom:
+ assert custom_blocks[0]["text"] == "\n\n# Agent\n\n" + custom
+ tokens = MarkdownIt().parse(rendered["text"])
+ headings = [
+ (token.tag, tokens[index + 1].content)
+ for index, token in enumerate(tokens) if token.type == "heading_open"
+ ]
+ assert headings[-1] == ("h1", "Agent")
+ catalog = export_prompt_studio_catalog()["documents"][0]["blocks"]
+ assert [block["id"] for block in catalog][-2:] == [
+ "runtime-agent-instructions", "runtime-runtime-snapshot-close",
+ ]
+
+
+def test_runtime_snapshot_has_only_tags_and_verbatim_content():
+ prompt = "User-authored 内容 {unchanged}\n"
+ assert prompt_text("runtime-snapshot-open") == "<avibe_runtime_instructions>\n\n"
+ assert CodexAgent._render_developer_prompt_snapshot(prompt) == (
+ "<avibe_runtime_instructions>\n\n" + prompt + "\n</avibe_runtime_instructions>"
+ )
+
+
@pytest.mark.parametrize("backend,memory,history,skill_mode", itertools.product(
("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"),
("empty", "manual", "single", "pages"),
@@ -287,6 +324,7 @@ def test_debug_cli_rejects_invalid_context_without_partial_json(tmp_path, capsys
({"context": {"user_id": "u"}}, "options.context.channel_id", "invalidField"),
({"memory_enabled": "false"}, "options.memory_enabled", "invalidField"),
({"include_show_pages": False}, "options.include_show_pages", "unknownField"),
+ ({"agent_instructions": "second owner"}, "options.agent_instructions", "unknownField"),
({"enabled_agents": 123}, "options.enabled_agents", "invalidField"),
({"unknown": True}, "options.unknown", "unknownField"),
])
@@ -384,12 +422,9 @@ def test_cli_localizes_invalid_context_files(monkeypatch, tmp_path, capsys, lang
assert output.err == cli.i18n_t("debug.cli.error.promptExport", language, error=error) + "\n"
-def test_companion_principles_and_history_move_preserve_all_other_injection_bytes(monkeypatch):
+def test_agent_tail_and_snapshot_cleanup_preserve_all_other_injection_bytes(monkeypatch):
outputs = []
- changed = {
- "agent-working-principles", "show-pages-prompt",
- "show-history-heading", "show-history-managed", "show-history-self-managed",
- }
+ changed = {"runtime-snapshot-open", "agent-instructions"}
for backend, memory, history, skill_mode in itertools.product(
("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),
):
@@ -397,6 +432,6 @@ def test_companion_principles_and_history_move_preserve_all_other_injection_byte
blocks = render_prompt_context(_inputs(backend, memory, history, skill_mode))["blocks"]
outputs.append("".join(block["text"] for block in blocks if block["id"] not in changed))
digest = hashlib.sha256(json.dumps(outputs, ensure_ascii=False).encode()).hexdigest()
- # Captured independently from 627ed97aebe26f4cc01cca3ffe159433d721ebdf,
- # omitting only this change's approved principles, routing, and history blocks.
- assert digest == "6dae9db6263a2dd4aec5e6be5b545ea5ed3daeb7140a4f228dc749f8247b3915"
+ # Captured independently from 03e42c205f3da668c3ef8580d68d6cead2a00410,
+ # omitting only the approved snapshot preamble and relocated Agent block.
+ assert digest == "8a6403a158b7fba7d0164ae40ceac7d1945935e9612d79b5588de4ef9d1e0dfe"