feat(aipro): implement bind, review, decide with gateway guardrail and <150 chars opinion validation

This commit is contained in:
gitea committed 2026-09-06 23:54:36 +08:00
1 parent 7e39d95b36
commit ca00e9a2cc
3 files changed
+412 -66

No files matched your search

+294 -66
View File
@@ -9,8 +9,12 @@ import {
ApprovalGatewayBlockedError,
FindingCheckStatus,
ApprovalRunRecord,
CreateFindingInput,
RuleRecord,
parseRuleBody,
} from "./domains/approval/index.js";
import { getRawBillFlow } from "./domains/bill/api.js";
import { approveBill, rejectBill } from "./domains/bill/tools.js";
import { translateBillFlowToMarkdown } from "./domains/bill/translator.js";
import { VERSION } from "./version.js";
@@ -347,6 +351,118 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
};
}
// ── 5. 挂载规则并拆解为待核验要点清单 (Bind Checklist) ─────────────────
case "bind":
case "mount": {
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
if (!runHandle) {
throw new Error("请提供会话 ID: hose-aipro bind --run <runId> --rules '[1, 2]'");
}
const runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
const rawRules = stringOption(parsed.options, ["rules", "rule", "codes", "c"]);
const rawIndexes = stringOption(parsed.options, ["indexes", "index", "i", "scopes", "scope", "s"]);
const fallbackRaw = positional.slice(1).find((p) => p !== runHandle && p.startsWith("[") && p.endsWith("]"));
const parseIntegers = (input?: string): number[] => {
if (!input) return [];
const trimmed = input.trim();
const list: number[] = [];
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
try {
const parsedJson = JSON.parse(trimmed);
if (Array.isArray(parsedJson)) {
for (const item of parsedJson) {
const n = Number(item);
if (!isNaN(n)) list.push(n);
}
return list;
}
} catch {}
}
const inner = trimmed.replace(/[\[\]]/g, "");
const parts = inner.split(/[,,\s]+/).filter(Boolean);
for (const p of parts) {
const n = Number(p.replace(/['"]/g, ""));
if (!isNaN(n)) list.push(n);
}
return list;
};
const ruleCodes = parseIntegers(rawRules || fallbackRaw);
const indexNums = parseIntegers(rawIndexes);
if (ruleCodes.length === 0 && indexNums.length === 0) {
throw new Error("请指定要挂载的规则或场景索引,例如: hose-aipro bind --run <runId> --rules '[1, 2]'");
}
const targetRulesMap = new Map<number, RuleRecord>();
for (const code of ruleCodes) {
const r = repo.getRuleByCode(code);
if (r && r.status === "active") {
targetRulesMap.set(r.code, r);
}
}
for (const idx of indexNums) {
const detail = repo.getScopeDetail(idx);
if (detail) {
for (const r of detail.rules) {
if (r.status === "active") {
targetRulesMap.set(r.code, r);
}
}
}
}
if (targetRulesMap.size === 0) {
throw new Error("未找到任何有效规则,请先运行 hose-aipro scopes 和 hose-aipro rules 查看规约");
}
const sortedRules = Array.from(targetRulesMap.values()).sort((a, b) => a.code - b.code);
const findingsToInject: CreateFindingInput[] = [];
for (const r of sortedRules) {
const parsedRule = parseRuleBody(r.body);
for (const clause of parsedRule.clauses) {
findingsToInject.push({
ruleId: r.id,
clauseText: clause.action,
strictness: clause.strictness,
checkStatus: "PENDING",
});
}
}
const injected = repo.injectFindings(runRecord.id, findingsToInject);
repo.logAiProAction({
action: "bind",
runId: runRecord.shortId || runRecord.id,
documentSn: runRecord.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `在会话 [${runRecord.shortId}] 挂载 ${injected.length} 条审核要点清单(涵盖规则: ${sortedRules.map((r) => `#${r.code}`).join(", ")})`,
});
const output = injected.map((f, i) => ({
要点编号: i + 1,
严格程度: f.strictness,
归属规则: f.ruleCode ?? "-",
审核要点: f.clauseText,
核验状态: "待核验",
}));
return {
stdout: JSON.stringify(output, null, 2) + "\n",
stderr: "",
exitCode: 0,
};
}
// ── 4. 查看审核要点清单(纯规则元数据,与具体单据无关)────────────────
case "points":
case "clauses": {
@@ -597,37 +713,56 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 3. 事实核验打标录入 ───────────────────────────────────────────────
// ── 6. 事实核验打标录入 (Review / Fact Check) ─────────────────────────
case "review":
case "eval":
case "evaluate": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro review <单号> --eval '...'");
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
if (!runHandle) {
throw new Error("请提供会话 ID: hose-aipro review --run <runId> --eval '...'");
}
const runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
const findings = repo.getFindingsByRunId(runRecord.id);
if (findings.length === 0) {
throw new Error(
`会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何审核要点清单,请先执行 hose-aipro bind --run ${runRecord.shortId || runRecord.id} --rules '...'`
);
}
const evalStr = stringOption(parsed.options, ["eval", "findings", "e"]);
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
const reasoning = stringOption(parsed.options, ["reasoning", "reason"]);
const normalizeStatus = (raw: string): FindingCheckStatus => {
const upper = raw.trim().toUpperCase();
if (["PASS", "通过", "合规", "OK", "YES"].includes(upper)) return "PASS";
if (["FAIL", "未通过", "不通过", "违规", "NO"].includes(upper)) return "FAIL";
if (["SKIP", "跳过", "不适用", "NA", "N/A"].includes(upper)) return "SKIP";
return "PENDING";
};
const updates: Array<{
index?: number;
id?: string;
index: number;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({ index: pointIndex, status: statusInput, evidence, reasoning });
updates.push({ index: pointIndex, status: normalizeStatus(statusInput), evidence, reasoning });
} else if (evalStr) {
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
const segments = evalStr.split(/[;\n]+/).map((s) => s.trim()).filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
const match = seg.match(/^(\d+)\s*=\s*([A-Za-z\u4e00-\u9fa5]+)(?::(.*))?$/);
if (match) {
const idx = parseInt(match[1], 10);
const status = match[2].toUpperCase() as FindingCheckStatus;
const status = normalizeStatus(match[2]);
const desc = match[3]?.trim();
updates.push({ index: idx, status, evidence: desc, reasoning: desc });
}
@@ -637,53 +772,142 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
if (updates.length === 0) {
throw new Error(
`请提供核验判定参数,例如:\n` +
` hose-aipro review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
` 或: hose-aipro review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
` hose-aipro review --run ${runRecord.shortId || runRecord.id} --eval "1=PASS:已上传发票; 2=FAIL:住宿超标; 3=SKIP"\n`
);
}
const activeCorpId = requireCorpId();
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, activeCorpId);
for (const item of updates) {
const target = findings[item.index - 1];
if (!target) {
throw new Error(`要点编号超出范围: #${item.index} (当前要点总数: ${findings.length})`);
}
repo.updateFinding(target.id, {
checkStatus: item.status,
evidence: item.evidence,
reasoning: item.reasoning,
});
}
const updatedFindings = repo.getFindingsByRunId(runRecord.id);
const passCount = updatedFindings.filter((f) => f.checkStatus === "PASS").length;
const failCount = updatedFindings.filter((f) => f.checkStatus === "FAIL").length;
const skipCount = updatedFindings.filter((f) => f.checkStatus === "SKIP").length;
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
repo.logAiProAction({
action: "review",
documentSn: targetSn,
runId: runRecord.shortId || runRecord.id,
documentSn: runRecord.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `已录入 ${updates.length} 处要点核验事实(待核验剩余: ${pendingCount} 项)`,
summary: `在会话 [${runRecord.shortId || runRecord.id}] 录入 ${updates.length} 项要点核验(通过: ${passCount}, 违规: ${failCount}, 待核验: ${pendingCount})`,
});
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
const rows = updatedFindings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const checklistOutput = updatedFindings.map((f, i) => ({
要点编号: i + 1,
严格程度: f.strictness,
归属规则: f.ruleCode ?? "-",
审核要点: f.clauseText,
核验状态: f.checkStatus === "PASS" ? "通过" : f.checkStatus === "FAIL" ? "未通过" : f.checkStatus === "SKIP" ? "已跳过" : "待核验",
事实依据: Array.from(new Set([f.evidence, f.reasoning].filter(Boolean))).join(" - ") || "-",
}));
const table = printTable(headers, rows);
const msg =
`====== [AI PRO] 单据 ${targetSn} 事实核验已登记入库 (待核验剩余: ${pendingCount} 项) ======\n` +
table +
(pendingCount === 0
? `\n🎉 [事实全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-aipro decide ${targetSn} --apply --yes\n`
: `\n⏳ [待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
const resultObj = {
会话ID: runRecord.shortId || runRecord.id,
单号: runRecord.documentSn,
要点总数: updatedFindings.length,
已通过: passCount,
未通过: failCount,
已跳过: skipCount,
待核验: pendingCount,
核验清单: checklistOutput,
};
return { stdout: msg, stderr: "", exitCode: 0 };
return {
stdout: JSON.stringify(resultObj, null, 2) + "\n",
stderr: "",
exitCode: 0,
};
}
// ── 4. 确定性网关仲裁决断与执行 ───────────────────────────────────────
// ── 7. 决断动作与网关安全阻拦 (Decide with Gateway Interception) ──────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro decide <单号> [--apply] [--yes]");
const runHandle =
stringOption(parsed.options, ["run", "r"]) ||
positional.slice(1).find((p) => !["approve", "reject", "pass", "同意", "通过", "驳回", "拒绝"].includes(p.toLowerCase()));
if (!runHandle) {
throw new Error("请提供会话 ID: hose-aipro decide <approve|reject> --run <runId> --opinion '...'");
}
const runRecord = repo.getRunByHandle(runHandle);
if (!runRecord) {
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
}
let actionRaw: string | undefined = positional[1]?.toLowerCase();
if (actionRaw === runHandle?.toLowerCase()) {
actionRaw = positional[2]?.toLowerCase();
}
if (!actionRaw || actionRaw.startsWith("-")) {
actionRaw = stringOption(parsed.options, ["action", "a"])?.toLowerCase();
}
if (command === "approve") {
actionRaw = "approve";
} else if (command === "reject") {
actionRaw = "reject";
}
let action: "APPROVE" | "REJECT" | undefined;
if (["approve", "pass", "同意", "通过"].includes(actionRaw || "")) {
action = "APPROVE";
} else if (["reject", "refuse", "驳回", "拒绝"].includes(actionRaw || "")) {
action = "REJECT";
}
if (!action) {
throw new Error("请指定要执行的审批动作: hose-aipro decide approve 或 hose-aipro decide reject");
}
const opinion = (
stringOption(parsed.options, ["opinion", "comment", "message", "m", "审批意见", "意见"]) || ""
).trim();
if (!opinion) {
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}),物理切断“同意”流转,绝对禁止放行!`);
}
}
// Apply execution
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
let executionStatus = "模拟完成(未带 --apply,未真实修改线上单据)";
if (apply) {
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
if (!confirmed) {
@@ -691,51 +915,55 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
}
const { prompt } = await import("./cli/helpers.js");
const ans = await prompt("[AI PRO] 即将向合思系统真实执行审批流转/意见留痕,确认执行?输入 yes: ");
const ans = await prompt(`[AI PRO] 即将向合思系统真实执行审批流转 [${action === "APPROVE" ? "同意" : "驳回"}],确认执行?输入 yes: `);
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
const context = await getClient();
if (action === "APPROVE") {
await approveBill(context.client, context.corpId, runRecord.documentSn, {
comment: opinion,
});
} else {
await rejectBill(context.client, context.corpId, runRecord.documentSn, {
comment: opinion,
});
}
executionStatus = "已真实下发合思系统流转";
}
const requestedAction = command === "approve" ? "approve" : command === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
const context = await getClient();
const decisionResult = await service.decideAudit(context.client, context.corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
// Update run in database
repo.updateApprovalRun(runRecord.id, {
decision: action,
decisionSummary: opinion,
failedRulesCount: findings.filter((f) => f.checkStatus === "FAIL").length,
});
repo.logAiProAction({
action: "decide",
documentSn: targetSn,
runId: runRecord.shortId || runRecord.id,
documentSn: runRecord.documentSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: decisionResult.decision,
summary: `网关仲裁完成: ${decisionResult.decision} (硬性违规: ${decisionResult.hardFailedCount}, 弹性违规: ${decisionResult.elasticFailedCount})`,
decision: action,
summary: `审批动作 [${action === "APPROVE" ? "同意" : "驳回"}] (${executionStatus})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult),
stderr: "",
exitCode: 0,
};
}
const resultObj = {
会话ID: runRecord.shortId || runRecord.id,
单号: runRecord.documentSn,
执行动作: action === "APPROVE" ? "同意" : "驳回",
审批意见: opinion,
流转状态: executionStatus,
网关状态: "放行",
};
const outLines: string[] = [];
outLines.push(`\n====== [AI PRO] 合思确定性网关仲裁决断书 (单号: ${targetSn}) ======`);
outLines.push(`网关决策 : ${decisionResult.decision}`);
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
if (apply) {
outLines.push(`下游动作 : 已安全真实执行 [${decisionResult.appliedAction}] 动作`);
} else {
outLines.push(`执行模式 : 仿真预审 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
}
outLines.push(`\n--- 审计意见留痕快照 ---\n${decisionResult.decisionSummary}\n`);
return { stdout: outLines.join("\n"), stderr: "", exitCode: 0 };
return {
stdout: JSON.stringify(resultObj, null, 2) + "\n",
stderr: "",
exitCode: 0,
};
}
// ── 5. 全流程监控流水查看 (Audit Logs) ────────────────────────────────