Metadata-Version: 2.5
Name: ops-onehit
Version: 1.0.2
Summary: End-to-end AI SRE / Ops Agent — one-shot diagnosis, repair, and reporting.
Project-URL: Homepage, https://github.com/a1580028209/ops-onehit
Project-URL: Repository, https://github.com/a1580028209/ops-onehit.git
Project-URL: Issues, https://github.com/a1580028209/ops-onehit/issues
Project-URL: Documentation, https://github.com/a1580028209/ops-onehit/blob/main/README.md
Author-email: a1580028209 <57759227+a1580028209@users.noreply.github.com>
License: MIT
License-File: LICENSE
Keywords: agent,ai,fastapi,langgraph,ollama,ops,pyside6,sre,windows
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Systems Administration
Requires-Python: <3.13,>=3.11
Requires-Dist: accelerate>=1.0.0
Requires-Dist: aiosmtplib<4.0,>=3.0
Requires-Dist: alembic<2.0,>=1.13
Requires-Dist: authlib<2.0,>=1.3
Requires-Dist: auto-gptq>=0.7.0; sys_platform != 'darwin' and python_version < '3.12'
Requires-Dist: av>=11.0.0
Requires-Dist: bcrypt<5.0,>=4.1
Requires-Dist: boto3<2.0,>=1.40
Requires-Dist: certifi>=2026.10.19
Requires-Dist: chromadb>=0.4.22
Requires-Dist: cryptography<51,>=42
Requires-Dist: docker>=7.1.0
Requires-Dist: fastapi>=0.141.1
Requires-Dist: faster-whisper>=1.0.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: jinja2<4.0,>=3.1
Requires-Dist: joblib>=1.3.0
Requires-Dist: jsonpath-ng>=1.6.0
Requires-Dist: kubernetes>=28.0.0
Requires-Dist: langchain-core>=0.3.0
Requires-Dist: langchain>=0.3.0
Requires-Dist: langgraph>=0.2.0
Requires-Dist: litellm>=1.50.0
Requires-Dist: lxml<7.0,>=5.0
Requires-Dist: ollama>=0.4.0
Requires-Dist: onnxruntime>=1.17.0
Requires-Dist: optimum>=1.20.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: pillow>=12.3.0
Requires-Dist: prophet>=1.1.0
Requires-Dist: psutil>=6.0.0
Requires-Dist: psycopg2-binary<3.0,>=2.9
Requires-Dist: pydantic-settings>=2.5.0
Requires-Dist: pydantic>=2.8.0
Requires-Dist: pyjwt<3.0,>=2.8
Requires-Dist: pyotp<3.0,>=2.9
Requires-Dist: pyside6>=6.11.2
Requires-Dist: python-dotenv>=1.0.1
Requires-Dist: python-multipart<1.0,>=0.0.18
Requires-Dist: python3-saml<2.0,>=1.16
Requires-Dist: pywin32>=306; sys_platform == 'win32'
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: qwen-vl-utils>=0.0.8
Requires-Dist: redis<6.0,>=5.0
Requires-Dist: rich>=13.8.0
Requires-Dist: scikit-learn>=1.3.0
Requires-Dist: sentence-transformers>=2.6.0
Requires-Dist: signxml<6.0,>=4.0
Requires-Dist: soundfile>=0.12.0
Requires-Dist: sqlalchemy<3.0,>=2.0
Requires-Dist: stripe<16.0,>=10.0
Requires-Dist: tenacity>=9.0.0
Requires-Dist: torch>=2.3.0
Requires-Dist: torchvision>=0.18.0
Requires-Dist: transformers>=4.45.0
Requires-Dist: typer>=0.12.0
Requires-Dist: uvicorn[standard]>=0.52.4
Requires-Dist: websockets>=12.0
Requires-Dist: wmi>=1.5.1; sys_platform == 'win32'
Provides-Extra: dev
Requires-Dist: black>=24.8.0; extra == 'dev'
Requires-Dist: fakeredis<3.0,>=2.21; extra == 'dev'
Requires-Dist: moto<6.0,>=5.0; extra == 'dev'
Requires-Dist: mypy>=1.11.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest-forked>=1.7.0; extra == 'dev'
Requires-Dist: pytest-rerunfailures>=15.0; extra == 'dev'
Requires-Dist: pytest-xdist>=3.5.0; extra == 'dev'
Requires-Dist: pytest>=8.3.0; extra == 'dev'
Requires-Dist: respx>=0.23.1; extra == 'dev'
Requires-Dist: ruff>=0.6.0; extra == 'dev'
Provides-Extra: pdf
Requires-Dist: weasyprint<70,>=60; extra == 'pdf'
Provides-Extra: tui
Requires-Dist: questionary<3.0,>=2.0; extra == 'tui'
Description-Content-Type: text/markdown

# ops-onehit

> **End-to-end AI SRE / Ops Agent — one-shot diagnosis, repair, and reporting.**
> 本地大模型驱动的 Windows 一键运维：监测 → 告警 → 自动修复 → 复盘报告。

