К основному содержанию
скилл CX Codex

anomaly-detection — скилл для Claude Code, Codex, Gemini CLI

Скилл anomaly-detection находит аномалии во временных рядах из CSV, мониторинга облака и других источников. Автоматически выбирает алгоритм и параметры сглаживания, или работает по вашим настройкам.

Apache-2.0 ★ 151 обновлён 2026-10-12

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add gemini-cli-extensions/sre
/plugin install sre-extension@sre
Открыть на GitHub

Что делает anomaly-detection

Скилл анализирует метрики как опытный SRE: загружает данные из указанного источника, выбирает нужные метрики (или уточняет, какие именно), применяет сглаживание при необходимости и запускает обнаружение аномалий. По умолчанию используется Isolation Forest, но вы можете выбрать KNN или Z-Score с собственными параметрами.

Внутри — набор скриптов Python для предобработки данных, несколько алгоритмов обнаружения и автоматическая проверка качества результатов. Если обнаружено слишком много аномалий (более 5% от всех точек), скилл переключается на более строгие настройки: сглаживание с окном 5 и Z-Score с порогом 3.0 или выше. Результаты выводятся как графики PNG с отмеченными аномалиями и список временных меток подозрительных значений.

Для работы нужна виртуальная окружение sre-extension-anomaly-detection с Python и необходимыми библиотеками; путь указывается в команде активации.

Какие задачи решает

  • найти выбросы в метриках мониторинга за несколько часов или дней
  • сравнить поведение разных метрик в один период времени
  • подготовить отчёт по аномалиям из CSV-логов приложения
  • настроить чувствительность детектора под шумные или чистые данные
  • визуализировать временные ряды с отмеченными странными точками

Примеры запросов агенту

  • Найди аномалии в метриках CPU и памяти из файла metrics.csv за последний день
  • Какие выбросы в response_time? Используй алгоритм zscore с порогом 2.5
  • Проанализируй данные из Cloud Monitoring, сглади moving_average с окном 7 и примени isolation_forest

Как установить anomaly-detection

1Через маркетплейс плагинов

/plugin marketplace add gemini-cli-extensions/sre
/plugin install sre-extension@sre

Команда ставит плагин sre-extension целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add gemini-cli-extensions/sre --skill anomaly-detection -a claude-code

3Вручную: положить файлы

~/.claude/skills/anomaly-detection/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/anomaly-detection/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об anomaly-detection

Как установить anomaly-detection в Claude Code?

Выполни команды по порядку: /plugin marketplace add gemini-cli-extensions/sre, затем /plugin install sre-extension@sre, потом npx skills add gemini-cli-extensions/sre --skill anomaly-detection -a claude-code. После этого откройся файл ~/.claude/skills/anomaly-detection/SKILL.md.

Что делает anomaly-detection?

Анализирует временные ряды (метрики, логи) и выявляет необычные значения с помощью алгоритмов машинного обучения. Автоматически сглаживает шум, выбирает метод обнаружения и проверяет качество результата. Выводит графики и список аномальных моментов времени.

Какие требования для работы скилла?

Нужна активированная виртуальная окружение sre-extension-anomaly-detection с Python и зависимостями для Isolation Forest, KNN или Z-Score. Данные могут быть из CSV-файлов или Cloud Monitoring.

Исходный текст

SKILL.md · Apache-2.0
---
name: anomaly-detection
description: 🐉 Detects anomalies in time-series data from various sources.
metadata:
  author: Google
  version: 0.1.0
  status: published
---

# Anomaly Detection Skill

You are an expert SRE Detective. Your job is to analyze time-series metrics and pinpoint anomalous behavior with minimal user friction.

**Inputs:**

*   `source_type`: String indicating the data source (e.g., "csv", "cloud_monitoring").
*   `source_details`: A dictionary or list containing the necessary information to access the data source.
    *   For `source_type: "csv"`: A list of file paths.
*   `context`: (Optional) String, either free-form text describing the issue or an issue tracker ID like a GitHub issue or Jira ticket.
*   `metrics`: (Optional) List of strings, specific metric names to analyze from the source.
*   `smoothing`: (Optional) String, method for smoothing (e.g., "moving_average", "exponential"). USER OVERRIDE.
*   `window`: (Optional) Integer, window for moving average. USER OVERRIDE.
*   `alpha`: (Optional) Float, alpha for exponential smoothing. USER OVERRIDE.
*   `algorithm`: (Optional) String, anomaly detection algorithm (e.g., "knn", "zscore", "isolation_forest"). USER OVERRIDE.
*   `n_neighbors`: (Optional) Integer for KNN detector. USER OVERRIDE.
*   `threshold`: (Optional) Float, for Z-Score. USER OVERRIDE.
*   `contamination`: (Optional: Float or "auto") For Isolation Forest. USER OVERRIDE.

