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(runtime): give Agent commands a managed ripgrep (#2428)

Call White6c33c09e8c17
diff --git a/.github/workflows/release-mirror.yml b/.github/workflows/release-mirror.yml
index 2e364bdd9..683664bd5 100644
--- a/.github/workflows/release-mirror.yml
+++ b/.github/workflows/release-mirror.yml
@@ -12,7 +12,8 @@ on:
- Build local-only Git runtime
types: [completed]
# Safety net for missed triggers and renamed workflows, and the trigger for
- # the other mirrored repositories' releases (askill, avault, tmux-builds).
+ # the other mirrored repositories' releases (askill, avault, tmux-builds,
+ # ripgrep).
schedule:
- cron: "41 * * * *"
workflow_dispatch:
diff --git a/core/agent_path.py b/core/agent_path.py
new file mode 100644
index 000000000..949ffd9ed
--- /dev/null
+++ b/core/agent_path.py
@@ -0,0 +1,25 @@
+"""The managed tools every backend puts on an Agent command's PATH."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, MutableMapping
+from pathlib import Path
+
+
+def prepend_managed_tools_to_path(
+ env: MutableMapping[str, str],
+ *,
+ base_env: Mapping[str, str],
+ working_dir: Path | str | None,
+) -> bool:
+ """Prepend verified Git, then the managed ripgrep, where the effective PATH lacks them.
+
+ Each tool follows its own module's rules; this is the one composition every
+ backend's command environment uses. Returns whether PATH changed.
+ """
+
+ from core import git_runtime, ripgrep_runtime
+
+ git_changed = git_runtime.prepend_vendored_git_to_path(env, base_env=base_env, working_dir=working_dir)
+ rg_changed = ripgrep_runtime.prepend_managed_ripgrep_to_path(env, base_env=base_env)
+ return git_changed or rg_changed
diff --git a/core/dependency_network.py b/core/dependency_network.py
index 98a6766b5..b56cda68f 100644
--- a/core/dependency_network.py
+++ b/core/dependency_network.py
@@ -39,6 +39,7 @@ RELEASE_MIRRORS = {
"https://github.com/avibe-bot/askill/releases/download/": "https://dl.avibe.bot/askill/releases/",
"https://github.com/avibe-bot/avault/releases/download/": "https://dl.avibe.bot/avault/releases/",
"https://github.com/tmux/tmux-builds/releases/download/": "https://dl.avibe.bot/tmux/releases/",
+ "https://github.com/BurntSushi/ripgrep/releases/download/": "https://dl.avibe.bot/ripgrep/releases/",
}
# Index into download_sources() of the source that last completed a download.
_preferred_source = 0
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 2ad82d7cc..a11129e0b 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -489,10 +489,10 @@ class SessionHandler(BaseHandler):
@staticmethod
def _claude_git_path_state(working_path: str) -> str:
- from core.git_runtime import prepend_vendored_git_to_path
+ from core.agent_path import prepend_managed_tools_to_path
env: dict[str, str] = {}
- prepend_vendored_git_to_path(
+ prepend_managed_tools_to_path(
env,
base_env=os.environ,
working_dir=working_path,
@@ -1774,7 +1774,7 @@ class SessionHandler(BaseHandler):
CLAUDE_SETTING_SOURCES,
build_claude_subprocess_env,
)
- from core.git_runtime import prepend_vendored_git_to_path
+ from core.agent_path import prepend_managed_tools_to_path
claude_env = build_claude_subprocess_env(claude_config)
if model_hub_launch is not None:
@@ -1787,7 +1787,7 @@ class SessionHandler(BaseHandler):
claude_cli_path=managed_skill_claude_cli_path(launch_config),
)
)
- prepend_vendored_git_to_path(
+ prepend_managed_tools_to_path(
claude_env,
base_env=os.environ,
working_dir=working_path,
diff --git a/core/ripgrep_runtime.py b/core/ripgrep_runtime.py
new file mode 100644
index 000000000..7a3a20c20
--- /dev/null
+++ b/core/ripgrep_runtime.py
@@ -0,0 +1,87 @@
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+from collections.abc import Mapping, MutableMapping
+from pathlib import Path
+
+from config import paths
+from core.managed_runtime import ManagedRuntimeManager, ManagedRuntimeSpec, env_flag_enabled
+from core.process_isolation import isolated_subprocess_kwargs
+
+
+_RIPGREP_SPEC = ManagedRuntimeSpec(
+ runtime_id="ripgrep",
+ manifest_resource="ripgrep_runtime_manifest.json",
+ version_field="ripgrep_version",
+ default_bin_path="rg",
+)
+
+
+class RipgrepRuntimeManager(ManagedRuntimeManager):
+ """Install and resolve the official ripgrep release Agent commands search with."""
+
+ def __init__(
+ self,
+ *,
+ runtime_dir: Path | None = None,
+ manifest_path: Path | str | None = None,
+ manifest_url: str | None = None,
+ offline: bool | None = None,
+ ) -> None:
+ super().__init__(
+ spec=_RIPGREP_SPEC,
+ runtime_dir=runtime_dir or paths.get_runtime_dir() / "ripgrep",
+ manifest_path=manifest_path or os.environ.get("VIBE_RIPGREP_MANIFEST_PATH"),
+ manifest_url=manifest_url if manifest_url is not None else os.environ.get("VIBE_RIPGREP_MANIFEST_URL"),
+ offline=env_flag_enabled("VIBE_RIPGREP_OFFLINE") if offline is None else offline,
+ )
+
+ def _binary_version(self, binary: Path | None) -> str | None:
+ return _probe_ripgrep_version(binary)
+
+
+def prepend_managed_ripgrep_to_path(
+ env: MutableMapping[str, str],
+ *,
+ base_env: Mapping[str, str],
+) -> bool:
+ """Prepend the verified managed ripgrep when the effective Agent PATH has no ``rg``.
+
+ PATH composition follows ``prepend_vendored_git_to_path``: a ``PATH`` key in
+ ``env`` wins even when empty, and only an absent key falls back to
+ ``base_env``. An ``rg`` the PATH already resolves is the user's and is kept.
+ A missing or unverifiable managed install leaves PATH unchanged.
+ """
+
+ current_path = env["PATH"] if "PATH" in env else base_env.get("PATH", "")
+ if current_path and shutil.which("rg", path=current_path):
+ return False
+ managed = RipgrepRuntimeManager().resolve_binary()
+ if managed is None:
+ return False
+ bin_dir = str(managed.parent)
+ env["PATH"] = bin_dir if not current_path else f"{bin_dir}{os.pathsep}{current_path}"
+ return True
+
+
+def _probe_ripgrep_version(binary: Path | None) -> str | None:
+ if binary is None:
+ return None
+ try:
+ proc = subprocess.run(
+ [str(binary), "--version"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ check=False,
+ **isolated_subprocess_kwargs(),
+ )
+ except Exception: # noqa: BLE001
+ return None
+ if proc.returncode != 0:
+ return None
+ # ``ripgrep 15.2.0 (rev e89fff89ac)``, then feature lines.
+ words = (proc.stdout or "").strip().split()
+ return words[1] if len(words) > 1 and words[0] == "ripgrep" else None
diff --git a/docs/plans/release-download-mirror.md b/docs/plans/release-download-mirror.md
index 18a0e4da8..9805b267f 100644
--- a/docs/plans/release-download-mirror.md
+++ b/docs/plans/release-download-mirror.md
@@ -35,11 +35,16 @@ Each mirrored repository owns one bucket root:
| `avibe-bot/askill` | `askill/` |
| `avibe-bot/avault` | `avault/` |
| `tmux/tmux-builds` | `tmux/` |
+| `BurntSushi/ripgrep` | `ripgrep/` |
`tmux/tmux-builds` is third-party: the ISC-licensed tmux builds the managed
tmux runtime pins. Its releases are mirrored like Avibe's own, with their
`LICENSES.tar.gz`.
+`BurntSushi/ripgrep` is third-party too, and only the releases that
+`vibe/ripgrep_runtime_manifest.json` pins or once pinned are mirrored. See
+`docs/plans/ripgrep-runtime.md`.
+
- `https://dl.avibe.bot/<root>releases/<tag>/<asset>` is byte-identical to
`https://github.com/<repository>/releases/download/<tag>/<asset>`.
Clients derive the mirror URL only by substituting that prefix, which keeps
@@ -96,6 +101,12 @@ tmux runtime pins. Its releases are mirrored like Avibe's own, with their
- tmux-builds keeps no prereleases. Its `preview` prerelease is rebuilt in
place, changing bytes under unchanged asset names, which the reconciler must
treat as published bytes changing.
+- ripgrep keeps every release a manifest has pinned, and nothing else; its
+ root only grows. The mirror is those releases' backup. When GitHub no longer
+ publishes a currently pinned archive with the manifest's size and digest, the
+ run fails before planning. A release an earlier manifest pinned stays in the
+ index and the bucket after the pin moves, because released Avibe versions
+ still name it.
- At the time of writing Avibe is 89 releases and about 19 GB, most of it the
desktop bundles in recent prereleases (about 0.7 GB each). askill adds 16
releases and about 7 GB, avault 5 releases and 0.04 GB, tmux-builds 5
@@ -148,8 +159,8 @@ Cloudflare configuration lives outside the repository. The expected state:
## Client downloads
-The managed git and tmux runtimes, the model hub engine, Show Runtime manifest
-archives, and the askill and avault binaries download through
+The managed git, tmux, and ripgrep runtimes, the model hub engine, Show
+Runtime manifest archives, and the askill and avault binaries download through
`core.dependency_network.fetch_to_path`:
- A mirrored repository's release URL without a query tries the mirror, then
diff --git a/docs/plans/ripgrep-runtime.md b/docs/plans/ripgrep-runtime.md
new file mode 100644
index 000000000..10c4f1d52
--- /dev/null
+++ b/docs/plans/ripgrep-runtime.md
@@ -0,0 +1,63 @@
+# Managed ripgrep Runtime
+
+## Background
+
+Vibey's system prompt, ported from Pi, told the model to "use bash for file
+operations like ls, rg, find". Vibey's commands run in a non-interactive bash
+with the service's PATH, which usually has no `rg`. A Claude Code shell snapshot
+may define `rg` as a zsh function, but that function never reaches Avibe's
+commands. In issue #2425 Vibey fell back to `git grep` after `rg` was not found.
+The prompt had stated a tool that did not exist.
+
+## Design
+
+- `vibe runtime prepare` installs the official ripgrep release through the
+ shared managed-runtime core, under
+ `~/.avibe/runtime/ripgrep/versions/<version>/<platform>/<fingerprint>/`. A
+ missing or failed ripgrep never fails `prepare --strict`.
+- `vibe/ripgrep_runtime_manifest.json` pins the upstream `BurntSushi/ripgrep`
+ release archives directly, as the tmux manifest does. Each archive carries its
+ size, its sha256 (matching both upstream's `.sha256` sidecar and GitHub's asset
+ digest), and the sha256 of the extracted `rg`. Linux uses the static musl
+ builds.
+- `core.agent_path.prepend_managed_tools_to_path` is the one PATH composition
+ that the Claude, Codex, OpenCode, and Vibey command environments use. It adds
+ verified Git under its existing rules, then the managed ripgrep only when the
+ effective PATH has no `rg`, so a user's own ripgrep keeps precedence, as for
+ Git. An absent or unverifiable install leaves PATH unchanged.
+- Vibey's bash rule names `rg` only when the Turn's composed PATH finds it, and
+ `grep` otherwise. That PATH changes only when the service's PATH or the
+ installed tools change, so a Session's system prompt stays byte-stable and
+ cacheable between Turns. No per-Session state is kept.
+
+## Availability
+
+Avibe cannot republish into or restore a third-party release, so the download
+mirror is the backup. Under the `ripgrep/` root, `scripts/release_mirror.py`
+mirrors only releases a manifest pins. It fails the hourly run if GitHub no
+longer publishes a pinned archive with the manifest's size and digest. Clients
+try the mirror first, so they still get the verified copy. The root only grows:
+when the manifest moves to a newer ripgrep, the earlier pinned release stays
+mirrored, because released Avibe versions still install from it. Mirroring all
+of ripgrep's releases would not work: releases up to 14.x have no GitHub
+digests, which the mirror requires.
+
+## Scope
+
+- The platforms are darwin and linux on arm64 and x64, as for the Git runtime.
+ Windows reports `ripgrep_platform_unsupported` for these reasons:
+ - The managed-runtime core extracts only `.tar.gz`, and upstream ships a
+ Windows `.zip`.
+ - Vibey's job host does not run commands on Windows.
+ - The Codex, Claude Code, and OpenCode CLIs bundle their own ripgrep.
+- ripgrep is not a `vibe doctor` dependency or repair target. Its absence only
+ changes the prompt line, and `vibe runtime prepare` installs it again.
+- To move to a newer ripgrep, update the manifest. The mirror then adds the new
+ pinned release and keeps the earlier one.
+- The upstream 15.2.0 `x86_64-unknown-linux-musl` binary is the artifact named
+ in ripgrep issue #3494. That issue is an occasional SIGSEGV during very large,
+ highly concurrent searches, which its analysis traces to a Linux kernel
+ page-table bug, and the same bytes ship inside Codex. The release has no
+ x86_64 glibc archive, and a glibc build would also tie the binary to the
+ host's glibc, so the static musl build stays. A crash fails that one search
+ command, not the Turn.
diff --git a/docs/release.md b/docs/release.md
index a1978bfc1..f0c65146e 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -32,7 +32,9 @@ must include an installable wheel containing `ui/dist` and
Published managed-runtime manifests are availability contracts. Keep their
release URLs under the scheduled manifest-verified backup/recovery guard.
Publish replacement assets before changing a pinned manifest so the guard never
-restores bytes from a different release.
+restores bytes from a different release. A manifest that pins a third-party
+release that Avibe cannot republish (ripgrep) relies on the download mirror as
+that guard: the mirror holds the pinned release, verified against the manifest.
## Download mirror
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 4a1ae7167..c66eb4089 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -3193,7 +3193,7 @@ class CodexAgent(BaseAgent):
``process_env`` is the environment of the app-server that runs the
turn, which its shell inherits; see ``_process_environment``.
"""
- from core.git_runtime import prepend_vendored_git_to_path
+ from core.agent_path import prepend_managed_tools_to_path
env = self._caller_env_for_request(request)
runtime_env = process_env
@@ -3206,13 +3206,13 @@ class CodexAgent(BaseAgent):
if env:
env_script_path = self._caller_env_script_path(request)
set_env.update({**env, "BASH_ENV": str(env_script_path)})
- git_path_changed = prepend_vendored_git_to_path(
+ path_changed = prepend_managed_tools_to_path(
set_env,
base_env=runtime_env,
working_dir=getattr(request, "working_path", None),
)
git_path_state = set_env["PATH"] if "PATH" in set_env else runtime_env.get("PATH", "")
- path_managed = had_path or git_path_changed or force_path
+ path_managed = had_path or path_changed or force_path
if force_path:
set_env["PATH"] = git_path_state
if not env and not path_managed:
@@ -3223,11 +3223,11 @@ class CodexAgent(BaseAgent):
return git_path_state, path_managed
def _git_path_state_for_request(self, request: AgentRequest, process_env: Mapping[str, str]) -> str:
- from core.git_runtime import prepend_vendored_git_to_path
+ from core.agent_path import prepend_managed_tools_to_path
runtime_env = process_env
env: dict[str, str] = {}
- prepend_vendored_git_to_path(
+ prepend_managed_tools_to_path(
env,
base_env=runtime_env,
working_dir=getattr(request, "working_path", None),
diff --git a/modules/agents/opencode/caller_context.py b/modules/agents/opencode/caller_context.py
index 798d337a6..497996954 100644
--- a/modules/agents/opencode/caller_context.py
+++ b/modules/agents/opencode/caller_context.py
@@ -221,7 +221,7 @@ def bind_session(
session record the conversation it came from.
"""
- from core.git_runtime import prepend_vendored_git_to_path
+ from core.agent_path import prepend_managed_tools_to_path
session_id = str(opencode_session_id or "").strip()
if not session_id:
@@ -234,7 +234,7 @@ def bind_session(
env = caller.to_env() if caller is not None else {}
if extra_env:
env.update((str(key), str(value)) for key, value in extra_env.items() if str(key) and str(value))
- prepend_vendored_git_to_path(
+ prepend_managed_tools_to_path(
env,
base_env=base_env,
working_dir=working_dir,
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index c6f1234df..7a15c89fc 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -26,6 +26,7 @@ import asyncio
import logging
import os
import secrets
+import shutil
import time
from contextlib import asynccontextmanager
from dataclasses import dataclass, field, replace
@@ -526,7 +527,12 @@ class VibeyAgent(BaseAgent):
return HubModelRouter(resolve, self._providers, first=await resolve())
def _start_agent(self, turn: _Run, cwd: str, sections: str, environment: Mapping[str, str]) -> None:
- """The Turn's loop, over its router, tools, system prompt, and the environment its commands run in."""
+ """The Turn's loop, over its router, tools, system prompt, and the environment its commands run in.
+
+ The bash rule names ``rg`` only when that environment's PATH finds it. That PATH is the service's
+ PATH plus the installed managed tools, which change only on an install or upgrade, so a Session's
+ Turns keep one system prompt, which changes only when ripgrep's availability does.
+ """
request, session_id = turn.request, turn.session_id
suite = self._tools()
agent = Agent(
@@ -546,7 +552,8 @@ class VibeyAgent(BaseAgent):
# Job-backed tools receive the loop's tracking wrapper, so Stop kills foreground commands.
tools = mark_skill_loads(tuple(suite.create_tools(agent.jobs, self.media.image_sink(session_id))))
agent.set_tools(tools)
- agent.system = system_prompt([tool.spec.name for tool in tools], sections)
+ finds_rg = shutil.which("rg", path=environment.get("PATH", "")) is not None
+ agent.system = system_prompt([tool.spec.name for tool in tools], sections, rg=finds_rg)
turn.agent, turn.cwd = agent, cwd
async def _on_event(self, run: _Run, event: AgentEvent) -> None:
@@ -990,11 +997,11 @@ class VibeyAgent(BaseAgent):
The service's environment without its own caller provenance, then this Turn's
caller context (``AVIBE_SESSION_ID``, ``AVIBE_CALLER_*``, so a ``vibe`` call in a
command records where it came from), the managed-skill bindings, and verified
- Git on ``PATH``, composed as the Codex backend composes its shell environment.
+ Git and ripgrep on ``PATH``, composed as the Codex backend composes its shell environment.
The Model Hub gateway token stays in the adapter.
"""
from core.caller_context import caller_env_for_platform_payload, environment_without_caller_context
- from core.git_runtime import prepend_vendored_git_to_path
+ from core.agent_path import prepend_managed_tools_to_path
from core.managed_skills import (
managed_skill_claude_cli_path,
managed_skill_environment,
@@ -1017,7 +1024,7 @@ class VibeyAgent(BaseAgent):
claude_cli_path=managed_skill_claude_cli_path(self.config),
)
)
- prepend_vendored_git_to_path(environment, base_env=environment, working_dir=cwd or None)
+ prepend_managed_tools_to_path(environment, base_env=environment, working_dir=cwd or None)
return environment
def _environment(self, session_id: str) -> dict[str, EnvironmentValue]:
diff --git a/modules/agents/vibey/prompt.py b/modules/agents/vibey/prompt.py
index 7f29122a2..8ed98e11b 100644
--- a/modules/agents/vibey/prompt.py
+++ b/modules/agents/vibey/prompt.py
@@ -63,14 +63,17 @@ FORK_HISTORY = "the conversation above is that Session's history through context
FORK_NO_HISTORY = "it starts empty, before that Session's first finished Turn, so no history is inherited"
-def coding_prompt(tool_names: Iterable[str]) -> str:
- """Pi's preamble, tool list, and rules for the tools actually offered."""
+def coding_prompt(tool_names: Iterable[str], *, rg: bool) -> str:
+ """Pi's preamble, tool list, and rules for the tools actually offered.
+
+ ``rg`` is whether the Session's commands find ripgrep; the bash rule names it only then, and ``grep`` otherwise.
+ """
offered = set(tool_names)
names = [name for name in TOOL_ORDER if name in offered]
tools = "\n".join(f"- {name}: {TOOL_SNIPPETS[name]}" for name in names) or "(none)"
rules: list[str] = []
if "bash" in names:
- rules.append("Use bash for file operations like ls, rg, find")
+ rules.append(f"Use bash for file operations like ls, {'rg' if rg else 'grep'}, find")
for name in names:
rules.extend(TOOL_GUIDELINES.get(name, ()))
rules += ["Be concise in your responses", "Show file paths clearly when working with files", FINAL_REPLY_RULE]
@@ -83,8 +86,8 @@ def coding_prompt(tool_names: Iterable[str]) -> str:
)
-def system_prompt(tool_names: Iterable[str], avibe_sections: str) -> str:
- return "\n\n".join(part for part in (coding_prompt(tool_names), avibe_sections.strip()) if part)
+def system_prompt(tool_names: Iterable[str], avibe_sections: str, *, rg: bool) -> str:
+ return "\n\n".join(part for part in (coding_prompt(tool_names, rg=rg), avibe_sections.strip()) if part)
# --- environment block ---------------------------------------------------------
diff --git a/pyproject.toml b/pyproject.toml
index 5eb618317..bd6f4ce4d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -108,6 +108,7 @@ artifacts = [
"vibe/show_runtime_manifest.json",
"vibe/tmux_runtime_manifest.json",
"vibe/git_runtime_manifest.json",
+ "vibe/ripgrep_runtime_manifest.json",
"vibe/model_hub_runtime/cliproxyapi_manifest.json",
]
@@ -140,6 +141,7 @@ include = [
"vibe/show_runtime_manifest.json",
"vibe/tmux_runtime_manifest.json",
"vibe/git_runtime_manifest.json",
+ "vibe/ripgrep_runtime_manifest.json",
"vibe/model_hub_runtime/cliproxyapi_manifest.json",
"README.md",
"LICENSE",
diff --git a/scripts/release_mirror.py b/scripts/release_mirror.py
index c3d5337fc..151caa8d8 100644
--- a/scripts/release_mirror.py
+++ b/scripts/release_mirror.py
@@ -25,6 +25,7 @@ from typing import Any, Mapping, Sequence
from urllib.parse import quote
+REPO_ROOT = Path(__file__).resolve().parents[1]
# Bucket root of each mirrored repository. Avibe's own releases keep the bucket
# root, where their mirror URLs were first published.
REPOSITORIES = {
@@ -32,7 +33,14 @@ REPOSITORIES = {
"avibe-bot/askill": "askill/",
"avibe-bot/avault": "avault/",
"tmux/tmux-builds": "tmux/",
+ "BurntSushi/ripgrep": "ripgrep/",
}
+# Repositories mirrored only for the releases packaged managed-runtime
+# manifests pin. The mirror is those releases' backup: a pinned archive GitHub
+# no longer publishes with the manifest's bytes fails the run, and a release an
+# earlier manifest pinned stays, since released Avibe versions still name it.
+# ripgrep's older releases also carry no GitHub digest.
+PINNED_BY_MANIFEST = {"BurntSushi/ripgrep": REPO_ROOT / "vibe" / "ripgrep_runtime_manifest.json"}
# Repositories mirrored without prereleases. tmux-builds rebuilds its
# ``preview`` prerelease in place, changing bytes under unchanged asset names,
# which the mirror must treat as published bytes changing.
@@ -141,6 +149,23 @@ def parse_releases(
return releases
+def pinned_releases(
+ repository: str, payload: Sequence[Mapping[str, Any]], manifest_path: Path
+) -> list[Mapping[str, Any]]:
+ """Return the release the manifest pins, once GitHub proves every pinned archive."""
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ tag = manifest["release_tag"]
+ pinned = [item for item in payload if item["tag_name"] == tag and not item["draft"]]
+ if not pinned:
+ raise MirrorError(f"pinned release is not published: {repository} {tag}")
+ published = {raw["name"]: raw for raw in pinned[0]["assets"]}
+ for archive in manifest["archives"].values():
+ raw = published.get(archive["name"]) or {}
+ if raw.get("size") != archive["size"] or raw.get("digest") != f"sha256:{archive['sha256']}":
+ raise MirrorError(f"pinned archive differs from its manifest: {repository} {tag}/{archive['name']}")
+ return pinned
+
+
def select(releases: Sequence[Release], keep_prereleases: int) -> list[Release]:
"""Keep every full release and the newest prereleases, newest first."""
ordered = sorted(releases, key=lambda release: (release.published_at, release.tag), reverse=True)
@@ -185,13 +210,50 @@ def _indexed_digests(repository: str, index: bytes | None) -> dict[str, str]:
return {}
+def with_earlier_pins(repository: str, releases: Sequence[Release], index: bytes | None) -> list[Release]:
+ """Add the releases the previous index holds that the current pin no longer selects."""
+ selected = {release.tag for release in releases}
+ try:
+ document = json.loads(index) if index is not None else {"releases": []}
+ earlier = [
+ Release(
+ repository=repository,
+ tag=item["tag"],
+ prerelease=bool(item["prerelease"]),
+ published_at=item["published_at"],
+ commit=item["commit"],
+ assets=tuple(
+ Asset(
+ name=asset["name"],
+ size=int(asset["size"]),
+ sha256=asset["sha256"],
+ url=f"https://github.com/{repository}/releases/download/{quote(item['tag'])}/{quote(asset['name'])}",
+ content_type="application/octet-stream",
+ )
+ for asset in item["assets"]
+ ),
+ )
+ for item in document["releases"]
+ if item["tag"] not in selected
+ ]
+ except (ValueError, KeyError, TypeError) as exc:
+ # The objects stay either way (``plan`` never deletes a pinned root); only the index omits them.
+ print(f"warning: ignoring unreadable mirror index: {exc}", file=sys.stderr)
+ earlier = []
+ return sorted([*releases, *earlier], key=lambda release: (release.published_at, release.tag), reverse=True)
+
+
def plan(
repository: str,
releases: Sequence[Release],
objects: Mapping[str, int],
previous_index: bytes | None,
) -> Plan:
- """Compare the selected releases with the repository's ``releases/`` objects."""
+ """Compare the selected releases with the repository's ``releases/`` objects.
+
+ A manifest-pinned repository's root only grows: its objects are the backup of
+ every release a published manifest pinned.
+ """
if not releases:
raise MirrorError(f"GitHub returned no published releases for {repository}; refusing to reconcile")
prefix = release_prefix(repository)
@@ -208,7 +270,11 @@ def plan(
elif prior is None or objects.get(key) != asset.size:
# Only an object this job verified and indexed is trusted.
uploads.append((key, asset))
- deletions = sorted(key for key in objects if key.startswith(prefix) and key not in expected)
+ deletions = (
+ []
+ if repository in PINNED_BY_MANIFEST
+ else sorted(key for key in objects if key.startswith(prefix) and key not in expected)
+ )
return Plan(
uploads=tuple(uploads),
deletions=tuple(deletions),
@@ -301,10 +367,15 @@ class Bucket:
def reconcile(repository: str, bucket: Bucket, *, keep_prereleases: int, dry_run: bool) -> int:
- releases = select(parse_releases(repository, github_releases(repository), tag_commits(repository)), keep_prereleases)
+ payload = github_releases(repository)
+ if repository in PINNED_BY_MANIFEST:
+ payload = pinned_releases(repository, payload, PINNED_BY_MANIFEST[repository])
+ releases = select(parse_releases(repository, payload, tag_commits(repository)), keep_prereleases)
objects = bucket.objects()
key = index_key(repository)
previous_index = bucket.read(key) if key in objects else None
+ if repository in PINNED_BY_MANIFEST:
+ releases = with_earlier_pins(repository, releases, previous_index)
result = plan(repository, releases, objects, previous_index)
size = sum(asset.size for _, asset in result.uploads)
print(
diff --git a/tests/test_release_mirror.py b/tests/test_release_mirror.py
index a78821fcf..4c104fcf5 100644
--- a/tests/test_release_mirror.py
+++ b/tests/test_release_mirror.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import hashlib
+import json
import re
from dataclasses import replace
@@ -147,6 +148,96 @@ def test_tmux_builds_mirrors_its_full_releases_but_not_its_rebuilt_preview(monke
assert bucket.writes == ["tmux/releases/v3.6b/tmux-3.6b-linux-x86_64.tar.gz", "tmux/index/releases.json"]
+RIPGREP = "BurntSushi/ripgrep"
+
+
+def ripgrep_releases():
+ """GitHub's view of ripgrep: the release the runtime manifest pins, and an older one without digests."""
+ manifest = json.loads(mirror.PINNED_BY_MANIFEST[RIPGREP].read_text(encoding="utf-8"))
+ tag = manifest["release_tag"]
+ pinned = github_release(tag, published_at="2026-07-15T16:26:10Z", assets=("ripgrep.deb",), repository=RIPGREP)
+ for archive in manifest["archives"].values():
+ pinned["assets"].append({
+ "name": archive["name"], "size": archive["size"], "digest": f"sha256:{archive['sha256']}",
+ "content_type": "application/gzip", "browser_download_url": archive["url"],
+ })
+ older = github_release("14.1.1", published_at="2024-09-09T02:28:54Z", assets=("old.tgz",), repository=RIPGREP)
+ older["assets"][0]["digest"] = None
+ return manifest, [pinned, older]
+
+
+def reconcile_ripgrep(monkeypatch, items, bucket):
+ monkeypatch.setattr(mirror, "Bucket", lambda name, endpoint_url: bucket)
+ monkeypatch.setattr(mirror, "github_releases", lambda repository: items)
+ monkeypatch.setattr(mirror, "tag_commits", lambda repository: {item["tag_name"]: "0" * 40 for item in items})
+ monkeypatch.setattr(mirror, "download", lambda asset, destination: destination.write_bytes(b""))
+ return mirror.main(["--repository", RIPGREP, "--bucket", "avibe", "--endpoint-url", "https://r2.invalid"])
+
+
+def test_ripgrep_mirrors_only_the_release_its_runtime_manifest_pins(monkeypatch):
+ manifest, items = ripgrep_releases()
+ bucket = RecordingBucket({}, None)
+
+ assert reconcile_ripgrep(monkeypatch, items, bucket) == 0
+ tag = manifest["release_tag"]
+ archives = sorted(archive["name"] for archive in manifest["archives"].values())
+ assert bucket.writes == [
+ *(f"ripgrep/releases/{tag}/{name}" for name in sorted([*archives, "ripgrep.deb"])),
+ "ripgrep/index/releases.json",
+ ]
+
+
[email protected]("index_readable", [True, False])
+def test_ripgrep_keeps_the_releases_earlier_manifests_pinned(monkeypatch, index_readable):
+ manifest, items = ripgrep_releases()
+ (earlier,) = releases(
+ github_release("15.1.0", published_at="2025-10-22T13:00:26Z", assets=("ripgrep-15.1.0.tar.gz",),
+ repository=RIPGREP),
+ repository=RIPGREP,
+ )
+ (earlier_asset,) = earlier.assets
+ prior = mirror.render_index(RIPGREP, [earlier]) if index_readable else b"{not json"
+ written = {}
+
+ class IndexBucket(RecordingBucket):
+ def put(self, key, path, **metadata):
+ super().put(key, path, **metadata)
+ if key == "ripgrep/index/releases.json":
+ written.update(json.loads(path.read_bytes()))
+
+ bucket = IndexBucket({earlier.key(earlier_asset): earlier_asset.size, "ripgrep/index/releases.json": 1}, prior)
+
+ # Avibe builds released with the earlier manifest still download that release.
+ assert reconcile_ripgrep(monkeypatch, items, bucket) == 0
+ assert earlier.key(earlier_asset) not in bucket.writes
+ indexed = [release["tag"] for release in written["releases"]]
+ assert indexed == ([manifest["release_tag"], "15.1.0"] if index_readable else [manifest["release_tag"]])
+
+
+ "diverge",
+ [
+ lambda pinned: pinned.update(tag_name="15.2.1"),
+ lambda pinned: pinned["assets"].pop(),
+ lambda pinned: pinned["assets"][-1].update(digest=f"sha256:{'0' * 64}"),
+ ],
+ ids=["release-gone", "archive-gone", "archive-changed"],
+)
+def test_ripgrep_diverging_from_its_manifest_fails_without_touching_the_mirror(monkeypatch, capsys, diverge):
+ manifest, items = ripgrep_releases()
+ tag = manifest["release_tag"]
+ mirrored = {
+ f"ripgrep/releases/{tag}/{archive['name']}": archive["size"] for archive in manifest["archives"].values()
+ }
+ bucket = RecordingBucket({**mirrored, "ripgrep/index/releases.json": 1}, b"{}")
+ diverge(items[0])
+
+ # The mirror keeps the verified copy clients try first; the failing run is the alarm.
+ assert reconcile_ripgrep(monkeypatch, items, bucket) == 1
+ assert bucket.writes == []
+ assert "error: BurntSushi/ripgrep: pinned" in capsys.readouterr().err
+
+
def test_a_completed_reconcile_is_a_no_op_on_the_next_run():
selected = releases(
github_release("v1.0.0", published_at="2026-01-01T00:00:00Z", assets=("a.tgz", "b+local.whl")),
diff --git a/tests/test_ripgrep_runtime.py b/tests/test_ripgrep_runtime.py
new file mode 100644
index 000000000..66f24aaf0
--- /dev/null
+++ b/tests/test_ripgrep_runtime.py
@@ -0,0 +1,142 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import stat
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from core import managed_runtime
+from core.agent_path import prepend_managed_tools_to_path
+from core.ripgrep_runtime import RipgrepRuntimeManager, prepend_managed_ripgrep_to_path
+
+UPSTREAM = "https://github.com/BurntSushi/ripgrep/releases/download"
+
+
+def install_test_ripgrep(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, tamper: str | None = None) -> dict:
+ """Install a stand-in ``rg`` through a test manifest the default manager also reads."""
+
+ stem = "ripgrep-15.2.0-test"
+ binary = tmp_path / "archive-root" / stem / "rg"
+ binary.parent.mkdir(parents=True)
+ binary.write_text('#!/bin/sh\necho "ripgrep 15.2.0 (rev test)"\n', encoding="utf-8")
+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)
+ archive = tmp_path / f"{stem}.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ tar.add(binary, arcname=f"{stem}/rg")
+ entry = {
+ "name": archive.name,
+ "url": archive.as_uri(),
+ "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),
+ "binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
+ "size": archive.stat().st_size,
+ "bin_path": f"{stem}/rg",
+ }
+ if tamper is not None:
+ entry[tamper] = "0" * 64
+ manifest = tmp_path / "ripgrep_runtime_manifest.json"
+ manifest.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "ripgrep_version": "15.2.0",
+ "source": "test",
+ "release_tag": "15.2.0",
+ "archives": {managed_runtime.runtime_platform_tag(): entry},
+ }
+ ),
+ encoding="utf-8",
+ )
+ # The runtime installs under the test's own AVIBE_HOME (conftest).
+ monkeypatch.setenv("VIBE_RIPGREP_MANIFEST_PATH", str(manifest))
+ return RipgrepRuntimeManager().ensure()
+
+
+def test_packaged_manifest_pins_the_official_four_platform_release(tmp_path: Path) -> None:
+ manifest = RipgrepRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)._load_manifest(
+ allow_network=False
+ )
+
+ assert manifest is not None
+ assert manifest.runtime_version == manifest.payload["release_tag"] == "15.2.0"
+ targets = {
+ "darwin-arm64": "aarch64-apple-darwin",
+ "darwin-x64": "x86_64-apple-darwin",
+ "linux-arm64": "aarch64-unknown-linux-musl",
+ "linux-x64": "x86_64-unknown-linux-musl",
+ }
+ assert set(manifest.archives) == set(targets)
+ for platform_tag, archive in manifest.archives.items():
+ stem = f"ripgrep-15.2.0-{targets[platform_tag]}"
+ assert archive.name == f"{stem}.tar.gz"
+ assert archive.url == f"{UPSTREAM}/15.2.0/{archive.name}"
+ assert archive.bin_path == f"{stem}/rg"
+ assert archive.size is not None and archive.size > 0
+ assert re.fullmatch(r"[0-9a-f]{64}", archive.sha256)
+ assert re.fullmatch(r"[0-9a-f]{64}", archive.binary_sha256 or "")
+
+
+ ("tamper", "reason"),
+ (
+ (None, None),
+ ("sha256", "ripgrep_archive_checksum_mismatch"),
+ ("binary_sha256", "ripgrep_binary_checksum_mismatch"),
+ ),
+)
+def test_install_accepts_only_the_bytes_the_manifest_pins(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, tamper: str | None, reason: str | None
+) -> None:
+ result = install_test_ripgrep(tmp_path, monkeypatch, tamper=tamper)
+
+ assert result.get("reason") == reason
+ resolved = RipgrepRuntimeManager().resolve_binary()
+ if reason is None:
+ assert result["ok"] is True and result["version"] == "15.2.0"
+ assert resolved == Path(result["path"]) and resolved.name == "rg"
+ else:
+ assert result["ok"] is False and resolved is None
+
+
+def test_agent_path_gains_managed_rg_only_where_path_finds_none(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ installed = Path(install_test_ripgrep(tmp_path, monkeypatch)["path"])
+ without_rg = tmp_path / "bin-without-rg"
+ without_rg.mkdir()
+ with_rg = tmp_path / "bin-with-rg"
+ with_rg.mkdir()
+ (with_rg / "rg").write_text("#!/bin/sh\n", encoding="utf-8")
+ (with_rg / "rg").chmod(0o755)
+
+ # Absent key: the base environment's PATH, behind the managed rg.
+ env: dict[str, str] = {}
+ assert prepend_managed_ripgrep_to_path(env, base_env={"PATH": str(without_rg)}) is True
+ assert env["PATH"] == f"{installed.parent}{os.pathsep}{without_rg}"
+
+ # The user's own rg on PATH is kept.
+ env = {"PATH": str(with_rg)}
+ assert prepend_managed_ripgrep_to_path(env, base_env={"PATH": str(without_rg)}) is False
+ assert env == {"PATH": str(with_rg)}
+
+ # Every backend composes Git and ripgrep through one call.
+ env = {"PATH": str(without_rg)}
+ assert prepend_managed_tools_to_path(env, base_env={}, working_dir=tmp_path) is True
+ assert env["PATH"].split(os.pathsep)[0] == str(installed.parent)
+
+
+def test_agent_path_is_unchanged_without_a_verified_managed_rg(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ installed = Path(install_test_ripgrep(tmp_path, monkeypatch)["path"])
+ installed.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8")
+ without_rg = tmp_path / "bin-without-rg"
+ without_rg.mkdir()
+ env = {"PATH": str(without_rg)}
+
+ assert prepend_managed_ripgrep_to_path(env, base_env={}) is False
+ assert env == {"PATH": str(without_rg)}
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 4a89aaac8..bec305c80 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -68,6 +68,7 @@ def _stub_runtime_prepare_dependencies(
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", fake_avault)
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", fake_tmux)
monkeypatch.setattr(cli, "_ensure_git_during_prepare", fake_git)
+ monkeypatch.setattr(cli, "_ensure_ripgrep_during_prepare", lambda **_kwargs: {"ok": True})
return calls
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 5511b8c7d..5e242bf04 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -3742,6 +3742,7 @@ def test_runtime_prepare_strict_does_not_report_policy_skip_as_ready(monkeypatch
monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
+ monkeypatch.setattr(cli, "_ensure_ripgrep_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_model_hub_engine_during_prepare", lambda **_kwargs: {"ok": True})
@@ -3783,6 +3784,7 @@ def test_runtime_prepare_reports_cpa_failure_without_blocking_avibe_upgrade(
monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
+ monkeypatch.setattr(cli, "_ensure_ripgrep_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(
cli,
@@ -3849,6 +3851,7 @@ def test_runtime_prepare_localizes_cpa_output(
monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
+ monkeypatch.setattr(cli, "_ensure_ripgrep_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(
cli,
@@ -3874,6 +3877,55 @@ def test_runtime_prepare_localizes_cpa_output(
assert "Model Hub engine" not in captured.out + captured.err
+ ("ripgrep_result", "expected", "stream"),
+ (
+ ({"ok": True, "changed": True}, "ripgrep 已安装。", "out"),
+ ({"ok": True, "changed": False}, "ripgrep 已就绪。", "out"),
+ (
+ {"ok": False, "reason": "ripgrep_platform_unsupported"},
+ "ripgrep 尚未就绪:ripgrep_platform_unsupported",
+ "err",
+ ),
+ ),
+)
+def test_strict_runtime_prepare_reports_ripgrep_without_requiring_it(
+ monkeypatch,
+ capsys,
+ ripgrep_result,
+ expected,
+ stream,
+):
+ manager = SimpleNamespace(
+ prepare=lambda **_kwargs: {
+ "ok": True,
+ "policy": {"state": "allowed", "reason": None},
+ "install": {"state": "installed", "reason": None},
+ "runtime": {"state": "unchecked", "reason": None},
+ "status": {"install": {"state": "installed", "install_dir": None}},
+ }
+ )
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda _args: manager)
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
+ monkeypatch.setattr(cli, "_ensure_ripgrep_during_prepare", lambda **_kwargs: ripgrep_result)
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
+ monkeypatch.setattr(cli, "_ensure_model_hub_engine_during_prepare", lambda **_kwargs: {"ok": True})
+
+ # Agents fall back to grep without it, so it never fails an install or upgrade.
+ assert (
+ cli.cmd_runtime(
+ SimpleNamespace(runtime_command="prepare", offline=False, force=False, json=False, strict=True)
+ )
+ == 0
+ )
+
+ captured = capsys.readouterr()
+ assert expected in getattr(captured, stream)
+
+
def test_runtime_prepare_force_does_not_report_explicit_command_as_replaced(monkeypatch, capsys):
manager = SimpleNamespace(
prepare=lambda **_kwargs: {
@@ -3892,6 +3944,7 @@ def test_runtime_prepare_force_does_not_report_explicit_command_as_replaced(monk
monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_tmux_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_git_during_prepare", lambda **_kwargs: {"ok": True, "mode": "system"})
+ monkeypatch.setattr(cli, "_ensure_ripgrep_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda **_kwargs: {"ok": True})
monkeypatch.setattr(cli, "_ensure_model_hub_engine_during_prepare", lambda **_kwargs: {"ok": True})
@@ -4044,8 +4097,8 @@ def test_runtime_clean_json_keeps_nested_failure_payload_and_exits_nonzero(monke
@pytest.mark.parametrize(
("language", "consumer_scope", "failure_contract"),
[
- ("en", "Show, Git, Model Hub, and tmux", "exit nonzero if any cleanup fails"),
- ("zh", "Show、Git、Model Hub 和 tmux", "任一清理失败时以非零状态退出"),
+ ("en", "Show, Git, Model Hub, tmux, and ripgrep", "exit nonzero if any cleanup fails"),
+ ("zh", "Show、Git、Model Hub、tmux 和 ripgrep", "任一清理失败时以非零状态退出"),
],
)
def test_runtime_clean_help_names_consumers_and_failure_exit(
@@ -4693,7 +4746,7 @@ def test_shutdown_intent_rejects_stale_payload(tmp_path, monkeypatch):
assert runtime.consume_shutdown_intent(12345, signal.SIGTERM) is None
[email protected]("consumer", ["model-hub", "tmux"])
[email protected]("consumer", ["model-hub", "tmux", "ripgrep"])
def test_runtime_clean_reclaims_each_shared_consumer_in_preview_and_real_run(
monkeypatch,
capsys,
@@ -4707,13 +4760,20 @@ def test_runtime_clean_reclaims_each_shared_consumer_in_preview_and_real_run(
runtime_dir=tmp_path / "model-hub-runtime",
offline=True,
)
- else:
+ elif consumer == "tmux":
from core.tmux_runtime import TmuxRuntimeManager
manager = TmuxRuntimeManager(
runtime_dir=tmp_path / "tmux-runtime",
offline=True,
)
+ else:
+ from core.ripgrep_runtime import RipgrepRuntimeManager
+
+ manager = RipgrepRuntimeManager(
+ runtime_dir=tmp_path / "ripgrep-runtime",
+ offline=True,
+ )
from core.managed_runtime import runtime_platform_tag
@@ -4807,7 +4867,7 @@ def test_runtime_clean_reclaims_each_shared_consumer_in_preview_and_real_run(
def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatch):
- from core import tmux_runtime
+ from core import ripgrep_runtime, tmux_runtime
from vibe.model_hub_runtime import installer as model_hub_installer
calls = []
@@ -4835,6 +4895,7 @@ def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatc
"get_tmux_runtime_manager",
lambda: FakeManager("tmux"),
)
+ monkeypatch.setattr(ripgrep_runtime, "RipgrepRuntimeManager", lambda: FakeManager("ripgrep"))
results = cli._clean_managed_runtime_consumers(keep_previous=2, dry_run=True)
@@ -4842,11 +4903,13 @@ def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatc
"git",
"model_hub_engine",
"tmux",
+ "ripgrep",
]
assert calls == [
("git", 2, True),
("model_hub_engine", 2, True),
("tmux", 2, True),
+ ("ripgrep", 2, True),
]
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 37370b8b5..fbd7571af 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -1493,6 +1493,26 @@ async def test_the_system_prompt_lists_every_tool_the_run_offers(engine, session
assert "- Only your final reply is reliably shown to the user; put anything the user must see in it" in system
[email protected]("finds_rg", (True, False))
+async def test_the_bash_rule_names_rg_only_when_the_turns_commands_find_it(
+ engine, session, tmp_path, published, monkeypatch, finds_rg
+) -> None:
+ # The service's PATH, as the Turn's commands get it; no managed rg is installed.
+ service_bin = tmp_path / "service-bin"
+ service_bin.mkdir()
+ if finds_rg:
+ (service_bin / "rg").write_text("#!/bin/sh\n", encoding="utf-8")
+ (service_bin / "rg").chmod(0o755)
+ monkeypatch.setenv("PATH", str(service_bin))
+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]], tools=[FakeTool("bash")])
+
+ await harness.agent.handle_message(harness.request("find the TODOs"))
+
+ system = harness.provider.requests[0].system
+ assert ("- Use bash for file operations like ls, rg, find" in system) is finds_rg
+ assert ("- Use bash for file operations like ls, grep, find" in system) is not finds_rg
+
+
async def test_the_system_prompt_offers_no_computer_use_it_cannot_call(
engine, session, tmp_path, published, monkeypatch
) -> None:
@@ -2038,6 +2058,29 @@ async def test_a_turn_runs_bash_through_the_real_job_host(engine, session, tmp_p
assert "hi from bash" in str(harness.provider.requests[1].messages[-1])
+async def test_a_turns_bash_runs_the_managed_rg_when_the_service_path_has_none(
+ engine, session, tmp_path, published, monkeypatch
+) -> None:
+ from tests.test_ripgrep_runtime import install_test_ripgrep
+
+ assert install_test_ripgrep(tmp_path / "ripgrep", monkeypatch)["ok"]
+ service_bin = tmp_path / "service-bin"
+ service_bin.mkdir()
+ monkeypatch.setenv("PATH", str(service_bin))
+ call = ToolCallBlock(id="call_rg", name="bash", arguments={"command": "rg --version"})
+ harness = _Harness(
+ engine, tmp_path, "avibe",
+ [[Done(assistant("", calls=(call,)))], [Done(assistant("done"))]],
+ suite=local_tool_suite(str(tmp_path / "jobs")),
+ )
+
+ await harness.agent.handle_message(harness.request("which ripgrep do you have"))
+
+ result = (await harness.context_rows())[2].message
+ assert not result.is_error and "ripgrep 15.2.0" in result.content[0].text
+ assert "- Use bash for file operations like ls, rg, find" in harness.provider.requests[0].system
+
+
async def test_bash_runs_with_the_turns_caller_environment(engine, session, tmp_path, published) -> None:
from core.caller_context import AVIBE_CALLER_BACKEND_ENV, AVIBE_SESSION_ID_ENV, CALLER_CONTEXT_ENV_NAMES
diff --git a/vibe/cli.py b/vibe/cli.py
index 401399f82..58e720825 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -15986,6 +15986,7 @@ def cmd_runtime(args) -> int:
askill = _ensure_askill_during_prepare(offline=bool(offline), force=force)
tmux = _ensure_tmux_during_prepare(offline=bool(offline), force=force)
git = _ensure_git_during_prepare(offline=offline, force=force)
+ ripgrep = _ensure_ripgrep_during_prepare(offline=offline, force=force)
avault = _ensure_avault_during_prepare(offline=bool(offline), force=force)
model_hub_engine = _ensure_model_hub_engine_during_prepare(
offline=bool(offline),
@@ -15996,6 +15997,7 @@ def cmd_runtime(args) -> int:
payload["model_hub_engine"] = model_hub_engine
payload["tmux"] = tmux
payload["git"] = git
+ payload["ripgrep"] = ripgrep
install = payload.get("install") if isinstance(payload.get("install"), dict) else {}
policy = payload.get("policy") if isinstance(payload.get("policy"), dict) else {}
runtime_prepared = bool(payload.get("ok"))
@@ -16091,6 +16093,22 @@ def cmd_runtime(args) -> int:
f"git runtime not ready: {git.get('message') or git.get('reason') or 'install failed'}",
file=sys.stderr,
)
+ if ripgrep.get("ok"):
+ print(
+ i18n_t(
+ "runtime.prepare.ripgrepInstalled" if ripgrep.get("changed") else "runtime.prepare.ripgrepReady",
+ language,
+ )
+ )
+ else:
+ print(
+ i18n_t(
+ "runtime.prepare.ripgrepNotReady",
+ language,
+ reason=ripgrep.get("message") or ripgrep.get("reason") or "install failed",
+ ),
+ file=sys.stderr,
+ )
strict_ok = runtime_prepared and _git_prepare_satisfies_strict(git)
return 1 if getattr(args, "strict", False) and not strict_ok else 0
if command == "clean":
@@ -16295,6 +16313,17 @@ def _ensure_git_during_prepare(offline: bool | None = None, force: bool = False)
return {"ok": False, "message": str(exc)}
+def _ensure_ripgrep_during_prepare(offline: bool | None = None, force: bool = False) -> dict:
+ """Prepare the managed ripgrep for Agent commands; its absence never fails prepare."""
+
+ try:
+ from core.ripgrep_runtime import RipgrepRuntimeManager
+
+ return RipgrepRuntimeManager(offline=offline).ensure(force=force)
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": str(exc)}
+
+
def _format_byte_size(size: int) -> str:
if size < 1024:
return f"{size} B"
@@ -16308,6 +16337,7 @@ def _format_byte_size(size: int) -> str:
def _managed_runtime_cleaners() -> tuple[tuple[str, Callable[..., dict[str, Any]]], ...]:
"""Return the shared-runtime cleanup passes in stable output order."""
+ from core.ripgrep_runtime import RipgrepRuntimeManager
from core.tmux_runtime import get_tmux_runtime_manager
from vibe.model_hub_runtime.installer import EngineRuntimeManager
@@ -16324,10 +16354,17 @@ def _managed_runtime_cleaners() -> tuple[tuple[str, Callable[..., dict[str, Any]
dry_run=dry_run,
)
+ def clean_ripgrep(*, keep_previous: int, dry_run: bool) -> dict[str, Any]:
+ return RipgrepRuntimeManager().clean(
+ keep_previous=keep_previous,
+ dry_run=dry_run,
+ )
+
return (
("git", _clean_git_runtime),
("model_hub_engine", clean_model_hub),
("tmux", clean_tmux),
+ ("ripgrep", clean_ripgrep),
)
@@ -16388,6 +16425,7 @@ def _managed_runtime_label(runtime_id: str) -> str:
"git": "Git Runtime",
"model_hub_engine": "Model Hub Runtime",
"tmux": "tmux Runtime",
+ "ripgrep": "ripgrep Runtime",
}
return labels.get(runtime_id, runtime_id.replace("-", " ").replace("_", " ").title())
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 377ee5c8f..bcbe71a48 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1075,10 +1075,13 @@
"modelHubEngineSkipped": "Model Hub engine: skipped ({reason}).",
"modelHubEngineInstalled": "Model Hub engine installed.",
"modelHubEngineReady": "Model Hub engine ready.",
- "modelHubEngineNotReady": "Model Hub engine not ready: {reason}"
+ "modelHubEngineNotReady": "Model Hub engine not ready: {reason}",
+ "ripgrepInstalled": "ripgrep installed.",
+ "ripgrepReady": "ripgrep ready.",
+ "ripgrepNotReady": "ripgrep not ready: {reason}"
},
"clean": {
- "commandHelp": "Remove stale Show, Git, Model Hub, and tmux runtime installs and archives; exit nonzero if any cleanup fails.",
+ "commandHelp": "Remove stale Show, Git, Model Hub, tmux, and ripgrep runtime installs and archives; exit nonzero if any cleanup fails.",
"dryRunHelp": "Report stale archives and cache entries without removing anything.",
"wouldRemoveItems": "Would remove {count} Show Runtime cache item(s).",
"wouldRemoveArchives": "Would remove {count} downloaded Show Runtime archive(s) ({size}).",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index ce156eea9..856833247 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1075,10 +1075,13 @@
"modelHubEngineSkipped": "Model Hub 引擎:已跳过({reason})。",
"modelHubEngineInstalled": "Model Hub 引擎已安装。",
"modelHubEngineReady": "Model Hub 引擎已就绪。",
- "modelHubEngineNotReady": "Model Hub 引擎尚未就绪:{reason}"
+ "modelHubEngineNotReady": "Model Hub 引擎尚未就绪:{reason}",
+ "ripgrepInstalled": "ripgrep 已安装。",
+ "ripgrepReady": "ripgrep 已就绪。",
+ "ripgrepNotReady": "ripgrep 尚未就绪:{reason}"
},
"clean": {
- "commandHelp": "清理过期的 Show、Git、Model Hub 和 tmux 运行时安装与归档;任一清理失败时以非零状态退出。",
+ "commandHelp": "清理过期的 Show、Git、Model Hub、tmux 和 ripgrep 运行时安装与归档;任一清理失败时以非零状态退出。",
"dryRunHelp": "仅报告可清理的归档与缓存条目,不删除任何内容。",
"wouldRemoveItems": "将清理 {count} 项 Show Runtime 缓存。",
"wouldRemoveArchives": "将清理 {count} 个已下载的 Show Runtime 归档({size})。",
diff --git a/vibe/ripgrep_runtime_manifest.json b/vibe/ripgrep_runtime_manifest.json
new file mode 100644
index 000000000..04b77e1a5
--- /dev/null
+++ b/vibe/ripgrep_runtime_manifest.json
@@ -0,0 +1,41 @@
+{
+ "schema_version": 1,
+ "ripgrep_version": "15.2.0",
+ "source": "BurntSushi/ripgrep",
+ "source_url": "https://github.com/BurntSushi/ripgrep/releases/tag/15.2.0",
+ "release_tag": "15.2.0",
+ "archives": {
+ "darwin-arm64": {
+ "name": "ripgrep-15.2.0-aarch64-apple-darwin.tar.gz",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-apple-darwin.tar.gz",
+ "sha256": "3750b2e93f37e0c692657da574d7019a101c0084da05a790c83fd335bad973e4",
+ "binary_sha256": "a326a1fb48074202e9ad41e4cd1e389eeea372c8c6f7d7e80da81176d5d9430e",
+ "size": 1764284,
+ "bin_path": "ripgrep-15.2.0-aarch64-apple-darwin/rg"
+ },
+ "darwin-x64": {
+ "name": "ripgrep-15.2.0-x86_64-apple-darwin.tar.gz",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-apple-darwin.tar.gz",
+ "sha256": "af7825fcc69a2afc7a7aea55fc9af90e26421d8f20fe59df32e233c0b8a231c1",
+ "binary_sha256": "0c9a0066db0d26b640777db88045b0ccdd58509a746700e43e1c4ff8707a5ed0",
+ "size": 1878284,
+ "bin_path": "ripgrep-15.2.0-x86_64-apple-darwin/rg"
+ },
+ "linux-arm64": {
+ "name": "ripgrep-15.2.0-aarch64-unknown-linux-musl.tar.gz",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-unknown-linux-musl.tar.gz",
+ "sha256": "800b1e7206afe799dfb5a6901f23147cfaabe0e52210538100f61e86e1740915",
+ "binary_sha256": "c14cdb389f34e504d69e386cfc67d5c5d9a730a990de03ca6910b2a15e30386a",
+ "size": 1982561,
+ "bin_path": "ripgrep-15.2.0-aarch64-unknown-linux-musl/rg"
+ },
+ "linux-x64": {
+ "name": "ripgrep-15.2.0-x86_64-unknown-linux-musl.tar.gz",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-unknown-linux-musl.tar.gz",
+ "sha256": "33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c",
+ "binary_sha256": "e62198eb19b136b88c330af83647b5a962cb99b6b1f066758568f12de1974849",
+ "size": 2265718,
+ "bin_path": "ripgrep-15.2.0-x86_64-unknown-linux-musl/rg"
+ }
+ }
+}