feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)

- Pure Rule Model & AST Parser:
  - Eliminate redundant title field; model rules purely via scope (scene index) and natural language body.
  - Implement AST parser for inline clauses: [action]{硬性|弹性|建议|特殊}.
  - Validate and enforce preference references with @{级别} syntax, strictly blocking invalid grammar.

- Embedded SQLite Database & Repository:
  - Native bun:sqlite integration with zero external dependencies, stored at ~/.config/hose-use/approval.db.
  - 5 core schemas: rules, preferences, approval_runs, approval_findings, and aipro_logs.
  - Support deduplicated scope indexing (listScopes with 1-based indices) and scope drill-down (getScopeDetail).

- Bill Requisition & Backlog Query Extension:
  - Add formatFlowAsBill adapter in domains/bill/tools.ts.
  - Fall back to flow and backlog inspection when bills are not found in invoice endpoints, unlocking full structured inspection for requisitions (such as S26000001) and loan requests.

- Deterministic Approval Gateway & Lifecycle:
  - Enforce mandatory approval lifecycle: points -> checklist -> review -> decide.
  - Physical gateway blocking: forbid decision if audit checklist is missing or empty, or if pending points remain unverified.
  - Hard tier severance: automatically sever and throw GatewayBlockError on approval attempts violating {硬性} clauses.

- Dedicated hose-aipro Global CLI & Immutable Audit Ledger:
  - Register secondary global binary hose-aipro alongside hose-use in package.json and build-binary.mjs.
  - Automatically record every AI Pro invocation, document context, args snapshot, operator, status, and verdict in aipro_logs.
  - Provide intuitive subcommands: points, checklist, review, decide, logs, rules.
  - Bump project version to v0.7.0 and regenerate OpenAPI bundles.
This commit is contained in:
gitea committed 2026-09-06 19:03:06 +08:00
1 parent 7c0bdb7518
commit 4e36a1d9a5
23 files changed
+3095 -13

No files matched your search