**Workflow:**

1.  **Get Data:**
    *   Call `@skills/data_ingestion` with `source_type` and `source_details`.
    *   Save output to `.gemini/tmp/user/merged_data.json`.

2.  **Select Metrics:** (Same as before - infer from query/context, ask if needed)
    *   Let `available_metrics` be `metadata.available_metrics` from `merged_data.json`.
    *   If `metrics` input is provided, validate they are in `available_metrics`. Use these valid metrics.
    *   If `metrics` input is NOT provided, analyze the user's initial query and `context` for metric names. Try to match keywords with `available_metrics`.
    *   If no clear metrics can be inferred, or if there's ambiguity, use `ask_user` to prompt the user to select one or more metrics from `available_metrics`.
    *   Let `selected_metrics` be the list of metrics to analyze.

3.  **Process Each Selected Metric:** Iterate through each `metric_name` in `selected_metrics`:

    a.  **Filter Metric Data:** Create a temporary JSON file (`/tmp/single_metric_data.json`) containing only the "timestamp" and the current `metric_name` column from `merged_data.json`. You can write a short Python script to extract the relevant column based on the metric index in the `"columns"` list, ignoring rows where the metric value is `null`.

    b.  **Automated Preprocessing:**
        *   **Check for User Override:** If `smoothing` parameter is provided, use the specified method and parameters.
        *   **Automated Choice:** If no override, the agent should *autonomously* decide if smoothing is needed. Heuristic: calculate the point-to-point change percentage. If a significant number of points exceed a threshold (e.g., >20% change), apply a default `moving_average` with a small window (e.g., 3 or 5).
        *   Log the decision: "No smoothing applied" or "Applied Moving Average smoothing with window=3".
        *   If smoothing is applied, run `scripts/preprocess_data.py` as before, outputting to `/tmp/preprocessed_data.json`.
        *   Input to next step is `/tmp/preprocessed_data.json` or `/tmp/single_metric_data.json`.
        *   Let this be `data_for_detection.json`.

    c.  **Automated Algorithm Selection:**
        *   **Check for User Override:** If `algorithm` parameter is provided, use the specified algorithm.
        *   **Automated Choice:** Default to `isolation_forest` as it's generally robust. Contamination set to "auto".
        *   Let `chosen_algorithm` be the selected method.

    d.  **Detect Anomalies:** Execute the script for `chosen_algorithm`:
        *   All detection scripts take `data_for_detection.json` as input and output to `/tmp/detected_data.json`.
        *   **Example (Isolation Forest):**
            ```bash
            source $HOME/.venvs/sre-extension-anomaly-detection/bin/activate &&
            python3 .gemini/skills/anomaly_detection/scripts/detect_isolation_forest.py \
            /tmp/data_for_detection.json --contamination auto \
            > /tmp/detected_data.json
            ```
        *   Adjust command and parameters for knn or zscore if overridden.

    e.  **Evaluate Noise & Auto-Tune (Self-Reflection) - MANDATORY:**
        *   **Requirement:** You MUST evaluate the noise level of the detection result for EVERY metric, without exception.
        *   **Calculation:** Use `jq` to count the total points and the anomaly points in `/tmp/detected_data.json`.
        *   **Noise Threshold:** If the anomaly count exceeds **5%** of the total data points, the result is considered "noisy" (false positives).
        *   **Autonomous Fallback:** If noisy, you MUST discard the result, log "Detection too noisy ({count} anomalies), applying autonomous auto-tuning", and loop back to **Step 3.b**.
        *   **Auto-Tune Parameters:** Force **Smoothing** to `moving_average` (window=5) and **Algorithm** to `zscore` (threshold=3.0).
        *   **Quality Check:** After re-running, ensure the new result is within reasonable bounds (e.g., < 2% of points). If still noisy, increase the Z-Score threshold iteratively (e.g., to 4.0 or 5.0) until the signal is clear.

    f.  **Plot Anomalies:** Execute `scripts/plot_anomalies.py` and move the output to the destination directory.
        *   **Example:**
            ```bash
            PLOT_FILE=$(python3 .gemini/skills/anomaly_detection/scripts/plot_anomalies.py /tmp/detected_data.json) &&
            mkdir -p data && mv "$PLOT_FILE" data/${metric_name}_anomalies.png
            ```

    g.  **Extract Results Summary:** Use `jq` to extract the exact timestamps where an anomaly was detected to summarize the findings.
        *   **Example:**
            ```bash
            jq -r '.timeseries[] | select(.[2] == true) | .[0]' /tmp/detected_data.json | head -n 5
            ```

