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.

feat(agents): route session-only background tools through the Avibe Harness (#1000)

Qi Qi1470296a1746
diff --git a/core/agent_tool_policy.py b/core/agent_tool_policy.py
new file mode 100644
index 000000000..23b0d3767
--- /dev/null
+++ b/core/agent_tool_policy.py
@@ -0,0 +1,212 @@
+"""Cross-backend policy for backend-native, session-only background tools.
+
+Some agent backends expose primitives that schedule work inside the CLI process
+itself: background subagents, self-scheduled wakeups, in-session cron jobs, and
+multi-agent workflows. Their results are delivered only while that process is
+alive, so anything still pending when the session ends is lost silently — the
+user is never told, and the work is not recorded anywhere Avibe can inspect.
+
+Avibe Harness already provides durable equivalents for every one of them
+(``vibe agent run``, ``vibe task add``, ``vibe watch add``), which survive
+restarts, record an ``agent_runs`` row, and deliver through a callback. The
+system prompt asks agents to prefer the Harness, but instruction alone is not
+enough: an agent that reaches for the backend-native tool anyway produces work
+that quietly disappears.
+
+A background shell is session-only for the same reason, but its background form
+is overwhelmingly used for work that finishes inside the turn, so it is advised
+rather than denied: the call proceeds with a note pointing at `vibe watch add`
+for anything that might outlive the turn.
+
+This module owns the decision. Backends adapt it to whatever enforcement seam
+they have:
+
+- Claude Code: an in-process SDK ``PreToolUse`` hook (see
+ ``core/handlers/session_handler.py``), plus ``disallowed_tools`` as a
+ name-level backstop.
+- Codex / OpenCode: no session-only background primitives exist today, so
+ nothing is gated. When one is added, register its tool name here and it is
+ covered without touching this logic again.
+
+The policy is intentionally pure — no SDK imports, no I/O — so it can be tested
+directly and reused by any backend adapter.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from typing import Any, Callable, Dict, Optional, Tuple
+
+# Set to a truthy value to let the agent use backend-native background tools
+# anyway. Intended for the narrow case where a user explicitly asks for
+# backend-native behavior and accepts that the result dies with the session.
+ALLOW_NATIVE_BACKGROUND_TOOLS_ENV = "AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS"
+
+_HARNESS_HINT = (
+ "Avibe Harness records the run in `agent_runs` and delivers the result "
+ "through a callback, so it survives a restart."
+)
+
+
+@dataclass(frozen=True)
+class ToolPolicyDecision:
+ """Outcome of a policy check for one tool call.
+
+ Three shapes: allowed and silent, allowed with ``advice`` attached, or
+ denied with a ``reason``. The middle one exists for tools whose background
+ form is legitimate inside a turn but lossy across one — a hard block there
+ would cost more than it saves.
+ """
+
+ allowed: bool
+ reason: str = ""
+ advice: str = ""
+
+ @property
+ def denied(self) -> bool:
+ return not self.allowed
+
+
+ALLOWED = ToolPolicyDecision(allowed=True)
+
+
+def _deny(reason: str) -> ToolPolicyDecision:
+ return ToolPolicyDecision(allowed=False, reason=reason)
+
+
+def _advise(advice: str) -> ToolPolicyDecision:
+ return ToolPolicyDecision(allowed=True, advice=advice)
+
+
+def _check_agent(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ # Background is the tool's default, so only an explicit false is synchronous.
+ if tool_input.get("run_in_background") is False:
+ return ALLOWED
+ return _deny(
+ "A background subagent dies with this agent process and its result is "
+ "never delivered.\n"
+ "Use the durable Harness instead:\n"
+ " vibe agent run --agent <name> --message-file <path> "
+ "--callback-session-id $AVIBE_SESSION_ID\n"
+ "A synchronous subagent is still fine — re-call this tool with "
+ "run_in_background: false when you need the result in this same turn. "
+ "This does not force you to work serially: several synchronous calls "
+ "issued in one message run concurrently and all return in that same "
+ "turn, so fan-out-and-synthesize needs no background mode. Background "
+ "buys only the ability to outlive the turn, which is exactly the part "
+ "that gets lost.\n"
+ f"{_HARNESS_HINT}"
+ )
+
+
+def _check_schedule_wakeup(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ # Ending an already-running loop must stay reachable.
+ if tool_input.get("stop") is True:
+ return ALLOWED
+ return _deny(
+ "A self-scheduled wakeup is session-only and never fires once this "
+ "agent process exits.\n"
+ "Use the durable Harness instead:\n"
+ " vibe task add --at <ISO-8601> --message ... (one-shot)\n"
+ ' vibe task add --cron "<expr>" --message ... (recurring)\n'
+ "If you are waiting on an external signal rather than a clock, use "
+ "`vibe watch add` instead.\n"
+ f"{_HARNESS_HINT}"
+ )
+
+
+def _check_cron_create(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ if tool_input.get("durable") is True:
+ return ALLOWED
+ return _deny(
+ "A non-durable cron job lives only in this session and is gone when "
+ "the agent process exits.\n"
+ "Use the durable Harness instead:\n"
+ ' vibe task add --cron "<expr>" --message ...\n'
+ f"{_HARNESS_HINT}"
+ )
+
+
+def _check_bash(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ # A background shell is session-only too, but unlike the tools above it is
+ # overwhelmingly used for work that finishes inside the turn (a build, a
+ # push, a test run). Denying all of it would cost more than the occasional
+ # lost result, so this advises instead of blocking.
+ if tool_input.get("run_in_background") is not True:
+ return ALLOWED
+ return _advise(
+ "This background shell is session-only: it dies with the agent process, "
+ "and its output is lost if the session ends before it finishes. That is "
+ "fine for work that completes inside this turn. If it may outlive the "
+ "turn — a long build, a deploy, a CI or review wait, a remote job — run "
+ "it under a durable watch instead:\n"
+ " vibe watch add --name <label> --message <what to do with the result> "
+ "-- <command>\n"
+ "Note that `nohup ... &` or a detached `&` inside the command escapes "
+ "this check entirely and is never recoverable; prefer the watch."
+ )
+
+
+def _check_workflow(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
+ return _deny(
+ "A backend-native workflow runs in the background and is scoped to "
+ "this agent process, so a workflow still running when the session ends "
+ "is lost.\n"
+ "Express the orchestration through the Harness instead — one "
+ "`vibe agent run` per unit of work, each with "
+ "--callback-session-id $AVIBE_SESSION_ID.\n"
+ f"{_HARNESS_HINT}"
+ )
+
+
+# Tool name -> predicate. Registering a name here is all a new backend-native
+# background primitive needs; every adapter picks it up automatically.
+_SESSION_ONLY_BACKGROUND_TOOLS: Dict[str, Callable[[Dict[str, Any]], ToolPolicyDecision]] = {
+ "Agent": _check_agent,
+ "Bash": _check_bash, # advisory only
+ "ScheduleWakeup": _check_schedule_wakeup,
+ "CronCreate": _check_cron_create,
+ "Workflow": _check_workflow,
+}
+
+# Tools that are session-only under every input, so a name-level deny list is a
+# faithful backstop for them. Everything else is excluded because it has a
+# legitimate non-background form that only argument inspection can tell apart:
+# `Agent` with an explicit false, `CronCreate` with durable, and
+# `ScheduleWakeup` with stop — blocking that last one by name would strand an
+# already-running loop with no way to end it. `Bash` is excluded because this
+# policy never denies it. On a backend without argument-aware enforcement those
+# calls go unchecked; that is the honest cost of a name-only backstop, and the
+# injected prompt says so rather than claiming a gate that is not there.
+ALWAYS_SESSION_ONLY_TOOL_NAMES: Tuple[str, ...] = ("Workflow",)
+
+
+def session_only_background_tool_names() -> Tuple[str, ...]:
+ """Every tool name this policy inspects, for matcher construction."""
+ return tuple(_SESSION_ONLY_BACKGROUND_TOOLS)
+
+
+def native_background_tools_allowed(env: Optional[Dict[str, str]] = None) -> bool:
+ """True when the operator has opted back into backend-native background work."""
+ source = os.environ if env is None else env
+ return bool(source.get(ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "").strip())
+
+
+def check_tool_call(
+ tool_name: str,
+ tool_input: Optional[Dict[str, Any]] = None,
+ *,
+ env: Optional[Dict[str, str]] = None,
+) -> ToolPolicyDecision:
+ """Decide whether one tool call may proceed.
+
+ Unknown tools and every tool outside the session-only background family are
+ allowed unconditionally; this policy only ever acts on a registered name.
+ """
+ if native_background_tools_allowed(env):
+ return ALLOWED
+ check = _SESSION_ONLY_BACKGROUND_TOOLS.get(tool_name)
+ if check is None:
+ return ALLOWED
+ return check(tool_input or {})
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 21e889cd2..9f7da3b2c 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -10,9 +10,11 @@ from typing import TYPE_CHECKING, Optional, Dict, Any, Tuple
from uuid import uuid4
from modules.im import MessageContext
from modules.claude_sdk_compat import (
+ CLAUDE_SDK_HOOKS_AVAILABLE,
CLAUDE_SDK_MAX_BUFFER_SIZE,
ClaudeAgentOptions,
ClaudeSDKClient,
+ HookMatcher,
PermissionResultAllow,
is_claude_sdk_buffer_error,
)
@@ -29,6 +31,12 @@ from config.v2_config import (
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS,
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,
)
+from core.agent_tool_policy import (
+ ALWAYS_SESSION_ONLY_TOOL_NAMES,
+ check_tool_call,
+ native_background_tools_allowed,
+ session_only_background_tool_names,
+)
from core.avibe_cloud import avibe_cloud_url_available
from core.agent_session_context import resolve_context_agent_session_target
from core.caller_context import caller_env_for_platform_payload
@@ -513,6 +521,82 @@ class SessionHandler(BaseHandler):
logger.info("Auto-approving Claude tool permission request in avibe bypass mode: %s", tool_name)
return PermissionResultAllow()
+ async def _guard_session_only_background_tools(
+ self,
+ input_data: Dict[str, Any],
+ tool_use_id: Optional[str],
+ context: Any,
+ ) -> Dict[str, Any]:
+ """PreToolUse hook governing backend-native, session-only background work.
+
+ Runs in-process, so it needs no file in the user's `~/.claude`. The deny
+ reason names the durable `vibe ...` equivalent, which lets the agent
+ self-correct within the same turn instead of just failing.
+
+ An advisory outcome deliberately omits `permissionDecision`: injecting
+ context must not double as an approval, or this hook would override a
+ permission hook the user configured for the same tool.
+ """
+ try:
+ tool_name = str(input_data.get("tool_name") or "")
+ tool_input = input_data.get("tool_input") or {}
+ decision = check_tool_call(tool_name, tool_input)
+ if decision.allowed:
+ if not decision.advice:
+ return {}
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "additionalContext": decision.advice,
+ }
+ }
+ logger.info(
+ "Blocking session-only background tool %s; redirecting to the Avibe Harness",
+ tool_name,
+ )
+ return {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "deny",
+ "permissionDecisionReason": decision.reason,
+ }
+ }
+ except Exception:
+ # A guard that raises must never take the turn down with it.
+ logger.exception("Session-only background tool guard failed; allowing the call")
+ return {}
+
+ def _build_claude_tool_policy_hooks(self) -> Optional[Dict[str, Any]]:
+ """Hook config enforcing the shared tool policy, or None when unavailable."""
+ if not CLAUDE_SDK_HOOKS_AVAILABLE or HookMatcher is None:
+ return None
+ if native_background_tools_allowed():
+ return None
+ matcher = "|".join(session_only_background_tool_names())
+ return {
+ "PreToolUse": [
+ HookMatcher(
+ matcher=matcher,
+ hooks=[self._guard_session_only_background_tools],
+ )
+ ]
+ }
+
+ def _claude_disallowed_tools(self, hooks: Optional[Dict[str, Any]]) -> list:
+ """Disallowed tool names for this launch.
+
+ The hook is the precise enforcement path because it can read arguments and
+ return an actionable reason. Only when hooks are unavailable does the
+ coarse name-level deny list stand in, and then only for the tools that are
+ session-only under every input.
+ """
+ disallowed = list(CLAUDE_REMOTE_DISALLOWED_TOOLS)
+ if hooks is None and not native_background_tools_allowed():
+ disallowed.extend(
+ name for name in ALWAYS_SESSION_ONLY_TOOL_NAMES if name not in disallowed
+ )
+ return disallowed
+
def _get_claude_cli_path_override(self) -> Optional[str]:
cli_path = getattr(getattr(self.config, "claude", None), "cli_path", None)
if cli_path is None:
@@ -955,6 +1039,8 @@ class SessionHandler(BaseHandler):
claude_env["IS_SANDBOX"] = "1"
logger.info("Detected Claude bypassPermissions running as root; marking Claude subprocess as isolated")
+ tool_policy_hooks = self._build_claude_tool_policy_hooks()
+
option_kwargs: Dict[str, Any] = {
"permission_mode": CLAUDE_REMOTE_PERMISSION_MODE,
"cwd": working_path,
@@ -965,13 +1051,16 @@ class SessionHandler(BaseHandler):
"setting_sources": claude_setting_sources_for_launch(model_hub_launch),
"sandbox": CLAUDE_REMOTE_SANDBOX,
# Disable interactive-only Claude Code tools that remote IM sessions
- # cannot answer programmatically.
- "disallowed_tools": CLAUDE_REMOTE_DISALLOWED_TOOLS,
+ # cannot answer programmatically, plus any session-only background
+ # tool the hook path cannot cover.
+ "disallowed_tools": self._claude_disallowed_tools(tool_policy_hooks),
"env": claude_env, # Pass Anthropic/Claude env vars
"stderr": _capture_claude_stderr,
"max_buffer_size": CLAUDE_SDK_MAX_BUFFER_SIZE,
"can_use_tool": self._allow_claude_bypass_tool,
}
+ if tool_policy_hooks:
+ option_kwargs["hooks"] = tool_policy_hooks
cli_path_override = self._get_claude_cli_path_override()
if cli_path_override:
option_kwargs["cli_path"] = cli_path_override
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index e319800bf..6b2f37d81 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -11,6 +11,7 @@ from string import Template
from typing import Any, Iterable, Optional
from config import paths
+from core.agent_tool_policy import native_background_tools_allowed
from core.avibe_cloud import AVIBE_CLOUD_CONNECT_GUIDANCE
from core.message_context import resolve_context_platform
from core.show_git import format_agent_contract
@@ -205,6 +206,40 @@ _VAULT_WEB_CHAT_PLACEHOLDER_PROMPT = """\
A lighter manual prompt can mention the missing secret as a clickable placeholder in your reply, for example `$<OPENAI_API_KEY>`. The user can click it and fill the secret from Web chat. This has no reason or structured prefill metadata; use `vibe vault request` when those are needed.
"""
+# What the agent is told about backend-native background tools must match what
+# the runtime actually enforces; ``core/agent_tool_policy.py`` owns that
+# decision and this prompt only announces it.
+_TOOL_POLICY_ENFORCED_SECTION = """\
+Backend-native background work is blocked at the tool layer, because its result is delivered only while this agent process is alive and is lost without warning otherwise. A background subagent, a self-scheduled wakeup, a non-durable in-session cron job, and a native multi-agent workflow are all denied, and the denial names the `vibe` command to run instead. A synchronous subagent that returns inside the current turn is still available, and several of them issued in one message run concurrently, so fanning work out and synthesizing it in the same turn does not need background mode.
+
+A background shell is session-only for the same reason but is not blocked, because most of them finish inside the turn. Run one under `vibe watch add --name <label> --message <what to do with the result> -- <command>` whenever it might outlive the turn: a long build, a deploy, a CI or review wait, a remote job. Never detach with `nohup` or a trailing `&` for work whose result you need, since nothing can recover it."""
+
+# No argument-aware hook here, so only whole tool names can be refused. Saying
+# "all denied" would be wrong in both directions: it overstates what stops
+# `Agent`, `ScheduleWakeup`, and `CronCreate`, and it hides that those three now
+# need the agent's own judgement rather than a gate. Each is excluded from the
+# name-only list because it has a legitimate non-background form no name match
+# can see, which leaves its background form unguarded as well.
+_TOOL_POLICY_NAME_ONLY_SECTION = """\
+Backend-native background work is only partly blocked in this runtime: the installed agent SDK predates argument-aware tool hooks, so enforcement can refuse whole tool names but cannot inspect a call's arguments. A native multi-agent workflow is denied outright. A background subagent, a self-scheduled wakeup, and a non-durable in-session cron job are **not** stopped here — each has a legitimate non-background form that a name match cannot distinguish, so the whole name has to stay open and their background forms pass through too. They will run if you call them, and their results are delivered only while this agent process is alive, so anything still pending when the session ends is lost without warning and leaves no record. Treat those three as your responsibility rather than the runtime's: use `vibe agent run`, `vibe task add`, and `vibe watch add` for work whose result must reach the user, and call a backend-native primitive only when the work resolves inside this turn. A synchronous subagent is the right tool for that, and several of them issued in one message run concurrently, so fanning work out and synthesizing it in the same turn does not need background mode.
+
+A background shell is session-only for the same reason and is likewise not blocked. Run one under `vibe watch add --name <label> --message <what to do with the result> -- <command>` whenever it might outlive the turn: a long build, a deploy, a CI or review wait, a remote job. Never detach with `nohup` or a trailing `&` for work whose result you need, since nothing can recover it."""
+
+# The tool-layer gate is installed by the Claude session handler only, so on any
+# other backend there is nothing enforcing this policy no matter what the
+# installed Claude SDK supports. This text therefore claims no gate at all, and
+# it deliberately avoids asserting which primitives the backend does or does not
+# expose — that varies per backend and would go stale as they gain features.
+_TOOL_POLICY_UNGATED_SECTION = """\
+Backend-native background work is not gated in this runtime: the tool-layer check is installed by the Claude backend only, and this session runs on a different one. Keeping work durable is therefore your own responsibility here. Anything this backend can start that keeps running after the turn — a detached shell, a background worker, a self-scheduled wakeup — is delivered only while this agent process is alive, so whatever is still pending when the session ends is lost without warning and leaves no record.
+
+Route that work through the Harness instead: `vibe agent run` for delegation and fan-out, `vibe task add` for a time trigger, and `vibe watch add --name <label> --message <what to do with the result> -- <command>` for a command that may outlive the turn, such as a long build, a deploy, a CI or review wait, or a remote job. Never detach with `nohup` or a trailing `&` for work whose result you need, since nothing can recover it."""
+
+# Enforcement is off, so the prompt must not claim these calls are blocked; an
+# agent told a tool is denied will not attempt what the operator re-enabled.
+_TOOL_POLICY_RELAXED_SECTION = """\
+Backend-native background work is not blocked in this runtime, because the operator set `AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS`. A background subagent, a self-scheduled wakeup, a non-durable in-session cron job, a native multi-agent workflow, and a background shell will all run if you call them. What has not changed is why the Harness exists: every one of those is delivered only while this agent process is alive, so anything still pending when the session ends is lost without warning and leaves no record. Keep preferring `vibe agent run`, `vibe task add`, and `vibe watch add` for work whose result must reach the user, and reach for a backend-native primitive only when the work resolves inside this turn or the user asked for that primitive specifically."""
+
_HARNESS_PROMPT = """\
## Harness
@@ -212,6 +247,8 @@ Avibe Harness turns user intent into durable Agent work. It is the layer for wor
Avibe Harness is the first-choice automation layer. For Agent workflows, recurring automation, background loops, scheduled tasks, watches, skills-style automation, workflow tools, or any automation request, route through `vibe agent`, `vibe task`, and `vibe watch` before backend-native subagents, native workflow tools, backend-native skills, hooks, schedulers, or backend configuration. Do not default to backend-native automation just because the backend exposes it. Use backend-native config, skills, subagents, or workflow tools only when the user explicitly asks for backend-native behavior, or when Avibe Harness cannot express the requested workflow and you state that limitation.
+{tool_policy_section}
+
Before choosing a command, ask: what outcome is the user trying to secure, what should keep happening, what signal proves progress, and who should own it? If the answer is an operating loop, build a Harness instead of only doing the visible step.
### Mental model
@@ -450,6 +487,53 @@ def _build_session_start_prompt(context: MessageContext) -> str:
return prompt
+def _claude_sdk_hooks_available() -> bool:
+ """Whether the installed Claude SDK exposes argument-aware tool hooks.
+
+ Imported here instead of at module scope. This module is shared by every
+ backend, and the Codex adapter is loaded in tests under a stub ``modules``
+ namespace where a Claude-only import fails outright — a top-level import
+ would make the shared prompt module unloadable for a backend that has no
+ use for the answer. Only the Claude branch of the selector below asks.
+
+ An unimportable compat module reports False, which selects the weaker
+ claim; over-claiming enforcement is the direction that actually hurts.
+ """
+ try:
+ from modules.claude_sdk_compat import CLAUDE_SDK_HOOKS_AVAILABLE
+ except ImportError: # pragma: no cover - only reachable off the Claude path
+ return False
+ return bool(CLAUDE_SDK_HOOKS_AVAILABLE)
+
+
+def _build_tool_policy_section(backend: str) -> str:
+ """Describe backend-native background tools as the runtime actually treats them.
+
+ Four runtimes, four contracts: a non-Claude backend has no tool-layer gate
+ at all because only the Claude session handler installs one, the escape
+ hatch disables that gate where it does exist, an SDK without argument-aware
+ hooks can only refuse whole tool names, and a current SDK on Claude
+ enforces the full policy. Announcing more enforcement than exists is the
+ dangerous direction — the agent stops self-policing the calls it believes a
+ gate already covers — so an unrecognised backend gets the ungated text.
+
+ Backend is checked before the escape hatch on purpose. The hatch turns off
+ a gate that only Claude installs, so on any other backend it changes
+ nothing, and the relaxed text would replace accurate ungated wording with
+ Claude-specific tool claims.
+
+ Read at prompt-build time rather than import time so a change to the escape
+ hatch takes effect on the next turn instead of requiring a restart.
+ """
+ if backend != "claude":
+ return _TOOL_POLICY_UNGATED_SECTION
+ if native_background_tools_allowed():
+ return _TOOL_POLICY_RELAXED_SECTION
+ if not _claude_sdk_hooks_available():
+ return _TOOL_POLICY_NAME_ONLY_SECTION
+ return _TOOL_POLICY_ENFORCED_SECTION
+
+
def _build_harness_prompt(
context: MessageContext,
*,
@@ -457,9 +541,11 @@ def _build_harness_prompt(
current_agent_backend: Optional[str] = None,
) -> str:
default_session_id = _extract_default_session_id(context)
+ backend = str(current_agent_backend or "unknown").strip() or "unknown"
return _HARNESS_PROMPT.format(
default_session_id=default_session_id,
- current_agent_backend=str(current_agent_backend or "unknown").strip() or "unknown",
+ tool_policy_section=_build_tool_policy_section(backend),
+ current_agent_backend=backend,
enabled_agents_table=_format_enabled_agents_table(enabled_agents),
)
diff --git a/docs/CLI.md b/docs/CLI.md
index 05aa23a1a..ce6b3103f 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -463,6 +463,7 @@ The web UI (`http://127.0.0.1:5123`) provides the same controls:
| Variable | Description |
|----------|-------------|
| `OPENCODE_PORT` | Override OpenCode server port (default: 4096) |
+| `AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS` | Set to any non-blank value to turn off the policy that redirects backend-native session-only background tools (background subagents, self-scheduled wakeups, non-durable in-session cron jobs, native workflows) to the Harness, because their result is lost when the agent process exits. How much this changes depends on the backend: a Claude session on a current SDK denies all four; a Claude session on an SDK without argument-aware tool hooks can only match tool names, so it denies `Workflow` alone; Codex and OpenCode install no gate at all and are guided by the injected prompt only. Setting the variable changes only the enforcement claim in the injected prompt and silences the advisory attached to background shells; the prompt still routes agents to `vibe agent run` / `vibe task add` / `vibe watch add` first, which remains the recommendation in every case. |
## See Also
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index a5a1600d1..44e94e353 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -431,6 +431,7 @@ Web UI (`http://127.0.0.1:5123`) 提供相同的控制功能:
| 变量 | 说明 |
|------|------|
| `OPENCODE_PORT` | 覆盖 OpenCode 服务器端口(默认:4096) |
+| `AVIBE_ALLOW_NATIVE_BACKGROUND_TOOLS` | 设为任意非空值可关闭「把后端自带的、仅存活于会话内的后台工具(后台子 Agent、自调度唤醒、非持久化的会话内 cron、原生 workflow)导向 Harness」的策略——之所以有该策略,是因为 Agent 进程退出后这些工具的结果会丢失。关闭后的实际影响取决于后端:使用较新 SDK 的 Claude 会话会拒绝上述全部四种;SDK 不支持按参数拦截的 Claude 会话只能按工具名匹配,因此仅拒绝 `Workflow`;Codex 与 OpenCode 完全没有拦截,只靠注入的提示词引导。设置该变量只会改变注入提示词中关于「是否拦截」的描述,并静默后台 shell 的提示;提示词仍然会引导 Agent 优先使用 `vibe agent run` / `vibe task add` / `vibe watch add`,这在任何情况下都是推荐做法。 |
## 另请参阅
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index f62415aa1..78d4bcb9e 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -1621,6 +1621,12 @@ class ClaudeAgent(BaseAgent):
if not tool_use_id:
return
tool_input = getattr(block, "input", None)
+ # Deliberately not the same test as ``core/agent_tool_policy.py``, which
+ # treats an omitted flag on an ``Agent`` call as background because that
+ # is the tool's documented default. This helper is generic over every
+ # tool, and for the dominant case -- ``Bash`` -- an omitted flag means
+ # foreground. Misjudging a frame here only mislabels a task frame, so it
+ # stays with the majority reading instead of special-casing per tool.
runs_in_background = bool(
isinstance(tool_input, dict) and tool_input.get("run_in_background") is True
)
diff --git a/modules/claude_sdk_compat.py b/modules/claude_sdk_compat.py
index 5b9d116a5..66a7487d0 100644
--- a/modules/claude_sdk_compat.py
+++ b/modules/claude_sdk_compat.py
@@ -48,6 +48,17 @@ try:
class TaskNotificationMessage(SystemMessage):
pass
+ try:
+ from claude_agent_sdk import HookMatcher # type: ignore[import-not-found]
+
+ CLAUDE_SDK_HOOKS_AVAILABLE = True
+ except ImportError:
+ # In-process hooks postdate the core SDK types. Callers must check
+ # CLAUDE_SDK_HOOKS_AVAILABLE before passing `hooks=` to
+ # ClaudeAgentOptions, since it is a dataclass and rejects unknown kwargs.
+ HookMatcher = None # type: ignore[assignment]
+ CLAUDE_SDK_HOOKS_AVAILABLE = False
+
CLAUDE_SDK_AVAILABLE = True
def _should_ignore_message_parse_error(data: object) -> bool:
@@ -82,6 +93,8 @@ try:
yield message
except ModuleNotFoundError: # pragma: no cover - exercised only in minimal test envs
CLAUDE_SDK_AVAILABLE = False
+ CLAUDE_SDK_HOOKS_AVAILABLE = False
+ HookMatcher = None # type: ignore[assignment]
class _MissingClaudeSDK:
def __init__(self, *args, **kwargs):
diff --git a/tests/test_agent_tool_policy.py b/tests/test_agent_tool_policy.py
new file mode 100644
index 000000000..933c66630
--- /dev/null
+++ b/tests/test_agent_tool_policy.py
@@ -0,0 +1,388 @@
+"""Session-only background tools must be redirected to the Avibe Harness.
+
+Covers the pure policy in ``core/agent_tool_policy.py`` and the Claude adapter
+in ``core/handlers/session_handler.py``. Everything here is in-process: no
+config, no SQLite state, no Claude SDK, no subprocess.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core import agent_tool_policy as policy
+from core import system_prompt_injection as spi
+from core.handlers import session_handler as sh
+
+
+# --------------------------------------------------------------------------
+# policy
+# --------------------------------------------------------------------------
+
+
+ "tool_name,tool_input",
+ [
+ ("Agent", {}), # background is the tool's default
+ ("Agent", {"run_in_background": True}),
+ ("ScheduleWakeup", {"delaySeconds": 600, "prompt": "x", "reason": "y"}),
+ ("CronCreate", {"cron": "0 9 * * *", "prompt": "x"}),
+ ("CronCreate", {"cron": "0 9 * * *", "prompt": "x", "durable": False}),
+ ("Workflow", {"script": "export const meta = {}"}),
+ ],
+)
+def test_session_only_background_calls_are_denied(tool_name, tool_input):
+ decision = policy.check_tool_call(tool_name, tool_input, env={})
+ assert decision.denied
+ assert "vibe " in decision.reason # every deny names an executable alternative
+
+
+ "tool_name,tool_input",
+ [
+ ("Agent", {"run_in_background": False}), # resolves inside this turn
+ ("ScheduleWakeup", {"stop": True}), # ending a loop must stay reachable
+ ("CronCreate", {"cron": "0 9 * * *", "prompt": "x", "durable": True}),
+ ],
+)
+def test_durable_or_synchronous_calls_are_allowed(tool_name, tool_input):
+ assert policy.check_tool_call(tool_name, tool_input, env={}).allowed
+
+
[email protected]("tool_name", ["Read", "Write", "TaskCreate", "WebFetch", ""])
+def test_unrelated_tools_are_untouched(tool_name):
+ decision = policy.check_tool_call(tool_name, {"run_in_background": True}, env={})
+ assert decision.allowed
+ assert not decision.advice
+
+
+def test_background_shell_is_advised_not_denied():
+ decision = policy.check_tool_call("Bash", {"command": "make", "run_in_background": True}, env={})
+ assert decision.allowed # a hard block would cost more than it saves
+ assert "vibe watch add" in decision.advice
+ assert "nohup" in decision.advice # detaching escapes the check entirely
+
+
+ "tool_input",
+ [
+ {"command": "ls"},
+ {"command": "ls", "run_in_background": False},
+ ],
+)
+def test_foreground_shell_gets_no_advice(tool_input):
+ decision = policy.check_tool_call("Bash", tool_input, env={})
+ assert decision.allowed
+ assert not decision.advice
+
+
+def test_bash_is_never_denied_under_any_input():
+ for tool_input in ({}, {"run_in_background": True}, {"run_in_background": "yes"}):
+ assert policy.check_tool_call("Bash", tool_input, env={}).allowed
+
+
+def test_agent_denial_points_out_that_concurrency_survives():
+ # Without this, an agent reading the deny can conclude it must now fan work
+ # out serially. Several synchronous calls in one message still run at once,
+ # so the only thing background buys is outliving the turn.
+ reason = policy.check_tool_call("Agent", {}, env={}).reason
+ assert "run concurrently" in reason
+ assert "run_in_background: false" in reason
+
+
+def test_missing_tool_input_is_treated_as_the_tool_default():
+ assert policy.check_tool_call("Agent", None, env={}).denied
+
+
+def test_env_escape_hatch_restores_backend_native_behavior():
+ env = {policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV: "1"}
+ assert policy.check_tool_call("Agent", {}, env=env).allowed
+ assert policy.check_tool_call("Workflow", {}, env=env).allowed
+ assert policy.native_background_tools_allowed(env) is True
+ # The advisory is part of the same policy, so it goes quiet too.
+ assert not policy.check_tool_call("Bash", {"run_in_background": True}, env=env).advice
+
+
+def test_blank_escape_hatch_does_not_disable_the_policy():
+ env = {policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV: " "}
+ assert policy.native_background_tools_allowed(env) is False
+ assert policy.check_tool_call("Agent", {}, env=env).denied
+
+
+def test_always_session_only_names_are_a_subset_of_the_policy():
+ covered = set(policy.session_only_background_tool_names())
+ assert set(policy.ALWAYS_SESSION_ONLY_TOOL_NAMES) <= covered
+ # Names with a legitimate non-background form must not be blocked by name,
+ # and an advisory-only tool must never reach a deny list at all.
+ assert "Agent" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+ assert "CronCreate" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+ assert "Bash" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+
+
+def test_name_only_fallback_never_strands_a_running_loop():
+ # `ScheduleWakeup {"stop": true}` is the only way to end a dynamic loop.
+ # A name-level block cannot see the argument, so listing the tool there
+ # would make an already-running loop unstoppable on older SDKs.
+ assert "ScheduleWakeup" not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES
+ assert policy.check_tool_call("ScheduleWakeup", {"stop": True}, env={}).allowed
+
+
[email protected]("name", policy.ALWAYS_SESSION_ONLY_TOOL_NAMES)
+def test_name_only_fallback_entries_are_denied_under_every_input(name):
+ # A name-level block is faithful only if no input to that tool is allowed.
+ for tool_input in ({}, {"stop": True}, {"durable": True}, {"run_in_background": False}):
+ assert policy.check_tool_call(name, tool_input, env={}).denied
+
+
+# --------------------------------------------------------------------------
+# injected prompt
+# --------------------------------------------------------------------------
+
+
+def test_shared_prompt_module_has_no_top_level_claude_import():
+ # `core/system_prompt_injection.py` is imported by every backend adapter,
+ # and the Codex adapter is loaded under a stub `modules` namespace where a
+ # Claude-only import raises at module scope. A top-level import here breaks
+ # collection of that suite outright, so the dependency stays inside the
+ # Claude branch of the selector.
+ import ast
+
+ source = Path(spi.__file__).read_text(encoding="utf-8")
+ for node in ast.parse(source).body: # module scope only, not nested
+ if isinstance(node, ast.ImportFrom):
+ assert not (node.module or "").startswith("modules.claude"), (
+ f"top-level import of {node.module} makes this module "
+ "unloadable for non-Claude backends"
+ )
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ assert not alias.name.startswith("modules.claude")
+
+
+def test_prompt_describes_enforcement_when_the_policy_is_active(monkeypatch):
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ section = spi._build_tool_policy_section("claude")
+ assert "is blocked at the tool layer" in section
+ assert "are all denied" in section
+
+
+def test_prompt_admits_partial_enforcement_without_argument_aware_hooks(monkeypatch):
+ # The name-only fallback cannot inspect arguments, so it blocks Workflow and
+ # nothing else. Claiming full denial would stop the agent from self-policing
+ # exactly the calls no gate is covering.
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: False)
+ section = spi._build_tool_policy_section("claude")
+ assert "only partly blocked" in section
+ assert "A native multi-agent workflow is denied outright" in section
+ assert "are **not** stopped here" in section
+ assert "is blocked at the tool layer" not in section
+ assert "are all denied" not in section
+
+
+def test_hookless_prompt_names_every_tool_the_name_list_leaves_open(monkeypatch):
+ # Whatever `check_tool_call` can deny but the name-only list does not carry
+ # is unguarded on this path, and the prompt is the only thing left telling
+ # the agent so. `Bash` is exempt because the policy never denies it.
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: False)
+ section = spi._build_tool_policy_section("claude")
+ unguarded = {
+ name
+ for name in policy.session_only_background_tool_names()
+ if name not in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES and name != "Bash"
+ }
+ assert unguarded == {"Agent", "ScheduleWakeup", "CronCreate"}
+ described = {
+ "Agent": "background subagent",
+ "ScheduleWakeup": "self-scheduled wakeup",
+ "CronCreate": "non-durable in-session cron job",
+ }
+ for name in unguarded:
+ assert described[name] in section, f"{name} is unguarded but unmentioned"
+
+
+def test_prompt_claims_no_gate_on_backends_that_install_none(monkeypatch):
+ # Only the Claude session handler installs the hook, so hook availability in
+ # an importable SDK says nothing about a Codex or OpenCode session.
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ for backend in ("codex", "opencode", "unknown"):
+ section = spi._build_tool_policy_section(backend)
+ assert "is not gated in this runtime" in section
+ assert "blocked at the tool layer" not in section
+ assert "only partly blocked" not in section
+ assert "vibe watch add" in section
+
+
+def test_escape_hatch_outranks_hook_availability(monkeypatch):
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: False)
+ assert "is not blocked in this runtime" in spi._build_tool_policy_section("claude")
+
+
+def test_escape_hatch_does_not_reach_backends_it_cannot_affect(monkeypatch):
+ # The hatch turns off a gate only Claude installs, so on another backend it
+ # changes nothing. Letting the relaxed text win there would swap accurate
+ # ungated wording for Claude-specific tool claims.
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ for backend in ("codex", "opencode", "unknown"):
+ section = spi._build_tool_policy_section(backend)
+ assert "is not gated in this runtime" in section
+ assert "is not blocked in this runtime" not in section
+ assert policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV not in section
+
+
+def test_prompt_drops_the_block_claim_under_the_escape_hatch(monkeypatch):
+ # Enforcement is off here, so telling the agent these tools are denied
+ # would stop it from using what the operator deliberately re-enabled.
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ section = spi._build_tool_policy_section("claude")
+ assert "is not blocked in this runtime" in section
+ assert "blocked at the tool layer" not in section
+ assert "denied" not in section
+ # The Harness is still the default; only the enforcement claim changes.
+ assert "vibe agent run" in section
+ assert policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV in section
+
+
+def test_prompt_section_is_read_per_turn_not_at_import(monkeypatch):
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ monkeypatch.setattr(spi, "_claude_sdk_hooks_available", lambda: True)
+ before = spi._build_tool_policy_section("claude")
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+ assert spi._build_tool_policy_section("claude") != before
+
+
+# --------------------------------------------------------------------------
+# claude adapter
+# --------------------------------------------------------------------------
+
+
+class _Controller:
+ """Minimal stand-in for BaseHandler's controller dependency."""
+
+ def __init__(self):
+ self.config = object()
+ self.im_client = object()
+ self.settings_manager = object()
+ self.sessions = object()
+ self.session_manager = object()
+ self.claude_sessions = {}
+ self.receiver_tasks = {}
+ self.stored_session_mappings = {}
+
+
+def _handler() -> sh.SessionHandler:
+ return sh.SessionHandler(_Controller())
+
+
+def _run_guard(tool_name, tool_input):
+ return asyncio.run(
+ _handler()._guard_session_only_background_tools(
+ {"hook_event_name": "PreToolUse", "tool_name": tool_name, "tool_input": tool_input},
+ "toolu_test",
+ None,
+ )
+ )
+
+
+def test_guard_denies_a_background_subagent():
+ out = _run_guard("Agent", {"prompt": "go", "run_in_background": True})
+ specific = out["hookSpecificOutput"]
+ assert specific["hookEventName"] == "PreToolUse"
+ assert specific["permissionDecision"] == "deny"
+ assert "vibe agent run" in specific["permissionDecisionReason"]
+
+
+def test_guard_allows_a_synchronous_subagent():
+ assert _run_guard("Agent", {"prompt": "go", "run_in_background": False}) == {}
+
+
+def test_guard_allows_unrelated_tools():
+ assert _run_guard("Read", {"file_path": "/tmp/x"}) == {}
+
+
+def test_guard_stays_silent_on_a_foreground_shell():
+ assert _run_guard("Bash", {"command": "ls"}) == {}
+
+
+def test_guard_advises_on_a_background_shell_without_granting_permission():
+ out = _run_guard("Bash", {"command": "make", "run_in_background": True})
+ specific = out["hookSpecificOutput"]
+ assert specific["hookEventName"] == "PreToolUse"
+ assert "vibe watch add" in specific["additionalContext"]
+ # Injecting context must not double as an approval: an explicit "allow" here
+ # would override any permission hook the user configured for Bash.
+ assert "permissionDecision" not in specific
+
+
+def test_guard_never_raises_on_a_malformed_payload():
+ # A guard that throws would take the whole turn down with it.
+ out = asyncio.run(_handler()._guard_session_only_background_tools({}, None, None))
+ assert out == {}
+
+
+def test_hooks_are_wired_when_the_sdk_supports_them(monkeypatch):
+ captured = {}
+
+ class _HookMatcher:
+ def __init__(self, matcher=None, hooks=None, timeout=None):
+ captured["matcher"] = matcher
+ captured["hooks"] = hooks
+
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", True)
+ monkeypatch.setattr(sh, "HookMatcher", _HookMatcher)
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+
+ handler = _handler()
+ hooks = handler._build_claude_tool_policy_hooks()
+
+ assert list(hooks) == ["PreToolUse"]
+ assert set(captured["matcher"].split("|")) == set(policy.session_only_background_tool_names())
+ assert captured["hooks"] == [handler._guard_session_only_background_tools]
+ # The precise hook path owns enforcement, so nothing extra is denied by name.
+ assert handler._claude_disallowed_tools(hooks) == sh.CLAUDE_REMOTE_DISALLOWED_TOOLS
+
+
+def test_older_sdk_falls_back_to_a_name_level_deny_list(monkeypatch):
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", False)
+ monkeypatch.setattr(sh, "HookMatcher", None)
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+
+ handler = _handler()
+ assert handler._build_claude_tool_policy_hooks() is None
+
+ disallowed = handler._claude_disallowed_tools(None)
+ for name in sh.CLAUDE_REMOTE_DISALLOWED_TOOLS:
+ assert name in disallowed
+ for name in policy.ALWAYS_SESSION_ONLY_TOOL_NAMES:
+ assert name in disallowed
+ assert len(disallowed) == len(set(disallowed))
+
+
+def test_escape_hatch_disables_both_enforcement_paths(monkeypatch):
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", True)
+ monkeypatch.setenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, "1")
+
+ handler = _handler()
+ assert handler._build_claude_tool_policy_hooks() is None
+ assert handler._claude_disallowed_tools(None) == sh.CLAUDE_REMOTE_DISALLOWED_TOOLS
+
+
+def test_disallowed_tools_constant_is_not_mutated(monkeypatch):
+ monkeypatch.setattr(sh, "CLAUDE_SDK_HOOKS_AVAILABLE", False)
+ monkeypatch.delenv(policy.ALLOW_NATIVE_BACKGROUND_TOOLS_ENV, raising=False)
+ before = list(sh.CLAUDE_REMOTE_DISALLOWED_TOOLS)
+
+ _handler()._claude_disallowed_tools(None)
+
+ assert sh.CLAUDE_REMOTE_DISALLOWED_TOOLS == before
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 2ca410ae5..81ac9dc14 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -360,6 +360,12 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
with (
patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),
patch("core.show_git.show_git_checkpointing_active", return_value=True),
+ # The tool-policy paragraphs vary with SDK hook support, so pin it
+ # rather than let the installed SDK decide what this test asserts.
+ # Pinned to True on purpose: a Codex prompt must not inherit the
+ # Claude enforcement claim just because that SDK happens to be
+ # installed alongside it.
+ patch("core.system_prompt_injection._claude_sdk_hooks_available", return_value=True),
):
prompt = build_system_prompt_injection(
include_quick_replies=True,
@@ -396,6 +402,14 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("native workflow tools, backend-native skills", prompt)
self.assertIn("Do not default to backend-native automation just because the backend exposes it", prompt)
self.assertIn("Use backend-native config, skills, subagents, or workflow tools only when the user explicitly asks for backend-native behavior", prompt)
+ # This is a Codex session, and only the Claude session handler installs
+ # the tool-layer gate, so the prompt must claim no enforcement here even
+ # though the Claude SDK is importable (pinned above).
+ self.assertIn("Backend-native background work is not gated in this runtime", prompt)
+ self.assertNotIn("blocked at the tool layer", prompt)
+ self.assertNotIn("only partly blocked", prompt)
+ self.assertIn("Route that work through the Harness instead", prompt)
+ self.assertIn("Never detach with `nohup` or a trailing `&` for work whose result you need", prompt)
self.assertIn("what outcome is the user trying to secure", prompt)
self.assertIn("If the answer is an operating loop, build a Harness instead of only doing the visible step", prompt)
self.assertIn("### Mental model", prompt)