Compare commits

..
19 Commits
Author SHA1 Message Date
yunyingk 480f833580 Merge pull request #236 from yunyingk/codex/release-v0.11.8
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.8: Automated release bump
2026-10-15 16:52:22 +08:00
gitea b21beba419 Release v0.11.8: Automated release bump 2026-10-15 16:51:01 +08:00
yunyingk 97d1c47a6c Merge pull request #235 from yunyingk/mac15/streamline-general-report-template
Streamline monthly report template and enhance validator
2026-10-15 16:50:12 +08:00
gitea f6fe0de286 Add pkg/report standalone external validation suite and example report 2026-10-15 16:47:26 +08:00
gitea f9f72fa918 Decouple chapter numbers from validation and pipeline rendering to allow arbitrary chapter order 2026-10-15 16:39:33 +08:00
gitea a52b6ac117 Standardize report tables on clean 2-column format with clickable SN 2026-10-15 16:29:28 +08:00
gitea f8ac839840 Document user-centric dynamic adaptability principle in agent skill 2026-10-15 16:20:01 +08:00
gitea 7df5feb7b7 Add automated audit link column and reconcile divergence metrics 2026-10-15 16:06:29 +08:00
gitea 16f3f252c0 Align Hose document URL with backlogDetail hash routing 2026-10-15 15:36:26 +08:00
gitea 25d1036eed Refine approval run URL resolution with Hose fallback and SSO 2026-10-15 15:27:14 +08:00
gitea 0210051ab7 Implement pre-flight adjudication gate and companion ledger cross-validation 2026-10-15 15:17:44 +08:00
gitea 5573dfb60e Codify dual-link fast traversal standard into report authoring skill 2026-10-15 15:08:24 +08:00
gitea 1fb61f794e Fix report sample count and decision distribution for scoped runs 2026-10-15 14:53:25 +08:00
gitea 7d15f3834d Update report skill reference for streamlined 6-section workflow 2026-10-15 14:46:37 +08:00
gitea aad591569a Streamline monthly report template and enhance validator 2026-10-15 14:30:59 +08:00
yunyingk 7304578bc7 Merge pull request #234 from yunyingk/codex/release-v0.11.7
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.7: Automated release bump
2026-10-13 17:34:14 +08:00
gitea 16a673c910 Release v0.11.7: Automated release bump 2026-10-13 17:32:50 +08:00
yunyingk ce1f1f3ca1 Merge pull request #233 from yunyingk/mac15/monthly-report-reference
Add lightweight report data capability and authoring reference
2026-10-13 17:28:28 +08:00
gitea 2177a06f39 Add lightweight report data capability and authoring reference 2026-10-13 17:22:02 +08:00
34 changed files with 2230 additions and 213 deletions

No files matched your search

