Metadata-Version: 2.5
Name: ops-onehit
Version: 1.0.3
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: aiosmtplib<4.0,>=3.0
Requires-Dist: bcrypt<5.0,>=4.1
Requires-Dist: boto3<2.0,>=1.40
Requires-Dist: certifi>=2026.10.19
Requires-Dist: cryptography<51,>=42
Requires-Dist: fastapi>=0.141.1
Requires-Dist: httpx>=0.27.0
Requires-Dist: jinja2<4.0,>=3.1
Requires-Dist: jsonpath-ng>=1.6.0
Requires-Dist: lxml<7.0,>=5.0
Requires-Dist: pillow>=12.3.0
Requires-Dist: psutil>=6.0.0
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: 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: redis<6.0,>=5.0
Requires-Dist: rich>=13.8.0
Requires-Dist: signxml<6.0,>=4.0
Requires-Dist: sqlalchemy<3.0,>=2.0
Requires-Dist: stripe<16.0,>=10.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: alembic<2.0,>=1.13; 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: gui
Requires-Dist: pyside6-essentials>=6.11.2; extra == 'gui'
Provides-Extra: integrations
Requires-Dist: docker>=7.1.0; extra == 'integrations'
Requires-Dist: kubernetes>=28.0.0; extra == 'integrations'
Requires-Dist: psycopg2-binary<3.0,>=2.9; extra == 'integrations'
Requires-Dist: pyyaml>=6.0.1; extra == 'integrations'
Provides-Extra: ml
Requires-Dist: accelerate>=1.0.0; extra == 'ml'
Requires-Dist: auto-gptq>=0.7.0; (sys_platform != 'darwin' and python_version < '3.12') and extra == 'ml'
Requires-Dist: av>=11.0.0; extra == 'ml'
Requires-Dist: chromadb>=0.4.22; extra == 'ml'
Requires-Dist: faster-whisper>=1.0.0; extra == 'ml'
Requires-Dist: joblib>=1.3.0; extra == 'ml'
Requires-Dist: onnxruntime>=1.17.0; extra == 'ml'
Requires-Dist: optimum>=1.20.0; extra == 'ml'
Requires-Dist: pandas>=2.0.0; extra == 'ml'
Requires-Dist: prophet>=1.1.0; extra == 'ml'
Requires-Dist: qwen-vl-utils>=0.0.8; extra == 'ml'
Requires-Dist: scikit-learn>=1.3.0; extra == 'ml'
Requires-Dist: sentence-transformers>=2.6.0; extra == 'ml'
Requires-Dist: soundfile>=0.12.0; extra == 'ml'
Requires-Dist: torch>=2.3.0; extra == 'ml'
Requires-Dist: torchvision>=0.18.0; extra == 'ml'
Requires-Dist: transformers>=4.45.0; extra == 'ml'
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)](#25-docker-部署)
[![K8s](https://img.shields.io/badge/K8s-kustomize%20ready-326CE5?logo=kubernetes&logoColor=white)](#26-kubernetes-部署)
[![Dependabot](https://img.shields.io/badge/Dependabot-enabled-blue?logo=dependabot)](https://github.com/a1580028209/ops-onehit/security/dependabot)

## 0. Quick Start

```powershell
# 安装（核心功能，29 个直接依赖 / 59 个传递闭包，~143MB 实测）
pip install ops-onehit

# 可选：桌面悬浮 widget / 系统托盘 / 告警气泡（PySide6，+214MB）
pip install "ops-onehit[gui]"

# 可选：机器学习能力（真 RAG / 异常检测 / 图像语音多模态，+1.6GB）
pip install "ops-onehit[ml]"

# 可选：外部系统集成（Postgres / Docker / K8s）
pip install "ops-onehit[integrations]"

# 可选：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
```

> 五个安装形态分别装了什么、什么时候需要装 → [§4.0 安装形态一览](#40-从-pypi-装推荐)

**更多用法**：[`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. **修复执行**：告警进入 FIRING 时**自动**启动对应 SOP 剧本（L0/L1 自动执行，L2+ 升级给人确认）；L2+ 被拒的步骤落成 `pending` 提案行，**人在面板上点一下确认即真执行**（`POST /api/repairs/{id}/confirm`）；K8s 修复（Pod 重启 / Deployment 扩缩）走真实 API，需 `user_confirmed=true`；剧本执行结果落 `sop_runs` 表，`GET /api/sop-runs` 可查 —— 剩余一处边界见 [§2.3](#23-目前还做不到什么) 与 [`docs/CAPABILITY_MATRIX.md`](docs/CAPABILITY_MATRIX.md) §1.5.1
5. **复盘报告**：所有执行结果持久化到 SQLite，Web 面板 / Tray 菜单 / Agent Ask 都能查

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

## 2. 当前版本的真实能力边界

这一节把「引擎已经写好」和「链路已经接通」分开讲清楚 —— 让你第一次用的时候，既不白等一个还没接上的自动化，也不低估已经能跑的部分。

### 2.1 现在就能自动做到什么

- **持续监测**：`--web` 启动即拉起后台采集器，每 5 秒采一次 CPU / 内存 / 磁盘 / 网络，落 `monitoring` 表
- **规则告警**：6 条内置规则 + 状态机（inactive → pending → firing → resolved），每次状态变化落一行 `alerts`
- **根因分析（RCA）**：本地 LLM 出根因 + 置信度分级（L0~L4）；异常检测基于历史样本
- **真的动手修**：`repairs/actions.py` 里 4 个本机动作**实际调 subprocess**（`clear_temp_files` / `flush_dns_cache` / `kill_process` / `restart_service`），K8s 侧 2 个（`restart_pod` / `scale_deployment`）走**真实 K8s API**
- **SOP 编排是真跑**：`sop/runner.py` 逐条调 `RepairExecutor`，abort / continue / rollback 失败策略、修复后验证、经验沉淀全部实现
- **告警自动启动剧本（批次 2 已接电）**：6 条内置规则与 6 个 SOP 剧本一一对应。告警进入 FIRING → 自动跑对应剧本 → **L0/L1 动作（诊断 / 清临时文件 / 清 DNS）当场执行**；同一 metric 只跑最严重的那条（CPU 99% 时只跑 `cpu_critical`），同一台机器一次只跑一个剧本
- **人工确认通道真执行（批次 3 已接电）**：L2+ 被权限闸门拒下的步骤会落成一条 `pending` 提案行；人确认一次 → `RepairExecutor.execute(user_confirmed=true)` **真的动手** → 真实结果回写提案行 + audit 入库
- **确认就在面板上点（批次 4 已接电）**：总览页顶部有「待确认修复」面板，列出等你点头的提案（动作 / 等级 / 来源告警 / 剧本 / 参数），点「确认执行」会先弹二次确认（**这活儿会真的动主机**），点「拒绝」则后端**一个动作都不执行**
- **复盘留痕**：所有执行结果落 SQLite，Web 面板 / 托盘 / Agent 都能查

### 2.2 需要人确认什么

| 事项 | 规则 |
|---|---|
| L2 及以上修复动作（杀进程 / 重启服务 / 清日志） | `RepairExecutor` 运行时校验 `user_confirmed=true`，没确认不放行。**自动触发时永远不代你确认** —— 这类步骤会被判 `denied` 并记进 `sop_runs.needs_human_steps`，等你点头 |
| 在哪儿点头 | **Web 面板总览页顶部的「待确认修复」**（批次 4）。也可以直接 `POST /api/repairs/{id}/confirm`。developer 只能确认 L1，sre / admin 才能确认 L2 / L3 |
| 面板上点了会不会白挨 403 | 不会。面板按动作的**真实等级**（取自动作注册表）点亮按钮，与后端鉴权**同一个判据** —— 亮着的按钮点下去就能过 |
| K8s 修复（Pod 重启 / Deployment 扩缩） | HTTP 入口必须显式带 `user_confirmed=true` |
| 剧本启动 | 已自动（告警 FIRING 即触发）。要临时关掉：`OPS_ONEHIT_AUTO_SOP=0` |

### 2.3 目前还做不到什么

修复链路还有一处「引擎在、线没接上」的断点（**断点 1 已在批次 2 修好，断点 2 已在批次 3 修好**）：

| # | 断点 | 你实际会看到什么 |
|---|---|---|
| ~~1~~ | ~~告警进入 FIRING 不会自动启动 SOP~~ ✅ **已修** | 批次 2 新增 `alerts/sop_trigger.py`：`AlertManager.persist_changes()` → `AlertSOPTrigger` → `SOPRunner` → `RepairExecutor`。安全边界由 executor 强制（L2+ 必 `user_confirmed`，自动触发时不给），不是靠自觉 |
| ~~2~~ | ~~`POST /api/repairs/{id}/confirm` 只改状态，不执行~~ ✅ **已修** | 批次 3 把它接成**真执行**：确认一条 `pending` 提案 → `RepairExecutor.execute(user_confirmed=true)` 真动手 → 真实结果回写提案行。更深一层的缺口也一并补了 —— `pending` 提案行原先**在 `src/` 里根本没有生产者**，现在由 `AlertSOPTrigger` 在剧本被权限闸门拒下时自动产出 |
| ~~2b~~ | ~~确认通道只有 curl 能用（前端零调用）~~ ✅ **已修** | 批次 4 补上面板：总览页顶部「待确认修复」，`GET /api/repairs?status=pending` 拉清单 + `POST /api/repairs/{id}/confirm` 点头，列表端点补齐决策上下文（告警来源 / 剧本 / 目标 / 参数） |
| 3 | **`runbook/` 模块的 12 个 action 是模拟的** | `runbook/executor.py:_execute_step()` 直接返回 `{"simulated": True}`，只写 `runbook_runs` 记录。真正会改主机状态的是另一套 `repairs/actions.py` + `repairs/k8s_actions.py` —— 两套「剧本」系统**同名不同物**，看文档时容易误判 |

> 剩下这处是**已知边界，不是隐藏缺陷**：能力都在，差的是最后一段接线。逐条实测证据见 [`docs/CAPABILITY_MATRIX.md`](docs/CAPABILITY_MATRIX.md) §1.5.1；触发方式与注意事项见 [§8 SOP 修复剧本](#8-sop-修复剧本)。

## 3. 核心能力

| 模块 | 文件 | 能力 |
|---|---|---|
| 数据采集 | `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) + 验证（**告警 FIRING 自动触发**，见 §2.1） |
| Agent | `src/ops_onehit/agent/` | ReAct 框架 + 7 个工具 (查告警 / 跑 SOP / 查知识库 / 写反馈) |
| Web 面板 | `src/ops_onehit/api/` | FastAPI + Vue 3 控制台（Dashboard v2）+ 完整 REST API + 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 注入偏好 |

## 4. 快速开始

### 4.0 从 PyPI 装（推荐）

```powershell
# 一行装核心（29 个直接依赖 / 59 个传递闭包，~143MB 实测）
pip install ops-onehit

# 跑自检（确认 DB + LLM 后端连通）
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 知识库（需要 [ml]，6 条默认 SRE 知识入 ChromaDB）
pip install "ops-onehit[ml]"
ops-onehit --init-knowledge
```

#### 安装形态一览

核心依赖已从 59 个降到 **29 个**（传递闭包 59 个包），重依赖按用途拆成 extra。按「你打算用到什么」装，不用全装。

体积是**实测值**（Windows / Python 3.11 / 干净 venv 装完的磁盘占用，2026-10-24）：

| 形态 | 安装命令 | 装了什么 | 增量体积 | 什么时候需要装 |
|---|---|---|---|---|
| **核心** | `pip install ops-onehit` | 采集 / 告警 / RCA / 修复执行 / SOP 编排 / 报告 / Web 面板 / CLI —— 29 个直接依赖 / 59 个传递闭包 | **143 MB** | **默认就够**。只想「装上就能跑」先装这个 |
| **桌面 GUI** | `pip install "ops-onehit[gui]"` | `pyside6-essentials`（QtCore / QtGui / QtWidgets）—— 桌面悬浮 widget / 系统托盘 / 告警气泡 | +214 MB | 要 `--widget` 桌面悬浮窗时。**Web 面板 / API / CLI / 采集告警完全不需要它** |
| **机器学习** | `pip install "ops-onehit[ml]"` | 追加 17 个：VLM（`torch` / `torchvision` / `transformers` / `qwen-vl-utils` / `accelerate` / `optimum` / `auto-gptq`）、ASR（`faster-whisper` / `soundfile` / `av`）、RAG 向量库（`chromadb` / `sentence-transformers` / `onnxruntime`）、异常检测（`prophet` / `scikit-learn` / `pandas` / `joblib`） | **+1.6 GB** | 要用真 RAG（`--init-knowledge` / `/api/knowledge/search`）、异常检测（`--anomaly`）、图像 / 语音多模态时 |
| **外部系统集成** | `pip install "ops-onehit[integrations]"` | 追加 4 个：`psycopg2-binary`（Postgres）/ `docker`（容器指标）/ `kubernetes`（K8s 采集 + 修复）/ `pyyaml`（kubeconfig 解析） | +131 MB | 要接 Postgres、拉容器指标、管 K8s 集群时 |
| **PDF 报告** | `pip install "ops-onehit[pdf]"` | `weasyprint`（还需系统装 cairo / pango） | 很小 | 要 SLA 月报出 PDF 而非 HTML 时；不装自动降级成 HTML |
| **增强交互** | `pip install "ops-onehit[tui]"` | `questionary` | 很小 | onboarding 向导想要更顺手的 prompt；不装走 `rich.prompt` |

> 这一轮拆分把核心安装从 **1027 MB 压到 143 MB**（−86%）。省下来的主要是两处：
> **① 8 个从没被 import 的死依赖**（`litellm` 157MB / `langchain` 全家 / `ollama` / `authlib` / `alembic`）—— 纯下载体积，零功能；
> **② `pyside6` meta 包** —— 它会把 QtWebEngine(332MB) + addons(100MB) 全拉进来，而项目只用到 QtCore/QtGui/QtWidgets。

> **不装 extra 不会崩，只会明确告诉你缺什么**：RAG / 异常检测 / VLM / ASR 会提示装 `pip install "ops-onehit[ml]"`（CLI 退 1、HTTP 端点返 **503** 而不是 500）；Postgres 会提示装 `pip install "ops-onehit[integrations]"`；K8s / Docker 采集器则**优雅跳过**（CLI 退 1 并打印安装命令），不影响其它采集器。
>
> 复制命令时**连引号一起复制**（`pip install "ops-onehit[ml]"`）：少了引号，shell 会把 `[ml]` 当通配符。

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

### 4.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 推理后端（二选一）**:
  - **LM Studio**（默认）— 装 [lmstudio.ai](https://lmstudio.ai)，在 **Developer** 标签启 **Developer Server**（默认端口 `1234`），加载任一模型
  - **Ollama** — 装 [ollama.com](https://ollama.com)，拉模型 `ollama pull qwen2.5:7b`（端口 `11434`）
  - 默认 provider 是 `lm_studio`（环境变量 `OPS_ONEHIT_LLM__PROVIDER`）。切到 Ollama 的完整步骤见 [`docs/LLM_SETUP.md`](docs/LLM_SETUP.md) §5
- **可选**: WMI 已默认开启；如需 CPU 温度则需主板/驱动支持 `Win32_Fan` / `Win32_TemperatureProbe`

### 4.2 装与启动

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

# 2. 装依赖（uv 会自动建 .venv）
uv sync                    # 只装核心 + dev 依赖
uv sync --extra ml         # 需要 RAG / 异常检测 / 多模态时
uv sync --extra integrations   # 需要 Postgres / Docker / K8s 时
uv sync --extra gui        # 需要桌面悬浮 widget 时

# 3. 起 LLM 后端（任选）
# 或 LM Studio 里点 "Start Server"（默认 provider，端口 1234）
ollama serve               # 用 Ollama（端口 11434，需先设 OPS_ONEHIT_LLM__PROVIDER=ollama）

# 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
```

> `uv sync` 默认只装核心依赖（29 个直接依赖 / 59 个传递包 / 实测 143MB）。RAG、异常检测、多模态在 `[ml]` extra 里 —— 不用 `uv sync --extra ml` 的话，`--init-knowledge` / `--anomaly` 会明确提示你去装。桌面悬浮 widget 则在 `[gui]` extra 里（`uv sync --extra gui`）。
> 第一次跑会做几件事：在 `data/ops_onehit.db` 建 SQLite，初始化 6 条告警规则，6 个 SOP 模板注册。冷启动 ≈ 1.5 秒。

### 4.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`。

### 4.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`) 加速国内访问
- **两种失败，处理方式不同**:
  - `chromadb` 本身没装（没装 `[ml]` extra）→ 抛 `ChromaRAGStoreUnavailable`，CLI 退 1、HTTP 端点返 503，并提示 `pip install "ops-onehit[ml]"`
  - 模型下载 / 加载失败 → 自动降级 mock embedding，检索链路不挂（降级原因记在 `provider.fallback_reason`）
- **跨进程共享**: 加完 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}")
```

## 5. 架构总览

```
┌───────────────────────  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/`）。

## 6. 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
```

## 7. Web 面板

`--web` 启 FastAPI 服务（`src/ops_onehit/api/server.py`），默认 `http://127.0.0.1:8080/`。常用 API（完整端点列表见 `/docs`）：

| Method | Path | 说明 |
|---|---|---|
| GET | `/api/health` | 健康检查 |
| GET | `/api/status` | 实时 CPU / 内存 / 磁盘 / 告警数 |
| GET | `/api/alerts` | 告警历史（可按 `state` 过滤）|
| GET | `/api/repairs` | 修复执行历史（可按 `status` 过滤；`status=pending` 就是「待人工确认」清单）|
| POST | `/api/repairs/{id}/confirm` | 确认 / 拒绝一条待确认的修复提案 —— **确认即真执行**（按动作等级校验 `write:confirm_repair_l1/l2/l3`）|
| GET | `/api/sop-runs` | 告警 → SOP 自动执行历史（可按 `alert_rule` 过滤）|
| POST | `/api/ask` | 问 SRE Agent（需要 LLM 在跑） |
| POST | `/api/knowledge/search` | RAG 知识库检索 |
| GET | `/` | 跳转到 Vue 3 控制台（`/dashboard/`）；未构建时回退到旧单文件 HTML |
| GET | `/docs` | FastAPI 自动生成的 OpenAPI 文档 |

T5.2 起提供 **Bearer Token 鉴权**，且它是**全局开关**，没有中间态：

| 状态 | 怎么触发 | 行为 |
|---|---|---|
| **不鉴权** | 不设 `OPS_ONEHIT_WEB_AUTH_TOKEN`，也不传 `--auth-token` | **所有请求直接放行**，任何能访问到该端口的人都能读写面板 |
| **全局 Bearer** | 设了 `OPS_ONEHIT_WEB_AUTH_TOKEN`（或传 `--auth-token`） | **每一个请求**都要带 `Authorization: Bearer <token>` |

几个容易踩的点：

- **没有「本机 127.0.0.1 豁免」这回事**。token 一旦设上，从本机访问 `http://127.0.0.1:8080/` 同样必须带 header —— 实测本机直连 8080 也是 401。
- 开了鉴权后**连首页和 `/docs` 都要带 token**：`/`、`/api/*`、`/static/*`、`/docs`、`/openapi.json` 一视同仁。浏览器直接敲 URL 拿不到页面，要用带 header 的请求（`curl -H "Authorization: Bearer <token>" http://127.0.0.1:8080/`）。
- **token 来源优先级**：`--auth-token` 命令行参数 > 环境变量 `OPS_ONEHIT_WEB_AUTH_TOKEN`（或项目根 `.env` 里同名项）> `core/config.py` 里 `web_auth_token` 字段的默认值（默认 `None`）。
- **不鉴权是默认值**，适合「只有自己能碰到这台机器」的桌面自用场景。一旦把 `--host` 改成 `0.0.0.0`、或放到 nginx 反代后面对外，**必须**先设 token。

配置示例（PowerShell，复制即用）：

```powershell
# 生成一个 32 字符随机 token
$token = -join ((1..32) | ForEach-Object { '{0:x}' -f (Get-Random -Max 16) })

# 方式 A：环境变量（推荐 —— 后台服务 / 计划任务都读得到）
$env:OPS_ONEHIT_WEB_AUTH_TOKEN = $token
ops-onehit --web --port 8080

# 方式 B：命令行参数（临时用，token 会留在 shell history 里）
ops-onehit --web --port 8080 --auth-token $token

# 验证：带 token 应返 200，不带应返 401
curl -H "Authorization: Bearer $token" http://127.0.0.1:8080/api/health
curl http://127.0.0.1:8080/api/health
```

> 环境变量名是 **`OPS_ONEHIT_WEB_AUTH_TOKEN`**（对应 `src/ops_onehit/core/config.py` 的 `web_auth_token` 字段）。历史上文档里写过的另一个 token 变量名**不是真实存在的变量名** —— 设了它不生效，鉴权会按「未配置」处理，也就是**完全不鉴权**。

## 8. 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 节。

> ✅ **触发方式（批次 2 已接电）**：告警进入 FIRING → **自动**启动对应剧本（`AlertManager.persist_changes()` → `AlertSOPTrigger` → `SOPRunner` → `RepairExecutor`）。
> - **L0/L1 自动执行**（诊断 / 清临时文件 / 清 DNS 缓存）；**L2+ 绝不代你确认** —— 被权限闸门判 `denied`，记进 `sop_runs.needs_human_steps` 等人工确认。
> - 同一 metric 只跑最严重的那条（CPU 99% 时只跑 `cpu_critical`）；同一台机器一次只跑一个剧本。
> - 执行结果落 `sop_runs` 表，`GET /api/sop-runs` 可查；总开关 `OPS_ONEHIT_AUTO_SOP`（默认开，设 `0` 关闭）。
> - 仍可由 Agent 的 `run_sop` 工具手动触发；执行历史用 `GET /api/sop-runs` 查。
>
> ✅ **人工确认通道（批次 3 已接电）**：被拒的 L2+ 步骤会落成一条 `status='pending'` 的**提案行**，人点一下即真执行。
> - 拉待确认清单：`GET /api/repairs?status=pending`（含 `params`，能显示「确认下去到底要干什么」）
> - 确认执行：`POST /api/repairs/{id}/confirm` `{"confirmed": true, "confirmed_by": "sre_alice"}` → **真调 `RepairExecutor`** → 真实结果回写提案行，响应带 `executed` / `execution_status` / `execution_result`
> - 拒绝：`{"confirmed": false}` → 写 `denied`，**动作函数一次都不被调用**
> - 权限按动作**真实等级**分级（L1 / L2 / L3 三档）；等级取自动作注册表，不信任库里那列 `level`
> - 只吃 `pending`，其它状态返 409（防止重复执行）；单个动作 180s 超时判 `error`
>
> ✅ **面板入口（批次 4 已接电）**：不用 curl 了 —— **总览页顶部就有「待确认修复」面板**。
> - 列出等你点头的提案：动作 / 等级 / 来源（哪个告警 + 哪个剧本）/ 参数 / 时间
> - 点「确认执行」会先弹**二次确认**（这活儿会真的动主机）；点「拒绝」则后端**一个动作都不执行**
> - 按钮按等级分档点亮（L1 / L2 / L3），与后端鉴权**同一个判据** —— 亮着的按钮点下去就能过，不会白挨 403
> - 角色链 `super_admin ⊃ admin ⊃ sre ⊃ developer ⊃ viewer`：developer 只能确认 L1，sre / admin 才能确认 L2 / L3
>
> ⚠️ 还剩一处断点：`runbook/` 模块的 12 个 action 是**模拟的**（`_execute_step()` 直接返回 `{"simulated": True}`）—— 与 `repairs/actions.py` 那套同名不同物。
> 完整分析见 [§2.3 目前还做不到什么](#23-目前还做不到什么) 与 [`docs/CAPABILITY_MATRIX.md`](docs/CAPABILITY_MATRIX.md) §1.5.1。

## 9. 开发与测试

### 9.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）

### 9.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
```

### 9.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()"的禁忌

## 10. 部署

生产部署走 **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）。

## 11. 截图

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

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

## 12. 路线图

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

## 13. 安全模型

修复层 **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

## 14. 常见问题

**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: 本地 LLM 后端怎么配？（Ollama 还是 LM Studio？）**
A: 两个都支持，**默认走 LM Studio**（`OPS_ONEHIT_LLM__PROVIDER` 默认值 `lm_studio`）。选一个装好、启起来就行：

| 后端 | 端口 | 怎么确认它在跑 | 怎么切过去 |
|---|---|---|---|
| **LM Studio**（默认） | `1234` | LM Studio → **Developer** 标签 → **Start Server** 变绿；再 `curl http://127.0.0.1:1234/v1/models` 能返回模型列表 | 不用切，默认就是它 |
| **Ollama** | `11434` | `ollama list` 能看到已拉模型；`curl http://127.0.0.1:11434/api/tags` 能返回列表 | 设 `OPS_ONEHIT_LLM__PROVIDER=ollama`（cmd 加 `set ` 前缀，PowerShell 用 `$env:` 前缀），再把 `OPS_ONEHIT_LLM__BASE_URL` 设为 `http://127.0.0.1:11434` |

`ops-onehit --test` 自检探的是**当前 provider** 的端点（默认 LM Studio `1234`），并会**顺手把另一个常见本地后端也探一遍**（Ollama `11434`），好告诉你是不是装了另一个后端却没切过来。两个后端都没起时你会看到：

```
> LLM 后端不可达（provider=lm_studio base_url=http://127.0.0.1:1234），跳过对话自检（DB 自检通过）
> 后端探测：lm_studio http://127.0.0.1:1234/v1/models 不可达；ollama http://localhost:11434/api/tags 可达
👉 探测到 ollama 在跑 —— 切过去：OPS_ONEHIT_LLM__PROVIDER=ollama
```

看到最后那行就照着切；没有这行说明两个后端都没起。确认后端是否真的在跑，用上表里那条 `curl http://127.0.0.1:1234/v1/models`，或直接跑 `ops-onehit --ask "ping"`（这条走当前 provider）。完整的 provider 切换与排错见 [`docs/LLM_SETUP.md`](docs/LLM_SETUP.md)。

**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**。

## 15. 许可与致谢

- **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)

## 16. Changelog

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

- **1.0.3** — **告警 → SOP 自动接电 + 人工确认真执行 + 待确认面板 + 依赖瘦身 + 文档对齐真实行为**:断点 2 已修 —— `POST /api/repairs/{id}/confirm` 现在**真执行**修复(此前只改 `status` 不碰主机),并补上了更深的那个缺口(`pending` 提案行在 `src/` 里原本**零生产者**,端点改成真执行也找不到对象):SOP 被权限闸门拒下的 L2+ 步骤现在自动落成 `pending` 提案行,人点一下即真执行;权限按动作**真实等级**(取自动作注册表,不信任库里那列 `level`)分 L1/L2/L3 三档校验,旧端点那个**从来没写成功过**的 audit log 也一并修好;**批次 4 把这条通道接到界面上** —— 总览页顶部新增「待确认修复」面板,列出等你点头的提案(动作 / 等级 / 来源告警 / 剧本 / 参数),点「确认执行」有二次确认(这活儿会真的动主机),点「拒绝」后端一个动作都不执行,按钮按等级分档点亮且与后端鉴权**同一个判据**(亮着的按钮点下去就能过,不会白挨 403),顺带修掉 `query_repair_actions` 把数据库 NULL 变成字面量 `"None"` 的数据缺陷与 `AnomalyList` 空态显示 key 名的缺陷;告警进入 FIRING **自动**启动对应剧本(断点 1 已修)—— L0/L1 自动执行、L2+ 绝不代你确认(升级给人)、同一 metric 只跑最严重的、同一台机器一次只跑一个剧本,结果落 `sop_runs` 表 + `GET /api/sop-runs` 可查,总开关 `OPS_ONEHIT_AUTO_SOP`;修 RCA 在调 LLM 前的 2.3 秒白等(Windows 上全量取 `psutil` 的 `status` 属性,~5ms/进程 ⇒ 2.28s → 0.61s,顺带修掉一个 CI flaky);核心依赖 59 → **29**(传递闭包 59 包 / **143MB 实测**,清理前 1027MB,**−86%**);清掉 8 个从没被 import 的死依赖(litellm / langchain 全家 / ollama SDK / authlib / alembic / tenacity);`pyside6` meta 包换成 `pyside6-essentials` 并挪进新增的 `[gui]` extra(桌面 widget 用,Web/API/CLI 零 Qt 依赖);重依赖拆成 `[ml]`(实测 +1.6GB) / `[integrations]`(+131MB) / `[gui]`(+214MB);不装 extra 时明确提示装哪个、HTTP 返 503 而不是 500;CLI 的 LLM 后端改与 Web API 同源(`settings.llm`),修容器默认命令 `serve` 不存在导致秒退的 bug;修 3 个「整轮 pytest 永久假死」根因(PySide6 模拟不彻底 / 采集器默认开 WMI 温度 / `clear_temp_files` 扫真 `%TEMP%` 且阻塞 event loop);Web 面板鉴权变量名更正为 `OPS_ONEHIT_WEB_AUTH_TOKEN`;README 新增「当前版本的真实能力边界」一节
- **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**

## 17. 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)。

---

## 18. 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)。

---

## 19. 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)。

---

## 21. 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)。

---

## 22. 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)。

---

## 23. 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)。

---

## 24. 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。

---

## 25. 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 ≈ 190 MB**:`python:3.11-slim` ~45 MB + 核心依赖实测 143 MB(死依赖清理前是 358 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。

---

## 26. 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 部署。

---

## 27. 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。

### 27.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。

### 27.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 |

### 27.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。

### 27.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。

### 27.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/
```

### 27.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 新增测试

### 27.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