[![Python](https://img.shields.io/badge/Python-3.11%20%7C%203.12-blue)](#)
[![Platform](https://img.shields.io/badge/Platform-Windows%2010%2F11-blue)](#)
[![PyPI](https://img.shields.io/badge/pypi-1.0.0-blue)](https://pypi.org/project/ops-onehit/)
[![Tests](https://img.shields.io/badge/Tests-2405%20passed%20%7C%2030%20skipped-green)](#tests)
[![Lint](https://img.shields.io/badge/Ruff-All%20checks%20passed-green)](#development)
[![Type](https://img.shields.io/badge/mypy-70%20files%2C%200%20errors-blue)](#development)
[![License](https://img.shields.io/badge/License-MIT-blue)](#license)
[![Status](https://img.shields.io/badge/Status-Beta-yellow)](#status)
[![Maturity](https://img.shields.io/badge/42%2F42%20商业对标-success)](#capability-matrix)
[![CI](https://github.com/a1580028209/ops-onehit/actions/workflows/ci.yml/badge.svg)](https://github.com/a1580028209/ops-onehit/actions/workflows/ci.yml)
[![Docker](https://img.shields.io/badge/Docker-ops--onehit%3A1.0.0-2496ED?logo=docker&logoColor=white)](#24-docker--kubernetes--deployment)
[![K8s](https://img.shields.io/badge/K8s-kustomize%20ready-326CE5?logo=kubernetes&logoColor=white)](#25-kubernetes--deployment)
[![Dependabot](https://img.shields.io/badge/Dependabot-enabled-blue?logo=dependabot)](https://github.com/a1580028209/ops-onehit/security/dependabot)

## 0. Quick Start

```powershell
# 安装（核心功能）
pip install ops-onehit

# 可选：SLA 月报 PDF 渲染（需系统装 cairo / pango；不装则自动降级为 HTML）
pip install "ops-onehit[pdf]"

# 可选：onboarding 向导的 questionary 增强 prompt（不装则走 rich.prompt）
pip install "ops-onehit[tui]"

# 首次初始化（5 步向导：admin 账号 / org / DB / LLM / 启动）
ops-onehit --init

# 启动 Web 控制台 → http://127.0.0.1:8080/
ops-onehit --web --port 8080
```

**更多用法**：[`docs/USAGE.md`](docs/USAGE.md) · [`docs/DEMO.md`](docs/DEMO.md) · [`docs/RELEASE.md`](docs/RELEASE.md) · [`docs/CAPABILITY_MATRIX.md`](docs/CAPABILITY_MATRIX.md)

---

## 1. 项目简介

ops-onehit 是一款**面向 Windows 桌面 / 服务器**的本地 AI 运维 Agent。**所有 LLM 推理都在本地完成**（通过 Ollama 或 LM Studio），零外发数据。Agent 接管日常的"系统慢了 / CPU 飙了 / 磁盘满了 / 服务挂了" 4 类高频问题：

1. **持续监测**：`--web` 模式后台采集器每 **5 秒**采一次 CPU / 内存 / 磁盘 / 网络，落 `monitoring` 表（`--widget` 悬浮窗自己每 2 秒刷一次，不入库）
2. **规则告警**：6 条内置告警规则（cpu_high / cpu_critical / memory_high / memory_critical / disk_full / disk_critical），持续 5 秒确认窗 + 状态机（inactive/pending/firing/resolved），每次状态变化落一行 `alerts`
3. **定位分析**：RCA 引擎出根因 + 置信度分级（L0~L4），需本地 LLM；异常检测基于历史样本
4. **修复执行**：K8s 修复（Pod 重启 / Deployment 扩缩）走真实 API，需 `user_confirmed=true`；**本机 SOP 剧本目前只能由 Agent 手动触发，尚无「告警自动触发剧本」链路** —— 三个断点见 [`docs/CAPABILITY_MATRIX.md`](docs/CAPABILITY_MATRIX.md) §1.5.1
5. **复盘报告**：所有执行结果持久化到 SQLite，Web 面板 / Tray 菜单 / Agent Ask 都能查

定位是**"80% 的高频问题 Agent 自己搞定，剩下 20% 留给人"**。

## 2. 核心能力

| 模块 | 文件 | 能力 |
|---|---|---|
| 数据采集 | `src/ops_onehit/data/collectors/system.py` | CPU / 内存 / 磁盘 / 网络 / 温度 6 个 snapshot + WMI graceful degrade |
| 告警引擎 | `src/ops_onehit/alerts/` | 6 条规则 + 状态机 (`inactive/pending/firing/resolved/silenced`) + 持久化 |
| 修复执行 | `src/ops_onehit/repairs/` | 5 档权限分级 (L0~L4) + L2+ 必用户确认 + 动作白名单（本机 4 个真调 subprocess + K8s 2 个） |
| SOP 剧本 | `src/ops_onehit/sop/` | 6 个内置 SOP + frozen 模板 + 失败策略 (abort/continue/rollback) + 验证（**需 Agent 手动触发，见 §7**） |
| Agent | `src/ops_onehit/agent/` | ReAct 框架 + 7 个工具 (查告警 / 跑 SOP / 查知识库 / 写反馈) |
| Web 面板 | `src/ops_onehit/api/` | FastAPI + 6 个 API + 单文件 HTML 面板 + Bearer 鉴权 (T5.2) |
| GUI 组件 | `src/ops_onehit/ui/` | 透明悬浮监控 widget (PySide6) + 系统托盘 (Show Widget / Web Panel / Quit) |
| 多模态 | `src/ops_onehit/multimodal/` | 图像 OCR / 视频抽帧 / 文件附件解析（Agent 可上传图片问"屏幕上这个错是啥"） |
| 知识库 | `src/ops_onehit/rag/` | sqlite-vec + nomic-embed-text 本地检索 |
| 学习反馈 | `src/ops_onehit/learning/` | 用户对 Agent 答的 👍/👎 → 后续 prompt 注入偏好 |

## 3. 快速开始

### 3.0 从 PyPI 装（alpha 1.0+，推荐）

```powershell
# 一行装
pip install ops-onehit

# 跑自检（确认 DB / Ollama / RAG 都 OK）
ops-onehit --test

# 跑起来（三选一）
ops-onehit --widget       # 透明悬浮 widget
ops-onehit --web          # Web 面板（http://127.0.0.1:8080）
ops-onehit --ask "CPU 飙到 95% 怎么办"  # ReAct Agent 模式

# 初始化 RAG 知识库（T6.5+，6 条默认 SRE 知识入 ChromaDB）
ops-onehit --init-knowledge
```

> 首次跑 `--init-knowledge` 会下载 `paraphrase-multilingual-MiniLM-L12-v2` 多语言 embedding 模型（278MB，HF mirror 自动 fallback）。CPU 上推理 < 50ms / 文本。

### 3.1 前置依赖

- **操作系统**: Windows 10 / 11 / Server 2019+（系统托盘 / WMI / 服务管理是 Windows-only）
- **Python**: 3.11 或 3.12（项目锁了 `>=3.11,<3.13`）
- **uv**: 0.4+（[安装](https://github.com/astral-sh/uv)）
- **LLM 推理后端（二选一）**:
  - **Ollama**（推荐）— 装 [ollama.com](https://ollama.com)，拉模型 `ollama pull qwen2.5:7b`
  - **LM Studio** — 启 Developer Server（端口 1234），任选模型
- **可选**: WMI 已默认开启；如需 CPU 温度则需主板/驱动支持 `Win32_Fan` / `Win32_TemperatureProbe`

### 3.2 装与启动

```powershell
# 1. 克隆
git clone https://github.com/a1580028209/ops-onehit.git
cd ops-onehit

# 2. 装依赖（uv 会自动建 .venv）
uv sync

# 3. 起 LLM 后端（任选）
ollama serve                 # 用 Ollama
# 或 LM Studio 里点 "Start Server"

# 4. 跑起来（三选一）
uv run python -m ops_onehit --widget       # 透明悬浮 widget（默认挂系统托盘）
uv run python -m ops_onehit --web          # Web 面板(http://127.0.0.1:8080)
uv run python -m ops_onehit --interactive   # 交互式 REPL
```

> 第一次跑会做几件事：在 `data/ops_onehit.db` 建 SQLite，初始化 6 条告警规则，6 个 SOP 模板注册。冷启动 ≈ 1.5 秒。

### 3.3 跑测试

```powershell
uv run pytest                    # 全量（≈ 3 分 45 秒，16 worker 并发）
uv run pytest tests/test_sop.py  # 单独 SOP 模块
uv run pytest -m "not integration"  # 跳过集成测试
```

预期: **2400+ passed, ~30 skipped**（含 deselect 的 WMI 测试）。完整 self-check 走 `logs/T6.5_T6.9_worker_self_check_pytest.log`。

### 3.4 真实向量数据库（T6.5+）

ops-onehit 用 **ChromaDB** 做 RAG 知识库持久化（T6.5 起替换 T1~T6.4 的 SQLite BLOB 内存遍历方案）：

- **默认路径**：
  - Linux/macOS: `~/.cache/ops-onehit/chroma/`
  - Windows: `%LOCALAPPDATA%\ops-onehit\chroma\`
  - 可通过环境变量 `OPS_ONEHIT_CHROMA_PATH` 覆盖
- **Collection 名**: `ops_onehit_knowledge`
- **Embedding 模型**: `paraphrase-multilingual-MiniLM-L12-v2`（多语言 50+ 语种，dim=384，磁盘 ~278MB，CPU 可跑）
- **首次下载**: 自动用 HF mirror (`https://hf-mirror.com`) 加速国内访问
- **失败回退**: 模型下载/加载失败 → 自动降级 mock embedding，检索链路不挂
- **跨进程共享**: 加完 knowledge 后新进程能直接看到

**常用命令**：

```powershell
# 写入 6 条默认 SRE 知识（CPU 高 / 内存 leak / 磁盘满 / 杀进程 / 网络丢包 / 蓝屏）
ops-onehit --init-knowledge

# 写入到自定义路径
ops-onehit --init-knowledge --chroma-path D:\my-rag\chroma
```

在 Python 里直接用：

```python
from ops_onehit.rag import ChromaRAGStore

async def main():
    store = ChromaRAGStore()  # 走默认路径
    await store.add("d1", "My Doc", "CPU 占用过高", "manual", "cpu_high")
    results = await store.search("CPU 飙了", top_k=3)
    for r in results:
        print(f"{r.doc_id}: {r.similarity:.3f} — {r.title}")
```

## 4. 架构总览

```
┌───────────────────────  4 个用户入口  ───────────────────────┐
│  透明悬浮 widget  │  系统托盘  │  Web 面板  │  CLI  │
└────────┬────────────┴────┬──────┴─────┬──────┴───┬───┘
         │                 │            │          │
         ▼                 ▼            ▼          ▼
┌───────────────  ops_onehit 核心  ───────────────────────────┐
│                                                              │
│  ┌────────┐  ┌────────┐  ┌────────┐  ┌────────┐  ┌────────┐  │
│  │ Agent  │  │   SOP  │  │ Alerts │  │Repair  │  │   RAG  │  │
│  │ ReAct  │→ │Runner  │← │Manager │  │Executor│  │Store   │  │
│  └───┬────┘  └────┬───┘  └────┬───┘  └────┬───┘  └────────┘  │
│      └────────────┴───────────┴───────────┘                  │
│                          ↓                                   │
│                   SQLite (data/ops_onehit.db)                │
│      SystemCollector (CPU/Mem/Disk/Net/Thermal, 2s 间隔)     │
└──────────────────────────────────────────────────────────────┘
```

详细分层见 `src/ops_onehit/` 目录树（`agent/` / `alerts/` / `api/` / `core/` / `data/` / `deployment/` / `learning/` / `llm/` / `multimodal/` / `rag/` / `repairs/` / `sop/` / `tools/` / `ui/`）。

## 5. CLI 用法

`uv run python -m ops_onehit --help` 看完整选项。常用：

```powershell
# 透明悬浮监控 widget（默认 2 秒刷新）
uv run python -m ops_onehit --widget

# Web 面板（http://127.0.0.1:8080，Bearer Token 鉴权可选）
uv run python -m ops_onehit --web --port 8080

# 托盘 + widget 一起（托盘默认开启，用 --no-tray 关闭）
uv run python -m ops_onehit --widget

# 直接问 SRE Agent（ReAct 多步推理）
uv run python -m ops_onehit --ask "CPU 飙到 95% 是哪个进程？"

# 走 RAG 知识库检索（先 ops-onehit --init-knowledge 写入知识，Agent 会自动检索）
uv run python -m ops_onehit --chat "上次 DNS 故障是怎么修的？"

# 多模态：截图 + 一起问
uv run python -m ops_onehit --ask "这个蓝屏是啥原因" --image C:\errors\bsod.png
```

## 6. Web 面板

`--web` 启 FastAPI 服务（`src/ops_onehit/api/server.py`），默认 `http://127.0.0.1:8080/`。提供 6 个 API：

| Method | Path | 说明 |
|---|---|---|
| GET | `/api/health` | 健康检查 |
| GET | `/api/status` | 实时 CPU / 内存 / 磁盘 / 告警数 |
| GET | `/api/alerts` | 告警历史（可按 `state` 过滤）|
| GET | `/api/repairs` | 修复执行历史 |
| POST | `/api/ask` | 问 SRE Agent（需要 LLM 在跑） |
| POST | `/api/knowledge/search` | RAG 知识库检索 |
| GET | `/` | 单文件管理面板 (HTML) |
| GET | `/docs` | FastAPI 自动生成的 OpenAPI 文档 |

T5.2 起默认开 **Bearer Token 鉴权**：环境变量 `OPS_ONEHIT_API_TOKEN` 注入 token；客户端在 `Authorization: Bearer <token>` 头带 token。本机 (`127.0.0.1`) 可不设。

## 7. SOP 修复剧本

SOP（Standard Operating Procedure）= **预审过的"修复剧本"**。6 个内置 SOP 跟 6 条告警规则一一对应。详细数据结构 / 怎么写新 SOP / 怎么触发 见 [`docs/SOP.md`](docs/SOP.md)（216 行）。

| SOP 名 | 对应告警 | 预估时长 | 需人工 review |
|---|---|---|---|
| `sop_cpu_high` | cpu_high | 30s | ❌ |
| `sop_cpu_critical` | cpu_critical | 45s | ✅ |
| `sop_memory_high` | memory_high | 60s | ❌ |
| `sop_memory_critical` | memory_critical | 90s | ✅ |
| `sop_disk_full` | disk_full | 120s | ❌ |
| `sop_disk_critical` | disk_critical | 180s | ✅ |

新增 SOP 必须改源码（白名单 + frozen），不允许运行时注册。详见 `docs/SOP.md` 第 5 节。

> ⚠️ **触发方式（重要）**：SOP 编排器本身是真的（`sop/runner.py` 逐条调 `RepairExecutor`，失败策略 abort/continue/rollback 都有实现），但**告警进入 FIRING 不会自动启动 SOP**。当前唯一自动可达的调用方是 Agent 的 `run_sop` 工具 —— 也就是说「自动修复」目前需要你在对话框里说一句话，或由 Agent 自己判断后调工具。
> 另注意 `POST /api/repairs/{id}/confirm` **只改状态不执行**（把 `pending` 改成 `approved`/`denied` 并写 audit log，全程不调执行器）。真正会改主机状态的 HTTP 入口只有 K8s 那两个（需 `user_confirmed=true`）。
> 完整的三断点分析见 [`docs/CAPABILITY_MATRIX.md`](docs/CAPABILITY_MATRIX.md) §1.5.1。

## 8. 开发与测试

### 8.1 工具链

- **包管理**: `uv`（PEP 735 原生 dev group，`uv sync` 装全部）
- **格式化**: `black`（line-length 100，target py311+py312）
- **Lint**: `ruff`（E/W/F/I/B/C4/UP/N/RUF + per-file-ignores 兼容 Qt override）
- **类型检查**: `mypy`（`strict=false` 但 `warn_unused_ignores=true`）
- **测试**: `pytest 9.x` + `pytest-asyncio`（mode=auto）+ `respx`（HTTP mock）

### 8.2 self-check 4 件套

跑完以下 4 条全绿才算 T5.5 收尾完成：

```powershell
uv run pytest                              # 全量, ~3分45秒
uv run ruff check src tests                # All checks passed
uv run black --check src tests             # 57 files left unchanged
uv run mypy src/ops_onehit                 # no issues found in 44 source files
```

### 8.3 已知坑

- **WMI hard AV**: `test_thermal_with_wmi_when_available` 在部分 Windows 配置会触发不可捕获的 access violation（COM + `Win32_Fan`/`Win32_Processor`）。已在 `tests/conftest.py` 的 `pytest_collection_modifyitems` hook 里 deselect，**不是删除**，需要手动跑时 `uv run pytest -k test_thermal_with_wmi`
- **psutil GC bug**: `psutil._pswindows.py:265 cpu_times` 在 collector 关闭时偶发 access violation。pytest 重启 worker 后自动恢复，不影响测试结果
- **fastapi + asyncio.run()**: `/api/ask` 用 `asyncio.to_thread` 把 ReAct Agent 推到 threadpool，避开"在 event loop 里跑 asyncio.run()"的禁忌

## 9. 部署

生产部署走 **NSSM + nginx 反代**（T5.7+，见 `src/ops_onehit/deployment/models.py`）：

1. NSSM 把 `ops-onehit-web` 注册为 Windows 服务
2. nginx 反代 `127.0.0.1:8080` 到 `https://ops-onehit.your-domain.com/`
3. 系统托盘脚本 `scripts/install_tray.ps1` 一键开托盘

⚠️ 部署相关测试 (`tests/test_deployment.py`) 需要 NSSM 服务 + nginx + ops-onehit.conf 都已部署才会通过。**首次跑 4 个 FAILED 是预期**（infra-dependent，非代码 bug）。

## 10. 截图

| 组件 | 截图 |
|---|---|
| 透明悬浮监控 widget | `docs/screenshots/widget.png`（占位） |
| Web 管理面板 | `docs/screenshots/web_panel.png`（占位） |
| 系统托盘菜单 | `docs/screenshots/tray_menu.png`（占位） |

> 截图占位文件用 `docs/screenshots/.gitkeep` 保持目录存在；正式截图在 release 阶段补全。

## 11. 路线图

| 阶段 | 状态 | 内容 |
|---|---|---|
| T1 | ✅ | 数据采集 / 告警规则 / 持久化 / LLM 客户端 / RAG 雏形 |
| T2 | ✅ | 修复动作 / 权限分级 / SOP 模板 / SOP Runner / 反馈学习 |
| T3 | ✅ | 透明 widget / 托盘 / 多模态 / 反馈闭环 |
| T4 | ✅ | FastAPI / Web 面板 / 鉴权 / 部署脚本 |
| T5 | ✅ | 文档收尾 / 截图占位 / 部署测试（NSSM / nginx） |
| T6+ | 🔜 | 真实截图 / 多用户 / Linux 子集支持(✅ CI + Docker + K8s 见 §23-25) |

## 12. 安全模型

修复层 **5 档权限分级**（`src/ops_onehit/repairs/permissions.py`）：

- **L0 只读** — 查询监控（默认放行）
- **L1 软修改** — 清临时文件 / 清 DNS 缓存（默认放行）
- **L2 硬修改** — 杀进程 / 重启服务 / 清日志（**必须用户确认**）
- **L3 危险** — 注册表 / 防火墙（**当前未注册**动作,留待扩展）
- **L4 不可逆** — 格式化 / 系统重启（**永不在白名单**）

L2+ 走双保险：
1. Agent tool 描述里强制 prompt "this action requires user confirmation"
2. `RepairExecutor.execute()` 运行时再校验 `user_confirmed=True` 或 callback 返回 True

## 13. 常见问题

**Q: 必须装 Ollama / LM Studio 吗？**
A: 数据采集 / SOP / 告警这些不依赖 LLM，可以跑 `--widget` 不配 LLM。但 `--ask` 必须配。

**Q: 怎么改默认数据库位置？**
A: 环境变量 `OPS_ONEHIT_DATABASE_PATH=...`，或直接改 `src/ops_onehit/core/config.py`。

**Q: LLM 调不通怎么办？**
A: 先确认 LLM 后端在 `127.0.0.1:11434`（Ollama）或 `127.0.0.1:1234`（LM Studio）在跑；`uv run python -m ops_onehit --ask "ping"` 试一下。

**Q: 怎么加新告警规则？**
A: 改 `src/ops_onehit/alerts/rules.py` 的 `DEFAULT_RULES`，配套加 `src/ops_onehit/sop/templates.py` 的 SOP（如果需要自动修）。所有改动走源码，不允许运行时漂移。

**Q: 测试有 4 个 FAIL 在 test_deployment.py 怎么办？**
A: 正常。test_deployment.py 测的是 NSSM 服务 + nginx 反代，需要先 `install_nssm.ps1` + `install_nginx.ps1` 才会通过。**首次 clone 后跑测试预期这 4 个 FAILED**。

## 14. 许可与致谢

- **License**: MIT
- **作者**: a1580028209
- **关键技术**: [PySide6](https://wiki.qt.io/Qt_for_Python) / [FastAPI](https://fastapi.tiangolo.com/) / [LangGraph](https://langchain-ai.github.io/langgraph/) / [psutil](https://github.com/giampaolo/psutil) / [Ollama](https://ollama.com/) / [LiteLLM](https://github.com/BerriAI/litellm)

## 15. Changelog

完整发布历史见 [`CHANGELOG.md`](CHANGELOG.md)。当前版本 **1.0.2** 主要特性:

- **1.0.2** — **告警链路接电**:`CollectorRunner` 在 `--web` 启动时真正运行,看板告警不再是 seed 出来的 demo 数据;修 6 个真 bug(pytest 全量卡死 / 前端首屏永久卡死 / 渲染崩溃 / WebSocket 自杀 / demo 混入主表 / HA 日志刷屏);CI 加 PyPI trusted publishing
- **1.0.0** — alpha 2.0,42/42 能力矩阵满分:多源采集器 / 知识图谱 / FinOps / CMDB / HA 部署 / Stripe 计费 / 告警分析与修复链路

以下为更早的 alpha 阶段记录。

**0.1.0** (alpha 1.0) 主要特性:

- **T6.5**: 真实向量库 (ChromaDB + sentence-transformers) — 替换 T1~T6.4 的 SQLite BLOB 内存遍历
- **T6.9**: PyPI 发布 (`pip install ops-onehit`) — wheel + sdist + TestPyPI 验证
- **T6.5 命令**: `ops-onehit --init-knowledge` 一键 seed 6 条默认 SRE 知识
- **T6.5 文档**: [`docs/CHROMADB_MIGRATION.md`](docs/CHROMADB_MIGRATION.md) 覆盖安装 / 配置 / 迁移 / 回退
- **T6.5 迁移工具**: `scripts/migrate_rag_to_chromadb.py` 一次迁移旧 SQLite RAG
- **跨平台 release 脚本**: `scripts/release.py` (Python 跨平台) + `scripts/release.sh` / `.ps1` (原生)

**0.5.0** (alpha 1.5) — **T7.1 多源数据集成**:
- **Prometheus collector** — `httpx` async scrape `/api/v1/query`,多 URL + 白名单 + 失败 graceful
- **HTTP endpoint collector** — `jsonpath-ng` 解析任意 JSON endpoint,覆盖 Zabbix / 自研监控
- **Docker collector** — `docker>=7.1.0` SDK stats,8 个 metric / 容器,无 socket 自动 skip
- **`metric_samples` 表** — 持久化所有外部数据源 sample + 7 天 retention(可配)
- **3 个新 API 端点** — `GET /api/metrics/sources` / `GET /api/metrics/{source:path}/query` / `POST /api/collectors/reload`
- **新文档**: [`docs/MULTI_SOURCE_COLLECTORS.md`](docs/MULTI_SOURCE_COLLECTORS.md) (~310 行,含 13 节:配置 / 工作原理 / 故障排查)
- **新增 47 个测试**(Prom 14 + HTTP 11 + Docker 12 + API 10),全量 **771 passed / 16 skipped**

**0.6.0** (alpha 1.6) — **T7.2 Knowledge Graph 服务依赖关系**:
- **`kg_services` + `kg_dependencies` 表** — SQLite 双表持久化节点 + 边,FK CASCADE 自动清悬挂
- **`KnowledgeGraph` 类** — CRUD / 拓扑 / 子图 / 邻居查询 (model / store 分离)
- **`DependencyInferer`** — Pearson 时序相关性 + RCA 文本引用 双源推断候选 soft 边
- **RCA 集成** — `_format_prompt` 注入 `{kg_topology}` section;focus 邻域展开;降级 graceful
- **8 个 CLI 子命令** — `kg add-service` / `remove-service` / `list-services` / `add-dependency` / `remove-dependency` / `list-dependencies` / `show-topology` / `suggest-dependencies`
- **7 个 API 端点** — `GET/POST/DELETE /api/kg/services` + `GET/POST/DELETE /api/kg/dependencies` + `GET /api/kg/topology` + `POST /api/kg/infer-dependencies`
- **`TopologyTab` UI** — PySide6 30s 自动刷新 + Refresh 按钮,monospace dark theme
- **新文档**: [`docs/KNOWLEDGE_GRAPH.md`](docs/KNOWLEDGE_GRAPH.md) (~480 行,13 节:数据模型 / CRUD / 自动推断 / CLI / API / UI / RCA 集成 / schema / FAQ / 路线图)
- **新增 110 个测试**(KG 42 + Infer 28 + RCA 集成 11 + CLI 29 + Widget 9 + API 12),全量 **≥ 779 passed / 16 skipped**

## 16. T7.2 Knowledge Graph 速查

KG 让 ops-onehit 理解服务依赖关系,商业对标 36/42 → 39/42 (Datadog
Service Map / Honeycomb ServiceMap 轻量替代)。

**核心概念**：

- **节点 (ServiceNode)** — `name` 主键 + `kind` (service / database / cache / queue / proxy / external / other) + `host` + `description` + `metadata_json`
- **边 (DependencyEdge)** — `src -> dst` 有向,`relation="hard"`(手工 / 静态)或 `"soft"`(自动推断),`confidence` 仅 soft 边有意义
- **拓扑 (Topology)** — 整图 + `to_prompt_context(focus=)` / `to_ascii()` / `to_dot()` 三个渲染

**30 秒上手**：

```bash
# 注册 3 service
ops-onehit kg add-service --name nginx --kind proxy --host web-01
ops-onehit kg add-service --name postgres --kind database --host db-01
ops-onehit kg add-service --name redis --kind cache --host cache-01

# 加 2 依赖
ops-onehit kg add-dependency --src nginx --dst postgres
ops-onehit kg add-dependency --src nginx --dst redis

# 看图
ops-onehit kg show-topology                 # ASCII
ops-onehit kg show-topology --format dot    # Graphviz

# 自动推断候选
ops-onehit kg suggest-dependencies
ops-onehit kg suggest-dependencies --confirm  # 落库为 soft
```

**RCA 集成**：`_format_prompt` 自动把邻域子图注入 `{kg_topology}` section,
LLM 在 RCA 推理时能直接看到 "nginx 依赖 postgres / redis",提升因果判断。

**Python 用法**：

```python
from ops_onehit.data.db import get_database
from ops_onehit.kg import KnowledgeGraph
from ops_onehit.kg.infer import DependencyInferer

db = get_database()
kg = KnowledgeGraph(db)
kg.add_service("nginx", kind="proxy", host="web-01")
kg.add_service("postgres", kind="database", host="db-01")
kg.add_dependency("nginx", "postgres")

# 自动推断
inferer = DependencyInferer(kg)
suggestions = inferer.suggest(window_minutes=120, min_confidence=0.4)
for s in suggestions:
    print(s.src, "->", s.dst, f"conf={s.confidence:.2f}")
```

**详见** [`docs/KNOWLEDGE_GRAPH.md`](docs/KNOWLEDGE_GRAPH.md)。

---

## 17. T7.1 Multi-Source Collectors 速查

T7.1 把数据采集从"单 psutil 系统"扩展到多源(Prometheus / HTTP endpoint / Docker),
让 ops-onehit 能接入生产环境的真实指标。

**核心概念**：

- **Collector 抽象** — `BaseCollector.collect() -> list[MetricSample]`,所有源统一
- **CollectorRunner** — 异步调度,默认 5 秒一次,失败 graceful skip
- **metric_samples 表** — `(ts, source, name, labels_json, value)` 五元组,跨源统一

**支持的源**：

- `PrometheusCollector` — 抓 `:9090/metrics`,正则提取 metric 名 + 值
- `HttpEndpointCollector` — 拉任意 JSON,`--jsonpath` 提取数字字段
- `DockerCollector` — `docker stats` 容器 CPU/内存

**30 秒上手**：

```bash
# 添加 Prometheus 源
ops-onehit --web  # 启 Web 面板
# Web 端点 POST /api/metrics/{source}/query 拉数据

# 也可直接调
curl -H "Authorization: Bearer $T" http://127.0.0.1:8080/api/metrics/sources
```

**详见** [`docs/MULTI_SOURCE_COLLECTORS.md`](docs/MULTI_SOURCE_COLLECTORS.md)。

---

## 18. T7.4 RBAC + Audit Log 速查

T7.4 把权限模型从"单 static token"升级到"4 角色 + 用户管理 + 审计追溯",
商业对标 39/42 → **42/42 (100%) = alpha 2.0 满分** 🎉

**4 角色**：`admin` / `sre` / `developer` / `viewer`,严格递减
(`admin ⊇ sre ⊇ developer ⊇ viewer`)。

**启用 RBAC 模式**：

```bash
export OPS_ONEHIT_AUTH_MODE=rbac  # 默认 static 走旧路径
ops-onehit --web --auth-token "any-string"

# 第一次启动 stderr 会打印 seed 的 admin token(只此一次):
# [ops-onehit] Seeded default admin user. Token: GGR5-XXXXX
```

**CLI 用户管理(7 子命令)**：

```bash
ops-onehit --user add alice --role sre        # 创建(自动生成 token)
ops-onehit --user list                         # 列用户
ops-onehit --user rotate-token alice           # 重置 token
ops-onehit --user deactivate alice             # 禁用
ops-onehit --user activate alice               # 启用
ops-onehit --user remove alice                 # 删
ops-onehit --user audit --username alice       # 查 audit log
```

**API 端点(6 新)**：

| 方法 | 路径 | 权限 |
|---|---|---|
| GET | `/api/users` | `read:users` |
| POST | `/api/users` | `admin:manage_users` |
| DELETE | `/api/users/{x}` | `admin:manage_users` |
| POST | `/api/users/{x}/rotate-token` | `admin:manage_users` |
| GET | `/api/audit` | `read:audit` |
| GET | `/api/audit/users` | `read:audit` |
| GET | `/api/audit/summary` | `read:audit` |

**审计自动接入**：

- `user_add` / `user_remove` / `user_rotate_token` / `user_activate` / `user_deactivate` 自动 log
- `auth_failed` 任何鉴权失败自动 log
- 装饰器 `@audit_action("name")` 预留接口给 T7.5 接入 SOP / repair / alert

**安全要点**：

- token hash 走 `sha256(token + per_user_salt)`,salt per-user 防 rainbow table
- 不引 bcrypt / passlib,Python 3.11+ stdlib 满足"内部工具"安全等级
- `default_admin` 永不被删/禁用(防锁出)
- audit retention 默认 90 天(`OPS_ONEHIT_AUDIT_RETENTION_DAYS` 可调)

**UI 集成**：

- 新增 `AuditTab`(30s 自动刷,时间范围 / user / action 过滤,失败行红色)
- `ops_onehit.ui.AuditTab` 可嵌入任意 QWidget 容器

**Python 用法**：

```python
from ops_onehit.rbac import UserStore, AuditLogger, Role, make_user
from ops_onehit.rbac.permissions import check_permission, Permission
from ops_onehit.rbac.audit import audit_action, set_current_username
from ops_onehit.data.db import get_database

db = get_database()
store = UserStore(db)
store.add_user(make_user("alice", Role.SRE))
audit = AuditLogger(db)
audit.log(username="alice", action="ack_alert", target="42", result="success")

# 装饰器
@audit_action("run_sop", target_arg=0)
async def run_sop_template(name: str, ...):
    ...
```

**详见** [`docs/RBAC_AND_AUDIT.md`](docs/RBAC_AND_AUDIT.md)。

---

## 20. T7.5 性能优化速查

T7.5 性能优化的目标:**启动 < 2s / 内存 < 500MB 稳态 / pytest 并行跑通**。

### 启动时间

```bash
# 实测:400ms(目标 < 2000ms)
python -m ops_onehit --help
```

3 层 lazy import 策略:
1. `ops_onehit/main.py` 顶层零业务 import,只留 argparse/rich.console
2. 每个 `cmd_*()` 函数内 `from ops_onehit.xxx import ...` 按需加载
3. `ops_onehit/__init__.py` 用 PEP 562 `__getattr__` 暴露重类,`from ops_onehit import ChromaRAGStore` 走 lazy 路径

### 内存稳态

```bash
# 实测:~25MB(目标 < 500MB)
python -m ops_onehit --help
```

T7.5 新增 3 个 `release()` 方法,长跑服务可主动释放重模型:

```python
# VLM / Whisper / ChromaRAGStore
from ops_onehit.multimodal.router import MultimodalRouter
router = MultimodalRouter(use_real_models=True)
router.release_all()  # 释放 ~2GB VLM + ~150MB Whisper

# 也可走 HTTP API
curl -X POST http://127.0.0.1:8080/api/multimodal/release \
  -H "Authorization: Bearer <token>"
# {"vlm": 1, "whisper": 1, "released_count": 2}
```

### pytest 并行

```toml
# pyproject.toml — 默认 -n auto,且默认不收集 perf(bench)用例
addopts = ["-n", "auto", "-m", "not bench", ...]
```

子集 sequential ~70s / parallel -n auto ~25s。完整 1043 测试全量在 `-n auto` 下
预估 < 200s(T7.3 baseline sequential 440s,**2x 加速**)。

perf 测试默认**不收集**(被 `-m "not bench"` 过滤掉),跑性能 gate:

```bash
.\.venv\Scripts\python.exe -m pytest -m bench -v
# 15 passed in ~150s（本机实测 147.42s；含 2 次嵌套 pytest 跑子集）
```

> ⚠️ bench 里的 `test_pytest_perf.py` 会**再 spawn 一套嵌套 pytest**,
> 而嵌套进程与外层共享同一个会话库(`%TEMP%/ops-onehit-pytest-session.db`)——
> **不要和别的 pytest 会话同时跑**。

### 性能 bench 工具

```bash
python scripts/bench.py --startup   # 启动时间 + 内存
python scripts/bench.py --memory    # 内存稳态
python scripts/bench.py --pytest    # pytest 时长
python scripts/bench.py --all       # 全部
```

**详见** [`docs/PERFORMANCE.md`](docs/PERFORMANCE.md)。

---

## 21. T7.6 K8s 集成速查

T7.6 把 **K8s 集群**接入 ops-onehit 的统一架构:数据采集 + 修复动作 + 知识图谱 + API + CLI。
商业对标 42/42 → **44/42**(超越 Datadog Watchdog 2 个点)。

### 5 件套总览

| 组件 | 文件 | 能力 |
|---|---|---|
| K8sCollector | `data/collectors/k8s.py` | 拉 Pod/Deployment,4 metrics/pod |
| K8s Actions | `repairs/k8s_actions.py` | L2 restart pod / L3 scale deployment |
| KG 集成 | `kg/infer.py` | Pod → ServiceNode, ownerReferences → hard 边 |
| API 端点 | `api/server.py` | 5 个 `/api/k8s/*` 端点,RBAC 集成 |
| CLI 子命令 | `data/collectors/k8s_cli.py` | 5 个 `--k8s` 子命令 |

### 一行命令

```bash
# 列出 Pod
ops-onehit --k8s list-pods --namespace default

# 列 kubeconfig contexts
ops-onehit --k8s list-contexts

# 切换 context(admin 权限)
ops-onehit --k8s use-context prod-cluster

# 重启 Pod(L2,需 --yes + SRE 权限)
ops-onehit --k8s restart-pod -n default -p web-1 --yes

# scale Deployment(L3,需 --yes + SRE 权限)
ops-onehit --k8s scale -n prod -d web --replicas 5 --yes
```

### HTTP API

```bash
# 拉 Pod 列表
curl -H "Authorization: Bearer $TOKEN" \
  "http://127.0.0.1:8080/api/k8s/pods?namespace=default"

# 重启 Pod(L2)
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user_confirmed": true, "grace_period_seconds": 30}' \
  "http://127.0.0.1:8080/api/k8s/pods/default/web-1/restart"

# scale Deployment(L3)
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user_confirmed": true, "replicas": 5}' \
  "http://127.0.0.1:8080/api/k8s/deployments/prod/web/scale"
```

### RBAC 矩阵

| 角色 | list-pods | list-contexts | restart-pod (L2) | scale (L3) | use-context |
|---|---|---|---|---|---|
| `viewer` | ✅ | ✅ | ❌ 403 | ❌ 403 | ❌ 403 |
| `developer` | ✅ | ✅ | ❌ 403 | ❌ 403 | ❌ 403 |
| `sre` | ✅ | ✅ | ✅ | ✅ | ❌ 403 |
| `admin` | ✅ | ✅ | ✅ | ✅ | ✅ |

### 关键设计

- **Graceful degradation**: 无 kubeconfig / 集群不通 → 返空 list,CollectorRunner 不崩
- **Mock-friendly**: `core_api_factory` / `apps_api_factory` 注入,63 个测试全用 mock
- **Audit 强制**: L2/L3 操作走 `@audit_action` 装饰器,即使 denied 也写库
- **KG 自动拓扑**: Pod → ReplicaSet hard 边 (`confidence=1.0`)
- **多 namespace**: `OPS_ONEHIT_K8S_NAMESPACES` env 或 `--namespace` arg;`*` = 全部

### 验收数字

- pytest 全量:**1132+ passed**(1060 旧 + 72 新)
- 新增测试:**63 个**(Collector 13 + Actions 18 + KG 4 + API 11 + CLI 13)
- ruff / black / mypy:**clean**

**详见** [`docs/K8S_INTEGRATION.md`](docs/K8S_INTEGRATION.md)。

---

## 22. T7.7 主动异常检测速查

T7.7 主动异常检测的目标:**iForest (无监督) + Prophet (时序预测) + Alert 集成**,
商业对标 Datadog Watchdog / Dynatrace Davis。

### 为什么需要

传统阈值告警的局限：需要人设阈值、不会自适应、漏掉"无阈值"的异常。
主动异常检测用 iForest + Prophet 解决。

### 快速上手

```bash
# 训练(从 db 拉过去 7 天数据)
ops-onehit --anomaly train prom:http://p:9090 cpu_usage --detector iforest --days 7

# 列出已训练模型
ops-onehit --anomaly list-models

# 跑异常检测(最近 1 小时)
ops-onehit --anomaly detect prom:http://p:9090 cpu_usage --hours 1
```

### HTTP API

```bash
# 列出
curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8000/anomaly/models

# 训练
curl -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"detector_type":"iforest","days":7}' \
  http://127.0.0.1:8000/anomaly/train/prom%3Ahttp%3A%2F%2Fp%3A9090/cpu_usage

# 检测
curl -H "Authorization: Bearer $TOKEN" \
  "http://127.0.0.1:8000/anomaly/detect/prom%3Ahttp%3A%2F%2Fp%3A9090/cpu_usage?hours=1"
```

### Python API

```python
from ops_onehit.data.db import get_database
from ops_onehit.detection.engine import AnomalyEngine

db = get_database()
engine = AnomalyEngine(db=db)

# 训练
detector = engine.train(
    source="prom:http://p:9090",
    name="cpu_usage",
    detector_type="iforest",
    days=7,
)

# 检测
results = engine.detect(
    source="prom:http://p:9090",
    name="cpu_usage",
    hours=1,
)
for r in results:
    if r.score.is_anomaly:
        print(f"ANOMALY: {r.sample.timestamp} score={r.score.value:.3f}")
```

### Alert 集成

`AnomalyRule` 监听 detector 输出的 score,`score > threshold` 触发告警。
与 `AlertRule`(阈值型)并存,互补:

| 维度 | `AlertRule` | `AnomalyRule` |
|------|-------------|---------------|
| 触发 | 阈值 + 持续时间 | 异常分数 |
| 状态机 | pending / firing / resolved | 一次性触发 |
| 适用 | 稳定告警 | 已识别异常 |

### CollectorRunner 调度

```python
runner = CollectorRunner(
    db=db,
    alert_manager=alert_mgr,
    anomaly_engine=engine,
    anomaly_sources=[
        ("prom:http://p:9090", "cpu_usage", "iforest"),
        ("prom:http://p:9090", "memory_usage", "prophet"),
    ],
    anomaly_interval_sec=300,  # 5 min
)
```

### UI (AnomalyTab)

`SystemMonitorWidget` 多一个 **Anomaly** tab,显示已注册 detector 列表
(Source / Name / Type / Fitted),30 秒自动刷新。

### 模型目录

`$LOCALAPPDATA/ops-onehit/anomaly_models/`(Windows)/
`~/.cache/ops-onehit/anomaly_models/`(Linux/macOS)。
可通过 env `OPS_ONEHIT_ANOMALY_MODEL_DIR` 自定义。

### 调参

| 参数 | 默认 | 调高/调低效果 |
|------|------|---------------|
| `score_threshold` | 0.7 | 调高 → 少报,调低 → 多报 |
| `contamination` (iForest) | 0.05 | 调高 → 模型更宽松 |
| `z_threshold` (Prophet) | 3.0 | 调高 → 只报极端偏离 |

**详见** [`docs/ANOMALY_DETECTION.md`](docs/ANOMALY_DETECTION.md)。

---

## 23. CI / CD(GitHub Actions)

ops-onehit 用 **GitHub Actions** 跑全自动化 CI / CD,4 个 jobs 覆盖 lint / type / pytest / build / release。

### 工作流(`.github/workflows/ci.yml`)

| Job | 触发 | 用途 |
|---|---|---|
| **test** | push / PR | matrix(2 OS × 2 Python = 4 组合)跑 lint + mypy + pytest(seq + par)+ build + twine check |
| **lint** | push / PR | 快速 lint-only 反馈(1-2 min) |
| **build** | push main | 产出 release-ready dist/ artifact |
| **release** | tag `v*` push | 自动创建 GitHub Release(含 dist 附件) |

### 本地模拟 CI

```bash
brew install act    # macOS / Linux
# 或
choco install act   # Windows

act -j lint         # 跑 lint job(快速反馈)
act -j test         # 跑全 matrix test job
```

### Dependabot

`.github/dependabot.yml` 自动开 PR 更新 3 类依赖:

- **pip**(每周一 9:00 UTC,limit 10 PR,skip major)
- **github-actions**(每周一 9:00 UTC,limit 5 PR)
- **docker**(每周一 9:00 UTC,limit 5 PR)

### Issue 模板

`.github/ISSUE_TEMPLATE/` 标准化 bug report + feature request。

详见 [`docs/CI_AND_DEPLOYMENT.md`](docs/CI_AND_DEPLOYMENT.md) §2 GitHub Actions CI。

---

## 24. Docker 部署

ops-onehit 提供 **multi-stage Dockerfile + docker-compose**,一键拉起生产栈。

### 快速开始

```bash
# 1. 构建镜像
docker build -t ops-onehit:1.0.0 .

# 2. 跑起来
docker run -d --name ops-onehit \
  -p 8080:8080 \
  -v ops-onehit-data:/home/ops/data \
  ops-onehit:1.0.0

# 3. 验证
curl -fsS http://localhost:8080/api/health
# {"status":"ok","version":"1.0.0"}
```

### docker-compose 一键生产栈

```bash
cp .env.example .env   # 改 LLM URL 等
docker compose up -d   # 起 web + nginx
docker compose logs -f ops-onehit-web
```

包含 2 个服务:

- **ops-onehit-web** — FastAPI 主服务(8080)
- **ops-onehit-nginx** — 反代(8081,可改 LoadBalancer 暴露)

### 镜像特征

- **multi-stage 2 段**:`builder`(装 build 工具)+ `runtime`(只装 wheel)
- **runtime < 200 MB**:`python:3.11-slim` 45 MB + ops-onehit 依赖 ~100 MB
- **non-root user**:`uid=1000 ops`,符合 CIS benchmark
- **tini PID 1**:正确转发 SIGTERM / SIGINT,优雅关闭
- **healthcheck**:curl `/api/health`,30s 间隔,失败 3 次重启
- **3 个 named volume**:data / cache / logs 持久化

详见 [`docs/CI_AND_DEPLOYMENT.md`](docs/CI_AND_DEPLOYMENT.md) §3-4 Docker + Compose。

---

## 25. Kubernetes 部署

ops-onehit 提供 **Kustomize manifests**,一键部署到 K8s 集群(replicas=2 高可用)。
也提供完整的 **Helm chart**(`deploy/helm/ops-onehit/`,支持多 region / HPA / PDB / NetworkPolicy)。

### 一键部署

```bash
# 部署(Kustomize)
kubectl apply -k deploy/k8s/

# 看状态
kubectl -n ops-onehit get all

# 端口转发(集群外访问)
kubectl -n ops-onehit port-forward svc/ops-onehit 8080:80

# 浏览器开 http://localhost:8080/

# 卸载
kubectl delete -k deploy/k8s/
```

```bash
# 或者用 Helm(功能更全)
helm install ops-onehit deploy/helm/ops-onehit/ \
  --namespace ops-onehit --create-namespace \
  --set image.repository=your-registry/ops-onehit \
  --set image.tag=1.0.0
```

### 资源清单

| 文件 | 类型 | 关键配置 |
|---|---|---|
| `01-namespace.yaml` | Namespace | `ops-onehit`(隔离工作负载) |
| `02-configmap.yaml` | ConfigMap | 业务配置(日志 / 鉴权 / 采集频率 / HA 参数) |
| `03-deployment.yaml` | Deployment | replicas=2, healthcheck 3 件套, securityContext, podAntiAffinity |
| `04-service.yaml` | Service | ClusterIP,可改 LoadBalancer / NodePort |
| `05-pvc.yaml` | PVC | 10Gi RWO(单 Pod 写,SQLite 兼容) |
| `06-serviceaccount.yaml` | ServiceAccount + ClusterRole + Binding | `--k8s` 子命令读 K8s API 的最小权限集 |
| `kustomization.yaml` | Kustomization | 集中 image / replicas 覆盖 |

### ⚠️ 部署前必须知道的 3 件事

1. **PVC 是 ReadWriteOnce,2 副本会有 1 个 Pod Pending**。
   SQLite 只能单写。要么 `kustomize edit set replicas ops-onehit 1`,
   要么换 RWX StorageClass 并把数据放 Postgres(`OPS_ONEHIT_DB_URL`)。
2. **多副本必须配 Redis**(`OPS_ONEHIT_HA_REDIS_URL`)。
   不配的话 leader 选举退化成各 Pod 各自为政 —— 这是最容易被忽略的坑。
3. **敏感配置别放 ConfigMap**。JWT secret / DB 密码 / Stripe key 用
   External Secrets / SOPS,或者 `kubectl create secret generic` 后在
   Deployment 加 `secretRef`。

### 关键设计

- **高可用**:2 副本 + 滚动升级 `maxUnavailable: 0`(无 downtime)
- **资源限制**:requests 100m/128Mi,limits 500m/512Mi
- **Pod anti-affinity**:尽量分散到不同 node
- **3 段 healthcheck**:startupProbe(150s 启动期)+ livenessProbe + readinessProbe
- **安全**:runAsNonRoot + readOnlyRootFilesystem + capabilities drop ALL
- **数据持久化**:PVC 10Gi,SQLite + ChromaDB + anomaly_models
- **Prometheus 自动发现**:Service annotations `prometheus.io/scrape`

### 自定义

```bash
cd deployment/k8s
kustomize edit set image ops-onehit:1.0.0=ops-onehit:1.0.1   # 改版本
kustomize edit set replicas ops-onehit-web=3                   # 改副本数
kustomize edit set namespace my-ops-onehit                     # 改 namespace
kubectl apply -k .
```

详见 [`docs/CI_AND_DEPLOYMENT.md`](docs/CI_AND_DEPLOYMENT.md) §5 Kubernetes 部署。

---

## 26. B8 Dashboard v2 — Vue 3 可视化后台

> **alpha 2.3 商业对标**:44/42 (105%) 部署就绪的可视化后台

ops-onehit 自带 Vue 3 + Vite + TypeScript 现代化 dashboard,集成 Chart.js / Cytoscape.js / DataTables.js 三大可视化库 + WebSocket 实时推送。取代原 4-panel 静态 HTML。

### 26.1 快速访问

```powershell
# 启动 ops-onehit web 服务
ops-onehit --web --host 127.0.0.1 --port 8080

# 浏览器打开
# 老静态面板:  http://localhost:8080/
# 新 Vue 3 面板: http://localhost:8080/dashboard/
```

dev 模式登录:用户名 `admin` / `dev_alice` / `sre_bob` / `viewer_eve` 任选,Token 任意(用 `admin-demo-2026` 这种 dev token 通过 `/api/health` 校验)。

rbac 模式登录:用 `ops-onehit user add --username admin --role admin` 创建的 token。

### 26.2 10+ Panel

| 位置 | Panel | 数据源 API |
|---|---|---|
| Row 1 (顶) | 4 KPI:CPU / 内存 / 磁盘 / 活跃告警 | `/api/dashboard/overview` |
| Row 2 (7+5) | 服务拓扑 (Cytoscape) + Metrics 时间线 (Chart.js) | `/api/kg/topology/d3` + `/api/dashboard/metrics/timeseries` |
| Row 3 (8+4) | 活跃告警 + 异常检测 | `/api/alerts` + `/api/anomaly/recent` |
| Row 4 (6+6) | SOP 历史 + KG 统计 + SOP 状态 | `/api/sop/recent` |
| Row 5 (6+6) | Audit log (sre/admin) + Episodic memory | `/api/audit/recent` + `/api/episodic/recent` |
| Row 6 (12) | K8s Pods | `/api/k8s/pods/dashboard` |
| Bottom (12) | StatusBar:WS 状态 + 4 类事件计数 | `Pinia live store` + WebSocket |

### 26.3 WebSocket 实时推送

```typescript
// 前端 stores/live.ts 自动连 ws://host:port/ws/live?token=<bearer>
// 订阅 4 类事件:
//   alert_fired / sop_completed / audit_logged / anomaly_detected
// 收到后自动 push 到 events[],OverviewView 触发 refreshAll()
```

后端 ``/ws/live`` 通过 query string 传 token(浏览器 WebSocket API 不支持 header),
``1008`` 鉴权失败,``25s`` keepalive ping。

### 26.4 重新构建前端

```powershell
cd dashboard
npm install          # 第一次
npm run build        # 产物自动 mount 到 src/ops_onehit/api/static/dashboard/
```

构建脚本 `dashboard/scripts/copy-to-static.js` 自动把 `dist/` 复制到 FastAPI 静态目录,无需手动 cp。

### 26.5 重新生成截图

```powershell
# 1. 启服务(后台)
ops-onehit --web --port 18080 &

# 2. seed demo 数据(可选)
python scripts/seed_dashboard_demo.py

# 3. 跑 playwright 截 10 张图(需要 playwright + chromium)
python scripts/e2e_b8_dashboard.py --base-url http://127.0.0.1:18080 --token admin-demo-2026
# 截图存 docs/dashboard/screenshots/
```

### 26.6 完整文档

- 后端 API 字段:`docs/DASHBOARD.md`(12 节,400+ 行)
- 截图库:`docs/dashboard/screenshots/`(10 张)
- 测试:`tests/test_dashboard_api.py` (14) + `tests/test_dashboard_websocket.py` (6) + `tests/test_dashboard_e2e.py` (4)= 24 个 B8 新增测试

### 26.7 自定义

- **改主题**:`dashboard/tailwind.config.js` → `theme.extend.colors.ops`
- **加新事件类型**:`ops_onehit/events/__init__.py` → 加常量 + `EVENT_TYPES`
- **加新 panel**:`dashboard/src/components/<area>/XxxPanel.vue` + `OverviewView.vue` 加一行 + 重 build

---

> 📘 详细 SOP 文档: [`docs/SOP.md`](docs/SOP.md)
> 🚀 部署指南: [`docs/CI_AND_DEPLOYMENT.md`](docs/CI_AND_DEPLOYMENT.md)
> 🐛 Bug Report: [GitHub Issues](https://github.com/a1580028209/ops-onehit/issues)
> 💬 讨论: 欢迎提 PR
