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): share production order with Studio (#1918)

Call Whiteaded5bb77736
diff --git a/core/managed_skills.py b/core/managed_skills.py
index 75bbd21c6..f5d6a5ea5 100644
--- a/core/managed_skills.py
+++ b/core/managed_skills.py
@@ -1177,7 +1177,7 @@ def render_skill_catalog_blocks(skills: Sequence[ManagedSkill]) -> list[Rendered
if any(skill.disable_model_invocation for skill in skills):
return [render_prompt_block("skills-manual-prompt")]
return []
- blocks = [render_prompt_block("skills-prompt")]
+ blocks = [render_prompt_block("skills-prompt"), render_prompt_block("skills-catalog-heading")]
if next_page is not None:
blocks.append(render_prompt_block("skills-pagination-prompt"))
blocks.append(render_prompt_block("skills-catalog", skill_rows=rows))
diff --git a/core/prompt_registry.py b/core/prompt_registry.py
index 80382371c..646e5849c 100644
--- a/core/prompt_registry.py
+++ b/core/prompt_registry.py
@@ -69,37 +69,40 @@ class PromptModule:
return {**stable, "order": order, "revision": revision}
-# Tuple order is the public catalog order. It changes only when the authored
-# prompt structure changes, never because filesystem enumeration changed.
+# One composition order for production, debug export, and Studio. Optional
+# branches occupy their real insertion point; omitted blocks leave no placeholder.
+# 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",)),
+ PromptModule("forked-session-prompt", "Forked Session Prompt", "forked-session.md", trailing_newlines=2, placeholders=("source_session_id", "default_session_id")),
PromptModule("base-capabilities-body", "Base Capabilities Body", "base-capabilities.md", trailing_newlines=1),
+ PromptModule("skills-prompt", "Skills Usage", "skills.md", leading_newlines=2, trailing_newlines=2),
PromptModule("codex-generated-images", "Codex-generated images", "codex-generated-images.md", leading_newlines=1, trailing_newlines=1, placeholders=("example_uri",)),
PromptModule("show-pages-prompt", "Show Pages Prompt", "show-pages.md", leading_newlines=1, trailing_newlines=1),
+ PromptModule("show-history-heading", "Show History Heading", "show-history-heading.md", leading_newlines=1, trailing_newlines=1),
+ PromptModule("show-history-managed", "Show History: Managed Workspace", "show-history-managed.md"),
+ PromptModule("show-history-self-managed", "Show History: User Repository", "show-history-self-managed.md"),
+ PromptModule("quick-replies-prompt", "Quick Replies Prompt", "quick-replies.md", leading_newlines=1, trailing_newlines=1),
PromptModule("vault-routing-prompt", "Vault Routing Prompt", "vault.md", leading_newlines=1, trailing_newlines=1),
PromptModule("harness-routing-prompt", "Harness Routing Prompt", "harness.md", leading_newlines=1, trailing_newlines=1),
PromptModule("harness-agents-prompt", "Harness Agents Prompt", "harness-agents.md", placeholders=("enabled_agents_rows",)),
- PromptModule("session-start-prompt", "Session Start Prompt", "session-start.md", trailing_newlines=2, placeholders=("default_session_id",)),
- PromptModule("forked-session-prompt", "Forked Session Prompt", "forked-session.md", trailing_newlines=2, placeholders=("source_session_id", "default_session_id")),
- PromptModule("quick-replies-prompt", "Quick Replies Prompt", "quick-replies.md", leading_newlines=1, trailing_newlines=1),
PromptModule("preferences-context-prompt", "Preferences and Project Context Prompt", "preferences-context.md", leading_newlines=1, trailing_newlines=1, placeholders=("preferences_path", "platform")),
PromptModule("memory-context-prompt", "Memory and Project Context Prompt", "memory-context.md", leading_newlines=1, trailing_newlines=1),
- PromptModule("session-title-prompt", "Session Title Prompt", "session-title.md", leading_newlines=1, trailing_newlines=1),
- PromptModule("skills-prompt", "Skills Usage", "skills.md", leading_newlines=2, trailing_newlines=2),
PromptModule("skills-manual-prompt", "Explicit Skill Requests", "skills-manual.md", leading_newlines=2),
+ PromptModule("skills-catalog-heading", "Available Skills Heading", "skills-catalog-heading.md", leading_newlines=2, trailing_newlines=1),
PromptModule("skills-pagination-prompt", "Skills Discovery Pagination", "skills-pagination.md", trailing_newlines=1),
- PromptModule("skills-more-notice", "Skills Next Page", "skills-more.md", placeholders=("next_page",)),
PromptModule("skills-catalog", "Available Skills", "skills-catalog.md", placeholders=("skill_rows",)),
- PromptModule("show-history-managed", "Show History: Managed Workspace", "show-history-managed.md"),
- PromptModule("show-history-self-managed", "Show History: User Repository", "show-history-self-managed.md"),
- PromptModule("runtime-snapshot-open", "Codex Runtime Snapshot Start", "runtime-snapshot-open.md", trailing_newlines=2),
+ 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("runtime-snapshot-close", "Codex Runtime Snapshot End", "runtime-snapshot-close.md", leading_newlines=1),
- PromptModule("agent-instructions", "Agent Custom Instructions", "agent-instructions.md", trailing_newlines=2, placeholders=("agent_instructions",)),
- PromptModule("show-history-heading", "Show History Heading", "show-history-heading.md", leading_newlines=1, trailing_newlines=1),
)
_MODULES_BY_ID = {module.id: module for module in PROMPT_MODULES}
+_MODULE_ORDER = {module.id: index for index, module in enumerate(PROMPT_MODULES)}
if len(_MODULES_BY_ID) != len(PROMPT_MODULES): # pragma: no cover - import-time invariant
raise RuntimeError("Avibe prompt module ids must be unique")
if len({module.filename for module in PROMPT_MODULES}) != len(PROMPT_MODULES): # pragma: no cover
@@ -152,6 +155,11 @@ def join_prompt_blocks(blocks: list[RenderedPromptBlock]) -> str:
return "".join(block.text for block in blocks)
+def order_prompt_blocks(blocks: list[RenderedPromptBlock]) -> list[RenderedPromptBlock]:
+ """Compose selected production blocks in the source catalog's single order."""
+ return sorted(blocks, key=lambda block: _MODULE_ORDER[block.module_id])
+
+
def runtime_snapshot_blocks(blocks: list[RenderedPromptBlock]) -> list[RenderedPromptBlock]:
return [render_prompt_block("runtime-snapshot-open"), *blocks, render_prompt_block("runtime-snapshot-close")]
diff --git a/core/prompts/codex-generated-images.md b/core/prompts/codex-generated-images.md
index 72c3b0467..b6f95ddef 100644
--- a/core/prompts/codex-generated-images.md
+++ b/core/prompts/codex-generated-images.md
@@ -1,2 +1,2 @@
-### Codex-generated images
+## Codex-generated images
If you generate an image with Codex, include it in the final reply with Markdown image syntax, using a real file URI under the local Codex generated_images directory, for example: `![generated image]({example_uri})`. Replace the example thread id and filename with the actual generated image path. Never emit variables, placeholder paths, or sandbox paths like `/mnt/data/...`; if you cannot determine the real path, leave the final reply empty.
diff --git a/core/prompts/skills-catalog-heading.md b/core/prompts/skills-catalog-heading.md
new file mode 100644
index 000000000..e8d98b4e2
--- /dev/null
+++ b/core/prompts/skills-catalog-heading.md
@@ -0,0 +1 @@
+## Available skills
diff --git a/core/prompts/skills-catalog.md b/core/prompts/skills-catalog.md
index a731c5624..9e7382a6f 100644
--- a/core/prompts/skills-catalog.md
+++ b/core/prompts/skills-catalog.md
@@ -1,2 +1 @@
-### Available skills
{skill_rows}
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index fa0ad7ffe..b8c91e3f8 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -11,7 +11,7 @@ from typing import Any, Iterable, Optional
from config import paths
from core.message_context import resolve_context_platform
-from core.prompt_registry import RenderedPromptBlock, join_prompt_blocks, render_prompt, render_prompt_block
+from core.prompt_registry import RenderedPromptBlock, join_prompt_blocks, order_prompt_blocks, render_prompt, render_prompt_block
from core.show_git import agent_contract_block
from modules.im import MessageContext
@@ -30,6 +30,8 @@ logger = logging.getLogger(__name__)
# capability details; never gate them on a backend, Skill, or Turn.
# - Author all injected prose in the registry. Production text and debug JSON
# 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.
@dataclass(frozen=True)
@@ -260,7 +262,7 @@ 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"))
- return blocks
+ return order_prompt_blocks(blocks)
def build_system_prompt_injection(**kwargs: Any) -> str:
diff --git a/docs/plans/prompt-studio.md b/docs/plans/prompt-studio.md
index 1c25319f0..d5bc7bae7 100644
--- a/docs/plans/prompt-studio.md
+++ b/docs/plans/prompt-studio.md
@@ -23,6 +23,18 @@ Git or choose a branch. A contributor reviews the branch they have checked out.
Catalog order and revisions are content-derived and deterministic; the export
contains no generation timestamp.
+The registry defines production composition order, and Studio preserves that
+order without a display-only sort. Each rendered prompt is an ordered subset of
+the complete source catalog, including backend wrappers and optional branches.
+Static Skills Usage follows Base Capabilities Body; dynamic Skill rows remain
+near the end so catalog edits preserve the earlier static prefix.
+Separated capabilities have independent level-two Markdown headings: Codex image
+guidance is no longer a subsection of Send files, and the Available skills heading
+precedes both discovery pagination guidance and rows. The heading has its own
+source module so pagination remains source-addressable without attaching to Memory
+or Preferences. These heading boundaries change with the deliberate usage move;
+all other prose and relative positions remain unchanged.
+
Completeness is defined by the production injection, not by a manually selected
set of files. All authored prose, including Skill invocation/pagination rules,
Show history contracts, and Codex snapshot boundaries, belongs in the registry.
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 5099ff4e9..00dcc2309 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -1961,7 +1961,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
transport.send_request.assert_not_awaited()
self.assertIn("## Send files", developer_instructions)
- self.assertIn("### Codex-generated images", developer_instructions)
+ self.assertIn("## Codex-generated images", developer_instructions)
self.assertIn("If you generate an image with Codex", developer_instructions)
self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)
self.assertIn(
diff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.py
index a5586212c..453b2aa59 100644
--- a/tests/test_prompt_render_export.py
+++ b/tests/test_prompt_render_export.py
@@ -5,9 +5,11 @@ import itertools
import json
import subprocess
import sys
+from dataclasses import replace
from pathlib import Path
import pytest
+from markdown_it import MarkdownIt
from config import paths
from core import managed_skills, show_git
@@ -48,6 +50,8 @@ def _environment(monkeypatch, history="managed", skill_mode="pages"):
monkeypatch.setattr(show_git, "show_git_checkpointing_active", lambda: history != "off")
monkeypatch.setattr(show_git, "_workspace_is_self_managed", lambda _: history == "self-managed")
names = [f"skill-{index:02}" for index in range(26)] + ["use-avibe-vault"]
+ if skill_mode == "single":
+ names = names[:1]
skills = [
ManagedSkill(name, f"Description {name}", Path("/fixture") / name, (0,), disable_model_invocation=skill_mode == "manual")
for name in names
@@ -56,7 +60,7 @@ def _environment(monkeypatch, history="managed", skill_mode="pages"):
@pytest.mark.parametrize("backend,memory,history,skill_mode", itertools.product(
- ("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),
+ ("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"), ("empty", "manual", "single", "pages"),
))
def test_export_reconstructs_production_text_with_source_for_every_block(monkeypatch, backend, memory, history, skill_mode):
_environment(monkeypatch, history, skill_mode)
@@ -75,18 +79,59 @@ def test_export_reconstructs_production_text_with_source_for_every_block(monkeyp
assert production.index(principles) < production.index(prompt_text("base-capabilities-body"))
assert [block["text"] for block in result["blocks"] if block["id"] == "agent-working-principles"] == [principles]
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]
for block in result["blocks"]:
assert block["source_path"] == catalog[block["id"]].source_path
assert result == render_prompt_context(request)
assert request["options"]["context"]["platform"] == "avibe"
- if skill_mode == "pages":
+ if skill_mode in {"single", "pages"}:
+ assert ids[ids.index("base-capabilities-body") + 1] == "skills-prompt"
+ assert production.count(prompt_text("skills-prompt")) == 1
assert "vibe skill load -- <name>" in production
- assert "vibe skill list --page 2" in production
+ assert ("vibe skill list --page 2" in production) == (skill_mode == "pages")
assert "- skill-00: Description skill-00" in production
assert ("## Personal Memory" in production) == memory
assert ("preferences.md" in production) != memory
[email protected]("backend,memory,history,skill_mode", itertools.product(
+ ("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"),
+ ("empty", "manual", "single", "pages"),
+))
+def test_separated_capabilities_keep_independent_markdown_sections(monkeypatch, backend, memory, history, skill_mode):
+ _environment(monkeypatch, history, skill_mode)
+ rendered = render_prompt_context(_inputs(backend, memory, history, skill_mode))
+ parser = MarkdownIt()
+ tokens = parser.parse(rendered["text"])
+ section = None
+ sections = {}
+ for index, token in enumerate(tokens):
+ if token.type == "heading_open" and token.tag == "h2":
+ section = tokens[index + 1].content
+ sections[section] = []
+ elif token.type == "inline" and tokens[index - 1].type != "heading_open" and section:
+ sections[section].extend(token.content.splitlines())
+ expected_sections = {
+ "skills-prompt": "Skills",
+ "skills-manual-prompt": "Skills",
+ "skills-pagination-prompt": "Available skills",
+ "skills-catalog": "Available skills",
+ "skills-more-notice": "Available skills",
+ "codex-generated-images": "Codex-generated images",
+ }
+ for block in rendered["blocks"]:
+ if block["id"] not in expected_sections:
+ continue
+ members = sections[expected_sections[block["id"]]]
+ block_tokens = parser.parse(block["text"])
+ for index, token in enumerate(block_tokens):
+ if token.type == "inline" and (index == 0 or block_tokens[index - 1].type != "heading_open"):
+ assert all(line in members for line in token.content.splitlines()), block["id"]
+ assert ("Available skills" in sections) == (skill_mode in {"single", "pages"})
+ assert ("Codex-generated images" in sections) == (backend == "codex")
+
+
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
def test_working_principles_remain_without_session_skills_or_optional_capabilities(backend):
request = {
@@ -128,6 +173,7 @@ def test_history_and_pagination_keep_their_own_source_provenance(monkeypatch, hi
assert blocks["show-history-heading"]["text"] == prompt_text("show-history-heading")
assert "History contract:" not in blocks[f"show-history-{history}"]["text"]
rows = "\n".join(f"- skill-{index:02}: Description skill-{index:02}" for index in range(25))
+ assert blocks["skills-catalog-heading"]["text"] == "\n\n## Available skills\n"
assert blocks["skills-catalog"]["text"] == prompt_text("skills-catalog").format(skill_rows=rows)
assert blocks["skills-more-notice"] == {
"id": "skills-more-notice",
@@ -149,6 +195,23 @@ def test_rendered_revision_changes_only_when_rendered_bytes_change(monkeypatch):
assert render_prompt_context(request)["revision"] != before["revision"]
+def test_live_skill_changes_preserve_the_static_usage_prefix(monkeypatch):
+ _environment(monkeypatch)
+ request = _inputs()
+ before = render_prompt_context(request)
+ skills = managed_skills.resolve_skills("/fixture/project")
+ updated = [replace(skill, description="Updated description") for skill in reversed(skills)]
+ monkeypatch.setattr(managed_skills, "resolve_skills", lambda *_args, **_kwargs: updated)
+ after = render_prompt_context(request)
+ before_blocks = before["blocks"]
+ after_blocks = after["blocks"]
+ row_index = next(index for index, block in enumerate(before_blocks) if block["id"] == "skills-catalog")
+ assert after_blocks[:row_index] == before_blocks[:row_index]
+ assert after_blocks[row_index + 1:] == before_blocks[row_index + 1:]
+ assert after_blocks[row_index]["text"] != before_blocks[row_index]["text"]
+ assert after == render_prompt_context(request)
+
+
def test_debug_cli_exports_both_sources_and_production_blocks(monkeypatch, tmp_path, capsys):
_environment(monkeypatch)
source = export_prompt_studio_catalog()
@@ -316,11 +379,27 @@ def test_working_principles_addition_preserves_all_other_injection_bytes(monkeyp
("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),
):
_environment(monkeypatch, history, skill_mode)
- rendered = render_prompt_context(_inputs(backend, memory, history, skill_mode))["text"]
+ blocks = render_prompt_context(_inputs(backend, memory, history, skill_mode))["blocks"]
+ # Undo the usage move and independent heading boundaries, never prose changes.
+ blocks = [dict(block) for block in blocks if block["id"] != "skills-catalog-heading"]
+ for block in blocks:
+ if block["id"] == "skills-catalog":
+ block["text"] = "### Available skills\n" + block["text"]
+ elif block["id"] == "codex-generated-images":
+ block["text"] = block["text"].replace("\n## Codex-generated images\n", "\n### Codex-generated images\n", 1)
+ usage = next((block for block in blocks if block["id"] == "skills-prompt"), None)
+ if usage:
+ blocks.remove(usage)
+ catalog_start = next(
+ index for index, block in enumerate(blocks)
+ if block["id"] in {"skills-pagination-prompt", "skills-catalog"}
+ )
+ blocks.insert(catalog_start, usage)
+ rendered = "".join(block["text"] for block in blocks)
principles = prompt_text("agent-working-principles")
assert rendered.count(principles) == 1
outputs.append(rendered.replace(principles, "", 1))
digest = hashlib.sha256(json.dumps(outputs, ensure_ascii=False).encode()).hexdigest()
# Captured from the pre-migration renderer at 928924dd82bb48c7eea67ff06ddd844d442cb2a1.
- # Only the approved working-principles block may differ from that baseline.
+ # Only working principles, Skills Usage placement, and heading boundaries differ.
assert digest == "adbf608248e0b0a03d6646f57d31816cdb520c86113225e281b2aa007b100bc5"
diff --git a/tests/test_prompt_studio_catalog.py b/tests/test_prompt_studio_catalog.py
index a00ad3330..5a03e0c56 100644
--- a/tests/test_prompt_studio_catalog.py
+++ b/tests/test_prompt_studio_catalog.py
@@ -3,7 +3,14 @@ from __future__ import annotations
import json
from pathlib import Path
-from core.prompt_registry import PROMPT_MODULES, export_prompt_catalog, prompt_module, render_prompt
+from core.prompt_registry import (
+ PROMPT_MODULES,
+ RenderedPromptBlock,
+ export_prompt_catalog,
+ order_prompt_blocks,
+ prompt_module,
+ render_prompt,
+)
from core.prompt_studio_catalog import (
PROMPT_STUDIO_CATALOG_SCHEMA,
_markdown_blocks,
@@ -21,12 +28,10 @@ def test_every_prompt_markdown_file_has_one_stably_ordered_registry_entry() -> N
assert len(registered) == len(set(registered))
assert sorted(registered) == present
- assert [module.id for module in PROMPT_MODULES[:4]] == [
- "base-capabilities-intro",
- "agent-working-principles",
- "base-capabilities-body",
- "codex-generated-images",
- ]
+ ids = [module.id for module in PROMPT_MODULES]
+ assert ids[ids.index("base-capabilities-body") + 1] == "skills-prompt"
+ assert ids.index("skills-catalog") > ids.index("memory-context-prompt")
+ assert ids.index("skills-catalog-heading") < ids.index("skills-pagination-prompt") < ids.index("skills-catalog")
def test_prompt_rendering_replaces_only_declared_placeholders() -> None:
@@ -55,6 +60,15 @@ def test_prompt_catalog_export_is_deterministic_and_source_addressable() -> None
assert (ROOT / module["source_path"]).read_text(encoding="utf-8") == module["source"] + "\n"
+def test_production_order_follows_the_catalog_without_changing_block_bytes() -> None:
+ blocks = [RenderedPromptBlock(module.id, f"\n{module.id} exact bytes\n") for module in PROMPT_MODULES]
+ unordered = list(reversed(blocks))
+ ordered = order_prompt_blocks(unordered)
+ assert unordered == list(reversed(blocks))
+ assert ordered == blocks
+ assert all(actual is expected for actual, expected in zip(ordered, blocks))
+
+
def test_studio_catalog_contains_runtime_modules_and_builtin_skills() -> None:
catalog = export_prompt_studio_catalog()
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 3fb792be7..2ccf7cca3 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -150,7 +150,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
include_codex_generated_images=True,
)
- self.assertIn("### Codex-generated images", prompt)
+ self.assertIn("## Codex-generated images", prompt)
self.assertIn("If you generate an image with Codex", prompt)
self.assertIn("file:///Users/test/.codex/generated_images/thread-id/image-file.png", prompt)
self.assertIn("Never emit variables, placeholder paths, or sandbox paths like `/mnt/data/...`", prompt)