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
@@ -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