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): export the complete injection sources and rendering (#1880)

Call White81b12d64f158
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 5e90b0617..8dd4a4a91 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -1774,7 +1774,9 @@ class SessionHandler(BaseHandler):
)
if base_prompt:
- return f"{base_prompt}\n\n{system_prompt_injection}"
+ from core.prompt_registry import render_prompt
+
+ return render_prompt("agent-instructions", agent_instructions=base_prompt) + system_prompt_injection
return {
"type": "preset",
"preset": "claude_code",
diff --git a/core/managed_skills.py b/core/managed_skills.py
index 2092d3d9e..75bbd21c6 100644
--- a/core/managed_skills.py
+++ b/core/managed_skills.py
@@ -23,6 +23,7 @@ from typing import Any, Sequence
import yaml
from config import paths
+from core.prompt_registry import RenderedPromptBlock, join_prompt_blocks, render_prompt, render_prompt_block
try:
import tomllib
@@ -1153,46 +1154,37 @@ def render_skill_list(
more_notice: str | None = None,
) -> str:
entries, next_page = _page(skills, page)
- lines = [f"- {skill.name}: {skill.description}" for skill in entries]
+ lines = _skill_list_rows(entries)
if next_page is not None:
lines.append(
- more_notice or f"More skills are available. Run `vibe skill list --page {next_page}` to view more."
+ more_notice or render_prompt("skills-more-notice", next_page=next_page)
)
return "\n".join(lines)
+def _skill_list_rows(entries: Sequence[ManagedSkill]) -> list[str]:
+ return [f"- {skill.name}: {skill.description}" for skill in entries]
+
+
def render_skill_catalog_prompt(skills: Sequence[ManagedSkill]) -> str:
- rows = render_skill_list(skills, page=1)
+ return join_prompt_blocks(render_skill_catalog_blocks(skills))
+
+
+def render_skill_catalog_blocks(skills: Sequence[ManagedSkill]) -> list[RenderedPromptBlock]:
+ entries, next_page = _page(skills, 1)
+ rows = "\n".join(_skill_list_rows(entries))
if not rows:
if any(skill.disable_model_invocation for skill in skills):
- return (
- "\n\n## Skills\n\n"
- "If the user requests a Skill by exact name, ensure its content is in context: "
- "reuse an earlier successful load that remains in context; otherwise run "
- "`vibe skill load -- <name>` before proceeding.\n"
- "Otherwise, do not guess skill names."
- )
- return ""
- _, next_page = _page(skills, 1)
- later_page_guidance = (
- "Use `vibe skill list --page 2` only when more discovery is useful; "
- "ordinary tasks do not require scanning every page.\n"
- if next_page is not None
- else ""
- )
- return (
- "\n\n## Skills\n\n"
- "Skills provide specialized instructions and workflows for specific tasks.\n"
- "Before acting on a task covered by a listed Skill, ensure its content is in context: "
- "reuse an earlier successful load that remains in context; otherwise run "
- "`vibe skill load -- <name>`.\n"
- "If the user requests a Skill by exact name, apply this rule to that name.\n"
- "For non-explicit requests, only load Skill names listed here or returned by "
- "`vibe skill list`; do not guess names.\n\n"
- f"{later_page_guidance}"
- "### Available skills\n"
- f"{rows}"
- )
+ return [render_prompt_block("skills-manual-prompt")]
+ return []
+ blocks = [render_prompt_block("skills-prompt")]
+ if next_page is not None:
+ blocks.append(render_prompt_block("skills-pagination-prompt"))
+ blocks.append(render_prompt_block("skills-catalog", skill_rows=rows))
+ if next_page is not None:
+ notice = render_prompt_block("skills-more-notice", next_page=next_page)
+ blocks.append(RenderedPromptBlock(notice.module_id, "\n" + notice.text))
+ return blocks
def render_skill_content(skill: ManagedSkill) -> str:
diff --git a/core/prompt_registry.py b/core/prompt_registry.py
index a9cb10df4..32700e8f5 100644
--- a/core/prompt_registry.py
+++ b/core/prompt_registry.py
@@ -78,13 +78,24 @@ PROMPT_MODULES: tuple[PromptModule, ...] = (
PromptModule("show-pages-prompt", "Show Pages Prompt", "show-pages.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_table",)),
+ 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-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("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}
@@ -120,6 +131,30 @@ def render_prompt(module_id: str, **values: object) -> str:
return prompt_module(module_id).render(values)
+@dataclass(frozen=True)
+class RenderedPromptBlock:
+ """One production-rendered block, addressable by the source catalog."""
+
+ module_id: str
+ text: str
+
+ def export(self) -> dict[str, str]:
+ module = prompt_module(self.module_id)
+ return {"id": self.module_id, "source_path": module.source_path, "text": self.text}
+
+
+def render_prompt_block(module_id: str, **values: object) -> RenderedPromptBlock:
+ return RenderedPromptBlock(module_id, render_prompt(module_id, **values))
+
+
+def join_prompt_blocks(blocks: list[RenderedPromptBlock]) -> str:
+ return "".join(block.text for block in blocks)
+
+
+def runtime_snapshot_blocks(blocks: list[RenderedPromptBlock]) -> list[RenderedPromptBlock]:
+ return [render_prompt_block("runtime-snapshot-open"), *blocks, render_prompt_block("runtime-snapshot-close")]
+
+
def export_prompt_catalog() -> dict[str, Any]:
modules = [module.export(order=index) for index, module in enumerate(PROMPT_MODULES)]
catalog_revision = _stable_digest({"schema": PROMPT_CATALOG_SCHEMA, "modules": modules})
diff --git a/core/prompt_studio_catalog.py b/core/prompt_studio_catalog.py
index ea5057843..1dc3d6174 100644
--- a/core/prompt_studio_catalog.py
+++ b/core/prompt_studio_catalog.py
@@ -3,14 +3,16 @@
from __future__ import annotations
import hashlib
+import inspect
import json
import re
-from typing import Any
+from typing import Any, get_type_hints
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
+from core.prompt_registry import export_prompt_catalog, join_prompt_blocks, render_prompt_block, runtime_snapshot_blocks
PROMPT_STUDIO_CATALOG_SCHEMA = "avibe-prompt-studio-catalog/1"
@@ -142,7 +144,87 @@ def _skill_documents() -> list[dict[str, Any]]:
return documents
-def export_prompt_studio_catalog() -> dict[str, Any]:
+class PromptRenderInputError(ValueError):
+ """Localized at the CLI boundary; never expose validator exception prose."""
+
+ def __init__(self, key: str, *, field: str = ""):
+ super().__init__(key)
+ self.key = key
+ self.field = field
+
+
+def _render_options(raw: object) -> dict[str, Any]:
+ from core.system_prompt_injection import _coerce_agent_prompt_info, build_system_prompt_blocks
+ from modules.im import MessageContext
+
+ if not isinstance(raw, dict):
+ raise PromptRenderInputError("invalidField", field="options")
+ parameters = inspect.signature(build_system_prompt_blocks).parameters
+ types = get_type_hints(build_system_prompt_blocks)
+ # Python callers can supply domain objects and arbitrary iterables. JSON
+ # callers supply an array of named objects, never strings or object keys.
+ types["enabled_agents"] = list[dict[str, Any]] | None
+ options: dict[str, Any] = {}
+ for name, value in raw.items():
+ field = f"options.{name}"
+ if name not in parameters:
+ raise PromptRenderInputError("unknownField", field=field)
+ if name == "context" and isinstance(value, dict):
+ unknown = set(value) - set(MessageContext.__dataclass_fields__)
+ if unknown:
+ raise PromptRenderInputError("unknownField", field=f"{field}.{sorted(unknown)[0]}")
+ try:
+ # Validate from JSON so dataclasses and paths accept their JSON
+ # representation while scalars retain strict bool/string types.
+ options[name] = TypeAdapter(types[name]).validate_json(json.dumps(value), strict=True)
+ except ValidationError as exc:
+ location = ".".join(str(part) for part in exc.errors()[0]["loc"])
+ raise PromptRenderInputError("invalidField", field=f"{field}.{location}" if location else field) from exc
+ if name == "enabled_agents":
+ for index, agent in enumerate(options[name] or []):
+ try:
+ _coerce_agent_prompt_info(agent)
+ except ValueError as exc:
+ raise PromptRenderInputError("invalidField", field=f"{field}.{index}") from exc
+ return options
+
+
+def render_prompt_context(request: dict[str, Any]) -> dict[str, Any]:
+ """Render explicit builder inputs, not a guessed or recorded native session.
+
+ No backend is started and no Memory admission/configuration is performed.
+ Skill discovery, when requested through skills_cwd, uses the production
+ resolver and its ordinary built-in snapshot maintenance.
+ """
+ from core.system_prompt_injection import build_system_prompt_blocks
+
+ if not isinstance(request, dict) or set(request) - {"backend", "agent_instructions", "options"}:
+ raise PromptRenderInputError("invalidContext")
+ backend = request.get("backend")
+ if backend not in ("claude", "codex", "opencode"):
+ raise PromptRenderInputError("invalidBackend")
+ agent_instructions = request.get("agent_instructions", "")
+ if not isinstance(agent_instructions, str):
+ 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))
+ if backend == "codex":
+ blocks = runtime_snapshot_blocks(blocks)
+ text = join_prompt_blocks(blocks)
+ return {
+ "backend": backend,
+ "scope": "avibe-injection",
+ "context_source": "supplied",
+ "blocks": [block.export() for block in blocks],
+ "text": text,
+ "revision": _digest_text(text),
+ }
+
+
+def export_prompt_studio_catalog(*, render_context: dict[str, Any] | None = None) -> dict[str, Any]:
prompt_catalog = export_prompt_catalog()
prompt_blocks = []
for module in prompt_catalog["modules"]:
@@ -172,8 +254,11 @@ def export_prompt_studio_catalog() -> dict[str, Any]:
},
*_skill_documents(),
]
- return {
+ result = {
"schema": PROMPT_STUDIO_CATALOG_SCHEMA,
"catalog_revision": _stable_digest({"schema": PROMPT_STUDIO_CATALOG_SCHEMA, "documents": documents}),
"documents": documents,
}
+ if render_context is not None:
+ result["rendered"] = render_prompt_context(render_context)
+ return result
diff --git a/core/prompts/agent-instructions.md b/core/prompts/agent-instructions.md
new file mode 100644
index 000000000..f13588b8a
--- /dev/null
+++ b/core/prompts/agent-instructions.md
@@ -0,0 +1 @@
+{agent_instructions}
diff --git a/core/prompts/harness-agents.md b/core/prompts/harness-agents.md
index de436ec95..9e1b4198a 100644
--- a/core/prompts/harness-agents.md
+++ b/core/prompts/harness-agents.md
@@ -1,7 +1,9 @@
### Agents
The table below is generated from currently enabled Agents at prompt-injection time. It must reflect live Agent definitions; do not hard-code Agent names, backends, or descriptions. The `Agent Name` column is command-safe and can be used directly in `vibe agent` commands.
-{enabled_agents_table}
+| Agent Name | Backend | Agent Description |
+| --- | --- | --- |
+{enabled_agents_rows}
Rules:
- All Agents listed in the generated table are enabled. Use the `Agent Name` value exactly as listed in shell commands such as `vibe agent show <agent-name>` and `vibe agent run --agent <agent-name> ...`.
diff --git a/core/prompts/runtime-snapshot-close.md b/core/prompts/runtime-snapshot-close.md
new file mode 100644
index 000000000..ae7f12feb
--- /dev/null
+++ b/core/prompts/runtime-snapshot-close.md
@@ -0,0 +1 @@
+</avibe_runtime_instructions>
diff --git a/core/prompts/runtime-snapshot-open.md b/core/prompts/runtime-snapshot-open.md
new file mode 100644
index 000000000..442c9f51a
--- /dev/null
+++ b/core/prompts/runtime-snapshot-open.md
@@ -0,0 +1,2 @@
+<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/prompts/show-history-heading.md b/core/prompts/show-history-heading.md
new file mode 100644
index 000000000..f2e0e092f
--- /dev/null
+++ b/core/prompts/show-history-heading.md
@@ -0,0 +1 @@
+History contract:
diff --git a/core/prompts/show-history-managed.md b/core/prompts/show-history-managed.md
new file mode 100644
index 000000000..0c885d9cd
--- /dev/null
+++ b/core/prompts/show-history-managed.md
@@ -0,0 +1,5 @@
+History is saved automatically around each turn; do not manage versions yourself.
+Read freely: `git -C <workspace> status / log / diff / show`.
+Restore only via `git restore --source=<ref> -- <path>`; the turn-end checkpoint records it as a forward commit.
+Never move HEAD, switch branches, rewrite history, or run gc; if you do, the platform self-heals with the worktree as truth.
+Never add remotes, push, or publish the workspace anywhere unless the user explicitly asks.
diff --git a/core/prompts/show-history-self-managed.md b/core/prompts/show-history-self-managed.md
new file mode 100644
index 000000000..ed7662964
--- /dev/null
+++ b/core/prompts/show-history-self-managed.md
@@ -0,0 +1,3 @@
+Avibe's shadow history continues automatically in the background; you don't manage it.
+`git -C <workspace>` addresses the **user's repo**, not Avibe history: never commit, push, or publish on their behalf, and never use it for Avibe restore.
+Never locate or mutate Avibe's shadow gitdir on your own initiative. Only if the user explicitly asks to recover from Avibe history, use standard git with explicit `--git-dir` and `--work-tree` against the session's shadow gitdir for read or restore only; never commit to it.
diff --git a/core/prompts/skills-catalog.md b/core/prompts/skills-catalog.md
new file mode 100644
index 000000000..a731c5624
--- /dev/null
+++ b/core/prompts/skills-catalog.md
@@ -0,0 +1,2 @@
+### Available skills
+{skill_rows}
diff --git a/core/prompts/skills-manual.md b/core/prompts/skills-manual.md
new file mode 100644
index 000000000..1d7997b66
--- /dev/null
+++ b/core/prompts/skills-manual.md
@@ -0,0 +1,4 @@
+## Skills
+
+If the user requests a Skill by exact name, ensure its content is in context: reuse an earlier successful load that remains in context; otherwise run `vibe skill load -- <name>` before proceeding.
+Otherwise, do not guess skill names.
diff --git a/core/prompts/skills-more.md b/core/prompts/skills-more.md
new file mode 100644
index 000000000..129410623
--- /dev/null
+++ b/core/prompts/skills-more.md
@@ -0,0 +1 @@
+More skills are available. Run `vibe skill list --page {next_page}` to view more.
diff --git a/core/prompts/skills-pagination.md b/core/prompts/skills-pagination.md
new file mode 100644
index 000000000..f9375991c
--- /dev/null
+++ b/core/prompts/skills-pagination.md
@@ -0,0 +1 @@
+Use `vibe skill list --page 2` only when more discovery is useful; ordinary tasks do not require scanning every page.
diff --git a/core/prompts/skills.md b/core/prompts/skills.md
new file mode 100644
index 000000000..cff8488d9
--- /dev/null
+++ b/core/prompts/skills.md
@@ -0,0 +1,6 @@
+## Skills
+
+Skills provide specialized instructions and workflows for specific tasks.
+Before acting on a task covered by a listed Skill, ensure its content is in context: reuse an earlier successful load that remains in context; otherwise run `vibe skill load -- <name>`.
+If the user requests a Skill by exact name, apply this rule to that name.
+For non-explicit requests, only load Skill names listed here or returned by `vibe skill list`; do not guess names.
diff --git a/core/show_git.py b/core/show_git.py
index 0e46bf7dc..87054a9b0 100644
--- a/core/show_git.py
+++ b/core/show_git.py
@@ -16,6 +16,7 @@ from typing import Any
from config import paths
from core.git_binary import ResolvedGit, resolve_git
+from core.prompt_registry import RenderedPromptBlock, prompt_text
from vibe.message_types import input_author_type_pairs
logger = logging.getLogger(__name__)
@@ -71,18 +72,8 @@ _INPUT_TURN_MESSAGE_TYPES = tuple(
dict.fromkeys(message_type for _, message_type in input_author_type_pairs())
)
-SHOW_GIT_AGENT_CONTRACT = (
- "History is saved automatically around each turn; do not manage versions yourself.",
- "Read freely: `git -C <workspace> status / log / diff / show`.",
- "Restore only via `git restore --source=<ref> -- <path>`; the turn-end checkpoint records it as a forward commit.",
- "Never move HEAD, switch branches, rewrite history, or run gc; if you do, the platform self-heals with the worktree as truth.",
- "Never add remotes, push, or publish the workspace anywhere unless the user explicitly asks.",
-)
-SHOW_GIT_SELF_MANAGED_AGENT_CONTRACT = (
- "Avibe's shadow history continues automatically in the background; you don't manage it.",
- "`git -C <workspace>` addresses the **user's repo**, not Avibe history: never commit, push, or publish on their behalf, and never use it for Avibe restore.",
- "Never locate or mutate Avibe's shadow gitdir on your own initiative. Only if the user explicitly asks to recover from Avibe history, use standard git with explicit `--git-dir` and `--work-tree` against the session's shadow gitdir for read or restore only; never commit to it.",
-)
+SHOW_GIT_AGENT_CONTRACT = tuple(prompt_text("show-history-managed").splitlines())
+SHOW_GIT_SELF_MANAGED_AGENT_CONTRACT = tuple(prompt_text("show-history-self-managed").splitlines())
class ShowGitError(RuntimeError):
"""A platform Git operation failed."""
@@ -193,17 +184,33 @@ def format_agent_contract(
checkpointing_available: bool | None = None,
session_id: str | None = None,
) -> str:
+ block = agent_contract_block(
+ numbered=numbered, checkpointing_available=checkpointing_available, session_id=session_id,
+ )
+ return block.text if block else ""
+
+
+def agent_contract_block(
+ *,
+ numbered: bool = False,
+ checkpointing_available: bool | None = None,
+ session_id: str | None = None,
+) -> RenderedPromptBlock | None:
if checkpointing_available is None:
checkpointing_available = show_git_checkpointing_active()
if not checkpointing_available:
- return ""
+ return None
if session_id is not None and _workspace_is_self_managed(session_id):
lines = SHOW_GIT_SELF_MANAGED_AGENT_CONTRACT
+ module_id = "show-history-self-managed"
else:
lines = SHOW_GIT_AGENT_CONTRACT
+ module_id = "show-history-managed"
if numbered:
- return "\n".join(f"{index}. {line}" for index, line in enumerate(lines, start=1))
- return "\n".join(f"- {line}" for line in lines)
+ text = "\n".join(f"{index}. {line}" for index, line in enumerate(lines, start=1))
+ else:
+ text = "\n".join(f"- {line}" for line in lines)
+ return RenderedPromptBlock(module_id, text)
def _single_line(value: Any) -> str:
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index e9837a16a..04ed645a5 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -11,8 +11,8 @@ from typing import Any, Iterable, Optional
from config import paths
from core.message_context import resolve_context_platform
-from core.prompt_registry import prompt_text, render_prompt
-from core.show_git import format_agent_contract
+from core.prompt_registry import RenderedPromptBlock, join_prompt_blocks, render_prompt, render_prompt_block
+from core.show_git import agent_contract_block
from modules.im import MessageContext
logger = logging.getLogger(__name__)
@@ -26,6 +26,8 @@ logger = logging.getLogger(__name__)
# health. Runtime policy belongs in the enforcing layer, not in its description.
# - Keep every generated collection deterministic, including Agent and Skill order.
# - Required built-in Skill routing is unconditional; installation guarantees it.
+# - Author all injected prose in the registry. Production text and debug JSON
+# must consume the same ordered rendered blocks; Studio never assembles prose.
@dataclass(frozen=True)
@@ -35,36 +37,10 @@ class AgentPromptInfo:
backend: str = "unknown"
-_BASE_CAPABILITIES_INTRO = prompt_text("base-capabilities-intro")
-
-_BASE_CAPABILITIES_BODY = prompt_text("base-capabilities-body")
-
-_SHOW_PAGES_PROMPT = prompt_text("show-pages-prompt")
-
-_VAULT_ROUTING_PROMPT = prompt_text("vault-routing-prompt")
-
-_HARNESS_ROUTING_PROMPT = prompt_text("harness-routing-prompt")
-
-_HARNESS_AGENTS_PROMPT = prompt_text("harness-agents-prompt")
-
-_SESSION_START_PROMPT = prompt_text("session-start-prompt")
-
-_FORKED_SESSION_PROMPT = prompt_text("forked-session-prompt")
-
-
-def _build_codex_generated_images_prompt() -> str:
+def _codex_generated_images_block() -> RenderedPromptBlock:
codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex").expanduser().resolve()
example_uri = (codex_home / "generated_images" / "thread-id" / "image-file.png").as_uri()
- return render_prompt("codex-generated-images", example_uri=example_uri)
-
-
-_QUICK_REPLIES_PROMPT = prompt_text("quick-replies-prompt")
-
-_SESSION_TITLE_PROMPT = prompt_text("session-title-prompt")
-
-_PREFERENCES_CONTEXT_PROMPT = prompt_text("preferences-context-prompt")
-
-_MEMORY_CONTEXT_PROMPT = prompt_text("memory-context-prompt")
+ return render_prompt_block("codex-generated-images", example_uri=example_uri)
def _extract_default_session_id(context: MessageContext) -> str:
@@ -141,7 +117,7 @@ def _escape_markdown_table_cell(value: str) -> str:
return str(value).replace("\\", "\\\\").replace("|", "\\|").replace("\n", " ").strip()
-def _format_enabled_agents_table(enabled_agents: Optional[Iterable[Any]]) -> str:
+def _format_enabled_agents_rows(enabled_agents: Optional[Iterable[Any]]) -> str:
if enabled_agents is None:
return ""
@@ -155,7 +131,7 @@ def _format_enabled_agents_table(enabled_agents: Optional[Iterable[Any]]) -> str
if not rows:
return ""
- lines = ["| Agent Name | Backend | Agent Description |", "| --- | --- | --- |"]
+ lines = []
for agent in sorted(
rows,
key=lambda item: (
@@ -192,75 +168,23 @@ def get_enabled_agents_for_prompt(controller: Any) -> Optional[list[AgentPromptI
return rows
-def _build_session_start_prompt(context: MessageContext) -> str:
- default_session_id = _extract_default_session_id(context)
- prompt = render_prompt("session-start-prompt", default_session_id=default_session_id)
- fork_correction = build_forked_session_correction_prompt(context)
- if fork_correction:
- prompt += fork_correction
- return prompt
-
-
-def _build_harness_prompt(
- *,
- enabled_agents: Optional[Iterable[Any]] = None,
-) -> str:
- prompt = _HARNESS_ROUTING_PROMPT
- table = _format_enabled_agents_table(enabled_agents)
- if table:
- prompt += render_prompt("harness-agents-prompt", enabled_agents_table=table)
- return prompt
-
-
-def _build_show_pages_prompt(
- context: MessageContext,
-) -> str:
- default_session_id = _extract_default_session_id(context)
- prompt = _SHOW_PAGES_PROMPT
- history_contract = format_agent_contract(numbered=True, session_id=default_session_id)
- if history_contract:
- prompt += f"\nHistory contract:\n{history_contract}\n"
- return prompt
-
-
-def _build_vault_prompt(
- context: Optional[MessageContext],
- *,
- fallback_platform: Optional[str] = None,
-) -> str:
- del context, fallback_platform
- return _VAULT_ROUTING_PROMPT
-
-
-def _build_session_end_prompt(
- context: MessageContext,
- *,
- fallback_platform: Optional[str] = None,
-) -> str:
- prompt = ""
- platform = resolve_context_platform(context, fallback_platform=fallback_platform, default="<platform>")
- if _is_web_platform(platform):
- prompt += _SESSION_TITLE_PROMPT
- return prompt
-
-
-def _build_context_prompt(
+def _context_block(
context: Optional[MessageContext],
*,
fallback_platform: Optional[str] = None,
memory_enabled: bool = False,
-) -> str:
+) -> RenderedPromptBlock:
if memory_enabled:
- return _MEMORY_CONTEXT_PROMPT
+ return render_prompt_block("memory-context-prompt")
platform = resolve_context_platform(context, fallback_platform=fallback_platform, default="<platform>")
- return render_prompt(
+ return render_prompt_block(
"preferences-context-prompt",
preferences_path=f"`{paths.get_user_preferences_path()}`",
platform=platform,
)
-def build_system_prompt_injection(
+def build_system_prompt_blocks(
*,
include_quick_replies: bool = True,
include_show_pages: bool = True,
@@ -273,8 +197,8 @@ def build_system_prompt_injection(
skills_cwd: str | Path | None = None,
skills_project_base: str | Path | None = None,
skills_claude_cli_path: str | None = None,
-) -> str:
- """Build avibe system prompt additions for an agent backend."""
+) -> list[RenderedPromptBlock]:
+ """The production composition, also exported by the debug command."""
skills = None
if skills_cwd is not None:
@@ -293,32 +217,47 @@ def build_system_prompt_injection(
skill.name == "use-avibe-vault" for skill in advertisable_skills
)
- prompt = _BASE_CAPABILITIES_INTRO
+ blocks = [render_prompt_block("base-capabilities-intro")]
if context is not None:
- prompt += _build_session_start_prompt(context)
- prompt += _BASE_CAPABILITIES_BODY
+ blocks.append(render_prompt_block("session-start-prompt", default_session_id=_extract_default_session_id(context)))
+ correction = build_forked_session_correction_prompt(context)
+ if correction:
+ blocks.append(RenderedPromptBlock("forked-session-prompt", correction))
+ blocks.append(render_prompt_block("base-capabilities-body"))
if include_codex_generated_images:
- prompt += _build_codex_generated_images_prompt()
+ blocks.append(_codex_generated_images_block())
if include_show_pages and context is not None:
- prompt += _build_show_pages_prompt(context)
+ blocks.append(render_prompt_block("show-pages-prompt"))
+ history = agent_contract_block(numbered=True, session_id=_extract_default_session_id(context))
+ if history:
+ blocks.append(render_prompt_block("show-history-heading"))
+ blocks.append(RenderedPromptBlock(history.module_id, history.text + "\n"))
if include_quick_replies:
- prompt += _QUICK_REPLIES_PROMPT
+ blocks.append(render_prompt_block("quick-replies-prompt"))
if vault_skill_available:
- prompt += _build_vault_prompt(context, fallback_platform=fallback_platform)
+ blocks.append(render_prompt_block("vault-routing-prompt"))
if context is not None:
- prompt += _build_harness_prompt(
- enabled_agents=enabled_agents,
- )
+ blocks.append(render_prompt_block("harness-routing-prompt"))
+ agent_rows = _format_enabled_agents_rows(enabled_agents)
+ if agent_rows:
+ blocks.append(render_prompt_block("harness-agents-prompt", enabled_agents_rows=agent_rows))
if include_context_guidance:
- prompt += _build_context_prompt(
+ blocks.append(_context_block(
context,
fallback_platform=fallback_platform,
memory_enabled=memory_enabled,
- )
+ ))
if skills is not None:
- from core.managed_skills import render_skill_catalog_prompt
+ from core.managed_skills import render_skill_catalog_blocks
- prompt += render_skill_catalog_prompt(skills)
+ blocks.extend(render_skill_catalog_blocks(skills))
if context is not None:
- prompt += _build_session_end_prompt(context, fallback_platform=fallback_platform)
- return prompt
+ 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
+
+
+def build_system_prompt_injection(**kwargs: Any) -> str:
+ """Render the production blocks without changing their byte boundaries."""
+ return join_prompt_blocks(build_system_prompt_blocks(**kwargs))
diff --git a/docs/plans/prompt-studio.md b/docs/plans/prompt-studio.md
index 47c8747a4..1c25319f0 100644
--- a/docs/plans/prompt-studio.md
+++ b/docs/plans/prompt-studio.md
@@ -23,6 +23,61 @@ 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.
+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.
+Agent instructions and generated Skill/Agent catalogs have declared input slots;
+their machine/session-specific values are not alternative English sources.
+
+The default export is the complete **source catalog**, including mutually
+exclusive branches. It is not a rendered session prompt. To render explicit
+inputs, use the same command with `--context-file context.json`:
+
+```json
+{
+ "backend": "codex",
+ "agent_instructions": "Review changes carefully.",
+ "options": {
+ "context": {
+ "user_id": "reviewer",
+ "channel_id": "review",
+ "platform": "avibe",
+ "platform_specific": {"agent_session_id": "sesreview"}
+ },
+ "memory_enabled": true,
+ "skills_cwd": "/path/to/project",
+ "enabled_agents": [
+ {"name": "codex", "backend": "codex", "description": "Code review"}
+ ]
+ }
+}
+```
+
+`options` are the keyword inputs of `build_system_prompt_blocks`; omitted
+options use that builder's defaults. Image guidance defaults to Codex only.
+In JSON, `enabled_agents` is an array of Agent objects or `null`, not an arbitrary
+Python iterable. Each object must have a usable `name` or `normalized_name`;
+optional fields use the production defaults. An empty array, `null`, or omission
+renders no Agent table. Invalid input returns a localized error, not a rendering
+with silently discarded Agent rows.
+Callers reproducing a turn must supply its effective options (for example,
+quick replies disabled on WeChat), Agent instructions, and enabled Agent list;
+the command does not infer them from the Session ID. Normal path and Show
+history resolution still use the invoking environment. Providing `skills_cwd`
+uses production discovery, including ordinary built-in snapshot maintenance.
+
+The additive `rendered` field contains ordered, source-addressable `blocks`,
+their exact concatenated `text`, and its content-derived `revision`. This calls
+the same block builder used by all three production backends. Codex includes its
+snapshot envelope; native backend presets, project files, tool schemas and
+conversation history are outside this Avibe-injection scope. The export is a
+rendering of supplied inputs, not a claim to have captured a live model request.
+It starts no backend and does not grant Memory access or change configuration.
+
+Studio must consume this interface rather than select files or assemble prompt
+text itself. Source-document token estimates and rendered-injection token
+estimates are different measurements; never present the former as the latter.
+
## Runtime compatibility
Markdown files omit composition-only leading and trailing newlines. The registry
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 9b0a4087d..2c209e4b4 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -27,6 +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.services.agent_steering import (
ActiveSteerTarget,
SteerOutcome,
@@ -2510,7 +2511,7 @@ class CodexAgent(BaseAgent):
instruction_parts: list[str] = []
if agent_instructions:
- instruction_parts.append(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
@@ -2538,7 +2539,7 @@ class CodexAgent(BaseAgent):
)
)
- return "\n\n".join(part for part in instruction_parts if part) or None
+ return "".join(part for part in instruction_parts if part) or None
async def _inject_forked_session_correction(
self,
@@ -2794,16 +2795,9 @@ class CodexAgent(BaseAgent):
@staticmethod
def _render_developer_prompt_snapshot(developer_instructions: str) -> str:
return (
- "<avibe_runtime_instructions>\n"
- "This is the complete current Avibe runtime instruction snapshot. "
- "Only the most recent snapshot is active. It replaces all earlier "
- "Avibe-generated runtime prompt snapshots, including untagged versions. "
- "Rules and capability, Agent, or Skill catalog entries omitted from this "
- "snapshot no longer apply: do not carry them forward from earlier snapshots. "
- "This replacement does not revoke user or project instructions or erase "
- "conversation history.\n\n"
- f"{developer_instructions}\n"
- "</avibe_runtime_instructions>"
+ prompt_text("runtime-snapshot-open")
+ + developer_instructions
+ + prompt_text("runtime-snapshot-close")
)
async def _inject_thread_developer_instructions(
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index c5f83479c..7dc51d3e0 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -1573,7 +1573,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
),
)
if request.vibe_agent_system_prompt:
- system_prompt_injection = f"{request.vibe_agent_system_prompt}\n\n{system_prompt_injection}"
+ 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 {}
diff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.py
new file mode 100644
index 000000000..71ddc0daa
--- /dev/null
+++ b/tests/test_prompt_render_export.py
@@ -0,0 +1,296 @@
+from __future__ import annotations
+
+import hashlib
+import itertools
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from config import paths
+from core import managed_skills, show_git
+from core.managed_skills import ManagedSkill
+from core.prompt_registry import PROMPT_MODULES, prompt_text
+from core.prompt_studio_catalog import export_prompt_studio_catalog, render_prompt_context
+from core.system_prompt_injection import build_system_prompt_injection
+from modules.agents.codex.agent import CodexAgent
+from modules.im import MessageContext
+from vibe import cli
+
+
+def _inputs(backend="codex", memory=True, history="managed", skill_mode="pages"):
+ options = {
+ "context": {
+ "user_id": "reviewer",
+ "channel_id": "review",
+ "platform": "avibe",
+ "platform_specific": {
+ "agent_session_id": "sesreview",
+ "agent_session_target": {"native_session_fork": {"source_session_id": "sessource"}},
+ },
+ },
+ "memory_enabled": memory,
+ "include_codex_generated_images": backend == "codex",
+ "skills_cwd": "/fixture/project",
+ "enabled_agents": [
+ {"name": "zeta", "backend": "claude", "description": "Last"},
+ {"name": "alpha", "backend": "codex", "description": "First"},
+ ],
+ }
+ return {"backend": backend, "agent_instructions": "Custom {unchanged} instructions", "options": options}
+
+
+def _environment(monkeypatch, history="managed", skill_mode="pages"):
+ monkeypatch.setenv("CODEX_HOME", "/fixture/codex")
+ monkeypatch.setattr(paths, "get_user_preferences_path", lambda: Path("/fixture/preferences.md"))
+ 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"]
+ skills = [
+ ManagedSkill(name, f"Description {name}", Path("/fixture") / name, (0,), disable_model_invocation=skill_mode == "manual")
+ for name in names
+ ] if skill_mode != "empty" else []
+ monkeypatch.setattr(managed_skills, "resolve_skills", lambda *_args, **_kwargs: skills)
+
+
[email protected]("backend,memory,history,skill_mode", itertools.product(
+ ("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),
+))
+def test_export_reconstructs_production_text_with_source_for_every_block(monkeypatch, backend, memory, history, skill_mode):
+ _environment(monkeypatch, history, skill_mode)
+ request = _inputs(backend, memory, history, skill_mode)
+ 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)
+ if backend == "codex":
+ production = CodexAgent._render_developer_prompt_snapshot(production)
+
+ assert result["text"] == production
+ assert "".join(block["text"] for block in result["blocks"]) == production
+ catalog = {module.id: module for module in PROMPT_MODULES}
+ 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":
+ assert "vibe skill load -- <name>" in production
+ assert "vibe skill list --page 2" in production
+ assert "- skill-00: Description skill-00" in production
+ assert ("## Personal Memory" in production) == memory
+ assert ("preferences.md" in production) != memory
+
+
+def test_exported_sources_cover_all_rendered_branches(monkeypatch):
+ visited = set()
+ for backend, memory, history, skill_mode in itertools.product(
+ ("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),
+ ):
+ _environment(monkeypatch, history, skill_mode)
+ result = render_prompt_context(_inputs(backend, memory, history, skill_mode))
+ visited.update(block["id"] for block in result["blocks"])
+ assert visited == {module.id for module in PROMPT_MODULES}
+
+
[email protected]("history", ["managed", "self-managed"])
+def test_history_and_pagination_keep_their_own_source_provenance(monkeypatch, history):
+ _environment(monkeypatch, history=history)
+ rendered = render_prompt_context(_inputs(history=history))
+ blocks = {block["id"]: block for block in rendered["blocks"]}
+ 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"]["text"] == prompt_text("skills-catalog").format(skill_rows=rows)
+ assert blocks["skills-more-notice"] == {
+ "id": "skills-more-notice",
+ "source_path": "core/prompts/skills-more.md",
+ "text": "\n" + prompt_text("skills-more-notice").format(next_page=2),
+ }
+ assert "| Agent Name | Backend | Agent Description |" in prompt_text("harness-agents-prompt")
+
+
+def test_rendered_revision_changes_only_when_rendered_bytes_change(monkeypatch):
+ _environment(monkeypatch)
+ request = _inputs()
+ before = render_prompt_context(request)
+ request["options"]["enabled_agents"].reverse()
+ assert render_prompt_context(request) == before
+ request["options"]["context"]["message_id"] = "a-different-turn"
+ assert render_prompt_context(request) == before
+ request["agent_instructions"] = "Revised instructions"
+ assert render_prompt_context(request)["revision"] != before["revision"]
+
+
+def test_debug_cli_exports_both_sources_and_production_blocks(monkeypatch, tmp_path, capsys):
+ _environment(monkeypatch)
+ source = export_prompt_studio_catalog()
+ context_file = tmp_path / "context.json"
+ context_file.write_text(json.dumps(_inputs()), encoding="utf-8")
+ args = cli.build_parser().parse_args(["debug", "prompt", "export", "--context-file", str(context_file)])
+ assert cli.cmd_debug_prompt(args) == 0
+ exported = json.loads(capsys.readouterr().out)
+ assert exported["documents"] == source["documents"]
+ assert exported["catalog_revision"] == source["catalog_revision"]
+ assert exported["rendered"]["scope"] == "avibe-injection"
+ assert "{skill_rows}" not in exported["rendered"]["text"]
+ assert "{enabled_agents_rows}" not in exported["rendered"]["text"]
+
+
+def test_real_cli_discovers_updated_skill_and_exports_its_rendered_row(monkeypatch, tmp_path):
+ for name, value in vars(managed_skills).items():
+ if name.endswith("_ENV") and isinstance(value, str):
+ monkeypatch.delenv(value, raising=False)
+ project = tmp_path / "project"
+ skill = project / ".agents" / "skills" / "review-example" / "SKILL.md"
+ skill.parent.mkdir(parents=True)
+ context_file = tmp_path / "context.json"
+ context_file.write_text(json.dumps({
+ "backend": "opencode",
+ "options": {"skills_cwd": str(project), "include_context_guidance": False},
+ }), encoding="utf-8")
+ command = [sys.executable, "-c", "from vibe.cli import main; main()", "debug", "prompt", "export", "--context-file", str(context_file)]
+
+ def exported_row():
+ payload = json.loads(subprocess.check_output(command, text=True, cwd=Path(__file__).resolve().parents[1]))
+ rendered = payload["rendered"]
+ assert "".join(block["text"] for block in rendered["blocks"]) == rendered["text"]
+ return rendered
+
+ skill.write_text("---\nname: review-example\ndescription: First revision\n---\nBody only on load.\n", encoding="utf-8")
+ first = exported_row()
+ assert "- review-example: First revision" in first["text"]
+ assert "Body only on load." not in first["text"]
+ skill.write_text("---\nname: review-example\ndescription: Second revision\n---\nBody only on load.\n", encoding="utf-8")
+ second = exported_row()
+ assert "- review-example: Second revision" in second["text"]
+ assert second["revision"] != first["revision"]
+
+
[email protected]("payload", [[], None, {"backend": "unknown"}, {"backend": "codex", "options": {"unknown": True}}])
+def test_debug_cli_rejects_invalid_context_without_partial_json(tmp_path, capsys, payload):
+ context_file = tmp_path / "context.json"
+ context_file.write_text(json.dumps(payload), encoding="utf-8")
+ args = cli.build_parser().parse_args(["debug", "prompt", "export", "--context-file", str(context_file)])
+ assert cli.cmd_debug_prompt(args) == 1
+ captured = capsys.readouterr()
+ assert not captured.out
+ assert captured.err
+
+
[email protected]("language", ["en", "zh"])
[email protected]("options,field,kind", [
+ ({"context": {"user_id": "u", "channel_id": "c", "platform_specific": [1]}}, "options.context.platform_specific", "invalidField"),
+ ({"context": {"user_id": "u", "channel_id": "c", "platform_specific": "text"}}, "options.context.platform_specific", "invalidField"),
+ ({"context": {"user_id": "u", "channel_id": "c", "unknown": 1}}, "options.context.unknown", "unknownField"),
+ ({"context": {"user_id": "u"}}, "options.context.channel_id", "invalidField"),
+ ({"memory_enabled": "false"}, "options.memory_enabled", "invalidField"),
+ ({"include_show_pages": []}, "options.include_show_pages", "invalidField"),
+ ({"enabled_agents": 123}, "options.enabled_agents", "invalidField"),
+ ({"unknown": True}, "options.unknown", "unknownField"),
+])
+def test_cli_localizes_validation_before_rendering(monkeypatch, tmp_path, capsys, language, options, field, kind):
+ def unexpected_render(*_args, **_kwargs):
+ pytest.fail("Invalid input reached production rendering")
+
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)
+ monkeypatch.setattr(managed_skills, "resolve_skills", unexpected_render)
+ context_file = tmp_path / "context.json"
+ context_file.write_text(json.dumps({
+ "backend": "codex", "options": {"skills_cwd": "/fixture/project", **options},
+ }), encoding="utf-8")
+ args = cli.build_parser().parse_args(["debug", "prompt", "export", "--context-file", str(context_file)])
+ assert cli.cmd_debug_prompt(args) == 1
+ output = capsys.readouterr()
+ assert output.out == ""
+ error = cli.i18n_t(f"debug.cli.error.{kind}", language, field=field)
+ assert output.err == cli.i18n_t("debug.cli.error.promptExport", language, error=error) + "\n"
+
+
[email protected]("language", ["en", "zh"])
[email protected]("agents,location", [
+ ("codex", ""), ("", ""), ({"name": "codex"}, ""), ({}, ""),
+ (True, ""), (123, ""), (1.5, ""),
+ (["codex"], ".0"), ([None], ".0"), ([42], ".0"), ([[]], ".0"),
+ ([{}], ".0"), ([{"description": "Code review"}], ".0"),
+ ([{"name": " "}], ".0"), ([{"name": "!!!"}], ".0"),
+ ([{"name": "codex"}, {}], ".1"),
+])
+def test_cli_rejects_invalid_json_agent_inputs(monkeypatch, tmp_path, capsys, language, agents, location):
+ def unexpected_discovery(*_args, **_kwargs):
+ pytest.fail("Invalid Agent input reached production rendering")
+
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)
+ monkeypatch.setattr(managed_skills, "resolve_skills", unexpected_discovery)
+ request = _inputs()
+ request["options"]["enabled_agents"] = agents
+ context_file = tmp_path / "context.json"
+ context_file.write_text(json.dumps(request), encoding="utf-8")
+ args = cli.build_parser().parse_args(["debug", "prompt", "export", "--context-file", str(context_file)])
+ assert cli.cmd_debug_prompt(args) == 1
+ output = capsys.readouterr()
+ assert output.out == ""
+ error = cli.i18n_t("debug.cli.error.invalidField", language, field=f"options.enabled_agents{location}")
+ assert output.err == cli.i18n_t("debug.cli.error.promptExport", language, error=error) + "\n"
+
+
[email protected]("agents,expected_rows", [
+ (None, []), ([], []),
+ ([{"name": "codex"}], ["| codex | unknown | (no description) |"]),
+ ([{"normalized_name": "Custom_Agent", "description": "Review"}], ["| Custom_Agent | unknown | Review |"]),
+ ([{"name": "zeta"}, {"name": "alpha", "backend": "codex"}], [
+ "| alpha | codex | (no description) |", "| zeta | unknown | (no description) |",
+ ]),
+])
+def test_cli_renders_valid_json_agent_arrays(monkeypatch, tmp_path, capsys, agents, expected_rows):
+ _environment(monkeypatch)
+ request = _inputs()
+ request["options"]["enabled_agents"] = agents
+ context_file = tmp_path / "context.json"
+ context_file.write_text(json.dumps(request), encoding="utf-8")
+ args = cli.build_parser().parse_args(["debug", "prompt", "export", "--context-file", str(context_file)])
+ assert cli.cmd_debug_prompt(args) == 0
+ output = capsys.readouterr()
+ assert output.err == ""
+ rendered = json.loads(output.out)["rendered"]
+ tables = [block for block in rendered["blocks"] if block["id"] == "harness-agents-prompt"]
+ assert bool(tables) == bool(expected_rows)
+ if tables:
+ rows = [line for line in tables[0]["text"].splitlines() if line.startswith("| ")][2:]
+ assert rows == expected_rows
+ omitted = _inputs()
+ del omitted["options"]["enabled_agents"]
+ if agents is None:
+ assert render_prompt_context(omitted) == rendered
+
+
[email protected]("language", ["en", "zh"])
[email protected]("content,kind", [
+ (b"{", "invalidJson"), (b"\xff", "invalidJson"), (None, "unreadableContext"),
+ (b"null", "invalidContext"), (b'{}', "invalidBackend"),
+ (b'{"backend":"codex","extra":1}', "invalidContext"),
+])
+def test_cli_localizes_invalid_context_files(monkeypatch, tmp_path, capsys, language, content, kind):
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)
+ context_file = tmp_path / "context.json"
+ if content is not None:
+ context_file.write_bytes(content)
+ args = cli.build_parser().parse_args(["debug", "prompt", "export", "--context-file", str(context_file)])
+ assert cli.cmd_debug_prompt(args) == 1
+ output = capsys.readouterr()
+ assert output.out == ""
+ error = cli.i18n_t(f"debug.cli.error.{kind}", language)
+ assert output.err == cli.i18n_t("debug.cli.error.promptExport", language, error=error) + "\n"
+
+
+def test_source_migration_preserves_injection_bytes(monkeypatch):
+ outputs = []
+ for backend, memory, history, skill_mode in itertools.product(
+ ("claude", "codex", "opencode"), (False, True), ("off", "managed", "self-managed"), ("empty", "manual", "pages"),
+ ):
+ _environment(monkeypatch, history, skill_mode)
+ outputs.append(render_prompt_context(_inputs(backend, memory, history, skill_mode))["text"])
+ digest = hashlib.sha256(json.dumps(outputs, ensure_ascii=False).encode()).hexdigest()
+ # Captured from the pre-migration renderer at 928924dd82bb48c7eea67ff06ddd844d442cb2a1.
+ assert digest == "adbf608248e0b0a03d6646f57d31816cdb520c86113225e281b2aa007b100bc5"
diff --git a/vibe/cli.py b/vibe/cli.py
index 442f527d1..b5f910311 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -886,13 +886,41 @@ def cmd_skill(args) -> int:
def cmd_debug_prompt(args) -> int:
- """Export the deterministic Prompt Studio source catalog."""
+ """Export all authored sources, optionally with the production rendering."""
if args.debug_command != "prompt" or args.prompt_debug_command != "export":
return 1
- from core.prompt_studio_catalog import export_prompt_studio_catalog
+ from core.prompt_studio_catalog import PromptRenderInputError, export_prompt_studio_catalog
- print(json.dumps(export_prompt_studio_catalog(), ensure_ascii=False, indent=2))
+ context_file = getattr(args, "context_file", None)
+ context = None
+ try:
+ if context_file:
+ try:
+ raw = Path(context_file).read_text(encoding="utf-8")
+ except OSError as exc:
+ raise PromptRenderInputError("unreadableContext") from exc
+ except UnicodeError as exc:
+ raise PromptRenderInputError("invalidJson") from exc
+ try:
+ context = json.loads(raw)
+ except ValueError as exc:
+ raise PromptRenderInputError("invalidJson") from exc
+ if not isinstance(context, dict):
+ raise PromptRenderInputError("invalidContext")
+ payload = export_prompt_studio_catalog(render_context=context)
+ except PromptRenderInputError as exc:
+ language = _configured_cli_language()
+ error = i18n_t(f"debug.cli.error.{exc.key}", language, field=exc.field)
+ print(i18n_t("debug.cli.error.promptExport", language, error=error), file=sys.stderr)
+ return 1
+ except (OSError, ValueError, TypeError):
+ logger.debug("Prompt export failed", exc_info=True)
+ language = _configured_cli_language()
+ error = i18n_t("debug.cli.error.renderFailed", language)
+ print(i18n_t("debug.cli.error.promptExport", language, error=error), file=sys.stderr)
+ return 1
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
return 0
@@ -15935,6 +15963,10 @@ def build_parser():
"export",
help=i18n_t("debug.cli.help.promptExport", debug_help_language),
)
+ debug_prompt_export_parser.add_argument(
+ "--context-file",
+ help=i18n_t("debug.cli.help.promptContext", debug_help_language),
+ )
debug_prompt_export_parser.add_argument(
"--format",
choices=("json",),
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 6dbbe5ca2..3bb626777 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -782,8 +782,19 @@
"help": {
"command": "Inspect internal Avibe state",
"prompt": "Inspect authored prompt sources",
- "promptExport": "Export the Prompt Studio source catalog",
+ "promptExport": "Export all prompt sources, optionally with the production rendering",
+ "promptContext": "JSON file with backend, optional agent_instructions and production builder options",
"promptFormat": "Export format"
+ },
+ "error": {
+ "promptExport": "Prompt export failed: {error}",
+ "invalidContext": "The context must be a JSON object containing only backend, agent_instructions and options.",
+ "invalidBackend": "backend must be claude, codex or opencode.",
+ "invalidField": "Invalid field type or missing required field: {field}",
+ "unknownField": "Unknown field: {field}",
+ "unreadableContext": "Cannot read the context file. Check its path and permissions.",
+ "invalidJson": "The context file must contain valid UTF-8 JSON.",
+ "renderFailed": "Cannot render the prompt sources. Check the sources and rendering inputs."
}
}
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 8689cfa76..020029d67 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -782,8 +782,19 @@
"help": {
"command": "查看 Avibe 内部状态",
"prompt": "查看维护中的 Prompt 源",
- "promptExport": "导出 Prompt Studio 源目录",
+ "promptExport": "导出完整 Prompt 源区块,可附带生产渲染结果",
+ "promptContext": "包含 backend、可选 agent_instructions 和生产构建参数 options 的 JSON 文件",
"promptFormat": "导出格式"
+ },
+ "error": {
+ "promptExport": "Prompt 导出失败:{error}",
+ "invalidContext": "上下文必须是 JSON 对象,且只能包含 backend、agent_instructions 和 options。",
+ "invalidBackend": "backend 必须为 claude、codex 或 opencode。",
+ "invalidField": "字段类型无效或缺少必填字段:{field}",
+ "unknownField": "未知字段:{field}",
+ "unreadableContext": "无法读取上下文文件,请检查路径和权限。",
+ "invalidJson": "上下文文件必须包含有效的 UTF-8 JSON。",
+ "renderFailed": "无法渲染提示词来源,请检查源文件和渲染输入。"
}
}
},