Add tenant contract doctor probe and automated regression test matrix
This commit is contained in:
1 parent
e76af01480
commit
733ede97d9
12 files changed
+1741
-4
No files matched your search
@@ -0,0 +1,226 @@
|
||||
# Seal-Use AI-Native Harness 架构演进与需求提案白皮书
|
||||
|
||||
> **设计核心哲学**:本系统的使用者与维护者主要为 AI 智能体(Agent Harness)。系统设计的首要目标不是人类的图形交互或阅读习惯,而是 **AI Agent 的极致易用性** —— **输入输出零歧义、上下文高信噪比、问题能够自动探查与感知、错误具备结构化自愈闭环(Self-Healing)**。
|
||||
|
||||
---
|
||||
|
||||
## 一、AI-Native vs Human-Centric 范式对比
|
||||
|
||||
| 维度 | 传统面向人类设计 (Human-Centric) | 面向 AI 智能体设计 (AI-Native Harness) |
|
||||
| :--- | :--- | :--- |
|
||||
| **交互输出** | 富文本、表格渲染、色彩斑斓的进度条、多步骤弹窗向导 | **`stdout` 纯严格 Schema JSON**,无冗余修饰,保证 LLM 解析 100% 稳定 |
|
||||
| **故障提示** | 模糊的人类提示(如“操作失败,请检查网络或参数”) | **高密度诊断信道 (`stderr`) + 机器可执行的下一步命令**(`👉 Next action: seal-use ...`) |
|
||||
| **错误定位** | 让人类打开 Web 控制台查看图表、肉眼比对单据差异 | **自动化断言探针 (`test regression`)**,自动计算混淆矩阵与决策翻转差异 |
|
||||
| **变更验证** | 人工点选测试单据、口头确认“看起来没问题” | **数学与逻辑确定性**:规则死锁检测、定量边界检查、全量沙箱重放验证 |
|
||||
| **容错机制** | 弹出警告等待人类决策 | **结构化修复建议与自动修复命令**(Exit Code 10 确认契约、Autofix Patch) |
|
||||
|
||||
---
|
||||
|
||||
## 二、测试环境与代码库深度 Review 现状剖析
|
||||
|
||||
针对当前测试环境(以 `xiezihao` 及绑定的生产租户 `LyG3iezucw03fs` 为基准)与整体代码库进行全链路审查,发现以下几个核心痛点与系统盲区:
|
||||
|
||||
### 1. 规则系统的“模糊地带”依然存在
|
||||
- **实测现状**:
|
||||
- 执行 `seal-use rules lint --corp xiezihao`:检出规则 13 存在 `适当`、`酌情` 等主观模糊词。
|
||||
- 执行 `seal-use rules lint --corp xiezihao --linter strict`:检出 7 条规则缺乏定量指标(金额、天数)或绝对刚性边界词(规则 17、19、20、21、24、25、26)。
|
||||
- **AI 视角的痛点**:
|
||||
- 当规则中包含“适当放宽”、“结合实际情况酌情”时,大模型在自动审核时的判定置信度(Confidence)会产生明显波动,导致同一种单据今天通过、明天驳回,产生偶发性幻觉。
|
||||
- AI Agent 目前只能“发现”问题,缺乏**标准化、无提示词漂移的自动修复工具**。
|
||||
|
||||
### 2. 规则迭代缺乏“防劣化回归测试闭环”
|
||||
- **实测现状**:
|
||||
- 目前已有 `corps sync-test`(同步配置到测试环境)和 `corps replay-test <sn>`(单笔单据重放测试)。
|
||||
- **AI 视角的痛点**:
|
||||
- 当 AI 修改了某条规则(例如将团建费规则的人均标准改为 60 元),AI 无法回答一个关键问题:**“这次修改是否会导致历史正常通过的单据被意外驳回?”**
|
||||
- 当前缺乏批量回归能力,AI 必须逐笔单据拉取、重放、对比,耗费大量 Token 且容易由于大模型上下文窗口截断而遗漏决策翻转(Decision Flips)。
|
||||
|
||||
### 3. Webhook 异步回调链路“本地断链”
|
||||
- **实测现状**:
|
||||
- `corps replay-test` 将单据推入测试环境后,Seal 后端完成异步审核,会向配置的 `outgoingResultWebhook` 发送 HTTP POST 回调。
|
||||
- 在测试租户中,回调地址往往是测试桩(如 `https://baidu.com` 或内网不可达地址)。
|
||||
- **AI 视角的痛点**:
|
||||
- AI 发送测试单据后,无法直接捕获后端的实际审核产物(决策结果、风险标签、审核理由),只能被动轮询 `runs list`。缺乏端到端的闭环测试能力。
|
||||
|
||||
### 4. 智能洞察(Analytics)目前是“被动拉取”,缺乏“主动哨兵”
|
||||
- **实测现状**:
|
||||
- 智能洞察已支持 `insight`、`risks`、`performance`、`analyze`、`export`。
|
||||
- **AI 视角的痛点**:
|
||||
- 返回的是全量统计数据(如 20 个标签、平均耗时等)。AI Agent 需要主动进行差分计算才能识别异常。
|
||||
- 缺乏针对“异常激增”、“置信度暴跌”、“审核吞吐突降”的主动预警计算引擎。
|
||||
|
||||
---
|
||||
|
||||
## 三、六大 AI-Native 核心需求规划提案
|
||||
|
||||
为彻底落实“**能自动测出问题、专为 AI 好用**”的目标,建议演进以下六大功能模块:
|
||||
|
||||
### 需求提案 1: `seal-use test regression` —— 规则变更自动化回归测试矩阵
|
||||
|
||||
#### 业务价值与 AI 交互设计
|
||||
- **目标**:AI 在修改规则草稿后,一键执行全自动历史单据回归验证,防止规则劣化。
|
||||
- **命令行界面 (CLI)**:
|
||||
```bash
|
||||
seal-use test regression --corp <testCorpId> [--samples 20] [--draft]
|
||||
```
|
||||
- **工作机制**:
|
||||
1. 自动从绑定的生产租户抓取最近 $N$ 笔已归档单据的原始输入与原始判定;
|
||||
2. 将单据批量推入测试租户(使用当前未发布的 Draft 规则执行审核);
|
||||
3. 自动比对两套判定,统计 **决策一致率** 与 **决策翻转明细 (Decision Flips)**;
|
||||
- **AI 输出 Schema (`stdout`)**:
|
||||
```json
|
||||
{
|
||||
"status": "COMPLETED",
|
||||
"samples": 20,
|
||||
"concordanceRate": 0.90,
|
||||
"verdict": "REGRESSION_DETECTED",
|
||||
"flips": [
|
||||
{
|
||||
"sn": "BX20260901001",
|
||||
"title": "市场部团建费报销",
|
||||
"prodDecision": "PASS",
|
||||
"testDecision": "REJECT",
|
||||
"flippedRuleId": "rule-13",
|
||||
"reasonDiff": "+ 人均金额 65 元超过上限 50 元",
|
||||
"riskTag": "B.1.1"
|
||||
}
|
||||
],
|
||||
"safeToPublish": false
|
||||
}
|
||||
```
|
||||
- **AI 友好特性**:`safeToPublish` 布尔标记直接给出确定性结论,AI Agent 无需自行阅读 20 份单据长文本即可判断是否可以发布上线。
|
||||
|
||||
---
|
||||
|
||||
### 需求提案 2: `seal-use rules check-conflicts` —— 规则语义冲突与死锁静态分析
|
||||
|
||||
#### 业务价值与 AI 交互设计
|
||||
- **目标**:在规则发布前,自动探测规则集内部是否存在自相矛盾或相互死锁的逻辑。
|
||||
- **命令行界面 (CLI)**:
|
||||
```bash
|
||||
seal-use rules check-conflicts --corp <corpId> [--draft]
|
||||
```
|
||||
- **核心检测模型**:
|
||||
1. **作用域重叠冲突 (Scope Overlap)**:如规则 A 和规则 B 均适用于 `单据模板=费用报销单` 且 `费用类型=交通费`,但规则 A 判定“必须上传行程单(MUST_FOLLOW)”,规则 B 判定“无行程单可做建议通过(SUGGESTION)”。
|
||||
2. **边界倒置 (Threshold Inversion)**:规则 A 规定“金额 > 5000 需总监审批”,规则 B 规定“金额 > 3000 需总经理审批”。
|
||||
3. **循环依赖与前提悬空**:规则声明必须关联采购单,但同一单据类型根本无采购单关联字段。
|
||||
- **AI 输出 Schema (`stdout`)**:
|
||||
```json
|
||||
{
|
||||
"hasConflicts": true,
|
||||
"conflicts": [
|
||||
{
|
||||
"type": "CONTRADICTORY_STRICTNESS",
|
||||
"rules": [16, 21],
|
||||
"scope": "单据模板=对公付款单",
|
||||
"explanation": "规则 16 要求未开具发票必须直接驳回,而规则 21 允许待开发票通过并补充凭证",
|
||||
"suggestedFix": "缩小规则 16 范围,排除税费缴纳类付款单"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 需求提案 3: `seal-use rules autofix` —— 规则缺陷自动修补与 Patch 引擎
|
||||
|
||||
#### 业务价值与 AI 交互设计
|
||||
- **目标**:将 Linter 发现的缺陷直接转为确定性的规范化重写建议,避免 AI Agent 自由发挥导致提示词漂移。
|
||||
- **命令行界面 (CLI)**:
|
||||
```bash
|
||||
seal-use rules autofix --corp <corpId> --rule <ruleCode> [--dry-run] [--yes]
|
||||
```
|
||||
- **工作机制**:
|
||||
- 针对 `VAGUE_WORD`(如“适当放宽”),自动基于企业既往审计偏好提供标准化替换模板(例如转换为明确的数值浮动比例或条件分支)。
|
||||
- 自动规范化条款格式:标号化(`1️⃣ 2️⃣`)、前置条件与驳回动作明确分离。
|
||||
- `--dry-run` 输出精准 Unified Diff;`--yes` 直接更新草稿。
|
||||
- **AI 友好特性**:Agent 可直接通过 `--dry-run` 读取 Patch,确认无误后执行 `--yes`,形成全自动修复流水线。
|
||||
|
||||
---
|
||||
|
||||
### 需求提案 4: `seal-use doctor tenant` —— 租户全链路健康契约探针与自愈
|
||||
|
||||
#### 业务价值与 AI 交互设计
|
||||
- **目标**:现有的 `seal-use doctor` 主要针对本地文件、二进制与 CLI 环境。新增租户级契约巡检,一键探测云端租户配置的完整性与可用性。
|
||||
- **命令行界面 (CLI)**:
|
||||
```bash
|
||||
seal-use doctor tenant --corp <corpId> [--repair]
|
||||
```
|
||||
- **核心探针项目**:
|
||||
1. **凭证存活性 (Auth Probe)**:OAuth/SSO 令牌剩余有效期、网关 Cookie 连通性、租户管理员权限完整度;
|
||||
2. **版本一致性 (Draft State Probe)**:规则是否存在未发布的脏草稿?发布版本是否落后于生产环境?
|
||||
3. **集成健康度 (Integration Probe)**:入向 Webhook URL 是否能够接收校验请求?出向 Webhook 是否存活(Ping 测试响应 2xx/3xx)?
|
||||
4. **知识库引用有效性 (Knowledge Probe)**:规则描述中引用的制度文件名称是否在知识库中真实存在?
|
||||
- **自动自愈 (`--repair`)**:
|
||||
- 若发现配置漂移,自动调用同步逻辑修复缺失项,使测试环境瞬间恢复到健康可用状态。
|
||||
|
||||
---
|
||||
|
||||
### 需求提案 5: `seal-use webhook mock-sink` —— 闭环本地模拟回调接收器
|
||||
|
||||
#### 业务价值与 AI 交互设计
|
||||
- **目标**:解决单据重放测试中“出向回调无人接收、测试无法闭环验证”的问题。
|
||||
- **命令行界面 (CLI)**:
|
||||
```bash
|
||||
seal-use webhook mock-sink --corp <corpId> --listen 9999 --timeout 30s
|
||||
```
|
||||
- **工作机制**:
|
||||
1. CLI 在本地启动一个微型 HTTP 监听端点;
|
||||
2. 自动临时将测试租户的 `outgoingResultWebhook` 更新为该端点(通过隧道或直连网段);
|
||||
3. 执行单据推送;
|
||||
4. 捕获 Seal 后端推送过来的完整决策 JSON,校验签名,打印到 `stdout`;
|
||||
5. 超时或收到结果后自动恢复原出向回调配置。
|
||||
- **AI 友好特性**:让 Agent 具备端到端的异步调用验证能力,真正做到“单据进 -> 判定出 -> 自动断言”。
|
||||
|
||||
---
|
||||
|
||||
### 需求提案 6: `seal-use analytics alerts` —— 质效异动哨兵与规则关联归因
|
||||
|
||||
#### 业务价值与 AI 交互设计
|
||||
- **目标**:将大盘数据的被动查询,升级为具备异常检测能力的“质量监控哨兵”。
|
||||
- **命令行界面 (CLI)**:
|
||||
```bash
|
||||
seal-use analytics alerts --corp <corpId> [--window 7d]
|
||||
```
|
||||
- **检测算法**:
|
||||
1. **低置信度突增预警**:检测置信度 $< 0.80$ 的风险标签占比是否超过 15%;
|
||||
2. **高频驳回标签突增**:检测某类风险(如“发票要素不全”)在规则修改后出现倍增;
|
||||
3. **归因推导**:将异常指标直接与具体的规则编号绑定,输出精准的修复建议。
|
||||
- **AI 输出 Schema (`stdout`)**:
|
||||
```json
|
||||
{
|
||||
"healthy": false,
|
||||
"alerts": [
|
||||
{
|
||||
"severity": "HIGH",
|
||||
"category": "CONFIDENCE_DROP",
|
||||
"message": "标签 'A.1.2 关键业务信息缺失' 平均置信度仅为 0.72",
|
||||
"affectedRules": [13, 21],
|
||||
"suggestedAction": "seal-use rules lint --corp xiezihao --rule 13"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、演进实施优先级与排期建议
|
||||
|
||||
| 优先级 | 需求模块 | 核心收益 | 实施复杂度 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **P0** | **`test regression` 自动化回归矩阵** | 解决 AI 修复规则时的“不敢改、不知改后是否破坏其他单据”的根本痛点 | 中(依赖已有的 Webhook Replay 与判定比较引擎) |
|
||||
| **P0** | **`doctor tenant` 租户契约探针与自愈** | 彻底消除 AI 任务前置准备阶段因环境配置残缺导致的未知报错 | 低(基于现有 API 组合健康检测函数) |
|
||||
| **P1** | **`rules check-conflicts` 规则死锁检测** | 提前在编译期/发布期拦截规则逻辑矛盾,杜绝 LLM 审核幻觉 | 中(建立 Scope 与 Strictness 的求交算法) |
|
||||
| **P1** | **`rules autofix` 规则修补 Patch 引擎** | 减少 AI 自由造句引起的格式漂移,提供标准化的规则修正模板 | 低至中(基于正则与 AST 替换) |
|
||||
| **P2** | **`analytics alerts` 质效异动哨兵** | 将分析报表升级为自动化质检闭环,主动通知 AI 优化特定规则 | 低(纯指标阈值与历史窗口滑动计算) |
|
||||
| **P2** | **`webhook mock-sink` 异步回调接收器** | 打造完整的 E2E 本地测试闭环 | 中(涉及临时端点管理与测试租户出向地址动态绑定) |
|
||||
|
||||
---
|
||||
|
||||
## 五、总结
|
||||
|
||||
将 `seal-use` 从“人类可用的 CLI 工具”转变为“**AI Agent 专用的自愈型 Harness**”,核心在于把**问题探查的主动权从人类眼睛转移给自动化算法与断言矩阵**。
|
||||
|
||||
通过实现回归矩阵(`test regression`)、租户探针(`doctor tenant`)以及规则死锁检测(`rules check-conflicts`),未来的 AI Agent 在接到“某客户反馈规则误报”的需求时,可以全自主地完成:
|
||||
$$\text{自动诊断} \longrightarrow \text{自动修复} \longrightarrow \text{批量回归验证} \longrightarrow \text{零劣化证明} \longrightarrow \text{发布上线}$$
|
||||
全程无需人类介入,实现真正的自动化可信运维。
|
||||
@@ -25,6 +25,31 @@ export async function handleDoctorCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Output tenant-level health contract and quota diagnosis
|
||||
if (subAction === "tenant" || subAction === "corp" || subAction === "enterprise") {
|
||||
const { selectCorp } = await import("../helpers.js");
|
||||
const { createSealClient } = await import("../../core/http/factory.js");
|
||||
const { stringOption } = await import("../parser.js");
|
||||
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../core/doctor/tenant-diagnose.js");
|
||||
|
||||
const corpSelector =
|
||||
stringOption(args.options.corp) ??
|
||||
(maybeName && maybeName !== subAction ? maybeName : undefined) ??
|
||||
(args.command[2] && args.command[2] !== subAction ? args.command[2] : undefined);
|
||||
|
||||
const corp = selectCorp(corpSelector);
|
||||
const client = await createSealClient(corp);
|
||||
const diagnosis = await diagnoseTenantContract(client, corp);
|
||||
|
||||
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
|
||||
if (!isQuiet) {
|
||||
console.error(formatTenantDoctorDashboard(diagnosis));
|
||||
}
|
||||
|
||||
printJson(diagnosis);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Default: Full system diagnostic inspection
|
||||
const diagnosis = diagnoseSystem();
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
|
||||
describe("seal-use test regression CLI", () => {
|
||||
test("fails with exit code 2 when unknown subaction is requested", async () => {
|
||||
const result = await runCli(["test", "invalid-action"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("未知的 test 子命令");
|
||||
});
|
||||
|
||||
test("rejects when production enterprise has no bound test enterprise", async () => {
|
||||
const result = await runCli(["test", "regression", "--corp", "ID01Nl1kQVYbKL"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("未绑定测试靶场企业");
|
||||
expect(result.stderr).toContain("硬性规定:回归测试严禁在生产环境直接运行");
|
||||
});
|
||||
|
||||
test("executes dry-run regression preview on paired test enterprise", async () => {
|
||||
const result = await runCli(["test", "regression", "--corp", "xiezihao", "--samples", "2", "--dry-run"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
const payload = JSON.parse(result.stdout);
|
||||
expect(payload.ok).toBe(true);
|
||||
expect(payload.verdict).toBe("DRY_RUN");
|
||||
expect(payload.safeToPublish).toBe(true);
|
||||
expect(payload.metrics.sampleCount).toBe(2);
|
||||
expect(payload.sourceCorp.id).toBe("LyG3iezucw03fs");
|
||||
expect(payload.targetCorp.id).toBe("xiezihao");
|
||||
expect(payload.records.length).toBe(2);
|
||||
|
||||
expect(result.stderr).toContain("规则回归测试矩阵");
|
||||
expect(result.stderr).toContain("DRY-RUN");
|
||||
});
|
||||
|
||||
test("corps regression alias routes to test regression command", async () => {
|
||||
const result = await runCli(["corps", "regression", "--corp", "xiezihao", "--samples", "2", "--dry-run"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
const payload = JSON.parse(result.stdout);
|
||||
expect(payload.verdict).toBe("DRY_RUN");
|
||||
expect(payload.targetCorp.id).toBe("xiezihao");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { CliError } from "../errors.js";
|
||||
import { selectCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { createSealClient } from "../../core/http/factory.js";
|
||||
import {
|
||||
formatRegressionDashboard,
|
||||
runRegressionTest
|
||||
} from "../../domains/seal/regression/service.js";
|
||||
|
||||
export async function handleTestCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
const subAction = (action ?? maybeName ?? "regression").toLowerCase();
|
||||
|
||||
if (subAction === "regression" || subAction === "regress" || subAction === "matrix") {
|
||||
const corpSelector =
|
||||
stringOption(args.options.corp) ??
|
||||
(maybeName && maybeName !== subAction ? maybeName : undefined);
|
||||
|
||||
const baseCorp = selectCorp(corpSelector);
|
||||
|
||||
let sourceCorp = baseCorp;
|
||||
let targetCorp = baseCorp;
|
||||
|
||||
if (baseCorp.environment === "test") {
|
||||
targetCorp = baseCorp;
|
||||
const sourceCorpId =
|
||||
stringOption(args.options["prod-corp"]) ??
|
||||
stringOption(args.options["prod"]) ??
|
||||
baseCorp.prodCorpId;
|
||||
|
||||
if (!sourceCorpId) {
|
||||
throw new CliError(
|
||||
`测试企业「${baseCorp.name}」(${baseCorp.id}) 未绑定生产母企业,无法拉取历史样本。\n` +
|
||||
`请建立绑定或通过 --prod-corp 参数指定生产企业来源。`,
|
||||
2,
|
||||
`seal-use corps bind-test <prodCorpId> ${baseCorp.id}`
|
||||
);
|
||||
}
|
||||
sourceCorp = selectCorp(sourceCorpId);
|
||||
} else {
|
||||
sourceCorp = baseCorp;
|
||||
const targetCorpId =
|
||||
stringOption(args.options["test-corp"]) ??
|
||||
stringOption(args.options["test"]) ??
|
||||
baseCorp.testCorpId;
|
||||
|
||||
if (!targetCorpId) {
|
||||
throw new CliError(
|
||||
`生产企业「${baseCorp.name}」(${baseCorp.id}) 未绑定测试靶场企业。\n` +
|
||||
`硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。`,
|
||||
2,
|
||||
`seal-use corps bind-test ${baseCorp.id} <testCorpId>`
|
||||
);
|
||||
}
|
||||
targetCorp = selectCorp(targetCorpId);
|
||||
}
|
||||
|
||||
const sourceClient = await createSealClient(sourceCorp);
|
||||
const targetClient = await createSealClient(targetCorp);
|
||||
|
||||
const samples =
|
||||
numberOption(args.options.samples) ??
|
||||
numberOption(args.options.limit) ??
|
||||
numberOption(args.options.n) ??
|
||||
10;
|
||||
|
||||
const dryRun = booleanOption(args.options["dry-run"]);
|
||||
const failOnFlips = booleanOption(args.options["fail-on-flips"]);
|
||||
const pollIntervalMs = numberOption(args.options["poll-interval"]) ?? 2000;
|
||||
const timeoutMs = numberOption(args.options.timeout) ?? 45000;
|
||||
const snPrefix = stringOption(args.options["sn-prefix"]) ?? "REG_";
|
||||
|
||||
const result = await runRegressionTest({
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
sourceClient,
|
||||
targetClient,
|
||||
samples,
|
||||
dryRun,
|
||||
pollIntervalMs,
|
||||
timeoutMs,
|
||||
snPrefix,
|
||||
failOnFlips
|
||||
});
|
||||
|
||||
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
|
||||
if (!isQuiet) {
|
||||
console.error(formatRegressionDashboard(result));
|
||||
}
|
||||
|
||||
// Machine channel (stdout): clean, structured JSON
|
||||
printJson(result);
|
||||
|
||||
if (failOnFlips && !result.ok) {
|
||||
throw new CliError(
|
||||
`回归测试发现 ${result.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,
|
||||
1
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw new CliError(
|
||||
`未知的 test 子命令: "${subAction}"。\n可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,
|
||||
2,
|
||||
"seal-use test regression --help"
|
||||
);
|
||||
}
|
||||
@@ -143,6 +143,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
name: "add-link",
|
||||
summary: "Import enterprise configuration from a Hose assistance link",
|
||||
usage: ["seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]"]
|
||||
},
|
||||
{
|
||||
name: "regression",
|
||||
aliases: ["test-regression"],
|
||||
summary: "Run automated rule regression test matrix against paired test enterprise",
|
||||
usage: ["seal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]"],
|
||||
options: [
|
||||
{ flag: "--samples <N>", description: "Number of historical production runs to replay (default: 10)" },
|
||||
{ flag: "--dry-run", description: "Preview sample documents and verify quota without executing replayed audits" },
|
||||
{ flag: "--fail-on-flips", description: "Exit with non-zero code if any decision flip is detected" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1009,6 +1020,38 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
aliases: ["dirs"],
|
||||
summary: "Inspect core filesystem paths and directory health",
|
||||
usage: ["seal-use doctor paths"]
|
||||
},
|
||||
{
|
||||
name: "tenant",
|
||||
aliases: ["corp", "enterprise"],
|
||||
summary: "Inspect tenant-level health contract, auth permissions, AI approval quota, and rules state",
|
||||
usage: ["seal-use doctor tenant [--corp <corpId>] [--quiet]"],
|
||||
options: [
|
||||
{ flag: "--corp <corpId>", description: "Enterprise ID or selector to diagnose" },
|
||||
{ flag: "--quiet", description: "Suppress formatted dashboard on stderr" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "test",
|
||||
title: "Automated test harnesses and rule regression matrix",
|
||||
description: "Run automated regression tests and decision comparison matrix across paired production and test environments.",
|
||||
commands: [
|
||||
{
|
||||
name: "regression",
|
||||
aliases: ["regress", "matrix"],
|
||||
summary: "Run automated rule regression test matrix against paired test enterprise",
|
||||
usage: ["seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]"],
|
||||
options: [
|
||||
{ flag: "--corp <corpId>", description: "Target test enterprise or production parent (must be paired)" },
|
||||
{ flag: "--samples <N>", description: "Number of historical production runs to replay (default: 10)" },
|
||||
{ flag: "--dry-run", description: "Preview sample documents and verify quota without executing replayed audits" },
|
||||
{ flag: "--fail-on-flips", description: "Exit with non-zero code if any decision flip is detected" },
|
||||
{ flag: "--prod-corp <id>", description: "Explicit production enterprise source for sample documents" },
|
||||
{ flag: "--test-corp <id>", description: "Explicit test enterprise target for replay" },
|
||||
{ flag: "--quiet", description: "Suppress formatted summary dashboard on stderr" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+12
-1
@@ -29,6 +29,7 @@ import { handleServiceCommand } from "./commands/service.js";
|
||||
import { handleSimulationCommand } from "./commands/simulation.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import { handleSourceCommand } from "./commands/source.js";
|
||||
import { handleTestCommand } from "./commands/test.js";
|
||||
import { handleToolCommand } from "./commands/tool.js";
|
||||
import { handleToolsListCommand } from "./commands/tools.js";
|
||||
import { handleUpdateCommand } from "./commands/update.js";
|
||||
@@ -91,7 +92,8 @@ export const KNOWN_AREAS = new Set([
|
||||
"openapi",
|
||||
"probe",
|
||||
"doctor",
|
||||
"changelog"
|
||||
"changelog",
|
||||
"test"
|
||||
]);
|
||||
|
||||
export type { CliResult, CliRunOptions } from "./types.js";
|
||||
@@ -228,6 +230,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "test") {
|
||||
await handleTestCommand(action, maybeName, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "config") {
|
||||
handleConfigCommand(action, maybeName, args);
|
||||
return;
|
||||
@@ -283,6 +290,10 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
}
|
||||
|
||||
if (area === "corps" || area === "corp") {
|
||||
if (action === "regression" || action === "test-regression") {
|
||||
await handleTestCommand("regression", maybeName, args);
|
||||
return;
|
||||
}
|
||||
await handleCorpsCommand(action, maybeName, args);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { diagnoseTenantContract, formatTenantDoctorDashboard } from "./tenant-diagnose.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
function createMockClient(opts: {
|
||||
whoami?: any;
|
||||
billing?: any;
|
||||
rules?: any;
|
||||
webhooks?: any;
|
||||
}) {
|
||||
return {
|
||||
get: async (url: string) => {
|
||||
if (url === "api/v1/auth/me") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: opts.whoami ?? {
|
||||
user: { id: "u_admin", tenantId: "t_1", name: "Admin", isAdmin: true, permissions: ["*"] },
|
||||
tenant: { id: "t_1", name: "Test Corp", tenantSlug: "testcorp" }
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (url === "api/v1/billing/status") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: opts.billing ?? {
|
||||
features: [
|
||||
{ code: "ai-approval", balance: 5000, deductionAmount: 100 },
|
||||
{ code: "approval-rules", quota: 100, used: 10, remaining: 90 }
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (url === "api/v1/rules") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: opts.rules ?? {
|
||||
rules: [
|
||||
{ id: "r1", description: "Rule 1", scope: "all", strictness: "MUST_FOLLOW", status: "ACTIVE" },
|
||||
{ id: "r2", description: "Rule 2", scope: "all", strictness: "SUGGESTION", status: "DISABLED" }
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (url === "api/v1/agent/ai-approval/config" || url === "api/v1/integrations/webhook") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
integrations: opts.webhooks ?? [
|
||||
{
|
||||
type: "webhook",
|
||||
id: "wh_1",
|
||||
name: "回放测试通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhook: { id: "in_1", url: "https://test.com/in" },
|
||||
outgoingResultWebhook: "https://test.com/out",
|
||||
incomingManualResultWebhook: { id: "manual_1", url: "https://test.com/manual" },
|
||||
secret: "sec_123"
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
throw new Error(`Unhandled mock GET url: ${url}`);
|
||||
}
|
||||
} as any;
|
||||
}
|
||||
|
||||
describe("tenant-diagnose", () => {
|
||||
test("diagnoses a healthy test tenant with sufficient quota and bindings", async () => {
|
||||
const mockClient = createMockClient({});
|
||||
const testCorp: CorpConfig = {
|
||||
id: "test-corp",
|
||||
name: "测试企业",
|
||||
environment: "test",
|
||||
prodCorpId: "prod-corp",
|
||||
source: { type: "seal" },
|
||||
seal: { url: "https://test.sealai.cc" }
|
||||
} as any;
|
||||
|
||||
const result = await diagnoseTenantContract(mockClient, testCorp);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.verdict).toBe("HEALTHY");
|
||||
expect(result.quota.balance).toBe(5000);
|
||||
expect(result.quota.estimatedRuns).toBe(50);
|
||||
expect(result.quota.status).toBe("sufficient");
|
||||
expect(result.rules.totalCount).toBe(2);
|
||||
expect(result.rules.activeCount).toBe(1);
|
||||
expect(result.webhooks.hasReplayChannel).toBe(true);
|
||||
expect(result.summary.failedChecks).toBe(0);
|
||||
|
||||
const dashboard = formatTenantDoctorDashboard(result);
|
||||
expect(dashboard).toContain("HEALTHY");
|
||||
expect(dashboard).toContain("5000");
|
||||
});
|
||||
|
||||
test("flags warning for low quota and unbound prod corp", async () => {
|
||||
const mockClient = createMockClient({
|
||||
billing: {
|
||||
features: [
|
||||
{ code: "ai-approval", balance: 500, deductionAmount: 100 }
|
||||
]
|
||||
},
|
||||
rules: { rules: [] }
|
||||
});
|
||||
|
||||
const unboundProdCorp: CorpConfig = {
|
||||
id: "prod-corp",
|
||||
name: "未绑定生产企业",
|
||||
environment: "production",
|
||||
source: { type: "seal" },
|
||||
seal: { url: "https://prod.sealai.cc" }
|
||||
} as any;
|
||||
|
||||
const result = await diagnoseTenantContract(mockClient, unboundProdCorp);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.verdict).toBe("DEGRADED");
|
||||
expect(result.quota.estimatedRuns).toBe(5);
|
||||
expect(result.quota.status).toBe("low");
|
||||
expect(result.rules.totalCount).toBe(0);
|
||||
expect(result.summary.warningChecks).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("flags fail when quota is exhausted or auth fails", async () => {
|
||||
const mockClient = createMockClient({
|
||||
billing: {
|
||||
features: [
|
||||
{ code: "ai-approval", balance: 0, deductionAmount: 100 }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
const testCorp: CorpConfig = {
|
||||
id: "test-corp",
|
||||
name: "额度耗尽企业",
|
||||
environment: "test",
|
||||
prodCorpId: "prod-corp",
|
||||
source: { type: "seal" },
|
||||
seal: { url: "https://test.sealai.cc" }
|
||||
} as any;
|
||||
|
||||
const result = await diagnoseTenantContract(mockClient, testCorp);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.verdict).toBe("BLOCKED");
|
||||
expect(result.quota.status).toBe("exhausted");
|
||||
expect(result.summary.failedChecks).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,413 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
|
||||
export interface TenantHealthCheck {
|
||||
id: string;
|
||||
name: string;
|
||||
status: "pass" | "warn" | "fail";
|
||||
summary: string;
|
||||
details: Record<string, unknown>;
|
||||
recommendation?: string;
|
||||
}
|
||||
|
||||
export interface TenantDoctorDiagnosis {
|
||||
ok: boolean;
|
||||
verdict: "HEALTHY" | "DEGRADED" | "BLOCKED";
|
||||
timestamp: string;
|
||||
corp: {
|
||||
id: string;
|
||||
name: string;
|
||||
environment: "production" | "test";
|
||||
sourceType: string;
|
||||
boundCorpId?: string;
|
||||
boundCorpRole?: "prodParent" | "testTarget";
|
||||
};
|
||||
summary: {
|
||||
totalChecks: number;
|
||||
passedChecks: number;
|
||||
warningChecks: number;
|
||||
failedChecks: number;
|
||||
};
|
||||
checks: TenantHealthCheck[];
|
||||
quota: {
|
||||
featureCode: string;
|
||||
balance: number;
|
||||
deductionAmount: number;
|
||||
estimatedRuns: number;
|
||||
status: "sufficient" | "low" | "exhausted";
|
||||
};
|
||||
rules: {
|
||||
totalCount: number;
|
||||
activeCount: number;
|
||||
quotaUsed?: number;
|
||||
quotaRemaining?: number;
|
||||
};
|
||||
webhooks: {
|
||||
integrationCount: number;
|
||||
hasReplayChannel: boolean;
|
||||
activeWebhookId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export async function diagnoseTenantContract(
|
||||
client: KyInstance,
|
||||
corp: CorpConfig
|
||||
): Promise<TenantDoctorDiagnosis> {
|
||||
const checks: TenantHealthCheck[] = [];
|
||||
const environment = corp.environment === "test" ? "test" : "production";
|
||||
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
|
||||
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
|
||||
|
||||
// 1. Auth & Admin Probe
|
||||
let userDetail: any = null;
|
||||
let tenantDetail: any = null;
|
||||
try {
|
||||
const whoami = await api.getMe(client);
|
||||
userDetail = whoami.user;
|
||||
tenantDetail = whoami.tenant;
|
||||
|
||||
const isAdmin = Boolean(userDetail?.isAdmin || userDetail?.permissions?.includes("*"));
|
||||
if (isAdmin) {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "pass",
|
||||
summary: `已认证为管理员「${userDetail.name ?? "未知"}」(${userDetail.id ?? ""}),具备完整操作权限`,
|
||||
details: {
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: true,
|
||||
tenantSlug: tenantDetail?.tenantSlug,
|
||||
permissions: userDetail.permissions
|
||||
}
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "warn",
|
||||
summary: `已认证为普通用户「${userDetail.name ?? "未知"}」,非超级管理员,部分配置操作可能受限`,
|
||||
details: {
|
||||
userId: userDetail.id,
|
||||
userName: userDetail.name,
|
||||
isAdmin: false,
|
||||
permissions: userDetail.permissions
|
||||
},
|
||||
recommendation: "建议使用具有管理权限的企业主账号执行规则修改与集成发布"
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "auth_identity",
|
||||
name: "身份与权限契约",
|
||||
status: "fail",
|
||||
summary: `鉴权握手失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) },
|
||||
recommendation: `请执行 seal-use auth login --corp ${corp.id} 重新登录或更新 Token`
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Billing & AI Approval Quota Probe
|
||||
let quotaInfo = {
|
||||
featureCode: "ai-approval",
|
||||
balance: 0,
|
||||
deductionAmount: 120,
|
||||
estimatedRuns: 0,
|
||||
status: "exhausted" as "sufficient" | "low" | "exhausted"
|
||||
};
|
||||
|
||||
let ruleQuota = {
|
||||
used: 0,
|
||||
remaining: 0
|
||||
};
|
||||
|
||||
try {
|
||||
const billing = await api.getBillingStatus(client);
|
||||
const features = Array.isArray(billing.features) ? billing.features : [];
|
||||
|
||||
// Find AI Approval feature
|
||||
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
|
||||
if (aiApproval) {
|
||||
const balance = typeof aiApproval.balance === "number" ? aiApproval.balance : 0;
|
||||
const deductionAmount = typeof aiApproval.deductionAmount === "number" && aiApproval.deductionAmount > 0
|
||||
? aiApproval.deductionAmount
|
||||
: 120;
|
||||
const estimatedRuns = Math.floor(balance / deductionAmount);
|
||||
|
||||
quotaInfo.balance = balance;
|
||||
quotaInfo.deductionAmount = deductionAmount;
|
||||
quotaInfo.estimatedRuns = estimatedRuns;
|
||||
|
||||
if (balance <= 0) {
|
||||
quotaInfo.status = "exhausted";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "fail",
|
||||
summary: `当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试`,
|
||||
details: { balance, deductionAmount, estimatedRuns },
|
||||
recommendation: "请联系管理员为企业充值 AI 审批额度"
|
||||
});
|
||||
} else if (estimatedRuns < 10) {
|
||||
quotaInfo.status = "low";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: `额度偏低:剩余 ${balance} 点 (单笔扣除 ${deductionAmount} 点),仅可支持约 ${estimatedRuns} 笔审核`,
|
||||
details: { balance, deductionAmount, estimatedRuns },
|
||||
recommendation: "建议在发起大规模自动化回归前充值补充额度"
|
||||
});
|
||||
} else {
|
||||
quotaInfo.status = "sufficient";
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "pass",
|
||||
summary: `额度充裕:剩余 ${balance} 点,预估可支持 ${estimatedRuns} 笔审核单据`,
|
||||
details: { balance, deductionAmount, estimatedRuns }
|
||||
});
|
||||
}
|
||||
} else {
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: "未检索到「ai-approval」功能包额度明细,按默认通道运行",
|
||||
details: { features: features.map((f: any) => f?.code) }
|
||||
});
|
||||
}
|
||||
|
||||
// Rule quota
|
||||
const ruleFeat = features.find((f: any) => f?.code === "approval-rules");
|
||||
if (ruleFeat) {
|
||||
ruleQuota.used = typeof ruleFeat.used === "number" ? ruleFeat.used : 0;
|
||||
ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0;
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "billing_quota",
|
||||
name: "AI 审批额度余量",
|
||||
status: "warn",
|
||||
summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Rules & Draft State Probe
|
||||
let rulesSummary = {
|
||||
totalCount: 0,
|
||||
activeCount: 0,
|
||||
quotaUsed: ruleQuota.used,
|
||||
quotaRemaining: ruleQuota.remaining
|
||||
};
|
||||
|
||||
try {
|
||||
const rulesData = await api.listApprovalRules(client);
|
||||
const rules = Array.isArray(rulesData.rules) ? rulesData.rules : [];
|
||||
rulesSummary.totalCount = rules.length;
|
||||
rulesSummary.activeCount = rules.filter((r) => r.status === "ACTIVE").length;
|
||||
|
||||
if (rules.length === 0) {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "warn",
|
||||
summary: "当前租户未配置任何审核规则 (规则数为 0)",
|
||||
details: { totalCount: 0, activeCount: 0 },
|
||||
recommendation: environment === "test" && boundCorpId
|
||||
? `可运行 seal-use corps sync-test --corp ${boundCorpId} 从生产企业同步规则`
|
||||
: "可运行 seal-use rules add 创建基础规则"
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "pass",
|
||||
summary: `审核规则健康:共 ${rulesSummary.totalCount} 条规则,其中生效活跃 ${rulesSummary.activeCount} 条`,
|
||||
details: {
|
||||
totalCount: rulesSummary.totalCount,
|
||||
activeCount: rulesSummary.activeCount,
|
||||
quotaUsed: ruleQuota.used,
|
||||
quotaRemaining: ruleQuota.remaining
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "rules_status",
|
||||
name: "审核规则状态",
|
||||
status: "fail",
|
||||
summary: `拉取规则列表失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Webhook Integration Probe
|
||||
let webhooksSummary = {
|
||||
integrationCount: 0,
|
||||
hasReplayChannel: false,
|
||||
activeWebhookId: undefined as string | undefined
|
||||
};
|
||||
|
||||
try {
|
||||
const integrations = await api.listWebhookIntegrations(client);
|
||||
webhooksSummary.integrationCount = integrations.length;
|
||||
|
||||
const replayChannel = integrations.find(
|
||||
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
|
||||
);
|
||||
webhooksSummary.hasReplayChannel = Boolean(replayChannel);
|
||||
webhooksSummary.activeWebhookId = replayChannel?.id ?? integrations[0]?.id;
|
||||
|
||||
if (integrations.length === 0) {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "warn",
|
||||
summary: "未配置任何 Webhook 集成通道,执行重放测试时将自动创建临时回放通道",
|
||||
details: { integrationCount: 0 },
|
||||
recommendation: "可运行 seal-use webhook add --name (回放通道) 手动注册专属通道"
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "pass",
|
||||
summary: `Webhook 集成通道就绪:共 ${integrations.length} 个通道${replayChannel ? ` (含专属回放通道「${replayChannel.name}」)` : ""}`,
|
||||
details: {
|
||||
integrationCount: integrations.length,
|
||||
hasReplayChannel: webhooksSummary.hasReplayChannel,
|
||||
activeWebhookId: webhooksSummary.activeWebhookId
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
checks.push({
|
||||
id: "webhook_integrations",
|
||||
name: "单据推送 Webhook 通道",
|
||||
status: "warn",
|
||||
summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
details: { error: String(err) }
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Environment Pairing Probe
|
||||
if (environment === "test") {
|
||||
if (boundCorpId) {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "测试环境配对契约",
|
||||
status: "pass",
|
||||
summary: `测试租户已绑定生产母企业「${boundCorpId}」,具备样本拉取与配置同步能力`,
|
||||
details: { environment, boundCorpId, boundCorpRole }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "测试环境配对契约",
|
||||
status: "warn",
|
||||
summary: "测试租户尚未绑定对应的生产母企业,无法直接拉取生产样本执行自动化回归",
|
||||
details: { environment },
|
||||
recommendation: `可运行 seal-use corps bind-test <prodCorpId> ${corp.id} 建立 1 对 1 绑定`
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (boundCorpId) {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "生产环境安全隔离契约",
|
||||
status: "pass",
|
||||
summary: `生产企业已绑定沙箱测试靶场「${boundCorpId}」,回归测试将严格限制在靶场中运行`,
|
||||
details: { environment, boundCorpId, boundCorpRole }
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
id: "environment_binding",
|
||||
name: "生产环境安全隔离契约",
|
||||
status: "warn",
|
||||
summary: "生产企业尚未绑定任何测试企业,所有回归测试功能将触发安全拦截",
|
||||
details: { environment },
|
||||
recommendation: `可运行 seal-use corps bind-test ${corp.id} <testCorpId> 为该生产租户绑定测试靶场`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Compute overall verdict
|
||||
const failedChecks = checks.filter((c) => c.status === "fail").length;
|
||||
const warningChecks = checks.filter((c) => c.status === "warn").length;
|
||||
const passedChecks = checks.filter((c) => c.status === "pass").length;
|
||||
|
||||
let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY";
|
||||
if (failedChecks > 0) {
|
||||
verdict = "BLOCKED";
|
||||
} else if (warningChecks > 0) {
|
||||
verdict = "DEGRADED";
|
||||
}
|
||||
|
||||
return {
|
||||
ok: failedChecks === 0,
|
||||
verdict,
|
||||
timestamp: new Date().toISOString(),
|
||||
corp: {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
environment,
|
||||
sourceType: corp.source?.type ?? "native",
|
||||
boundCorpId,
|
||||
boundCorpRole
|
||||
},
|
||||
summary: {
|
||||
totalChecks: checks.length,
|
||||
passedChecks,
|
||||
warningChecks,
|
||||
failedChecks
|
||||
},
|
||||
checks,
|
||||
quota: quotaInfo,
|
||||
rules: rulesSummary,
|
||||
webhooks: webhooksSummary
|
||||
};
|
||||
}
|
||||
|
||||
export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): string {
|
||||
const { corp, verdict, summary, checks, quota, rules, webhooks } = diagnosis;
|
||||
|
||||
const verdictBadge =
|
||||
verdict === "HEALTHY"
|
||||
? "🟢 健康良好 (HEALTHY)"
|
||||
: verdict === "DEGRADED"
|
||||
? "🟡 亚健康降级 (DEGRADED)"
|
||||
: "🔴 阻断受限 (BLOCKED)";
|
||||
|
||||
const lines: string[] = [
|
||||
"",
|
||||
`🏥 [Seal Use Doctor] 租户全链路契约体检: ${corp.name} (${corp.id})`,
|
||||
` 状态: ${verdictBadge} · 环境: ${corp.environment.toUpperCase()} · 耗时: 实时探针`,
|
||||
" " + "─".repeat(60)
|
||||
];
|
||||
|
||||
// Core metrics overview
|
||||
lines.push(
|
||||
` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
|
||||
);
|
||||
if (corp.boundCorpId) {
|
||||
lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`);
|
||||
}
|
||||
lines.push(" " + "─".repeat(60));
|
||||
|
||||
for (const check of checks) {
|
||||
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗";
|
||||
lines.push(` [${icon}] ${check.name}: ${check.summary}`);
|
||||
if (check.recommendation) {
|
||||
lines.push(` 👉 建议: ${check.recommendation}`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(" " + "─".repeat(60));
|
||||
lines.push(` 检查汇总: 通过 ${summary.passedChecks} · 告警 ${summary.warningChecks} · 失败 ${summary.failedChecks}`);
|
||||
lines.push("");
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -682,7 +682,7 @@ export async function listApprovalRuns(
|
||||
toTimestamp?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
status?: string;
|
||||
status?: string | string[];
|
||||
sourceSystem?: string;
|
||||
taskMode?: string;
|
||||
manualApprovalStatus?: string | string[];
|
||||
@@ -699,7 +699,7 @@ export async function listApprovalRuns(
|
||||
setOptional(searchParams, "toTimestamp", params.toTimestamp);
|
||||
setOptional(searchParams, "startDate", params.startDate);
|
||||
setOptional(searchParams, "endDate", params.endDate);
|
||||
setOptional(searchParams, "status", params.status);
|
||||
setArrayOptional(searchParams, "status", params.status);
|
||||
setOptional(searchParams, "sourceSystem", params.sourceSystem);
|
||||
setOptional(searchParams, "taskMode", params.taskMode);
|
||||
setOptional(searchParams, "search", params.search);
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { formatRegressionDashboard, runRegressionTest } from "./service.js";
|
||||
|
||||
const mockSourceCorp: CorpConfig = {
|
||||
id: "prod-corp",
|
||||
name: "母企业",
|
||||
environment: "production",
|
||||
testCorpId: "test-corp",
|
||||
source: { type: "seal" },
|
||||
seal: { url: "https://prod.sealai.cc" }
|
||||
} as any;
|
||||
|
||||
const mockTargetCorp: CorpConfig = {
|
||||
id: "test-corp",
|
||||
name: "测试靶场",
|
||||
environment: "test",
|
||||
prodCorpId: "prod-corp",
|
||||
source: { type: "seal" },
|
||||
seal: { url: "https://test.sealai.cc" }
|
||||
} as any;
|
||||
|
||||
describe("regression service", () => {
|
||||
test("enforces Red Line 1: rejects when target is not a test enterprise", async () => {
|
||||
const invalidTarget: CorpConfig = {
|
||||
...mockTargetCorp,
|
||||
environment: "production"
|
||||
} as any;
|
||||
|
||||
expect(
|
||||
runRegressionTest({
|
||||
sourceCorp: mockSourceCorp,
|
||||
targetCorp: invalidTarget,
|
||||
sourceClient: {} as any,
|
||||
targetClient: {} as any,
|
||||
samples: 5
|
||||
})
|
||||
).rejects.toThrow("非测试环境");
|
||||
});
|
||||
|
||||
test("enforces Red Line 2: blocks when quota balance is insufficient", async () => {
|
||||
const mockTargetClient = {
|
||||
get: async (url: string) => {
|
||||
if (url === "api/v1/billing/status") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
features: [
|
||||
{ code: "ai-approval", balance: 200, deductionAmount: 100 }
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected url: ${url}`);
|
||||
}
|
||||
} as any;
|
||||
|
||||
expect(
|
||||
runRegressionTest({
|
||||
sourceCorp: mockSourceCorp,
|
||||
targetCorp: mockTargetCorp,
|
||||
sourceClient: {} as any,
|
||||
targetClient: mockTargetClient,
|
||||
samples: 5 // requires 5 * 100 = 500 > 200
|
||||
})
|
||||
).rejects.toThrow("AI 审批额度不足");
|
||||
});
|
||||
|
||||
test("executes dry-run preview and returns sample records without network mutations", async () => {
|
||||
const mockSourceClient = {
|
||||
get: async (url: string) => {
|
||||
if (url.startsWith("api/v1/approvals")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "run_1",
|
||||
sourceDocumentSN: "SN001",
|
||||
result: { decision: "APPROVE", summary: "通过" }
|
||||
},
|
||||
{
|
||||
id: "run_2",
|
||||
sourceDocumentSN: "SN002",
|
||||
result: { decision: "REJECT", summary: "超标驳回" }
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected url: ${url}`);
|
||||
}
|
||||
} as any;
|
||||
|
||||
const mockTargetClient = {
|
||||
get: async (url: string) => {
|
||||
if (url === "api/v1/billing/status") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
features: [
|
||||
{ code: "ai-approval", balance: 5000, deductionAmount: 100 }
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected url: ${url}`);
|
||||
}
|
||||
} as any;
|
||||
|
||||
const result = await runRegressionTest({
|
||||
sourceCorp: mockSourceCorp,
|
||||
targetCorp: mockTargetCorp,
|
||||
sourceClient: mockSourceClient,
|
||||
targetClient: mockTargetClient,
|
||||
samples: 2,
|
||||
dryRun: true
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.verdict).toBe("DRY_RUN");
|
||||
expect(result.safeToPublish).toBe(true);
|
||||
expect(result.metrics.sampleCount).toBe(2);
|
||||
expect(result.records[0]!.sn).toBe("SN001");
|
||||
expect(result.records[0]!.prodDecision).toBe("APPROVE");
|
||||
expect(result.records[1]!.sn).toBe("SN002");
|
||||
expect(result.records[1]!.prodDecision).toBe("REJECT");
|
||||
|
||||
const dashboard = formatRegressionDashboard(result);
|
||||
expect(dashboard).toContain("DRY-RUN");
|
||||
expect(dashboard).toContain("2");
|
||||
});
|
||||
|
||||
test("executes live regression, detects decision flips, and calculates concordance", async () => {
|
||||
const mockSourceClient = {
|
||||
get: async (url: string) => {
|
||||
if (url === "api/v1/approvals/run_1") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
id: "run_1",
|
||||
sourceDocumentSN: "SN001",
|
||||
document: { fields: [{ key: "f1", label: "事由", type: "TEXT", value: "团建" }] }
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (url === "api/v1/approvals/run_2") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
id: "run_2",
|
||||
sourceDocumentSN: "SN002",
|
||||
document: { fields: [{ key: "f1", label: "事由", type: "TEXT", value: "招待" }] }
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (url.startsWith("api/v1/approvals")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "run_1",
|
||||
sourceDocumentSN: "SN001",
|
||||
result: { decision: "APPROVE", summary: "原生产通过" }
|
||||
},
|
||||
{
|
||||
id: "run_2",
|
||||
sourceDocumentSN: "SN002",
|
||||
result: { decision: "APPROVE", summary: "原生产通过" }
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected source url: ${url}`);
|
||||
}
|
||||
} as any;
|
||||
|
||||
const mockTargetClient = {
|
||||
get: async (url: string, opts?: any) => {
|
||||
const fullUrl = opts?.searchParams ? `${url}?${opts.searchParams.toString()}` : url;
|
||||
|
||||
if (url === "api/v1/billing/status") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
features: [
|
||||
{ code: "ai-approval", balance: 5000, deductionAmount: 100 }
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (url === "api/v1/agent/ai-approval/config" || url === "api/v1/integrations/webhook") {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
integrations: [
|
||||
{
|
||||
type: "webhook",
|
||||
id: "wh_test",
|
||||
name: "回放通道",
|
||||
mode: "assisted",
|
||||
incomingDocumentWebhook: { id: "in_1", url: "https://test.sealai.cc/api/v1/integrations/webhook/wh_test/document" },
|
||||
outgoingResultWebhook: "https://test.sealai.cc/out",
|
||||
incomingManualResultWebhook: { id: "man_1", url: "https://test.sealai.cc/man" },
|
||||
secret: "sec123"
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (fullUrl.includes("sourceDocumentSN=REG_SN001")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "test_run_1",
|
||||
status: "completed",
|
||||
result: { decision: "APPROVE", summary: "测试规则依然通过" }
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
if (fullUrl.includes("sourceDocumentSN=REG_SN002")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "test_run_2",
|
||||
status: "completed",
|
||||
result: { decision: "REJECT", summary: "测试新规则判定超标驳回" }
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected target url: ${fullUrl}`);
|
||||
}
|
||||
} as any;
|
||||
|
||||
const mockFetch = async (url: string) => {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ success: true })
|
||||
} as any;
|
||||
};
|
||||
|
||||
const result = await runRegressionTest({
|
||||
sourceCorp: mockSourceCorp,
|
||||
targetCorp: mockTargetCorp,
|
||||
sourceClient: mockSourceClient,
|
||||
targetClient: mockTargetClient,
|
||||
samples: 2,
|
||||
pollIntervalMs: 5,
|
||||
timeoutMs: 1000,
|
||||
fetchFn: mockFetch as unknown as typeof fetch
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.verdict).toBe("REGRESSIONS_DETECTED");
|
||||
expect(result.safeToPublish).toBe(false);
|
||||
expect(result.metrics.sampleCount).toBe(2);
|
||||
expect(result.metrics.matchCount).toBe(1);
|
||||
expect(result.metrics.flipCount).toBe(1);
|
||||
expect(result.metrics.concordanceRate).toBe(0.5);
|
||||
|
||||
expect(result.flips.length).toBe(1);
|
||||
expect(result.flips[0]!.sn).toBe("SN002");
|
||||
expect(result.flips[0]!.prodDecision).toBe("APPROVE");
|
||||
expect(result.flips[0]!.testDecision).toBe("REJECT");
|
||||
|
||||
const dashboard = formatRegressionDashboard(result);
|
||||
expect(dashboard).toContain("REGRESSIONS_DETECTED");
|
||||
expect(dashboard).toContain("SN002");
|
||||
expect(dashboard).toContain("50.0%");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,402 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { CliError } from "../../../cli/errors.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||
import * as api from "../api.js";
|
||||
import type { ApprovalRun } from "../types.js";
|
||||
import {
|
||||
ensureTestWebhookIntegration,
|
||||
pushWebhookDocument,
|
||||
transformApprovalRunToWebhookDocument
|
||||
} from "../webhook-replay.js";
|
||||
|
||||
export interface RegressionTestOptions {
|
||||
sourceCorp: CorpConfig;
|
||||
targetCorp: CorpConfig;
|
||||
sourceClient: KyInstance;
|
||||
targetClient: KyInstance;
|
||||
samples?: number;
|
||||
dryRun?: boolean;
|
||||
pollIntervalMs?: number;
|
||||
timeoutMs?: number;
|
||||
snPrefix?: string;
|
||||
failOnFlips?: boolean;
|
||||
fetchFn?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface RegressionSampleRecord {
|
||||
sn: string;
|
||||
sourceRecordId: string;
|
||||
prodDecision: string;
|
||||
prodSummary?: string;
|
||||
testRecordId?: string;
|
||||
testDecision?: string;
|
||||
testSummary?: string;
|
||||
status: "MATCHED" | "FLIPPED" | "FAILED" | "DRY_RUN";
|
||||
diff?: {
|
||||
from: string;
|
||||
to: string;
|
||||
reasonDiff?: string;
|
||||
};
|
||||
durationMs?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface RegressionTestResult {
|
||||
ok: boolean;
|
||||
verdict: "CLEAN" | "REGRESSIONS_DETECTED" | "DRY_RUN";
|
||||
safeToPublish: boolean;
|
||||
timestamp: string;
|
||||
sourceCorp: { id: string; name: string; environment: string };
|
||||
targetCorp: { id: string; name: string; environment: string };
|
||||
quota: {
|
||||
featureCode: string;
|
||||
balanceBefore: number;
|
||||
deductionAmount: number;
|
||||
estimatedRequired: number;
|
||||
balanceAfter?: number;
|
||||
};
|
||||
metrics: {
|
||||
sampleCount: number;
|
||||
successCount: number;
|
||||
failureCount: number;
|
||||
matchCount: number;
|
||||
flipCount: number;
|
||||
concordanceRate: number;
|
||||
};
|
||||
flips: RegressionSampleRecord[];
|
||||
records: RegressionSampleRecord[];
|
||||
}
|
||||
|
||||
function normalizeDecision(val: unknown): string {
|
||||
if (typeof val !== "string" || !val.trim()) return "UNKNOWN";
|
||||
const upper = val.toUpperCase().trim();
|
||||
if (upper === "APPROVE" || upper === "PASS") return "APPROVE";
|
||||
if (upper === "REJECT" || upper === "DENIED") return "REJECT";
|
||||
if (upper === "MANUAL" || upper === "ASSISTED") return "MANUAL";
|
||||
if (upper === "ERROR" || upper === "FAILED") return "ERROR";
|
||||
return upper;
|
||||
}
|
||||
|
||||
export async function runRegressionTest(
|
||||
options: RegressionTestOptions
|
||||
): Promise<RegressionTestResult> {
|
||||
const {
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
sourceClient,
|
||||
targetClient,
|
||||
samples = 10,
|
||||
dryRun = false,
|
||||
pollIntervalMs = 2000,
|
||||
timeoutMs = 45000,
|
||||
snPrefix = "REG_",
|
||||
fetchFn = fetch
|
||||
} = options;
|
||||
|
||||
// 1. Red Line 1: Enterprise Isolation Guard
|
||||
if (targetCorp.environment !== "test") {
|
||||
throw new CliError(
|
||||
`重放目标企业「${targetCorp.name}」(${targetCorp.id}) 的环境为「${targetCorp.environment}」,非测试环境!\n` +
|
||||
`硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。`,
|
||||
2,
|
||||
`seal-use corps bind-test ${sourceCorp.id} <testCorpId>`
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Red Line 2: Quota Pre-Flight Check
|
||||
const billing = await api.getBillingStatus(targetClient);
|
||||
const features = Array.isArray(billing.features) ? billing.features : [];
|
||||
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
|
||||
|
||||
const balance = typeof aiApproval?.balance === "number" ? aiApproval.balance : 0;
|
||||
const deductionAmount =
|
||||
typeof aiApproval?.deductionAmount === "number" && aiApproval.deductionAmount > 0
|
||||
? aiApproval.deductionAmount
|
||||
: 120;
|
||||
const estimatedRequired = samples * deductionAmount;
|
||||
|
||||
if (balance < estimatedRequired) {
|
||||
throw new CliError(
|
||||
`测试企业「${targetCorp.name}」AI 审批额度不足:当前剩余 ${balance} 点,本次回归抽样 ${samples} 笔需要约 ${estimatedRequired} 点。\n` +
|
||||
`为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。`,
|
||||
2,
|
||||
`请为测试企业「${targetCorp.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1, Math.floor(balance / deductionAmount))})`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Extract Historical Production Samples
|
||||
const runsResponse = await api.listApprovalRuns(sourceClient, {
|
||||
limit: samples,
|
||||
status: "completed"
|
||||
});
|
||||
|
||||
let sourceRuns = Array.isArray(runsResponse.records) ? runsResponse.records : [];
|
||||
if (sourceRuns.length === 0) {
|
||||
// Fall back to any status if completed is empty
|
||||
const fallbackResponse = await api.listApprovalRuns(sourceClient, { limit: samples });
|
||||
sourceRuns = Array.isArray(fallbackResponse.records) ? fallbackResponse.records : [];
|
||||
}
|
||||
|
||||
if (sourceRuns.length === 0) {
|
||||
throw new CliError(
|
||||
`在母企业「${sourceCorp.name}」(${sourceCorp.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
// Slice to requested samples
|
||||
sourceRuns = sourceRuns.slice(0, samples);
|
||||
|
||||
// Dry-run mode: return preview without network mutation
|
||||
if (dryRun) {
|
||||
const dryRunRecords: RegressionSampleRecord[] = sourceRuns.map((r) => {
|
||||
const sn = r.sourceDocumentSN ?? r.id;
|
||||
const rawDecision = (r as any)?.result?.decision ?? r.aiDecision ?? (r as any)?.decision;
|
||||
const decision = normalizeDecision(rawDecision);
|
||||
const prodSummary = (r as any)?.result?.summary ?? r.aiSummary;
|
||||
return {
|
||||
sn,
|
||||
sourceRecordId: r.id,
|
||||
prodDecision: decision,
|
||||
prodSummary,
|
||||
status: "DRY_RUN"
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
verdict: "DRY_RUN",
|
||||
safeToPublish: true,
|
||||
timestamp: new Date().toISOString(),
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment ?? "production" },
|
||||
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment ?? "test" },
|
||||
quota: {
|
||||
featureCode: "ai-approval",
|
||||
balanceBefore: balance,
|
||||
deductionAmount,
|
||||
estimatedRequired
|
||||
},
|
||||
metrics: {
|
||||
sampleCount: dryRunRecords.length,
|
||||
successCount: dryRunRecords.length,
|
||||
failureCount: 0,
|
||||
matchCount: dryRunRecords.length,
|
||||
flipCount: 0,
|
||||
concordanceRate: 1.0
|
||||
},
|
||||
flips: [],
|
||||
records: dryRunRecords
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Resolve Target Webhook Channel in Test Corp
|
||||
const targetWebhook = await ensureTestWebhookIntegration(targetClient, targetCorp);
|
||||
|
||||
// 5. Execute Batch Replay & HTTPS Run Polling
|
||||
const records: RegressionSampleRecord[] = [];
|
||||
|
||||
for (const sourceSummaryRun of sourceRuns) {
|
||||
const startTime = Date.now();
|
||||
const originalSN = sourceSummaryRun.sourceDocumentSN ?? sourceSummaryRun.id;
|
||||
const prodDecision = normalizeDecision(
|
||||
(sourceSummaryRun as any)?.result?.decision ??
|
||||
sourceSummaryRun.aiDecision ??
|
||||
(sourceSummaryRun as any)?.decision
|
||||
);
|
||||
const prodSummary = (sourceSummaryRun as any)?.result?.summary ?? sourceSummaryRun.aiSummary;
|
||||
|
||||
try {
|
||||
// Fetch full source run details with document fields
|
||||
const fullSourceRun = await api.getApprovalRun(sourceClient, sourceSummaryRun.id);
|
||||
|
||||
// Reconstruct clean webhook document payload
|
||||
const replayedSN = `${snPrefix}${originalSN}`;
|
||||
const webhookDoc = transformApprovalRunToWebhookDocument(fullSourceRun, {
|
||||
snPrefix,
|
||||
docIdPrefix: snPrefix
|
||||
});
|
||||
|
||||
// Push into target test enterprise webhook
|
||||
await pushWebhookDocument(
|
||||
targetWebhook.incomingDocumentWebhook.url,
|
||||
targetWebhook.secret,
|
||||
webhookDoc,
|
||||
fetchFn,
|
||||
resolveSealCustomHeaders(targetCorp.seal)
|
||||
);
|
||||
|
||||
// Poll target enterprise for completion
|
||||
let testRun: ApprovalRun | null = null;
|
||||
const pollStart = Date.now();
|
||||
|
||||
while (Date.now() - pollStart < timeoutMs) {
|
||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||
|
||||
const searchRes = await api.listApprovalRuns(targetClient, {
|
||||
sourceDocumentSN: replayedSN,
|
||||
limit: 1
|
||||
});
|
||||
|
||||
if (searchRes.records && searchRes.records.length > 0) {
|
||||
const candidate = searchRes.records[0]!;
|
||||
if (candidate.status === "completed" || candidate.status === "failed") {
|
||||
testRun = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!testRun) {
|
||||
records.push({
|
||||
sn: originalSN,
|
||||
sourceRecordId: sourceSummaryRun.id,
|
||||
prodDecision,
|
||||
prodSummary,
|
||||
status: "FAILED",
|
||||
error: `测试租户单据审核超时 (${Math.round(timeoutMs / 1000)}s 未完成)`,
|
||||
durationMs: Date.now() - startTime
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const testDecision = normalizeDecision(
|
||||
(testRun as any)?.result?.decision ??
|
||||
testRun.aiDecision ??
|
||||
(testRun as any)?.decision ??
|
||||
(testRun.status === "completed" ? "APPROVE" : "ERROR")
|
||||
);
|
||||
const testSummary = (testRun as any)?.result?.summary ?? testRun.aiSummary;
|
||||
|
||||
const isMatched = prodDecision === testDecision;
|
||||
const sampleStatus: "MATCHED" | "FLIPPED" = isMatched ? "MATCHED" : "FLIPPED";
|
||||
|
||||
const recordItem: RegressionSampleRecord = {
|
||||
sn: originalSN,
|
||||
sourceRecordId: sourceSummaryRun.id,
|
||||
prodDecision,
|
||||
prodSummary,
|
||||
testRecordId: testRun.id,
|
||||
testDecision,
|
||||
testSummary,
|
||||
status: sampleStatus,
|
||||
durationMs: Date.now() - startTime
|
||||
};
|
||||
|
||||
if (!isMatched) {
|
||||
recordItem.diff = {
|
||||
from: prodDecision,
|
||||
to: testDecision,
|
||||
reasonDiff: testSummary && prodSummary && testSummary !== prodSummary
|
||||
? `生产: ${prodSummary.slice(0, 60)}... -> 测试: ${testSummary.slice(0, 60)}...`
|
||||
: undefined
|
||||
};
|
||||
}
|
||||
|
||||
records.push(recordItem);
|
||||
} catch (err) {
|
||||
records.push({
|
||||
sn: originalSN,
|
||||
sourceRecordId: sourceSummaryRun.id,
|
||||
prodDecision,
|
||||
prodSummary,
|
||||
status: "FAILED",
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
durationMs: Date.now() - startTime
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Aggregate Metrics & Verdict
|
||||
const successRecords = records.filter((r) => r.status === "MATCHED" || r.status === "FLIPPED");
|
||||
const matchRecords = records.filter((r) => r.status === "MATCHED");
|
||||
const flipRecords = records.filter((r) => r.status === "FLIPPED");
|
||||
const failureCount = records.filter((r) => r.status === "FAILED").length;
|
||||
|
||||
const matchCount = matchRecords.length;
|
||||
const flipCount = flipRecords.length;
|
||||
const totalEvaluated = matchCount + flipCount;
|
||||
const concordanceRate = totalEvaluated > 0 ? matchCount / totalEvaluated : 0;
|
||||
|
||||
const hasRegressions = flipCount > 0;
|
||||
const verdict: "CLEAN" | "REGRESSIONS_DETECTED" = hasRegressions ? "REGRESSIONS_DETECTED" : "CLEAN";
|
||||
const safeToPublish = !hasRegressions && failureCount === 0;
|
||||
|
||||
// Post-check remaining balance if possible
|
||||
let balanceAfter: number | undefined;
|
||||
try {
|
||||
const postBilling = await api.getBillingStatus(targetClient);
|
||||
const postFeatures = Array.isArray(postBilling.features) ? postBilling.features : [];
|
||||
const postAi = postFeatures.find((f: any) => f?.code === "ai-approval");
|
||||
if (typeof postAi?.balance === "number") {
|
||||
balanceAfter = postAi.balance;
|
||||
}
|
||||
} catch {
|
||||
// optional post-check
|
||||
}
|
||||
|
||||
return {
|
||||
ok: !hasRegressions && failureCount === 0,
|
||||
verdict,
|
||||
safeToPublish,
|
||||
timestamp: new Date().toISOString(),
|
||||
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment ?? "production" },
|
||||
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment ?? "test" },
|
||||
quota: {
|
||||
featureCode: "ai-approval",
|
||||
balanceBefore: balance,
|
||||
deductionAmount,
|
||||
estimatedRequired,
|
||||
balanceAfter
|
||||
},
|
||||
metrics: {
|
||||
sampleCount: records.length,
|
||||
successCount: successRecords.length,
|
||||
failureCount,
|
||||
matchCount,
|
||||
flipCount,
|
||||
concordanceRate: Number(concordanceRate.toFixed(4))
|
||||
},
|
||||
flips: flipRecords,
|
||||
records
|
||||
};
|
||||
}
|
||||
|
||||
export function formatRegressionDashboard(result: RegressionTestResult): string {
|
||||
const { sourceCorp, targetCorp, verdict, safeToPublish, metrics, quota, flips, records } = result;
|
||||
|
||||
const verdictBadge =
|
||||
verdict === "CLEAN"
|
||||
? "🟢 决策完全一致 (CLEAN - 无回归)"
|
||||
: verdict === "DRY_RUN"
|
||||
? "⚪ 预演模式 (DRY-RUN)"
|
||||
: "🔴 发现决策翻转 (REGRESSIONS_DETECTED)";
|
||||
|
||||
const lines: string[] = [
|
||||
"",
|
||||
`🧪 [Seal Use Test] 规则回归测试矩阵: 生产「${sourceCorp.name}」-> 测试靶场「${targetCorp.name}」`,
|
||||
` 判定: ${verdictBadge} · 准许发布: ${safeToPublish ? "YES (可安全上线)" : "NO (存在行为偏离/待复核)"}`,
|
||||
" " + "─".repeat(65),
|
||||
` 样本总数: ${metrics.sampleCount} | 一致通过: ${metrics.matchCount} | 决策翻转: ${metrics.flipCount} | 异常失败: ${metrics.failureCount}`,
|
||||
` 一致率: ${(metrics.concordanceRate * 100).toFixed(1)}% | 消耗预估: ${quota.estimatedRequired} 点 (余量: ${quota.balanceBefore}${quota.balanceAfter !== undefined ? ` -> ${quota.balanceAfter}` : ""})`,
|
||||
" " + "─".repeat(65)
|
||||
];
|
||||
|
||||
if (flips.length > 0) {
|
||||
lines.push(` ⚠️ 决策翻转清单 (${flips.length} 笔单据在新规则下结果改变):`);
|
||||
for (const flip of flips) {
|
||||
lines.push(` • 单据 [${flip.sn}]: 原生产判定「${flip.prodDecision}」 ➔ 测试新判定「${flip.testDecision}」`);
|
||||
if (flip.diff?.reasonDiff) {
|
||||
lines.push(` 理由差异: ${flip.diff.reasonDiff}`);
|
||||
}
|
||||
}
|
||||
lines.push(" " + "─".repeat(65));
|
||||
lines.push(" 👉 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。");
|
||||
} else if (verdict === "CLEAN") {
|
||||
lines.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% 吻合,无任何意外误杀或漏判。");
|
||||
lines.push(` 👉 下一步操作: seal-use deploy hosecloud sync <signKey> 或发布正式版本`);
|
||||
}
|
||||
|
||||
lines.push("");
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -290,7 +290,8 @@ export async function ensureTestWebhookIntegration(
|
||||
corp: CorpConfig,
|
||||
selector?: string
|
||||
): Promise<WebhookIntegration> {
|
||||
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
|
||||
const endpoint = corp.seal?.endpoints?.approvalStylePreferences ?? "api/v1/agent/ai-approval/config";
|
||||
const integrations = await api.listWebhookIntegrations(client, endpoint);
|
||||
if (selector || integrations.length > 0) {
|
||||
return selectWebhookIntegration(integrations, selector, corp.id);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user