+440
View File
@@ -0,0 +1,440 @@
#!/usr/bin/env bun
import { parseArgs, stringOption, booleanOption, numberOption } from "./cli/parser.js";
import { printJson, printTable, redactSensitiveText } from "./cli/printer.js";
import { initCorpRuntime } from "./cli/helpers.js";
import { createEkbClient } from "./core/auth/ekb.js";
import {
ApprovalService,
ApprovalRepository,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "./domains/approval/index.js";
import { VERSION } from "./version.js";
export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const parsed = parseArgs(rawArgs);
const runtime = initCorpRuntime({
corpId: stringOption(parsed.options, ["corp", "c"]),
jsonMode: booleanOption(parsed.options, ["json"]),
});
const corp = runtime.selectedCorp;
if (!corp) {
return {
stdout: "",
stderr: "未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。\n",
exitCode: 1,
};
}
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const repo = new ApprovalRepository();
const service = new ApprovalService(repo);
const positional: string[] = [];
for (let i = 0; i < rawArgs.length; i++) {
const arg = rawArgs[i];
if (arg === "--") {
positional.push(...rawArgs.slice(i + 1));
break;
}
if (arg.startsWith("-")) {
const eqIdx = arg.indexOf("=");
if (eqIdx === -1) {
const flagName = arg.replace(/^--?/, "").toLowerCase();
const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute", "run", "do"].includes(flagName);
if (!isBool && i + 1 < rawArgs.length && !rawArgs[i + 1].startsWith("-")) {
i++; // skip option value
}
}
continue;
}
positional.push(arg);
}
const command = (positional[0] || "help").toLowerCase();
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const args = positional.slice(1);
const operator = corp.staffId || corp.name || "AI-Agent";
try {
switch (command) {
// ── 1. 明细级规则注入(出审核要点清单)────────────────────────────────
case "points":
case "inject": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro points <单号> [--scope <1|场景>]");
}
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
const result = await service.injectAuditPoints(client, corpId, targetSn, {
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
});
repo.logAiProAction({
action: "points",
documentSn: result.bill.billCode,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: "PENDING",
summary: `注入审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson({
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
}),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
const rows = result.findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus,
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 单据 ${result.bill.billCode} 审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
const tip =
`\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` +
`下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` +
`最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`;
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
}
// ── 2. 查看审核要点清单与进度(未注入则硬阻断)────────────────────────
case "checklist":
case "list":
case "status": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro checklist <单号>");
}
const { run, findings } = service.getAuditChecklist(targetSn);
if (!run || findings.length === 0) {
repo.logAiProAction({
action: "checklist",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "BLOCKED",
summary: "查询审核清单阻断:单据尚未注入任何审核要点",
});
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`网关安全卡点生效:在要点未注入前,审批链路物理不通!\n` +
`请先执行: hose-aipro points ${targetSn} 注入明细级审核要点清单。\n`;
return { stdout: "", stderr: errorMsg, exitCode: 1 };
}
if (runtime.jsonMode) {
return {
stdout: printJson({ run, findings }),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 说明"];
const rows = findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
const title = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 3. 事实核验打标录入 ───────────────────────────────────────────────
case "review":
case "eval":
case "evaluate": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro review <单号> --eval '...'");
}
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 updates: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({ index: pointIndex, status: statusInput, evidence, reasoning });
} else if (evalStr) {
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
if (match) {
const idx = parseInt(match[1], 10);
const status = match[2].toUpperCase() as FindingCheckStatus;
const desc = match[3]?.trim();
updates.push({ index: idx, status, evidence: desc, reasoning: desc });
}
}
}
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 "缺少特批邮件"`
);
}
const updatedFindings = service.evaluateAuditPoints(targetSn, updates);
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
repo.logAiProAction({
action: "review",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `已录入 ${updates.length} 处要点核验事实(待核验剩余: ${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 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`);
return { stdout: msg, stderr: "", exitCode: 0 };
}
// ── 4. 确定性网关仲裁决断与执行 ───────────────────────────────────────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro decide <单号> [--apply] [--yes]");
}
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
if (apply) {
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
if (!confirmed) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
}
const { prompt } = await import("./cli/helpers.js");
const ans = await prompt("[AI PRO] 即将向合思系统真实执行审批流转/意见留痕,确认执行?输入 yes: ");
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
}
const requestedAction = command === "approve" ? "approve" : command === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
});
repo.logAiProAction({
action: "decide",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: decisionResult.decision,
summary: `网关仲裁完成: ${decisionResult.decision} (硬性违规: ${decisionResult.hardFailedCount}, 弹性违规: ${decisionResult.elasticFailedCount})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult),
stderr: "",
exitCode: 0,
};
}
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 };
}
// ── 5. 全流程监控流水查看 (Audit Logs) ────────────────────────────────
case "logs":
case "log":
case "history":
case "trail": {
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
const logs = repo.listAiProLogs(targetSn || undefined, limit);
if (runtime.jsonMode) {
return {
stdout: printJson({ total: logs.length, logs }),
stderr: "",
exitCode: 0,
};
}
if (logs.length === 0) {
return {
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetSn ? ` (单号: ${targetSn})` : ""}。\n`,
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "发生时间", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"];
const rows = logs.map((l, i) => [
i + 1,
new Date(l.createdAt).toLocaleString("zh-CN"),
l.action,
l.documentSn || "-",
l.operator || "-",
l.status === "SUCCESS" ? "✅ SUCCESS" : l.status === "BLOCKED" ? "🚫 BLOCKED" : "❌ ERROR",
l.decision || "-",
l.summary || "-",
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO 全流程监控流水账本] (共登记 ${logs.length} 条记录) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 6. 规约快捷查看 ───────────────────────────────────────────────────
case "rules":
case "rule":
case "scopes": {
const scopes = repo.listScopes();
const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"];
const rows = scopes.map((s) => [
s.index,
s.scope,
s.ruleCount,
s.ruleCodes.map((c) => `#${c}`).join(", "),
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 规约场景索引库 (共 ${scopes.length} 个场景) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 7. 帮助 ───────────────────────────────────────────────────────────
case "help":
default: {
const helpText = `
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
核心工作流:
1. 规则注入 (出明细级审核要点清单):
hose-aipro points <单号> [--scope <索引号|场景>]
2. 查看审核要点清单与核验进度 (未注入则硬阻断):
hose-aipro checklist <单号>
3. 逐项录入事实核验打标:
hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP"
hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票"
4. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支):
hose-aipro decide <单号> # 预审仿真 (Dry Run)
hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论
5. 全流程监控日志流水查看:
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
6. 查看审批规约场景:
hose-aipro rules # 查看所有场景与规则分布
`;
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
}
}
} catch (err: any) {
// 将阻断或异常统一记录至审计日志
if (err instanceof ApprovalGatewayBlockedError) {
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "BLOCKED",
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: "",
stderr: `\n${err.message}\n`,
exitCode: 1,
};
}
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "ERROR",
summary: String(err?.message || err),
});
return {
stdout: "",
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
exitCode: 1,
};
}
}
// 直接作为可执行脚本运行时
if (import.meta.main) {
const rawArgs = process.argv.slice(2);
const result = await runAiProCli(rawArgs);
if (result.stdout) process.stdout.write(redactSensitiveText(result.stdout));
if (result.stderr) process.stderr.write(redactSensitiveText(result.stderr));
process.exit(result.exitCode);
}