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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
refactor(runtime): remove Sentry integration
Call White9f8bd0e5cb6e
diff --git a/.agents/skills/use-sentry-cli-debug/SKILL.md b/.agents/skills/use-sentry-cli-debug/SKILL.mddeleted file mode 100644index d54eb793a..000000000--- a/.agents/skills/use-sentry-cli-debug/SKILL.md+++ /dev/null@@ -1,134 +0,0 @@-----name: use-sentry-cli-debug-slug: use-sentry-cli-debug-description: Use the official Sentry CLI to investigate issues, events, traces, and logs for Vibe Remote without committing Sentry credentials into the repository.-version: 0.1.0------# Use Sentry CLI Debug--Use this skill when the user asks to inspect Sentry issues, events, traces, logs, or authenticated Sentry API responses from the command line while working in the Vibe Remote repository.--## Core Rules--1. Prefer `sentry` CLI subcommands over raw REST calls. Use `sentry issue`, `sentry event`, `sentry trace`, and `sentry log` first. Fall back to `sentry api` only when the dedicated command cannot expose the needed field.-2. Do not commit credentials. Prefer `sentry auth login` interactive auth. If token auth is required, use a shell-scoped `SENTRY_AUTH_TOKEN` or another untracked local secret source. Never write tokens into tracked repo files.-3. Keep output small. Prefer `--json --fields ...`, `--limit ...`, and `jq` when filtering.-4. Stay read-only by default. Do not resolve, mute, delete, or otherwise mutate Sentry state unless the user explicitly asks.-5. Verify CLI context before debugging. Run `sentry auth status`, then confirm the target org/project if auto-detection looks ambiguous.--## Prerequisites--If `sentry` is not installed:--```bash-curl https://cli.sentry.dev/install -fsS | bash-```--Then verify:--```bash-sentry --help-sentry auth status-```--Authentication options that do not require committing secrets:--```bash-# Preferred: interactive login managed by the CLI-sentry auth login--# Alternative: shell-scoped token-export SENTRY_AUTH_TOKEN=...-sentry auth login --token "$SENTRY_AUTH_TOKEN"-```--Never add the token to tracked files such as `.env`, `.envrc`, `config/*.json`, `settings.json`, or skill files.--## Repo-Specific Context--Before querying Sentry, read [vibe-remote.md](references/vibe-remote.md) for the tags and environment metadata currently attached by this repository.--Important current signals:--- `component=service` for the main service-- `component=ui` for the Flask UI-- `mode=<config.mode>`-- `primary_platform=<config.platforms.primary>`-- `deployment_environment=<resolved environment>`-- `release=vibe-remote@<version>`--These are useful narrowing dimensions when many unrelated issues exist in the same Sentry org/project.--## Debug Workflow--### 1. Confirm auth and scope--```bash-sentry auth status-sentry org list-sentry project list <org>-```--If auto-detection is unreliable, use explicit `<org>/<project>` in every command.--### 2. Triage recent issues--```bash-sentry issue list <org>/<project> \- --query 'is:unresolved' \- --limit 10 \- --json \- --fields shortId,title,count,userCount,lastSeen,level,status-```--Common filters:--```bash-sentry issue list <org>/<project> --query 'is:unresolved environment:regression'-sentry issue list <org>/<project> --query 'component:service'-sentry issue list <org>/<project> --query 'component:ui'-sentry issue list <org>/<project> --query 'primary_platform:slack'-sentry issue list <org>/<project> --query 'release:[email protected]'-```--### 3. Inspect one issue deeply--```bash-sentry issue view <short-id>-sentry issue explain <short-id>-```--Use `sentry issue explain` only after you have the raw issue details. Treat the AI explanation as a hint, not ground truth.--### 4. Inspect concrete event, trace, and logs--```bash-sentry event view <org>/<project>/<event-id>-sentry trace view <trace-id>-sentry trace logs <trace-id> --limit 100-sentry log list <org>/<project> --query 'level:error' --limit 100-```--Use trace and log commands when the issue points to timing, retries, upstream HTTP failures, or multi-step orchestration problems.--### 5. Use `sentry api` only as a fallback--```bash-sentry api /api/0/organizations/<org>/issues/-```--Prefer `--method`, `--data`, and `--header` only when the dedicated CLI command cannot express the operation.--## Vibe Remote Triage Hints--1. If the bug is user-visible in regression, first search `environment:regression`.-2. Split `component:service` and `component:ui` early. Do not mix backend startup errors with UI Flask failures.-3. When the report is platform-specific, try `primary_platform:<platform>` and cross-check local logs if Sentry detail is incomplete.-4. If no Sentry result appears, check whether the problem was only logged locally in `~/.vibe_remote/logs/vibe_remote.log`.-5. If Sentry output is too noisy, reduce fields instead of pasting full blobs back to the user.--## When Not to Use This Skill--- When the user wants release management or source map upload only, use generic `sentry` CLI commands directly without a full debug workflow.-- When the user explicitly wants dashboard/MCP-based investigation instead of CLI.diff --git a/.agents/skills/use-sentry-cli-debug/references/vibe-remote.md b/.agents/skills/use-sentry-cli-debug/references/vibe-remote.mddeleted file mode 100644index c68148d4b..000000000--- a/.agents/skills/use-sentry-cli-debug/references/vibe-remote.md+++ /dev/null@@ -1,54 +0,0 @@-# Vibe Remote Sentry Context--This repository already initializes the Python Sentry SDK in two entry points:--- `main.py` initializes Sentry for the main service-- `vibe/ui_server.py` initializes Sentry for the Flask UI--Current runtime metadata attached during initialization:--- `release = vibe-remote@<package-version>`-- tag `component = service|ui`-- tag `mode = <config.mode>`-- tag `primary_platform = <config.platforms.primary>`-- tag `deployment_environment = <resolved environment>`--Current structured contexts include:--- `runtime`-- `host`-- `deployment`--Environment resolution currently behaves like this:--1. Use `VIBE_SENTRY_ENVIRONMENT` or `SENTRY_ENVIRONMENT` if set.-2. Else use `VIBE_DEPLOYMENT_ENV` if set.-3. Else use `regression` when `VIBE_REMOTE_HOME` contains `three-regression`.-4. Else use `integration` when `E2E_TEST_MODE=true|1|yes`.-5. Else default to `local`.--Useful query ideas for this repo:--```bash-# Recent unresolved regression issues-sentry issue list <org>/<project> --query 'is:unresolved environment:regression'--# Service-only failures-sentry issue list <org>/<project> --query 'component:service'--# UI-only failures-sentry issue list <org>/<project> --query 'component:ui'--# Platform-focused drilldown-sentry issue list <org>/<project> --query 'primary_platform:slack'-sentry issue list <org>/<project> --query 'primary_platform:discord'-sentry issue list <org>/<project> --query 'primary_platform:lark'--# Deployment mode focused drilldown-sentry issue list <org>/<project> --query 'mode:self_host'-```--Operational note:--- Sentry is useful for grouped failures, stack traces, events, traces, and correlated logs.-- Local logs remain the fallback for configuration mistakes, startup failures before SDK init, and any problem that was only logged but never captured as an exception.diff --git a/docs/plans/2026-08-16-cloud-model-service-and-config-center.md b/docs/plans/2026-08-16-cloud-model-service-and-config-center.mdindex 2734d58f4..ad4dc0357 100644--- a/docs/plans/2026-08-16-cloud-model-service-and-config-center.md+++ b/docs/plans/2026-08-16-cloud-model-service-and-config-center.md@@ -206,8 +206,8 @@ scope per instance behind them.unchanged saved ciphertext is exempt. Status uses decrypt-validate-and-discard and never retainsor returns plaintext. This status-only read-path exception supersedes the earlier proxy-only wording.All read APIs return `has_api_key: true/false`, never the value. Keys and ciphertext never enter- API responses, logs, Sentry, or usage events. Missing or invalid key-secret material for a- committed saved slot is reported as a high-priority Sentry event tagged by scope, capability,+ API responses, logs, or usage events. Missing or invalid key-secret material for a+ committed saved slot is reported as a high-priority structured log tagged by scope, capability,instance, and config revision, using only scrubbed metadata. Emission is transition-deduplicatedby scope, config revision, and capability so status polling cannot create one event per instanceper minute; the first observing instance remains a context tag but is not part of the@@ -219,7 +219,7 @@ scope per instance behind them.to emit the outage event. A successful managed decrypt of committed saved ciphertext attemptsthe `available` transition on every call; candidate save round trips never read or write alertstate. If that recovery write fails, the usable call still proceeds, the write is retried on the- next successful decrypt, and the persistence failure itself is reported directly to Sentry+ next successful decrypt, and the persistence failure itself is reported to local diagnosticswithout relying on the unavailable transition table. Concurrent and cold-started Vercelisolates therefore observe the same edges without making alert infrastructure part of serviceavailability.@@ -491,7 +491,7 @@ when no slot is degraded.`status: "error"` events carry upstream-reported token usage whenever the failure response includesit (induced failures — `finish_reason: length`/`content_filter`, malformed payloads — cannot bypassmetering or quota). A metering-write failure never breaks the served call: the response/transcript-is still delivered, the failure is reported loudly (Sentry + structured log), and connections close+is still delivered, the failure is reported loudly (structured log), and connections closein a controlled way. A worker crash between upstream completion and the event insert loses onlythat telemetry row — the reservation reaper keeps enforcement truthful — and falls under the sameaccepted, monitored v1 gap. Fail-closed metering is deliberately deferred to M3, when enforcement@@ -515,7 +515,7 @@ turns on.row and emits no ops alert because the request response and admin UI are its presentation surface.For unrecovered saved-slot failures, status marks the affected capability false with the samereason. Every saved-key decryption-failure transition, including one masked by approved platform- recovery, emits one scrubbed high-priority Sentry event per scope/config revision/capability;+ recovery, emits one scrubbed high-priority structured log per scope/config revision/capability;repeated failures at the same active edge emit none, and successful decryption of the committedsaved ciphertext rearms a later failure through the persisted `available` state. Candidateround trips never rearm that state. Failure to persist the committed recovery state never changes@@ -544,7 +544,7 @@ turns on.quota, for any capability; a missing or disabled organization slot yields`model_service_not_configured`, while an enabled slot with unavailable key custody yields`model_service_key_unavailable`, never a silent fallback.-3. No API response, log line, Sentry event, usage event, or error message ever contains a slot API+3. No API response, log line, usage event, or error message ever contains a slot APIkey or its ciphertext; a `mak_` key appears exactly once — in the body of its own mint/rotateresponse (shown once by design) — and nowhere else; config reads expose only `has_api_key`.Every newly submitted or legacy-materialized key is decrypt-valid before persistence, includingdiff --git a/docs/plans/fastapi-migration.md b/docs/plans/fastapi-migration.mdindex 5ec6afcd9..ae9e11ef0 100644--- a/docs/plans/fastapi-migration.md+++ b/docs/plans/fastapi-migration.md@@ -199,7 +199,6 @@ def run_ui_server(host: str, port: int) -> None:paths.ensure_data_dirs()config = _load_config_safely()if config is not None:- init_sentry(config, component="ui", enable_fastapi=True)_start_remote_access_heartbeat_safely(config)uvicorn_config = uvicorn.Config(@@ -218,7 +217,8 @@ def run_ui_server(host: str, port: int) -> None:server.run() # blocks```-Use FastAPI's `lifespan` context to start / stop the OAuth service singleton (replacing the daemon-thread loop) and the Sentry FastAPI integration:+Use FastAPI's `lifespan` context to start / stop the OAuth service singleton+(replacing the daemon-thread loop):```pythonfrom contextlib import asynccontextmanager@@ -236,11 +236,12 @@ app = FastAPI(lifespan=lifespan)Port-bind retry loop (currently in `make_server` wrapper for EADDRINUSE handling) lives outside uvicorn — wrap `server.run()` in the same retry loop.-### Sentry integration+### Optional error telemetry-`init_sentry(..., enable_flask=True)` currently activates the Flask integration. Switch to FastAPI:-- `enable_flask=True` flag in `vibe/sentry_integration.py` becomes `enable_fastapi=True`.-- Inside, swap `sentry_sdk.integrations.flask.FlaskIntegration()` for `sentry_sdk.integrations.fastapi.FastApiIntegration()` and `sentry_sdk.integrations.starlette.StarletteIntegration()`.+The former external error-reporting integration is intentionally out of scope+for this migration. The current product has no external telemetry dependency,+initialization, or environment configuration; do not add one back while+finishing the remaining FastAPI work.### Tests@@ -285,7 +286,7 @@ The chat feature will land in a follow-up PR using this same pattern. We just ne| 74 routes — long migration, easy to miss subtle response-shape differences | Migrate one router file at a time, run the existing test for that surface after each, smoke via curl. Don't merge until ALL test files pass and a manual smoke against the React UI is clean. || Tests embedded in Flask test client semantics (cookies, sessions) | TestClient is largely API-compatible; deal with cookie domain quirks one test file at a time. Allocate ~25% of the migration budget for tests. || CSRF / remote_access middleware: ordering bugs | Port one middleware at a time with focused FastAPI tests in `tests/test_ui_server_fastapi.py`. |-| Sentry integration regression | Init in lifespan startup; verify Sentry breadcrumbs still appear via the regression env's dev key. |+| Optional error telemetry | Out of scope; failures remain in local structured logs. || WSGI-specific subprocess launching pattern in `run_ui_server` | Uvicorn handles this natively in-process; keep the EADDRINUSE retry loop. || Frontend assumptions about specific status codes / response shapes | Don't refactor any payload shape during the migration. Same path, same method, same JSON. || Streaming responses (logs tail, OAuth status long-poll) | All current "streaming" looks like polling, not SSE. Confirm during route porting; if any real SSE shows up, convert to `StreamingResponse`. |@@ -304,7 +305,7 @@ Each phase ends with a green test run + a manual smoke. Commit between phases.6. **IM platform credentials.** Slack / Discord / Telegram / Feishu / WeChat routes. WeChat QR login long-poll is a candidate for `StreamingResponse` (or stays as poll — keep behavior identical).7. **Config / settings / sessions / logs / version / remote-access / browse.** The remaining bulk.8. **WebSocket smoke route** + frontend hello-world dialog (optional) to prove the substrate.-9. **Cleanup.** Remove `VIBE_UI_FRAMEWORK` flag, delete `_legacy_flask_app`, drop `flask` from `pyproject.toml`, regenerate lockfile. Update `vibe/sentry_integration.py` to use `FastApiIntegration`/`StarletteIntegration`.+9. **Cleanup.** Remove `VIBE_UI_FRAMEWORK` flag, delete `_legacy_flask_app`, drop `flask` from `pyproject.toml`, regenerate lockfile.10. **Tests.** Convert `app.test_client()` → `TestClient(app)`. The 5–6 test files using Flask testing patterns need a uniform pass.Codex review after each phase keeps the surface area manageable.@@ -331,5 +332,4 @@ The migration is too large to be a single commit. Land it as a stacked PR series1. **Phase granularity** — single PR or stacked PRs? Single is simpler to verify; stacked is easier to review. Lean stacked if review burden looks heavy.2. **`request.remote_addr` proxy header logic** — the Flask path has bespoke handling for `X-Forwarded-For` / `X-Forwarded-Host` to support Cloudflare Tunnel. Verify Starlette's `request.client.host` honors `forwarded` properly; if not, port the bespoke logic into middleware that writes `request.state.client_host`.3. **Logging integration** — uvicorn has its own access log format. Decide whether to disable uvicorn's access log (current Flask doesn't have one anyway) or pipe it through `vibe/logging.py`.-4. **Sentry** — confirm `FastApiIntegration` + `StarletteIntegration` is the right combination (not just one of them).-5. **Test client async helpers** — if any test currently uses Flask's `with app.test_request_context()` pattern, port to `httpx.AsyncClient` for the async equivalent.+4. **Test client async helpers** — if any test currently uses Flask's `with app.test_request_context()` pattern, port to `httpx.AsyncClient` for the async equivalent.diff --git a/docs/plans/rebrand-avibe.md b/docs/plans/rebrand-avibe.mdindex 3a6563f1c..b3ff189b7 100644--- a/docs/plans/rebrand-avibe.md+++ b/docs/plans/rebrand-avibe.md@@ -294,10 +294,10 @@ change in implementation.- Bot/platform setup surfaces: `vibe/templates/slack_manifest.json`, READMEexamples such as `@Vibe Remote /start`, and platform setup docs should becomeon-brand. Actual platform-side app renames remain external.-- Sentry and HTTP user agents: `vibe/sentry_integration.py`,- `vibe/api.py`, and `vibe/remote_access.py` still use `vibe-remote` /- `Vibe Remote` release or user-agent labels. Decide whether to move these to- `avibe-os@<version>` / `avibe` while preserving search compatibility.+- HTTP user agents: `vibe/api.py` and `vibe/remote_access.py` still use+ `vibe-remote` / `Vibe Remote` release or user-agent labels. Decide whether+ to move these to `avibe-os@<version>` / `avibe` while preserving search+ compatibility.- `avibe-bot-backend/next.config.ts`: public `/install.sh` remains`https://avibe.bot/install.sh`, but the backend redirect target must bechanged from `cyhhao/vibe-remote` raw to `avibe-bot/avibe` raw at transfer.@@ -413,7 +413,7 @@ Do first:old `~/.vibe_remote` adoption,back-symlink, conflict rules, and old-user simulation tests.- P3 main-repo product copy: README/README_ZH, VISION/VISION_ZH, backend i18n,- frontend i18n, UI metadata, Slack manifest, Sentry/user-agent labels where+ frontend i18n, UI metadata, Slack manifest, user-agent labels whereappropriate.Do not spend first-pass effort rewriting historical `docs/plans/` files,@@ -471,7 +471,7 @@ Updated surfaces:settings, Slack install, update notifications, and related user-visiblestrings. EN/ZH keys remain in lockstep.- UI metadata, PWA manifest, web-push defaults, Slack manifest, remote-access- pairing defaults, system prompt injection, Sentry release labels, and+ pairing defaults, system prompt injection, release labels, andnon-protocol user agents now use `avibe`.Intentionally retained:diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.mdindex 16aa2ef23..60d2b3504 100644--- a/docs/plans/tunnel-quality-and-route-recovery.md+++ b/docs/plans/tunnel-quality-and-route-recovery.md@@ -813,7 +813,7 @@ independently:- an unsupported future `schema_version` is ignored, not rejected; and- a supported sample more than five minutes ahead of backend time is discarded asunreasonable clock skew;-- validation failures are rate-limited in logs/Sentry without echoing payloads.+- validation failures are rate-limited in local logs without echoing payloads.V2 validation also preserves the producer's correlated semantics rather thanaccepting each field independently. A non-null request path contains at leastdiff --git a/docs/plans/web-fetch.md b/docs/plans/web-fetch.mdindex c368c21ea..2e4e1d8b0 100644--- a/docs/plans/web-fetch.md+++ b/docs/plans/web-fetch.md@@ -266,7 +266,7 @@ The degraded HTTP/2 path sends `User-Agent: Avibe/<version>`, negotiatedor `Sec-Fetch-*` fingerprint headers. It decodes only gzip/deflate (plus identity)with bounded standard-library decoders. Native br/zstd decoding stays insidelibcurl; do not install Python `brotli` or `zstandard` for this feature, because-importable codecs change unrelated Sentry/HTTP/Discord defaults. It cannot+importable codecs change unrelated HTTP/Discord defaults. It cannotimpersonate Chrome TLS; its`transport_degraded` marker explicitly states that exception and it must notsilently choose another browser profile.diff --git a/main.py b/main.pyindex a7ffbe9c3..1e092fb86 100644--- a/main.py+++ b/main.py@@ -194,10 +194,7 @@ def main():logger.warning("Avibe built-in Skills are unavailable", exc_info=True)apply_claude_sdk_patches()- from vibe.sentry_integration import init_sentry- init_sentry(config, component="service")-logger.info("Starting vibe-remote service...")logger.info(f"Working directory: {config.runtime.default_cwd}")logger.info(diff --git a/pyproject.toml b/pyproject.tomlindex f1992e65c..643fc3ab6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -71,16 +71,13 @@ dependencies = ["requests>=2.31.0",# eMudhra distrust: 2026.10.23 drops emSign ECC Root CA - G3 and the C1/C3 roots."certifi>=2026.10.23",- # The fail-closed redacting transport is audited against this exact SDK.- # Upgrade only with vibe/sentry_integration.py and its real-SDK tests.- "sentry-sdk==2.56.0","python-socks[asyncio]>=2.0.0","aiohttp-socks>=0.8.0","httpx[http2,socks]>=0.27",# WF-2G: update this version only together with the locked chrome150 profile."curl_cffi==0.16.3; platform_python_implementation == 'CPython' and ((sys_platform == 'darwin' and (platform_machine == 'arm64' or platform_machine == 'x86_64')) or (sys_platform == 'linux' and (platform_machine == 'x86_64' or platform_machine == 'aarch64')) or (sys_platform == 'win32' and (platform_machine == 'AMD64' or platform_machine == 'ARM64')))",# Keep br/zstd inside libcurl: Python codec imports change other clients'- # defaults (Sentry, HTTPX, Discord). The degraded path uses stdlib codecs.+ # defaults (HTTPX, Discord). The degraded path uses stdlib codecs."trafilatura>=2.3.1","pypdf>=6.21.2","python-multipart>=0.0.9",diff --git a/scripts/ci_unit_test_timings.json b/scripts/ci_unit_test_timings.jsonindex 823057e80..f275126e5 100644--- a/scripts/ci_unit_test_timings.json+++ b/scripts/ci_unit_test_timings.json@@ -422,7 +422,6 @@"tests/test_save_opencode_provider_auth.py": 9.5,"tests/test_scheduled_command_task_integration.py": 10.0,"tests/test_scheduled_tasks.py": 90.5,- "tests/test_sentry_integration.py": 7.0,"tests/test_service_lock_record.py": 10.5,"tests/test_service_logging_handlers.py": 3.0,"tests/test_service_readiness.py": 7.5,diff --git a/scripts/terminal_bench/runner.py b/scripts/terminal_bench/runner.pyindex 29d1f36cb..383e8d917 100644--- a/scripts/terminal_bench/runner.py+++ b/scripts/terminal_bench/runner.py@@ -228,7 +228,7 @@ class FullRuntimeTrial:env.update({"AVIBE_HOME": str(self.avibe_home), _OWNER: self.marker,"AVIBE_WEB_UI_SUPERVISOR": "terminal-bench-no-ui",- "VIBE_SENTRY_DSN": "", "VIBE_STARTUP_DEPENDENCY_RECONCILE": "0",+ "VIBE_STARTUP_DEPENDENCY_RECONCILE": "0","VIBE_INSTALL_SKIP_ASKILL": "1", "VIBE_ASKILL_AUTO_UPDATE": "0","VIBE_SHOW_RUNTIME_OFFLINE": "1" if self.profile.offline else "0","VIBE_TMUX_OFFLINE": "1" if self.profile.offline else "0",diff --git a/tests/e2e/drivers/model_hub_app.py b/tests/e2e/drivers/model_hub_app.pyindex 2728af129..adb25b79b 100644--- a/tests/e2e/drivers/model_hub_app.py+++ b/tests/e2e/drivers/model_hub_app.py@@ -248,7 +248,6 @@ class ModelHubTestApp:"VIBE_INTERNAL_DISPATCH_SOCKET": str(self.runtime_root / "dispatch.sock"),- "VIBE_SENTRY_DSN": "",# OpenCode installs @opencode-ai/plugin from npm before its first# request once a plugin is configured; offline, that install fails# at once, and the Avibe plugin imports nothing from it.diff --git a/tests/e2e/test_model_hub_service_acceptance.py b/tests/e2e/test_model_hub_service_acceptance.pyindex 8475be1ca..f49e9cb77 100644--- a/tests/e2e/test_model_hub_service_acceptance.py+++ b/tests/e2e/test_model_hub_service_acceptance.py@@ -139,7 +139,6 @@ class _Service:# the engine still installs from the packaged manifest. The catalogs# it reads are this checkout's backend catalog and a models.dev copy# that describes nothing; neither is needed by the turns below.- "VIBE_SENTRY_DSN": "","AVIBE_BACKEND_MODEL_CATALOG_URL": _BACKEND_CATALOG.as_uri(),"AVIBE_MODELS_DEV_URL": models_dev.as_uri(),"VIBE_INSTALL_SKIP_ASKILL": "1",diff --git a/tests/test_macos_session_diagnostics.py b/tests/test_macos_session_diagnostics.pyindex 459967e3a..f6a1e8173 100644--- a/tests/test_macos_session_diagnostics.py+++ b/tests/test_macos_session_diagnostics.py@@ -395,7 +395,6 @@ def test_service_main_owns_monitor_shutdown(monkeypatch) -> None:import core.controllerimport core.process_diagnosticsimport main as service_main- import vibe.sentry_integrationfrom vibe import runtimefrom vibe import desktop_runtime@@ -465,7 +464,6 @@ def test_service_main_owns_monitor_shutdown(monkeypatch) -> None:"start_macos_session_diagnostics",lambda logger: calls.append("diagnostics.start") or FakeMonitor(),)- monkeypatch.setattr(vibe.sentry_integration, "init_sentry", lambda *args, **kwargs: None)monkeypatch.setattr(core.process_diagnostics, "log_process_snapshot", lambda *args, **kwargs: None)monkeypatch.setattr(core.controller, "Controller", FakeController)monkeypatch.setattr(config.v2_compat, "to_app_config", lambda loaded: loaded)diff --git a/tests/test_sentry_integration.py b/tests/test_sentry_integration.pydeleted file mode 100644index 22228336e..000000000--- a/tests/test_sentry_integration.py+++ /dev/null@@ -1,1253 +0,0 @@-from __future__ import annotations--import sys-import types-import importlib-import ast-from concurrent.futures import ThreadPoolExecutor-from pathlib import Path--import pytest--sys.path.insert(0, str(Path(__file__).resolve().parents[1]))--from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config-from vibe import sentry_integration---def _config() -> V2Config:- return V2Config(- mode="self_host",- version="v2",- slack=SlackConfig(bot_token=""),- runtime=RuntimeConfig(default_cwd="/tmp/workdir", log_level="INFO"),- agents=AgentsConfig(),- )--[email protected](autouse=True)-def _isolate_user_state(monkeypatch, tmp_path):- home = tmp_path / "home"- monkeypatch.setenv("HOME", str(home))- monkeypatch.setenv("XDG_CONFIG_HOME", str(home / "config"))- monkeypatch.setenv("XDG_DATA_HOME", str(home / "data"))- monkeypatch.setenv("XDG_CACHE_HOME", str(home / "cache"))- monkeypatch.setenv("XDG_STATE_HOME", str(home / "state"))- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))- with sentry_integration._KNOWN_SECRETS_LOCK:- sentry_integration._known_secret_files_state.clear()- sentry_integration._known_secret_values.clear()- sentry_integration._known_secret_snapshot = (False, None, None)- sentry_integration._known_secret_collection_uncertain = False- sentry_integration._known_secret_collection_overflowed = False- assert sentry_integration._refresh_known_secret_state()---def test_resolve_sentry_options_prefers_environment(monkeypatch):- monkeypatch.setenv("VIBE_SENTRY_DSN", "https://[email protected]/2")- monkeypatch.setenv("VIBE_DEPLOYMENT_ENV", "regression")- monkeypatch.setenv("VIBE_SENTRY_TRACES_SAMPLE_RATE", "0.25")-- options = sentry_integration.resolve_sentry_options()-- assert options is not None- assert options["dsn"] == "https://[email protected]/2"- assert options["environment"] == "regression"- assert options["traces_sample_rate"] == 0.25---def test_resolve_sentry_options_returns_none_without_dsn(monkeypatch):- monkeypatch.delenv("VIBE_SENTRY_DSN", raising=False)- monkeypatch.delenv("SENTRY_DSN", raising=False)- monkeypatch.setattr(sentry_integration, "DEFAULT_SENTRY_DSN", "")-- assert sentry_integration.resolve_sentry_options() is None---def test_resolve_sentry_options_honors_empty_env_dsn_as_opt_out(monkeypatch):- monkeypatch.setenv("VIBE_SENTRY_DSN", "")- monkeypatch.setattr(sentry_integration, "DEFAULT_SENTRY_DSN", "https://[email protected]/1")-- assert sentry_integration.resolve_sentry_options() is None---def test_detect_sentry_environment_defaults_to_local(monkeypatch, tmp_path):- monkeypatch.delenv("VIBE_SENTRY_ENVIRONMENT", raising=False)- monkeypatch.delenv("SENTRY_ENVIRONMENT", raising=False)- monkeypatch.delenv("VIBE_DEPLOYMENT_ENV", raising=False)- monkeypatch.delenv("E2E_TEST_MODE", raising=False)- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))- monkeypatch.setattr(sentry_integration, "Path", lambda _: type("P", (), {"exists": staticmethod(lambda: False)})())-- assert sentry_integration.detect_sentry_environment() == "local"---def test_detect_sentry_environment_uses_explicit_deployment_env(monkeypatch):- monkeypatch.delenv("VIBE_SENTRY_ENVIRONMENT", raising=False)- monkeypatch.delenv("SENTRY_ENVIRONMENT", raising=False)- monkeypatch.setenv("VIBE_DEPLOYMENT_ENV", "production")-- assert sentry_integration.detect_sentry_environment() == "production"---def test_detect_sentry_environment_marks_integration_mode(monkeypatch, tmp_path):- monkeypatch.delenv("VIBE_SENTRY_ENVIRONMENT", raising=False)- monkeypatch.delenv("SENTRY_ENVIRONMENT", raising=False)- monkeypatch.delenv("VIBE_DEPLOYMENT_ENV", raising=False)- monkeypatch.setenv("E2E_TEST_MODE", "true")- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))-- assert sentry_integration.detect_sentry_environment() == "integration"---def test_build_sentry_contexts_contains_debug_metadata(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))-- contexts = sentry_integration.build_sentry_contexts(_config(), component="service", environment="regression")-- assert contexts["deployment"]["environment"] == "regression"- assert contexts["deployment"]["component"] == "service"- assert contexts["deployment"]["default_agent_name"] is None- assert contexts["runtime"]["python_version"]- assert "hostname" in contexts["host"]---def test_init_sentry_returns_false_when_sdk_init_raises(monkeypatch):- monkeypatch.setenv("VIBE_SENTRY_DSN", "https://[email protected]/2")-- sentry_sdk = types.ModuleType("sentry_sdk")- sentry_sdk.init = lambda **kwargs: (_ for _ in ()).throw(ValueError("bad dsn"))- sentry_sdk.set_tag = lambda *args, **kwargs: None- sentry_sdk.set_context = lambda *args, **kwargs: None-- logging_integration_module = types.ModuleType("sentry_sdk.integrations.logging")-- class FakeLoggingIntegration:- def __init__(self, *args, **kwargs):- self.args = args- self.kwargs = kwargs-- logging_integration_module.LoggingIntegration = FakeLoggingIntegration-- monkeypatch.setitem(sys.modules, "sentry_sdk", sentry_sdk)- monkeypatch.setitem(sys.modules, "sentry_sdk.integrations.logging", logging_integration_module)-- assert sentry_integration.init_sentry(_config(), component="service") is False---def test_init_sentry_disables_client_discard_reports(monkeypatch):- monkeypatch.setenv("VIBE_SENTRY_DSN", "https://[email protected]/2")- init_kwargs = {}-- sentry_sdk = types.ModuleType("sentry_sdk")- sentry_sdk.init = lambda **kwargs: init_kwargs.update(kwargs)- sentry_sdk.set_tag = lambda *args, **kwargs: None- sentry_sdk.set_context = lambda *args, **kwargs: None-- logging_integration_module = types.ModuleType("sentry_sdk.integrations.logging")-- class FakeLoggingIntegration:- def __init__(self, *args, **kwargs):- self.args = args- self.kwargs = kwargs-- logging_integration_module.LoggingIntegration = FakeLoggingIntegration-- monkeypatch.setitem(sys.modules, "sentry_sdk", sentry_sdk)- monkeypatch.setitem(sys.modules, "sentry_sdk.integrations.logging", logging_integration_module)-- assert sentry_integration.init_sentry(_config(), component="service") is True- assert init_kwargs["send_client_reports"] is False- assert init_kwargs["spotlight"] is False- assert init_kwargs["transport"] is sentry_integration._RedactingHttpTransport---def test_run_ui_server_skips_sentry_when_config_load_fails(monkeypatch):- ui_server = importlib.import_module("vibe.ui_server")-- class DummyServer:- def __init__(self, *_args, **_kwargs):- pass-- def run(self, sockets=None):- return None-- fake_uvicorn = types.ModuleType("uvicorn")- fake_uvicorn.Config = lambda *args, **kwargs: (args, kwargs)- fake_uvicorn.Server = DummyServer- monkeypatch.setitem(sys.modules, "uvicorn", fake_uvicorn)-- monkeypatch.setattr(ui_server.paths, "ensure_data_dirs", lambda: None)- monkeypatch.setattr(- ui_server.V2Config,- "load",- lambda *args, **kwargs: (_ for _ in ()).throw(ValueError("bad config")),- )- sentry_calls = []- monkeypatch.setattr(ui_server, "init_sentry", lambda *args, **kwargs: sentry_calls.append((args, kwargs)))-- ui_server.run_ui_server("127.0.0.1", 0)-- assert sentry_calls == []---def test_run_ui_server_reconciles_remote_access_after_binding(monkeypatch):- from vibe import ui_server- from vibe import remote_access-- class DummyServer:- def __init__(self, *_args, **_kwargs):- pass-- def run(self, sockets=None):- return None-- fake_uvicorn = types.ModuleType("uvicorn")- fake_uvicorn.Config = lambda *args, **kwargs: (args, kwargs)- fake_uvicorn.Server = DummyServer- monkeypatch.setitem(sys.modules, "uvicorn", fake_uvicorn)-- import time-- from core.services import settings as settings_service-- reconcile_calls = []- config = _config()-- monkeypatch.setattr(ui_server.paths, "ensure_data_dirs", lambda: None)- # run_ui_server loads config via settings_service.load_config (PR #340), not- # V2Config.load — patch the real seam, otherwise config is None and the- # reconcile thread early-returns.- monkeypatch.setattr(settings_service, "load_config", lambda *args, **kwargs: config)- monkeypatch.setattr(ui_server, "init_sentry", lambda *args, **kwargs: None)- # With a non-None config the start path also kicks the status heartbeat; keep it inert.- monkeypatch.setattr(remote_access, "start_status_heartbeat", lambda *args, **kwargs: None)- monkeypatch.setattr(remote_access, "reconcile", lambda next_config=None: reconcile_calls.append(next_config) or {"ok": True})-- ui_server.run_ui_server("127.0.0.1", 0)-- # Reconcile runs on a daemon thread spawned after binding; poll briefly.- for _ in range(200):- if reconcile_calls:- break- time.sleep(0.01)-- assert reconcile_calls == [config]---def test_run_ui_server_retries_when_prebind_reports_port_in_use(monkeypatch):- from vibe import ui_server-- class DummySocket:- def close(self):- return None-- class DummyServer:- def __init__(self, *_args, **_kwargs):- pass-- def run(self, sockets=None):- run_calls.append(sockets)-- fake_uvicorn = types.ModuleType("uvicorn")- fake_uvicorn.Config = lambda *args, **kwargs: (args, kwargs)- fake_uvicorn.Server = DummyServer- monkeypatch.setitem(sys.modules, "uvicorn", fake_uvicorn)-- attempts = {"count": 0}- run_calls = []-- def bind_socket(_host, _port):- attempts["count"] += 1- if attempts["count"] == 1:- raise OSError(48, "Address already in use")- return DummySocket()-- monkeypatch.setattr(ui_server.paths, "ensure_data_dirs", lambda: None)- monkeypatch.setattr(ui_server.V2Config, "load", lambda *args, **kwargs: _config())- monkeypatch.setattr(ui_server, "init_sentry", lambda *args, **kwargs: None)- monkeypatch.setattr(ui_server, "_bind_ui_socket", bind_socket)- monkeypatch.setattr(ui_server.time, "sleep", lambda _seconds: None)- monkeypatch.setattr(ui_server, "_reconcile_remote_access_for_ui_start", lambda _config: None)-- ui_server.run_ui_server("127.0.0.1", 5123)-- assert attempts["count"] == 2- assert len(run_calls) == 1---def test_run_ui_server_keepalive_outlives_upstream_proxy_pool(monkeypatch):- """The UI's idle keep-alive must outlive any proxy pooling its connections.-- cloudflared reuses idle origin connections for up to its own keep-alive- timeout. If the server expires them first, a reused connection races the- close and the browser gets a 502 from a perfectly healthy service. Assert- the ordering property rather than a specific number, so retuning either- constant cannot silently reintroduce the race.- """-- from vibe import ui_server- from core.services import settings as settings_service-- captured: dict = {}-- class DummySocket:- def close(self):- return None-- class DummyServer:- def __init__(self, *_args, **_kwargs):- pass-- def run(self, sockets=None):- return None-- def capture_config(*args, **kwargs):- captured.update(kwargs)- return (args, kwargs)-- fake_uvicorn = types.ModuleType("uvicorn")- fake_uvicorn.Config = capture_config- fake_uvicorn.Server = DummyServer- monkeypatch.setitem(sys.modules, "uvicorn", fake_uvicorn)-- monkeypatch.setattr(ui_server.paths, "ensure_data_dirs", lambda: None)- # Keep the probe hermetic: no real config load, no remote-access reconcile.- monkeypatch.setattr(settings_service, "load_config", lambda *args, **kwargs: None)- monkeypatch.setattr(ui_server, "_bind_ui_socket", lambda _host, _port: DummySocket())- monkeypatch.setattr(ui_server, "_reconcile_remote_access_for_ui_start", lambda _config: None)-- ui_server.run_ui_server("127.0.0.1", 5123)-- assert captured["timeout_keep_alive"] > ui_server._CLOUDFLARED_PROXY_KEEPALIVE_TIMEOUT_SECONDS---def test_ui_error_handler_does_not_explicitly_capture_exceptions():- source = Path("vibe/ui_server.py").read_text(encoding="utf-8")- module = ast.parse(source)-- handle_exception = next(- node for node in module.body if isinstance(node, ast.FunctionDef) and node.name == "handle_exception"- )-- calls_capture_exception = False- for node in ast.walk(handle_exception):- if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "capture_exception":- calls_capture_exception = True- break-- assert calls_capture_exception is False---def test_scrub_data_redacts_sensitive_values():- event = {- "request": {- "headers": {"Authorization": "Bearer abc", "Cookie": "session=secret"},- "data": {"bot_token": "xoxb-secret", "nested": [{"client_secret": "shh"}]},- },- "message": "token=abc123 and xapp-123456",- }-- scrubbed = sentry_integration.scrub_data(event)-- assert scrubbed["request"]["headers"]["Authorization"] == "[Filtered]"- assert scrubbed["request"]["headers"]["Cookie"] == "[Filtered]"- assert scrubbed["request"]["data"]["bot_token"] == "[Filtered]"- assert scrubbed["request"]["data"]["nested"][0]["client_secret"] == "[Filtered]"- assert "[Filtered]" in scrubbed["message"]--- ("text", "secret", "kept"),- [- (- "lark config rejected: LarkConfig(app_id='cli_x', app_secret='lark-s3cret', domain='feishu')",- "lark-s3cret",- "app_id='cli_x'",- ),- (- 'save failed: {"api_key": "sk-s3cret", "base_url": "https://api.example"}',- "sk-s3cret",- '"base_url": "https://api.example"',- ),- ("refresh failed client_secret=gw-s3cret status=401", "gw-s3cret", "status=401"),- # Credential names the code uses, in the spellings it uses them.- ({"provider": {"apiKey": "oc-s3cret"}, "model": "m1"}, "oc-s3cret", '"model": "m1"'),- ("request headers x-api-key: an-s3cret accept: json", "an-s3cret", "accept: json"),- ("engine health X-Management-Key: mk-s3cret status=503", "mk-s3cret", "status=503"),- ("media decrypt failed aes_key=aes-s3cret file=a.jpg", "aes-s3cret", "file=a.jpg"),- ('{"passphrase": "pp-s3cret", "vault": "v1"}', "pp-s3cret", '"vault": "v1"'),- ("Binding(private_key='pk-s3cret', agent='a1')", "pk-s3cret", "agent='a1'"),- # Generic names, as whole keys only: Model Hub validates ``{"key": ...}``.- ("probe failed {'vendor': 'openai', 'key': 'mh-s3cret'} cache_key=c1", "mh-s3cret", "cache_key=c1"),- ("upstream auth: Bearer au-s3cret author=me", "au-s3cret", "author=me"),- # Quoting: an escaped quote inside, a trailing backslash, JSON in a JSON string.- ('api_key="ab\\"esc-s3cret" retry=2', "esc-s3cret", "retry=2"),- ("cfg {'api_key': 'bs-s3cret\\\\'}", "bs-s3cret", "cfg {'api_key': "),- ('{"body": "{\\"api_key\\": \\"nest-s3cret\\", \\"n\\": 1}"}', "nest-s3cret", '\\"n\\": 1'),- # Any URL keeps only its origin.- (- "poll error url=https://api.telegram.org/bot123456:AAHs3cretS3cretS3cretS3cretS3cret/getUpdates",- "AAHs3cretS3cretS3cretS3cretS3cret",- "url=https://api.telegram.org/",- ),- ("409 url=https://hooks.slack.com/actions/T01/123/sl-s3cret", "sl-s3cret", "https://hooks.slack.com/"),- ("POST https://discord.com/api/v10/interactions/1/dc-s3cret/callback", "dc-s3cret", "https://discord.com/"),- ("GET https://cdn.weixin.qq.com/download?encrypted_query_param=wx-s3cret", "wx-s3cret", "https://cdn.weixin.qq.com/"),- ("proxy error http://alice:[email protected]:8080 timed out", "px-s3cret", "@proxy.local:8080 timed out"),- ("bad proxy http://bob:p/[email protected]/x", "w-s3cret", "bad proxy http://"),- # A quote or bracket in the password must not end the URL early.- ("proxy error http://alice:pa'[email protected]:8080 timed out", "sq-s3cret", "@proxy.local:8080 timed out"),- ('proxy error http://alice:pa"[email protected]:8080 timed out', "dq-s3cret", "@proxy.local:8080 timed out"),- ("proxy error http://alice:pa`[email protected]:8080 timed out", "bt-s3cret", "@proxy.local:8080 timed out"),- ("cfg {'proxy_url': 'http://alice:pa\\'[email protected]:8080'}", "rq-s3cret", "@proxy.local:8080'}"),- ("POST hooks.slack.com/actions/T01/123/ns-s3cret failed", "ns-s3cret", "POST hooks.slack.com/"),- # The same URLs spelled another way.- ('{"response_url":"https:\\/\\/hooks.slack.com\\/actions\\/T01\\/js-s3cret"}', "js-s3cret", "hooks.slack.com/"),- ("redirect=https%3A%2F%2Fhooks.slack.com%2Factions%2FT01%2Fpe-s3cret", "pe-s3cret", "hooks.slack.com/"),- ("next=https%253A%252F%252Fdiscord.com%252Fapi%252Fde-s3cret", "de-s3cret", "discord.com/"),- ("https:\\u002f\\u002fdiscord.com\\u002fapi\\u002fue-s3cret", "ue-s3cret", "discord.com/"),- ("https://discord.com/api/he-s3cret", "he-s3cret", "discord.com/"),- ("https:\\\\discord.com\\api\\bp-s3cret", "bp-s3cret", "discord.com/"),- ("fetch //discord.com/api/webhooks/1/sr-s3cret", "sr-s3cret", "fetch //discord.com/"),- ("GET 10.0.0.5:8080/download/ip-s3cret", "ip-s3cret", "GET 10.0.0.5:8080/"),- ("GET localhost:5123/api/media/lh-s3cret", "lh-s3cret", "GET localhost:5123/"),- ("GET [::1]:5123/api/media/v6-s3cret", "v6-s3cret", "GET [::1]:5123/"),- ("state=abc%26access_token%3Dqe-s3cret", "qe-s3cret", "state=abc&access_token="),- # A quoted value longer than any scan window is redacted to its end.- ('api_key="' + "x" * 9000 + 'lv-s3cret" next', "lv-s3cret", 'api_key="'),- ],-)-def test_scrub_data_redacts_secrets_inside_free_text(text, secret, kept):- """Log and exception messages carry secrets as text, not under a dict key."""- import json-- scrubbed = sentry_integration.scrub_data({"logentry": {"params": [text]}})-- (value,) = scrubbed["logentry"]["params"]- rendered = json.dumps(value) if isinstance(value, dict) else value- assert secret not in rendered- assert "[Filtered]" in rendered- assert kept in rendered- assert sentry_integration.scrub_data(value) == value--- "text",- [- '{"url":"http://host:8080","email":"[email protected]"}',- "{'url':'http://host:8080','email':'[email protected]'}",- "path /Users/x/.avibe/config/config.json line 3, see ./scripts/run.sh",- "Retrying in 5s (attempt 2/3) status: 401 cache_key=c1 author=me",- ],-)-def test_scrub_data_keeps_ordinary_text(text):- """Over-redaction costs the debugging the events exist for."""- assert sentry_integration.scrub_data(text) == text---def test_before_send_redacts_stored_credentials_in_any_text(monkeypatch, tmp_path):- """A credential Avibe stores leaves no trace however the text around it is shaped.-- Prose such as ``auth failed for <secret>`` has no key for a pattern to find, a- secret can be escaped by JSON or repr or name a dict entry, and an unreadable- store must not keep a rotated credential from being covered.- """- import json-- from config import paths- from config.v2_config import LarkConfig, TelegramConfig-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()- config = _config()- config.lark = LarkConfig(- app_id="cli_x",- app_secret='lark"first\\s3cret',- proxy_url="http://bob:q'[email protected]:8080",- )- config.telegram = TelegramConfig(bot_token="s3cr7")- config.save()- state = paths.get_runtime_dir() / "model-hub" / "state"- (state / "credentials").mkdir(parents=True)- (state / "instances" / "i1").mkdir(parents=True)- (state / "credentials" / "cred_a.json").write_text(- json.dumps({"kind": "api_key", "vendor": "openai", "value": "mh-stored-s3cret"})- )- (state / "instances" / "i1" / "runtime-secrets.json").write_text(- json.dumps({"management_key": "mh-management-s3cret", "gateway_token": "mh-gateway-s3cret"})- )- assert sentry_integration._refresh_known_secret_state()-- def send(message, extra=None):- event = {"logentry": {"message": message}, "breadcrumbs": {"values": [{"message": message}]}}- if extra is not None:- event["extra"] = extra- return json.dumps(sentry_integration.before_send(event, {}))-- first = send(- "rejected mh-stored-s3cret and mh-management-s3cret (openai); short s3cr7! "- + json.dumps({"note": 'lark"first\\s3cret'})- + " "- + repr('lark"first\\s3cret')- + " proxy refused q'proxy-s3cret",- extra={"sessions": {"mh-gateway-s3cret": "active"}},- )- for secret in ("mh-stored-s3cret", "mh-management-s3cret", "mh-gateway-s3cret", "s3cr7", "first", "proxy-s3cret"):- assert secret not in first- assert "rejected [Filtered] and [Filtered] (openai); short [Filtered]!" in first-- config.lark.app_secret = "lark-rotated-s3cret"- config.save()- assert sentry_integration._refresh_known_secret_state()- rotated = send("lark auth failed for lark-rotated-s3cret (cli_x)")- assert "lark-rotated-s3cret" not in rotated- assert "(cli_x)" in rotated---def test_before_send_keeps_request_records_to_their_origin(monkeypatch, tmp_path):- """Request records keep method, origin and status, never paths, queries or bodies.-- The shapes are the ones the SDK attaches: an HTTP client breadcrumb, a- subprocess breadcrumb and an incoming request.- """- import json-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()- event = {- "message": "request records",- "request": {- "method": "POST",- "url": "http://127.0.0.1:5123/api/media/md-s3cret",- "query_string": "state=st-s3cret",- "data": {"content": "body-s3cret"},- "cookies": "__Host-vibe_remote_session=ck-s3cret",- "headers": {"x-forwarded-for": "203.0.113.10"},- "env": {"REMOTE_ADDR": "203.0.113.10"},- },- "breadcrumbs": {- "values": [- {- "type": "http",- "category": "httplib",- "data": {- "http.method": "POST",- "url": "https://discord.com/api/webhooks/1/hk-s3cret",- "http.query": "wait=hq-s3cret",- "http.fragment": "fr-s3cret",- "http.response.status_code": 404,- },- },- {"type": "subprocess", "category": "subprocess", "message": "/usr/bin/git push https://x-access-token:[email protected]/o/r", "data": {"subprocess.cwd": "/srv/cw-s3cret"}},- ]- },- }-- sent = sentry_integration.before_send(event, {})- rendered = json.dumps(sent)-- assert "s3cret" not in rendered- assert sent["request"] == {"method": "POST", "url": "http://127.0.0.1:5123/[Filtered]"}- http_crumb, subprocess_crumb = sent["breadcrumbs"]["values"]- assert http_crumb["data"]["url"] == "https://discord.com/[Filtered]"- assert http_crumb["data"]["http.response.status_code"] == 404- assert subprocess_crumb["message"] == "git"- assert subprocess_crumb["data"] == {}---def test_known_secret_matching_survives_normalization_and_early_breadcrumbs(monkeypatch, tmp_path):- """A credential is protected before and after delimiter normalization on both hooks."""- import json-- from config.v2_config import LarkConfig-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))- monkeypatch.setenv("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW", "0")- config = _config()- config.lark = LarkConfig(app_secret="demo%3Acredential")- config.save()- assert sentry_integration._refresh_known_secret_state()-- breadcrumb = sentry_integration.before_breadcrumb(- {"message": "early breadcrumb demo%3Acredential"}, {}- )- subprocess_breadcrumb = sentry_integration.before_breadcrumb(- {- "type": "subprocess",- "category": "subprocess",- "message": "/usr/bin/git push demo%3Acredential",- "data": {"credential": "demo%3Acredential"},- },- {},- )- event = {- "message": "event demo%3Acredential and normalized demo:credential",- "breadcrumbs": {"values": [breadcrumb]},- }- sent = sentry_integration.before_send(event, {})-- rendered = json.dumps(sent)- assert "demo%3Acredential" not in rendered- assert "demo:credential" not in rendered- assert breadcrumb["message"] == "early breadcrumb [Filtered]"- assert subprocess_breadcrumb["message"] == "git"- assert subprocess_breadcrumb["data"] == {}---def test_known_secret_redaction_preserves_protocol_keys_and_filters_user_maps(monkeypatch, tmp_path):- """Stored values cannot rewrite Sentry schema keys while custom maps stay protected."""- from config.v2_config import LarkConfig-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))- monkeypatch.setenv("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW", "0")- config = _config()- config.lark = LarkConfig(app_secret="type")- config.save()- assert sentry_integration._refresh_known_secret_state()-- sent = sentry_integration.before_send(- {- "message": "failure type",- "exception": {"values": [{"type": "ValueError", "value": "type"}]},- "threads": {"values": [{"type": "type", "stacktrace": {"frames": [{"type": "type"}]}}]},- "contexts": {- "trace": {"type": "type", "values": "type"},- "custom": {"type": "type"},- },- "spans": [{"op": "http.client", "data": {"type": "type"}}],- "extra": {"type": "type"},- },- {},- )-- assert sent["message"] == "failure [Filtered]"- assert sent["exception"]["values"][0]["type"] == "ValueError"- assert sent["exception"]["values"][0]["value"] == "[Filtered]"- assert sent["threads"]["values"][0]["type"] == "[Filtered]"- assert sent["threads"]["values"][0]["stacktrace"]["frames"][0]["type"] == "[Filtered]"- assert sent["contexts"]["trace"]["type"] == "[Filtered]"- assert sent["contexts"]["trace"]["values"] == "[Filtered]"- assert sent["contexts"]["custom"]["[Filtered]"] == "[Filtered]"- assert sent["spans"][0]["data"] == {"[Filtered]": "[Filtered]"}-- config.lark.app_secret = "threads"- config.save()- assert sentry_integration._refresh_known_secret_state()- shape = sentry_integration.before_send(- {"threads": {"values": [{"type": "threads"}]}, "extra": {"threads": "threads"}}, {}- )- assert "threads" in shape- assert shape["threads"]["values"][0]["type"] == "[Filtered]"- assert shape["extra"] == {"[Filtered]": "[Filtered]"}- assert sent["extra"] == {"[Filtered]": "[Filtered]"}---def test_capture_hook_uses_published_snapshot_while_worker_refresh_blocks(monkeypatch, tmp_path):- import threading-- from config.v2_config import LarkConfig-- config = _config()- config.lark = LarkConfig(app_secret="hook-s3cret")- config.save()- assert sentry_integration._refresh_known_secret_state()- original_files = sentry_integration._known_secret_files- scan_entered = threading.Event()- release_scan = threading.Event()- hook_finished = threading.Event()-- def blocked_files():- scan_entered.set()- assert release_scan.wait(2)- return original_files()-- monkeypatch.setattr(sentry_integration, "_known_secret_files", blocked_files)- refresh = threading.Thread(target=sentry_integration._refresh_known_secret_state)- refresh.start()- assert scan_entered.wait(1)-- def capture_breadcrumb():- result = sentry_integration.before_breadcrumb({"message": "ordinary warning"}, {})- assert result == {"message": "ordinary warning"}- hook_finished.set()-- hook = threading.Thread(target=capture_breadcrumb)- hook.start()- try:- assert hook_finished.wait(1)- finally:- release_scan.set()- refresh.join(2)- hook.join(2)- assert hook_finished.is_set()---def test_init_sentry_disables_spotlight_env_bypass(monkeypatch, tmp_path):- import sentry_sdk-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_SENTRY_DSN", "http://[email protected]:9/1")- monkeypatch.setenv("SENTRY_SPOTLIGHT", "true")- sent = []-- class Response:- status = 200- headers = {}- data = b""- content = b""-- def close(self):- return None-- monkeypatch.setattr(- sentry_integration._RedactingHttpTransport,- "_request",- lambda _transport, _method, _endpoint_type, body, headers: sent.append(body) or Response(),- )- try:- assert sentry_integration.init_sentry(_config(), component="service") is True- client = sentry_sdk.get_client()- assert client.spotlight is None- sentry_sdk.capture_message("spotlight disabled")- sentry_sdk.flush(timeout=2)- assert sent- finally:- sentry_sdk.get_client().close(timeout=0)- sentry_sdk.get_global_scope().set_client(None)---def _decode_sentry_wire_body(body, headers):- if headers["Content-Encoding"] == "br":- import brotli- return brotli.decompress(body)- import gzip-- assert headers["Content-Encoding"] == "gzip"- return gzip.decompress(body)---def test_performance_transactions_are_scrubbed_like_events(monkeypatch, tmp_path):- """Transactions skip ``before_send``; their spans must not carry what events may not."""-- import sentry_sdk- from sentry_sdk.envelope import Envelope-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_SENTRY_DSN", "http://[email protected]:9/1")- monkeypatch.setenv("VIBE_SENTRY_TRACES_SAMPLE_RATE", "1.0")- sent = []-- class Response:- status = 200- headers = {}- data = b""- content = b""-- def close(self):- return None-- def request(_transport, _method, _endpoint_type, body, headers):- sent.append((body, headers))- return Response()-- monkeypatch.setattr(sentry_integration._RedactingHttpTransport, "_request", request)- try:- assert sentry_integration.init_sentry(_config(), component="service") is True- with sentry_sdk.start_transaction(op="task", name="refresh"):- with sentry_sdk.start_span(op="http.client", name="POST https://discord.com/api/webhooks/1/tx-s3cret") as span:- span.set_data("url", "https://discord.com/api/webhooks/1/tx-s3cret")- span.set_data("http.query", "wait=tq-s3cret")- with sentry_sdk.start_span(op="subprocess", name="git push https://x:[email protected]/o/r"):- pass- with sentry_sdk.start_span(op="task", name="refresh lark app_secret=ts-s3cret"):- pass- sentry_sdk.flush(timeout=2)- finally:- sentry_sdk.get_client().close(timeout=0)- sentry_sdk.get_global_scope().set_client(None)-- (body, headers), = sent- raw = _decode_sentry_wire_body(body, headers)- envelope = Envelope.deserialize(raw)- payload = next(item.get_bytes().decode("utf-8") for item in envelope.items if item.type == "transaction")- assert "s3cret" not in payload- assert "https://discord.com/[Filtered]" in payload---def test_real_sdk_event_shapes_preserve_protocol_ownership(monkeypatch, tmp_path):- import json-- import sentry_sdk- from config.v2_config import LarkConfig, TelegramConfig- from sentry_sdk.envelope import Envelope-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_SENTRY_DSN", "http://[email protected]:9/1")- config = _config()- config.slack.signing_secret = "logentry"- config.lark = LarkConfig(app_secret="frames")- config.telegram = TelegramConfig(bot_token="type")- config.save()- sent = []-- class Response:- status = 200- headers = {}- data = b""- content = b""-- def close(self):- return None-- monkeypatch.setattr(- sentry_integration._RedactingHttpTransport,- "_request",- lambda _transport, _method, _endpoint_type, body, headers: sent.append((body, headers)) or Response(),- )- try:- assert sentry_integration.init_sentry(config, component="service") is True- sentry_sdk.capture_event(- {- "message": "schema ownership",- "logentry": {"message": "failure"},- "exception": {- "values": [- {"type": "ValueError", "stacktrace": {"frames": [{"filename": "worker.py"}]}}- ]- },- "contexts": {- "trace": {"type": "trace", "trace_id": "a" * 32, "span_id": "b" * 16},- "custom": {"type": "type"},- },- }- )- sentry_sdk.flush(timeout=2)- finally:- sentry_sdk.get_client().close(timeout=0)- sentry_sdk.get_global_scope().set_client(None)-- (body, headers), = sent- raw = _decode_sentry_wire_body(body, headers)- envelope = Envelope.deserialize(raw)- payload = json.loads(next(item.get_bytes() for item in envelope.items if item.type == "event"))- assert payload["logentry"]["message"] == "failure"- assert payload["exception"]["values"][0]["stacktrace"]["frames"][0]["filename"] == "worker.py"- assert payload["contexts"]["trace"]["type"] == "trace"- assert payload["contexts"]["custom"] == {"[Filtered]": "[Filtered]"}---def test_worker_scrub_retains_rotated_secret_after_enqueue(monkeypatch, tmp_path):- """A value queued before rotation remains covered by the process-lifetime union."""- import threading-- import sentry_sdk- from config.v2_config import LarkConfig- from sentry_sdk.envelope import Envelope-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _config()- config.lark = LarkConfig(app_secret="old-worker-s3cret")- config.save()- monkeypatch.setenv("VIBE_SENTRY_DSN", "http://[email protected]:9/1")- assert sentry_integration.init_sentry(config, component="service") is True- sent = []-- class Response:- status = 200- headers = {}- data = b""- content = b""-- def close(self):- return None-- def request(_transport, _method, _endpoint_type, body, headers):- sent.append((body, headers))- return Response()-- monkeypatch.setattr(sentry_integration._RedactingHttpTransport, "_request", request)- original_files = sentry_integration._known_secret_files- scan_entered = threading.Event()- release_scan = threading.Event()-- def blocked_files():- scan_entered.set()- assert release_scan.wait(2)- return original_files()-- monkeypatch.setattr(sentry_integration, "_known_secret_files", blocked_files)- transport = sentry_sdk.get_client().transport- envelope = Envelope()- envelope.add_event({"message": "old-worker-s3cret"})- transport.capture_envelope(envelope)- assert scan_entered.wait(2)-- config.lark.app_secret = "new-worker-s3cret"- config.save()- release_scan.set()- sentry_sdk.flush(timeout=2)- assert transport._worker.is_alive- transport.kill()- assert not transport._worker.is_alive-- try:- (body, headers), = sent- raw = _decode_sentry_wire_body(body, headers)- assert "old-worker-s3cret" not in raw.decode("utf-8")- finally:- sentry_sdk.get_client().close(timeout=0)- sentry_sdk.get_global_scope().set_client(None)---def test_worker_drops_envelope_when_secret_read_is_uncertain(monkeypatch, tmp_path):- import sentry_sdk- from config import paths- from config.v2_config import LarkConfig- from sentry_sdk.envelope import Envelope-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _config()- config.lark = LarkConfig(app_secret="uncertain-worker-s3cret")- config.save()- monkeypatch.setenv("VIBE_SENTRY_DSN", "http://[email protected]:9/1")- assert sentry_integration.init_sentry(config, component="service") is True- sent = []-- class Response:- status = 200- headers = {}-- def close(self):- return None-- monkeypatch.setattr(- sentry_integration._RedactingHttpTransport,- "_request",- lambda _transport, _method, _endpoint_type, body, headers: sent.append(body) or Response(),- )- paths.get_config_path().write_text("{not json", encoding="utf-8")- envelope = Envelope()- envelope.add_event({"message": "uncertain-worker-s3cret"})- sentry_sdk.get_client().transport.capture_envelope(envelope)- sentry_sdk.flush(timeout=2)-- try:- assert sent == []- finally:- sentry_sdk.get_client().close(timeout=0)- sentry_sdk.get_global_scope().set_client(None)---def test_worker_scrub_drops_attachments_and_unknown_raw_items(monkeypatch, tmp_path):- from config.v2_config import LarkConfig- from sentry_sdk.envelope import Envelope, Item-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _config()- config.lark = LarkConfig(app_secret="raw-item-s3cret")- config.save()- assert sentry_integration._refresh_known_secret_state()-- envelope = Envelope(headers={"trace": {"trace_id": "trace-id"}, "diagnostic": "raw-item-s3cret"})- envelope.add_event({"message": "raw-item-s3cret"})- envelope.add_item(Item(payload=b"raw-item-s3cret", type="attachment"))- envelope.add_item(Item(payload=b"raw-item-s3cret", type="future_item"))-- scrubbed = sentry_integration._scrub_envelope(envelope)- assert envelope.items[0].payload.json["message"] == "raw-item-s3cret"- assert [item.type for item in scrubbed.items] == ["event"]- assert "raw-item-s3cret" not in scrubbed.serialize().decode("utf-8")-- only_attachment = Envelope(items=[Item(payload=b"raw-item-s3cret", type="attachment")])- with pytest.raises(sentry_integration._DropEnvelope):- sentry_integration._scrub_envelope(only_attachment)-- unsafe_headers = Envelope(headers={"trace": {"secret": "raw-item-s3cret"}})- unsafe_headers.add_event({"message": "safe"})- with pytest.raises(sentry_integration._DropEnvelope):- sentry_integration._scrub_envelope(unsafe_headers)---def test_worker_scrub_covers_default_structured_item_families(monkeypatch, tmp_path):- from config.v2_config import LarkConfig- from sentry_sdk.envelope import Envelope, Item, PayloadRef-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _config()- config.lark = LarkConfig(app_secret="structured-item-s3cret")- config.save()- assert sentry_integration._refresh_known_secret_state()- payloads = {- "log": {"items": [{"body": "structured-item-s3cret", "attributes": {"secret": "structured-item-s3cret"}}]},- "trace_metric": {"items": [{"name": "structured-item-s3cret", "attributes": {"secret": "structured-item-s3cret"}}]},- "span": {"items": [{"name": "structured-item-s3cret", "attributes": {"secret": "structured-item-s3cret"}}]},- "session": {"sid": "structured-item-s3cret"},- "sessions": {"aggregates": [{"sid": "structured-item-s3cret"}]},- "client_report": {"discarded_events": [{"reason": "structured-item-s3cret"}]},- "check_in": {"check_in_id": "structured-item-s3cret"},- "profile": {"sample": "structured-item-s3cret"},- "profile_chunk": {"sample": "structured-item-s3cret"},- }-- for item_type, payload in payloads.items():- envelope = Envelope(items=[Item(payload=PayloadRef(json=payload), type=item_type)])- scrubbed = sentry_integration._scrub_envelope(envelope)- assert scrubbed.items[0].type == item_type- assert "structured-item-s3cret" not in scrubbed.serialize().decode("utf-8")---def test_worker_scrub_fails_closed_on_observation_overflow(monkeypatch, tmp_path):- from config.v2_config import LarkConfig- from sentry_sdk.envelope import Envelope-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config = _config()- config.lark = LarkConfig(app_secret="overflow-worker-s3cret")- config.save()- monkeypatch.setattr(sentry_integration, "_KNOWN_SECRET_MAX_VALUES", 0)-- assert not sentry_integration._refresh_known_secret_state()- assert sentry_integration._known_secret_files_state == {}- assert "overflow-worker-s3cret" not in sentry_integration._known_secret_values- config_path = sentry_integration.paths.get_config_path()- config_path.unlink()- assert not sentry_integration._refresh_known_secret_state()- assert sentry_integration._scrub_outgoing({"message": "overflow-worker-s3cret"}) is None- assert sentry_integration.before_send({"message": "overflow-worker-s3cret"}, {}) is None- envelope = Envelope()- envelope.add_event({"message": "overflow-worker-s3cret"})- with pytest.raises(sentry_integration._DropEnvelope):- sentry_integration._scrub_envelope(envelope)---def test_worker_scrub_fails_closed_on_file_state_overflow(monkeypatch, tmp_path):- monkeypatch.setattr(sentry_integration, "_KNOWN_SECRET_MAX_FILES", 0)- config = _config()- config.save()-- assert not sentry_integration._refresh_known_secret_state()- assert sentry_integration._known_secret_files_state == {}- assert not sentry_integration._known_secret_collection_is_complete()--[email protected]("unit", ["\\", "a.", "x-api-"])-def test_scrub_data_stays_linear_on_pathological_text(unit):- """Scrubbing runs synchronously on every log call, so it must never backtrack."""- import time-- text = unit * (40_000 // len(unit))- started = time.perf_counter()- sentry_integration.scrub_data(text)- assert time.perf_counter() - started < 1.0--- ("first", "second"),- [- (- "Failed to retrieve WSS URL: The request to the Slack API failed. "- "(url: https://slack.com/api/apps.connections.open, status: 200)",- "Failed to retrieve WSS URL: The request to the Slack API failed. "- "(url: https://slack.com/api/apps.connections.open, status: 200)",- ),- # Two different reconnect failures share the filter's fingerprint only- # through the method name, which appears inside the URL.- (- "The request to the Slack API failed. (url: https://slack.com/api/apps.connections.open, status: 200)",- "The request to the Slack API failed. (url: https://slack.com/api/apps.connections.open, status: 503)",- ),- ],-)-def test_before_send_throttles_repeated_noisy_slack_socket_events(monkeypatch, first, second):- monkeypatch.delenv("VIBE_SENTRY_NOISE_FILTERS", raising=False)- monkeypatch.delenv("VIBE_SENTRY_NOISE_TTL_SECONDS", raising=False)- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()-- def event(formatted):- return {"logger": "slack_sdk.socket_mode.aiohttp", "logentry": {"formatted": formatted}}-- assert sentry_integration.before_send(event(first), {}) is not None- assert sentry_integration.before_send(event(second), {}) is None---def test_before_send_throttles_repeated_normal_errors(monkeypatch):- monkeypatch.delenv("VIBE_SENTRY_NOISE_FILTERS", raising=False)- monkeypatch.delenv("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW", raising=False)- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()- event = {- "logger": "core.message_dispatcher",- "logentry": {"formatted": "Failed to send result message: unexpected application bug"},- }-- assert sentry_integration.before_send(dict(event), {}) is not None- assert sentry_integration.before_send(dict(event), {}) is None--- ("first", "second"),- [- (- "Failed to send result message: unexpected application bug",- "Failed to send result message: different application bug",- ),- # Errors on one host differ only by path, which the sent event no longer carries.- (- "Upload failed: 404 url=https://api.example.com/v1/files",- "Upload failed: 404 url=https://api.example.com/v1/messages",- ),- ],-)-def test_before_send_allows_distinct_normal_errors(monkeypatch, first, second):- monkeypatch.delenv("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW", raising=False)- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()- first_event = {- "logger": "core.message_dispatcher",- "logentry": {"formatted": first},- }- second_event = {- "logger": "core.message_dispatcher",- "logentry": {"formatted": second},- }-- assert sentry_integration.before_send(dict(first_event), {}) is not None- assert sentry_integration.before_send(dict(second_event), {}) is not None---def test_before_send_allows_distinct_exception_values(monkeypatch):- monkeypatch.delenv("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW", raising=False)- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()- first_event = {"exception": {"values": [{"type": "ValueError", "value": "invalid channel C123456789"}]}}- second_event = {"exception": {"values": [{"type": "ValueError", "value": "invalid channel C987654321"}]}}-- assert sentry_integration.before_send(dict(first_event), {}) is not None- assert sentry_integration.before_send(dict(second_event), {}) is not None- assert sentry_integration.before_send(dict(first_event), {}) is None---def test_before_send_noise_filter_can_be_disabled(monkeypatch):- monkeypatch.setenv("VIBE_SENTRY_NOISE_FILTERS", "0")- monkeypatch.setenv("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW", "0")- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()- event = {- "logger": "core.watches",- "logentry": {"formatted": "Managed watch reconcile failed: [Errno 28] No space left on device"},- }-- assert sentry_integration.before_send(dict(event), {}) is not None- assert sentry_integration.before_send(dict(event), {}) is not None---def test_before_send_rate_limit_can_be_raised(monkeypatch):- monkeypatch.setenv("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW", "2")- sentry_integration._NOISY_EVENT_LAST_SEEN.clear()- sentry_integration._EVENT_RATE_STATE.clear()- event = {- "logger": "core.message_dispatcher",- "logentry": {"formatted": "Failed to send result message: recurring application bug"},- }-- assert sentry_integration.before_send(dict(event), {}) is not None- assert sentry_integration.before_send(dict(event), {}) is not None- assert sentry_integration.before_send(dict(event), {}) is None---def test_event_rate_state_enforces_cache_limit(monkeypatch):- monkeypatch.setattr(sentry_integration, "_EVENT_RATE_CACHE_LIMIT", 2)- sentry_integration._EVENT_RATE_STATE.clear()-- for index in range(4):- event = {- "logger": "core.message_dispatcher",- "logentry": {"formatted": f"unique application bug {index}"},- }- assert sentry_integration.before_send(event, {}) is not None-- assert len(sentry_integration._EVENT_RATE_STATE) == 2---def test_event_rate_state_evicts_oldest_entries(monkeypatch):- monkeypatch.setattr(sentry_integration, "_EVENT_RATE_CACHE_LIMIT", 2)- sentry_integration._EVENT_RATE_STATE.clear()- sentry_integration._EVENT_RATE_STATE.update(- {- "z-oldest": (1.0, 1),- "a-middle": (2.0, 1),- "m-newest": (3.0, 1),- }- )-- sentry_integration._prune_event_rate_state(now=3.0, window_seconds=10.0)-- assert "z-oldest" not in sentry_integration._EVENT_RATE_STATE- assert set(sentry_integration._EVENT_RATE_STATE) == {"a-middle", "m-newest"}---def test_before_send_rate_state_is_thread_safe(monkeypatch):- monkeypatch.setattr(sentry_integration, "_EVENT_RATE_CACHE_LIMIT", 8)- sentry_integration._EVENT_RATE_STATE.clear()-- def send_event(index: int) -> bool:- event = {- "logger": "core.message_dispatcher",- "logentry": {"formatted": f"concurrent application bug {index}"},- }- return sentry_integration.before_send(event, {}) is not None-- with ThreadPoolExecutor(max_workers=8) as executor:- results = list(executor.map(send_event, range(64)))-- assert all(results)- assert len(sentry_integration._EVENT_RATE_STATE) <= 8---def test_sentry_events_carry_no_frame_locals(monkeypatch, tmp_path):- """An error event keeps its traceback but never the values its frames held.-- Frame locals carry what ``scrub_data`` cannot see into, such as a Vibey tool- context's whole environment rendered as one repr string.- """- import json- import logging- import uuid-- import sentry_sdk-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- monkeypatch.setenv("VIBE_SENTRY_DSN", "http://[email protected]:9/1")- events = []-- def capture(event, hint):- events.append(event)- return None # dropped before any transport-- monkeypatch.setattr(sentry_integration, "before_send", capture)- # Built at runtime: the event's source-context lines must not be what carries it.- secret = f"sk-{uuid.uuid4().hex}"-- def tool_execute(arguments, env):- raise RuntimeError("database is locked")-- try:- assert sentry_integration.init_sentry(_config(), component="service") is True- try:- tool_execute({"path": "/etc/hosts"}, {"OPENAI_API_KEY": secret})- except RuntimeError:- logging.getLogger("tests.sentry_frame_locals").exception("Tool execution failed")- sentry_sdk.flush(timeout=2)- finally:- sentry_sdk.get_client().close(timeout=0)- sentry_sdk.get_global_scope().set_client(None)-- (event,) = events- frames = event["exception"]["values"][0]["stacktrace"]["frames"]- assert [frame["function"] for frame in frames][-1] == "tool_execute"- assert all("vars" not in frame for frame in frames)- assert secret not in json.dumps(event, default=str)diff --git a/uv.lock b/uv.lockindex e2b35f561..50cd9a695 100644--- a/uv.lock+++ b/uv.lock@@ -402,7 +402,6 @@ dependencies = [{ name = "pywebpush" },{ name = "pyyaml" },{ name = "requests" },- { name = "sentry-sdk" },{ name = "slack-sdk" },{ name = "sqlalchemy", version = "2.0.54", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },{ name = "sqlalchemy", version = "2.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },@@ -455,7 +454,6 @@ requires-dist = [{ name = "pywebpush", specifier = ">=2.0.3" },{ name = "pyyaml", specifier = ">=6.0" },{ name = "requests", specifier = ">=2.31.0" },- { name = "sentry-sdk", specifier = "==2.56.0" },{ name = "slack-sdk", specifier = ">=3.26.0" },{ name = "sqlalchemy", specifier = ">=2.0.0" },{ name = "starlette", specifier = ">=1.3.1" },@@ -3250,19 +3248,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d1/b7/b95708304cd49b7b6f82fdd039f1748b66ec2b21d6a45180910802f1abf1/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:ac37f9f516c51e5753f27dfdef11a88330f04de2d564be3991384b2f3535d02e", size = 562191, upload-time = "2025-11-30T20:24:36.853Z" },]-[[package]]-name = "sentry-sdk"-version = "2.56.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "certifi" },- { name = "urllib3" },-]-sdist = { url = "https://files.pythonhosted.org/packages/de/df/5008954f5466085966468612a7d1638487596ee6d2fd7fb51783a85351bf/sentry_sdk-2.56.0.tar.gz", hash = "sha256:fdab72030b69625665b2eeb9738bdde748ad254e8073085a0ce95382678e8168", size = 426820, upload-time = "2026-03-24T09:56:36.575Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/cd/1a/b3a3e9f6520493fed7997af4d2de7965d71549c62f994a8fd15f2ecd519e/sentry_sdk-2.56.0-py2.py3-none-any.whl", hash = "sha256:5afafb744ceb91d22f4cc650c6bd048ac6af5f7412dcc6c59305a2e36f4dbc02", size = 451568, upload-time = "2026-03-24T09:56:34.807Z" },-]-[[package]]name = "six"version = "1.17.0"diff --git a/vibe/sentry_integration.py b/vibe/sentry_integration.pydeleted file mode 100644index 87b4be87a..000000000--- a/vibe/sentry_integration.py+++ /dev/null@@ -1,1201 +0,0 @@-from __future__ import annotations--import json-import logging-import os-import platform-import re-import socket-import sys-import threading-import time-from pathlib import Path-from typing import Any, Optional-from urllib.parse import quote, urlsplit--from config.v2_config import V2Config-from config import paths--try:- from sentry_sdk.transport import HttpTransport as _SentryHttpTransport-except Exception: # pragma: no cover - the dependency is required in packaged builds- _SentryHttpTransport = None--logger = logging.getLogger(__name__)--# Fill this with the real project DSN to make Sentry default-on across deployments.-DEFAULT_SENTRY_DSN = "https://b97175a2d2325951f1861e8a4386f840@o4511104395051008.ingest.us.sentry.io/4511104396820480"-DEFAULT_TRACES_SAMPLE_RATE = 0.0-DEFAULT_PROFILES_SAMPLE_RATE = 0.0-DEPLOYMENT_ENV_VAR = "VIBE_DEPLOYMENT_ENV"--_SENSITIVE_KEY_PARTS = (- "access_key",- "aes_key",- "api_key",- "app_token",- "authorization",- "bot_token",- "client_secret",- "cookie",- "credential",- "dsn",- "management_key",- "passphrase",- "password",- "private_key",- "secret",- "signing_secret",- "token",- "webhook",- "workspace_token",-)-# Generic names a credential also travels under, matched only as the whole key so-# ``cache_key`` or ``author`` stay readable. Model Hub sends ``{"key": ...}`` to-# validate a credential before it is stored anywhere.-_SENSITIVE_EXACT_KEYS = ("auth", "key")-# Fields that carry a request's query string; dropped whole.-_DROPPED_KEYS = frozenset({"http.query", "http.fragment", "query_string"})-_REDACTED = "[Filtered]"---def _normalized_key(key: str) -> str:- # ``api_key``, ``apiKey``, ``x-api-key`` and ``API-KEY`` name the same credential.- return re.sub(r"[^a-z0-9]", "", key.lower())---_SENSITIVE_KEY_TOKENS = tuple(_normalized_key(part) for part in _SENSITIVE_KEY_PARTS)---def _text_key_pattern(token: str) -> str:- # A normalized key as it may be written in text: any case, with an optional- # ``_``, ``-`` or ``.`` between its characters.- return "[_.-]?".join(re.escape(char) for char in token)---# A sensitive key rendered into free text: a dataclass repr, a header line,-# ``key=value``, or JSON, including JSON nested inside a JSON string. The key-# starts at a word boundary, and the key and its escaping depth are bounded so-# long runs of word characters or backslashes stay linear.-# A quoted value ends at its first unescaped closing delimiter; when none is-# found, everything after the opening delimiter is redacted rather than kept. An-# unquoted value led by an auth scheme (``Bearer <token>``) includes the token.-_SENSITIVE_KEY_VALUE_RE = re.compile(- r"(?i)(?<![\w.-])(?P<kq>\\{0,4}[\"']?)"- r"(?:[\w.-]{0,40}(?:" + "|".join(_text_key_pattern(token) for token in _SENSITIVE_KEY_TOKENS) + r")[\w.-]{0,40}"- r"|" + "|".join(_text_key_pattern(key) for key in _SENSITIVE_EXACT_KEYS) + r")"- r"(?P=kq)\s*[:=]\s*"- r"(?:(?P<vq>\\{0,4}[\"'])(?P<quoted>.*?)(?:(?<!\\)(?P=vq)|\Z)"- r"|(?P<bare>(?:(?:basic|bearer|bot|digest|token)\s+)?(?:[^\s\"'\\]|\\(?![\"']))+))",- re.DOTALL,-)---def _redact_key_value(match: re.Match[str]) -> str:- group = "quoted" if match.group("quoted") is not None else "bare"- start, end = match.span(group)- offset = match.start()- text = match.group(0)- return text[: start - offset] + _REDACTED + text[end - offset :]---# Any URL keeps only its origin. A path, query, fragment or userinfo carries-# capabilities no key name announces: a Slack response_url, a Discord-# interaction token, WeChat CDN parameters, a Telegram bot token, a proxy-# password. An authority that is not a plain host[:port] is dropped whole. The-# scheme is length-bounded so runs like ``a.a.a`` stay linear, and a backslash-# stands for a slash as browsers read it; it ends the URL only before a quote.-# A ``user:pass`` whose password holds a quote or bracket would end the URL-# early, so a colon-bearing authority cut by one of them, with an ``@`` before-# the next space, is read as userinfo running to that ``@`` - unless the cut is-# compact JSON structure (``","`` or ``":"``), as after ``"http://host:8080"``.-_URL_RE = re.compile(- r"(?i)\b(?P<scheme>[a-z][a-z0-9+.-]{0,30}:[/\\]{2})"- r"(?:(?P<userinfo>[^\s/\\?#\"'<>`@]*:[^\s/\\?#\"'<>`@]*"- r"(?![\"'][,:][\"'])\\{0,4}[\"'<>`](?:(?![\"'][,:][\"'])[^\s@]){0,256})@)?"- r"(?P<authority>[^\s/\\?#\"'<>`]*)"- r"(?P<rest>(?:[^\s\"'<>`\\]|\\(?![\"']))*)"-)-# The same for a URL written without its scheme: ``hooks.slack.com/actions/...``,-# ``//host/path``, ``10.0.0.5:8080/path``, ``localhost:5123/path``.-_SCHEMELESS_URL_RE = re.compile(- r"(?i)(?:(?<=//)|(?<![\w.@/-]))"- r"(?P<host>(?:(?:[a-z0-9-]{1,63}\.){1,10}[a-z]{2,24}|\d{1,3}(?:\.\d{1,3}){3}|localhost|\[[0-9a-f:.]{2,45}\])"- r"(?::\d{1,5})?)(?P<rest>/(?:[^\s\"'<>`\\]|\\(?![\"']))*)"-)-# URL delimiters spelled another way: percent-encoded (any depth of ``%25``),-# JSON ``\u00XX`` or ``\/``, or an HTML character reference. They are read as-# the delimiter itself before URLs and keys are matched.-_DELIMITER_CHARACTERS = {- "3a": ":", "2f": "/", "5c": "\\", "3f": "?", "23": "#", "40": "@", "3d": "=", "26": "&",-}-_DELIMITER_DECIMALS = {"58": ":", "47": "/", "92": "\\", "63": "?", "35": "#", "64": "@", "61": "=", "38": "&"}-_DELIMITER_NAMES = {- "colon": ":", "sol": "/", "bsol": "\\", "quest": "?", "num": "#", "commat": "@", "equals": "=", "amp": "&",-}-_ENCODED_DELIMITER_RE = re.compile(- r"(?i)%(?:25)*(?P<pct>3a|2f|5c|3f|23|40|3d|26)"- r"|\\u00(?P<uni>3a|2f|5c|3f|23|40|3d|26)"- r"|�*(?P<hex>3a|2f|5c|3f|23|40|3d|26);?"- r"|�*(?P<dec>58|47|92|63|35|64|61|38);?"- r"|&(?P<name>colon|sol|bsol|quest|num|commat|equals|amp);"- r"|\\(?P<slash>/)"-)---def _decoded_delimiter(match: re.Match[str]) -> str:- if match.group("slash"):- return "/"- if match.group("dec"):- return _DELIMITER_DECIMALS[match.group("dec")]- if match.group("name"):- return _DELIMITER_NAMES[match.group("name").lower()]- code = match.group("pct") or match.group("uni") or match.group("hex")- return _DELIMITER_CHARACTERS[code.lower()]---_URL_HOST_RE = re.compile(r"(?i)(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])(?::\d{1,5})?")-_URL_TRAILING_PUNCTUATION = ".,;:!?)]}"---def _reduced_url(origin: str, rest: str) -> str:- marker = "/" + _REDACTED- if rest.startswith(marker) and not rest[len(marker) :].rstrip(_URL_TRAILING_PUNCTUATION):- # Already reduced: scrubbing runs on a breadcrumb and again on its event.- return origin + rest- path = rest.rstrip(_URL_TRAILING_PUNCTUATION)- return origin + (marker if path else "") + rest[len(path) :]---def _url_origin(match: re.Match[str]) -> str:- _, at, host = match.group("authority").rpartition("@")- if not _URL_HOST_RE.fullmatch(host):- return match.group("scheme") + _REDACTED- has_userinfo = bool(at or match.group("userinfo") is not None)- return _reduced_url(match.group("scheme") + (_REDACTED + "@" if has_userinfo else "") + host, match.group("rest"))---def _schemeless_url_origin(match: re.Match[str]) -> str:- return _reduced_url(match.group("host"), match.group("rest"))---_URL_REPLACEMENTS = (- (_URL_RE, _url_origin),- (_SCHEMELESS_URL_RE, _schemeless_url_origin),-)-_STRING_REPLACEMENTS = (- (_ENCODED_DELIMITER_RE, _decoded_delimiter),- *_URL_REPLACEMENTS,- (re.compile(r"(?i)(authorization[:=]\s*)(bearer\s+)?\S+"), r"\1" + _REDACTED),- (re.compile(r"(?i)(token=)[^&\s]+"), r"\1" + _REDACTED),- (re.compile(r"(?i)(cookie[:=]\s*)\S+"), r"\1" + _REDACTED),- (re.compile(r"\bxox[baprs]-[A-Za-z0-9-]+\b"), _REDACTED),- (re.compile(r"\bxapp-[A-Za-z0-9-]+\b"), _REDACTED),- (_SENSITIVE_KEY_VALUE_RE, _redact_key_value),- # A Telegram bot token outside a URL (``bot<id>:<secret>``).- (re.compile(r"\b(bot)?\d{5,}:[A-Za-z0-9_-]{30,}"), r"\1" + _REDACTED),-)-# Credential values Avibe stores. Values shorter than this are not secrets worth-# the noise; short ones (below the boundary length) match only as a whole word.-_KNOWN_SECRET_MIN_LENGTH = 4-_KNOWN_SECRET_BOUNDARY_LENGTH = 12-# These caps bound the process-lifetime observation set and the compiled matcher.-# They are deliberately fail-closed: once a cap is exceeded, old observations are-# retained and telemetry is dropped rather than evicting a still-usable secret.-_KNOWN_SECRET_MAX_VALUES = 4096-_KNOWN_SECRET_MAX_VALUE_BYTES = 256 * 1024-_KNOWN_SECRET_MAX_PATTERN_BYTES = 512 * 1024-_KNOWN_SECRET_MAX_FILE_BYTES = 1024 * 1024-_KNOWN_SECRET_MAX_FILES = 1024-_KNOWN_SECRETS_LOCK = threading.RLock()-# path -> file signature; secret values live only in the process-lifetime union below.-_known_secret_files_state: dict[str, tuple[int, int, int, int]] = {}-_known_secret_values: set[str] = set()-# (ready, retained values at publication, compiled matcher). Hooks read this one-# immutable pointer; refresh publishes only after the worker has completed its scan.-_known_secret_snapshot: tuple[bool, frozenset[str] | None, re.Pattern[str] | None] = (False, None, None)-_known_secret_collection_uncertain = False-_known_secret_collection_overflowed = False---class _DropEnvelope(Exception):- """Private, secret-free signal used to fail closed before HTTP serialization."""-- pass---_ONE_DAY_SECONDS = 60 * 60 * 24-_NOISY_EVENT_TTL_SECONDS = _ONE_DAY_SECONDS-_NOISY_EVENT_CACHE_LIMIT = 128-_NOISY_EVENT_LAST_SEEN: dict[str, float] = {}-_SENTRY_EVENT_CACHE_LOCK = threading.RLock()-_EVENT_RATE_WINDOW_SECONDS = _ONE_DAY_SECONDS * 2-_EVENT_RATE_LIMIT_PER_WINDOW = 1-_EVENT_RATE_CACHE_LIMIT = 2048-_EVENT_RATE_STATE: dict[str, tuple[float, int]] = {}-_NETWORK_EXCEPTION_TYPES = {- "ClientConnectorDNSError",- "ClientConnectorError",- "ClientOSError",- "ConnectionResetError",- "ConnectionTimeoutError",- "ServerDisconnectedError",- "TimeoutError",-}---def _redact_string(value: str, *, minimize_urls: bool = True) -> str:- redacted = value- for pattern, replacement in _STRING_REPLACEMENTS:- if not minimize_urls and (pattern, replacement) in _URL_REPLACEMENTS:- continue- redacted = pattern.sub(replacement, redacted)- return redacted---def _is_sensitive_key(key: str) -> bool:- normalized = _normalized_key(key)- return normalized in _SENSITIVE_EXACT_KEYS or any(token in normalized for token in _SENSITIVE_KEY_TOKENS)---def scrub_data(value: Any, *, minimize_urls: bool = True) -> Any:- if isinstance(value, dict):- scrubbed: dict[Any, Any] = {}- for key, item in value.items():- # A key can itself be a secret, such as a token naming a cache entry.- out_key = _redact_string(key, minimize_urls=minimize_urls) if isinstance(key, str) else key- if isinstance(key, str) and (key in _DROPPED_KEYS or _is_sensitive_key(key)):- scrubbed[out_key] = _REDACTED- else:- scrubbed[out_key] = scrub_data(item, minimize_urls=minimize_urls)- return scrubbed- if isinstance(value, list):- return [scrub_data(item, minimize_urls=minimize_urls) for item in value]- if isinstance(value, tuple):- return tuple(scrub_data(item, minimize_urls=minimize_urls) for item in value)- if isinstance(value, str):- return _redact_string(value, minimize_urls=minimize_urls)- return value---def _program_name(command: Any) -> str | None:- # A command line carries whatever its caller passed; keep the program name.- words = command.split() if isinstance(command, str) else []- return os.path.basename(words[0]) if words else None---def _minimize_breadcrumb(crumb: dict[str, Any]) -> dict[str, Any]:- if crumb.get("type") != "subprocess" and crumb.get("category") != "subprocess":- return crumb- return {**crumb, "message": _program_name(crumb.get("message")), "data": {}}---def _minimize_span(span: dict[str, Any]) -> dict[str, Any]:- operation = str(span.get("op") or span.get("name") or "")- if not operation.startswith("subprocess"):- return span- minimized = dict(span)- for key in ("description", "name"):- if key in span:- minimized[key] = _program_name(span.get(key))- for key in ("data", "attributes"):- if key in span:- minimized[key] = {}- return minimized---def _minimize_event(event: dict[str, Any]) -> dict[str, Any]:- minimized = dict(event)- request = event.get("request")- if isinstance(request, dict):- # An incoming request's query, body, cookies, headers and environment- # stay local; the transaction already names the route.- minimized["request"] = {key: request[key] for key in ("method", "url") if key in request}- breadcrumbs = event.get("breadcrumbs")- if isinstance(breadcrumbs, dict) and isinstance(breadcrumbs.get("values"), list):- minimized["breadcrumbs"] = {- **breadcrumbs,- "values": [- _minimize_breadcrumb(crumb) if isinstance(crumb, dict) else crumb for crumb in breadcrumbs["values"]- ],- }- spans = event.get("spans")- if isinstance(spans, list):- minimized["spans"] = [_minimize_span(span) if isinstance(span, dict) else span for span in spans]- return minimized---def _collect_secret_values(- node: Any, found: set[str], *, value_keys: frozenset[str] = frozenset(), sensitive: bool = False-) -> None:- if isinstance(node, dict):- for key, item in node.items():- item_sensitive = sensitive or (isinstance(key, str) and (key in value_keys or _is_sensitive_key(key)))- _collect_secret_values(item, found, value_keys=value_keys, sensitive=item_sensitive)- elif isinstance(node, list):- for item in node:- _collect_secret_values(item, found, value_keys=value_keys, sensitive=sensitive)- elif isinstance(node, str):- if sensitive and len(node) >= _KNOWN_SECRET_MIN_LENGTH:- found.add(node)- # A stored URL's userinfo is a credential whatever its key is called,- # such as a platform ``proxy_url`` of ``http://user:pass@host``.- if "@" in node and "://" in node:- try:- parts = urlsplit(node.strip())- except ValueError:- return- if parts.password and len(parts.password) >= _KNOWN_SECRET_MIN_LENGTH:- found.add(parts.password)- # A username is a secret when it carries the credential alone- # (``https://<token>@host``) or is token-length; ``admin`` is not.- username = parts.username or ""- if username and (not parts.password or len(username) >= _KNOWN_SECRET_BOUNDARY_LENGTH):- if len(username) >= _KNOWN_SECRET_MIN_LENGTH:- found.add(username)---def _known_secret_files() -> list[tuple[Path, frozenset[str]]]:- """Files where Avibe stores credentials, with any extra keys naming a secret."""-- model_hub_state = paths.get_runtime_dir() / "model-hub" / "state"- files = [(paths.get_config_path(), frozenset())]- for pattern in ("instances/*/runtime-secrets.json", "auth/*.json", "oauth-staging/*.json"):- files.extend((path, frozenset()) for path in model_hub_state.glob(pattern))- # An API-key credential keeps its secret under ``value``.- files.extend((path, frozenset({"value"})) for path in model_hub_state.glob("credentials/*.json"))- return files---def _secret_spellings(value: str) -> set[str]:- # The value as it appears raw, URL-encoded, escaped inside JSON or a repr, and- # with either quote backslash-escaped as a repr picks its quote. Every spelling- # also gets the same delimiter normalization that the outbound scrubber applies,- # so an early breadcrumb cannot turn a credential into a new unmatched value.- backslashed = value.replace("\\", "\\\\")- base_spellings = {- value,- quote(value, safe=""),- json.dumps(value)[1:-1],- repr(value)[1:-1],- backslashed.replace("'", "\\'"),- backslashed.replace('"', '\\"'),- }- spellings: set[str] = set()- for spelling in base_spellings:- normalized = spelling- for _ in range(4):- decoded = _ENCODED_DELIMITER_RE.sub(_decoded_delimiter, normalized)- spellings.add(decoded)- if decoded == normalized:- break- normalized = decoded- return spellings---def _secret_alternative(spelling: str) -> str:- escaped = re.escape(spelling)- if len(spelling) < _KNOWN_SECRET_BOUNDARY_LENGTH:- return r"(?<![A-Za-z0-9])" + escaped + r"(?![A-Za-z0-9])"- return escaped---def _read_secret_values(- path: Path, value_keys: frozenset[str], signature: tuple[int, int, int, int]-) -> tuple[frozenset[str], bool]:- cached = _known_secret_files_state.get(str(path))- if cached == signature:- return frozenset(), False- if signature[2] > _KNOWN_SECRET_MAX_FILE_BYTES:- return frozenset(), True- try:- raw = path.read_bytes()- after = path.stat()- except OSError:- return frozenset(), True- after_signature = (after.st_ino, after.st_mtime_ns, after.st_size, after.st_mode & 0o7777)- if len(raw) != signature[2] or after_signature != signature:- return frozenset(), True- try:- data = json.loads(raw.decode("utf-8"))- except (UnicodeDecodeError, ValueError):- return frozenset(), True- found: set[str] = set()- _collect_secret_values(data, found, value_keys=value_keys)- return frozenset(found), False---def _compile_secret_pattern(values: frozenset[str]) -> tuple[re.Pattern[str] | None, bool]:- spellings = {spelling for value in values for spelling in _secret_spellings(value)}- source = "|".join(_secret_alternative(spelling) for spelling in sorted(spellings, key=len, reverse=True))- if len(source.encode("utf-8")) > _KNOWN_SECRET_MAX_PATTERN_BYTES:- return None, True- try:- return (re.compile(source) if source else None), False- except re.error:- return None, True---def _refresh_known_secret_state() -> bool:- """Refresh observed stores without ever evicting process-lifetime values."""-- global _known_secret_snapshot, _known_secret_collection_uncertain, _known_secret_collection_overflowed- with _KNOWN_SECRETS_LOCK:- if _known_secret_collection_overflowed:- _known_secret_collection_uncertain = True- _known_secret_snapshot = (False, _known_secret_snapshot[1], _known_secret_snapshot[2])- return False-- uncertain = False- present: set[str] = set()- try:- files = _known_secret_files()- except OSError:- files = []- uncertain = True- if len(files) > _KNOWN_SECRET_MAX_FILES:- _known_secret_collection_overflowed = True- _known_secret_collection_uncertain = True- _known_secret_snapshot = (False, _known_secret_snapshot[1], _known_secret_snapshot[2])- return False- for path, value_keys in files:- try:- stat = path.stat()- except FileNotFoundError:- continue- except OSError:- uncertain = True- continue- path_key = str(path)- present.add(path_key)- signature = (stat.st_ino, stat.st_mtime_ns, stat.st_size, stat.st_mode & 0o7777)- values, read_uncertain = _read_secret_values(path, value_keys, signature)- uncertain |= read_uncertain- if read_uncertain:- continue- new_values = values - _known_secret_values- new_value_bytes = sum(len(value.encode("utf-8")) for value in new_values)- current_value_bytes = sum(len(value.encode("utf-8")) for value in _known_secret_values)- if (- len(_known_secret_values) + len(new_values) > _KNOWN_SECRET_MAX_VALUES- or current_value_bytes + new_value_bytes > _KNOWN_SECRET_MAX_VALUE_BYTES- ):- _known_secret_collection_overflowed = True- _known_secret_collection_uncertain = True- return False- _known_secret_values.update(new_values)- _known_secret_files_state[path_key] = signature-- if len(_known_secret_files_state) > _KNOWN_SECRET_MAX_FILES:- _known_secret_collection_overflowed = True- _known_secret_collection_uncertain = True- _known_secret_snapshot = (False, _known_secret_snapshot[1], _known_secret_snapshot[2])- return False-- for stale in set(_known_secret_files_state) - present:- del _known_secret_files_state[stale]-- if not uncertain and _known_secret_snapshot[1] == frozenset(_known_secret_values):- _known_secret_collection_uncertain = False- _known_secret_snapshot = (True, _known_secret_snapshot[1], _known_secret_snapshot[2])- return True-- pattern, pattern_uncertain = _compile_secret_pattern(frozenset(_known_secret_values))- if pattern_uncertain:- _known_secret_collection_overflowed = True- uncertain = True- if not uncertain:- retained = frozenset(_known_secret_values)- _known_secret_snapshot = (True, retained, pattern)- else:- _known_secret_snapshot = (False, _known_secret_snapshot[1], _known_secret_snapshot[2])- _known_secret_collection_uncertain = uncertain- return not uncertain---def _published_secret_snapshot() -> tuple[bool, re.Pattern[str] | None]:- snapshot = _known_secret_snapshot- return snapshot[0], snapshot[2]---def _known_secret_pattern() -> re.Pattern[str] | None:- """Read the immutable published matcher without waiting for worker refresh."""-- return _published_secret_snapshot()[1]---def _known_secret_collection_is_complete() -> bool:- return _published_secret_snapshot()[0]---_ROOT_USER_MAPS = frozenset({"extra", "tags"})-_USER_MAP_BOUNDARIES = frozenset({"attributes", "cookies", "data", "env", "headers", "params", "vars"})-_TYPED_CONTEXT_NAMES = frozenset(- {- "app",- "browser",- "cloud_resource",- "culture",- "device",- "gpu",- "os",- "profile",- "replay",- "runtime",- "trace",- }-)---def _redaction_child_mode(owner: str, path: tuple[str, ...], key: str) -> str:- """Choose ownership from the containing Sentry shape, not from key names alone."""-- if owner == "user":- return "user"- if owner == "contexts":- return "typed_context" if key in _TYPED_CONTEXT_NAMES else "user"- if owner == "typed_context":- return "user" if key in _USER_MAP_BOUNDARIES else "protocol"- if owner == "user_object":- return "user" if key == "data" else "protocol"- if owner == "request":- return "user" if key in {"body", "cookies", "data", "env", "headers"} else "protocol"- if owner == "protocol":- if not path:- if key in _ROOT_USER_MAPS:- return "user"- if key == "contexts":- return "contexts"- if key == "request":- return "request"- if key == "user":- return "user_object"- if key in _USER_MAP_BOUNDARIES:- return "user"- return "protocol"- return "user"---def _redact_matches(- value: Any,- pattern: re.Pattern[str],- *,- mode: str = "protocol",- path: tuple[str, ...] = (),-) -> Any:- if isinstance(value, dict):- redacted: dict[Any, Any] = {}- for key, item in value.items():- if isinstance(key, str) and mode in {"user", "contexts"} and (- mode == "user" or key not in _TYPED_CONTEXT_NAMES- ):- out_key = pattern.sub(_REDACTED, key)- else:- out_key = key- child_mode = _redaction_child_mode(mode, path, key) if isinstance(key, str) else mode- redacted[out_key] = _redact_matches(item, pattern, mode=child_mode, path=path + (key,))- return redacted- if isinstance(value, list):- return [_redact_matches(item, pattern, mode=mode, path=path) for item in value]- if isinstance(value, tuple):- return tuple(_redact_matches(item, pattern, mode=mode, path=path) for item in value)- if isinstance(value, str):- return pattern.sub(_REDACTED, value)- return value---def _safe_float(raw: Optional[str], fallback: float) -> float:- if raw is None or raw == "":- return fallback- try:- value = float(raw)- except (TypeError, ValueError):- logger.warning("Invalid Sentry sample rate %r, falling back to %s", raw, fallback)- return fallback- if 0.0 <= value <= 1.0:- return value- logger.warning("Out-of-range Sentry sample rate %r, falling back to %s", raw, fallback)- return fallback---def _safe_positive_float(raw: Optional[str], fallback: float) -> float:- if raw is None or raw == "":- return fallback- try:- value = float(raw)- except (TypeError, ValueError):- logger.warning("Invalid Sentry positive float %r, falling back to %s", raw, fallback)- return fallback- if value >= 0.0:- return value- logger.warning("Out-of-range Sentry positive float %r, falling back to %s", raw, fallback)- return fallback---def _safe_nonnegative_int(raw: Optional[str], fallback: int) -> int:- if raw is None or raw == "":- return fallback- try:- value = int(raw)- except (TypeError, ValueError):- logger.warning("Invalid Sentry nonnegative integer %r, falling back to %s", raw, fallback)- return fallback- if value >= 0:- return value- logger.warning("Out-of-range Sentry nonnegative integer %r, falling back to %s", raw, fallback)- return fallback---def detect_sentry_environment() -> str:- explicit = os.environ.get("VIBE_SENTRY_ENVIRONMENT") or os.environ.get("SENTRY_ENVIRONMENT")- if explicit:- return explicit.strip()-- deployment = os.environ.get(DEPLOYMENT_ENV_VAR)- if deployment:- return deployment.strip()-- vibe_home = os.environ.get("AVIBE_HOME", "")- if "incus-regression" in vibe_home or "three-regression" in vibe_home:- return "regression"-- if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):- return "integration"-- return "local"---def resolve_sentry_options() -> Optional[dict[str, Any]]:- env_dsn = os.environ.get("VIBE_SENTRY_DSN")- if env_dsn is not None:- dsn = env_dsn.strip()- if not dsn:- return None- else:- fallback_dsn = os.environ.get("SENTRY_DSN")- if fallback_dsn is not None:- dsn = fallback_dsn.strip()- if not dsn:- return None- else:- dsn = DEFAULT_SENTRY_DSN- if not dsn:- return None-- return {- "dsn": dsn,- "environment": detect_sentry_environment(),- "traces_sample_rate": _safe_float(- os.environ.get("VIBE_SENTRY_TRACES_SAMPLE_RATE"),- DEFAULT_TRACES_SAMPLE_RATE,- ),- "profiles_sample_rate": _safe_float(- os.environ.get("VIBE_SENTRY_PROFILES_SAMPLE_RATE"),- DEFAULT_PROFILES_SAMPLE_RATE,- ),- }---def build_sentry_contexts(config: V2Config, component: str, environment: str) -> dict[str, dict[str, Any]]:- vibe_home = str(paths.get_vibe_remote_dir())- default_agent_name = None- try:- from core.vibe_agents import VibeAgentStore-- store = VibeAgentStore()- try:- default_agent = store.get_default_agent()- default_agent_name = default_agent.name if default_agent else None- finally:- store.close()- except Exception:- default_agent_name = None- return {- "runtime": {- "python_version": platform.python_version(),- "python_implementation": platform.python_implementation(),- "platform": sys.platform,- },- "host": {- "hostname": socket.gethostname(),- "system": platform.system(),- "release": platform.release(),- "version": platform.version(),- "machine": platform.machine(),- "processor": platform.processor() or None,- "docker": Path("/.dockerenv").exists(),- },- "deployment": {- "component": component,- "environment": environment,- "mode": config.mode,- "primary_platform": config.platforms.primary,- "enabled_platforms": config.platforms.enabled,- "default_agent_name": default_agent_name,- "cwd": config.runtime.default_cwd,- "vibe_home": vibe_home,- },- }---def _event_text(event: dict[str, Any]) -> str:- parts: list[str] = []- for key in ("message", "transaction"):- value = event.get(key)- if isinstance(value, str):- parts.append(value)-- logentry = event.get("logentry")- if isinstance(logentry, dict):- for key in ("formatted", "message"):- value = logentry.get(key)- if isinstance(value, str):- parts.append(value)-- for entry in event.get("entries") or []:- if not isinstance(entry, dict) or entry.get("type") != "message":- continue- data = entry.get("data")- if not isinstance(data, dict):- continue- for key in ("formatted", "message"):- value = data.get(key)- if isinstance(value, str):- parts.append(value)-- return "\n".join(parts)---def _exception_types(event: dict[str, Any]) -> set[str]:- values = ((event.get("exception") or {}).get("values") or []) if isinstance(event.get("exception"), dict) else []- return {value.get("type") for value in values if isinstance(value, dict) and isinstance(value.get("type"), str)}---def _exception_values(event: dict[str, Any]) -> list[str]:- values = ((event.get("exception") or {}).get("values") or []) if isinstance(event.get("exception"), dict) else []- return [value.get("value") for value in values if isinstance(value, dict) and isinstance(value.get("value"), str)]---def _noisy_event_fingerprint(event: dict[str, Any]) -> Optional[str]:- logger_name = str(event.get("logger") or "")- text = _event_text(event)- exception_types = _exception_types(event)-- if logger_name.startswith("slack_sdk.socket_mode") and (- "apps.connections.open" in text- or "Failed to retrieve WSS URL" in text- or "Failed to check the current session" in text- ):- return "slack-socket-mode-reconnect"-- if logger_name == "Lark" and (- "processor not found, type: im.message.reaction." in text- or "receive message loop exit, err: no close frame received or sent" in text- ):- return "lark-benign-ws-event"-- if logger_name == "core.watches" and ("No space left on device" in text or "Errno 28" in text):- return "watch-runtime-disk-full"-- if logger_name == "modules.im.wechat" and "Poll loop error" in text and exception_types & _NETWORK_EXCEPTION_TYPES:- return "wechat-poll-network"-- return None---def _noise_filters_enabled() -> bool:- raw = os.environ.get("VIBE_SENTRY_NOISE_FILTERS", "1").strip().lower()- return raw not in {"0", "false", "no", "off"}---def _noise_filter_ttl_seconds() -> float:- return _safe_positive_float(os.environ.get("VIBE_SENTRY_NOISE_TTL_SECONDS"), _NOISY_EVENT_TTL_SECONDS)---def _should_drop_noisy_event(event: dict[str, Any]) -> bool:- if not _noise_filters_enabled():- return False-- fingerprint = _noisy_event_fingerprint(event)- if not fingerprint:- return False-- ttl_seconds = _noise_filter_ttl_seconds()- if ttl_seconds <= 0:- return False-- now = time.monotonic()- with _SENTRY_EVENT_CACHE_LOCK:- last_seen = _NOISY_EVENT_LAST_SEEN.get(fingerprint)- _NOISY_EVENT_LAST_SEEN[fingerprint] = now-- if len(_NOISY_EVENT_LAST_SEEN) > _NOISY_EVENT_CACHE_LIMIT:- expired_before = now - ttl_seconds- for key, timestamp in list(_NOISY_EVENT_LAST_SEEN.items()):- if timestamp < expired_before:- _NOISY_EVENT_LAST_SEEN.pop(key, None)-- return last_seen is not None and now - last_seen < ttl_seconds---def _event_rate_window_seconds() -> float:- return _safe_positive_float(os.environ.get("VIBE_SENTRY_EVENT_RATE_WINDOW_SECONDS"), _EVENT_RATE_WINDOW_SECONDS)---def _event_rate_limit_per_window() -> int:- return _safe_nonnegative_int(- os.environ.get("VIBE_SENTRY_EVENT_RATE_LIMIT_PER_WINDOW"),- _EVENT_RATE_LIMIT_PER_WINDOW,- )---def _normalize_fingerprint_text(text: str) -> str:- text = re.sub(r"\b[0-9a-f]{16,}\b", "<hex>", text, flags=re.IGNORECASE)- text = re.sub(r"\b[0-9a-f]{8}-[0-9a-f-]{27,}\b", "<uuid>", text, flags=re.IGNORECASE)- text = re.sub(r"\bs_\d+\b", "s_<id>", text)- text = re.sub(r"\b\d{6,}\b", "<num>", text)- text = re.sub(r"file://\S+", "file://<path>", text)- return text[:240]---def _normalized_event_text(event: dict[str, Any]) -> str:- event_text = _event_text(event)- text = event_text.splitlines()[0] if event_text else ""- return _normalize_fingerprint_text(text)---def _normalized_exception_values(event: dict[str, Any]) -> str:- return "|".join(_normalize_fingerprint_text(value) for value in _exception_values(event))---def _event_rate_fingerprint(event: dict[str, Any]) -> str:- logger_name = str(event.get("logger") or "")- exception_types = ",".join(sorted(_exception_types(event)))- exception_values = _normalized_exception_values(event)- return f"{logger_name}|{exception_types}|{exception_values}|{_normalized_event_text(event)}"---def _prune_event_rate_state(now: float, window_seconds: float) -> None:- if len(_EVENT_RATE_STATE) <= _EVENT_RATE_CACHE_LIMIT:- return- expired_before = now - window_seconds- for key, (window_started_at, _count) in list(_EVENT_RATE_STATE.items()):- if window_started_at < expired_before:- _EVENT_RATE_STATE.pop(key, None)- overflow = len(_EVENT_RATE_STATE) - _EVENT_RATE_CACHE_LIMIT- if overflow <= 0:- return- oldest_keys = [- key- for key, _timestamp in sorted(- ((key, value[0]) for key, value in _EVENT_RATE_STATE.items()),- key=lambda item: item[1],- )[:overflow]- ]- for key in oldest_keys:- _EVENT_RATE_STATE.pop(key, None)---def _should_drop_repeated_event(event: dict[str, Any]) -> bool:- limit = _event_rate_limit_per_window()- if limit <= 0:- return False-- window_seconds = _event_rate_window_seconds()- if window_seconds <= 0:- return False-- now = time.monotonic()- fingerprint = _event_rate_fingerprint(event)- with _SENTRY_EVENT_CACHE_LOCK:- window_started_at, count = _EVENT_RATE_STATE.get(fingerprint, (now, 0))- if now - window_started_at >= window_seconds:- window_started_at = now- count = 0-- count += 1- _EVENT_RATE_STATE[fingerprint] = (window_started_at, count)- _prune_event_rate_state(now, window_seconds)- return count > limit---def before_send(event: dict[str, Any], hint: dict[str, Any]) -> Optional[dict[str, Any]]:- del hint- if not _known_secret_collection_is_complete():- return None- # Drop decisions stay in process and match on URL paths (Slack's- # ``apps.connections.open``) and tell errors on one host apart, so they see- # the text before URLs are reduced to their origin.- fingerprinted = scrub_data(event, minimize_urls=False)- if _should_drop_noisy_event(fingerprinted):- return None- if _should_drop_repeated_event(fingerprinted):- return None- return _scrub_outgoing(event)---def before_send_transaction(event: dict[str, Any], hint: dict[str, Any]) -> Optional[dict[str, Any]]:- """Performance transactions skip ``before_send``; their spans get the same scrub."""-- del hint- if not _known_secret_collection_is_complete():- return None- return _scrub_outgoing(event)---def _scrub_outgoing(event: dict[str, Any], *, breadcrumb: bool = False) -> Optional[dict[str, Any]]:- ready, known_secrets = _published_secret_snapshot()- if not ready:- return None- # Match stored credentials before normalization, then once again after it.- # The second pass covers values that arrived through before_breadcrumb or were- # transformed by URL/delimiter minimization into another spelling.- protected: Any = event- if known_secrets is not None:- protected = _redact_matches(protected, known_secrets)- minimized = _minimize_breadcrumb(protected) if breadcrumb else _minimize_event(protected)- scrubbed = scrub_data(minimized)- if known_secrets is not None:- scrubbed = _redact_matches(scrubbed, known_secrets)- return scrubbed---def before_breadcrumb(crumb: dict[str, Any], hint: dict[str, Any]) -> Optional[dict[str, Any]]:- del hint- return _scrub_outgoing(crumb, breadcrumb=True)---_STRUCTURED_ITEM_TYPES = frozenset(- {- "event",- "transaction",- "log",- "trace_metric",- "span",- "session",- "sessions",- "client_report",- "check_in",- "profile",- "profile_chunk",- }-)-_DROPPED_ITEM_TYPES = frozenset({"attachment"})-_HEADER_PROTOCOL_KEYS = frozenset(- {- "baggage",- "content_type",- "dsn",- "event_id",- "host",- "item_count",- "length",- "platform",- "sample_rates",- "sdk",- "section",- "sent_at",- "trace",- "type",- }-)---def _immutable_json_copy(value: Any) -> Any:- """Copy only JSON-shaped values so unsupported payloads fail closed."""-- if value is None or isinstance(value, (bool, int, float, str)):- return value- if isinstance(value, dict):- if any(not isinstance(key, str) for key in value):- raise _DropEnvelope- return {key: _immutable_json_copy(item) for key, item in value.items()}- if isinstance(value, (list, tuple)):- return [_immutable_json_copy(item) for item in value]- raise _DropEnvelope---def _header_contains_secret(value: Any, pattern: re.Pattern[str] | None) -> bool:- if pattern is None:- return False- if isinstance(value, dict):- return any(_header_contains_secret(item, pattern) for item in value.values())- if isinstance(value, list):- return any(_header_contains_secret(item, pattern) for item in value)- return isinstance(value, str) and pattern.search(value) is not None---def _scrub_header_value(value: Any, pattern: re.Pattern[str] | None) -> Any:- if isinstance(value, dict):- scrubbed: dict[str, Any] = {}- for key, item in value.items():- if not isinstance(key, str):- raise _DropEnvelope- if key in _HEADER_PROTOCOL_KEYS:- copied = _immutable_json_copy(item)- if _header_contains_secret(copied, pattern):- raise _DropEnvelope- scrubbed[key] = copied- elif key in _DROPPED_KEYS or _is_sensitive_key(key):- scrubbed[key] = _REDACTED- else:- scrubbed[key] = _scrub_header_value(item, pattern)- return scrubbed- if isinstance(value, list):- return [_scrub_header_value(item, pattern) for item in value]- if isinstance(value, str):- scrubbed = _redact_string(value)- return pattern.sub(_REDACTED, scrubbed) if pattern is not None else scrubbed- if value is None or isinstance(value, (bool, int, float)):- return value- raise _DropEnvelope---def _scrub_item_payload(payload: Any, item_type: str, pattern: re.Pattern[str] | None) -> Any:- copied = _immutable_json_copy(payload)- if pattern is not None:- copied = _redact_matches(copied, pattern)- if item_type in {"event", "transaction"}:- if not isinstance(copied, dict):- raise _DropEnvelope- copied = _minimize_event(copied)- elif item_type == "span" and isinstance(copied, dict) and isinstance(copied.get("items"), list):- copied = {**copied, "items": [_minimize_span(item) if isinstance(item, dict) else item for item in copied["items"]]}- copied = scrub_data(copied)- if pattern is not None:- copied = _redact_matches(copied, pattern)- return _immutable_json_copy(copied)---def _scrub_envelope(envelope: Any) -> Any:- """Return a new envelope, or refuse it before the SDK serializer sees it."""-- if not _refresh_known_secret_state():- raise _DropEnvelope- ready, pattern = _published_secret_snapshot()- if not ready:- raise _DropEnvelope- try:- from sentry_sdk.envelope import Envelope, Item, PayloadRef-- headers = _scrub_header_value(envelope.headers, pattern)- items = []- for item in envelope.items:- item_type = item.type- if item_type in _DROPPED_ITEM_TYPES:- continue- if item_type not in _STRUCTURED_ITEM_TYPES:- continue- payload = item.payload.json- if payload is None:- continue- scrubbed_payload = _scrub_item_payload(payload, item_type, pattern)- scrubbed_headers = _scrub_header_value(item.headers, pattern)- items.append(Item(payload=PayloadRef(json=scrubbed_payload), headers=scrubbed_headers))- if not items:- raise _DropEnvelope- return Envelope(headers=headers, items=items)- except _DropEnvelope:- raise- except Exception as exc:- del exc- raise _DropEnvelope from None---if _SentryHttpTransport is not None:-- class _RedactingHttpTransport(_SentryHttpTransport):- """Pinned SDK HTTP transport with final worker-side envelope scrubbing."""-- def __init__(self, options: dict[str, Any]) -> None:- import sentry_sdk-- if sentry_sdk.VERSION != "2.56.0" or not hasattr(_SentryHttpTransport, "_serialize_envelope"):- raise RuntimeError("unsupported sentry-sdk transport serialization seam")- super().__init__(options)-- def _serialize_envelope(self, envelope: Any) -> tuple[Optional[str], Any]:- scrubbed = _scrub_envelope(envelope)- return super()._serialize_envelope(scrubbed)--else: # pragma: no cover - only reachable in an incomplete installation- _RedactingHttpTransport = None---def init_sentry(config: V2Config, component: str, enable_fastapi: bool = False) -> bool:- options = resolve_sentry_options()- if not options:- return False- if _RedactingHttpTransport is None:- logger.warning("Sentry initialization skipped: supported transport seam unavailable")- return False- _refresh_known_secret_state()-- try:- import sentry_sdk- from sentry_sdk.integrations.logging import LoggingIntegration- except Exception as exc:- logger.warning("Sentry initialization skipped: %s", exc)- return False-- integrations: list[Any] = [- LoggingIntegration(- level=logging.WARNING,- event_level=logging.ERROR,- )- ]- if enable_fastapi:- try:- from sentry_sdk.integrations.fastapi import FastApiIntegration- from sentry_sdk.integrations.starlette import StarletteIntegration- except Exception as exc:- logger.warning("FastAPI Sentry integration unavailable: %s", exc)- else:- integrations.append(StarletteIntegration())- integrations.append(FastApiIntegration())-- from vibe import __version__-- try:- sentry_sdk.init(- dsn=options["dsn"],- environment=options["environment"],- release=f"avibe@{__version__}",- integrations=integrations,- before_send=before_send,- before_send_transaction=before_send_transaction,- before_breadcrumb=before_breadcrumb,- attach_stacktrace=True,- # Frame locals hold user data the scrubber cannot see into: an Agent's tool- # environment and file contents, raw config bytes. Tracebacks stay; values do not.- include_local_variables=False,- ignore_errors=[KeyboardInterrupt, SystemExit],- max_breadcrumbs=50,- sample_rate=1.0,- traces_sample_rate=options["traces_sample_rate"],- profiles_sample_rate=options["profiles_sample_rate"],- send_client_reports=False,- spotlight=False,- transport=_RedactingHttpTransport,- send_default_pii=True,- server_name=socket.gethostname(),- )- sentry_sdk.set_tag("component", component)- sentry_sdk.set_tag("mode", config.mode)- sentry_sdk.set_tag("primary_platform", config.platforms.primary)- sentry_sdk.set_tag("deployment_environment", options["environment"])- for name, context in build_sentry_contexts(config, component, options["environment"]).items():- sentry_sdk.set_context(name, context)- except Exception as exc:- logger.warning("Sentry initialization failed for %s: %s", component, exc)- return False- logger.info("Sentry initialized for %s (environment=%s)", component, options["environment"])- return True---def capture_exception(exc: Exception) -> None:- try:- import sentry_sdk- except Exception:- return- sentry_sdk.capture_exception(exc)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex f2b52288c..68197ba1c 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -88,7 +88,6 @@ from modules.agents.catalog import (from vibe.i18n import get_supported_languages, tfrom vibe.logging_config import application_log_pathsfrom vibe.runtime import get_ui_dist_path, get_working_dir-from vibe.sentry_integration import init_sentryfrom vibe import ui_asset_archivefrom storage.delivery_states import ADMITTED_DELIVERY_STATES@@ -17752,10 +17751,9 @@ def run_ui_server(host: str, port: int) -> None:except FileNotFoundError:config = Noneexcept Exception as exc:- logger.warning("Skipping UI Sentry init because config load failed: %s", exc)+ logger.warning("Skipping UI startup reconciliation because config load failed: %s", exc)config = Noneif config is not None:- init_sentry(config, component="ui", enable_fastapi=True)try:from vibe import remote_access