4.  **Correlate & Explain:** Synthesize the detected anomalies, matching up the time windows across multiple metrics. Explain which anomalies correlate and what the underlying cause might be.

5.  **Report Results:** Provide a clear summary to the user including the algorithm used, any preprocessing applied, the time windows of the anomalies, and the path to the generated plots.

© Google · Apache-2.0 · gemini-cli-extensions/sre

Похожие скиллы

Все скиллы по теме «ИИ и ML» →
Anomaly Detection aj-geddes Скилл Anomaly Detection для Claude Code ищет выбросы и аномалии в данных методами Z-score, IQR, Isolation Forest и автоэнкодерами. Задачи: мониторинг систем и поиск фрода. CX Codex +1 534установок kibana-anomaly-detection elastic Скилл kibana-anomaly-detection помогает расследовать сбои в Elastic ML, разбирать оценки моделей и проверять упавшие datafeed. Пригодится при поиске первопричин инцидентов. CX Codex +1 3 500установок huawei-cloud-cdn-traffic-anomaly-analysis huaweicloud Скилл huawei-cloud-cdn-traffic-anomaly-analysis смотрит режим оплаты CDN и метрики трафика домена через hcloud CLI, сравнивает текущее окно с базой за три месяца и показывает, где трафик вышел за норму. CX Codex +1 159установок elasticsearch-anomaly-detection elastic Скилл elasticsearch-anomaly-detection для Claude Code настраивает и запускает задачи Elastic ML anomaly detection в Elasticsearch через elastic CLI. Отслеживает всплески трафика и падения в потоках данных. CX Codex +1 1 500установок signals-scout-anomaly-detection PostHog Скилл signals-scout-anomaly-detection для Claude Code находит аномалии в сохранённых инсайтах PostHog: резкие всплески, падения и сломы трендов. Отслеживает ключевые дашборды с учётом сезонной базовой линии. CX Codex +1 318установок sre-engineer https://github.com/Jeffallan Скилл sre-engineer помогает рассчитать бюджет ошибок, задать SLO, настроить алерты по четырём золотым сигналам и убрать рутину. Пригодится при настройке надёжности сервисов. CX Codex +1 5 700установок

Из того же набора17

Весь набор →
postmortem-aggregator Скилл postmortem-aggregator для Claude Code разбирает Post Mortem в папке, рассчитывает показатели сбоев и обновляет POMO_AGGREGATED.md. Помогает находить повторяющиеся причины инцидентов. CX Codex +1 ★ 151звёзд репо gcp-mcp-setup Скилл gcp-mcp-setup для Claude Code, Codex и Gemini CLI автоматизирует подключение Google Managed MCP-серверов (OneMCP) к CLI-окружению. Включает нужные API, генерирует ключи и записывает конфигурацию в нужный файл настроек. CX Codex +1 ★ 151звёзд репо generic-mitigations Скилл generic-mitigations учит ИИ-агента купировать сбои в продакшене типовыми мерами SRE вместо долгих раскопок причин во время аварии. CX Codex +1 ★ 151звёзд репо monitoring-graphs Скилл monitoring-graphs для Claude Code, Codex и Gemini CLI генерирует аннотированные графики инцидентов на Python. Запускается, когда нужно визуализировать сбой, показать скачки ошибок или соотнести метрики с этапами инцидента. CX Codex +1 ★ 151звёзд репо investigation-entrypoint Скилл investigation-entrypoint расследования сбоев в Google Cloud Platform для Claude Code, Codex и Gemini CLI. Координирует диагностику GKE и Cloud Run при инцидентах. CX Codex +1 ★ 151звёзд репо postmortem-generator Скилл postmortem-generator для Claude Code собирает постмортем по инциденту: ведёт к таймлайну, action items и черновику Google Doc. Нужны данные расследования и root cause. CX Codex +1 ★ 151звёзд репо gcp-architecture-discovery Скилл gcp-architecture-discovery обходит GCP-проект от сбойного сервиса и собирает карту зависимостей: compute, сети, базы, бакеты. Результат кладёт в файлы, чтобы следующая сессия не начинала с нуля. CX Codex +1 ★ 151звёзд репо sre-extension Плагин sre-extension для Claude Code помогает расследовать сбои в Google Cloud, разбирать логи и создавать постмортемы. CX Codex ★ 151звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой