Compare commits

...
4 Commits
Author SHA1 Message Date
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
20 changed files with 893 additions and 61 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.6",
"version": "0.11.7",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+7
View File
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [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.7",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
-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.",
+19 -6
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.7: 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.7
short-description: Seal tenant and Hose approval automation (v0.11.7)
---
# 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`)。要点:
- **报告并非一键黑盒交付(人机协同研讨契约)**:数据接口无法自动获得“谁对谁错”的仲裁定性,也无法自动撰写管理归因与整改建议。生成初版 Markdown 后,Agent **严禁直接向客户交付带有 `> ⚠️ 数据说明` 警告框、模板假单号或 `(截图)` 占位符的半成品**,必须进入人机协同研讨模式(Tangent),向用户呈现分歧单据并共创定性分析文本。完整研讨流程、各章节动静边界与校验错误码见 `references/report-templates.md`。
- **推荐轻量 Agent 执笔**:调用 `seal-use report data` 获取干净的 JSON 数据包(含触发的单个判断条件 `triggeredConditions`),由 Agent 亲自将真实数据与复核分析填入 Markdown,避免代码层正则换数的死板与脆弱。
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,初稿保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- 默认模板、配图和校验/渲染引擎由仓库 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 注册表与读写白名单。
- **协同研讨指南**:分歧单据挑选呈现格式、失准深度归因撰写(§2)、系统迭代历程(§1.3)与严格离线校验(NM001~NM005)排查手册,完整参见 `references/report-templates.md`。
@@ -0,0 +1,218 @@
# 月度 AI 审核准确率报告编制与人机协同研讨指南 (Monthly Report Authoring & Tangent Workflow)
本文档面向 AI Agent 与实施运维人员,规范从**月度数据拉取与底稿装配**、**分歧单据人机复核研讨(Tangent)**、**纯文本质性分析与整改建议共创**,到**严格离线校验与多格式商业交付**的端到端标准工作流。
---
## 核心认知与架构分工 (Core Architecture & Division of Labor)
1. **轻量数据接口 + Agent 亲自执笔 (The Lightweight Authoring Model)**:
- **工具层(确定性计算与缓存)**:负责拉取审批运行数据、统计分模板数据、计算准确率公式、记录用户逐单裁决(`review set`)、生成独立矢量图表(`report chart venn`)以及提供离线格式/数值勾稽校验(`report validate`)与全格式编译(`report render`)。
- **Agent 层(智能分析与文档创作)**:Agent 最擅长理解数据、归纳总结、与用户对话,并撰写自然流畅的业务报告。因此,**推荐让 Agent 直接获取轻量数据包(`seal-use report data`),亲自将真实数据、分歧案例与整改建议手工填入 Markdown 模板**,彻底摆脱代码中死板的正则替换与假数据。
2. **严禁交付半成品 (Zero-Mock Delivery Red Line)**:
- 严禁向客户交付带有 `> ⚠️ **数据说明**:...需人工归类后替换` 警告框的半成品。
- 严禁保留模板中写死的假数据(如 `B26002583` 等固定占位单号)或字面 `(截图)` 占位符。
- 严禁跳过 `seal-use report validate` 直接交付未经勾稽校验的文档。
3. **单个判断条件与人机复核契约 (Triggered Conditions & Tangent Contract)**:
- 分歧单据中包含 AI 拦截触发的**单个具体判断条件**(`triggeredConditions`,如“发票日期早于行程日”、“未附改衣明细表”)。
- Agent 获取初版数据后,**必须主动进入“研讨模式”(Tangent)**,向用户呈现这些具体的触发条件,征询真实业务对错裁决,并引导用户共创定性分析文本。
---
## 端到端标准研讨流 (The 4-Stage Lifecycle)
```mermaid
flowchart TD
S1["Stage 1: 获取轻量报告数据包与模板 (report data & template)"] --> S2["Stage 2: 分歧单据人机复核研讨 (Diverged Runs Review Tangent)"]
S2 --> S3["Stage 3: 纯文本深度叙述与质性洞察共创 (Agent 执笔填入 Markdown)"]
S3 --> S4["Stage 4: 离线门禁校验与全格式商业渲染 (report validate & render)"]
```
---
### 第一阶段:获取轻量报告数据包与模板 (Data Pack & Template Scaffold)
#### 推荐方式:轻量数据驱动 (Mode A: Lightweight Data Pack)
1. **拉取纯结构化报告数据包 (JSON)**:
```bash
seal-use report data --month <YYYY-MM> --corp <corpId>
```
*说明:返回纯 JSON 数据,包含当期效能指标(样本量、AI 准确率、采纳率、平均耗时)、公式代入值、分模板统计、TOP 风险标签,以及**全量分歧单据及其触发的具体判断条件(`triggeredConditions`)**,完全不依赖任何 Markdown 模板。*
2. **获取纯净内置模板与生成矢量图表**:
```bash
# 保存纯净的内置月报模板 Markdown
seal-use report template --out reports/<企业名>-<YYYYMM>.md
# 准备配图目录并独立生成动态维恩图 SVG
mkdir -p reports/<企业名>-<YYYYMM>.assets
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
```
#### 传统方式:模板脚手架一键填充 (Mode B: Template Scaffold)
亦可使用经典命令一键拉取并由代码初步组装 Markdown 脚手架与伴随台账:
```bash
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/<企业名>-<YYYYMM>.md
```
*诊断返回 JSON 中的 `notes.humanAccuracyAvailable`,若为 `false` 则说明尚未复核,需进入第二阶段。*
---
### 第二阶段:分歧单据人机复核研讨 (Diverged Runs Review Tangent)
在 AI 审核与人工审批结论相悖的单据中(AI 同意但人工驳回,或 AI 驳回但人工同意),必须由熟悉业务的实施/财务人员裁决真实对错。
1. **提取高价值分歧单据**:
Agent 可直接分析伴随生成的《明细台账.csv》或调用查询命令检索分歧单据:
```bash
# 查看或导出当前月份分歧单据
seal-use report review list --month <YYYY-MM> --corp <corpId>
```
2. **结构化向用户呈现案例并征询裁决 (Interactive Tangent Prompting)**:
挑选 3~5 笔最具代表性的分歧单据,以结构化卡片形式向用户呈现关键上下文:
```markdown
【分歧单据复核研讨】单号:FP2026090123
- 单据模板:一般费用报销单【发票】- 个人报销
- 提交人 / 部门:张三 / 市场运营部
- AI 审核结论:建议驳回(发票开票日期早于出差行程起始日)
- 人工实际操作:直接审批同意(已支付)
👉 请教您对本单的裁决看法:
1. AI 正确(ai_correct):按财务规范确实属于跨期违规,人工属于特批放行,AI 依规放行正确;
2. 人工正确(human_correct):业务实际存在合理提前购票场景,规则未配置豁免,属于 AI 误判;
3. 双方都对(both_correct):规则执行无误,但存在线下特殊批复;
4. 其它/暂无法定性(undecided)。
```
3. **实时录入裁决定性**:
收到用户的确认后,执行 CLI 命令持久化到本地裁决账本:
```bash
seal-use report review set \
--month <YYYY-MM> \
--sn <SN> \
--verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> \
--note "跨期发票已获总监线下邮件特批,规则库缺少该豁免卡口" \
--reviewed-by "实施顾问/财务张老师" \
--corp <corpId>
```
*本地存储路径:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`。*
---
### 第三阶段:纯文本深度叙述与质性洞察共创 (Qualitative Narrative Co-Authoring)
模板中的许多章节属于管理咨询范畴,必须通过与用户沟通讨论,将模板占位符改写为客户真实的业务洞察:
```mermaid
flowchart LR
Review["复核定性成果"] --> Sec2["§2 失准归因与整改方案"]
Context["企业本月动态"] --> Sec1["§1.3 稳定性与迭代历程"]
RiskData["AI 风险统计"] --> Sec3["§3 潜在风险与拦截案例"]
HumanValue["财务反馈"] --> Sec4["§4 综合效益与人力释放"]
```
#### 1. §1.3 系统稳定性与迭代历程
- **模板问题**:内置模板写着死板的“自 8 月 8 日迭代后稳定在 96.07%”。
- **研讨引导**:
> “请问本月企业是否有上线新规则版本、更新豁免白名单,或者合思系统有单据模板调整?我们可以把具体的迭代时间节点与优化成效如实写进‘系统稳定性’一节。”
- **改写产出**:将通用的占位文字改写为真实事件,例如:“9 月 12 日优化‘发票查重与专票强制校验规则’后,全月系统审核成功率稳定在 97.4%”。
#### 2. §2 AI 失准深度归因与整改方案(报告核心技术价值)
- **模板问题**:代码存在硬编码假单号(如 `B26002583`)或默认示例分类。
- **研讨引导**:
> “基于我们在第二阶段复核出的 X 笔 AI 真实失准(`verdict === human_correct`),主要集中在以下两个现象:
> 1. 多附件中部分手写收据金额识别偏差(3 笔);
> 2. 差旅补贴跨自然月计算未自动扣除周末(2 笔)。
> 我们来总结针对这几类问题的整改建议与下月规则库优化计划。”
- **改写产出**:
- 彻底替换 `§2.2 ~ §2.4` 中的单号与问题描述为真实 SN 和真实原因;
- 撰写具体的“整改建议”,如“下期将差旅补贴计算调整为按工作日日历核算”、“针对手写收据调优大模型 OCR 提示词”。
#### 3. §3 潜在风险与拦截价值业务解读
- **业务价值**:AI 拦截了人工放行的风险单据,是向企业管理层证明“AI 审计提升内控质量”的最有力武器。
- **研讨引导**:
> “在人工审核通过的单据中,AI 额外拦截了 28 笔风险,其中 TOP 1 为‘无正规发票直接支付’(16 笔)。这些单据主要发生在哪些部门?我们可以结合公司的差旅/采购内控制度进行强调。”
#### 4. §4 综合效益与人力释放量化
- **质性文案润色**:与客户确认 AI 审核耗时(通常在 10~30 秒)对比财务人工审核周期(通常为 1~3 个工作日),突出“即提即审”的时效提升,以及协助财务防堵税务合规风险(如进项税虚开、专票未取等)的价值。
#### 5. 截图凭证指引 (Screenshots Placement)
- 提醒用户在正式提交前,将关键凭证(如发票实物照片、审批流驳回截图)替换到报告中:
- 将 `assets/图3-示例截图.svg` 替换为真实的代表性单据截图;
- 将 `§6` 明细表格中的 `(截图)` 占位字样替换为具体的图片引用或在附件中打包交付。
---
### 第四阶段:报告重新装配、严格离线校验与全格式导出 (Regenerate, Validate & Render)
1. **重新装配底稿(应用人工裁决)**:
```bash
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/<企业名>-<YYYYMM>.md --overwrite
```
*此时,由于本地已存在 `review-store` 裁决记录,底稿将自动完成指标闭环:人工准确率真实回填、维恩图准确渲染、分模板同意/驳回比与全量范围自动更新。*
2. **更新共创文本**:
使用文件编辑工具将第三阶段共创出的 §1.3、§2、§3、§4 文本精准写入 `reports/<企业名>-<YYYYMM>.md`,替换掉模板占位内容。
3. **执行严格离线门禁校验 (Zero-Error Gate)**:
```bash
seal-use report validate reports/<企业名>-<YYYYMM>.md
```
必须确保**校验通过(`valid: true`,0 ERROR)**。若遇到报错,参考下文排查手册逐一修复。
4. **全格式编译与打包交付 (Multi-Format Rendering)**:
```bash
# 一键导出自包含 HTML、超高精度长图 PNG 与 A4 PDF
seal-use report render reports/<企业名>-<YYYYMM>.md --out build/<企业名>-<YYYYMM>
```
最终交付物清单:
- `build/<企业名>-<YYYYMM>.html`:内嵌图片与 KaTeX 公式样式的单文件自包含 HTML(适合邮件与在线流转);
- `build/<企业名>-<YYYYMM>.png`:高清晰度长图(适合飞书、微信、钉钉大图浏览);
- `build/<企业名>-<YYYYMM>.pdf`:标准 A4 分页打印级 PDF(适合正式汇报与归档);
- `reports/明细台账.xlsx` 与 `明细台账.csv`:审计复核完整底账。
---
## 模板各章节深度剖析与动静边界 (Section Anatomy)
| 章节编号与名称 | 数据来源与机制 | 是否需要人工协同改写 / 研讨 | 说明与关注要点 |
| :--- | :--- | :--- | :--- |
| **标题与报告信息表** | 动态填充 | 否(自动替换) | 自动写入企业名称、统计期间、生成日期与报告编号。 |
| **摘要** | 动态换数 | 建议微调 | 正则自动替换总样本数、AI 准确率与风险拦截数;可根据企业汇报偏好润色开篇。 |
| **§1.1 数据来源与范围** | 动态生成 | 否(自动替换) | 自动汇总样本总量、业务单据模板种类数与决策分布。 |
| **§1.2 核心准确率 & 图 1** | 动态联动 | 否(自动联动) | AI 与人工准确率、公式代入值以及图 1 维恩图由底账与 review-store 动态计算联动。 |
| **§1.3 系统稳定性** | 静态占位 | **必须研讨改写** | 采纳率自动填充,但“迭代影响”必须替换为本月真实的上线与优化历程。 |
| **§2.1 失准构成总览** | 动态 / 模板 | **必须研讨确认** | 需确保维度单数、占比与合计严密勾稽(满足 NM001/NM003)。 |
| **§2.2~2.4 TOP 失准案例** | 模板假数据 | **必须完全替换** | **绝对不能保留假单号**!必须填入第二阶段复核出的真实 Bad Case 与针对性整改建议。 |
| **§3 潜在风险与拦截案例** | 动态标签 + 切片 | 建议研讨润色 | TOP 3 风险标签自动更新,明细案例可结合客户核心财务卡口进行价值解读。 |
| **§4 综合效益 & 图 2** | 半动态 + 静态图 | 建议微调 | 时效与风险笔数自动填充;工作量价值可结合企业实际审批流转特点润色。 |
| **§5 一致性示例 & 图 3** | 动态切片 + 占位图 | 需替换配图 | 表格可自动抽取人机一致单据,图 3 需替换为真实系统截图。 |
| **§6 AI通过/人工驳回明细** | 动态生成 | 需补充截图 | 自动取前 10 笔分歧单及复核结论;最后一列 `(截图)` 需在交付前处理。 |
| **§7 支撑数据与台账** | 动态生成 | 否(自动生成) | §7.1 分模板表、§7.2 配套 Excel 台账、§7.3 全量覆盖声明均由引擎全自动产出。 |
---
## 离线校验错误码排查手册 (Validator Error Code Playbook)
当 `seal-use report validate` 报错时,请根据以下代码快速定位:
- **`NM001` / `NM002`(分类总数与小节单数勾稽不符)**:
- 检查总览表各行单数之和是否等于“合计”行;
- 检查总览表中的单数是否与后续 `### 2.x` 或 `### 3.x` 小节标题中的 `(N 张 / X%)` 严格一致。
- **`NM003`(百分比算术不符)**:
- 检查各行单数除以合计总数得出的百分比,与表格中写的百分比差距是否超过 `0.15%`。
- **`NM004`(明细表行数与正文叙述不符)**:
- 检查 `§6` 叙述中的 `在上述 **N 笔**单据中` 与 `依规正确(计入 D4)`、`AI 真实失准` 数量是否与下表明细行完全相等。
- **`NM005`(公式算术错误或数值孤岛)**:
- 检查 `$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$` 中 $A / B$ 是否算术等于 $C\%$;
- 检查公式里的分子、分母数值是否在正文其他段落中有据可查。
- **`TB001`(表格列数不齐)**:某一行的竖线 `|` 数量与表头不一致,或未对单元格中的 `|` 字符进行 `\|` 转义。
- **`TB002`(表头含加粗)**:Markdown 表头行中严禁使用 `**加粗**`。
- **`HD001` / `HD002`(标题跳级或章节编号不规范)**:
- 二级标题必须严格按 `## 1.`, `## 2.`, ..., `## 7.` 编号;
- 不能出现从 `#` 直接跳到 `###` 的层级跳跃。
- **`INFO001` / `INFO002`(报告信息表缺失或字段为空)**:开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。
- **`IMG001`(图片不存在)**:引用的本地图片路径未找到,检查相对路径是否有效或文件名是否有中文编码问题。
- **`FM001` / `MK001`(模板痕迹或 Frontmatter 残留)**:严禁出现 YAML frontmatter 或 `<!--slot:` 等模板痕迹,必须是纯净 Markdown。
+52 -2
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) {
+31
View File
@@ -622,6 +622,37 @@ 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"],
+6 -6
View File
@@ -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", "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",
];
@@ -1170,6 +1170,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();
+1
View File
@@ -101,6 +101,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealPermissionsConfigsList",
"sealPreferenceGet",
"sealPreferenceThinkingDepthPoliciesList",
"sealReportDataGet",
"sealReportMonthlyGet",
"sealSessionGet",
"sealSimulationBatchGet",
+29 -1
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 = [
@@ -38,5 +38,33 @@ export const reportCapabilities = [
reportId: params.reportId,
maxRuns: params.maxRuns
})
},
{
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
})
}
];
+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/<报告文件>"
}
};
}
@@ -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";
+18 -21
View File
@@ -635,27 +635,24 @@ function replacementRows(
// §2 失准与复核分析明细表(2 列:单号 | 问题描述)
if (columns.length === 2 && columns.includes("单号") && columns.includes("问题描述") && heading.includes("2.")) {
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("2.3") || heading.includes("TOP 2")) sliceIndex = 1;
else if (heading.includes("2.4") || heading.includes("TOP 3")) sliceIndex = 2;
const start = sliceIndex * 3;
const picks = candidates.slice(start, start + 3);
if (!picks.length) return null;
return picks.map((b) => {
const issue = b.reviewNote || b.aiSummary || b.humanComment || b.conditions?.[0] || "规则执行与判定偏差";
return [b.sn, issue];
});
}
return null;
@@ -7,6 +7,7 @@ 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";
const TEMPLATE = join(import.meta.dirname, "..", "templates", "monthly.md");
@@ -346,3 +347,83 @@ 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>");
});
});