Merge pull request #48 from yunyingk/feat/configurable-approval-gateway

feat(approval): introduce configurable gateway policy script and enforce strict reject/approve guardrails
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-07 14:04:52 +08:00
commit 1b5ae12254
6 files changed
+698 -98

No files matched your search

+36
View File
@@ -112,4 +112,40 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
expect(actions).toContain("review");
expect(actions).toContain("decide");
});
test("门禁防御:单据无硬性或弹性违规时,尝试执行 reject 必须被网关阻断(禁止无因驳回)", async () => {
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
const run = repo.createApprovalRun({
documentSn: "CLEAN-BILL-001",
corpId: "test-corp",
documentSnapshot: "# 正常单据快照",
});
const runId = run.shortId!;
// 挂载规则 1 并打标为全部 PASS
await runAiProCli(["bind", "--run", runId, "--rules", "[1]"]);
await runAiProCli([
"review",
"--run",
runId,
"--eval",
"1=PASS:发票已上传; 2=PASS:事由已补充",
]);
// 尝试在无违规情况下驳回,必须被网关拦截
const blockReject = await runAiProCli([
"decide",
"reject",
"--run",
runId,
"--opinion",
"单据完全合规但尝试无故驳回",
]);
expect(blockReject.exitCode).toBe(1);
expect(blockReject.stderr).toContain("不存在任何【硬性】或【弹性】违规条款");
expect(blockReject.stderr).toContain("严禁无故或恶意驳回");
});
});
+8 -23
View File
@@ -12,6 +12,7 @@ import {
CreateFindingInput,
RuleRecord,
parseRuleBody,
validateGatewayAction,
} from "./domains/approval/index.js";
import { getRawBillFlow } from "./domains/bill/api.js";
import { approveBill, rejectBill } from "./domains/bill/tools.js";
@@ -878,31 +879,15 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
throw new Error("必须提供小于 150 字的审批意见: --opinion '<审批意见>'");
}
if (opinion.length > 150) {
throw new Error(`[参数校验阻断] 审批意见不可超过 150 字符,当前长度为 ${opinion.length} 字符,请精简。`);
}
const findings = repo.getFindingsByRunId(runRecord.id);
if (findings.length === 0) {
throw new Error(`[网关安全阻断] 会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何规约审核要点,审批链路物理不通!请先执行 bind 挂载。`);
}
// 网关刚性阻拦检查(它只阻拦,不决断)
if (action === "APPROVE") {
// 门禁 1: 漏检拦截
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
if (pendingFindings.length > 0) {
const pendingIndices = pendingFindings.map((f) => `#${findings.indexOf(f) + 1}`).join(", ");
throw new Error(`[网关安全阻断] 尚有 ${pendingFindings.length} 处审核要点处于“待核验”状态(要点 ${pendingIndices}),禁止盲目放行同意!`);
}
// 门禁 2: 硬性一票否决
const hardFailed = findings.filter((f) => f.checkStatus === "FAIL" && f.strictness === "硬性");
if (hardFailed.length > 0) {
const failedNames = hardFailed.map((f) => `【#${findings.indexOf(f) + 1} ${f.clauseText}】`).join("、");
throw new Error(`[网关安全阻断] 单据存在硬性违规条款未通过(${failedNames}),物理切断“同意”流转,绝对禁止放行!`);
}
}
// 网关刚性安全门禁检查(统一由可配置网关 TS 策略执行:意见长度、待核验漏检、硬性违规禁止同意、无硬性/弹性违规禁止驳回)
validateGatewayAction({
documentSn: runRecord.documentSn,
findings,
requestedAction: action === "APPROVE" ? "approve" : "reject",
opinion,
});
// Apply execution
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
+285
View File
@@ -0,0 +1,285 @@
import { describe, expect, test } from "bun:test";
import {
analyzeFindings,
validateGatewayAction,
evaluateGatewayPolicy,
ApprovalGatewayPolicy,
GatewayPolicyConfig,
} from "./gateway.js";
import { ApprovalFindingRecord, ApprovalGatewayBlockedError } from "./types.js";
function makeFinding(partial: Partial<ApprovalFindingRecord>): ApprovalFindingRecord {
return {
id: crypto.randomUUID(),
runId: "test-run",
clauseText: partial.clauseText ?? "测试条款",
strictness: partial.strictness ?? "硬性",
checkStatus: partial.checkStatus ?? "PASS",
evidence: partial.evidence ?? null,
reasoning: partial.reasoning ?? null,
createdAt: Date.now(),
};
}
describe("Approval Gateway Policy - 可配置审批网关规则测试", () => {
// ── 1. 硬性违规场景 ────────────────────────────────────────────────────────
test("硬性违规:必须驳回,绝对禁止同意放行", () => {
const findings: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "FAIL", evidence: "无发票" }),
makeFinding({ clauseText: "建议填写出差事由", strictness: "建议", checkStatus: "PASS" }),
];
// 1.1 尝试 approve 必须被网关强力阻断
expect(() => {
validateGatewayAction({
documentSn: "DOC-001",
findings,
requestedAction: "approve",
opinion: "尝试放行",
});
}).toThrow(ApprovalGatewayBlockedError);
// 1.2 尝试 reject 可以正常放行
expect(() => {
validateGatewayAction({
documentSn: "DOC-001",
findings,
requestedAction: "reject",
opinion: "缺少发票予以驳回",
});
}).not.toThrow();
// 1.3 默认仲裁决断结果必须为 REJECT
const result = evaluateGatewayPolicy({
documentSn: "DOC-001",
findings,
});
expect(result.decision).toBe("REJECT");
expect(result.hardFailedCount).toBe(1);
expect(result.decisionSummary).toContain("触犯硬性刚性条款,决策锁定为【驳回】");
});
// ── 2. 零违规(全通过)场景 ────────────────────────────────────────────────
test("零违规:没有硬性或弹性违规不能驳回,必须同意放行", () => {
const findings: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "PASS" }),
makeFinding({ clauseText: "尽量上传付款水单", strictness: "弹性", checkStatus: "PASS" }),
makeFinding({ clauseText: "建议补充事由", strictness: "建议", checkStatus: "SKIP" }),
];
// 2.1 尝试 reject 必须被网关阻断(禁止无因驳回)
expect(() => {
validateGatewayAction({
documentSn: "DOC-002",
findings,
requestedAction: "reject",
opinion: "恶意驳回",
});
}).toThrow(ApprovalGatewayBlockedError);
try {
validateGatewayAction({
documentSn: "DOC-002",
findings,
requestedAction: "reject",
opinion: "恶意驳回",
});
} catch (err: any) {
expect(err.message).toContain("不存在任何【硬性】或【弹性】违规条款");
}
// 2.2 尝试 approve 正常放行
expect(() => {
validateGatewayAction({
documentSn: "DOC-002",
findings,
requestedAction: "approve",
opinion: "合规通过",
});
}).not.toThrow();
// 2.3 决策结果为 APPROVE
const result = evaluateGatewayPolicy({
documentSn: "DOC-002",
findings,
});
expect(result.decision).toBe("APPROVE");
expect(result.decisionSummary).toContain("决策锁定为【同意通过】");
});
// ── 3. 仅建议项违规场景 ────────────────────────────────────────────────────
test("仅建议项违规:不构成驳回理由,禁止驳回,决断为备注通过", () => {
const findings: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "必须上传真实发票", strictness: "硬性", checkStatus: "PASS" }),
makeFinding({ clauseText: "建议补充说明消费事由", strictness: "建议", checkStatus: "FAIL", evidence: "事由偏简略" }),
];
// 3.1 尝试驳回:建议项不能作为驳回理由,必须阻断
expect(() => {
validateGatewayAction({
documentSn: "DOC-003",
findings,
requestedAction: "reject",
opinion: "因事由简略驳回",
});
}).toThrow("建议项不构成驳回理由");
// 3.2 尝试同意:放行
expect(() => {
validateGatewayAction({
documentSn: "DOC-003",
findings,
requestedAction: "approve",
opinion: "备注事由后放行",
});
}).not.toThrow();
// 3.3 决断结果为 PASS_WITH_NOTE
const result = evaluateGatewayPolicy({
documentSn: "DOC-003",
findings,
});
expect(result.decision).toBe("PASS_WITH_NOTE");
expect(result.decisionSummary).toContain("决策锁定为【备注通过】");
});
// ── 4. 弹性违规场景 ────────────────────────────────────────────────────────
test("弹性违规:允许驳回;数量 <= 2 时为备注通过,>= 3 时建议人工复核", () => {
// 4.1 存在 1 项弹性违规
const findings1: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
makeFinding({ clauseText: "尽量上传水单", strictness: "弹性", checkStatus: "FAIL", evidence: "未提供水单" }),
];
// 因为有弹性违规,允许驳回
expect(() => {
validateGatewayAction({
documentSn: "DOC-004-1",
findings: findings1,
requestedAction: "reject",
opinion: "未提供水单予以驳回",
});
}).not.toThrow();
// 自动决断为 PASS_WITH_NOTE(弹性超标未达阈值)
const result1 = evaluateGatewayPolicy({
documentSn: "DOC-004-1",
findings: findings1,
});
expect(result1.decision).toBe("PASS_WITH_NOTE");
// 4.2 存在 3 项弹性违规(达到阈值)
const findings3: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
makeFinding({ clauseText: "尽量上传水单1", strictness: "弹性", checkStatus: "FAIL" }),
makeFinding({ clauseText: "尽量上传水单2", strictness: "弹性", checkStatus: "FAIL" }),
makeFinding({ clauseText: "尽量上传水单3", strictness: "弹性", checkStatus: "FAIL" }),
];
const result3 = evaluateGatewayPolicy({
documentSn: "DOC-004-3",
findings: findings3,
});
expect(result3.decision).toBe("REVIEW");
expect(result3.decisionSummary).toContain("建议人工复核");
});
// ── 5. 特殊项违规场景 ──────────────────────────────────────────────────────
test("特殊项命中:转人工复核,禁止直接驳回", () => {
const findings: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PASS" }),
makeFinding({ clauseText: "大额争议须法务审核", strictness: "特殊", checkStatus: "FAIL", evidence: "单据超10万" }),
];
expect(() => {
validateGatewayAction({
documentSn: "DOC-005",
findings,
requestedAction: "reject",
opinion: "法务未审直接驳回",
});
}).toThrow("特殊");
const result = evaluateGatewayPolicy({
documentSn: "DOC-005",
findings,
});
expect(result.decision).toBe("REVIEW");
});
// ── 6. 待核验(PENDING)漏检拦截 ───────────────────────────────────────────
test("待核验漏检保护:存在 PENDING 要点时,同意和驳回均被阻断", () => {
const findings: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "发票检查", strictness: "硬性", checkStatus: "PASS" }),
makeFinding({ clauseText: "住宿限额检查", strictness: "硬性", checkStatus: "PENDING" }),
];
// 同意被阻断
expect(() => {
validateGatewayAction({
documentSn: "DOC-006",
findings,
requestedAction: "approve",
opinion: "盲目同意",
});
}).toThrow("PENDING 待核验状态");
// 驳回也被阻断(必须先完成核验)
expect(() => {
validateGatewayAction({
documentSn: "DOC-006",
findings,
requestedAction: "reject",
opinion: "盲目驳回",
});
}).toThrow("PENDING 待核验状态");
});
// ── 7. 审批意见长度边角限制 ───────────────────────────────────────────────
test("审批意见长度控制:超过 150 字符时抛错阻断", () => {
const findings: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "发票检查", strictness: "硬性", checkStatus: "FAIL" }),
];
const overLength = "超长意见内容".repeat(35); // > 150 字
expect(() => {
validateGatewayAction({
documentSn: "DOC-007",
findings,
requestedAction: "reject",
opinion: overLength,
});
}).toThrow("不可超过 150 字符");
});
// ── 8. 自定义逻辑扩展钩子 (customHook) ────────────────────────────────────
test("支持配置自定义网关钩子覆盖或扩展逻辑", () => {
const findings: ApprovalFindingRecord[] = [
makeFinding({ clauseText: "普通合规检查", strictness: "建议", checkStatus: "PASS" }),
];
const policy = new ApprovalGatewayPolicy({
customHook: (context, analysis, config) => {
if (context.documentSn.startsWith("VIP-")) {
return {
decision: "APPROVE",
decisionSummary: "VIP 单据走免审专属绿色通道",
analysis,
hardFailedCount: 0,
elasticFailedCount: 0,
suggestFailedCount: 0,
specialFailedCount: 0,
};
}
},
});
const result = policy.evaluate({
documentSn: "VIP-88888",
findings,
});
expect(result.decision).toBe("APPROVE");
expect(result.decisionSummary).toBe("VIP 单据走免审专属绿色通道");
});
});
+334
View File
@@ -0,0 +1,334 @@
import {
ApprovalDecision,
ApprovalFindingRecord,
ApprovalGatewayBlockedError,
StrictnessTier,
} from "./types.js";
/**
* 审批仲裁网关策略配置接口
*/
export interface GatewayPolicyConfig {
/**
* 弹性违规项允许的最大数量。超过此数量自动转为建议人工复核 (默认: 2)
*/
maxElasticViolationsForPassWithNote: number;
/**
* 是否严格禁止在无硬性违规且无弹性违规时执行驳回 (默认: true)
* 业务铁律:没有硬性违反或弹性违反不能驳回,物理切断恶意/无故驳回分支
*/
blockRejectWithoutHardOrElasticFailure: boolean;
/**
* 是否在存在硬性违规时一票否决,物理切断同意分支 (默认: true)
* 业务铁律:有硬性违反必须驳回(或复核),绝对禁止放行同意
*/
blockApproveWithHardFailure: boolean;
/**
* 审批意见的最大字符数限制 (默认: 150)
*/
maxOpinionLength: number;
/**
* 可配置的自定义逻辑扩展钩子。
* 返回具体结果时直接作为最终裁决;返回 void 或 undefined 时继续执行标准裁决矩阵。
*/
customHook?: (
context: GatewayContext,
analysis: FindingsAnalysis,
config: GatewayPolicyConfig
) => GatewayDecisionResult | void;
}
/**
* 网关默认策略配置
*/
export const DEFAULT_GATEWAY_CONFIG: GatewayPolicyConfig = {
maxElasticViolationsForPassWithNote: 2,
blockRejectWithoutHardOrElasticFailure: true,
blockApproveWithHardFailure: true,
maxOpinionLength: 150,
};
/**
* 网关裁决输入上下文
*/
export interface GatewayContext {
documentSn: string;
findings: ApprovalFindingRecord[];
requestedAction?: "approve" | "reject" | "comment";
opinion?: string;
}
/**
* 要点事实核验分析结果
*/
export interface FindingsAnalysis {
allFindings: ApprovalFindingRecord[];
pendingFindings: ApprovalFindingRecord[];
passedFindings: ApprovalFindingRecord[];
failedFindings: ApprovalFindingRecord[];
skippedFindings: ApprovalFindingRecord[];
hardFailed: ApprovalFindingRecord[];
elasticFailed: ApprovalFindingRecord[];
suggestFailed: ApprovalFindingRecord[];
specialFailed: ApprovalFindingRecord[];
}
/**
* 网关综合判定结果
*/
export interface GatewayDecisionResult {
decision: ApprovalDecision;
decisionSummary: string;
analysis: FindingsAnalysis;
hardFailedCount: number;
elasticFailedCount: number;
suggestFailedCount: number;
specialFailedCount: number;
}
/**
* 分析审核要点状态与严格度分布
*/
export function analyzeFindings(findings: ApprovalFindingRecord[]): FindingsAnalysis {
const pendingFindings: ApprovalFindingRecord[] = [];
const passedFindings: ApprovalFindingRecord[] = [];
const failedFindings: ApprovalFindingRecord[] = [];
const skippedFindings: ApprovalFindingRecord[] = [];
const hardFailed: ApprovalFindingRecord[] = [];
const elasticFailed: ApprovalFindingRecord[] = [];
const suggestFailed: ApprovalFindingRecord[] = [];
const specialFailed: ApprovalFindingRecord[] = [];
for (const f of findings) {
if (f.checkStatus === "PENDING") {
pendingFindings.push(f);
} else if (f.checkStatus === "PASS") {
passedFindings.push(f);
} else if (f.checkStatus === "SKIP") {
skippedFindings.push(f);
} else if (f.checkStatus === "FAIL") {
failedFindings.push(f);
if (f.strictness === "硬性") {
hardFailed.push(f);
} else if (f.strictness === "弹性") {
elasticFailed.push(f);
} else if (f.strictness === "建议") {
suggestFailed.push(f);
} else if (f.strictness === "特殊") {
specialFailed.push(f);
}
}
}
return {
allFindings: findings,
pendingFindings,
passedFindings,
failedFindings,
skippedFindings,
hardFailed,
elasticFailed,
suggestFailed,
specialFailed,
};
}
/**
* 校验网关拟执行的动作是否合法(前置门禁防御)
*
* 包含核心卡点:
* 1. 空要点清单拦截:未注入要点前物理切断审批链路
* 2. 审批意见长度校验:超长直接拦截
* 3. 待核验拦截:存在 PENDING 要点时禁止提前决断
* 4. 硬性一票否决:有硬性违规绝对禁止同意放行
* 5. 无因驳回拦截:无硬性违规且无弹性违规时绝对禁止驳回
*
* @throws {ApprovalGatewayBlockedError} 当任一门禁被触发时抛出
*/
export function validateGatewayAction(
context: GatewayContext,
userConfig?: Partial<GatewayPolicyConfig>
): FindingsAnalysis {
const config = { ...DEFAULT_GATEWAY_CONFIG, ...userConfig };
// ── 门禁 1: 空要点清单拦截 ────────────────────────────────────────────────
if (!context.findings || context.findings.length === 0) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${context.documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
`请先执行: hose-aipro bind 挂载审核要点清单。`
);
}
// ── 门禁 2: 审批意见长度边角检查 ──────────────────────────────────────────
if (context.opinion && context.opinion.length > config.maxOpinionLength) {
throw new ApprovalGatewayBlockedError(
`[参数校验阻断] 审批意见不可超过 ${config.maxOpinionLength} 字符,当前长度为 ${context.opinion.length} 字符,请精简。`
);
}
// ── 门禁 3: 漏检拦截(存在待核验项)───────────────────────────────────────
const analysis = analyzeFindings(context.findings);
if (analysis.pendingFindings.length > 0) {
const pendingIndices = analysis.pendingFindings
.map((f) => `#${context.findings.indexOf(f) + 1} [${f.strictness}] ${f.clauseText}`)
.join(";");
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${context.documentSn}] 尚有 ${analysis.pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
`待核验项: ${pendingIndices}`
);
}
// ── 门禁 4: 硬性条款刚性底线(有硬性违规时绝对禁止同意)─────────────────
if (context.requestedAction === "approve" && config.blockApproveWithHardFailure && analysis.hardFailed.length > 0) {
const violatedNames = analysis.hardFailed
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
.join("、");
throw new ApprovalGatewayBlockedError(
`[网关强力阻断] 单据 [${context.documentSn}] 存在硬性违规条款未通过(${violatedNames})!\n` +
`网关物理切断“同意”流转,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
);
}
// ── 门禁 5: 无因驳回拦截(没有硬性或弹性违规不能驳回)────────────────────
if (
context.requestedAction === "reject" &&
config.blockRejectWithoutHardOrElasticFailure &&
analysis.hardFailed.length === 0 &&
analysis.elasticFailed.length === 0
) {
let detail = "单据所有核验要点均已通过";
if (analysis.suggestFailed.length > 0) {
const suggestNames = analysis.suggestFailed
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
.join("、");
detail = `单据仅存在倡导性的【建议】项未满足(${suggestNames}),建议项不构成驳回理由`;
} else if (analysis.specialFailed.length > 0) {
const specialNames = analysis.specialFailed
.map((f) => `【#${context.findings.indexOf(f) + 1} ${f.clauseText}】`)
.join("、");
detail = `单据命中【特殊】条款(${specialNames}),按规则须提交人工复核,不能直接驳回`;
}
throw new ApprovalGatewayBlockedError(
`[网关安全阻断] 单据 [${context.documentSn}] 不存在任何【硬性】或【弹性】违规条款(${detail})!\n` +
`网关物理切断驳回分支,严禁无故或恶意驳回!当前只允许执行同意 (approve) 或转人工复核。`
);
}
return analysis;
}
/**
* 确定性网关仲裁:执行所有校验并计算最终决策结果与审查报告
*/
export function evaluateGatewayPolicy(
context: GatewayContext,
userConfig?: Partial<GatewayPolicyConfig>
): GatewayDecisionResult {
const config = { ...DEFAULT_GATEWAY_CONFIG, ...userConfig };
// 1. 前置动作合法性校验(拦截非法同意、非法驳回、未闭环核验等)
const analysis = validateGatewayAction(context, config);
// 2. 优先执行用户自定义逻辑钩子
if (config.customHook) {
const customResult = config.customHook(context, analysis, config);
if (customResult) {
return customResult;
}
}
// 3. 执行标准确定性裁决矩阵
let decision: ApprovalDecision;
if (analysis.hardFailed.length > 0) {
decision = "REJECT";
} else if (analysis.specialFailed.length > 0) {
decision = "REVIEW";
} else if (analysis.elasticFailed.length > 0) {
decision =
analysis.elasticFailed.length > config.maxElasticViolationsForPassWithNote
? "REVIEW"
: "PASS_WITH_NOTE";
} else if (analysis.suggestFailed.length > 0) {
decision = "PASS_WITH_NOTE";
} else {
decision = "APPROVE";
}
// 4. 组装格式化合规审查报告
const summaryLines: string[] = [];
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
summaryLines.push(`单号: ${context.documentSn} | 审核要点总数: ${context.findings.length} 项`);
summaryLines.push(``);
summaryLines.push(`[逐项核验事实]`);
context.findings.forEach((f, idx) => {
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
});
summaryLines.push(``);
if (decision === "REJECT") {
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
} else if (decision === "REVIEW") {
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
} else if (decision === "PASS_WITH_NOTE") {
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
} else {
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
}
if (context.opinion) {
summaryLines.push(`[审批附加说明] ${context.opinion}`);
}
const decisionSummary = summaryLines.join("\n");
return {
decision,
decisionSummary,
analysis,
hardFailedCount: analysis.hardFailed.length,
elasticFailedCount: analysis.elasticFailed.length,
suggestFailedCount: analysis.suggestFailed.length,
specialFailedCount: analysis.specialFailed.length,
};
}
/**
* 可配置的审批仲裁网关策略类
*/
export class ApprovalGatewayPolicy {
private config: GatewayPolicyConfig;
constructor(config?: Partial<GatewayPolicyConfig>) {
this.config = { ...DEFAULT_GATEWAY_CONFIG, ...config };
}
public getConfig(): GatewayPolicyConfig {
return { ...this.config };
}
public updateConfig(updates: Partial<GatewayPolicyConfig>): void {
this.config = { ...this.config, ...updates };
}
public validate(context: GatewayContext): FindingsAnalysis {
return validateGatewayAction(context, this.config);
}
public evaluate(context: GatewayContext): GatewayDecisionResult {
return evaluateGatewayPolicy(context, this.config);
}
}
/**
* 全局默认网关单例
*/
export const defaultGatewayPolicy = new ApprovalGatewayPolicy();
+1
View File
@@ -3,3 +3,4 @@ export * from "./parser.js";
export * from "./db.js";
export * from "./repository.js";
export * from "./service.js";
export * from "./gateway.js";
+34 -75
View File
@@ -8,6 +8,12 @@ import {
ApprovalRunRecord,
FindingCheckStatus,
} from "./types.js";
import {
ApprovalGatewayPolicy,
defaultGatewayPolicy,
evaluateGatewayPolicy,
GatewayPolicyConfig,
} from "./gateway.js";
import { getBillByCodeOrId, approveBill, rejectBill, commentBill } from "../bill/tools.js";
import type { FormattedBill } from "../bill/types.js";
@@ -22,6 +28,7 @@ export interface DecideAuditOptions {
requestedAction?: "approve" | "reject" | "comment";
apply?: boolean;
comment?: string;
gatewayConfig?: Partial<GatewayPolicyConfig>;
}
export interface DecideAuditResult {
@@ -38,9 +45,11 @@ export interface DecideAuditResult {
export class ApprovalService {
private repo: ApprovalRepository;
private gatewayPolicy: ApprovalGatewayPolicy;
constructor(repo?: ApprovalRepository) {
constructor(repo?: ApprovalRepository, gatewayPolicy?: ApprovalGatewayPolicy) {
this.repo = repo ?? new ApprovalRepository();
this.gatewayPolicy = gatewayPolicy ?? defaultGatewayPolicy;
}
/**
@@ -207,8 +216,7 @@ export class ApprovalService {
): Promise<DecideAuditResult> {
const { run, findings } = this.repo.getAuditChecklist(documentSn, corpId);
// ── 核心门禁 1:如果审核要点列表为空,审批链路物理不通! ────────────────────
if (!run || findings.length === 0) {
if (!run) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
@@ -216,80 +224,31 @@ export class ApprovalService {
);
}
// ── 核心门禁 2:检查是否有未完成事实核验的 PENDING 要点 ──────────────────────
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
if (pendingFindings.length > 0) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${documentSn}] 尚有 ${pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
`待核验项: ${pendingFindings.map((f, i) => `#${i + 1} [${f.strictness}] ${f.clauseText}`).join(";")}`
);
}
// 确定性网关仲裁:由独立的可配置网关策略脚本执行(执行核心门禁与裁决计算)
const gatewayResult = evaluateGatewayPolicy(
{
documentSn,
findings,
requestedAction: options.requestedAction,
opinion: options.comment,
},
options.gatewayConfig ?? this.gatewayPolicy.getConfig()
);
// ── 核心门禁 3:梯度级别与硬性刚性防线 ───────────────────────────────────────
const failedFindings = findings.filter((f) => f.checkStatus === "FAIL");
const hardFailed = failedFindings.filter((f) => f.strictness === "硬性");
const specialFailed = failedFindings.filter((f) => f.strictness === "特殊");
const elasticFailed = failedFindings.filter((f) => f.strictness === "弹性");
const suggestFailed = failedFindings.filter((f) => f.strictness === "建议");
// 硬性条款违规拦截:物理切断 approve 通道
if (hardFailed.length > 0 && options.requestedAction === "approve") {
const violatedNames = hardFailed.map((f) => `【${f.clauseText}】`).join("、");
throw new ApprovalGatewayBlockedError(
`[网关强力阻断] 单据 [${documentSn}] 触犯刚性底线【硬性】违规条款: ${violatedNames}!\n` +
`网关物理切断同意分支,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
);
}
// 计算网关裁决决策
let decision: ApprovalDecision;
if (hardFailed.length > 0) {
decision = "REJECT";
} else if (specialFailed.length > 0) {
decision = "REVIEW";
} else if (elasticFailed.length > 0) {
decision = elasticFailed.length >= 3 ? "REVIEW" : "PASS_WITH_NOTE";
} else if (suggestFailed.length > 0) {
decision = "PASS_WITH_NOTE";
} else {
decision = "APPROVE";
}
// 组装格式化合规意见报告
const summaryLines: string[] = [];
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
summaryLines.push(`单号: ${documentSn} | 审核要点总数: ${findings.length} 项`);
summaryLines.push(``);
summaryLines.push(`[逐项核验事实]`);
findings.forEach((f, idx) => {
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
});
summaryLines.push(``);
if (decision === "REJECT") {
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
} else if (decision === "REVIEW") {
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
} else if (decision === "PASS_WITH_NOTE") {
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
} else {
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
}
if (options.comment) {
summaryLines.push(`[审批附加说明] ${options.comment}`);
}
const decisionSummary = summaryLines.join("\n");
const {
decision,
decisionSummary,
hardFailedCount,
elasticFailedCount,
suggestFailedCount,
specialFailedCount,
} = gatewayResult;
// 4. 更新数据库中的运行记录状态
this.repo.updateApprovalRun(run.id, {
decision,
decisionSummary,
failedRulesCount: failedFindings.length,
failedRulesCount: gatewayResult.analysis.failedFindings.length,
});
let appliedAction = options.requestedAction;
@@ -332,10 +291,10 @@ export class ApprovalService {
run: updatedRun,
decision,
decisionSummary,
hardFailedCount: hardFailed.length,
elasticFailedCount: elasticFailed.length,
suggestFailedCount: suggestFailed.length,
specialFailedCount: specialFailed.length,
hardFailedCount,
elasticFailedCount,
suggestFailedCount,
specialFailedCount,
appliedAction,
actionResult,
};