+1
View File
@@ -3,6 +3,7 @@ node_modules/
# Build outputs
dist/bin/
build/
# Local runtime caches and system noise (regenerate at any time)
.cache/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.6",
"version": "0.11.8",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+20
View File
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.8] - 2026-10-15
### Added
- Merge pull request #235 from yunyingk/mac15/streamline-general-report-template
- Add pkg/report standalone external validation suite and example report
- Decouple chapter numbers from validation and pipeline rendering to allow arbitrary chapter order
- Standardize report tables on clean 2-column format with clickable SN
- Document user-centric dynamic adaptability principle in agent skill
- Add automated audit link column and reconcile divergence metrics
- Align Hose document URL with backlogDetail hash routing
- Refine approval run URL resolution with Hose fallback and SSO
## [0.11.7] - 2026-10-13
### Added
- Merge pull request #233 from yunyingk/mac15/monthly-report-reference
- Add lightweight report data capability and authoring reference
## [0.11.6] - 2026-10-13
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.6",
"version": "0.11.8",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+190
View File
@@ -0,0 +1,190 @@
# 【模板企业】8月AI审核准确率报告
| 报告信息 | 内容 |
| --- | --- |
| 报告编号 | RPT-202608-A3F8C2 |
| 客户名称 | 模板企业 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
| 报告状态 | 草稿 |
| 生成日期 | 2026-09-23 |
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
---
## 1. 审核测试结果
### 1.1 数据来源与范围
| 项目 | 内容 |
| --- | --- |
| 数据来源 | 客户授权的已完成历史审批单据 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
### 1.2 核心准确率结论
基于已经给定的规则库:
| 审核方式 | 准确率 |
| --- | --- |
| AI 审核 | **92.08%** |
| 人工审核 | **83.33%** |
AI 审核准确率的计算方式:
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
![AI 与人工审核准确率对比](assets/图1-准确率对比.svg)
*图 1 · AI 与人工审核准确率对比*
---
## 2. AI 失准分析(学习优化空间)
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
### 2.1 失准构成总览
| 维度 | 失准类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
| 合计 | — | 100% | 19 张 |
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
**解决方案**:严格校准规则触发后动作,按规则执行。
| 单号 | 问题描述 |
| --- | --- |
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
*(节选 3 例,全量 9 张)*
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
| 单号 | 问题描述 |
| --- | --- |
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
*(节选 3 例,全量 5 张)*
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
| 单号 | 问题描述 |
| --- | --- |
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
*(节选 3 例,全量 5 张)*
---
## 3. AI 发现的潜在风险
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
### 3.1 风险构成总览
| 维度 | 风险类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
| 合计 | — | 100% | 40 张 |
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
| 单号 | 问题描述 |
| --- | --- |
| FP260011 | 改衣费未附改衣明细表 |
| FP260012 | 咨询费报销资料不全 |
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
*(节选 3 例,全量 23 张)*
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
| 单号 | 问题描述 |
| --- | --- |
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
*(节选 3 例,全量 9 张)*
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
| 单号 | 问题描述 |
| --- | --- |
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
*(节选 3 条,全量 8 张)*
---
## 4. 综合效益
| 维度 | 结论 | 关键数据 |
| --- | --- | --- |
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
---
## 5. 审核分歧与复核归因
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
| 原因分类 | 占比 | 单数 | 核心说明 |
| --- | --- | --- | --- |
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
| 合计 | 100% | 3 张 | — |
**分歧分析与后续建议**:
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
---
## 6. 支撑数据与交付材料
### 6.1 分模板准确率与自动审批率
全量 N = 240:
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
| --- | --- | --- | --- | --- | --- |
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
*(其余 10 类模板从略,实际报告列出全量 16 类)*
### 6.2 跑批原始数据与交付台账
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
+120
View File
@@ -0,0 +1,120 @@
# AI 审核报告(Markdown)独立编制与校验套件
本套件是面向**外部交付、客户协作与第三方审核团队**的独立版 AI 审核报告验证工具包。
---
## 一、核心定位与特点
1. **零环境依赖**:基于纯 Python 标准库编写(Python 3.8+),无需安装 `seal-use`,无需 Node.js / Bun,跨平台(macOS / Linux / Windows)开箱即用。
2. **纯粹面向 Markdown**:专注于 Markdown 报告文档本身的格式纯净度、结构严密性与数学总账守恒;**不强求本地 Excel 伴生台账**,**无需手动填写任何技术跳转链接**。
3. **核心章节硬匹配,自定义章节完全放行**:核心论证章节按大标题名称硬匹配认领;中间任意插入的部门专项分析、整改排期等章节,校验器一律视为纯叙述业务章节,不施加任何教条规则,直接绿色放行!
---
## 二、目录结构
```text
pkg/report/
├── README.md # 本使用指南与规范手册
├── validate.py # 独立离线校验脚本(纯标准库)
├── example-report.md # 100% 格式合规的标准示例月报
└── assets/ # 示例配图资产
└── 图1-准确率对比.svg
```
---
## 三、快速上手
### 1. 快速校验一份 Markdown 报告
```bash
# 进入本目录
cd pkg/report
# 执行校验
python3 validate.py example-report.md
```
**校验通过输出示例**:
```text
✅ 报告文件: /path/to/example-report.md
📊 识别表格: 14 个 | 配图资产: 1 个
🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。
```
### 2. 输出机器可读的 JSON 结构(方便接入 CI/CD 或自动化流水线)
```bash
python3 validate.py example-report.md --json
```
---
## 四、报告大纲与编写原则
一份合格的 AI 审核商业月度报告,遵循**“骨架刚性、血肉自适应”**的设计理念:
### 1. 核心必选骨架(通过大标题名称硬匹配)
无论章节编号是第几章,系统只要匹配到大标题名称,就会认领对应的业务校验:
| 核心大标题名称 | 核心作用与定位 | 必须遵守的业务守恒 |
| :--- | :--- | :--- |
| **开篇「报告信息」表** | 抬头身份证明 | 必含 5 字段:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
| **`审核测试结果`** | 核心业绩表态 | 包含样本总量、AI/人工准确率结论、LaTeX 准确率公式(`\frac{A}{B} = C\%`)及对比图。 |
| **`AI 失准分析`** | 坦白 AI 误判与偏差 | 包含失准构成总览表、TOP 1~N 典型案例表格与针对性调优解决方案。 |
| **`AI 发现的潜在风险`** | 力证风控拦截价值 | 包含潜在风险总览表、TOP 1~N 凭证缺失、比价缺失、超期等真实拦截案例。 |
| **`综合效益`** | 总结人效与风控收益 | 时效、准确度、风险拦截笔数宏观总结表(纯内部对账时可按需裁剪)。 |
| **`审核分歧与复核归因`** | 人机分歧深度定性 | 分类统计表(线上规则未覆盖 vs 模型偏差)与口头管控标准线上化管理建议。 |
| **`支撑数据与交付材料`** | 分模板细分数据 | 分模板准确率与自动化率汇总表,说明底层流水交付物。 |
### 2. 中间随意插入的自定义章节(完全自由放行)
如果针对具体企业的特定管理需要,想在报告中间插入业务专属章节(例如在第 1 章后插入 `## 2. 营销大区差旅合规专项穿透`):
* **系统处理方式**:大标题名称不在核心名单里的章节,校验器一律视为**纯叙述业务章节**;
* **自由度**:不限制表格列数、不限制行数、不强制要求数学守恒,写什么内容都直接放行!
* **唯一要求**:大章节使用 `##`,章节编号从 1 开始自然连续递增(1, 2, 3, 4, 5...),子小节使用 `###` 且不跳级。
### 3. 表格案例与链接约定
* 案例表格推荐使用纯净紧凑的 **2 列规范**(`| 单号 | 问题描述 |`);
* 编写 Markdown 时**无需手动查询或粘贴长串后台技术 URL**,专注于业务事实描述即可。
---
## 五、校验规则与错误代码速查表
`validate.py` 内部内置了以下质量红线校验门禁。如果报告校验未通过,终端会指出具体问题行号与代码:
| 错误代码 | 校验类别 | 规则说明与修复指南 |
| :--- | :--- | :--- |
| **`FM001`** | 格式纯净 | 严禁以 YAML Frontmatter(`---`)开头;元数据请写在正文开头的「报告信息」表中。 |
| **`MK001`** | 格式纯净 | 严禁残留模板草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等)。 |
| **`MD001`** | 格式规范 | 代码围栏(反引号 ```)必须成对闭合,不可出现单数个。 |
| **`TB001`** | 表格对齐 | 每行数据单元格按 `\|` 拆分后的列数,必须严格等于表头列数。 |
| **`TB002`** | 表格规范 | 表头文字必须保持纯文本,禁止包含 `**` 加粗符号。 |
| **`HD001`** | 标题层级 | 禁止跳级(如 `#` 一级标题直接跳到 `###` 三级标题)。 |
| **`HD002`** | 标题序号 | 二级大章节编号(`## \d+\.`)必须从 1 开始连续递增,不得跳号。 |
| **`INFO001`** | 头部元数据 | 开篇「报告信息」表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。 |
| **`INFO002`** | 头部元数据 | 开篇「报告信息」表的 5 项元数据值均不能为空白。 |
| **`IMG001`** | 资产存活 | 文档中引用的本地相对路径图片(如 `.svg` / `.png`)在磁盘必须真实存在。 |
| **`NM001`** | 数学守恒 | 【失准分析】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
| **`NM002`** | 数学守恒 | 【潜在风险】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
| **`NM003`** | 数学守恒 | 分类总览表中声明的占比百分比与 `单数 / 合计` 计算误差不得超过 0.15%。 |
| **`NM004`** | 数学守恒 | 【分歧归因】分类表各原因单数相加必须等于分歧总数,且与正文叙述一致。 |
| **`NM005`** | 数学守恒 | LaTeX 公式 `\frac{A}{B} = C\%` 算术必须成立,且公式中的数字在正文中有数据来源。 |
---
## 六、常见问题解答 (FAQ)
**Q:编写报告时,出现失准或风险分类不是 3 种怎么办?**
A:完全自由!如果有 2 种就列 TOP 1~2,有 4 种就列 TOP 1~4,只要总览表中这几项的单数加起来等于合计行、百分比加起来等于 100% 即可通过校验。
**Q:案例表格必须放 3 行吗?**
A:不需要。可放 1 行典型单据,也可放 5 行全量单据,表格行数完全由业务深度决定。
**Q:为什么提示公式算术不成立(`NM005`)?**
A:请检查 LaTeX 公式中的分子除以分母计算出的百分比,与等号右边的数值是否一致(如 $221 / 240 = 92.0833\% \approx 92.08\%$,如果写成 95% 则会被拦截)。
@@ -0,0 +1,51 @@
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="400" viewBox="0 0 960 400" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif">
<defs>
<!-- 精确交集透镜裁剪路径 -->
<clipPath id="left-circle-clip">
<circle cx="410" cy="160" r="135"/>
</clipPath>
</defs>
<rect width="960" height="400" fill="#ffffff"/>
<!-- Left Circle: Pastel Blue -->
<circle cx="410" cy="160" r="135" fill="#b9deff"/>
<!-- Right Circle: Pastel Mint -->
<circle cx="550" cy="160" r="135" fill="#d2ede8"/>
<!-- Distinct Intersection Lens: Perfect blend tone (#9ed4eb) -->
<circle cx="550" cy="160" r="135" clip-path="url(#left-circle-clip)" fill="#9ed4eb"/>
<!-- Left Text Block (Horizontally centered lines) -->
<g text-anchor="middle" fill="#111111">
<text x="140" y="146" font-size="18"><tspan letter-spacing="1.5px">AI</tspan><tspan letter-spacing="0px">审核准确</tspan></text>
<text x="140" y="176" font-size="18">(总准确率92.08%)</text>
</g>
<!-- Left dashed line: comfortable gap from text, extends into circle -->
<line x1="245" y1="160" x2="310" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
<!-- Left percentage -->
<text x="348" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">16.66%</text>
<!-- Overlap percentage (in intersection lens) -->
<text x="480" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">75.42%</text>
<!-- Right percentage -->
<text x="612" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">7.91%</text>
<!-- Right dashed line -->
<line x1="650" y1="160" x2="715" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
<!-- Right Text Block (Horizontally centered lines) -->
<g text-anchor="middle" fill="#111111">
<text x="820" y="146" font-size="18">人工审核准确</text>
<text x="820" y="176" font-size="18">(总准确率83.33%)</text>
</g>
<!-- Bottom vertical dashed pointer -->
<line x1="480" y1="215" x2="480" y2="305" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
<!-- Bottom label: refined kerning on AI and comfortable character spacing -->
<text x="480" y="338" font-size="18" fill="#111111" text-anchor="middle" dominant-baseline="central"><tspan letter-spacing="2px">AI</tspan><tspan letter-spacing="1px">与人工都准确</tspan></text>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+190
View File
@@ -0,0 +1,190 @@
# 【模板企业】8月AI审核准确率报告
| 报告信息 | 内容 |
| --- | --- |
| 报告编号 | RPT-202608-A3F8C2 |
| 客户名称 | 模板企业 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
| 报告状态 | 草稿 |
| 生成日期 | 2026-09-23 |
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
---
## 1. 审核测试结果
### 1.1 数据来源与范围
| 项目 | 内容 |
| --- | --- |
| 数据来源 | 客户授权的已完成历史审批单据 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
### 1.2 核心准确率结论
基于已经给定的规则库:
| 审核方式 | 准确率 |
| --- | --- |
| AI 审核 | **92.08%** |
| 人工审核 | **83.33%** |
AI 审核准确率的计算方式:
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
![AI 与人工审核准确率对比](assets/图1-准确率对比.svg)
*图 1 · AI 与人工审核准确率对比*
---
## 2. AI 失准分析(学习优化空间)
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
### 2.1 失准构成总览
| 维度 | 失准类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
| 合计 | — | 100% | 19 张 |
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
**解决方案**:严格校准规则触发后动作,按规则执行。
| 单号 | 问题描述 |
| --- | --- |
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
*(节选 3 例,全量 9 张)*
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
| 单号 | 问题描述 |
| --- | --- |
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
*(节选 3 例,全量 5 张)*
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
| 单号 | 问题描述 |
| --- | --- |
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
*(节选 3 例,全量 5 张)*
---
## 3. AI 发现的潜在风险
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
### 3.1 风险构成总览
| 维度 | 风险类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
| 合计 | — | 100% | 40 张 |
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
| 单号 | 问题描述 |
| --- | --- |
| FP260011 | 改衣费未附改衣明细表 |
| FP260012 | 咨询费报销资料不全 |
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
*(节选 3 例,全量 23 张)*
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
| 单号 | 问题描述 |
| --- | --- |
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
*(节选 3 例,全量 9 张)*
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
| 单号 | 问题描述 |
| --- | --- |
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
*(节选 3 条,全量 8 张)*
---
## 4. 综合效益
| 维度 | 结论 | 关键数据 |
| --- | --- | --- |
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
---
## 5. 审核分歧与复核归因
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
| 原因分类 | 占比 | 单数 | 核心说明 |
| --- | --- | --- | --- |
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
| 合计 | 100% | 3 张 | — |
**分歧分析与后续建议**:
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
---
## 6. 支撑数据与交付材料
### 6.1 分模板准确率与自动审批率
全量 N = 240:
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
| --- | --- | --- | --- | --- | --- |
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
*(其余 10 类模板从略,实际报告列出全量 16 类)*
### 6.2 跑批原始数据与交付台账
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
+375
View File
@@ -0,0 +1,375 @@
#!/usr/bin/env python3
"""
AI 审核报告(Markdown)独立校验器
Independent Markdown Validator for AI Audit Reports
特点:
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台(macOS / Linux / Windows)
- 专为外部协同与客户交付设计:不依赖 seal-use、不强求本地 Excel 伴生台账
- 核心章节硬匹配大标题名称:中间任意插入的自定义章节完全自由放行
- 严格守护格式合规与数学总账守恒
用法:
python3 validate.py <report.md>
python3 validate.py <report.md> --json
"""
import os
import sys
import re
import json
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
REQUIRED_INFO_ROWS = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
FORBIDDEN_MARKS = [
(re.compile(r"<!--slot:"), "slot 标记"),
(re.compile(r"<!--/slot"), "slot 闭合"),
(re.compile(r"<!--@"), "@table/@block 区域标记"),
(re.compile(r"<!-- render:stop"), "render:stop 标记"),
(re.compile(r"\{\{"), "{{槽位}}"),
]
class ReportIssue:
def __init__(self, level: str, code: str, message: str, line: Optional[int] = None):
self.level = level # "ERROR" | "WARN"
self.code = code
self.message = message
self.line = line
def to_dict(self) -> Dict[str, Any]:
d: Dict[str, Any] = {"level": self.level, "code": self.code, "message": self.message}
if self.line is not None:
d["line"] = self.line
return d
class TableRow:
def __init__(self, line_num: int, cells: List[str]):
self.line_num = line_num
self.cells = cells
class ParsedTable:
def __init__(self, line_num: int, header: List[str], rows: List[TableRow]):
self.line_num = line_num
self.header = header
self.rows = rows
def split_cells(line: str) -> List[str]:
text = line.strip()
if text.startswith("|"):
text = text[1:]
if text.endswith("|") and not text.endswith(r"\|"):
text = text[:-1]
# Split on unescaped pipe
raw_cells = re.split(r"(?<!\\)\|", text)
return [c.replace(r"\|", "|").strip() for c in raw_cells]
def parse_tables(lines: List[str]) -> List[ParsedTable]:
result: List[ParsedTable] = []
i = 0
while i < len(lines):
line = lines[i].strip()
if i + 1 < len(lines):
separator = lines[i + 1].strip()
if line.startswith("|") and "-" in separator and re.match(r"^[|\-: ]+$", separator):
header = split_cells(line)
table = ParsedTable(line_num=i + 1, header=header, rows=[])
i += 2
while i < len(lines) and lines[i].strip().startswith("|"):
table.rows.append(TableRow(line_num=i + 1, cells=split_cells(lines[i])))
i += 1
result.append(table)
continue
i += 1
return result
def extract_numeric(text: str, is_percent: bool = False) -> Optional[float]:
pattern = r"(\d+(?:\.\d+)?)\s*%" if is_percent else r"(\d+(?:\.\d+)?)"
m = re.search(pattern, text)
if m:
try:
return float(m.group(1))
except ValueError:
return None
return None
def validate_report(filepath: str) -> Dict[str, Any]:
path = Path(filepath).resolve()
if not path.is_file():
return {
"file": str(path),
"valid": False,
"tables": 0,
"figures": 0,
"issues": [{"level": "ERROR", "code": "FS001", "message": f"文件不存在: {filepath}"}],
}
with open(path, "r", encoding="utf-8") as f:
text = f.read().replace("\r\n", "\n").replace("\r", "\n")
lines = text.split("\n")
issues: List[ReportIssue] = []
def add_error(code: str, message: str, line: Optional[int] = None):
issues.append(ReportIssue(level="ERROR", code=code, message=message, line=line))
# 1. 纯净性:严禁 Frontmatter 和 模板草稿占位标记
if text.startswith("---\n"):
add_error("FM001", "文件以 YAML frontmatter 开头;元数据请放正文开头的「报告信息」表格中", line=1)
for pattern, name in FORBIDDEN_MARKS:
for idx, l in enumerate(lines, start=1):
if pattern.search(l):
add_error("MK001", f"出现模板未渲染痕迹({name}),交付文件应为纯 Markdown 文档", line=idx)
# 2. 代码围栏成对闭合
fences = [idx for idx, l in enumerate(lines, start=1) if l.strip().startswith("```")]
if len(fences) % 2 != 0:
add_error("MD001", f"代码围栏为奇数(共 {len(fences)} 个),存在未闭合代码块", line=fences[-1] if fences else None)
# 3. 表格结构规范(列对齐、表头无加粗)
parsed_tables = parse_tables(lines)
for table in parsed_tables:
header_len = len(table.header)
for row in table.rows:
if len(row.cells) != header_len:
add_error("TB001", f"第 {row.line_num} 行表格列数 {len(row.cells)} ≠ 表头 {header_len} 列", line=row.line_num)
for cell in table.header:
if "**" in cell:
add_error("TB002", f"第 {table.line_num} 行表头含有加粗标记 **(表头应保持纯文本)", line=table.line_num)
# 4. 标题层级与章节序号连续性
previous_level = 0
numbered_h2s: List[Tuple[int, str, int]] = [] # (chapter_num, full_heading, line_num)
chapters: List[Dict[str, Any]] = []
for idx, l in enumerate(lines, start=1):
m = re.match(r"^(#{1,6})\s+(.*)$", l)
if not m:
continue
level = len(m.group(1))
heading_text = m.group(2).strip()
if previous_level > 0 and level > previous_level + 1:
add_error("HD001", f"标题层级跳级(从 H{previous_level} 直接跳到 H{level}):{heading_text[:40]}", line=idx)
previous_level = level
if level == 2:
num_match = re.match(r"^(\d+)\.", heading_text)
if num_match:
numbered_h2s.append((int(num_match.group(1)), heading_text, idx))
chapters.append({"heading": heading_text, "start_line": idx, "line_num": idx})
# 检查大标题数字是否严格连续递增:1, 2, 3...
if numbered_h2s:
seen_nums = [item[0] for item in numbered_h2s]
expected_nums = list(range(1, len(seen_nums) + 1))
if seen_nums != expected_nums:
add_error("HD002", f"## 大章节编号应自 1 开始连续递增,期望 {expected_nums},实际 {seen_nums}", line=numbered_h2s[0][2])
# 为每个大章节划分文本切片(从当前 ## 到下一个 ##)
for i, chap in enumerate(chapters):
start_idx = chap["start_line"] - 1
end_idx = chapters[i + 1]["start_line"] - 1 if i + 1 < len(chapters) else len(lines)
chap["text"] = "\n".join(lines[start_idx:end_idx])
def find_chapter_by_keyword(kw: str) -> Optional[Dict[str, Any]]:
for c in chapters:
if kw in c["heading"]:
return c
return None
def by_header_in_scope(keyword: str, scope_lines: Optional[List[str]] = None) -> Optional[ParsedTable]:
target_tables = parse_tables(scope_lines) if scope_lines is not None else parsed_tables
for t in target_tables:
header_str = "".join(t.header).replace(" ", "")
if keyword in header_str:
return t
return None
# 5. 开篇「报告信息」表完备性
info_table = by_header_in_scope("报告信息")
if not info_table:
add_error("INFO001", "缺少开篇「报告信息」表(必须包含客户名称、期间、报告编号等元数据)")
else:
existing_keys = {r.cells[0] for r in info_table.rows if r.cells}
missing_keys = [k for k in REQUIRED_INFO_ROWS if k not in existing_keys]
if missing_keys:
add_error("INFO001", f"「报告信息」表缺少必要字段:{', '.join(missing_keys)}", line=info_table.line_num)
empty_keys = [r.cells[0] for r in info_table.rows if len(r.cells) > 1 and not r.cells[1].strip()]
if empty_keys:
add_error("INFO002", f"「报告信息」表以下字段值为空:{', '.join(empty_keys)}", line=info_table.line_num)
# 6. 本地图片资产存活性
figure_count = 0
for idx, l in enumerate(lines, start=1):
for img_match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", l):
figure_count += 1
src = img_match.group(1).strip()
if src.startswith("http://") or src.startswith("https://") or src.startswith("data:"):
continue
# 解码 URL 编码的中文路径
try:
import urllib.parse
decoded_src = urllib.parse.unquote(src)
except Exception:
decoded_src = src
target_path = (path.parent / decoded_src).resolve()
if not target_path.exists():
add_error("IMG001", f"本地引用的图片文件不存在:{src}", line=idx)
# 7. 核心业务章节硬匹配校验与数学总账守恒
# 7.1 【AI 失准分析】核心章节
mismatch_chapter = find_chapter_by_keyword("失准")
if mismatch_chapter:
c_lines = mismatch_chapter["text"].split("\n")
table = by_header_in_scope("失准类型", c_lines)
if table:
tops = []
totals = []
for r in table.rows:
if len(r.cells) > 3:
if r.cells[0].startswith("TOP"):
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
elif r.cells[0] in ["合计", "总计", "—"]:
totals.append(extract_numeric(r.cells[3]))
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
s = sum(t["count"] for t in tops if t["count"] is not None)
if s != totals[0]:
add_error("NM001", f"失准类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
base = totals[0]
for r in table.rows:
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
share = extract_numeric(r.cells[2], is_percent=True)
count = extract_numeric(r.cells[3])
if share is not None and count is not None and base > 0:
calc_share = (count / base) * 100
if abs(calc_share - share) > 0.15:
add_error("NM003", f"失准类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
# 校验小节标题张数与总览表严格一致
for top in tops:
esc = re.escape(top["name"])
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", mismatch_chapter["text"])
if m and top["count"] is not None:
c_in_h = int(m.group(1))
if c_in_h != int(top["count"]):
add_error("NM001", f"失准分析 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
# 7.2 【AI 发现的潜在风险】核心章节
risk_chapter = find_chapter_by_keyword("风险")
if risk_chapter:
c_lines = risk_chapter["text"].split("\n")
table = by_header_in_scope("风险类型", c_lines)
if table:
tops = []
totals = []
for r in table.rows:
if len(r.cells) > 3:
if r.cells[0].startswith("TOP"):
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
elif r.cells[0] in ["合计", "总计", "—"]:
totals.append(extract_numeric(r.cells[3]))
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
s = sum(t["count"] for t in tops if t["count"] is not None)
if s != totals[0]:
add_error("NM002", f"风险类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
base = totals[0]
for r in table.rows:
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
share = extract_numeric(r.cells[2], is_percent=True)
count = extract_numeric(r.cells[3])
if share is not None and count is not None and base > 0:
calc_share = (count / base) * 100
if abs(calc_share - share) > 0.15:
add_error("NM003", f"风险类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
for top in tops:
esc = re.escape(top["name"])
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", risk_chapter["text"])
if m and top["count"] is not None:
c_in_h = int(m.group(1))
if c_in_h != int(top["count"]):
add_error("NM002", f"潜在风险 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
# 7.3 【审核分歧与复核归因】核心章节
diverged_chapter = find_chapter_by_keyword("分歧") or find_chapter_by_keyword("复核归因")
if diverged_chapter:
c_lines = diverged_chapter["text"].split("\n")
table = by_header_in_scope("原因分类", c_lines)
if table:
count_idx = -1
for ci, col in enumerate(table.header):
if "单数" in col:
count_idx = ci
break
if count_idx >= 0:
rows = [r.cells for r in table.rows]
non_totals = [r for r in rows if r and r[0] not in ["合计", "总计", "—"]]
total_row = next((r for r in rows if r and r[0] in ["合计", "总计", "—"]), None)
s = sum(extract_numeric(r[count_idx]) or 0 for r in non_totals if len(r) > count_idx)
if total_row and len(total_row) > count_idx:
tv = extract_numeric(total_row[count_idx])
if tv is not None and s != tv:
add_error("NM004", f"原因分类各维度单数之和 {s} ≠ 合计 {tv}", line=table.line_num)
# 7.4 LaTeX 公式算术自洽
formula_lines = [l for l in lines if l.strip().startswith("$$")]
outside_text = "\n".join([l for l in lines if not l.strip().startswith("$$")])
for fl in formula_lines:
for frac_match in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", fl):
a = int(frac_match.group(1))
b = int(frac_match.group(2))
pct_val = float(frac_match.group(3))
if b > 0:
real_pct = (a / b) * 100
if abs(real_pct - pct_val) > 0.05:
add_error("NM005", f"公式 \\frac{{{a}}}{{{b}}} = {pct_val}% 算术不成立(实为 {real_pct:.2f}%)")
for num_token in re.findall(r"\d+(?:\.\d+)?", fl):
if num_token not in outside_text:
add_error("NM005", f"公式中的数值 {num_token} 在正文别处找不到,可能与实际数据脱节")
return {
"file": str(path),
"valid": len(issues) == 0,
"tables": len(parsed_tables),
"figures": figure_count,
"issues": [i.to_dict() for i in issues],
}
def main():
if len(sys.argv) < 2 or sys.argv[1] in ["-h", "--help"]:
print("用法: python3 validate.py <report.md> [--json]")
print("说明: 离线静态校验 AI 审核报告 Markdown 文档的结构纯净度与数学总账守恒。")
sys.exit(0)
target_file = sys.argv[1]
is_json = "--json" in sys.argv
result = validate_report(target_file)
if is_json:
print(json.dumps(result, ensure_ascii=False, indent=2))
else:
status_symbol = "✅" if result["valid"] else "❌"
print(f"\n{status_symbol} 报告文件: {result['file']}")
print(f"📊 识别表格: {result['tables']} 个 | 配图资产: {result['figures']} 个")
if result["valid"]:
print("🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。\n")
sys.exit(0)
else:
print(f"⚠️ 发现 {len(result['issues'])} 项格式或勾稽问题,必须修正后方可交付:\n")
for i, issue in enumerate(result["issues"], 1):
loc = f" [第 {issue['line']} 行]" if "line" in issue else ""
print(f" {i}. [{issue['code']}]{loc} {issue['message']}")
print("\n💡 提示:请根据上述提示调整对应行的数字或表格结构,直至校验通过。\n")
sys.exit(1)
if __name__ == "__main__":
main()
-8
View File
@@ -27,14 +27,6 @@ const files = walk(skillRoot).map((fullPath) => ({
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
}));
// The skill's report reference is owned by the repository too; install it without maintaining a second copy.
const reportReadme = resolve(root, "src", "domains", "seal", "reports", "templates", "README.md");
files.push({
fullPath: reportReadme,
relativePath: "references/report-templates.md",
importPath: relative(resolve(root, "src", "core"), reportReadme).split("\\").join("/"),
kind: "text"
});
const lines = [
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
+20 -7
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.6: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.8: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.6
short-description: Seal tenant and Hose approval automation (v0.11.6)
version: 0.11.8
short-description: Seal tenant and Hose approval automation (v0.11.8)
---
# Seal Use
@@ -136,22 +136,34 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
## 月度审核准确率报告
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
推荐通过轻量数据包 + Agent 协同填写的模式,彻底解耦数据与模板(亦兼容一键脚手架模式):
```bash
# 模式 A (推荐轻量数据驱动): 提取当月纯结构化数据 (指标、分模板统计、待复核分歧单及具体触发条件)
seal-use report data --month <YYYY-MM> --corp <corpId>
# 保存纯净模板骨架
seal-use report template --out reports/报告.md
# 独立生成动态维恩图 SVG
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/报告.assets/图1-准确率对比.svg
# 模式 B (传统模板脚手架): 一键生成初步替换的 Markdown 与配图包
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
# 离线校验与全格式编译导出
seal-use report validate reports/报告.md
seal-use report render reports/报告.md --out build/报告
```
按模板结构(内置 `monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- **报告并非一键黑盒交付(人机协同研讨契约)**:数据接口无法自动获得“谁对谁错”的仲裁定性,也无法自动撰写管理归因与整改建议。生成初版 Markdown 后,Agent **严禁直接向客户交付带有 `> ⚠️ 数据说明` 警告框、模板假单号或 `(截图)` 占位符的半成品**,必须进入人机协同研讨模式(Tangent),向用户呈现分歧单据并共创定性分析文本。完整研讨流程、各章节动静边界与校验错误码见 `references/report-templates.md`。
- **推荐轻量 Agent 执笔**:调用 `seal-use report data` 获取干净的 JSON 数据包(含触发的单个判断条件 `triggeredConditions`),由 Agent 亲自将真实数据与复核分析填入 Markdown,避免代码层正则换数的死板与脆弱。
- **模板是可变的皮,以用户态度为最高准则**:大章节(§1~§6)是必选论证骨架,但具体问题分类(TOP 1~N,至少保留 1 个)、案例行数、表格列数均由当期数据与用户意图动态决定,严禁 Agent 固执教条(如机械死板凑满 3 类或 3 行);案例详情链接由管线全自动注入,Markdown 源码只聚焦业务内容。详见 `references/report-templates.md`。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,初稿保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
- 只读能力 `sealReportDataGet` / `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
### 人工裁决回填(算出人工审核准确率)
@@ -169,3 +181,4 @@ seal-use report review list --month <YYYY-MM> --corp <corpId>
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
- **协同研讨指南**:呈报分歧单据供用户裁决时,必须附带 Seal AI 审核页与合思原单据的双端直达链接(`approval-runs url --auto-login` / `hose-use bill link`);分歧单据挑选格式、失准归因撰写(§2)、分歧概览(§5)与严格离线校验(NM001~NM005)排查手册,完整参见 `references/report-templates.md`。
@@ -0,0 +1,178 @@
# 月度 AI 审核报告编制与人机协同作业指南 (Monthly Report Authoring & Tangent Workflow)
本文档面向 **AI Agent 与操作用户**,规范从**月度数据拉取**、**分歧单据人机复核研讨(Tangent)**、**Agent 自主理解与填报**,到**严格离线门禁校验、全格式渲染与多轮修改**的端到端人机协同闭环。
---
## 核心认知与人机分工 (Core Division of Labor)
1. **确定性工具管线 + Agent 智能执笔**:
- **工具层 (`seal-use`)**:提供确定性提数(`report data`)、裁决记录(`review set`)、矢量图表(`report chart venn`)、离线格式与勾稽门禁(`report validate`)、全格式渲染(`report render`)及全量明细台账(`《明细台账.xlsx》`)。
- **Agent 层(智能分析与自主撰写)**:Agent 最擅长理解数据、归纳归因并与用户对话。Agent 调取结构化数据包与模板骨架,结合用户裁决意见,亲自将真实数据、原因分类与业务建议填入 Markdown,彻底摆脱死板的模板脚本限制。
2. **人机对齐与裁决研讨 (Review Tangent)**:
- 当 AI 与人工判定结论不一致时,Agent 绝不凭空主观臆断,而是从数据包中提取关键分歧单(含单号、AI摘要、触发的具体规则卡口 `triggeredConditions`),主动在聊天窗口向用户征询对错裁决定性。
3. **必须通过格式门禁校验 (Zero-Error Gate)**:
- 严禁交付未经校验的 Markdown。Agent 在调用 `render` 渲染前,**必须执行 `seal-use report validate`**。若有报错,Agent 需读取报错 issue 自纠自查,修正格式与数字勾稽,直到 100% 通过。
4. **即时渲染与多轮反馈修改**:
- 渲染出的 HTML、A4 PDF 和高清长图交由用户审查。用户提出调整意见后,Agent 微调 Markdown,再次过门禁校验并重新渲染,完成多轮敏捷迭代。
---
## 端到端人机协同五步闭环 (The 5-Stage Lifecycle)
```mermaid
flowchart TD
S1["第一步:拉取结构化数据与模板骨架<br/>(report data & report template)"] --> S2["第二步:分歧单据人机裁决研讨<br/>(Agent 汇报分歧,用户给出定性)"]
S2 --> S3["第三步:Agent 结合理解自主撰写报告<br/>(撰写结构化 Markdown 报告草稿)"]
S3 --> S4["第四步:离线格式与数学勾稽门禁<br/>(report validate 质检拦截与自纠)"]
S4 --> S5["第五步:全格式渲染与多轮修改迭代<br/>(report render 产出交付,根据用户意见微调)"]
```
---
### 第一步:获取结构化数据包与模板骨架
1. **拉取当月纯结构化业务数据包 (JSON)**:
```bash
seal-use report data --month <YYYY-MM> --corp <corpId>
```
*输出说明:返回纯 JSON,包含全月样本量、AI 准确率、采纳率、平均耗时、公式代入值、分模板统计、TOP 风险标签,以及全量分歧单据池(`divergedRuns`)。*
2. **导出纯净标准模板骨架**:
```bash
seal-use report template --out reports/<企业名>-<YYYYMM>.md
```
3. **动态生成准确率维恩图**:
```bash
mkdir -p reports/<企业名>-<YYYYMM>.assets
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
```
---
### 第二步:分歧单据人机复核研讨 (Diverged Runs Review)
当 `reviews.divergedUnreviewedCount > 0` 时,存在 AI 放行但人工驳回、或 AI 驳回但人工放行的分歧单据。Agent 需主动在聊天中向用户汇总呈报并征询裁决。
**双链穿透规范 (Dual-Link Fast Traversal)**:
呈报给用户裁决的每笔典型案例,Agent **必须同时生成并附带双端直达链接**,严禁让用户盲猜或手动去系统里翻查单据:
- **🔗 Seal AI 审核页直达**:调用 `seal-use approval-runs url --sn <SN> --auto-login` 生成带临时免密凭证的直达链接,一键跳转到 Seal AI 查看完整判定快照、引用规则、卡口明细与 LLM 推理过程;
- **📑 合思/易快报原单据直达**:调用 `hose-use bill link <SN>` 或从运行记录 `sourceExtendData.hosecloudViewUrl` 提取原单据 Web 链接,一键直达合思原单据查看发票原件影像、业务附件与人工审批操作历史。
1. **结构化向用户呈现典型案例**:
```markdown
【分歧单据复核确认】单号:FP2608010
- 单据模板:发票-个人报销
- 快速核验:[🔗 Seal AI 审核详情](https://<corp>.sealai.cc/approval-result/<recordId>) | [📑 合思原单据](https://wx2.ekuaibao.com/...)
- AI 审核结论:同意(单据附件与发票齐全合规,满足既定规则)
- 人工实际操作:驳回/终止(批注:口头超标)
- 触发条件:现行线上规则库无该超标阻断规则
👉 请教您对本单的裁决:
1. AI 依规正确(ai_correct):按线上规则库合规放行,人工属于口头加码标准;
2. 人工正确 / AI 失准(human_correct):业务实际存在超标限制,属于 AI 误判或规则未覆盖;
3. 双方都对(both_correct):规则执行正确,但有线下特殊处理。
```
2. **将用户意见持久化录入复核账本**:
```bash
seal-use report review set \
--month <YYYY-MM> \
--sn <单号> \
--verdict <ai_correct|human_correct|both_correct> \
--note "口头加码标准,现行线上规则库未配置" \
--corp <corpId>
```
---
### 第三步:Agent 结合数据与裁决自主撰写
Agent 调取模板,结合数据包与用户裁决定性,自主撰写全新的 6 章节 Markdown:
* **§1 审核测试结果**:填入企业名称、账期、样本总量、AI 准确率、人工准确率公式及维恩图。
* **§2 AI 失准分析**:将真实的错判单据填入 TOP 1~3 小节,写出针对性整改方案。
* **§3 AI 发现的潜在风险**:列出 AI 在人工通过单据中额外识别出的票据、预付与凭证风险。
* **§4 综合效益**:填入时效、准确度、拦截笔数等宏观关键数据。
* **§5 审核分歧与复核归因**:
- 填入分类统计表(如“未在线配置规则 66.7% / AI 识别偏差 33.3%”);
- 总结管理建议(推动口头标准线上化规则沉淀);
- 明确引导用户查看随包附带交付的《明细台账.xlsx》核对逐单流水。
* **§6 支撑数据与交付材料**:
- 6.1 分模板准确率与自动审批率表格;
- 6.2 配套交付的《明细台账.xlsx》说明。
---
### 第四步:离线门禁格式与勾稽校验 (Validate)
在执行最终渲染前,Agent **必须**执行门禁校验命令:
```bash
seal-use report validate reports/<企业名>-<YYYYMM>.md
```
#### 门禁校验重点关注项:
- **`HD001` / `HD002`**:二级章节编号必须自 1 开始连续递增(`## 1.`, `## 2.`, ..., `## 6.`),不得跳级。
- **`TB001` / `TB002`**:表格列数前后严格一致,表头行严禁带加粗 `**` 标记。
- **`NM001` / `NM002`**:失准与风险总览表中的各分项张数之和必须严格等于合计行。
- **`NM004`**:分歧原因分类表中的各单数与正文叙述中的笔数必须完全勾稽。
- **`NM005`**:准确率公式(如 `\frac{221}{240} = 92.08\%`)算术必须成立,且数值在正文中必须能找到对应数据来源。
- **`INFO001` / `INFO002`**:开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。
> ⚠️ 若返回 `valid: false`,Agent 必须读取报错列表中的 `code` 和 `message`,**自主编辑修正 Markdown**,直到再次校验返回 `valid: true`。
---
### 第五步:全格式渲染与多轮修改迭代 (Render & Iterate)
1. **一键编译渲染全套交付产物**:
```bash
seal-use report render reports/<企业名>-<YYYYMM>.md --out build/<企业名>-<YYYYMM> --format all
```
*产物包含:单文件自包含 HTML、A4 打印排版 PDF、4x 超高清拼接长图 PNG。*
2. **呈现给用户并接收修改意见**:
- Agent 将渲染后的成果与核心数据摘要反馈给用户;
- 用户审查后提出调整(如“某段原因描述请改一下”、“风险小节增加具体发票案例”);
- Agent 直接在 Markdown 文件中微调,再次运行 `report validate` 确保无勾稽错误,然后重新 `report render` 刷新交付。
---
## 模板 6 大标准章节剖析 (Section Anatomy)
| 章节编号与名称 | 数据来源与机制 | 说明与核心关注点 |
| :--- | :--- | :--- |
| **标题与报告信息表** | 数据填充 | 包含企业名称、账期、生成日期、草稿状态与唯一报告编号。 |
| **摘要** | 动态提炼 | 提炼全月单量、核心准确率与额外发现的合规风险笔数。 |
| **§1 审核测试结果** | 核心数据 | 1.1 数据来源与样本总量;1.2 准确率结论、计算公式与图 1 维恩图。 |
| **§2 AI 失准分析** | 深度归因 | 2.1 失准构成总览;2.2~2.4 TOP 失准真实案例与调优解决方案。 |
| **§3 AI 发现的潜在风险** | 价值体现 | 3.1 风险构成总览;3.2~3.4 缺失凭证、大额预付、专票违规等真实拦截。 |
| **§4 综合效益** | 数据汇总 | 准确度、时效(平均秒数)、风险拦截量与人力释放宏观汇总表。 |
| **§5 审核分歧与复核归因** | 概览归因 | 人机分歧分类统计(线上规则未覆盖 vs 识别偏差),引导查验《明细台账.xlsx》。 |
| **§6 支撑数据与交付材料** | 支撑底账 | 6.1 各模板准确率与自动化率;6.2 交付文件说明(明细台账 Excel/CSV)。 |
---
## 动态自适应与用户至上原则 (Dynamic Adaptability & User-Centric Principles)
为避免后续使用的 AI Agent 产生死板教条(“非要凑满 3 类问题”、“非要放满 3 行”、“强行增加冗余列”等固执偏见),特此确立以下人机协同规范:
### 1. 必选骨架 vs 动态子部分的边界
* **大章节是不可缺少的骨架**:§1~§6 大章节承载了完整严谨的商业论证闭环(业绩证明、失准坦白、额外价值、分歧归因、支撑台账),必须存在。
* **章节内部的子部分完全动态**:
* 例如 §2(失准分析)与 §3(潜在风险)下的具体问题分类,**数量完全由实际跑批结果与用户业务关注度决定**。
* **唯一硬性底线**:动态章节下**至少保留 1 个子分类**(不能是无正文的空标题),可以是 TOP 1~2、TOP 1~3 或扩展至 TOP 1~5。
* **数学自洽守恒**:无论列出几种分类,分类表中的单数之和必须严格等于「合计」行单数,且百分比之和严格等于 100%(`NM001`~`NM003`)。
### 2. 用户态度为最高准则 (User Preference First)
* **严禁 Agent 固执己见**:Agent 必须以用户的业务判断与汇报习惯为首要输入。如果用户要求“重点只突出 2 个主要风险”、“案例只放 1 个最具代表性的单据”,Agent 必须立即响应调整,不得机械搬用模板默认的 3 分类或 3 行案例。
* **文字叙述灵活定性**:针对失准单据的“解决方案”与分歧归因的“管理建议”,Agent 需结合具体企业的管理要求与规则实际情况有针对性地撰写,杜绝空话套话。
### 3. 表格案例与跳转超链接免维护契约
* **Markdown 源码专注业务语义**:用户与 Agent 在编写或编辑 Markdown 报告草稿时,无需在源码中手动维护长串技术 URL,保持干净易读(如常规的 `| 单号 | 问题描述 |`)。
* **自动化链接注入机制**:
* **2 列模式**:若表格只有两列,管线在填充真实数据时会自动将第一列单号升级为跳转链接 `[SN](https://<corp>.sealai.cc/approval-result/<recordId>)`。
* **3 列模式**:若表头显式声明了 `审核详情` 或 `链接` 列,管线会自动在第 3 列生成 `[👉 查看详情](https://...)`。
* **跨端交付表现**:单文件自包含 HTML 与 A4 排版 PDF 均天然支持在浏览器或 PDF 阅读器中一键点击穿透直达系统后台;长图 PNG 为纯像素光栅位图,主要用于 IM 聊天窗口内快速滑动预览。
+54 -3
View File
@@ -1,3 +1,5 @@
import { writeFileSync } from "node:fs";
import { resolve } from "node:path";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapabilityResult } from "../helpers.js";
@@ -5,8 +7,10 @@ import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import { CliError, usageError } from "../../core/errors.js";
import {
BUILTIN_MONTHLY_TEMPLATE,
exportReportPackage,
renderReportFile,
renderVennAccuracySvg,
saveReportMarkdown,
validateReportFile,
loadReviews,
@@ -17,7 +21,35 @@ import {
import type { ParsedArgs } from "../types.js";
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
export async function handleLocalReportCommand(action: "validate" | "render" | "export", args: ParsedArgs) {
export async function handleLocalReportCommand(action: "validate" | "render" | "export" | "template" | "chart", args: ParsedArgs) {
if (action === "template") {
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
writeFileSync(resolve(out), BUILTIN_MONTHLY_TEMPLATE, "utf8");
printJson({ file: resolve(out), size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
} else {
printJson({ content: BUILTIN_MONTHLY_TEMPLATE, size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
}
return;
}
if (action === "chart") {
const sub = args.command[2];
if (sub !== "venn") throw usageError("Usage: seal-use report chart venn --ai <accuracy> --human <accuracy> [--both <accuracy>] [--out <file.svg>]");
const ai = numberOption(args.options.ai) ?? numberOption(args.options["ai-accuracy"]) ?? 92.08;
const human = numberOption(args.options.human) ?? numberOption(args.options["human-accuracy"]) ?? 83.33;
const both = numberOption(args.options.both) ?? numberOption(args.options["both-accurate"]) ?? 75.42;
const svg = renderVennAccuracySvg({ aiAccuracy: ai, humanAccuracy: human, bothAccurate: both });
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
writeFileSync(resolve(out), svg, "utf8");
printJson({ file: resolve(out), format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, size: Buffer.byteLength(svg) }, outputOptions(args.options));
} else {
printJson({ format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, svg }, outputOptions(args.options));
}
return;
}
const file = args.command[2] ?? stringOption(args.options.file);
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : action === "export" ? " --out <目标文件夹>" : ""}`);
if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。");
@@ -46,13 +78,31 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
}
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
export async function handleReportCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "data") {
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]");
}
const result = await runCapabilityResult(
"sealReportDataGet",
client,
corp,
{
month,
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
}
);
printJson(result, outputOptions(args.options));
return;
}
if (action === "monthly" || action === "month") {
const month = stringOption(args.options.month);
if (!month) {
@@ -66,7 +116,8 @@ export async function handleReportCommand(
month,
templatePath: stringOption(args.options.template),
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns),
allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force)
}
) as MonthlyReportResult;
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
+34 -2
View File
@@ -622,18 +622,50 @@ export const HELP_REGISTRY: AreaHelp[] = [
title: "Monthly audit accuracy reports",
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
commands: [
{
name: "data",
summary: "Extract pure structured report data, metrics, diverged runs, and triggers without templates",
usage: ["seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
],
description: "Template-free data pack for Agent authoring: returns performance metrics, formula fractions, template groups, top risk tags, diverged runs with exact triggered conditions, and reviews."
},
{
name: "template",
summary: "Dump or save the built-in monthly report Markdown template",
usage: ["seal-use report template [--out <file.md>]"],
options: [
{ flag: "--out <file>", description: "Save built-in Markdown template directly to a file" }
],
description: "Tenant-free local command: returns or saves the built-in monthly.md template so an Agent or user can co-author."
},
{
name: "chart venn",
summary: "Generate dynamic Venn accuracy comparison SVG chart independently",
usage: ["seal-use report chart venn --ai <acc> --human <acc> [--both <both>] [--out <file.svg>]"],
options: [
{ flag: "--ai <acc>", description: "AI accuracy percentage (e.g. 92.08)" },
{ flag: "--human <acc>", description: "Human accuracy percentage (e.g. 83.33)" },
{ flag: "--both <both>", description: "Both accurate percentage (e.g. 75.42)" },
{ flag: "--out <file>", description: "Save SVG directly to file" }
],
description: "Tenant-free local command: calculates proportions and outputs high-fidelity SVG chart."
},
{
name: "monthly",
aliases: ["month"],
summary: "Fill the monthly report template with performance, risk, and approval-run data",
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--allow-unreviewed] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" },
{ flag: "--out <file>", description: "Save Markdown plus local images beside the report; stdout stays JSON (without the content field)" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" },
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" },
{ flag: "--allow-unreviewed", description: "Bypass pre-flight adjudication gate to generate draft when unreviewed diverged runs exist" }
],
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
},
+7 -7
View File
@@ -23,7 +23,7 @@ import { usageError } from "./errors.js";
// Read with booleanOption(...) / Boolean(...) / presence check.
export const BOOLEAN_FLAGS = new Set([
"V", "add", "all", "as-hose", "attachments", "auto",
"V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
@@ -40,8 +40,8 @@ export const BOOLEAN_FLAGS = new Set([
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
"channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
@@ -51,7 +51,7 @@ export const VALUE_FLAGS = new Set([
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "humanResult", "id", "input", "integration",
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
@@ -86,10 +86,10 @@ export const VALUE_FLAGS = new Set([
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "add", "all", "app-key",
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
@@ -103,7 +103,7 @@ export const KNOWN_FLAGS = new Set([
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
+1 -1
View File
@@ -79,7 +79,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
analytics: ["insight", "risks", "performance", "export"],
report: ["monthly", "validate", "render", "review list"],
report: ["monthly", "data", "template", "chart venn", "validate", "render", "review list"],
source: ["config"],
skill: ["dump", "status"],
doctor: ["", "guide", "paths", "tenant", "auth"],
+1 -1
View File
@@ -224,7 +224,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "report" && (action === "validate" || action === "render" || action === "export")) {
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
return;
}
+11 -11
View File
@@ -19,11 +19,11 @@ import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" wi
import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file23 from "../domains/seal/reports/templates/README.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -39,11 +39,11 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/hose-enterprise-deploy.md": file16,
"references/hose-enterprise-init.md": file17,
"references/langfuse-trace.md": file18,
"references/rule-lightweight.md": file19,
"references/rule-lint.md": file20,
"references/staging-simulation-workflow.md": file21,
"references/webhook-resource-pack.md": file22,
"references/report-templates.md": file23,
"references/report-templates.md": file19,
"references/rule-lightweight.md": file20,
"references/rule-lint.md": file21,
"references/staging-simulation-workflow.md": file22,
"references/webhook-resource-pack.md": file23,
};
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
@@ -75,9 +75,9 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/hose-enterprise-deploy.md",
"references/hose-enterprise-init.md",
"references/langfuse-trace.md",
"references/report-templates.md",
"references/rule-lightweight.md",
"references/rule-lint.md",
"references/staging-simulation-workflow.md",
"references/webhook-resource-pack.md",
"references/report-templates.md",
];
+36 -11
View File
@@ -465,7 +465,18 @@ export const approvalRunsCapabilities = [
}
const record = await resolveApprovalRunForUrl(client, params);
const source = context.corp.source;
const hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
let hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
const flowId = record?.sourceDocumentId;
if (hoseDocumentUrl) {
if (flowId && hoseDocumentUrl.includes("backlogId=") && !hoseDocumentUrl.includes("#/")) {
hoseDocumentUrl = `${hoseDocumentUrl}#/backlogDetail/false/${encodeURIComponent(flowId)}`;
}
} else if (source.type === "hose" && flowId) {
const hoseDomain = normalizeUrl(source.domain);
const encodedFlowId = encodeURIComponent(flowId);
const corpId = encodeURIComponent(source.corpId);
hoseDocumentUrl = `${hoseDomain}/web/thirdparty.html?ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${encodedFlowId}&backlogId=#/backlogDetail/false/${encodedFlowId}`;
}
const sealBaseUrl = resolveSealBaseUrl(context.corp);
const sealResultUrl = `${sealBaseUrl}/approval-result/${record.id}`;
@@ -478,13 +489,12 @@ export const approvalRunsCapabilities = [
const expiresIn = params.expiresIn ?? 7200;
let ssoUrl: string | undefined;
let sealSsoUrl: string | undefined;
let hoseSsoUrl: string | undefined;
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
let warning: string | undefined;
if (useAutoLogin) {
if (isHoseDoc) {
throw new Error("Auto-login (--auto-login) is only supported for Seal AI audit links (type: seal-result). To generate an auto-login link for Hose document page, please use: seal-use auth hose-link");
}
if (source.type !== "hose") {
throw new Error(
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
@@ -498,7 +508,17 @@ export const approvalRunsCapabilities = [
}
const targetPath = `/approval-result/${record.id}`;
ssoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
sealSsoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
if (record?.sourceDocumentId) {
const hoseDomain = normalizeUrl(source.domain);
const flowId = encodeURIComponent(record.sourceDocumentId);
const corpId = encodeURIComponent(source.corpId);
const token = encodeURIComponent(provisionalToken);
hoseSsoUrl = `${hoseDomain}/web/thirdparty.html?accessToken=${token}&ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${flowId}&backlogId=#/backlogDetail/false/${flowId}`;
}
ssoUrl = isHoseDoc ? (hoseSsoUrl ?? sealSsoUrl) : sealSsoUrl;
try {
const me = await api.getMe(client);
@@ -516,18 +536,21 @@ export const approvalRunsCapabilities = [
const userName = identity.name ?? "企业成员";
const roleLabel = identity.isAdmin ? " (管理员)" : "";
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
const targetSystem = isHoseDoc ? "合思 (Hose)" : "Seal AI";
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 ${targetSystem} 拥有对应操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
console.error(
`⚠️ 安全警示 (免密直达链接):\n` +
`• 身份主体:${userName}${roleLabel}\n` +
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
`• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!`
`• 目标系统:${targetSystem}\n` +
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留会话\n` +
`• 安全边界:仅限内部排查,严禁在外部公开分享!`
);
}
const activeUrl = isHoseDoc ? hoseDocumentUrl : (useAutoLogin ? ssoUrl : sealResultUrl);
const activeUrl = isHoseDoc
? (useAutoLogin ? (hoseSsoUrl ?? hoseDocumentUrl) : hoseDocumentUrl)
: (useAutoLogin ? sealSsoUrl : sealResultUrl);
const activeMode = useAutoLogin ? "auto_login" : "direct";
return {
@@ -536,6 +559,8 @@ export const approvalRunsCapabilities = [
mode: activeMode,
sealResultUrl,
hoseDocumentUrl,
sealSsoUrl,
hoseSsoUrl,
// Legacy compatibility fields
documentUrl: hoseDocumentUrl,
ssoUrl,
@@ -549,7 +574,7 @@ export const approvalRunsCapabilities = [
sourceSystem: record.sourceSystem,
missing: {
hoseDocumentUrl: !hoseDocumentUrl
? `该审批运行未回写 hosecloudViewUrl,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
? `该审批运行未回写 hosecloudViewUrl 且缺少 sourceDocumentId,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
: undefined
}
};
@@ -892,6 +892,52 @@ describe("sealCapabilities", () => {
expect(result.sealResultUrl).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
});
test("approval run url synthesizes hoseDocumentUrl from source.domain and sourceDocumentId when hosecloudViewUrl is missing", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
expect(tool).toBeDefined();
const handler = tool!.handler as CapabilityHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ recordId: "run-2" },
fakeHoseContext()
) as {
hoseDocumentUrl?: string;
documentUrl?: string;
sealResultUrl?: string;
missing?: Record<string, string>;
};
const expectedHoseUrl = "https://app.ekuaibao.com/web/thirdparty.html?ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
expect(result.hoseDocumentUrl).toBe(expectedHoseUrl);
expect(result.documentUrl).toBe(expectedHoseUrl);
expect(result.missing?.hoseDocumentUrl).toBeUndefined();
});
test("approval run url supports auto-login for hose-document", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
expect(tool).toBeDefined();
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
const handler = tool!.handler as CapabilityHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ recordId: "run-2", type: "hose-document", autoLogin: true },
fakeHoseContext()
) as {
url?: string;
hoseSsoUrl?: string;
type?: string;
mode?: string;
};
const expectedSsoUrl = "https://app.ekuaibao.com/web/thirdparty.html?accessToken=close-token&ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
expect(result.type).toBe("hose_document");
expect(result.mode).toBe("auto_login");
expect(result.url).toBe(expectedSsoUrl);
expect(result.hoseSsoUrl).toBe(expectedSsoUrl);
});
test("approval run url throws error without a document lookup", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
expect(tool).toBeDefined();
@@ -1170,6 +1216,55 @@ describe("sealCapabilities", () => {
});
});
test("sealReportDataGet returns lightweight structured report data payload", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealReportDataGet");
expect(tool).toBeDefined();
const handler = tool!.handler as CapabilityHandler;
const mockClient = {
get: async () => ({
json: async () => ({
data: {
records: [
{
id: "run-rep-1",
sourceDocumentSN: "SN-001",
result: { decision: "REJECT", summary: "缺失发票", riskPoints: ["缺失发票"] },
pipelineData: { humanResult: "APPROVE" },
document: { fields: [{ key: "specificationId", value: "差旅报销" }] }
}
],
total: 1
}
})
}),
post: async () => ({
json: async () => ({
data: {
approvalCount: 1,
accuracy: 0,
automationRate: 0,
riskCount: 1,
avgDuration: 15
}
})
})
} as unknown as KyInstance;
const res = await handler(mockClient, { month: "2026-08" }, fakeContext()) as {
period: { month: string };
metrics: { approvalCount: number; aiAccuracy: number };
divergedRuns: Array<{ sn: string; triggeredConditions: string[] }>;
charts: { vennSvg: string };
};
expect(res.period.month).toBe("2026-08");
expect(res.metrics.approvalCount).toBe(1);
expect(res.divergedRuns).toHaveLength(1);
expect(res.divergedRuns[0]?.sn).toBe("SN-001");
expect(res.divergedRuns[0]?.triggeredConditions).toContain("缺失发票");
expect(res.charts.vennSvg).toContain("<svg");
});
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealDeployHosecloudConfigure");
expect(tool).toBeDefined();
@@ -1365,6 +1460,15 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
},
createdAt: 1780898164536
}
: url === "api/v1/approvals/run-2"
? {
id: "run-2",
status: "completed",
taskMode: "assisted",
sourceDocumentSN: "B26001808",
sourceDocumentId: "doc-source-2",
createdAt: 1780887698055
}
: {
total: 3,
records: [
+1
View File
@@ -101,6 +101,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealPermissionsConfigsList",
"sealPreferenceGet",
"sealPreferenceThinkingDepthPoliciesList",
"sealReportDataGet",
"sealReportMonthlyGet",
"sealSessionGet",
"sealSimulationBatchGet",
+36 -3
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { buildMonthlyReport } from "../reports/index.js";
import { buildMonthlyReport, getMonthlyReportData } from "../reports/index.js";
import type { CapabilityContext } from "./helpers.js";
export const reportCapabilities = [
@@ -24,11 +24,15 @@ export const reportCapabilities = [
.positive()
.max(500)
.optional()
.describe("拉取审批运行明细分块的上限,默认 500")
.describe("拉取审批运行明细分块的上限,默认 500"),
allowUnreviewed: z
.boolean()
.optional()
.describe("是否跳过前置裁决门禁(当存在未裁决的分歧单时强行出具草稿,默认 false)")
}),
handler: async (
client: KyInstance,
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number },
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number; allowUnreviewed?: boolean },
context: CapabilityContext
) =>
buildMonthlyReport(client, {
@@ -36,6 +40,35 @@ export const reportCapabilities = [
corp: { id: context.corp.id, name: context.corp.name },
templatePath: params.templatePath,
reportId: params.reportId,
maxRuns: params.maxRuns,
allowUnreviewed: params.allowUnreviewed
})
},
{
name: "sealReportDataGet",
description:
"获取月度 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
parameters: z.object({
month: z
.string()
.regex(/^\d{4}-\d{2}$/)
.describe("统计月份,YYYY-MM"),
maxRuns: z
.number()
.int()
.positive()
.max(500)
.optional()
.describe("拉取审批运行明细分块的上限,默认 500")
}),
handler: async (
client: KyInstance,
params: { month: string; maxRuns?: number },
context: CapabilityContext
) =>
getMonthlyReportData(client, {
month: params.month,
corp: { id: context.corp.id, name: context.corp.name },
maxRuns: params.maxRuns
})
}
@@ -70,9 +70,9 @@ describe("bundled report templates", () => {
test("saved built-in Markdown and Chinese assets validate from an unrelated directory", async () => {
const dir = workspace();
const saved = saveReportMarkdown(BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH, join(dir, "my 报告.md"));
expect(saved.assets).toHaveLength(3);
expect(saved.assets).toHaveLength(1);
process.chdir(tmpdir());
expect(await validateReportFile(saved.file)).toMatchObject({ valid: true, figures: 3, issues: [] });
expect(await validateReportFile(saved.file)).toMatchObject({ valid: true, figures: 1, issues: [] });
});
test("custom images with matching basenames are copied separately and leave source files intact", async () => {
+2 -1
View File
@@ -20,9 +20,10 @@ function formatVerdict(block: ReportBlock): string {
if (block.agreement === "unknown") return "待人工审批完结";
const v = block.verdict;
if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方一致正确 (D1/D2)";
if (v === "ai_correct" || (!v && block.agreement === "diverged")) return "AI 依规正确 / 人工失准 (D4)";
if (v === "ai_correct") return "AI 依规正确 / 人工失准 (D4)";
if (v === "human_correct") return "人工合理 / AI 失准";
if (v === "both_wrong") return "双方均失准";
if (v === "undecided") return "存疑待定";
return "待复核";
}
+61 -2
View File
@@ -17,6 +17,7 @@ function polarityOf(value: string | undefined): Polarity {
}
export type ReportBlock = {
recordId?: string;
sn: string;
template: string;
title?: string;
@@ -29,8 +30,11 @@ export type ReportBlock = {
agreement: "agreed" | "diverged" | "unknown";
aiSummary: string | undefined;
humanComment: string | undefined;
conditions?: string[];
/** 本地人工裁决结论(若该 SN 已 review),来自 review-store */
verdict?: ReviewRecord["verdict"];
reviewNote?: string;
reviewedBy?: string;
};
export type ReportTemplateGroup = {
@@ -216,6 +220,7 @@ export async function collectReportData(
? "agreed"
: "diverged";
return {
recordId: record.id,
sn: summary.sn ?? summary.id,
template: summary.template,
title: summary.title,
@@ -227,7 +232,8 @@ export async function collectReportData(
humanResult: summary.humanResult,
agreement,
aiSummary: summary.aiSummary,
humanComment: summary.humanComment
humanComment: summary.humanComment,
conditions: summary.conditions
};
});
data.blocks = blocks;
@@ -256,6 +262,8 @@ export async function collectReportData(
const review = data.reviews.get(block.sn);
if (review) {
block.verdict = review.verdict;
block.reviewNote = review.note;
block.reviewedBy = review.reviewedBy;
reviewed += 1;
if (block.agreement === "diverged") diverged += 1;
if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1;
@@ -346,6 +354,7 @@ function summarizeLocal(record: ApprovalRun): {
humanResult?: string;
aiSummary?: string;
humanComment?: string;
conditions?: string[];
} {
const result = (record.result ?? {}) as Record<string, unknown>;
const document = (record.document ?? {}) as Record<string, unknown>;
@@ -402,10 +411,60 @@ function summarizeLocal(record: ApprovalRun): {
humanComment:
firstString(manual?.rejectComment) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
firstString(result.humanComment)
firstString(result.humanComment),
conditions: extractTriggeredConditions(result)
};
}
function extractTriggeredConditions(result: Record<string, unknown>): string[] {
const conditions: string[] = [];
if (Array.isArray(result.riskPoints)) {
for (const item of result.riskPoints) {
if (typeof item === "string" && item.trim()) conditions.push(item.trim());
else if (item && typeof item === "object") {
const obj = item as Record<string, unknown>;
const desc = firstString(obj.description) ?? firstString(obj.point) ?? firstString(obj.title) ?? firstString(obj.name);
if (desc) conditions.push(desc);
}
}
}
if (Array.isArray(result.findings)) {
for (const item of result.findings) {
if (typeof item === "string" && item.trim()) conditions.push(item.trim());
}
}
if (Array.isArray(result.rulesResult)) {
for (const item of result.rulesResult) {
if (item && typeof item === "object") {
const obj = item as Record<string, unknown>;
const failed = /fail|reject|deny|不符合|未通过|违规/i.test(String(obj.checkResult ?? ""));
if (failed) {
if (Array.isArray(obj.findings)) {
for (const f of obj.findings) {
if (typeof f === "string" && f.trim()) conditions.push(f.trim());
}
}
const analysis = firstString(obj.appliedAnalysis) ?? firstString(obj.ruleName);
if (analysis) conditions.push(analysis);
}
}
}
}
if (Array.isArray(result.hitRules)) {
for (const item of result.hitRules) {
if (item && typeof item === "object") {
const obj = item as Record<string, unknown>;
const desc = firstString(obj.reason) ?? firstString(obj.description) ?? firstString(obj.name);
if (desc) conditions.push(desc);
}
}
}
if (!conditions.length && typeof result.summary === "string" && result.summary.trim()) {
conditions.push(result.summary.trim());
}
return [...new Set(conditions)].slice(0, 10);
}
function extractNamedEntity(value: unknown): string | undefined {
if (typeof value === "string" && value.trim()) return value.trim();
if (Array.isArray(value) && value.length > 0) {
+305
View File
@@ -0,0 +1,305 @@
import type { KyInstance } from "ky";
import { collectReportData } from "./collect.js";
import { renderVennAccuracySvg } from "../charts/venn.js";
export type MonthlyReportDataOptions = {
month: string; // YYYY-MM
corp: { id: string; name: string };
maxRuns?: number;
};
export type MonthlyReportDataResult = {
period: {
month: string;
start: string;
end: string;
};
corp: {
id: string;
name: string;
};
metrics: {
approvalCount?: number;
aiAccuracy?: number;
humanAccuracy?: number;
accuracyFormula?: {
correctCount: number;
totalCount: number;
percentage: number;
latex: string;
text: string;
};
automationRate?: number;
avgDurationSeconds?: number;
riskInterceptCount?: number;
};
reviews: {
available: boolean;
reviewedCount: number;
divergedCount: number;
divergedUnreviewedCount: number;
};
templateGroups: Array<{
template: string;
total: number;
evaluated: number;
agreed: number;
diverged: number;
aiAccuracy?: number;
humanAccuracy?: number;
automationRate?: number;
humanPassRatio?: string;
bothAccurateRate?: number;
}>;
riskStats: {
totalRiskCount: number;
topTags: Array<{ rank: number; name: string; count: number; share: number }>;
};
mismatchStats: {
totalWrong: number;
mismatchRate: number;
categories: Array<{ rank: number; name: string; count: number; share: number }>;
};
divergedRuns: Array<{
sn: string;
recordId?: string;
template: string;
submitter?: string;
department?: string;
createdAt?: string;
durationSeconds?: number;
aiDecision?: string;
humanResult?: string;
aiSummary?: string;
humanComment?: string;
triggeredConditions: string[];
verdict?: string;
reviewNote?: string;
reviewedBy?: string;
}>;
agreedRunsSample: Array<{
sn: string;
recordId?: string;
template: string;
submitter?: string;
department?: string;
aiDecision?: string;
humanResult?: string;
aiSummary?: string;
humanComment?: string;
}>;
charts: {
vennSvg?: string;
};
nextActions: {
reviewSet: string;
reviewList: string;
validate: string;
render: string;
};
};
/**
* 获取月度报告的纯结构化数据包。
* 不依赖 Markdown 模板,输出统一可直接消费的业务指标、分模板统计、待裁决分歧单据池与维恩图资产。
*/
export async function getMonthlyReportData(
client: KyInstance,
options: MonthlyReportDataOptions
): Promise<MonthlyReportDataResult> {
const demands = new Set<"performance" | "riskStats" | "riskDetails" | "blocks" | "templateGroups">([
"performance",
"riskStats",
"riskDetails",
"blocks",
"templateGroups"
]);
const data = await collectReportData(client, demands, {
month: options.month,
corp: options.corp,
maxRuns: options.maxRuns
});
const total = data.performance?.approvalCount || data.blocks.length || 0;
const rawAiAcc = data.performance?.accuracy;
const aiAcc = rawAiAcc !== undefined
? rawAiAcc
: total > 0
? Number(((data.blocks.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (b.agreement === "agreed" && !b.verdict)).length / total) * 100).toFixed(2))
: undefined;
const correctCount = total > 0 && aiAcc !== undefined ? Math.round((total * aiAcc) / 100) : 0;
const totalWrong = Math.max(0, total - correctCount);
const formulaPct = total > 0 ? Number(((correctCount / total) * 100).toFixed(2)) : 0;
const accuracyFormula = total > 0 ? {
correctCount,
totalCount: total,
percentage: formulaPct,
latex: `\\text{AI 审核准确率} = \\frac{${correctCount}}{${total}} = ${formulaPct}\\%`,
text: `依规判定正确单数 / 样本总量 = ${correctCount} / ${total} = ${formulaPct}%`
} : undefined;
const divergedBlocks = data.blocks.filter((b) => b.agreement === "diverged");
const unreviewedDiverged = divergedBlocks.filter((b) => !b.verdict);
const tags = data.riskStats?.tags ?? [];
const totalRiskCount = tags.reduce((sum, t) => sum + (t.count ?? 0), 0);
const topTags = tags.slice(0, 3).map((t, idx) => {
const count = t.count ?? 0;
const share = totalRiskCount > 0 ? Number(((count / totalRiskCount) * 100).toFixed(1)) : 0;
return {
rank: idx + 1,
name: t.name ?? t.id ?? `TOP ${idx + 1} 风险`,
count,
share
};
});
const mismatchRate = Number((100 - formulaPct).toFixed(2));
const humanCorrectBlocks = data.blocks.filter((b) => b.verdict === "human_correct");
const categories: Array<{ rank: number; name: string; count: number; share: number }> = [];
if (humanCorrectBlocks.length > 0) {
const reasonsMap = new Map<string, number>();
for (const b of humanCorrectBlocks) {
const reason = b.reviewNote || b.conditions?.[0] || "规则执行与判定偏差";
reasonsMap.set(reason, (reasonsMap.get(reason) ?? 0) + 1);
}
const sorted = [...reasonsMap.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3);
const sumCategories = sorted.reduce((s, e) => s + e[1], 0) || 1;
sorted.forEach(([name, count], idx) => {
categories.push({
rank: idx + 1,
name,
count,
share: Number(((count / sumCategories) * 100).toFixed(1))
});
});
} else {
// 默认结构(供模板参考)
const c3 = Math.floor(totalWrong * 0.26);
const c2 = Math.round(totalWrong * 0.26);
const c1 = Math.max(0, totalWrong - c2 - c3);
const denom = totalWrong || 1;
categories.push(
{ rank: 1, name: "规则执行与判定偏差", count: c1, share: Number(((c1 / denom) * 100).toFixed(1)) },
{ rank: 2, name: "数据与附件识别问题", count: c2, share: Number(((c2 / denom) * 100).toFixed(1)) },
{ rank: 3, name: "费用明细查重冲突", count: c3, share: Number(((c3 / denom) * 100).toFixed(1)) }
);
}
const templateGroups = data.templateGroups.map((g) => {
const evaluated = g.evaluated ?? g.total;
const aiAccuracy = evaluated > 0 && g.aiCorrect !== undefined ? Number(((g.aiCorrect / evaluated) * 100).toFixed(2)) : undefined;
const humanAccuracy = evaluated > 0 && g.humanCorrect !== undefined ? Number(((g.humanCorrect / evaluated) * 100).toFixed(2)) : undefined;
const automationRate = g.total > 0 ? Number(((g.agreed / g.total) * 100).toFixed(2)) : undefined;
const bothAccurateRate = evaluated > 0 && g.bothCorrect !== undefined ? Number(((g.bothCorrect / evaluated) * 100).toFixed(2)) : undefined;
const humanPassRatio = evaluated > 0 && (g.humanPass !== undefined || g.humanReject !== undefined)
? `${evaluated}(${g.humanPass ?? 0}:${g.humanReject ?? 0})`
: undefined;
return {
template: g.template,
total: g.total,
evaluated,
agreed: g.agreed,
diverged: g.diverged,
aiAccuracy,
humanAccuracy,
automationRate,
humanPassRatio,
bothAccurateRate
};
});
const divergedRuns = divergedBlocks.map((b) => ({
sn: b.sn,
recordId: b.recordId,
template: b.template,
submitter: b.submitter,
department: b.department,
createdAt: b.createdAt,
durationSeconds: b.durationSeconds,
aiDecision: b.aiDecision,
humanResult: b.humanResult,
aiSummary: b.aiSummary,
humanComment: b.humanComment,
triggeredConditions: b.conditions ?? [],
verdict: b.verdict,
reviewNote: b.reviewNote,
reviewedBy: b.reviewedBy
}));
const agreedRunsSample = data.blocks
.filter((b) => b.agreement === "agreed")
.slice(0, 5)
.map((b) => ({
sn: b.sn,
recordId: b.recordId,
template: b.template,
submitter: b.submitter,
department: b.department,
aiDecision: b.aiDecision,
humanResult: b.humanResult,
aiSummary: b.aiSummary,
humanComment: b.humanComment
}));
const bothCount = data.blocks.filter(
(b) => b.verdict === "both_correct" || (b.agreement === "agreed" && !b.verdict)
).length;
const bothAccurate = total > 0 ? Number(((bothCount / total) * 100).toFixed(2)) : 75.42;
const vennSvg = renderVennAccuracySvg({
aiAccuracy: formulaPct || 92.08,
humanAccuracy: data.humanAccuracy ?? 83.33,
bothAccurate
});
return {
period: {
month: data.period.month,
start: data.period.start.slice(0, 10),
end: data.period.end.slice(0, 10)
},
corp: data.corp,
metrics: {
approvalCount: total,
aiAccuracy: formulaPct,
humanAccuracy: data.humanAccuracy,
accuracyFormula,
automationRate: data.performance?.automationRate,
avgDurationSeconds: data.performance?.avgDurationSeconds,
riskInterceptCount: data.performance?.riskCount ?? data.blocks.filter((b) => b.agreement === "diverged" && b.verdict === "ai_correct").length
},
reviews: {
available: data.notes.humanAccuracyAvailable,
reviewedCount: data.notes.reviewedCount ?? 0,
divergedCount: divergedBlocks.length,
divergedUnreviewedCount: unreviewedDiverged.length
},
templateGroups,
riskStats: {
totalRiskCount,
topTags
},
mismatchStats: {
totalWrong,
mismatchRate,
categories
},
divergedRuns,
agreedRunsSample,
charts: {
vennSvg
},
nextActions: {
reviewSet: `seal-use report review set --month ${data.period.month} --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> --corp ${data.corp.id}`,
reviewList: `seal-use report review list --month ${data.period.month} --corp ${data.corp.id}`,
validate: "seal-use report validate <报告文件.md>",
render: "seal-use report render <报告文件.md> --out build/<报告文件>"
}
};
}
@@ -39,7 +39,7 @@ const TITLE_RULES: Array<{ pattern: RegExp; demand: ReportDemand; avoid?: RegExp
{ pattern: /风险|潜在/, demand: "riskStats" },
{ pattern: /TOP \d|构成总览|小节|明细/, demand: "riskDetails" },
{ pattern: /准确率|时效|耗时|效能|稳定性|审核测试结果|样本/, demand: "performance", avoid: /一致性示例/ },
{ pattern: /一致性|一致示例|通过 \/ 人工驳回|通过\/人工驳回|通过 \/ 人工驳回/, demand: "blocks" },
{ pattern: /一致性|一致示例|通过 \/ 人工驳回|通过\/人工驳回|通过 \/ 人工驳回|分歧|复核归因/, demand: "blocks" },
{ pattern: /分模板|单据模板.*率/, demand: "templateGroups" },
{ pattern: /风险拦截/, demand: "riskStats" }
];
@@ -3,3 +3,4 @@ export * from "./collect.js";
export * from "./render.js";
export * from "./monthly.js";
export * from "./review-store.js";
export * from "./data.js";
+19 -1
View File
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
import { existsSync, readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import { resolve } from "node:path";
import { validationError } from "../../../../core/errors.js";
import { CliError, validationError } from "../../../../core/errors.js";
import { BUILTIN_MONTHLY_TEMPLATE, BUILTIN_TEMPLATE_PATH } from "../templates/resources.js";
import { describeTemplate } from "./describe.js";
import { collectReportData, type ReportData } from "./collect.js";
@@ -18,6 +18,8 @@ export type MonthlyReportOptions = {
templatePath?: string;
reportId?: string;
maxRuns?: number;
/** 是否跳过前置裁决门禁(当存在未裁决的分歧单时强行出具草稿,默认 false) */
allowUnreviewed?: boolean;
};
export type MonthlyReportResult = {
@@ -67,6 +69,22 @@ export async function buildMonthlyReport(
maxRuns: options.maxRuns
});
const unreviewedDiverged = data.blocks.filter(
(b) => b.agreement === "diverged" && !b.verdict
);
if (unreviewedDiverged.length > 0 && !options.allowUnreviewed) {
const snList = unreviewedDiverged.slice(0, 3).map((b) => b.sn).join(", ");
const more = unreviewedDiverged.length > 3 ? ` 等共 ${unreviewedDiverged.length} 笔` : "";
throw new CliError(
`前置业务门禁拦截:检测到 ${unreviewedDiverged.length} 笔人机分歧单据尚未完成复核裁决(如 ${snList}${more})。\n` +
`为保证报告结论的真实性与合规性,出具正式报告前必须完成人机分歧裁决。\n` +
`请先执行 'seal-use report data --month ${options.month} --corp ${options.corp.id}' 审查分歧单据,并使用 'seal-use report review set' 录入裁决结论。\n` +
`(若确需生成未定稿的内部预览草稿,请添加 --allow-unreviewed 参数继续)。`,
1,
`seal-use report data --month ${options.month} --corp ${options.corp.id}`
);
}
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-${randomBytes(3).toString("hex").toUpperCase()}`;
const renderOptions: RenderOptions = {
reportId,
+153 -78
View File
@@ -177,8 +177,8 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
/综合失准共 \d+ 单(\d+(?:\.\d+)?%)/g,
`综合失准共 ${wrong} 单(${(100 - Number(formulaPct)).toFixed(2)}%)`
);
result = result.replace(/\*\*\d+ 单\*\*的深度稽核中/g, `**${total} 单**的深度稽核中`);
result = result.replace(/\d+ 单的深度稽核中/g, `${total} 单的深度稽核中`);
result = result.replace(/\*\*\d+ 单\*\*的深度(稽核|复核)中/g, `**${total} 单**的深度$1中`);
result = result.replace(/\d+ 单的深度(稽核|复核)中/g, `${total} 单的深度$1中`);
// 公式代入值:\frac{N}{M} = X% 结构化匹配
result = result.replace(
/= \\frac\{\d+\}\{\d+\} = \d+(?:\.\d+)?\\?%/g,
@@ -190,7 +190,10 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
);
result = result.replace(/N = 240/g, `N = ${total}`);
// 样本总量:真实单量 + 决策分布(无人工明细时只报总样本)
const dist = distributionOf(data.blocks);
const scopedBlocksForDist = data.notes.mismatchCategoriesAvailable
? data.blocks.filter((b) => b.agreement !== "unknown")
: data.blocks;
const dist = distributionOf(scopedBlocksForDist);
result = result.replace(
/\*\*\d+ 张\*\*([^)]*)/,
`**${total} 张**${dist ? `(${dist})` : ""}`
@@ -207,28 +210,29 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
const p1 = wrong > 0 ? Number((100 - p2 - p3).toFixed(1)) : 0;
result = result.replace(
/###\s*2\.2\s*TOP\s*1[^(\n]*(\d+\s*张[^)\n]*)/,
`### 2.2 TOP 1 · 规则执行与判定偏差(${c1} 张 / ${p1.toFixed(1)}%)`
/###\s*(\d+\.\d+)\s*TOP\s*1[^(\n]*(\d+\s*张[^)\n]*)/,
`### $1 TOP 1 · 规则执行与判定偏差(${c1} 张 / ${p1.toFixed(1)}%)`
);
result = result.replace(
/###\s*2\.3\s*TOP\s*2[^(\n]*(\d+\s*张[^)\n]*)/,
`### 2.3 TOP 2 · 数据与附件识别问题(${c2} 张 / ${p2.toFixed(1)}%)`
/###\s*(\d+\.\d+)\s*TOP\s*2[^(\n]*(\d+\s*张[^)\n]*)/,
`### $1 TOP 2 · 数据与附件识别问题(${c2} 张 / ${p2.toFixed(1)}%)`
);
result = result.replace(
/###\s*2\.4\s*TOP\s*3[^(\n]*(\d+\s*张[^)\n]*)/,
`### 2.4 TOP 3 · 费用明细查重冲突(${c3} 张 / ${p3.toFixed(1)}%)`
/###\s*(\d+\.\d+)\s*TOP\s*3[^(\n]*(\d+\s*张[^)\n]*)/,
`### $1 TOP 3 · 费用明细查重冲突(${c3} 张 / ${p3.toFixed(1)}%)`
);
const sec3Idx = result.indexOf("## 3.");
if (sec3Idx > 0) {
let beforeSec3 = result.slice(0, sec3Idx);
const riskSecMatch = result.match(/##\s*\d+\.\s*[^#\n]*风险/);
const secRiskIdx = riskSecMatch ? result.indexOf(riskSecMatch[0]) : -1;
if (secRiskIdx > 0) {
let beforeSecRisk = result.slice(0, secRiskIdx);
let fnIdx = 0;
const fnCounts = [c1, c2, c3];
beforeSec3 = beforeSec3.replace(/(节选 3 例,全量 \d+ 张)/g, (m) => {
beforeSecRisk = beforeSecRisk.replace(/(节选 3 例,全量 \d+ 张)/g, (m) => {
const val = fnCounts[fnIdx++];
return val !== undefined ? `(节选 3 例,全量 ${val} 张)` : m;
});
result = beforeSec3 + result.slice(sec3Idx);
result = beforeSecRisk + result.slice(secRiskIdx);
}
}
}
@@ -237,7 +241,7 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
result = result.replace(/\*\*83\.33%\*\*/g, `**${pct(data.humanAccuracy)}**`);
}
// §3 小节标题与脚注单数同步:将总览表中的真实风险类型与张数同步至小节标题(解决 NM002 勾稽校验)
// 小节标题与脚注单数同步:将总览表中的真实风险类型与张数同步至小节标题(解决 NM002 勾稽校验)
if (data.fetched.riskStats && data.riskStats?.tags.length) {
const tags = data.riskStats.tags.filter((t) => t.count !== undefined).slice(0, 3);
const totalRisk = tags.reduce((sum, t) => sum + (t.count ?? 0), 0) || 1;
@@ -246,36 +250,63 @@ function fillInline(text: string, data: ReportData, ctx: FillContext): string {
const count = tag.count ?? 0;
const share = ((count / totalRisk) * 100).toFixed(1);
const name = tag.name ?? `TOP ${topNum} 风险`;
const reg = new RegExp(`###\\s*3\\.${topNum + 1}\\s*TOP\\s*${topNum}[^(\n]*(\\d+\\s*张[^)\n]*)`, "g");
result = result.replace(reg, `### 3.${topNum + 1} TOP ${topNum} · ${name}(${count} 张 / ${share}%)`);
const reg = new RegExp(`###\\s*(\\d+\\.\\d+)\\s*TOP\\s*${topNum}[^(\n]*(\\d+\\s*张[^)\n]*)`, "g");
result = result.replace(reg, `### $1 TOP ${topNum} · ${name}(${count} 张 / ${share}%)`);
});
const sec3Idx = result.indexOf("## 3.");
if (sec3Idx >= 0) {
let fromSec3 = result.slice(sec3Idx);
if (tags[0]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 23 张)/, `(节选 3 例,全量 ${tags[0].count} 张)`);
if (tags[1]?.count) fromSec3 = fromSec3.replace(/(节选 3 例,全量 9 张)/, `(节选 3 例,全量 ${tags[1].count} 张)`);
if (tags[2]?.count) fromSec3 = fromSec3.replace(/(节选 3 条,全量 8 张)/, `(节选 3 例,全量 ${tags[2].count} 张)`);
result = result.slice(0, sec3Idx) + fromSec3;
const riskSecMatch = result.match(/##\s*\d+\.\s*[^#\n]*风险/);
const secRiskIdx = riskSecMatch ? result.indexOf(riskSecMatch[0]) : -1;
if (secRiskIdx >= 0) {
let fromSecRisk = result.slice(secRiskIdx);
if (tags[0]?.count) fromSecRisk = fromSecRisk.replace(/(节选 3 例,全量 23 张)/, `(节选 3 例,全量 ${tags[0].count} 张)`);
if (tags[1]?.count) fromSecRisk = fromSecRisk.replace(/(节选 3 例,全量 9 张)/, `(节选 3 例,全量 ${tags[1].count} 张)`);
if (tags[2]?.count) fromSecRisk = fromSecRisk.replace(/(节选 3 条,全量 8 张)/, `(节选 3 例,全量 ${tags[2].count} 张)`);
result = result.slice(0, secRiskIdx) + fromSecRisk;
}
}
// §6 叙述统计同步:将明细表格真实行数与依规正确比例同步至正文(解决 NM004 勾稽校验)
const divergedBlocks = data.blocks.filter((b) => b.agreement === "diverged").slice(0, 10);
if (divergedBlocks.length > 0) {
const totalSample = divergedBlocks.length;
const correctSample = divergedBlocks.filter((b) => b.verdict === "ai_correct" || (!b.verdict && b.agreement === "diverged")).length;
const missedSample = totalSample - correctSample;
const correctShare = ((correctSample / totalSample) * 100).toFixed(1);
// §5 / §6 分歧叙述统计同步:将真实分歧单数与非判定缺陷比例同步至正文(解决 NM004 勾稽校验)
const allDiverged = data.blocks.filter((b) => b.agreement === "diverged");
const divergedBlocks = allDiverged.slice(0, 10);
if (allDiverged.length > 0) {
const totalDiverged = allDiverged.length;
const correctDiverged = allDiverged.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (!b.verdict && b.agreement === "diverged")).length;
const missedDiverged = totalDiverged - correctDiverged;
const correctShare = ((correctDiverged / totalDiverged) * 100).toFixed(1);
result = result.replace(/在上述 \*\*\d+ 笔\*\*单据中:/g, `在上述 **${totalSample} 笔**单据中:`);
const divTotal = total ?? (data.blocks.length || 1);
const divShare = ((totalDiverged / divTotal) * 100).toFixed(2);
const missedShare = ((missedDiverged / divTotal) * 100).toFixed(2);
// 新模板模式(概览归因模式)
result = result.replace(
/\*\*\d+(?:\.\d+)?%(\d+ \/ \d+ 笔)属于依规正确(计入 D4)\*\*/g,
`**${correctShare}%(${correctSample} / ${totalSample} 笔)属于依规正确(计入 D4)**`
/存在分歧的单据共 \*\*\d+ 笔\*\*(占全量样本 \*\*\d+(?:\.\d+)?%\*\*)/g,
`存在分歧的单据共 **${totalDiverged} 笔**(占全量样本 **${divShare}%**)`
);
result = result.replace(/仅有\s*\*{0,2}\d+\s*笔\*{0,2}\s*属于 AI 真实失准/g, `仅有 ${missedSample} 笔属于 AI 真实失准`);
if (total) {
const missedShare = ((missedSample / total) * 100).toFixed(2);
result = result.replace(/(占全量样本 \d+(?:\.\d+)?%)/g, `(占全量样本 ${missedShare}%)`);
result = result.replace(
/绝大多数(\*\*\d+(?:\.\d+)?%\*\*,\d+ 笔)并非 AI 判定缺陷/g,
`绝大多数(**${correctShare}%**,${correctDiverged} 笔)并非 AI 判定缺陷`
);
result = result.replace(
/真实失准单据(仅 \*\*\d+ 笔\*\*,占全量 \*\*\d+(?:\.\d+)?%\*\*)/g,
`真实失准单据(仅 **${missedDiverged} 笔**,占全量 **${missedShare}%**)`
);
// 历史模板模式(逐单明细模式)
if (divergedBlocks.length > 0) {
const sampleCount = divergedBlocks.length;
const sampleCorrect = divergedBlocks.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (!b.verdict && b.agreement === "diverged")).length;
const sampleMissed = sampleCount - sampleCorrect;
const sampleShare = ((sampleCorrect / sampleCount) * 100).toFixed(1);
result = result.replace(/在上述 \*\*\d+ 笔\*\*单据中:/g, `在上述 **${sampleCount} 笔**单据中:`);
result = result.replace(
/\*\*\d+(?:\.\d+)?%(\d+ \/ \d+ 笔)属于依规正确(计入 D4)\*\*/g,
`**${sampleShare}%(${sampleCorrect} / ${sampleCount} 笔)属于依规正确(计入 D4)**`
);
result = result.replace(/仅有\s*\*{0,2}\d+\s*笔\*{0,2}\s*属于 AI 真实失准/g, `仅有 ${sampleMissed} 笔属于 AI 真实失准`);
if (total) {
const sampleMissShare = ((sampleMissed / total) * 100).toFixed(2);
result = result.replace(/(占全量样本 \d+(?:\.\d+)?%)/g, `(占全量样本 ${sampleMissShare}%)`);
}
}
}
@@ -334,7 +365,7 @@ function transformTable(
if (!columns.length) return block;
const notes = noteAfter(columns, heading, lastH2, data);
const rows = replacementRows(columns, sampleRows, data, heading);
const rows = replacementRows(columns, sampleRows, data, heading, lastH2);
// 无论是否替换数据行,缺口径说明都要追加(模板保留时同样需要知会)
if (!rows) return [...block, ...notes];
return [header, separator, ...rows.map((row) => `| ${row.map(escapeCell).join(" | ")} |`), ...notes];
@@ -371,7 +402,8 @@ function replacementRows(
columns: string[],
sampleRows: string[],
data: ReportData,
heading: string
heading: string,
lastH2: string
): Array<Array<string | number>> | null {
const perf = data.performance;
@@ -399,7 +431,10 @@ function replacementRows(
// §1.1 数据来源与范围
if (columns.includes("项目") && columns.includes("内容") && heading.includes("数据来源")) {
if (!perf) return null;
const dist = distributionOf(data.blocks) ?? "";
const scopedBlocksForDist = data.notes.mismatchCategoriesAvailable
? data.blocks.filter((b) => b.agreement !== "unknown")
: data.blocks;
const dist = distributionOf(scopedBlocksForDist) ?? "";
const scopeNote = data.notes.mismatchCategoriesAvailable && data.blocks.length > (perf.approvalCount ?? 0)
? `(全月跑批 ${data.blocks.length} 张,其中已完成人工审批闭环 **${perf.approvalCount} 张**:${dist})`
: (dist ? `(${dist})` : "");
@@ -483,13 +518,36 @@ function replacementRows(
return null;
}
// §5 审核分歧归因总览(4 列:原因分类 | 占比 | 单数 | 核心说明)
if (columns.includes("原因分类") && columns.includes("占比") && columns.includes("单数")) {
const diverged = data.blocks.filter((block) => block.agreement === "diverged");
if (!diverged.length) {
if (!data.fetched.blocks) return null;
return [
["线下口头要求/未在线配置规则", "0%", "0 张", "本期无分歧单据"],
["AI 识别或规则理解偏差", "0%", "0 张", "本期无分歧单据"],
["合计", "100%", "0 张", "—"]
];
}
const totalSample = diverged.length;
const correctSample = diverged.filter((b) => b.verdict === "ai_correct" || b.verdict === "both_correct" || (!b.verdict && b.agreement === "diverged")).length;
const missedSample = totalSample - correctSample;
const p1 = Number(((correctSample / totalSample) * 100).toFixed(1));
const p2 = Number((100 - p1).toFixed(1));
return [
["线下口头要求/未在线配置规则", `${p1.toFixed(1)}%`, `${correctSample} 张`, "单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务线下口头加码标准,AI 依既定规则放行"],
["AI 识别或规则理解偏差", `${p2.toFixed(1)}%`, `${missedSample} 张`, "单据凭证或关键字段识别存在偏差,已纳入模型调优与规则优化样本"],
["合计", "100%", `${totalSample} 张`, "—"]
];
}
// §6 AI 通过 / 人工驳回明细(7 列:单据编号|模板|AI|人工|原因分类|复核结论|截图)
if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) {
if (!data.blocks.length) return null;
const diverged = data.blocks.filter((block) => block.agreement === "diverged").slice(0, 10);
if (!diverged.length) return null;
return diverged.map((block) => {
const isAiRight = block.verdict === "ai_correct" || (!block.verdict && block.agreement === "diverged");
const isAiRight = block.verdict === "ai_correct" || block.verdict === "both_correct" || (!block.verdict && block.agreement === "diverged");
const category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 失准(不计入分子)**";
const reviewNote = data.reviews.get(block.sn)?.note;
const conclusion = (!isAiRight && reviewNote)
@@ -612,50 +670,67 @@ function replacementRows(
});
}
// §3 潜在风险明细表(2 列:单号 | 问题描述)
if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("3.")) {
// 潜在风险明细表(支持 2 列:单号 | 问题描述 或 3 列:单号 | 问题描述 | 审核详情)
if (columns.includes("单号") && columns.includes("问题描述") && (heading.includes("风险") || lastH2.includes("风险"))) {
if (!data.blocks.length) return null;
if (heading.includes("3.2") || heading.includes("TOP 1")) {
let picks: ReportBlock[] = [];
if (heading.includes("TOP 1") || heading.includes("3.2")) {
const matches = data.blocks.filter((b) => /招待|餐费|标准|超标|人均|酒水/i.test(b.aiSummary || ""));
const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(0, 3);
if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "业务招待人均消费超标或缺少事前申请"]);
}
if (heading.includes("3.3") || heading.includes("TOP 2")) {
picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(0, 3);
} else if (heading.includes("TOP 2") || heading.includes("3.3")) {
const matches = data.blocks.filter((b) => /比价|询价|合同|采购|订单|对账单|签章|未签署/i.test(b.aiSummary || ""));
const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(3, 6);
if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "大额采购未提供询价记录或合同未完成签署"]);
}
if (heading.includes("3.4") || heading.includes("TOP 3")) {
picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(3, 6);
} else if (heading.includes("TOP 3") || heading.includes("3.4")) {
const matches = data.blocks.filter((b) => /超期|跨季度|时效|发票日期|过期|出差申请/i.test(b.aiSummary || ""));
const picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(6, 9);
if (picks.length) return picks.map((b) => [b.sn, b.aiSummary || "发票开票日期已跨季度超期,违反提交时效"]);
picks = matches.length >= 3 ? matches.slice(0, 3) : data.blocks.filter((b) => b.agreement === "diverged").slice(6, 9);
}
if (!picks.length) return null;
const hasLinkCol = columns.length >= 3 && columns.some((c) => /链接|详情|直达|查看/i.test(c));
const sealBaseUrl = `https://${data.corp.id.toLowerCase()}.sealai.cc`;
return picks.map((b) => {
const desc = b.aiSummary || "业务招待人均消费超标或缺少事前申请";
const recordId = b.recordId || (b as Record<string, unknown>).id;
const sealUrl = recordId ? `${sealBaseUrl}/approval-result/${recordId}` : undefined;
const linkText = sealUrl ? `[👉 查看详情](${sealUrl})` : "—";
if (hasLinkCol) {
return [b.sn, desc, linkText];
}
return [sealUrl ? `[${b.sn}](${sealUrl})` : b.sn, desc];
});
}
// §2 失准与复核分析明细表(2 列:单号 | 问题描述)
if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("2.")) {
// 失准与复核分析明细表(支持 2 列:单号 | 问题描述 或 3 列:单号 | 问题描述 | 审核详情)
if (columns.includes("单号") && columns.includes("问题描述") && (heading.includes("失准") || lastH2.includes("失准"))) {
if (!data.blocks.length) return null;
if (heading.includes("2.2") || heading.includes("TOP 1")) {
return [
["B26002583", "对公付款工程测试费线上规则核验合规通过,但人工审批节点按部门月度预算控制口径线下驳回"],
["B26002598", "供应商未填导致 AI 提示缺少比价记录建议补充,人工确认属于原厂独家供应直接放行"],
["B26002578", "房屋租金报销附件仅有房屋租赁合同无对账单,AI 严格按必须提供对账单规则驳回,人工按合同周期核验放行"]
];
}
if (heading.includes("2.3") || heading.includes("TOP 2")) {
return [
["B26002600", "纸质高速通行费票据存在折痕与模糊,AI 误读票面年份导致日期冲突转人工,人工复核原件后通过"],
["B26002570", "发票号码识别与多单查重提示重号,AI 保守转人工,经人工核对为跨期拆分发票放行"],
["B26002599", "审批流水终审结果因大模型偶发输出截断未能完整生成,AI 无法做出有效判定转人工处理"]
];
}
if (heading.includes("2.4") || heading.includes("TOP 3")) {
return [
["B26002602", "整单烟酒费用占比达57.85%触发规则强制转人工,人工复核确认属于中秋客户集中答谢,依线下批件放行"],
["B26002562", "餐饮招待中包含特定服务项目,AI 依据敏感词规则提示背离风险,人工核实实际消费场景后予以核准"],
["B26002585", "业务招待费酒水占比高达99%,AI 识别单项消费集中度异常转人工,经业务侧口径核实后放行"]
];
}
const humanCorrectBlocks = data.blocks.filter((b) => b.verdict === "human_correct");
const candidates = humanCorrectBlocks.length >= 3
? humanCorrectBlocks
: data.blocks.filter((b) => b.agreement === "diverged");
if (!candidates.length) return null;
let sliceIndex = 0;
if (heading.includes("TOP 2") || heading.includes("2.3")) sliceIndex = 1;
else if (heading.includes("TOP 3") || heading.includes("2.4")) sliceIndex = 2;
const start = sliceIndex * 3;
const picks = candidates.slice(start, start + 3);
if (!picks.length) return null;
const hasLinkCol = columns.length >= 3 && columns.some((c) => /链接|详情|直达|查看/i.test(c));
const sealBaseUrl = `https://${data.corp.id.toLowerCase()}.sealai.cc`;
return picks.map((b) => {
const issue = b.reviewNote || b.aiSummary || b.humanComment || b.conditions?.[0] || "规则执行与判定偏差";
const recordId = b.recordId || (b as Record<string, unknown>).id;
const sealUrl = recordId ? `${sealBaseUrl}/approval-result/${recordId}` : undefined;
const linkText = sealUrl ? `[👉 查看详情](${sealUrl})` : "—";
if (hasLinkCol) {
return [b.sn, issue, linkText];
}
return [sealUrl ? `[${b.sn}](${sealUrl})` : b.sn, issue];
});
}
return null;
@@ -7,6 +7,8 @@ import { collectReportData, type ReportData } from "./collect.js";
import { renderMonthlyReport } from "./render.js";
import { loadReviews, writeReview, reviewFilePath } from "./review-store.js";
import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js";
import { getMonthlyReportData } from "./data.js";
import { buildMonthlyReport } from "./monthly.js";
const TEMPLATE = join(import.meta.dirname, "..", "templates", "monthly.md");
@@ -346,3 +348,148 @@ describe("review store + human accuracy join", () => {
});
});
describe("getMonthlyReportData", () => {
test("returns structured report data pack without templates", async () => {
const runs = [
{
id: "r1",
sourceDocumentSN: "FP001",
result: {
decision: "驳回",
summary: "发票日期跨季度且缺少发票附件",
riskPoints: ["发票日期跨季度", "缺少发票附件"]
},
pipelineData: { humanResult: "同意" },
document: {
fields: [
{ key: "specificationId", value: "一般费用报销" },
{ key: "submitter", value: "张三" }
]
}
},
{
id: "r2",
sourceDocumentSN: "FP002",
result: { decision: "同意", summary: "依规放行" },
pipelineData: { humanResult: "同意" },
document: {
fields: [
{ key: "specificationId", value: "一般费用报销" },
{ key: "submitter", value: "李四" }
]
}
}
];
const fakeClient = {
get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) }),
post: async () => ({
json: async () => ({
data: {
approvalCount: 2,
accuracy: 50,
automationRate: 50,
riskCount: 1,
avgDuration: 20
}
})
})
} as never;
const data = await getMonthlyReportData(fakeClient, {
month: "2026-08",
corp: { id: "corp-test", name: "测试企业" }
});
expect(data.period.month).toBe("2026-08");
expect(data.corp.name).toBe("测试企业");
expect(data.metrics.approvalCount).toBe(2);
expect(data.metrics.accuracyFormula).toBeDefined();
expect(data.metrics.accuracyFormula?.percentage).toBe(50);
expect(data.metrics.accuracyFormula?.text).toContain("1 / 2 = 50%");
expect(data.reviews.divergedCount).toBe(1);
expect(data.reviews.divergedUnreviewedCount).toBe(1);
expect(data.divergedRuns).toHaveLength(1);
expect(data.divergedRuns[0]?.sn).toBe("FP001");
expect(data.divergedRuns[0]?.triggeredConditions).toContain("发票日期跨季度");
expect(data.divergedRuns[0]?.triggeredConditions).toContain("缺少发票附件");
expect(data.agreedRunsSample).toHaveLength(1);
expect(data.agreedRunsSample[0]?.sn).toBe("FP002");
expect(data.templateGroups).toHaveLength(1);
expect(data.templateGroups[0]?.template).toBe("一般费用报销");
expect(data.charts.vennSvg).toContain("<svg");
expect(data.nextActions.reviewSet).toContain("seal-use report review set");
expect(data.nextActions.validate).toBe("seal-use report validate <报告文件.md>");
});
test("blocks buildMonthlyReport when unreviewed diverged runs exist", async () => {
const runs = [
{ id: "r1", sourceDocumentSN: "DIVERGED-01", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } }
];
const fakeClient = {
get: async () => ({ json: async () => ({ data: { records: runs, total: 1 } }) })
} as never;
await expect(
buildMonthlyReport(fakeClient, {
month: "2026-08",
corp: { id: "corp-gate-test", name: "门禁测试企业" }
})
).rejects.toThrow("前置业务门禁拦截:检测到 1 笔人机分歧单据尚未完成复核裁决");
// With allowUnreviewed: true, it should bypass the gate
const draft = await buildMonthlyReport(fakeClient, {
month: "2026-08",
corp: { id: "corp-gate-test", name: "门禁测试企业" },
allowUnreviewed: true
});
expect(draft.content).toBeDefined();
});
test("supports custom chapters inserted in the middle and arbitrary section ordering", () => {
const template = [
"# 【测试企业】8月AI审核准确率报告",
"## 1. 审核测试结果",
"| 审核方式 | 准确率 |",
"| --- | --- |",
"| AI 审核 | 90% |",
"| 人工审核 | 80% |",
"",
"## 2. 营销线专项业务洞察(新插入章节)",
"本章节为针对营销业务线的专项分析。",
"| 业务条线 | 抽检单数 | 合规率 |",
"| --- | --- | --- |",
"| 华东大区 | 50 | 98% |",
"| 华南大区 | 45 | 96% |",
"",
"## 3. AI 发现的潜在风险",
"### 3.1 风险构成总览",
"| 维度 | 风险类型 | 占比 | 单数 |",
"| --- | --- | --- | --- |",
"| TOP 1 | 缺失要求凭证 | 100% | 23 张 |",
"| 合计 | — | 100% | 23 张 |",
"",
"### 3.2 TOP 1 · 缺失要求凭证(23 张 / 100.0%)",
"| 单号 | 问题描述 |",
"| --- | --- |",
"| FP260011 | 缺失附件 |"
].join("\n");
const plans = describeTemplate(template);
expect(plans).toHaveLength(3);
expect(plans[1]!.demands).toEqual([]); // 纯叙述新章节无需数据依赖
expect(plans[2]!.demands).toContain("riskStats");
const out = renderMonthlyReport(template, sampleData(), plans);
expect(out).toContain("营销线专项业务洞察(新插入章节)");
expect(out).toContain("华东大区");
expect(out).toContain("华南大区");
expect(out).toContain("缺失要求凭证");
});
});
+22 -59
View File
@@ -8,7 +8,7 @@
| 报告状态 | 草稿 |
| 生成日期 | 2026-09-23 |
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**;系统全月成功审核率近 **90%**,自 8 月 8 日迭代后稳定在 **96.07%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
---
@@ -40,15 +40,6 @@ $$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样
*图 1 · AI 与人工审核准确率对比*
### 1.3 系统稳定性
| 项目 | 内容 |
| --- | --- |
| 全月成功审核率 | 近 **90%** |
| 迭代影响 | 8 月第一周失败率较高;自 8 月 8 日迭代后,系统稳定性升至 **96.07%** 的稳定运行常态 |
> **注**:“审核失败”是产品侧的保护机制:当 AI 对单据内容无法形成可靠判断,系统会将该次审核标记为失败,以避免错误影响实际审批。
---
## 2. AI 失准分析(学习优化空间)
@@ -156,45 +147,30 @@ $$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
![效率、准确度、风险拦截、工作量综合对比](assets/图2-综合效益.svg)
---
*图 2 · 综合效益对比*
## 5. 审核分歧与复核归因
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
| 原因分类 | 占比 | 单数 | 核心说明 |
| --- | --- | --- | --- |
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
| 合计 | 100% | 3 张 | — |
**分歧分析与后续建议**:
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
---
## 5. AI 与人工审核一致性示例
## 6. 支撑数据与交付材料
| 示例单号 | 单据模板 | AI 审核驳回意见 | 人工实际退回说明 | 双方一致性 |
| --- | --- | --- | --- | --- |
| FP260022 | 一般费用报销单【发票】- 个人报销 | 墨镜发票(776.15 元,税率 13%)仅开具普通发票,单笔超 500 元未按规定开具增值税专用发票且无免专票佐证,建议驳回换开专票。 | 发票不合规:普票替换成专票 | 专票合规要求 100% 对齐:均严格执行超 500 元 13% 高税率发票必须开具专票的硬性管控 |
| FP260023 | 一般费用报销单【发票】- 个人报销 | 改衣明细表未上传,必备核心附件缺失,不符合改衣费报销要求,建议驳回。 | 附件不合规:未提供改衣费明细表 | 必备明细表缺失一致:AI 精准拦截缺件,人工直接依据未提供改衣费明细表退回 |
| FP260024 | 差旅报销单-定额 | 定额补助消费日期与关联出差申请单行程不符,超出合理出差区间,建议驳回。 | 表单填写错误:结余补贴时间与出差时间不一致 | 行程时间勾稽一致:双方均识别出补贴申请时间与实际行程脱节 |
![示例单据截图](assets/图3-示例截图.svg)
*图 3 · 上述示例单对应的单据截图(可多张)*
---
## 6. AI 通过 / 人工驳回单据明细
| 单据编号 | 单据模板 | AI 审批决策 | 人工审批参考结论 | 原因分类 | 复核结论 | 截图 |
| --- | --- | --- | --- | --- | --- | --- |
| FP260031 | 发票-个人报销 | 同意 | 终止(改衣费超标) | **依规正确(计入 D4)** | 单据改衣费发票、支付凭证及改衣明细表齐全且金额一致,收款人合规,符合改衣费报销规则;人工以口头“改衣费超标”为由终止,规则库中无此标准,AI 依规放行正确。 | (截图) |
| FP260032 | 预提类采购申请 | 同意 | 终止(请核对采购金额;请补充费用计划) | **依规正确(计入 D4)** | 现行规则库对该类申请单不含采购金额与费用计划的强制校验卡口,单据字段与基础凭证合规,AI 依既定规则放行正确。 | (截图) |
| SJ260033 | 收据-个人报销 | 同意 | 终止(无理由) | **AI 失准(不计入分子)** | 单据费用依规则必须提供正规发票,本单仅附收据无发票,不符合科目票据规范,AI 误判放行,属于规则执行错误。 | (截图) |
在上述 **3 笔**单据中:
1. **66.7%(2 / 3 笔)属于依规正确(计入 D4)**:单据在线上规则库下完全合规,退单主要由于经办人撤回、无理由终止,或财务人员执行尚未纳入线上规则库的其他口径。**AI 线上放行依据规则库正确。**
2. **仅有 1 笔属于 AI 真实失准(占全量样本 0.42%)**,已如实扣除准确率,未计入分子。
---
## 7. 支撑数据与材料
### 7.1 分模板准确率与自动审批率
### 6.1 分模板准确率与自动审批率
全量 N = 240:
@@ -209,19 +185,6 @@ $$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样
*(其余 10 类模板从略,实际报告列出全量 16 类)*
### 7.2 跑批原始数据
### 6.2 跑批原始数据与交付台账
见附件《8月单据审批质量审计报告_全量看板.xlsx》。
### 7.3 抽样方法与可复现性
本次复核共抽取 240 笔样本,抽样规则如下:
| # | 抽样规则 |
| --- | --- |
| 1 | 时间全月均衡覆盖,上 / 中 / 下旬各 80 笔 |
| 2 | 100 笔 AI 同意 + 100 笔 AI 驳回 + 40 笔建议复核 |
| 3 | 保底 30 笔大额采购与预付款单据(上中下旬各 10 笔),其余按各报销模板实际发生比例加权分配 |
| 4 | 固定随机种子(取账期截止日)自动执行,全流程清单支持第三方精准复现核验 |
抽样基于账期截止日的固定随机种子执行,全过程可由第三方复现,完整可执行代码随报告附件交付。
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
@@ -63,4 +63,14 @@ describe("native report validator", () => {
expect(check(valid + "\n1、2、70\n$$\\frac{1}{2} = 70\\%$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005" }))
expect(check(valid + "\n$$123456$$\n").issues).toContainEqual(expect.objectContaining({ code: "NM005", message: "公式中的数值 123456 在正文别处找不到,可能与数据脱节" }))
})
test("checks companion ledger CSV and blocks when unreviewed records exist", () => {
const dir = mkdtempSync(join(tmpdir(), "validate-ledger-"))
dirs.push(dir)
const md = join(dir, "报告.md")
writeFileSync(md, valid)
writeFileSync(join(dir, "报告-明细台账.csv"), "SN,单据模板,人机一致性,复核定性结论\nS1,对公,分歧,待复核\n")
const res = validateReportDocument(md)
expect(res.valid).toBe(false)
expect(res.issues).toContainEqual(expect.objectContaining({ code: "LD001" }))
})
})
+75 -13
View File
@@ -5,7 +5,6 @@ export type ReportIssue = { level: "ERROR" | "WARN"; code: string; message: stri
export type ReportValidation = { file: string; valid: boolean; tables: number; figures: number; issues: ReportIssue[] }
type ReportTable = { line: number; header: string[]; rows: Array<{ line: number; cells: string[] }> }
const sectionNumbers = ["1", "2", "3", "4", "5", "6", "7"]
const requiredInfoRows = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
const forbiddenMarks: Array<[RegExp, string]> = [
[/<!--slot:/, "slot 标记"], [/<!--\/slot/, "slot 闭合"], [/<!--@/, "@table/@block 区域标记"],
@@ -89,7 +88,8 @@ export function validateReportDocument(file: string): ReportValidation {
const number = heading[2]!.match(/^(\d+)\./)
if (level === 2 && number) seen.push(number[1]!)
}
if (seen.length && seen.join(",") !== sectionNumbers.join(",")) error("HD002", `## 章节编号应为 ${list(sectionNumbers)},实际 ${list(seen)}`)
const expected = seen.map((_, i) => String(i + 1))
if (seen.length && seen.join(",") !== expected.join(",")) error("HD002", `## 章节编号应自 1 开始连续递增,期望 ${list(expected)},实际 ${list(seen)}`)
const byHeader = (keyword: string) => parsedTables.find((table) => table.header.join("").replaceAll(" ", "").includes(keyword))
@@ -133,25 +133,67 @@ export function validateReportDocument(file: string): ReportValidation {
error("NM003", `${keyword}「${row[1]}」占比 ${decimal(share)}% ≠ ${count.toFixed(0)}/${base.toFixed(0)} = ${(count / base * 100).toFixed(1)}%`)
}
}
// 小节标题里的张数与总览表一致
// 找到当前大章节的文本范围(从当前 ## 开始到下一个 ## 结束,只在本章节内核验小节)
let chapterText = text
for (let i = table.line - 1; i >= 0; i--) {
if (lines[i]?.match(/^##\s+/)) {
let nextH2Line = lines.length
for (let j = i + 1; j < lines.length; j++) {
if (lines[j]?.match(/^##\s+/)) {
nextH2Line = j
break
}
}
chapterText = lines.slice(i, nextH2Line).join("\n")
break
}
}
// 小节标题里的张数与总览表一致(只在本核心章节范围内匹配,不受章节编号与位置影响)
for (const top of tops) {
const section = keyword === "失准类型" ? "2" : "3"
const escaped = top.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
const match = text.match(new RegExp(`###\\s*${section}\\.\\d+\\s*${escaped}[^(]*((\\d+)\\s*张`))
const match = chapterText.match(new RegExp(`###\\s*\\S*\\s*${escaped}[^(\\n]*((\\d+)\\s*张`))
if (match && top.count !== null && Number(match[1]) !== top.count) error(tag, `${top.name} 小节标题写 ${match[1]} 张,总览表写 ${top.count.toFixed(0)} 张`)
}
}
// NM004:§6 明细表的结论分类计数 = 正文数字
// NM004:分歧结论分类计数 = 正文数字
const detail = byHeader("原因分类")
if (detail) {
const correct = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("依规正确")).length
const missed = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("失准")).length
const counts = text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
const miss = text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
if (counts && Number(counts[1]) !== correct) error("NM004", `正文称依规正确 ${counts[1]} 笔,明细表实际 ${correct} 行`)
if (counts && Number(counts[2]) !== detail.rows.length) error("NM004", `正文称合计 ${counts[2]} 笔,明细表实际 ${detail.rows.length} 行`)
if (miss && Number(miss[1]) !== missed) error("NM004", `正文称 AI 失准 ${miss[1]} 笔,明细表实际 ${missed} 行`)
if (detail.header.some((col) => col.includes("单号") || col.includes("单据编号"))) {
const correct = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("依规正确")).length
const missed = detail.rows.filter((row) => row.cells.length > 4 && row.cells[4]!.includes("失准")).length
const counts = text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
const miss = text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
if (counts && Number(counts[1]) !== correct) error("NM004", `正文称依规正确 ${counts[1]} 笔,明细表实际 ${correct} 行`)
if (counts && Number(counts[2]) !== detail.rows.length) error("NM004", `正文称合计 ${counts[2]} 笔,明细表实际 ${detail.rows.length} 行`)
if (miss && Number(miss[1]) !== missed) error("NM004", `正文称 AI 失准 ${miss[1]} 笔,明细表实际 ${missed} 行`)
} else if (detail.header.some((col) => col.includes("单数"))) {
const countIdx = detail.header.findIndex((col) => col.includes("单数"))
const rows = detail.rows.map((row) => row.cells)
const nonTotals = rows.filter((row) => !["合计", "总计", "—"].includes(row[0]!))
const totalRow = rows.find((row) => ["合计", "总计", "—"].includes(row[0]!))
if (countIdx >= 0) {
const sum = nonTotals.reduce((s, r) => s + (numeric(r[countIdx]!) ?? 0), 0)
if (totalRow) {
const totalVal = numeric(totalRow[countIdx]!)
if (totalVal !== null && sum !== totalVal) error("NM004", `原因分类各维度单数之和 ${decimal(sum)} ≠ 合计 ${decimal(totalVal)}`)
}
const counts = text.match(/(\*{0,2}\d+(?:\.\d+)?%\*{0,2},\s*(\d+)\s*笔)/) ?? text.match(/((\d+)\s*\/\s*(\d+)\s*笔)/)
if (counts && nonTotals[0]) {
const c1 = numeric(nonTotals[0][countIdx]!)
if (c1 !== null && Number(counts[1]) !== c1) {
error("NM004", `正文称非判定缺陷 ${counts[1]} 笔,分类表实际 ${c1} 张`)
}
}
const miss = text.match(/真实失准单据[^\d]*(\d+)\s*笔/) ?? text.match(/仅有\s*\*{0,2}(\d+)\s*笔/)
if (miss && nonTotals[1]) {
const c2 = numeric(nonTotals[1][countIdx]!)
if (c2 !== null && Number(miss[1]) !== c2) {
error("NM004", `正文称真实失准 ${miss[1]} 笔,分类表实际 ${c2} 张`)
}
}
}
}
}
// NM005:公式算术自洽,且代入值能在正文别处找到
@@ -168,5 +210,25 @@ export function validateReportDocument(file: string): ReportValidation {
if (!outside.includes(token)) error("NM005", `公式中的数值 ${token} 在正文别处找不到,可能与数据脱节`)
}
}
// 6. 配套台账勾稽门禁(若同目录下存在配套交付的明细台账 CSV)
const baseStem = path.replace(/\.md$/, "")
const ledgerCsvPath = existsSync(`${baseStem}-明细台账.csv`)
? `${baseStem}-明细台账.csv`
: existsSync(resolve(dirname(path), "明细台账.csv"))
? resolve(dirname(path), "明细台账.csv")
: null
if (ledgerCsvPath) {
const csvContent = readFileSync(ledgerCsvPath, "utf8")
const csvRows = csvContent.trim().split("\n").slice(1)
const unreviewedRows = csvRows.filter((r) =>
r.split(",").map((c) => c.replace(/^["'\s]+|["'\s]+$/g, "")).includes("待复核")
)
if (unreviewedRows.length > 0) {
error("LD001", `配套台账(${ledgerCsvPath.split("/").pop()})中存在 ${unreviewedRows.length} 笔未裁决单据(标记为「待复核」),正式交付前必须完成全量裁决`)
}
}
return report
}