Merge pull request #257 from yunyingk/mac15/approval-extra-risk

Add approval record extra risk filtering
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-22 12:36:35 +08:00
commit 6d310ba945
10 files changed
+290 -6

No files matched your search

@@ -16,6 +16,31 @@ Default output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDo
If there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.
## Find Runs With Extra Risks
审核结果区分 `result.rulesResult[].findings`(绑定规则的检查发现)与 `result.otherFindings[]`(额外发现)。额外发现中的 `warning` / `error` 计为额外风险,`info` 仅为提示;不根据最终审批结论或摘要文本推断额外风险。
前端将规则内发现映射为 `source: "rule"`,额外发现映射为 `source: "system"` 并标注“系统检测”。这是展示层根据字段来源派生的分类,不是当前审核列表接口已接入的筛选参数。“系统检测”也可能是 `info`,因此不能将全部系统检测项都计为风险。原始等级枚举为 `info / warning / error`;页面的“需复核”还可能由规则的 `UNCERTAIN` 结论派生。
```bash
# 从最近一页 100 条记录中筛出含额外风险的记录
seal-use approval-runs list --has-extra-risk --limit 100 --corp <corpId>
# 在时间、运行状态、人工结果等条件下筛选
seal-use approval-runs search --has-extra-risk --status completed --startDate 2026-10-01 --endDate 2026-10-22 --limit 100 --corp <corpId>
# 继续检查下一页;offset 按上游记录数推进,不按 matched 推进
seal-use approval-runs list --has-extra-risk --limit 100 --offset 100 --corp <corpId>
```
- `limit` 是筛选前读取的页大小(默认 50,最多 100),不会为凑满命中数自动翻页。`offset` 同样作用于上游结果集。
- `scanned` 是本页上游返回的条数,`matched` 是所有本地筛选后的返回条数。`total` 保留上游筛选条件下的记录总数,**不是额外风险单据总数**。
- 启用筛选时,`unknown` 是通过其他本地条件后,因结果缺失或格式异常而无法判断额外风险的条数。这些记录不混入命中列表;无筛选读取时,可通过 `extraFindingsStatus: "unknown"` 定位。
- 记录摘要包含 `otherFindingCount`(含 info 的额外发现总数)、`extraRiskCount`、`hasExtraRisk`、`extraFindingsStatus`。空数组表示已知无额外发现;缺失/异常数据的数量和布尔值为 `null`。
- 本筛选读取结构化的 `otherFindings`。前端还会转换旧版结果中的 `otherRisks` 等字段,但本筛选不推断旧版关联关系;未提供 `otherFindings` 的历史记录计为 `unknown`。
- 启用筛选时,每条命中记录附带 `extraRisks`,含风险标题、等级和描述。一次审核可能有多个风险,`matched` 按审核记录计数;同一单据多次审核也可能返回多条记录。
- `approval-runs result <recordId> --summary` 和 `get <recordId> --summary` 的 AI 结果也返回上述计数字段。查看全部额外发现可用 `get <recordId> --fields result.otherFindings`。
## Read Compact Run Detail
Use `--summary` for most diagnosis and support questions.
+1 -1
View File
@@ -98,7 +98,7 @@ seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sou
seal-use approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--corp <corpId>]
seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]
seal-use approval-runs hose-flow <recordId|SN> [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
+139
View File
@@ -0,0 +1,139 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_DISABLE_BG_UPDATE"] as const
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let requests: Request[]
const fixtures = [
{ id: "warning", result: { decision: "APPROVE", otherFindings: [
{ title: "说明", description: "仅说明", level: "info" },
{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }
] } },
{ id: "error", result: { decision: "REJECT", otherFindings: [{ title: "金额差异", description: "金额不一致", level: "error" }] } },
{ id: "info", result: { otherFindings: [{ title: "说明", description: "无需处理", level: "info" }] } },
{ id: "rule-only", result: { rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }], otherFindings: [] } },
{ id: "missing", result: {} },
{ id: "malformed", result: { otherFindings: "bad" } }
].map((record, index) => ({
...record, sourceDocumentSN: `SN-${index}`, status: "completed", createdAt: 1792639007830 - index,
pipelineData: { humanResult: index === 0 ? "驳回" : "通过" },
sourceExtendData: { _langfuseTraceId: `trace-${index}` }
}))
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-extra-risk-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
process.env.SEAL_DISABLE_BG_UPDATE = "1"
writeFileSync(join(enterprises, "extra-risk-test.json"), JSON.stringify({
id: "extra-risk-test", name: "Extra Risk Test", environment: "test",
seal: { url: "https://extra-risk.example.test" },
source: { type: "seal", token: "test-token", sealUrl: "https://extra-risk.example.test", staffId: "fixture" }
}))
requests = []
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
requests.push(request)
const url = new URL(request.url)
if (request.method !== "GET") return Response.json({ error: "unexpected mutation" }, { status: 405 })
if (url.pathname === "/api/v1/approvals") {
const offset = Number(url.searchParams.get("offset") ?? 0)
const limit = Number(url.searchParams.get("limit") ?? 50)
return Response.json({ data: { records: fixtures.slice(offset, offset + limit), total: 1000 } })
}
const record = fixtures.find(item => url.pathname === `/api/v1/approvals/${item.id}`)
return record ? Response.json({ data: record }) : Response.json({ error: "unexpected read" }, { status: 404 })
}) as typeof fetch
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
else process.env[key] = oldEnv[key]
}
globalThis.fetch = oldFetch
rmSync(dir, { recursive: true, force: true })
})
function cli(...argv: string[]) { return runCli(["approval-runs", ...argv, "--corp", "extra-risk-test"]) }
describe("approval run extra risk CLI", () => {
test("filters the fetched page, preserves upstream totals and aligns bridge to matches", async () => {
const response = await cli("list", "--has-extra-risk", "--limit", "100", "--includeBridge")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 2, unknown: 2, total: 1000 })
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning", "error"])
expect(data.records[0]).toMatchObject({
otherFindingCount: 2, extraRiskCount: 1, hasExtraRisk: true, extraFindingsStatus: "known",
extraRisks: [{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }]
})
expect(data.bridge).toHaveLength(2)
expect(requests).toHaveLength(1)
const url = new URL(requests[0]!.url)
expect(url.searchParams.get("limit")).toBe("100")
expect(url.searchParams.has("hasExtraRisk")).toBe(false)
expect(requests.every(request => request.method === "GET")).toBe(true)
})
test("limit and offset apply before filtering without fetching more pages", async () => {
const response = await cli("search", "--has-extra-risk", "--limit", "2", "--offset", "2")
expect(response.exitCode).toBe(0)
expect(JSON.parse(response.stdout)).toMatchObject({ scanned: 2, matched: 0, unknown: 0, total: 1000, records: [] })
expect(requests).toHaveLength(1)
expect(new URL(requests[0]!.url).searchParams.get("offset")).toBe("2")
})
test("combines with human-result filtering and forwards time and status conditions", async () => {
const response = await cli("search", "--has-extra-risk", "--humanResult", "驳回", "--status", "completed", "--startDate", "2026-10-01", "--endDate", "2026-10-22")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 1, unknown: 0 })
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning"])
const params = new URL(requests[0]!.url).searchParams
expect(params.get("status[0]")).toBe("completed")
expect(params.get("manualApprovalStatus[0]")).toBe("TERMINATED")
expect(params.get("startDate")).toBe(String(Date.parse("2026-10-01T00:00:00+08:00")))
expect(params.get("endDate")).toBe(String(Date.parse("2026-10-22T23:59:59.999+08:00")))
})
test("unfiltered lists preserve unknown and negative records with compact counts", async () => {
const response = await cli("list")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 6, total: 1000 })
expect(data).not.toHaveProperty("unknown")
expect(data.records[2]).toMatchObject({ otherFindingCount: 1, extraRiskCount: 0, hasExtraRisk: false })
expect(data.records[3]).toMatchObject({ otherFindingCount: 0, extraRiskCount: 0, hasExtraRisk: false })
expect(data.records[4]).toMatchObject({ extraFindingsStatus: "unknown", otherFindingCount: null, extraRiskCount: null, hasExtraRisk: null })
expect(data.records[0]).not.toHaveProperty("extraRisks")
})
test("result and detail summaries expose extra risk counts without replacing existing counts", async () => {
const result = await cli("result", "warning", "--summary")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ decision: "APPROVE", extraRiskCount: 1, otherFindingCount: 2, hasExtraRisk: true })
const detail = await cli("get", "warning", "--summary")
expect(detail.exitCode).toBe(0)
expect(JSON.parse(detail.stdout).aiResult).toMatchObject({ extraRiskCount: 1, hasExtraRisk: true })
})
test("supports the camelCase alias and explicit false without filtering", async () => {
const filtered = await cli("list", "--hasExtraRisk")
expect(filtered.exitCode).toBe(0)
expect(JSON.parse(filtered.stdout).matched).toBe(2)
const unfiltered = await cli("list", "--has-extra-risk=false")
expect(unfiltered.exitCode).toBe(0)
expect(JSON.parse(unfiltered.stdout).matched).toBe(6)
})
})
+1
View File
@@ -125,6 +125,7 @@ export async function handleApprovalRunsCommand(
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId),
humanResult: stringOption(args.options.humanResult),
hasExtraRisk: booleanOption(args.options["has-extra-risk"]) ?? booleanOption(args.options.hasExtraRisk),
query: stringOption(args.options.query),
includeBridge: booleanOption(args.options.includeBridge)
},
+6 -1
View File
@@ -515,7 +515,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "list",
aliases: ["search"],
summary: "Search approval records by keyword, dates, or decision status",
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]"]
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]"],
options: [
{ flag: "--has-extra-risk", description: "Filter the fetched page to records with warning/error in result.otherFindings; info is excluded. Includes extraRisks with titles, levels and descriptions." },
{ flag: "--limit <n>", description: "Records to scan before local filtering (default 50, maximum 100); no automatic pagination to fill matches" },
{ flag: "--offset <n>", description: "Offset in the upstream result set before local filtering" }
]
},
{
name: "pick",
+1 -1
View File
@@ -29,7 +29,7 @@ export const BOOLEAN_FLAGS = new Set([
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
@@ -0,0 +1,54 @@
import { describe, expect, test } from "bun:test"
import { summarizeExtraFindings } from "./extra-findings.js"
describe("extra findings", () => {
test("counts warning/error separately from info and ignores rule-bound findings", () => {
const summary = summarizeExtraFindings({
id: "run-1",
result: {
decision: "APPROVE",
rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }],
otherFindings: [
{ title: "说明", description: "仅作说明", level: "info" },
{ title: "待核实", description: "凭证主体不同", level: "warning", location: { scope: "FORM", refId: "" } },
{ title: "异常", description: "金额不符", level: "error" }
]
}
}, true)
expect(summary).toEqual({
extraFindingsStatus: "known", otherFindingCount: 3, extraRiskCount: 2, hasExtraRisk: true,
extraRisks: [
{ title: "待核实", description: "凭证主体不同", level: "warning" },
{ title: "异常", description: "金额不符", level: "error" }
]
})
})
test("empty arrays and info-only findings are known negatives regardless of decision", () => {
for (const otherFindings of [[], [{ title: "说明", description: "无需处理", level: "info" }]]) {
expect(summarizeExtraFindings({ id: "run", result: { decision: "REJECT", otherFindings } }, true)).toEqual({
extraFindingsStatus: "known", otherFindingCount: otherFindings.length,
extraRiskCount: 0, hasExtraRisk: false, extraRisks: []
})
}
})
test("missing, unsupported and partially malformed results remain unknown", () => {
for (const result of [
undefined, null, "{}", [], {}, { riskPoints: ["风险"] },
{ otherFindings: null }, { otherFindings: {} }, { otherFindings: [null] },
{ otherFindings: [{ title: "标题", description: "内容", level: "critical" }] },
{ otherFindings: [{ level: "warning" }] },
{ otherFindings: [{ title: "标题", description: "内容", level: "warning" }, "bad"] }
]) {
expect(summarizeExtraFindings({ id: "run", result }, true)).toEqual({
extraFindingsStatus: "unknown", otherFindingCount: null,
extraRiskCount: null, hasExtraRisk: null, extraRisks: null
})
}
})
test("default summaries omit risk detail", () => {
expect(summarizeExtraFindings({ id: "run", result: { otherFindings: [] } })).not.toHaveProperty("extraRisks")
})
})
@@ -0,0 +1,46 @@
import { z } from "zod"
import type { ApprovalRun } from "../types.js"
const extraFindingSchema = z.object({
title: z.string(),
description: z.string(),
level: z.enum(["info", "warning", "error"])
})
const extraFindingsSchema = z.array(extraFindingSchema)
export type ExtraRisk = z.infer<typeof extraFindingSchema>
export type ExtraFindingsSummary = {
extraFindingsStatus: "known" | "unknown";
otherFindingCount: number | null;
extraRiskCount: number | null;
hasExtraRisk: boolean | null;
extraRisks?: ExtraRisk[] | null;
}
/** Only otherFindings classifies rule-independent discoveries; missing data is not a negative. */
export function summarizeExtraFindings(record: ApprovalRun, includeRisks = false): ExtraFindingsSummary {
const result = record.result
const raw = result && typeof result === "object" && !Array.isArray(result)
? (result as Record<string, unknown>).otherFindings
: undefined
const parsed = extraFindingsSchema.safeParse(raw)
if (!parsed.success) {
return {
extraFindingsStatus: "unknown",
otherFindingCount: null,
extraRiskCount: null,
hasExtraRisk: null,
...(includeRisks ? { extraRisks: null } : {})
}
}
const risks = parsed.data.filter(finding => finding.level === "warning" || finding.level === "error")
return {
extraFindingsStatus: "known",
otherFindingCount: parsed.data.length,
extraRiskCount: risks.length,
hasExtraRisk: risks.length > 0,
...(includeRisks ? { extraRisks: risks } : {})
}
}
+13 -2
View File
@@ -6,6 +6,7 @@ import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
import { summarizeExtraFindings } from "../approval-runs/extra-findings.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
@@ -64,6 +65,7 @@ export const approvalRunsCapabilities = [
sourceDocumentSN: z.string().optional(),
sourceDocumentId: z.string().optional(),
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
hasExtraRisk: z.boolean().optional().describe("读取当前页后筛选 otherFindings 含 warning/error 的记录;limit 是扫描条数,缺失或异常结果计入 unknown"),
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配"),
includeBridge: z.boolean().optional().describe("是否返回完整 bridge 数组;默认 false,避免长输出")
}),
@@ -82,6 +84,7 @@ export const approvalRunsCapabilities = [
sourceDocumentSN?: string;
sourceDocumentId?: string;
humanResult?: string;
hasExtraRisk?: boolean;
query?: string;
includeBridge?: boolean;
}
@@ -93,13 +96,21 @@ export const approvalRunsCapabilities = [
endDate: normalizeTimestamp(params.endDate, true),
search: query
}));
const records = await prepareApprovalRuns(client, data.records, {
const prepared = await prepareApprovalRuns(client, data.records, {
humanResult: params.humanResult
});
const analyzed = prepared.map(record => ({ record, findings: summarizeExtraFindings(record, params.hasExtraRisk === true) }));
const selected = params.hasExtraRisk
? analyzed.filter(({ findings }) => findings.hasExtraRisk === true)
: analyzed;
const records = selected.map(({ record }) => record);
return {
...data,
records: records.map(summarizeApprovalRun),
scanned: data.records.length,
matched: records.length,
...(params.hasExtraRisk ? { unknown: analyzed.filter(({ findings }) => findings.extraFindingsStatus === "unknown").length } : {}),
records: selected.map(({ record, findings }) => ({ ...summarizeApprovalRun(record), ...findings })),
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
};
}
+4 -1
View File
@@ -24,6 +24,7 @@ import type {
WebhookIntegration
} from "../types.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import { summarizeExtraFindings, type ExtraFindingsSummary } from "../approval-runs/extra-findings.js";
import type { LocalRuleItem } from "../rules/local.js";
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
@@ -55,7 +56,7 @@ export function getConfiguredSealBaseUrl(corp: CorpConfig): string {
return corp.source.sealUrl;
}
export type ApprovalRunSummary = {
export type ApprovalRunSummary = ExtraFindingsSummary & {
id: string;
tenantId?: string;
agentId?: string;
@@ -500,6 +501,7 @@ export function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
humanResultPath: humanResult?.path,
aiDecision: ai.decision,
aiSummary: ai.summary,
...summarizeExtraFindings(record),
createdAt: record.createdAt,
updatedAt: record.updatedAt
};
@@ -596,6 +598,7 @@ export function summarizeApprovalRunDetail(record: ApprovalRun) {
export function summarizeApprovalRunResult(record: ApprovalRun) {
const result = asRecord(record.result);
return {
...summarizeExtraFindings(record),
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,