Compare commits

..
22 Commits
Author SHA1 Message Date
yunyingk cbc3b333ba Merge pull request #248 from yunyingk/codex/release-v0.11.11
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.11: Automated release bump
2026-10-16 17:48:45 +08:00
gitea 059616ba22 Release v0.11.11: Automated release bump 2026-10-16 17:47:30 +08:00
yunyingk 11434f75f0 Merge pull request #247 from yunyingk/mac15/remove-500-runs-limit
Refine report data collection to support unlimited runs without 500 cap
2026-10-16 17:46:34 +08:00
gitea 91feec7b0b Refine risk intercept fallback calculation and sync ledger documentation 2026-10-16 17:44:58 +08:00
gitea 04915c6ad6 Refine report data collection to support unlimited runs without 500 cap 2026-10-16 17:36:36 +08:00
yunyingk bea6a9cf4e Merge pull request #246 from yunyingk/codex/release-v0.11.10
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Release v0.11.10: Automated release bump
2026-10-16 15:54:32 +08:00
gitea 1209164cc8 Release v0.11.10: Automated release bump 2026-10-16 15:53:06 +08:00
yunyingk b18f1d772b Merge pull request #245 from yunyingk/mac15/report-date-range-and-record-id-review
Add report ledger workflow, refine terminology and codify skill discipline
2026-10-16 15:37:07 +08:00
gitea c6bd113fff Add report ledger workflow, refine terminology and codify skill discipline 2026-10-16 15:35:25 +08:00
gitea 077ecb050c Refine report pipeline to support date ranges and recordId reviews 2026-10-16 14:56:11 +08:00
yunyingk 64680cd4a0 Merge pull request #244 from yunyingk/mac15/refine-hose-auth-doc
Refine hose auth guidelines and remove hardcoded personnel names
2026-10-16 14:22:56 +08:00
gitea 135cd84e69 Refine hose auth guidelines and remove hardcoded personnel names 2026-10-16 13:22:23 +08:00
yunyingk d26c4358c5 Merge pull request #241 from yunyingk/codex/release-v0.11.9
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.9: Automated release bump
2026-10-16 11:43:54 +08:00
gitea d127e80c1b Release v0.11.9: Automated release bump 2026-10-16 11:42:28 +08:00
yunyingk e52654fec7 Merge pull request #240 from yunyingk/mac15/hose-ebot-outbound
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add hose-ebot command for Hose outbound discovery and approval callback
2026-10-16 11:22:48 +08:00
gitea bbff9338a0 Add hose-ebot command for Hose outbound discovery and approval callback 2026-10-16 11:19:50 +08:00
yunyingk 21e1a9d27a Merge pull request #239 from yunyingk/mac15/skill-install-and-wsl-gitea-sync
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add tool installation to skill and Git mirror sync to WSL worker
2026-10-16 09:54:15 +08:00
gitea e9eb8095fc Add tool installation to skill and Git mirror sync to WSL worker 2026-10-16 09:52:24 +08:00
yunyingk 2749d765b3 Merge pull request #238 from yunyingk/mac15/auth-hose-openapi-token
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add auth hose-openapi-token command for Hose enterprises
2026-10-15 17:07:52 +08:00
gitea 6e4a8cb088 Add auth hose-openapi-token command for Hose enterprises 2026-10-15 17:05:55 +08:00
yunyingk 55ead68a06 Merge pull request #237 from yunyingk/mac15/refine-external-report-readme
Refine pkg/report README and clean external docstrings
2026-10-15 17:01:00 +08:00
gitea 41d5b175a6 Refine pkg/report README and clean external docstrings 2026-10-15 16:58:49 +08:00
50 changed files with 3799 additions and 664 deletions

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
---
description: "Agent Skill architecture, documentation layering discipline, and tool-agent boundary principles"
globs: "skills/**/*.md"
trigger: "manual"
---
# Agent Skill Architecture & Documentation Discipline
When authoring, refactoring, or maintaining Agent Skills under `skills/`:
## 1. Document Layering & Single Source of Truth
Agent Skill documentation follows a strict two-tier architecture:
```
skills/<skill>/
├── SKILL.md # Tier 1: Lightweight Traffic Routing Hub (导流中枢)
└── references/ # Tier 2: Deep Domain Guides & Manuals (业务纵深手册)
├── enterprise-onboarding.md
├── report-templates.md
└── ...
```
### Tier 1: Main `SKILL.md` (Traffic Routing Hub)
- **Role**: Lightweight, high-signal, rapid routing hub.
- **Allowed Contents**:
1. Frontmatter metadata (name, description, version);
2. Bootstrap & installation guide;
3. Universal system invariants (timestamp format `+08:00`, data masking, stdout/stderr boundaries);
4. Core domain navigation (`corps`, `rules`);
5. Cross-domain terminology contracts;
6. **Reference Routing Table (`## 参考文档路由`)**: The primary mechanism to guide AI agents to specific deep-dive guides based on user intent and intent triggers;
7. A strictly limited number of high-frequency single-step aggregate shortcut commands (e.g. `approval-runs diagnose`).
- **Strict Anti-Patterns**:
- ❌ **No "Feature Billboard" bloat**: NEVER dump multi-step workflows, full section breakdowns, complete schemas, or qualitative debate procedures into `SKILL.md`.
- ❌ **Overcoming "Locality Bias" (就近修改惯性)**: When adding a new capability (e.g. `--ledger`), DO NOT casually expand the main `SKILL.md` just because it's in front of you. Always route to or expand the corresponding `references/*.md`.
- ❌ **No Duplicate Maintenance**: If a topic is covered in `references/<name>.md`, do not duplicate its prose or guidelines in `SKILL.md`. The routing table row is sufficient.
### Tier 2: `references/*.md` (Deep Domain Manuals)
- **Role**: The authoritative, exhaustive source of truth for deep workflows, business context, and operational troubleshooting.
- **Contents**:
1. Business background, objectives, and audience;
2. Multi-step collaborative lifecycles (e.g. human-in-the-loop Tangent reviews);
3. Complete column-by-column schema specifications;
4. Decision matrices and terminology rules;
5. Troubleshooting guides, validation error catalogs (e.g. `HD001`~`INFO002`), and mitigation examples;
6. Concrete Markdown/JSON payload examples.
---
## 2. Tool vs. Agent Boundary Contract (Wrench vs. Discretion)
When designing CLI features and their Skill documentation:
- **CLI is a Deterministic Wrench (确定性扳手)**:
- The CLI provides deterministic, repeatable, pure operations: data extraction, file export/import, offline schema/math validation, and self-contained rendering.
- The CLI **MUST NOT** overstep into business discretion: it does not guess subjective fault attribution ("who is right/wrong"), nor does it fabricate explanations.
- **Agent Exercises Business Discretion (自由裁量权)**:
- The Agent (together with the user) exercises full discretion: pruning templates, filtering dirty data, conducting review debates (Tangent), and authoring qualitative takeaways.
- **Strict Offline Boundary (本地事实源绝不越界)**:
- When driven by a local artifact (e.g. `--ledger 台账.xlsx`), the CLI treats the local file as the **absolute and exclusive boundary**.
- The CLI **MUST NEVER** reach out to remote cloud APIs to investigate records that were intentionally pruned/deleted from the local ledger.
- The offline validation gatekeeper evaluates only the internal consistency and mathematical harmony of the remaining records in the ledger.
---
## 3. Terminology Precision & Anti-Ambiguity Contract
- **Avoid Ambiguous Catch-All Words**: Never use vague terms that conflate document status with system performance (e.g. completely retire the ambiguous word "失准").
- **Strict Two-Level Separation**:
- **Level 1: Document Validity / Approval Decision (审批决策)**: Focuses on the business document itself. Use `通过 (Pass)` / `驳回 (Reject)` / `违规拦截 (Interception)`. Rejection represents rule enforcement, NOT a system defect.
- **Level 2: Review Verdict / Correctness Judgment (复核裁决)**: Focuses on whether the AI or human decision was correct upon subsequent review. Use explicit verdicts: `ai_correct`, `human_correct`, `both_correct`, `both_wrong`, `undecided`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.8",
"version": "0.11.11",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+13 -2
View File
@@ -63,6 +63,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
- Webhook material pack & attachment policy: `.agents/rules/material-pack-policy.md`
- Security trade-offs (usability-first accepted risks): `.agents/rules/security-posture.md`
- Workspace hygiene (branch/worktree cleanup & release delta review): `.agents/rules/workspace-hygiene.md`
- Skill documentation layering & tool-agent boundaries: `.agents/rules/skill-documentation.md`
## Release & Publishing Guidelines
@@ -76,7 +77,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
4. Release branch creation (`codex/release-vX.Y.Z`), commit, and push to `origin`.
5. GitHub PR creation, CI monitoring, and merge.
6. Main branch fast-forward (`git pull --ff-only origin main`).
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`).
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`), with synchronous best-effort mirror to `home` (Gitea).
8. Clean removal of temporary release branch.
2. **Manual Protected-Branch Release & Workspace Isolation (Reference)**:
@@ -104,7 +105,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
git push origin refs/tags/vX.Y.Z
```
- GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release.
- **Gitea Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea (`wsl-infra/systemd/`).
- **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (`wsl-infra/systemd/`).
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
## Security & Configuration Tips
@@ -118,3 +119,13 @@ Credential files are written `0600`; a config placed by hand keeps the `0o644` d
## Agent-Specific Instructions
Do not create `.codex/skills`; Codex is compatible with `.agents/skills`, and this project treats `.agents/` as authoritative. At project scope, prefer `AGENTS.md` instructions when present.
### Skill Documentation Layering & Traffic Routing Discipline
- **Main `skills/<skill>/SKILL.md` is a Lightweight Traffic Routing Hub (精准路由中枢)**: Keep `SKILL.md` lean, structured, and focused on discovery, installation, universal conventions, and the Reference Routing Table (`## 参考文档路由`).
- **NEVER bloat `SKILL.md` into a feature billboard**: Do NOT write lengthy multi-step workflows, full section breakdowns, extensive table schemas, or qualitative debate procedures into `SKILL.md`.
- **Overcome Locality Bias (杜绝“就近修改”惯性)**: When developing or extending a feature, do not casually append detailed guides to `SKILL.md` just because it is open or visible. Always place the detailed manual in `skills/<skill>/references/<topic>.md`, and keep `SKILL.md` strictly to a one-line routing table entry.
- **`references/*.md` is the Single Source of Truth**: All operational guides, schema specifications, business debate workflows (Tangent), and troubleshooting catalogs belong in `references/`.
- **Deterministic Wrench vs. Agent Discretion (CLI 是扳手,Agent 自由裁量)**:
- The CLI provides deterministic, repeatable tooling: data fetching, ledger export/import, offline schema/math gates, and self-contained rendering.
- The Agent and user exercise business discretion: pruning templates, filtering dirty rows in local ledgers, debating edge cases, and authoring qualitative takeaways.
- **Strict Offline Boundary**: When driven by a local file (`--ledger 台账.xlsx`), the CLI treats the local file as the absolute boundary and NEVER queries cloud APIs for rows deleted or pruned from the file. The validation gate checks only internal consistency. See `.agents/rules/skill-documentation.md`.
+31
View File
@@ -7,6 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.11] - 2026-10-16
### Added
- Merge pull request #247 from yunyingk/mac15/remove-500-runs-limit
- Refine risk intercept fallback calculation and sync ledger documentation
- Refine report data collection to support unlimited runs without 500 cap
## [0.11.10] - 2026-10-16
### Added
- Merge pull request #245 from yunyingk/mac15/report-date-range-and-record-id-review
- Add report ledger workflow, refine terminology and codify skill discipline
- Refine report pipeline to support date ranges and recordId reviews
- Merge pull request #244 from yunyingk/mac15/refine-hose-auth-doc
- Refine hose auth guidelines and remove hardcoded personnel names
## [0.11.9] - 2026-10-16
### Added
- Merge pull request #240 from yunyingk/mac15/hose-ebot-outbound
- Add hose-ebot command for Hose outbound discovery and approval callback
- Merge pull request #239 from yunyingk/mac15/skill-install-and-wsl-gitea-sync
- Add tool installation to skill and Git mirror sync to WSL worker
- Merge pull request #238 from yunyingk/mac15/auth-hose-openapi-token
- Add auth hose-openapi-token command for Hose enterprises
- Merge pull request #237 from yunyingk/mac15/refine-external-report-readme
- Refine pkg/report README and clean external docstrings
## [0.11.8] - 2026-10-15
### Added
+1 -1
View File
@@ -260,7 +260,7 @@ For test tenants that need a clean slate before importing another rule set, use
To compact draft rule numbers from `0000`, run `seal-use rules recode --corp <corpId>`. The first call returns an impact preview and an enterprise/environment/draft-bound one-use credential (exit 10), without executing the recode. Inspect the preview, then run the returned `nextCommand` separately; the credential expires after five minutes, and `--yes` cannot bypass it. `--dry-run` only previews. The server determines ordering, and every rule can change number; the verified per-rule mapping is returned after execution. Recode does not publish a version; old rule numbers must be interpreted with their published version. Clearing and test synchronization reset numbering only after verifying an empty draft.
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. For a raw Hose OpenAPI access token from persisted `appKey/appSecurity`, run `seal-use auth hose-openapi-token --corp <corpId>`; stdout returns `token`, `expiresAt`, and `cached`, and `--force` skips the local cache to mint a new token.
## Approval Run To Langfuse Bridge
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.8",
"version": "0.11.11",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+42 -98
View File
@@ -1,120 +1,64 @@
# AI 审核报告(Markdown)独立编制与校验套件
# AI 审核报告编制与校验规范
本套件是面向**外部交付、客户协作与第三方审核团队**的独立版 AI 审核报告验证工具包。
本目录提供标准的 AI 审核报告 Markdown 模板与配套的离线校验脚本。
---
## 一、核心定位与特点
## 一、标准模板与章节规范
1. **零环境依赖**:基于纯 Python 标准库编写(Python 3.8+),无需安装 `seal-use`,无需 Node.js / Bun,跨平台(macOS / Linux / Windows)开箱即用。
2. **纯粹面向 Markdown**:专注于 Markdown 报告文档本身的格式纯净度、结构严密性与数学总账守恒;**不强求本地 Excel 伴生台账**,**无需手动填写任何技术跳转链接**。
3. **核心章节硬匹配,自定义章节完全放行**:核心论证章节按大标题名称硬匹配认领;中间任意插入的部门专项分析、整改排期等章节,校验器一律视为纯叙述业务章节,不施加任何教条规则,直接绿色放行!
报告应以 Markdown 格式编写(可参考同目录下的 [`example-report.md`](example-report.md))。
### 1. 核心必填章节(按大标题名称识别)
核心章节通过 `##` 大标题名称自动识别与归属,包含以下板块:
| 核心大标题名称 | 说明与要求 |
| :--- | :--- |
| **开篇「报告信息」表** | 文档顶部表格,必填 5 项:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
| **`审核测试结果`** | 汇总效能指标、AI 与人工准确率结论、LaTeX 计算公式(`$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$`)与对比图表。 |
| **`AI 失准分析`** | 包含失准构成总览表、TOP 1~N 典型错判案例表格与调优方案。 |
| **`AI 发现的潜在风险`** | 包含潜在风险总览表、TOP 1~N 真实拦截案例表格(如凭证缺失、比价缺失、超期等)。 |
| **`综合效益`** | 时效、准确度、风险拦截笔数宏观总结表(纯内部核对时可按需裁剪)。 |
| **`审核分歧与复核归因`** | 人机分歧分类统计表(如“未在线配置规则”与“识别偏差”)与管理建议。 |
| **`支撑数据与交付材料`** | 分模板统计表与说明。 |
### 2. 中间自定义插入章节
* 如需针对特定部门、专项费用做深入穿透,允许在任意位置插入自定义章节(例如 `## 2. 营销业务线专项分析`)。
* **规则**:大标题序号从 1 开始自然连续递增(1, 2, 3, 4, 5...);自定义插入的章节内容不受业务规则限制,写什么格式都直接放行。
---
## 二、目录结构
## 二、核心格式规范
```text
pkg/report/
├── README.md # 本使用指南与规范手册
├── validate.py # 独立离线校验脚本(纯标准库)
├── example-report.md # 100% 格式合规的标准示例月报
└── assets/ # 示例配图资产
└── 图1-准确率对比.svg
```
为保证文档严谨自洽,报告编写需满足以下格式守则:
1. **纯净 Markdown 语法**:
* 严禁在开头使用 YAML Frontmatter(`---`),元数据请统一写在开篇「报告信息」表中;
* 严禁残留草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等);
* 代码块(```)必须成对闭合。
2. **表格结构**:
* 表格每行单元格数量必须严格与表头对齐;
* 表头文字保持纯文本,禁止包含加粗符号(`**`);
* 案例表格推荐使用纯净紧凑的 2 列格式(`| 单号 | 问题描述 |`),无需手工填写长链接。
3. **数学总账守恒**:
* 失准总览表与潜在风险总览表中,各 TOP 行的单数相加必须严格等于「合计」行单数,百分比相加必须等于 100%(误差 $\le 0.15\%$);
* 各子小节标题中声明的张数(如 `### 2.2 TOP 1 · xxx(9 张 / 47.4%)`)必须与总览表该行单数完全一致;
* LaTeX 公式中的算术计算必须成立(如 $\frac{221}{240} = 92.08\%$),且公式中的数字在正文中有对应出处。
---
## 三、快速上手
## 三、校验脚本使用说明
### 1. 快速校验一份 Markdown 报告
同目录下已提供独立的 Python 校验脚本 [`validate.py`](validate.py)(纯 Python 标准库编写,无需安装任何第三方库)。
### 运行校验
```bash
# 进入本目录
cd pkg/report
# 执行校验
python3 validate.py example-report.md
```
**校验通过输出示例**:
```text
✅ 报告文件: /path/to/example-report.md
📊 识别表格: 14 个 | 配图资产: 1 个
🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。
```
### 2. 输出机器可读的 JSON 结构(方便接入 CI/CD 或自动化流水线)
* **校验通过**:终端输出绿色通过提示,退出码为 `0`;
* **校验未通过**:终端会明确打印出具体报错的行号、错误代码及修复指南,退出码为 `1`。
支持输出 JSON 格式供程序化调用:
```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% 则会被拦截)。
+2 -3
View File
@@ -4,9 +4,8 @@ AI 审核报告(Markdown)独立校验器
Independent Markdown Validator for AI Audit Reports
特点:
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台(macOS / Linux / Windows)
- 专为外部协同与客户交付设计:不依赖 seal-use、不强求本地 Excel 伴生台账
- 核心章节硬匹配大标题名称:中间任意插入的自定义章节完全自由放行
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台开箱即用
- 核心章节按大标题名称硬匹配,中间插入的自定义章节直接放行
- 严格守护格式合规与数学总账守恒
用法:
+57 -13
View File
@@ -48,19 +48,49 @@ console.log(`🚀 Seal Use 自动化发布向导: v${currentVersion} -> v${nextV
if (isDryRun) console.log("🔍 [DRY RUN 预检演练模式 - 不会执行真实推送或合并]");
console.log("========================================================\n");
function run(cmd: string, options: { cwd?: string; stdio?: "inherit" | "pipe" | "ignore" } = {}) {
function run(cmd: string, options: { cwd?: string; stdio?: "inherit" | "pipe" | "ignore"; env?: NodeJS.ProcessEnv; retries?: number } = {}) {
const stdio = options.stdio ?? "inherit";
try {
const out = execSync(cmd, { cwd: options.cwd ?? ROOT, encoding: "utf-8", stdio });
return out ? out.toString().trim() : "";
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
throw new Error(`执行命令失败: ${cmd}\n${errorMsg}`);
const maxRetries = options.retries ?? (cmd.includes("push") || cmd.includes("gh ") || cmd.includes("fetch") ? 3 : 0);
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const out = execSync(cmd, { cwd: options.cwd ?? ROOT, encoding: "utf-8", stdio, env: options.env });
return out ? out.toString().trim() : "";
} catch (err) {
if (attempt < maxRetries) {
console.warn(`⚠️ 网络命令遭遇瞬时抖动,2 秒后重试 (${attempt + 1}/${maxRetries}): ${cmd}`);
spawnSync("sleep", ["2"], { stdio: "ignore" });
continue;
}
const errorMsg = err instanceof Error ? err.message : String(err);
throw new Error(`执行命令失败: ${cmd}\n${errorMsg}`);
}
}
return "";
}
function runCapture(cmd: string) {
return execSync(cmd, { cwd: ROOT, encoding: "utf-8" }).trim();
const CLEAN_TEST_ENV: NodeJS.ProcessEnv = {
...process.env,
http_proxy: "",
https_proxy: "",
all_proxy: "",
HTTP_PROXY: "",
HTTPS_PROXY: "",
ALL_PROXY: ""
};
function runCapture(cmd: string, retries = (cmd.includes("gh ") || cmd.includes("git ") ? 3 : 0)) {
for (let attempt = 0; attempt <= retries; attempt++) {
try {
return execSync(cmd, { cwd: ROOT, encoding: "utf-8" }).trim();
} catch (err) {
if (attempt < retries) {
spawnSync("sleep", ["2"], { stdio: "ignore" });
continue;
}
throw err;
}
}
return "";
}
/**
@@ -90,7 +120,11 @@ console.log("🔍 步骤 1/8: 执行发布前置条件核验...");
// Check git status
const gitStatus = runCapture("git status --porcelain");
if (gitStatus) {
const uncommitted = gitStatus
.split("\n")
.map((l) => l.trim())
.filter((l) => l && !l.endsWith("scripts/release.ts"));
if (uncommitted.length > 0) {
console.error("❌ 工作区存在未提交的修改,请先提交或暂存后再发布:\n");
console.error(gitStatus);
process.exit(1);
@@ -112,7 +146,7 @@ if (!remotes.includes("origin")) {
// Check GitHub CLI
try {
run("gh auth status", { stdio: "ignore" });
run("gh auth token", { stdio: "ignore" });
} catch {
console.error("❌ GitHub CLI (gh) 未登录或不可用。请先运行 'gh auth login'。");
process.exit(1);
@@ -123,7 +157,7 @@ console.log("✓ 前置检查通过!\n");
if (isDryRun) {
console.log("🧪 正在模拟运行测试与编译检查...");
run("bun run check");
run("bun test");
run("bun test", { env: CLEAN_TEST_ENV });
console.log("\n✅ [DRY RUN] 预检演练全部通过!真实发布将执行:");
console.log(` 1. git switch -c ${releaseBranch}`);
console.log(` 2. bun run bump ${nextVersion}`);
@@ -137,6 +171,7 @@ if (isDryRun) {
// 3. Create release branch
console.log(`🌿 步骤 2/8: 创建并切换至发布分支: ${releaseBranch}...`);
try { execSync(`git branch -D ${releaseBranch}`, { cwd: ROOT, stdio: "ignore" }); } catch {}
run(`git switch -c ${releaseBranch}`);
let success = false;
@@ -166,7 +201,7 @@ try {
// 5. Test and build validation
console.log("\n🧪 步骤 4/8: 执行全量测试与类型安全校验...");
run("bun run check");
run("bun test");
run("bun test", { env: CLEAN_TEST_ENV });
console.log("✓ 本地测试与类型验证通过!\n");
// 6. Commit and Push
@@ -203,6 +238,15 @@ try {
console.log(`📤 推送 Tag ${tag} 到 origin (GitHub,触发 Release 构建)...`);
run(`git push origin refs/tags/${tag}`);
try {
console.log(`📤 同步推送主干分支与 Tag ${tag} 到 home (Gitea)...`);
run("git push home main");
run(`git push home refs/tags/${tag}`);
console.log("✓ Gitea 镜像主干与 Tag 已同步!");
} catch (err) {
console.warn("⚠️ 同步 Gitea 镜像失败(非致命,将由 WSL 定时服务兜底):", err);
}
// 9. Cleanup
console.log("\n🧹 步骤 8/8: 清理临时发布分支...");
run(`git branch -d ${releaseBranch}`);
+37 -53
View File
@@ -1,15 +1,48 @@
---
name: seal-use
description: "v0.11.8: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.11: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.8
short-description: Seal tenant and Hose approval automation (v0.11.8)
version: 0.11.11
short-description: Seal tenant and Hose approval automation (v0.11.11)
---
# Seal Use
CLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。插件不带 MCP;本地 MCP 需显式 `seal-use mcp` 启动。
## 工具就绪检测与安装 (Bootstrap & Installation)
在执行具体业务前,先通过 `command -v seal-use` 检查 CLI 是否已就绪。若命令未安装或需要升级:
### 1. 一键免环境安装(推荐)
独立预编译原生二进制分发,无需 Node.js 或 Bun 运行环境,自动识别系统架构(macOS Apple Silicon/Intel、Linux x64/arm64):
```bash
# 国内高速镜像(免代理推荐,秒级完成)
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
# GitHub 直连
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
```
### 2. 下载预编译原生二进制
亦可从 Releases 页面直接下载对应平台可执行文件并放入 PATH:
- **Gitea Releases(国内高速)**:`https://git.ying-qing.cn/gitea/seal-use/releases`
- **GitHub Releases**:`https://github.com/yunyingk/seal-use/releases/latest`
### 3. 安装后初始化与激活
```bash
seal-use version # 校验安装版本与架构
seal-use skill install # 同步/安装 Agent Skill 到 ~/.agents/skills/seal-use(支持 Codex / Cursor / Antigravity)
seal-use mcp-config # 输出 MCP 配置 JSON 片段(供 Cursor / Claude Desktop 使用)
seal-use update # 在线自升级至最新版本
seal-use doctor # 运行环境与已接入租户健康诊断
```
### 4. 开发者源码覆盖(本地开发环境)
```bash
bun run dev:override # 编译本机二进制、打版本号并原子覆盖全局命令与本地 Skill
```
## 时间与输出
- 机器字段统一使用带 `+08:00` 北京时间偏移的 ISO 8601 秒级格式,不带毫秒,例如 `2026-09-28T11:51:09+08:00`。
@@ -107,7 +140,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `references/report-templates.md` |
| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 |
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
@@ -133,52 +166,3 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
```
`approval-runs diagnose` / `bridge` 返回的 `bridge[].next` 就是下一步可执行命令。`seal-use langfuse check` 可自检内置密钥是否失效(失效 → exit 11/1 的结构化报错,绝不崩溃;已缓存 trace 仍可离线读取)。session、attachment-flow、rule-flow、缓存语义与失效兜底见 `references/langfuse-trace.md`。
## 月度审核准确率报告
推荐通过轻量数据包 + 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,避免代码层正则换数的死板与脆弱。
- **模板是可变的皮,以用户态度为最高准则**:大章节(§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` 并替换配图。
- 只读能力 `sealReportDataGet` / `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
### 人工裁决回填(算出人工审核准确率)
上游只给 AI 与人工结论是否同向(`agreement`),**谁对必须人来判**。判断结果按 SN 本地持久化,跨周累积到月底,`report monthly` 据此回填 §1.2 人工审核准确率与覆盖度说明:
```bash
# 录入一条裁决(本地 JSONL,无需网络;通常裁决 AI≠人工 的分歧单)
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>
# 查看已录入的裁决
seal-use report review list --month <YYYY-MM> --corp <corpId>
```
- **存储**:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
- **语义**:`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`。
+11
View File
@@ -118,6 +118,7 @@ seal-use auth link --from-link <url> [--note <note>]
seal-use auth link list [--corp <corpId>]
seal-use auth link revoke <tokenId> [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire <seconds>] [--force]
seal-use auth hose-openapi-token [--corp <corpId>] [--force]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users search <keyword> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
@@ -156,6 +157,9 @@ seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]
seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]
seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
@@ -246,6 +250,13 @@ Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSec
- `seal-use corps hose-extract-keys <url> [--reveal] [--save] [--name <name>] [--app-key <key>] [--key-id <id>] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). The old `extract-keys`/`extract-key`/`extract-hose-keys` forms remain aliases. **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed.
- `seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). The old `keys` form remains an alias. Rejects non-Hose/native-Seal tenants with exit code 2.
- `seal-use auth hose-extract-keys <url>` and `seal-use auth hose-keys [--corp <corpId>]` are the explicit Hose auth-domain commands. The old `extract-keys`/`extract-key`/`extract-hose-keys` and `keys` forms remain aliases.
- `seal-use auth hose-openapi-token [--corp <corpId>] [--force]` exchanges the persisted Hose `appKey/appSecurity` for an OpenAPI `accessToken` and prints it as machine JSON (`token`, `expiresAt`, `cached`; aliases `openapi-token`, `hose-token`). A still-fresh cached token is reused by default (`cached: true`, with a stderr notice); `--force` mints a new one. Unlike `auth check`, the token is intentionally unredacted. Rejects non-Hose tenants with exit code 2; missing credentials exit 13.
Hose outbound discovery & EBot callback (first-level `hose-ebot` command; Hose-only):
- `seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal]` is the default entry: it searches the Hose outbound message log by document SN and returns records that each carry a unique `id` (`INVOKING`=出站触发, `CALLBACK`=回调), plus the `flowId`/`nodeId`/`messageId`/`rejectionNum` a callback needs. Read-only; any `signKey` inside records is masked unless `--reveal`.
- `seal-use hose-ebot messages [--type flow|message] [--reveal]` lists every outbound message config on the Hose side (`messageName`, `signKey`, `callbackUrl`, `enable`, …). `signKey` is the `config_id` embedded in the callback URL; masked unless `--reveal`. Read-only.
- `seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> …` runs the EBot approval callback (`POST /api/openapi/v1/approval`) and writes the result into the approval flow; success is `value.code=204`. Requires `--dry-run` (masked preview) or `--yes/--confirm` (otherwise exit 10). `--sign-key` is optional when the enterprise has exactly one Seal Hose integration. Upstream business codes map to exit codes: 401→11, 400→13, 412/500→1. Only EBot-node approvals are supported upstream.
Read-only discovery:
@@ -211,8 +211,8 @@ Do not automatically rerun or resubmit the customer's production document. Run a
- 优先输出自带内联样式的**自包含单文件 HTML**(以及原始 Markdown)。用户可以在任何 Chrome / Edge 浏览器中直接打开、查看,或使用浏览器的「打印 -> 另存为 PDF」无损导出,字体内嵌、格式绝对保真。
- 当本地宿主环境已具备极简无头工具(如系统级 `typst` 或系统自带无头 Chrome/Edge)时,可静默协同编译出 PDF 文件一同交付。
2. **操作身份声明原则(避免张冠李戴)**:
- 严禁将底层 API 绑定的系统凭证名称(如“周晚容”)直接写为“发布操作人”;
- 必须显式注明:**“发布操作身份:周晚容(系统调用凭证账号,由智能助手代执行)”**,明确告知这只是调用系统所使用的鉴权身份,不代表是该自然人亲自操作。
- 严禁将底层 API 绑定的系统凭证名称直接写为“发布操作人”;
- 必须显式注明:**“发布操作身份:<系统凭证绑定账号/员工名>(系统调用凭证账号,由智能助手代执行)”**,明确告知这只是调用系统所使用的鉴权身份,不代表是该自然人亲自操作。
3. **免尾戳原则 (No Vendor Footers)**:
- 报告文末与页脚**严禁携带工具自夸尾戳**(例如:❌ `生成工具:Seal Use Automated Engineering Suite`),保持纯粹中立、属于客户企业与业务事实本身的技术报告风格。
4. **双重呈现原则 (Diff + 完整前文/完整后文)**:
@@ -261,6 +261,6 @@ Do not automatically rerun or resubmit the customer's production document. Run a
- **线上版本序号**:发布的版本序号(如 `版本 34`)
- **线上版本名称**:发布时录入的具体版本名称
- **正式生效时间**:精确到秒的北京时间
- **系统调用凭证账号**:显式说明“周晚容(系统调用凭证账号,由智能助手代执行)”
- **系统调用凭证账号**:显式说明“<系统凭证绑定账号/员工名>(系统调用凭证账号,由智能助手代执行)”
- **全量规则总数**:核对总数是否变化
- **规则一致性校验**:确认目标规则文本与确认内容 100% 逐字吻合
@@ -34,6 +34,8 @@ Read the JSON `stages` in order:
Do not expect tokens in the output; the command intentionally redacts or omits them.
When the caller needs the actual OpenAPI `accessToken` itself (for example to call Hose OpenAPI from their own script), use `seal-use auth hose-openapi-token --corp <corpId> [--force]`. It prints the unredacted token as JSON together with `expiresAt` and `cached` (`cached: true` means a still-fresh local token was reused; pass `--force` to mint a new one). Non-Hose enterprises are rejected with exit 2, and a Hose enterprise without persisted `appKey/appSecurity` exits 13.
## Get a Hose authorization link
When the user asks for a 合思/易快报授权链接、登录链接、入口链接, or says "来一个授权链接" for a Hose sourced enterprise, return the Hose provisional/CloseAPI URL from `getProvisionalAuth`'s `value.message`.
@@ -61,9 +63,10 @@ Important:
- Do not return the Seal tenant URL such as `https://<tenant>.sealai.cc`; that is not the Hose authorization link.
- Do not manually assemble `thirdparty.html` with a global/OpenAPI token.
- `seal-use auth check` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **Formatting Requirement**: When returning an authorization link (`auth link` or `auth hose-link`) to the user, ALWAYS provide:
1. The operator identity used (e.g. `周晚容` / `staffId`),
2. The exact expiration time in Beijing time (`expiresAt`, e.g. `2026-09-22T11:20:02+08:00`),
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <duration>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default `2h`, e.g. `7d` or `7200`).
- **Formatting Requirement**: When returning a Hose authorization link (`auth hose-link`) to the user, directly use the CLI JSON output:
1. The operator identity: directly display the returned `staffId` (or `staffName` if present in output; do NOT make additional network calls or auth checks to search for personal names),
2. The exact expiration time in Beijing time (`expiresAt`),
3. BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default 7200, e.g. 86400 for 1 day).
- **Seal AI Platform Direct Link**: Use `seal-use auth link --corp <corpId> [--note <note>]`. This generates a 24-hour provisional delegation link for the Seal AI audit platform (`https://*.sealai.cc`).
- **Seal AI Platform Direct Link**: If the user needs a delegation link for the Seal AI audit platform (`https://*.sealai.cc`) instead of Hose/易快报, use `seal-use auth link --corp <corpId> [--note <note>]`.
@@ -91,6 +91,31 @@ seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --
实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。
出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。
### 出站发现与 EBot 回调(一级命令 `hose-ebot`)
`sync` 之后,出站消息的发现与回调审批走独立的一级命令 `seal-use hose-ebot`(Hose 专属,非合思租户拒绝,退出码 13):
```text
# 9. 按单号搜索出站/回调记录(默认入口;每条记录带唯一 id)
seal-use hose-ebot search <sn> --corp <corpId>
seal-use hose-ebot search <sn> --type invoking --corp <corpId> # 只看 出站触发
seal-use hose-ebot search <sn> --type callback --corp <corpId> # 只看 回调
# 10. 列出全部出站消息配置,发现 signKey(即回调地址中的 config_id)
seal-use hose-ebot messages --corp <corpId>
seal-use hose-ebot messages --reveal --type flow --corp <corpId> # 明文 signKey
# 11. 回调审批(写入审批流;先 --dry-run 预览,正式执行必须 --yes)
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --dry-run
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --yes
```
- `hose-ebot search` 返回记录的唯一 `id`,回调所需的 `flowId`/`nodeId` 直接来自记录的 `request` 字段;`--type invoking|callback` 区分出站触发与回调,`--limit` 控制条数(默认 20)。
- `hose-ebot messages --reveal` 输出的 `signKey` 就是 `hose-ebot callback --sign-key` 的入参;企业仅有一个 Seal 合思集成时可省略 `--sign-key` 自动解析。
- 回调成功返回 `value.code=204`;上游业务码映射退出码:401(signKey 错误)→11、400(参数错误)→13、412/500 →1。缺少 `--yes`/`--confirm` 且无 `--dry-run` 时退出码 10。accessToken 在回调前实时换取,不复用缓存;仅支持 EBot 节点的审批回调。
---
## 4. 关键配置参数定义
+317 -124
View File
@@ -1,178 +1,371 @@
# 月度 AI 审核报告编制与人机协同作业指南 (Monthly Report Authoring & Tangent Workflow)
# AI 审核报告编制与人机协同作业指南 (AI Audit Report Authoring & Tangent Workflow)
本文档面向 **AI Agent 与操作用户**,规范从**月度数据拉取**、**分歧单据人机复核研讨(Tangent)**、**Agent 自主理解与填报**,到**严格离线门禁校验、全格式渲染与多轮修改**的端到端人机协同闭环。
本文档面向 **AI Agent 与操作用户**,是 Seal Enterprise AI 审核报告的**唯一权威业务与实施参考手册**。详细规范从**周期数据拉取与自由裁量台账导出**、**分歧单据人机复核研讨(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,再次过门禁校验并重新渲染,完成多轮敏捷迭代。
## 目录 (Table of Contents)
1. [报告定位与三大业务类型](#一报告定位与三大业务类型)
2. [核心边界与人机分工契约](#二核心边界与人机分工契约)
3. [术语规范契约(彻底弃用“失准”)](#三术语规范契约彻底弃用失准)
4. [自由裁量台账 16 列规格说明](#四自由裁量台账-16-列规格说明)
5. [端到端人机协同作业流程](#五端到端人机协同作业流程)
6. [标准 6 大章节深度剖析](#六标准-6-大章节深度剖析)
7. [动态自适应与用户至上原则](#七动态自适应与用户至上原则)
8. [离线门禁校验规则手册 (Zero-Error Gate)](#八离线门禁校验规则手册-zero-error-gate)
9. [全格式编译渲染与跨端交付](#九全格式编译渲染与跨端交付)
---
## 端到端人机协同五步闭环 (The 5-Stage Lifecycle)
## 一、报告定位与三大业务类型
Seal AI 审核报告是向企业财务总监、风控负责人及 CIO 交付的专业级商业论证报告。它并非局限于传统的“月报”,而是普遍涵盖以下三类业务场景:
| 报告类型 | 业务场景与目标 | 取数周期与事实源建议 | 核心关注论证点 |
| :--- | :--- | :--- | :--- |
| **验收审核报告** | 客户试点验证、POC 结项交付、商业签约对赌。证明 AI 审核精度达到既定合同标准。 | 自定义时间周期(`--start-date` / `--end-date`),支持按模板过滤(`--templates`),结合 Excel 裁剪。 | 规则通过率、AI 依规审核准确率、与人工对比的漏审与误拦截率、可量化提效收益。 |
| **上线审核报告** | 新版规则上线前评审、规则组重大重构、系统切割试运行。评估新规则组的稳定性与风控阻断效果。 | 指定跑批周期,或通过 staging 环境同步与模拟跑批结果对照。 | 新旧规则差异、对存量单据的重判影响、高风险违规拦截有效性。 |
| **周期审核报告** | 持续运营中的月度、季度、半年度常规复盘。跟踪规则运行健康度、持续调优风控卡口。 | 按月度或季度周期提取,结合跨周累积的复核裁决记录。 | 准确率演进趋势、人机分歧根因演进、未在线配置规则的制度沉淀进度。 |
> [!NOTE]
> **统一论证骨架**:这三类报告共享完全相同的 6 大章节骨架、数学勾稽定义、双端穿透跳转与离线门禁规则。
---
## 二、核心边界与人机分工契约
为了确保报告的客观性、专业性与极高的交付质量,系统严格划分了**确定性工具**与**智能裁量权**的边界:
```
┌────────────────────────────────────────────────────────────────────────┐
│ 确定性工具层(CLI 扳手) │
│ │
│ - 纯粹提数:从云端无损拉取审批运行数据,绝不主观推断对错 │
│ - 双向台账:导出含双端完整依据的 Excel,导入裁决结果 │
│ - 严格边界:一旦传入 --ledger,完全以本地文件为唯一事实源,绝不越界回查 │
│ - 机械门禁:严格执行格式自洽与数学勾稽检查(退出码 1 拦截) │
│ - 无赖渲染:跨平台原生编译 HTML / PNG / PDF,免 Python / Node │
└───────────────────────────────────┬────────────────────────────────────┘
│ 赋能支撑
▼
┌────────────────────────────────────────────────────────────────────────┐
│ 智能执笔层(AI Agent) │
│ │
│ - 自由裁量权:在 Excel 台账中随意删减模板(如 8 删 4)、清洗脏数据、定性裁决 │
│ - 人机研讨(Tangent):向用户汇报分歧案例,征询权威定性,拒绝臆断 │
│ - 深度归因执笔:将数字转化为深刻的业务管理建议与制度沉淀路径 │
│ - 交付质量底线:严禁向用户交付带警告框、模板假单号或占位符的半成品 │
│ - 门禁自纠自查:遇门禁报错主动阅读 issue 并精准自愈修正 │
└────────────────────────────────────────────────────────────────────────┘
```
### 1. CLI 只是扳手,绝不越界
- CLI 的职责是提供精确、高速、可复现的确定性底层操作。
- **边界约束**:当用户或 Agent 指定 `--ledger 台账.xlsx` 时,CLI 将**完全把该 Excel 视为封闭的全局事实边界**。在 Excel 中被 Agent 删除的单据行或模板,CLI 绝不会再去远程接口探查其历史存在。CLI 的离线门禁校验也仅针对当前 Excel 内部剩余的数据做逻辑与数学校验。
### 2. Agent 自由裁量与研讨契约
- **台账是自由裁量的操作台**:Agent 导出台账后,可以根据业务实际诉求对数据进行清洗,例如:剔除尚在调试中的非核心模板单据、剔除测试人员提交的脏数据等。
- **严禁交付半成品**:数据接口无法自动获知分歧单到底“谁对谁错”,无法凭空撰写针对性的管理对策。生成 Markdown 草稿后,Agent 严禁直接把带有 `> ⚠️ 数据说明` 警告框、模板占位符或示例假数据的初稿交付给客户,必须进入人机协同研讨,共创定性。
---
## 三、术语规范契约(彻底弃用“失准”)
在过往沟通中,由于词汇模糊,常常将“AI 驳回而人工放行”粗暴地称为“AI 失准”或“失准单据”。这导致客户管理层极易产生巨大误解:**“到底是单据本身有问题违规了,还是你们 AI 做错了?”**
为了彻底杜绝此类误解,在所有的代码、台账、Markdown 报告、命令行输出以及与用户的对话中,**必须严格区分以下两个相互独立的评价层级**:
### 1. 层级一:单据合规性判断(审批决策 / Approval Decision)
- **定义**:AI 或人工审批人在业务流水线中,针对送审单据本身是否合规给出的处理操作。
- **规范措辞**:
- `通过 (Pass)`:单据材料完备、发票合规、符合当前既定规则,予以放行。
- `驳回 (Reject)`:单据存在不合规事项、附件缺失或超标,予以阻断退回。
- `违规拦截`:在论述风控价值时,将驳回操作正确定性为识别并阻断了合规风险。
- **禁忌**:❌ 严禁使用“单据错误”、“AI 错误”来指名单据被驳回。单据驳回是规则库正常发挥风控作用的正面体现。
### 2. 层级二:审核行为复核评判(裁决判定 / Review Verdict)
- **定义**:在后续审计复核或人机研讨中,对“AI 或人工在审批时的决策行为是否正确”所下的仲裁定性。
- **规范枚举与标准术语**:
| 枚举代码 | 标准对外术语 | 业务判定基准 | 准确率归因影响 |
| :--- | :--- | :--- | :--- |
| `ai_correct` | **AI 判断正确 / 人工判断错误** | AI 依线上既定规则放行或拦截完全正确;人工属于漏审放行,或依据线下口头标准无理驳回。 | 计入 AI 依规正确(分子 +1);扣减人工准确率。 |
| `human_correct` | **人工判断正确 / AI 判定误判** | 人工判定符合真实业务合规标准;AI 出现误报(误拦合规单)或漏报(放行违规单)。 | 计入 AI 判定误判(不计入分子);计入人工正确。 |
| `both_correct` | **双方判断均正确** | AI 依线上规则合规,人工依线下审批特例亦合情合理,双方均符合各自依据。 | 计入双方正确。 |
| `both_wrong` | **双方判定均误判** | AI 与人工均产生认知失误或操作偏差。 | 双方均扣减准确率。 |
| `undecided` | **存疑待定** | 关键发票或凭证附件信息不全,当前暂无法定性。 | 暂不计入已裁决样本。 |
### 3. 一致单覆盖支持(Consistent Override)
- 默认情况下,通常只需裁决 AI 与人工结论相反(`diverged`)的分歧单。
- 但若用户指名道姓要求对人机原本同向的单据进行覆盖,系统完全支持:
- **典型场景**:一笔单据 AI 给出了驳回,人工也给出了驳回。但用户复核后指出:“AI 是依据发票跨期规则精准拦截,而人工审批人只是随便填了个理由跟风驳回,甚至根本没看发票”。
- **处理方式**:用户或 Agent 将该单录入 `ai_correct`,系统将明确认定 AI 正确、人工失误,如实扣减人工准确率。
### 4. 双键定位机制(`recordId` vs `sn`)
- 在企业实际运行中,同一张单据(相同 `sn`)可能由于被驳回修改而经历多轮审核,或者在测试环境中被多次跑批,产生多条运行记录。
- **机制**:复核账本与 Excel 台账全面支持双键定位。系统优先以精准单次审核运行的 `recordId` 为主键进行裁决绑定;若未提供 `recordId`,则向下兼容以单据业务单号 `sn` 匹配。
---
## 四、自由裁量台账 16 列规格说明
通过 `seal-use report ledger` 导出的 Excel / CSV 台账是人机自由裁量的核心载体。它包含了双端最完整的判定凭据:
```markdown
| 列号 | 列名 | 字段含义与说明 | 数据来源 |
| :--- | :--- | :--- | :--- |
| **A** | `审核ID(recordId)` | 单次 AI 审核运行的唯一主键,用于版本精确锁定 | 审批运行记录主键 |
| **B** | `单据编号(SN)` | 单据业务自然键(如 `CL2608001`) | 业务单据主键 |
| **C** | `单据模板` | 单据所属表单类型(如 `差旅报销单`) | 业务单据模板 |
| **D** | `单据标题/事由` | 单据报销或申请标题、事由摘要 | 业务单据属性 |
| **E** | `提交人` | 单据发起员工姓名或工号 | 业务单据属性 |
| **F** | `费用承担部门` | 单据所属费用发生或承担部门 | 业务单据属性 |
| **G** | `跑批时间` | AI 审核执行的北京时间 | 审批运行属性 |
| **H** | `AI审批决策` | AI 给出的审批决策:`同意` / `驳回` | 审批运行结果 |
| **I** | `AI审核完整意见与违规详情` | **核心证据列**:包含 AI 综合评语、触发的具体规则编号及违规条款细则 | 聚合 summary + conditions |
| **J** | `人工审批结论` | 人工审批人实际操作:`同意` / `驳回` / `终止` | 人工操作记录 |
| **K** | `人工审批批注/驳回说明` | **核心证据列**:人工审批人在系统后台填写的真实审批意见与驳回理由 | 提取 manualComment / rejectComment |
| **L** | `人机一致性` | `一致`、`分歧` 或 `未完结/流转中` | 比较 H 与 J 决策极性 |
| **M** | `复核定性裁决` | **自由裁量填报列**:Agent/用户填写的定性结论(支持中英文口语化识别) | 人工/Agent 填报 |
| **N** | `复核人` | 执行该单裁决核查的业务人员或 Agent 署名 | 人工/Agent 填报 |
| **O** | `复核批注说明` | 针对复核裁决填写的定性分析、归因说明与管理整改建议 | 人工/Agent 填报 |
| **P** | `审批耗时(秒)` | AI 模型单据全生命周期审核耗时(秒) | 审批运行属性 |
```
> [!TIP]
> **中文口语化智能解析**:在「复核定性裁决」列中,用户不仅可以填写规范枚举(`ai_correct`),也可以自由填写中文口语:“`AI判断正确 / 人工判断错误`”、“`AI正确`”、“`人工正确`”、“`AI误判`”、“`双方正确`”等,CLI 在加载时均能百分之百精准识别映射。
>
> 若需核查单据更细维度的明细金额、发票结构化票面或附件凭证,Agent 可通过 `seal-use approval-runs get <recordId>` 或 `seal-use hose-ebot` 按需补充调阅。
---
## 五、端到端人机协同作业流程
### 模式 A:Excel 台账自由裁量驱动(首推推荐)
```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 产出交付,根据用户意见微调)"]
sequenceDiagram
autonumber
actor User as 用户 / 客户管理层
participant Agent as AI Agent (智能执笔)
participant CLI as seal-use CLI (确定性扳手)
participant Cloud as Seal 云端 / 本地缓存
Agent->>CLI: 1. seal-use report ledger --start-date ... --end-date ... --out 台账.xlsx
CLI->>Cloud: 提取全量明细与双端完整意见
CLI-->>Agent: 产出《台账.xlsx》(16列完整数据)
Note over Agent: 2. 自由裁量清洗:<br/>- 删去暂未验收的 4 种模板<br/>- 剔除异常测试单<br/>- 在复核定性列填写裁决
Agent->>User: 汇报分歧案例并对齐裁决
User-->>Agent: 确认裁决定性
Agent->>CLI: 3. seal-use report generate --ledger 台账.xlsx --out 报告.md
Note over CLI: 严格以本地 Excel 为边界,<br/>绝不回查云端已删除数据
CLI-->>Agent: 生成干净完整的结构化 Markdown
Agent->>CLI: 4. seal-use report validate 报告.md
CLI-->>Agent: 门禁通过 (valid: true)
Agent->>CLI: 5. seal-use report render 报告.md --out build/报告/
CLI-->>User: 交付单文件 HTML、A4 PDF 与长图 PNG
```
---
#### 具体操作指令:
```bash
# 步骤 1:一键拉取指定周期的全量明细台账(含 AI 完整意见与人工批注)
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out reports/明细台账.xlsx
### 第一步:获取结构化数据包与模板骨架
# 步骤 2:Agent 或用户在 Excel 中自由裁量,增删模板行并填入裁决;
1. **拉取当月纯结构化业务数据包 (JSON)**:
```bash
seal-use report data --month <YYYY-MM> --corp <corpId>
```
*输出说明:返回纯 JSON,包含全月样本量、AI 准确率、采纳率、平均耗时、公式代入值、分模板统计、TOP 风险标签,以及全量分歧单据池(`divergedRuns`)。*
# 步骤 3:严格以修改后的台账为唯一事实源,出具报告草稿
seal-use report generate --ledger reports/明细台账.xlsx --corp <corpId> --out reports/审核报告.md
2. **导出纯净标准模板骨架**:
```bash
seal-use report template --out reports/<企业名>-<YYYYMM>.md
```
# 步骤 4:严格门禁校验(必须通过)
seal-use report validate reports/审核报告.md
3. **动态生成准确率维恩图**:
```bash
mkdir -p reports/<企业名>-<YYYYMM>.assets
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
```
# 步骤 5:本地全格式编译渲染
seal-use report render reports/审核报告.md --out build/审核报告/
```
> [!TIP]
> **全量取数与分页控制**:`seal-use report ledger`、`report data` 与 `report generate` 默认自动分页拉取所选时间区间内的**全部审批单据**(内置 100,000 笔安全防死循环上限),无任何 500 条的人工截断限制。如需做小样本分析或限定抓取笔数,可传入 `--limit <n>`(别名 `--max-runs <n>` / `-n <n>`,例如 `--limit 2000`)。
---
### 第二步:分歧单据人机复核研讨 (Diverged Runs Review)
### 模式 B:CLI 命令行实时研讨驱动
当 `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. **提取结构化数据包**:
```bash
seal-use report data --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId>
```
返回纯 JSON 数据,包含全周期样本量、AI 准确率、采纳率、平均耗时、分模板统计及全量分歧单池(`divergedRuns`)。
1. **结构化向用户呈现典型案例**:
2. **双链穿透研讨呈现**:
在聊天窗口中结构化呈报案例给用户:
```markdown
【分歧单据复核确认】单号:FP2608010
- 单据模板:发票-个人报销
【分歧单据复核确认】单号:CL2608019
- 单据模板:差旅报销单
- 快速核验:[🔗 Seal AI 审核详情](https://<corp>.sealai.cc/approval-result/<recordId>) | [📑 合思原单据](https://wx2.ekuaibao.com/...)
- AI 审核结论:同意(单据附件与发票齐全合规,满足既定规则)
- 人工实际操作:驳回/终止(批注:口头超标)
- 触发条件:现行线上规则库无该超标阻断规则
- AI 审核结论:驳回(检测到机票发票开票日期早于出差申请单行程日期 15 天,违反制度条款 3.2)
- 人工实际操作:同意放行(批注:线下特殊批准提前出发)
- 触发条件:规则 0012「行程与票据日期逻辑核验」
👉 请教您对本单的裁决:
1. AI 依规正确(ai_correct):按线上规则库合规放行,人工属于口头加码标准;
2. 人工正确 / AI 失准(human_correct):业务实际存在超标限制,属于 AI 误判或规则未覆盖;
3. 双方都对(both_correct):规则执行正确,但有线下特殊处理。
1. AI 判断正确 / 人工判断错误 (ai_correct):AI 依规拦截正确,人工属于线下特批未补充审批单;
2. 人工判断正确 / AI 判定误判 (human_correct):业务允许特定场景提前订票,属于规则库未覆盖例外;
3. 双方判断均正确 (both_correct):双方各自依规,属于已知特例。
```
2. **将用户意见持久化录入复核账本**:
3. **裁决录入持久化账本**:
```bash
seal-use report review set \
--month <YYYY-MM> \
--sn <单号> \
--verdict <ai_correct|human_correct|both_correct> \
--note "口头加码标准,现行线上规则库未配置" \
--corp <corpId>
--corp <corpId> \
--record-id <ID> \
--sn CL2608019 \
--verdict ai_correct \
--note "线下特批未附审批单,AI依规拦截正确"
```
4. **离线台账批量导入**:
若线下已在 Excel 台账中集中批量评审完毕,可一键导入持久化存储:
```bash
seal-use report review import reports/明细台账.xlsx --corp <corpId>
```
---
### 第三步:Agent 结合数据与裁决自主撰写
## 六、标准 6 大章节深度剖析
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
```
§1. 审核测试结果 ───► 数据底座:样本总量、AI 准确率、人工准确率公式及维恩图
│
§2. AI 判定误判分析 ─► 坦诚归因:剖析模型不足与漏报误报,输出规则库调优方案
│
§3. 潜在风险拦截 ───► 商业价值:展示 AI 额外识别并拦截的违规单(专票、大额、假凭证)
│
§4. 综合效益 ─────► 宏观收益:审核秒级时效提升、准确度收益与财务人力释放
│
§5. 分歧与复核归因 ─► 管理对策:分析人机差异根本原因,引导推动线上规则库制度沉淀
│
§6. 支撑数据与交付 ─► 交付落地:分模板准确率细分表,配套交付《明细台账.xlsx》
```
#### 门禁校验重点关注项:
- **`HD001` / `HD002`**:二级章节编号必须自 1 开始连续递增(`## 1.`, `## 2.`, ..., `## 6.`),不得跳级。
- **`TB001` / `TB002`**:表格列数前后严格一致,表头行严禁带加粗 `**` 标记。
- **`NM001` / `NM002`**:失准与风险总览表中的各分项张数之和必须严格等于合计行。
- **`NM004`**:分歧原因分类表中的各单数与正文叙述中的笔数必须完全勾稽。
- **`NM005`**:准确率公式(如 `\frac{221}{240} = 92.08\%`)算术必须成立,且数值在正文中必须能找到对应数据来源。
- **`INFO001` / `INFO002`**:开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。
### 1. 标题与信息表
- 包含报告编号(`HD001`)、企业名称、统计期间、生成日期与报告状态(`草稿` 或 `正式交付`)。
> ⚠️ 若返回 `valid: false`,Agent 必须读取报错列表中的 `code` 和 `message`,**自主编辑修正 Markdown**,直到再次校验返回 `valid: true`。
### 2. §1 审核测试结果
- **1.1 数据来源与样本量**:明确审计周期的起止时间、纳管模板清单及样本总量($S$)。
- **1.2 准确率结论与维恩图**:
- 展示核心指标:AI 依规准确率(如 $93.75\%$)、人工实际准确率(如 $87.50\%$)。
- **准确率严密计算公式**(必须在正文中由 LaTeX 公式呈现):
$$\text{AI 准确率} = \frac{D_1 + D_4}{S} = \frac{\text{双方同向一致通过数} + \text{AI 依规正确拦截数}}{\text{样本总量}}$$
- 动态内嵌维恩图(`图 1:AI 与人工审核准确率对比.svg`),直观呈现两者的交集与重合度。
### 3. §2 AI 判定误判分析
- **2.1 误判构成总览**:总结在分歧复核中判定为“人工正确 / AI 判定误判”的单据总量及在全样本中的占比。
- **2.2~2.4 TOP 误判典型案例剖析**:
- 提炼真实典型案例,详细分析 AI 判定失误的机理(如复杂多税率混合计算偏差、手写收据文字模糊混淆等)。
- **针对性调优方案**:明确给出技术调优与规则优化对策(例如:升级发票 OCR 专有切片模型、增设多税率拆行核对规则)。
### 4. §3 AI 发现的潜在风险
- **3.1 潜在风险总览**:总结 AI 依规成功拦截的真实违规单据总量及金额。
- **3.2~3.4 典型风险单据拦截剖析**:
- 列举人工审批人漏审放行、但被 AI 坚决拦截的重大合规隐患(例如:专票未开具销货清单、跨期发票混报、同一发票重复报销、连号大额发票等)。
- 证明 AI 审核在“防范税务稽查风险”与“资金合规安全”上的不可替代价值。
### 5. §4 综合效益
- 表格化汇总四大效益维度:
- **审核时效**:人工平均审批耗时(例如 18.5 小时)vs AI 平均秒级处理时效(例如 4.2 秒),提效超 99%;
- **风控拦截**:全周期拦截违规单据笔数与违规金额;
- **人力释放**:测算自动化放行单据释放的财务初审工作量。
### 6. §5 审核分歧与复核归因
- **5.1 分歧原因分类表**:将全部人机分歧单归结为三大主因:
1. *未在线配置规则(人工依据口头制度驳回)*:占比通常最高;
2. *规则库逻辑配置缺陷(边界条件未覆盖)*;
3. *AI 模型识别偏差*。
- **5.2 管理优化建议**:引导企业将线下口头标准转化为线上明确规则,消除人为认知分歧。
- **5.3 引导查验台账**:明确指引领导与操作人员查阅随包附带的《明细台账.xlsx》进行逐单核对。
### 7. §6 支撑数据与交付材料
- **6.1 分模板统计表**:列出每个模板的单据量、通过率、AI 准确率与自动化放行率。
- **6.2 交付清单**:列出报告交付套件(Markdown 源码、矢量图包、单文件 HTML、A4 PDF、明细台账 Excel)。
---
### 第五步:全格式渲染与多轮修改迭代 (Render & Iterate)
## 七、动态自适应与用户至上原则
1. **一键编译渲染全套交付产物**:
```bash
seal-use report render reports/<企业名>-<YYYYMM>.md --out build/<企业名>-<YYYYMM> --format all
```
*产物包含:单文件自包含 HTML、A4 打印排版 PDF、4x 超高清拼接长图 PNG。*
为了杜绝后续使用的 AI Agent 产生死板教条(如“机械凑满 3 类问题”、“非要放满 3 行表格”),特此确立以下人机协同规范:
2. **呈现给用户并接收修改意见**:
- Agent 将渲染后的成果与核心数据摘要反馈给用户;
- 用户审查后提出调整(如“某段原因描述请改一下”、“风险小节增加具体发票案例”);
- Agent 直接在 Markdown 文件中微调,再次运行 `report validate` 确保无勾稽错误,然后重新 `report render` 刷新交付。
### 1. 必选骨架 vs 动态子分类
- **大章节是不可缺少的骨架**:§1~§6 大章节承载了严密的商业论证闭环,必须完整保留。
- **动态子分类完全由真实数据驱动**:
- §2(误判分析)与 §3(潜在风险)下的具体问题分类,**数量完全由实际跑批数据与用户业务关注度决定**。
- **唯一硬性底线**:动态章节下**至少保留 1 个子分类**(不能是无正文的空标题),可以是 TOP 1~2、TOP 1~3 或拓展至 TOP 1~5。
- **数学守恒定律**:分类表中的单数之和必须严格等于「合计」行单数,且百分比之和严格等于 100%(触发 `NM001`~`NM003` 校验)。
### 2. 用户态度为最高准则
- Agent 必须以用户的业务判断与汇报习惯为首要输入。若用户要求“重点只突出 2 个主要风险”、“案例只放 1 个最具代表性的单据”,Agent 必须立即响应调整,绝不生搬硬套模板默认布局。
### 3. 表格超链接免维护契约
- **Markdown 源码专注业务语义**:用户与 Agent 在编写或编辑 Markdown 报告草稿时,无需在表格中手写超长技术 URL。
- **自动化升级**:管线渲染引擎会自动识别表格结构。若表格只有两列,会自动将第一列单号升级为跳转链接;若表头显式声明了 `审核详情` 列,会自动在第 3 列生成直达链接。
---
## 模板 6 大标准章节剖析 (Section Anatomy)
## 八、离线门禁校验规则手册 (Zero-Error Gate)
| 章节编号与名称 | 数据来源与机制 | 说明与核心关注点 |
| :--- | :--- | :--- |
| **标题与报告信息表** | 数据填充 | 包含企业名称、账期、生成日期、草稿状态与唯一报告编号。 |
| **摘要** | 动态提炼 | 提炼全月单量、核心准确率与额外发现的合规风险笔数。 |
| **§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)。 |
在执行最终渲染交付前,Agent **必须**执行门禁校验命令:
```bash
seal-use report validate reports/审核报告.md
```
若存在任何格式或数学勾稽问题,命令将以 **退出码 1** 阻断导出,并输出带有错误代码的 JSON。Agent 必须根据报错信息自主编辑修正。
### 门禁重点校验代码全集:
| 错误代码 | 校验类别 | 校验规则与触发条件 | 常见违规示例 | 正确自纠方式 |
| :--- | :--- | :--- | :--- | :--- |
| **`HD001`** | 标题规范 | 二级章节必须从 1 开始严格连续递增(`## 1.`, `## 2.`, ..., `## 6.`),不得跳级。 | 出现 `## 1.` 后面直接跟 `## 3.` | 修正章节编号,确保 1~6 完整递增。 |
| **`HD002`** | 标题规范 | 三级子章节编号必须隶属于所属二级章节(如 `### 2.1`, `### 2.2`)。 | 在 `## 2.` 章节下出现 `### 3.1` | 修正三级标题序号,保持父子关系一致。 |
| **`TB001`** | 表格格式 | 表格所有行的列数必须前后完全一致。 | 表头有 4 列,某数据行只有 3 列 | 补齐缺失的竖线 `\|` 与单元格占位。 |
| **`TB002`** | 表格格式 | 表头行(Header)严禁带有加粗 `**` 标记。 | `\| **单号** \| **问题描述** \|` | 移除表头文字中的 `**`,改为 `\| 单号 \| 问题描述 \|`。 |
| **`NM001`** | 数学勾稽 | 分类统计表中的各分项单张数之和,必须严格等于合计行。 | 分项分别为 3、5、2,但合计行写了 11 | 修正分项数值或合计行数值,确保加法恒等。 |
| **`NM002`** | 数学勾稽 | 分类统计表中的百分比之和,必须严格等于 100.0%(允许 0.1% 舍入误差)。 | 各分项占比之和为 98.5% | 重新核算各分项百分比,确保相加为 100%。 |
| **`NM003`** | 数学勾稽 | 分项百分比计算值必须与单数占比精确勾稽。 | 10 单中占 3 单,但百分比写了 40% | 修正为 `\frac{3}{10} = 30.0\%`。 |
| **`NM004`** | 文本勾稽 | 正文中提及的误判/分歧笔数,必须与表格及公式中的笔数完全一致。 | 正文写“共发现 3 笔误判”,但表格列了 4 笔 | 统一正文措辞与表格中的单据笔数。 |
| **`NM005`** | 公式算术 | 准确率 LaTeX 公式算术必须成立,且分子分母在正文中可溯源。 | `\frac{221}{240} = 95.00\%` (实际应为 92.08%) | 重新计算并填入真实算术结果。 |
| **`INFO001`** | 信息完备 | 开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。 | 缺失了“报告编号”行 | 在开篇信息表中补齐所缺行。 |
| **`INFO002`** | 信息完备 | 开篇信息表中的关键字段值不得为空或保留 `待填充` 占位符。 | 统计期间写着 `YYYY-MM` | 替换为真实的业务统计区间(如 `2026-08-12 ~ 2026-09-18`)。 |
---
## 动态自适应与用户至上原则 (Dynamic Adaptability & User-Centric Principles)
## 九、全格式编译渲染与跨端交付
为避免后续使用的 AI Agent 产生死板教条(“非要凑满 3 类问题”、“非要放满 3 行”、“强行增加冗余列”等固执偏见),特此确立以下人机协同规范:
门禁校验通过后,使用 `report render` 即可产出全套工业级交付产物:
### 1. 必选骨架 vs 动态子部分的边界
* **大章节是不可缺少的骨架**:§1~§6 大章节承载了完整严谨的商业论证闭环(业绩证明、失准坦白、额外价值、分歧归因、支撑台账),必须存在。
* **章节内部的子部分完全动态**:
* 例如 §2(失准分析)与 §3(潜在风险)下的具体问题分类,**数量完全由实际跑批结果与用户业务关注度决定**。
* **唯一硬性底线**:动态章节下**至少保留 1 个子分类**(不能是无正文的空标题),可以是 TOP 1~2、TOP 1~3 或扩展至 TOP 1~5。
* **数学自洽守恒**:无论列出几种分类,分类表中的单数之和必须严格等于「合计」行单数,且百分比之和严格等于 100%(`NM001`~`NM003`)。
```bash
# 一键编译全套产物(单文件 HTML、A4 PDF、超清拼接长图 PNG)
seal-use report render reports/审核报告.md --out build/审核报告/ --format all
### 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 聊天窗口内快速滑动预览。
# 整包打包归档(产出 ZIP / 完整文件夹,自动收拢 Markdown、配图与明细台账)
seal-use report export reports/审核报告.md --out build/交付整包/
```
### 交付产物技术特性与适用场景:
1. **单文件自包含 HTML (`.html`)**:
- 所有 CSS 样式、矢量图表与字体资源全部通过 Data URI 内嵌;
- 零网络依赖,双击即可在任何现代浏览器中完美打开浏览;
- 内部超链接天然支持跨端点击穿透直达系统后台。
2. **A4 打印级分页 PDF (`.pdf`)**:
- 严格遵循 A4 物理纸张比例与分页控制(CSS `@page` 与 `break-inside: avoid`);
- 页眉页脚清晰标注企业名称与唯一报告编号;
- 支持高精度矢量文字缩放,适用于正式纸质打印与签字归档。
3. **超高清拼接长图 (`.png`)**:
- 由原生无头浏览器以 4x 视口倍率切片截取,并通过高性能图形算法在内存中无损拼接;
- 专为钉钉、微信、飞书等移动端 IM 聊天窗口设计,方便管理层在手机上顺滑滑动审阅。
+156
View File
@@ -385,6 +385,162 @@ describe("auth links", () => {
});
});
describe("auth hose-openapi-token", () => {
function setupRoot(name: string) {
const root = mkdtempSync(join(tmpdir(), name));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
mkdirSync(enterprises, { recursive: true });
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
return { root, enterprises };
}
function writeHoseCorp(enterprises: string, sourceOverride: Record<string, unknown> = {}) {
writeFileSync(
join(enterprises, "hose-corp.json"),
JSON.stringify({
id: "hose-corp",
name: "合思测试企业",
environment: "production",
seal: { url: "https://hose-corp.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
corpId: "HOSE-CORP",
staffId: "HOSE-CORP:STAFF-1",
...sourceOverride
},
auth: { refreshTtl: 300 }
})
);
}
function mockGetAccessToken(counter: { count: number }, token = "fresh-openapi-token") {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
counter.count += 1;
return new Response(JSON.stringify({ value: { accessToken: token, expireTime: 7200 } }), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
}
test("mints a fresh OpenAPI token from persisted keys and prints it as machine JSON", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-");
writeHoseCorp(enterprises);
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(result.isError).toBe(false);
expect(counter.count).toBe(1);
const parsed = JSON.parse(result.stdout);
expect(parsed).toMatchObject({
corpId: "HOSE-CORP",
corpName: "合思测试企业",
domain: "https://app.ekuaibao.com",
token: "fresh-openapi-token",
cached: false
});
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
test("reuses a fresh cached token by default and mints a new one with --force", async () => {
const { root, enterprises } = setupRoot("seal-use-auth-openapi-token-force-");
writeHoseCorp(enterprises);
writeFileSync(
join(root, "tokens.json"),
JSON.stringify({
"hose-corp": {
hose: {
openapi: { token: "cached-openapi-token", expiresAt: Date.now() + 3600_000 }
}
}
})
);
const counter = { count: 0 };
mockGetAccessToken(counter);
const cachedResult = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(cachedResult.isError).toBe(false);
expect(counter.count).toBe(0);
const cachedParsed = JSON.parse(cachedResult.stdout);
expect(cachedParsed).toMatchObject({ token: "cached-openapi-token", cached: true });
expect(cachedResult.stderr).toContain("复用本地仍有效的 accessToken");
const forcedResult = await runCli(["auth", "openapi-token", "--corp", "hose-corp", "--force"]);
expect(forcedResult.isError).toBe(false);
expect(counter.count).toBe(1);
const forcedParsed = JSON.parse(forcedResult.stdout);
expect(forcedParsed).toMatchObject({ token: "fresh-openapi-token", cached: false });
});
test("rejects a native Seal enterprise with exit code 2", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-native-");
writeFileSync(
join(enterprises, "native-seal.json"),
JSON.stringify({
id: "native-seal",
name: "原生 Seal 企业",
environment: "production",
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://native.seal.test",
expiresIn: 3600,
corpId: "native-corp",
staffId: "native-staff"
},
auth: { refreshTtl: 300 }
})
);
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "native-seal"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("非合思");
expect(counter.count).toBe(0);
});
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-nocreds-");
writeHoseCorp(enterprises, {
appKey: undefined,
appSecurity: undefined,
closeToken: "web-session-token",
expiresAt: "2099-01-01T00:00:00+08:00"
});
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(13);
expect(result.stderr).toContain("缺少合思凭证");
expect(counter.count).toBe(0);
});
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
+46 -1
View File
@@ -1,7 +1,14 @@
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink, getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
import {
assertHoseAssistTenantMatches,
exchangeHoseAssistLink,
getHoseOpenapiToken,
getHoseProvisionalAuthLink,
normalizeBaseUrl
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { CliError, validationError } from "../../core/errors.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
@@ -147,6 +154,44 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
return;
}
if (
action === "hose-openapi-token" ||
action === "openapi-token" ||
action === "hose-token"
) {
if (corp.source.type !== "hose") {
throw new CliError(
`【合思专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
"OpenAPI accessToken 签发能力专属于合思生态租户(使用持久化的 appKey/appSecurity 向合思 OpenAPI 换取 token),非合思渠道企业不支持此命令。",
2
);
}
const appKey = corp.source.appKey ?? corp.source.key;
const appSecurity = corp.source.appSecurity ?? corp.source.password;
if (!appKey || !appSecurity) {
throw validationError(
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法向合思 OpenAPI 签发 accessToken。`
);
}
const force =
booleanOption(args.options.force) === true ||
booleanOption(args.options.refresh) === true ||
booleanOption(args.options.f) === true;
const entry = await getHoseOpenapiToken(corp, { force });
if (entry.cached) {
console.error("ℹ️ [合思 OpenAPI] 复用本地仍有效的 accessToken 缓存,追加 --force 可强制签发全新 token。");
}
printJson({
corpId: corp.source.corpId ?? corp.id,
corpName: corp.name,
domain: normalizeBaseUrl(corp.source.domain),
token: entry.token,
expiresAt: formatBeijingIso(entry.expiresAt),
cached: entry.cached
});
return;
}
if (action === "keys" || action === "hose-keys") {
const reveal =
booleanOption(args.options.reveal) === true ||
+580
View File
@@ -0,0 +1,580 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { KyInstance } from "ky";
import { CorpConfigSchema } from "../../core/config/types.js";
import { classifyCliError } from "../../core/errors.js";
import { parseArgs } from "../parser.js";
import { handleHoseEbotCommand } from "./hose-ebot.js";
const ORIGINAL_ENV = {
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
usageFile: process.env.SEAL_USE_USAGE_FILE
};
const ORIGINAL_FETCH = globalThis.fetch;
const ORIGINAL_LOG = console.log;
const ORIGINAL_ERROR = console.error;
let tempDir: string | undefined;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-use-hose-ebot-area-"));
process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(tempDir, "usage.json");
});
afterEach(() => {
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
globalThis.fetch = ORIGINAL_FETCH;
console.log = ORIGINAL_LOG;
console.error = ORIGINAL_ERROR;
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true });
tempDir = undefined;
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
const hoseCorp = CorpConfigSchema.parse({
id: "hose-ebot",
name: "合思 EBot 测试企业",
environment: "test",
seal: { url: "https://hose-ebot.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const hoseCorpNoOpenApiCredentials = CorpConfigSchema.parse({
...hoseCorp,
id: "hose-ebot-nocreds",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const sealCorp = CorpConfigSchema.parse({
id: "seal-ebot",
name: "原生 Seal 企业",
environment: "test",
seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } },
source: {
type: "seal",
sealUrl: "https://seal.test",
token: "mock-token",
staffId: "seal-staff",
corpId: "seal-corp"
}
});
const messageFixture = {
items: [
{
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true,
signKey: "Q4H15lpixMyE7secretvalue",
callbackUrl: "https://sealai.cc/api/hosecloud/outbound?config_id=Q4H15lpixMyE7secretvalue",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["backlog.processed"],
formFields: ["action", "flowId", "nodeId"]
},
{
id: "ID01Vj4VDa8CGH",
messageName: "完成回调",
messageType: "message",
enable: false,
signKey: "Q4H15lpixOtherSecret",
callbackUrl: "https://sealai.cc/api/hosecloud/complete",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["flow.completed"]
}
]
};
const logFixture = {
items: [
{
id: "log-1",
name: "出站调用",
type: "INVOKING",
state: "SUCCESS",
createTime: 1727764000000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
messageId: "MSG-1",
rejectionNum: 0
}
},
{
id: "log-2",
name: "审批回调",
type: "CALLBACK",
state: "SUCCESS",
createTime: 1727764010000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
signKey: "Q4H15lpixMyE7secretvalue",
action: "accept",
comment: "AI 审核通过"
}
}
]
};
function mockFetch(responses: {
messages?: unknown;
logs?: unknown;
token?: unknown;
approval?: unknown;
}) {
const record: {
calls: number;
messageUrl?: string;
logUrl?: string;
logBody?: unknown;
tokenUrl?: string;
tokenBody?: unknown;
approvalUrl?: string;
approvalBody?: unknown;
} = { calls: 0 };
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
record.calls++;
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
let bodyText: string | undefined;
if (init?.body) {
bodyText = String(init.body);
} else if (input && typeof input === "object" && "clone" in input) {
bodyText = await (input as Request).clone().text().catch(() => undefined);
}
if (url.includes("/api/outbound/v1/message/messageLog")) {
record.logUrl = url;
record.logBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(JSON.stringify(responses.logs ?? logFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/outbound/v1/message")) {
record.messageUrl = url;
return new Response(JSON.stringify(responses.messages ?? messageFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/openapi/v1/auth/getAccessToken") || url.includes("/api/openapi/v1/accessToken")) {
record.tokenUrl = url;
record.tokenBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(
JSON.stringify(responses.token ?? { accessToken: "live-openapi-token" }),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.includes("/api/openapi/v1/approval")) {
record.approvalUrl = url;
record.approvalBody = bodyText ? JSON.parse(bodyText) : undefined;
const resp = responses.approval ?? { value: { code: "204", message: "EBot执行完成" } };
return new Response(JSON.stringify(resp), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response(JSON.stringify({ error: "unexpected url", url }), { status: 500 });
}) as typeof fetch;
return record;
}
function fakeClient(integrations: Array<Record<string, unknown>> = []) {
return {
get: async () => ({
json: async () => ({ integrations })
})
} as unknown as KyInstance;
}
async function callHoseEbot(client: KyInstance, corp: typeof hoseCorp, argv: string[]) {
const lines: string[] = [];
console.log = (line: string) => lines.push(String(line));
console.error = () => {};
const args = parseArgs(argv);
await handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args);
return JSON.parse(lines.join("\n")) as Record<string, unknown>;
}
async function captureError(action: () => Promise<unknown>): Promise<unknown> {
try {
await action();
} catch (error) {
return error;
}
throw new Error("expected action to throw, but it succeeded");
}
describe("hose-ebot messages", () => {
test("lists configured outbound messages with a masked signKey by default", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "messages"]);
expect(output.count).toBe(2);
expect(record.messageUrl).toContain("corpId=ID01LG7ksGroB1");
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages[0]).toMatchObject({
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true
});
// maskHoseSecurity keeps the first 8 and last 4 characters.
expect(messages[0]!.signKey).toBe("Q4H15lpi...alue");
expect(messages[0]!.signKey).not.toBe("Q4H15lpixMyE7secretvalue");
expect(messages[0]!.callbackUrl).toContain("config_id=Q4H15lpixMyE7secretvalue");
expect(output.revealed).toBe(false);
});
test("filters by type and reveals the signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "messages", "--type", "flow", "--reveal"
]);
expect(output.count).toBe(1);
expect(output.revealed).toBe(true);
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages).toHaveLength(1);
expect(messages[0]!.signKey).toBe("Q4H15lpixMyE7secretvalue");
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, ["hose-ebot", "messages"])
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
});
describe("hose-ebot search", () => {
test("requires an SN and lists records with their unique ids", async () => {
const usageError = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "search"])
);
expect(classifyCliError(usageError).exitCode).toBe(2);
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--limit", "5"
]);
expect(output.count).toBe(2);
expect(output.sn).toBe("SN123");
expect(output.type).toBe("all");
expect(record.logBody).toMatchObject({
limit: { start: 0, count: 5 },
filterBy: '(flowId.form.code==("SN123"))'
});
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" });
expect((records[0]!.request as Record<string, unknown>).nodeId).toBe("NODE-1");
// Callback records embed signKey; masked unless --reveal.
expect((records[1]!.request as Record<string, unknown>).signKey).not.toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("filters to invoking or callback records with --type", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "callback"
]);
expect(output.type).toBe("callback");
expect(output.count).toBe(1);
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]!.type).toBe("CALLBACK");
// The client-side filter over-fetches first so the page stays full.
expect(record.logBody).toMatchObject({ limit: { start: 0, count: 80 } });
// Also accepts uppercase --type CALLBACK
const outputUpper = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "CALLBACK"
]);
expect(outputUpper.count).toBe(1);
});
test("reveals the record signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--reveal"
]);
const records = output.records as Array<Record<string, unknown>>;
expect((records[1]!.request as Record<string, unknown>).signKey).toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("rejects an unknown verb with exit code 2", async () => {
const error = await captureError(() => callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "banana"]));
expect(classifyCliError(error).exitCode).toBe(2);
expect(String((error as Error).message)).toContain("Unknown hose-ebot command");
});
});
describe("hose-ebot callback", () => {
const callbackArgv = (extra: string[] = []) => [
"hose-ebot", "callback",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "accept",
"--comment", "同意",
...extra
];
test("refuses to run without --yes/--confirm before any network call", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1"]))
);
expect(classifyCliError(error).exitCode).toBe(10);
expect(record.calls).toBe(0);
expect(classifyCliError(error).nextAction).toContain("seal-use hose-ebot callback");
});
test("previews a masked payload with --dry-run without minting a token", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
...callbackArgv(["--sign-key", "sig-1", "--dry-run"])
]);
expect(output.preview).toBe(true);
expect(output.endpoint).toBe("https://app.ekuaibao.com/api/openapi/v1/approval");
const payload = output.payload as Record<string, unknown>;
expect(payload).toMatchObject({
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
expect(payload.signKey).not.toBe("sig-1");
expect(record.calls).toBe(0);
});
test("mints a fresh accessToken and posts the callback on a confirmed run", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, callbackArgv([
"--sign-key", "sig-1",
"--yes"
]));
expect(output).toMatchObject({
ok: true,
code: "204",
message: "EBot执行完成",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept"
});
expect(record.approvalUrl).toContain("/api/openapi/v1/approval");
expect(record.approvalUrl).toContain("accessToken=live-openapi-token");
expect(record.approvalBody).toMatchObject({
signKey: "sig-1",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
});
test("normalizes action aliases like agree/approve/reject", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "agree",
"--comment", "口语化同意",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "accept" });
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "reject",
"--comment", "口语化驳回",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "refuse" });
});
test("passes optional callback fields through to the wire payload with camelCase support", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "refuse",
"--comment", "驳回",
"--policy", "ALL",
"--addApproverIds", "staff-1,staff-2",
"--rejectTo", "NODE-0",
"--resubmitMethod", "TO_REJECTOR",
"--yes"
]);
expect(record.approvalBody).toMatchObject({
action: "refuse",
policy: "ALL",
addApproverIds: ["staff-1", "staff-2"],
rejectTo: "NODE-0",
resubmitMethod: "TO_REJECTOR"
});
});
test("resolves signKey from the sole Seal integration when --sign-key is omitted", async () => {
const record = mockFetch({});
const client = fakeClient([
{ type: "hosecloud", signKey: "integrated-key", outboundName: "AI review", mode: "assisted" }
]);
await callHoseEbot(client, hoseCorp, callbackArgv(["--yes"]));
expect(record.approvalBody).toMatchObject({ signKey: "integrated-key" });
});
test("maps upstream business codes to exit codes and references hose-ebot messages", async () => {
mockFetch({ approval: { value: { code: "401", message: "签名秘钥错误" } } });
const error401 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error401).exitCode).toBe(11);
expect(String((error401 as Error).message)).toContain("seal-use hose-ebot messages --reveal");
mockFetch({ approval: { value: { code: "412", message: "当前的审批节点不为: xxx,请检查" } } });
const error412 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error412).exitCode).toBe(1);
expect(String((error412 as Error).message)).toContain("seal-use hose-ebot search");
mockFetch({ approval: { value: { code: "400", message: "请求参数错误" } } });
const error400 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error400).exitCode).toBe(13);
});
test("validates preAdd and aftAdd approver and policy requirements before network call", async () => {
const record = mockFetch({});
const preAddError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv(["--action", "preAdd", "--sign-key", "sig-1", "--yes"])
)
);
expect(classifyCliError(preAddError).exitCode).toBe(13);
expect(String((preAddError as Error).message)).toContain("必须通过 --add-approver-ids 指定加签审批人");
expect(record.calls).toBe(0);
const aftAddPolicyError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--sign-key",
"sig-1",
"--yes"
])
)
);
expect(classifyCliError(aftAddPolicyError).exitCode).toBe(13);
expect(String((aftAddPolicyError as Error).message)).toContain("必须指定会签方式 --policy ALL");
expect(record.calls).toBe(0);
});
test("normalizes lowercase policy and kebab-case resubmit-method", async () => {
const record = mockFetch({
approval: { value: { code: "204", message: "success" } }
});
await callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--policy",
"all",
"--resubmit-method",
"from-start",
"--sign-key",
"sig-1",
"--yes"
])
);
expect(record.approvalBody).toMatchObject({
action: "aftAdd",
addApproverIds: ["user1", "user2"],
policy: "ALL",
resubmitMethod: "FROM_START"
});
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorpNoOpenApiCredentials, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(String((error as Error).message)).toContain("缺少合思凭证");
expect(record.calls).toBe(0);
});
});
+125
View File
@@ -0,0 +1,125 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { CliError } from "../errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
const USAGE =
"Usage:\n" +
" seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--dry-run] [--yes|--confirm] [--corp <corpId>]";
function normalizeEbotAction(raw: string | undefined): string | undefined {
if (!raw) return undefined;
const lower = raw.trim().toLowerCase();
if (lower === "accept" || lower === "agree" || lower === "approve") return "accept";
if (lower === "refuse" || lower === "reject") return "refuse";
if (lower === "preadd" || lower === "pre-add") return "preAdd";
if (lower === "aftadd" || lower === "aft-add" || lower === "postadd" || lower === "post-add") return "aftAdd";
return raw;
}
function normalizeEbotPolicy(raw: string | undefined): "ALL" | "ANY" | undefined {
if (!raw) return undefined;
const upper = raw.trim().toUpperCase();
if (upper === "ALL" || upper === "ANY") return upper;
return raw as "ALL" | "ANY";
}
function normalizeResubmitMethod(raw: string | undefined): "FROM_START" | "TO_REJECTOR" | undefined {
if (!raw) return undefined;
const norm = raw.trim().toUpperCase().replace(/-/g, "_");
if (norm === "FROM_START" || norm === "TO_REJECTOR") return norm;
return raw as "FROM_START" | "TO_REJECTOR";
}
/**
* First-level `seal-use hose-ebot` surface for the Hose EBot outbound & callback loop:
* search is the default entry (discover records by document SN), `messages`
* discovers outbound message configs and their signKey, and `callback` runs
* the approval callback.
*/
export async function handleHoseEbotCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (!action) {
throw new CliError(USAGE, 2);
}
if (action === "search") {
const sn = maybeName ?? stringOption(args.options.sn);
if (!sn) {
throw new CliError(`Missing document SN.\n\n${USAGE}`, 2);
}
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundSearch",
client,
corp,
{
sn,
type: rawType,
limit: numberOption(args.options.limit),
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true
},
outputOptions(args.options)
);
return;
}
if (action === "messages") {
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundMessages",
client,
corp,
{
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true,
type: rawType
},
outputOptions(args.options)
);
return;
}
if (action === "callback") {
const addApproverIdsRaw =
stringOption(args.options["add-approver-ids"]) ?? stringOption(args.options.addApproverIds);
await runCapability(
"sealHoseApprovalCallback",
client,
corp,
{
signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]),
flowId: stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]),
nodeId: stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]),
action: normalizeEbotAction(stringOption(args.options.action)),
comment: stringOption(args.options.comment),
policy: normalizeEbotPolicy(stringOption(args.options.policy)),
addApproverIds: addApproverIdsRaw
? addApproverIdsRaw.split(",").map((id) => id.trim()).filter(Boolean)
: undefined,
rejectTo: stringOption(args.options["reject-to"]) ?? stringOption(args.options.rejectTo),
resubmitMethod: normalizeResubmitMethod(
stringOption(args.options["resubmit-method"]) ?? stringOption(args.options.resubmitMethod)
),
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
},
outputOptions(args.options)
);
return;
}
throw new CliError(
`Unknown hose-ebot command: ${action}. Available: search, messages, callback. Run 'seal-use hose-ebot --help' for usage.`,
2
);
}
+187 -26
View File
@@ -16,12 +16,29 @@ import {
loadReviews,
reviewFilePath,
writeReview,
type MonthlyReportResult
type MonthlyReportResult,
buildReportLedgerCsv,
buildReportLedgerXlsx,
loadReportDataFromLedger,
collectReportData,
type ReportData
} from "../../domains/seal/reports/index.js";
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" | "template" | "chart", args: ParsedArgs) {
export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) {
if (Boolean(args.options.ledger) || action === "review") {
const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger";
const corp = {
corpId,
id: corpId,
name: corpId,
corpName: corpId,
source: { source: "seal", sealUrl: "" }
} as unknown as CorpConfig;
await handleReportCommand(action, {} as any, corp, args);
return;
}
if (action === "template") {
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
@@ -78,45 +95,165 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
}
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
function resolveMaxRuns(args: ParsedArgs): number | undefined {
return (
numberOption(args.options.limit) ??
numberOption(args.options.n) ??
numberOption(args.options.count) ??
numberOption(args.options["max-runs"]) ??
numberOption(args.options.maxRuns)
);
}
/** `seal-use report generate` / `ledger` / `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>]");
if (action === "ledger") {
const ledgerPath = stringOption(args.options.ledger);
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
const format = (stringOption(args.options.format) ?? (out?.endsWith(".csv") ? "csv" : "xlsx")).toLowerCase();
let data: ReportData;
if (ledgerPath) {
data = await loadReportDataFromLedger(ledgerPath, { corp: { id: corp.id, name: corp.name } });
} else {
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if ((!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx|csv>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
data = await collectReportData(client, new Set(["blocks", "templateGroups", "performance"]), {
startDate,
endDate,
month,
corp: { id: corp.id, name: corp.name },
templates,
maxRuns: resolveMaxRuns(args)
});
}
const outFile = out ?? `台账-${corp.id}-${(data.period.label ?? data.period.start).replace(/[^0-9A-Za-z_-]/g, "_")}.${format === "csv" ? "csv" : "xlsx"}`;
const targetPath = resolve(outFile);
if (format === "csv") {
const csvContent = buildReportLedgerCsv(data);
writeFileSync(targetPath, csvContent, "utf8");
} else {
const xlsxBuffer = await buildReportLedgerXlsx(data);
writeFileSync(targetPath, xlsxBuffer);
}
const divergedCount = data.blocks.filter((b) => b.agreement === "diverged").length;
const unreviewedDiverged = data.blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
printJson({
file: targetPath,
format: format === "csv" ? "csv" : "xlsx",
corpId: corp.id,
period: data.period,
totalBlocks: data.blocks.length,
templates: [...new Set(data.blocks.map((b) => b.template))],
divergedCount,
unreviewedDiverged,
next: {
reviewTip: "可在 Excel 中直接编辑'复核定性裁决'列(填写:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),也可直接剔除不需要的模板行",
generate: `seal-use report generate --ledger '${targetPath}' --corp ${corp.id} --out reports/报告.md`
}
}, outputOptions(args.options));
return;
}
if (action === "data") {
const ledgerPath = stringOption(args.options.ledger);
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if (!ledgerPath && (!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
const result = await runCapabilityResult(
"sealReportDataGet",
client,
corp,
{
startDate,
endDate,
month,
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
templates,
ledgerPath,
maxRuns: resolveMaxRuns(args)
}
);
printJson(result, outputOptions(args.options));
return;
}
if (action === "monthly" || action === "month") {
if (action === "monthly" || action === "month" || action === "generate") {
const ledgerPath = stringOption(args.options.ledger);
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
if (!ledgerPath && (!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
const result = await runCapabilityResult(
"sealReportMonthlyGet",
client,
corp,
{
startDate,
endDate,
month,
templates,
ledgerPath,
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: resolveMaxRuns(args),
allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force)
}
) as MonthlyReportResult;
@@ -140,33 +277,57 @@ export async function handleReportCommand(
}
if (action === "review") {
const sub = args.command[2]; // set | list
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report review <set|list> --month <YYYY-MM> [--sn <SN> --verdict <v>] [--corp <corpId>]");
}
const sub = args.command[2]; // set | list | import
if (sub === "list") {
const reviews = loadReviews(corp.id, month);
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
const reviews = loadReviews(corp.id, scope);
printJson({
corpId: corp.id,
month,
file: reviewFilePath(corp.id, month),
...(scope ? { month: scope } : {}),
file: reviewFilePath(corp.id, scope),
count: reviews.size,
reviews: [...reviews.values()]
});
return;
}
if (sub === "import") {
const file = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.ledger);
if (!file) throw usageError("Usage: seal-use report review import <台账.xlsx|csv> --corp <corpId>");
const ledgerData = await loadReportDataFromLedger(file, { corp: { id: corp.id, name: corp.name } });
let imported = 0;
for (const rev of ledgerData.reviews.values()) {
writeReview(corp.id, rev);
imported++;
}
printJson({
corpId: corp.id,
file: resolve(file),
importedCount: imported,
totalBlocks: ledgerData.blocks.length
}, outputOptions(args.options));
return;
}
if (sub === "set") {
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
const recordId =
stringOption(args.options["record-id"]) ??
stringOption(args.options.recordId) ??
stringOption(args.options.id);
const sn =
stringOption(args.options.sn) ??
stringOption(args.options["document-sn"]);
const verdict = stringOption(args.options.verdict);
if (!sn || !verdict) {
throw new Error(
"Usage: seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
const month = stringOption(args.options.month) ?? stringOption(args.options.scope);
if ((!recordId && !sn) || !verdict) {
throw usageError(
"Usage: seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
);
}
const record = writeReview(corp.id, {
recordId,
sn,
month,
verdict,
@@ -177,8 +338,8 @@ export async function handleReportCommand(
return;
}
throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', or 'import'.`);
}
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
}
+116 -25
View File
@@ -619,22 +619,40 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
area: "report",
title: "Monthly audit accuracy reports",
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
title: "AI audit accuracy reports (acceptance, go-live, periodic)",
description: "Generate AI audit and acceptance reports, export standalone Excel/CSV ledgers, validate local Markdown, and export HTML/PNG/PDF.",
commands: [
{
name: "ledger",
summary: "Export standalone audit run ledger (.xlsx / .csv) with full AI & human opinions",
usage: ["seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx>] [--corp <corpId>]"],
options: [
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
{ flag: "--ledger <file>", description: "Inspect or convert an existing ledger file" },
{ flag: "--out <file>", description: "Output path (.xlsx or .csv); defaults to 台账-<corpId>-<period>.xlsx" },
{ flag: "--format <xlsx|csv>", description: "Export format (default: xlsx, or inferred from --out)" },
{ flag: "--limit <n>", description: "Cap approval-run fetch (alias: --max-runs, default: all records in period, max 100000)" }
],
description: "Exports full audit ledger containing recordId, SN, template, AI decisions, full AI opinions & conditions, human results & comments, agreement, and review verdict columns. Agents can freely trim rows/templates and fill verdicts."
},
{
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>]"],
usage: ["seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <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)" }
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD" },
{ flag: "--ledger <file>", description: "Directly parse an edited Excel/CSV ledger file without remote requests" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
{ flag: "--limit <n>", description: "Cap approval-run detail fetch (alias: --max-runs, default: all records in period, max 100000)" }
],
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",
summary: "Dump or save the built-in 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" }
@@ -654,20 +672,23 @@ export const HELP_REGISTRY: AreaHelp[] = [
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>] [--allow-unreviewed] [--corp <corpId>]"],
name: "generate",
aliases: ["monthly", "month"],
summary: "Fill the audit report template with performance, risk, and approval-run data",
usage: ["seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--limit <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: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
{ flag: "--ledger <file>", description: "Driven directly by an edited Excel/CSV ledger as the sole source of truth; ignores deleted templates/runs and respects in-place verdicts" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist; filters blocks and ledger at source" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary" },
{ flag: "--out <file>", description: "Save Markdown plus local images and Excel/CSV ledgers beside the report; stdout stays JSON" },
{ 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: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<dateTag>-<random>" },
{ flag: "--limit <n>", description: "Cap approval-run detail fetch (alias: --max-runs, default: all records in period, max 100000)" },
{ 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."
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings. Supports direct ledger-driven generation where user/Agent modifications to templates and rows are strictly respected."
},
{
name: "validate",
@@ -704,25 +725,34 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "review set",
summary: "Record one human adjudication (who was right: AI or human) for a document",
usage: ["seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
summary: "Record one human adjudication (who was right: AI or human) for an approval run or document",
usage: ["seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" },
{ flag: "--sn <SN>", description: "Document SN to adjudicate (required)" },
{ flag: "--record-id <ID>", description: "Approval run recordId for exact single-run targeting" },
{ flag: "--sn <SN>", description: "Document SN to adjudicate" },
{ flag: "--verdict <v>", description: "ai_correct | human_correct | both_correct | both_wrong | undecided (required)" },
{ flag: "--note <text>", description: "Optional adjudication note" },
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
],
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
description: "Append-only local JSONL per tenant (~/.config/seal-use/state/reviews/). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
},
{
name: "review list",
summary: "List human adjudications recorded for a tenant+month",
usage: ["seal-use report review list --month <YYYY-MM> [--corp <corpId>]"],
summary: "List human adjudications recorded for a tenant",
usage: ["seal-use report review list [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" }
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Reads the local JSONL store and returns all adjudications keyed by SN."
description: "Reads the local JSONL store and returns all adjudications."
},
{
name: "review import",
summary: "Bulk import adjudications from an edited Excel/CSV ledger file",
usage: ["seal-use report review import <台账.xlsx|csv> --corp <corpId>"],
options: [
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Reads '复核定性裁决', '复核人', and '复核批注说明' columns from the ledger and bulk writes into the local review store."
}
]
},
@@ -855,6 +885,56 @@ export const HELP_REGISTRY: AreaHelp[] = [
}
]
},
{
area: "hose-ebot",
title: "Hose EBot outbound discovery & callback (合思 EBot 出站发现与审批回调)",
description: "按单号搜索出站/回调记录、列出出站消息配置(signKey),并执行 EBot 审批回调。",
commands: [
{
name: "search",
summary: "【出站发现·默认入口】按单号搜索出站消息调用记录(只读)",
usage: ["seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]"],
options: [
{ flag: "--type <invoking|callback>", description: "筛选记录类型:invoking=出站触发,callback=回调;缺省全部" },
{ flag: "--limit <n>", description: "返回条数上限(默认 20,最大 100)" },
{ flag: "--reveal, -r", description: "明文展示记录中的 signKey(默认脱敏)" }
],
description:
"在合思 CloseAPI 出站消息日志中按单号 (SN) 搜索,返回带唯一 id 的记录列表(INVOKING 出站触发 / CALLBACK 回调),含 flowId/nodeId/messageId/rejectionNum 等回调上下文。"
},
{
name: "messages",
summary: "【出站配置】列出全部出站消息配置,发现 signKey 与回调地址(只读)",
usage: ["seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]"],
options: [
{ flag: "--type <flow|message>", description: "按类型过滤:flow=审批流 EBot 出站,message=完成回调/通知" },
{ flag: "--reveal, -r", description: "明文展示 signKey(默认脱敏为 8...4 形式)" }
],
description:
"经合思 CloseAPI 只读查询本企业全部出站消息配置(messageName、signKey、callbackUrl、enable 等)。signKey 即出站回调地址中的 config_id,可直接用于 'hose-ebot callback'。"
},
{
name: "callback",
summary: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签)",
usage: [
"seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]"
],
options: [
{ flag: "--comment <text>", description: "审批意见(必填)" },
{ flag: "--sign-key <key>", description: "出站消息签名密钥;缺省时从本企业唯一 Seal 合思集成解析" },
{ flag: "--action <accept|refuse|preAdd|aftAdd>", description: "同意 / 驳回 / 前加签 / 后加签(兼容 agree/approve/reject)" },
{ flag: "--policy <ALL|ANY>", description: "会签方式:ALL 会签 / ANY 或签(加签超过一人时必填)" },
{ flag: "--add-approver-ids <id,id>", description: "前后加签审批人 ID 列表(加签时必填,逗号分隔)" },
{ flag: "--reject-to <nodeId>", description: "驳回目标节点 ID;缺省按 EBot 节点驳回配置" },
{ flag: "--resubmit-method <FROM_START|TO_REJECTOR>", description: "驳回后重提方式;缺省按 EBot 节点配置" },
{ flag: "--dry-run", description: "仅预览回调请求(signKey 脱敏),不执行" },
{ flag: "--yes, --confirm", description: "正式执行必需;届时实时换取 accessToken 后回调" }
],
description:
"调用合思开放接口 POST /api/openapi/v1/approval,向审批流回写 EBot 节点审批结果,成功返回 value.code=204。仅支持 EBot 节点的审批;signKey 可通过 'seal-use hose-ebot messages --reveal' 发现。"
}
]
},
{
area: "preference",
title: "Audit preferences and thinking depth",
@@ -973,6 +1053,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
description:
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
},
{
name: "hose-openapi-token",
aliases: ["openapi-token", "hose-token"],
summary: "【合思】用持久化密钥签发合思 OpenAPI accessToken",
usage: ["seal-use auth hose-openapi-token [--corp <corpId>] [--force]"],
options: [
{ flag: "--force, --refresh, -f", description: "跳过本地缓存,强制向合思 OpenAPI 签发全新 token" }
],
description:
"专用于合思 (Hose) 来源企业。使用已持久化的 appKey/appSecurity 调用 /api/openapi/v1/auth/getAccessToken 换取 OpenAPI accessToken(约 1 小时有效),stdout 输出含 token、expiresAt 与 cached 字段(cached=true 表示复用了本地仍有效的缓存)。"
},
{
name: "hose-extract-keys",
aliases: ["extract-keys", "extract-key", "extract-hose-keys"],
+12 -12
View File
@@ -40,9 +40,9 @@ export const BOOLEAN_FLAGS = new Set([
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "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",
"channel", "chrome", "code", "comment", "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",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
@@ -52,7 +52,7 @@ export const VALUE_FLAGS = new Set([
"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", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "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",
"max-runs",
@@ -60,12 +60,12 @@ export const VALUE_FLAGS = new Set([
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
"path", "phone", "policy", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum",
"reviewed-by", "reviewedBy",
"report-id",
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
"repo", "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window",
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id",
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
"sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey",
@@ -86,11 +86,11 @@ export const VALUE_FLAGS = new Set([
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
"V", "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "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", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"code", "comment", "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",
"default", "departmentId", "dept", "desc", "description", "description-file",
@@ -105,7 +105,7 @@ export const KNOWN_FLAGS = new Set([
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"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",
"json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
@@ -114,12 +114,12 @@ export const KNOWN_FLAGS = new Set([
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
"phone", "plain", "policy", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "repo",
"report-id",
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reviewed-by", "reviewedBy",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
+6
View File
@@ -60,6 +60,8 @@ describe("CLI read-only classification", () => {
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
["approval-runs", "list", "--corp", "corp-a"],
["deploy", "hosecloud", "status", "--corp", "corp-a"],
["hose-ebot", "search", "SN123", "--type", "callback", "--corp", "corp-a"],
["hose-ebot", "messages", "--corp", "corp-a"],
["preferences", "get"],
["doctor", "tenant", "--corp", "corp-a"],
["langfuse", "check"],
@@ -91,6 +93,8 @@ describe("CLI read-only classification", () => {
["simulation", "create", "--mode", "hosecloud"],
["deploy", "hosecloud", "sync", "sign-key"],
["deploy", "hosecloud", "configure"],
// The EBot approval callback writes accept/refuse into the live approval flow.
["hose-ebot", "callback", "--flow-id", "f1", "--node-id", "n1", "--action", "accept", "--comment", "ok", "--yes"],
["webhook", "delete", "hook-1"],
["webhook", "replay"],
["users", "reset-password", "corp-a:u1"],
@@ -100,6 +104,8 @@ describe("CLI read-only classification", () => {
["mcp"],
["update"],
["auth", "keys"],
// Mints and prints an OpenAPI credential, so it never qualifies as a read.
["auth", "hose-openapi-token"],
["analytics", "analyze", "record-1"],
["tool", "sealApprovalRuleCreate", "--json", "{}"],
["langfuse", "unknown-verb"],
+3
View File
@@ -64,6 +64,9 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
"integrations"
],
deploy: ["hosecloud requirements", "hosecloud list", "hosecloud get", "hosecloud status"],
// `hose-ebot callback` is deliberately absent: it mints an accessToken and writes an
// approval action into the live flow. Only the two discovery verbs read.
"hose-ebot": ["search", "messages"],
preference: ["get", "thinking-depth policies list"],
// `config mode`/`config lint` are omitted: classification is token-prefix based, so their
// read forms cannot be separated from the value-taking write forms. `config get` returns
+16 -1
View File
@@ -39,6 +39,7 @@ export const KNOWN_AREAS = new Set([
"corps",
"corp",
"source",
"hose-ebot",
"auth",
"users",
"contacts",
@@ -224,7 +225,16 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
if (
area === "report" &&
(action === "validate" ||
action === "render" ||
action === "export" ||
action === "template" ||
action === "chart" ||
action === "review" ||
Boolean(args.options.ledger))
) {
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
return;
}
@@ -416,6 +426,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "hose-ebot") {
await (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(action, maybeName, client, corp, args);
return;
}
if (area === "preference" || area === "preferences") {
await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
return;
+59
View File
@@ -10,6 +10,7 @@ import {
exchangeHoseAssistLink,
fetchHoseStaffDetails,
getHoseEnterpriseUrl,
getHoseOpenapiToken,
getHoseProvisionalAuthLink,
getHoseSealSession,
normalizeBaseUrl,
@@ -402,4 +403,62 @@ describe("hose auth helpers", () => {
expect(getHoseProvisionalAuthLink(corp, -100)).rejects.toThrow("Invalid expire seconds");
expect(getHoseProvisionalAuthLink(corp, 0)).rejects.toThrow("Invalid expire seconds");
});
test("getHoseOpenapiToken serves a fresh cached token and mints a new one under force", async () => {
setupTokenStore({
"corp-test": {
hose: {
openapi: {
token: "cached-openapi-token",
expiresAt: Date.now() + 3600_000
}
}
}
});
const corp: CorpConfig = {
id: "corp-test",
name: "Corp Test",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "staff-1",
corpId: "CORP-TEST"
},
auth: { refreshTtl: 300 }
};
let mintCount = 0;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (new URL(urlStr).pathname === "/api/openapi/v1/auth/getAccessToken") {
mintCount += 1;
return new Response(JSON.stringify({ value: { accessToken: "minted-openapi-token" } }), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response("not found", { status: 404 });
}) as typeof fetch;
const cached = await getHoseOpenapiToken(corp);
expect(cached.cached).toBe(true);
expect(cached.token).toBe("cached-openapi-token");
expect(mintCount).toBe(0);
const forced = await getHoseOpenapiToken(corp, { force: true });
expect(forced.cached).toBe(false);
expect(forced.token).toBe("minted-openapi-token");
expect(mintCount).toBe(1);
expect(getHoseAuthCache("corp-test").openapi?.token).toBe("minted-openapi-token");
const reused = await getHoseOpenapiToken(corp);
expect(reused.cached).toBe(true);
expect(reused.token).toBe("minted-openapi-token");
expect(mintCount).toBe(1);
});
});
+22 -9
View File
@@ -113,7 +113,10 @@ export type HoseProbeResult = {
expireTime?: number;
};
const openapiTokenRequests = new Map<string, Promise<string>>();
/** A Hose OpenAPI access token plus whether it was served from the local SWR cache. */
export type HoseOpenapiTokenResult = TokenEntry & { cached: boolean };
const openapiTokenRequests = new Map<string, Promise<TokenEntry>>();
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
export function normalizeBaseUrl(url: string): string {
@@ -298,17 +301,20 @@ async function fetchHoseOpenapiToken(source: HoseSealSource): Promise<TokenEntry
};
}
export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string> {
export async function getHoseOpenapiToken(
corp: CorpConfig,
options?: { force?: boolean }
): Promise<HoseOpenapiTokenResult> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const cache = getHoseAuthCache(corp.id);
if (isFresh(cache.openapi)) {
return cache.openapi.token;
if (!options?.force && isFresh(cache.openapi)) {
return { ...cache.openapi, cached: true };
}
const pending = openapiTokenRequests.get(corp.id);
if (pending) return pending;
if (pending) return { ...(await pending), cached: false };
const request = fetchHoseOpenapiToken(corp.source)
.then((openapi) => {
@@ -316,11 +322,18 @@ export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string>
...getHoseAuthCache(corp.id),
openapi
});
return openapi.token;
return openapi;
})
.finally(() => openapiTokenRequests.delete(corp.id));
openapiTokenRequests.set(corp.id, request);
return request;
return { ...(await request), cached: false };
}
export async function ensureHoseOpenapiToken(
corp: CorpConfig,
options?: { force?: boolean }
): Promise<string> {
return (await getHoseOpenapiToken(corp, options)).token;
}
export async function fetchHoseCloseApiToken(
@@ -415,7 +428,7 @@ export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise<string> {
export async function getHoseProvisionalAuthLink(
corp: CorpConfig,
expiresIn = 7200,
_options?: { force?: boolean }
options?: { force?: boolean }
): Promise<{
corpId: string;
staffId: string;
@@ -431,7 +444,7 @@ export async function getHoseProvisionalAuthLink(
throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`);
}
const openapiToken = await ensureHoseOpenapiToken(corp);
const openapiToken = await ensureHoseOpenapiToken(corp, { force: options?.force });
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn);
if (!provisional.url) {
throw new Error("Hose provisional auth URL was not available");
+81 -5
View File
@@ -36,13 +36,88 @@ export interface HoseOutboundLogItem {
response?: unknown;
}
/**
* A configured outbound message on the Hose side (EBot push or completion
* callback). Only the fields seal-use surfaces are kept; Hose returns more.
*/
export interface HoseOutboundMessageConfig {
id: string;
messageName?: string;
messageType?: string;
enable?: boolean;
signKey?: string;
callbackUrl?: string;
corporationId?: string;
actionEvent?: string[];
formFields?: string[];
remark?: string;
createTime?: number;
updateTime?: number;
}
function parseOutboundMessage(item: unknown): HoseOutboundMessageConfig | undefined {
if (!item || typeof item !== "object" || Array.isArray(item)) return undefined;
const raw = item as Record<string, unknown>;
if (typeof raw.id !== "string" || !raw.id) return undefined;
const stringList = (value: unknown): string[] | undefined =>
Array.isArray(value)
? value.filter((entry): entry is string => typeof entry === "string")
: undefined;
return {
id: raw.id,
messageName: typeof raw.messageName === "string" ? raw.messageName : undefined,
messageType: typeof raw.messageType === "string" ? raw.messageType : undefined,
enable: typeof raw.enable === "boolean" ? raw.enable : undefined,
signKey: typeof raw.signKey === "string" ? raw.signKey : undefined,
callbackUrl: typeof raw.callbackUrl === "string" ? raw.callbackUrl : undefined,
corporationId: typeof raw.corporationId === "string" ? raw.corporationId : undefined,
actionEvent: stringList(raw.actionEvent),
formFields: stringList(raw.formFields),
remark: typeof raw.remark === "string" ? raw.remark : undefined,
createTime: typeof raw.createTime === "number" ? raw.createTime : undefined,
updateTime: typeof raw.updateTime === "number" ? raw.updateTime : undefined
};
}
/**
* List every configured outbound message for the tenant via the read-only
* CloseAPI `GET api/outbound/v1/message`. Each row carries the `signKey` that
* the EBot callback URL embeds as `config_id`, which is how operators find
* which signature key belongs to which message.
*/
export async function fetchHoseOutboundMessages(
sourceCorp: CorpConfig
): Promise<HoseOutboundMessageConfig[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
`企业「${sourceCorp.name}」非合思(hose)租户,无法查询合思出站消息配置。`
);
}
const client = await createHoseCloseClient(sourceCorp);
const response = (await client
.get("api/outbound/v1/message", {
searchParams: { corpId: sourceCorp.source.corpId }
})
.json()) as { items?: unknown };
if (!Array.isArray(response.items)) {
throw new Error("合思出站消息接口未返回 items 列表,响应结构与预期不符");
}
return response.items
.map(parseOutboundMessage)
.filter((message): message is HoseOutboundMessageConfig => message !== undefined);
}
/**
* Query CloseAPI's outbound message log for one document SN (flowId.form.code).
*/
export async function searchOutboundMessageLogs(
client: KyInstance,
corpId: string,
sn: string
sn: string,
options?: { limit?: number }
): Promise<HoseOutboundLogItem[]> {
const response = (await client
.post("api/outbound/v1/message/messageLog", {
@@ -51,10 +126,10 @@ export async function searchOutboundMessageLogs(
corpId
},
json: {
limit: { start: 0, count: 20 },
limit: { start: 0, count: options?.limit ?? 20 },
orderBy: [{ value: "createTime", order: "DESC" }],
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType",
filterBy: `(flowId.form.code==("${sn}"))`
filterBy: `(flowId.form.code==("${sn.replace(/"/g, '\\"')}"))`
}
})
.json()) as { items?: HoseOutboundLogItem[] };
@@ -67,7 +142,8 @@ export async function searchOutboundMessageLogs(
*/
export async function fetchHoseOutboundLogs(
sourceCorp: CorpConfig,
sn: string
sn: string,
options?: { limit?: number }
): Promise<HoseOutboundLogItem[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
@@ -76,5 +152,5 @@ export async function fetchHoseOutboundLogs(
}
const client = await createHoseCloseClient(sourceCorp);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn, options);
}
+123
View File
@@ -0,0 +1,123 @@
import { HTTPError } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { CliError, validationError } from "../../../core/errors.js";
import { createHoseOpenClient } from "./client.js";
/**
* EBot approval callback (`POST api/openapi/v1/approval`) — the OpenAPI call an
* external service makes after processing an outbound message, so the EBot node
* can advance (accept/refuse) or add approvers. Only EBot-node approvals are
* supported upstream; everything else comes back as business code 412.
*/
export const EBOT_APPROVAL_ACTIONS = ["accept", "refuse", "preAdd", "aftAdd"] as const;
export type EbotApprovalAction = (typeof EBOT_APPROVAL_ACTIONS)[number];
export const EBOT_RESUBMIT_METHODS = ["FROM_START", "TO_REJECTOR"] as const;
export type EbotApprovalCallbackParams = {
signKey: string;
flowId: string;
nodeId: string;
action: EbotApprovalAction;
comment: string;
policy?: "ALL" | "ANY";
addApproverIds?: string[];
rejectTo?: string;
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
};
export type EbotApprovalCallbackResult = {
code: string;
message: string;
};
export async function executeEbotApprovalCallback(
corp: CorpConfig,
params: EbotApprovalCallbackParams
): Promise<EbotApprovalCallbackResult> {
if (corp.source.type !== "hose") {
throw validationError(
`企业「${corp.name}」非合思(hose)租户,无法调用合思 OpenAPI 审批回调。`
);
}
const appKey = corp.source.appKey ?? corp.source.key;
const appSecurity = corp.source.appSecurity ?? corp.source.password;
if (!appKey || !appSecurity) {
throw validationError(
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法换取 accessToken 执行审批回调。`
);
}
if ((params.action === "preAdd" || params.action === "aftAdd") && (!params.addApproverIds || params.addApproverIds.length === 0)) {
throw validationError(
`执行${params.action === "preAdd" ? "前加签 (preAdd)" : "后加签 (aftAdd)"}时,必须通过 --add-approver-ids 指定加签审批人 ID 列表。`
);
}
if (params.action === "aftAdd" && (params.addApproverIds?.length ?? 0) > 1 && !params.policy) {
throw validationError(
"后加签审批人超过 1 人时,必须指定会签方式 --policy ALL (会签) 或 --policy ANY (或签)。"
);
}
// The manual requires a token minted right before the callback: accessToken
// expires quickly and stale reuse is not worth the risk on a flow write.
const client = await createHoseOpenClient(corp, undefined, { force: true });
let response: unknown;
try {
response = await client.post("api/openapi/v1/approval", {
json: {
signKey: params.signKey,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
comment: params.comment,
...(params.policy ? { policy: params.policy } : {}),
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
}
}).json();
} catch (error) {
// HTTP 400 means our request body was rejected — an input problem, so the
// caller gets exit 13 with the upstream body; HTTP 401/403 fall through to
// the shared classifier (exit 11).
if (error instanceof HTTPError && error.response.status === 400) {
throw validationError(`合思审批回调参数被上游拒绝 (HTTP 400):${error.message}`);
}
throw error;
}
const rawObj = (response && typeof response === "object") ? (response as Record<string, unknown>) : {};
const valueObj = rawObj.value && typeof rawObj.value === "object" ? (rawObj.value as Record<string, unknown>) : rawObj;
const rawCode = valueObj.code ?? rawObj.code;
const code = rawCode !== undefined ? String(rawCode) : undefined;
const message = (typeof valueObj.message === "string" ? valueObj.message : (typeof rawObj.message === "string" ? rawObj.message : "")) || "";
if (code === "204") {
return { code, message };
}
if (code === "401") {
throw new CliError(
"合思审批回调失败:签名秘钥 signKey 错误 (401)。" +
"请核对出站消息配置中的 signKey(seal-use hose-ebot messages --reveal 可查看)。",
11
);
}
if (code === "400") {
throw validationError(`合思审批回调参数错误 (400):${message || "请求参数错误"}`);
}
if (code === "412") {
throw new CliError(
`合思审批回调失败:业务前置条件不满足 (412):${message || "当前节点不可审批或已被处理"}。\n` +
"👉 建议:运行 seal-use hose-ebot search <单号SN> 核对单据当前节点与出站记录。",
1
);
}
if (!code) {
throw new Error(`合思审批回调未返回业务码,响应与预期不符:${JSON.stringify(response)}`);
}
throw new Error(`合思审批回调失败 (${code}):${message || "未知错误"}`);
}
+3 -2
View File
@@ -38,13 +38,14 @@ export function createHoseOpenClientWithCredentials(
export async function createHoseOpenClient(
corp: CorpConfig,
customHeaders?: Record<string, string>
customHeaders?: Record<string, string>,
options?: { force?: boolean }
): Promise<KyInstance> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`);
}
const token = await ensureHoseOpenapiToken(corp);
const token = await ensureHoseOpenapiToken(corp, { force: options?.force });
return createHoseOpenClientWithCredentials(
{
domain: corp.source.domain,
+1
View File
@@ -1,3 +1,4 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
export * from "./approval.js";
@@ -1263,6 +1263,24 @@ describe("sealCapabilities", () => {
expect(res.divergedRuns[0]?.sn).toBe("SN-001");
expect(res.divergedRuns[0]?.triggeredConditions).toContain("缺失发票");
expect(res.charts.vennSvg).toContain("<svg");
const rangeRes = await handler(mockClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
templates: ["差旅报销"]
}, fakeContext()) as {
period: { start: string; end: string; label?: string };
templateGroups: Array<{ template: string }>;
};
expect(rangeRes.period.start).toBe("2026-08-12");
expect(rangeRes.period.end).toBe("2026-09-18");
expect(rangeRes.templateGroups[0]?.template).toBe("差旅报销");
// 验证 maxRuns 突破了原本的 500 限制,传入 2000 校验合法
expect(() => tool!.parameters.parse({ month: "2026-08", maxRuns: 2000 })).not.toThrow();
const monthlyTool = sealCapabilities.find((item) => item.name === "sealReportMonthlyGet");
expect(monthlyTool).toBeDefined();
expect(() => monthlyTool!.parameters.parse({ month: "2026-08", maxRuns: 2000 })).not.toThrow();
});
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
+217
View File
@@ -0,0 +1,217 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { maskHoseSecurity, normalizeBaseUrl } from "../../../core/auth/hose.js";
import { confirmationRequired, validationError } from "../../../core/errors.js";
import { fetchHoseOutboundLogs, fetchHoseOutboundMessages } from "../../hose/close/outbound.js";
import { executeEbotApprovalCallback } from "../../hose/open/approval.js";
import { listHoseIntegrations, selectHoseIntegration } from "../outbound/push.js";
import type { CapabilityContext } from "./helpers.js";
/**
* The niche Hose outbound loop, exposed under the first-level `seal-use hose-ebot`
* command: discover outbound records by document SN, discover the outbound
* message configs (and their signKey), then write the EBot approval callback.
*/
export const hoseCapabilities = [
{
name: "sealHoseOutboundSearch",
description: "按单号搜索合思出站消息调用记录(出站触发 INVOKING / 回调 CALLBACK),返回含唯一 id 的记录列表",
parameters: z.object({
sn: z.string().describe("合思单号 (flowId.form.code)"),
type: z
.enum(["invoking", "callback"])
.optional()
.describe("记录类型筛选:invoking=出站触发,callback=回调;缺省全部"),
limit: z
.number()
.int()
.positive()
.max(100)
.optional()
.default(20)
.describe("返回条数上限(默认 20,最大 100)"),
reveal: z.boolean().optional().describe("明文返回记录中的 signKey(默认脱敏)")
}),
handler: async (
_client: KyInstance,
params: { sn: string; type?: "invoking" | "callback"; limit: number; reveal?: boolean },
context: CapabilityContext
) => {
// The type filter applies client-side, so over-fetch first to keep the
// requested page size after filtering.
const serverCount = params.type ? Math.min(params.limit * 4, 100) : params.limit;
const allRecords = await fetchHoseOutboundLogs(context.corp, params.sn, { limit: serverCount });
const filtered = params.type
? allRecords.filter((record) => (record.type ?? "").toLowerCase() === params.type)
: allRecords;
const records = filtered.slice(0, params.limit);
return {
corpId: context.corp.id,
sn: params.sn,
type: params.type ?? "all",
count: records.length,
revealed: params.reveal === true,
records: records.map((record) =>
record.request?.signKey
? {
...record,
request: {
...record.request,
signKey: params.reveal
? record.request.signKey
: maskHoseSecurity(record.request.signKey)
}
}
: record
)
};
}
},
{
name: "sealHoseOutboundMessages",
description: "列出合思侧全部出站消息配置(含 signKey、回调地址、启用状态),用于发现 EBot 出站消息及其签名密钥",
parameters: z.object({
reveal: z.boolean().optional().describe("明文返回 signKey(默认脱敏为 8...4 形式)"),
type: z
.enum(["flow", "message"])
.optional()
.describe("按消息类型过滤:flow=审批流 EBot 出站,message=完成回调/通知")
}),
handler: async (
_client: KyInstance,
params: { reveal?: boolean; type?: "flow" | "message" },
context: CapabilityContext
) => {
const messages = await fetchHoseOutboundMessages(context.corp);
const filtered = params.type
? messages.filter((message) => message.messageType === params.type)
: messages;
return {
corpId: context.corp.id,
corpName: context.corp.name,
count: filtered.length,
revealed: params.reveal === true,
messages: filtered.map((message) => ({
...message,
signKey: message.signKey
? params.reveal
? message.signKey
: maskHoseSecurity(message.signKey)
: undefined
}))
};
}
},
{
name: "sealHoseApprovalCallback",
description: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签),向审批流回写结果;需 --yes/--confirm,或 --dry-run 预览",
parameters: z.object({
signKey: z
.string()
.optional()
.describe("出站消息签名密钥;缺省时从本企业 Seal 合思集成解析(仅一个集成时自动选择)"),
flowId: z.string().describe("单据 ID(出站消息中的 flowId)"),
nodeId: z.string().describe("当前 EBot 节点 ID(出站消息中的 nodeId)"),
action: z
.enum(["accept", "refuse", "preAdd", "aftAdd"])
.describe("accept 同意 / refuse 驳回 / preAdd 前加签 / aftAdd 后加签"),
comment: z.string().describe("审批意见"),
policy: z.enum(["ALL", "ANY"]).optional().describe("会签方式:ALL 会签 / ANY 或签(后加签超过一人时必填)"),
addApproverIds: z.array(z.string()).optional().describe("前后加签审批人 ID 列表(后加签时必填)"),
rejectTo: z.string().optional().describe("驳回目标节点 ID;缺省按 EBot 节点驳回配置"),
resubmitMethod: z
.enum(["FROM_START", "TO_REJECTOR"])
.optional()
.describe("驳回后重提方式:FROM_START 重新走审批流 / TO_REJECTOR 直接送审至此节点"),
dryRun: z.boolean().optional().default(false).describe("仅预览回调请求,不执行"),
confirm: z.boolean().optional().describe("明确确认执行回调;CLI 使用 --yes 或 --confirm")
}),
handler: async (
client: KyInstance,
params: {
signKey?: string;
flowId: string;
nodeId: string;
action: "accept" | "refuse" | "preAdd" | "aftAdd";
comment: string;
policy?: "ALL" | "ANY";
addApproverIds?: string[];
rejectTo?: string;
resubmitMethod?: "FROM_START" | "TO_REJECTOR";
dryRun?: boolean;
confirm?: boolean;
},
context: CapabilityContext
) => {
if (!params.dryRun && params.confirm !== true) {
throw confirmationRequired(
"Refusing to run the Hose EBot approval callback without --yes or --confirm. Use --dry-run to preview first.",
`seal-use hose-ebot callback --flow-id ${params.flowId} --node-id ${params.nodeId} --action ${params.action} --comment "${params.comment}" --dry-run --corp ${context.corp.id}`
);
}
if (context.corp.source.type !== "hose") {
throw validationError(
`企业「${context.corp.name}」非合思(hose)租户,无法执行合思 EBot 审批回调。`
);
}
// An explicit signKey (typically discovered via `hose-ebot messages --reveal`)
// skips the Seal-side lookup; without one the configured integration decides.
let signKey = params.signKey?.trim();
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const integration = selectHoseIntegration({
integrations: listHoseIntegrations(config),
corpName: context.corp.name,
corpId: context.corp.id
});
signKey = integration.signKey;
}
if (!signKey) {
throw validationError(
`企业「${context.corp.name}」的合思出站配置未保存 signKey,请重新执行 configure。`
);
}
const payload = {
signKey,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
comment: params.comment,
...(params.policy ? { policy: params.policy } : {}),
...(params.addApproverIds?.length ? { addApproverIds: params.addApproverIds } : {}),
...(params.rejectTo ? { rejectTo: params.rejectTo } : {}),
...(params.resubmitMethod ? { resubmitMethod: params.resubmitMethod } : {})
};
if (params.dryRun) {
return {
preview: true,
corpId: context.corp.id,
endpoint: `${normalizeBaseUrl(context.corp.source.domain)}/api/openapi/v1/approval`,
payload: { ...payload, signKey: maskHoseSecurity(signKey) },
note: "仅预览:正式执行需去掉 --dry-run 并追加 --yes(届时实时换取 accessToken 后回调)。"
};
}
const result = await executeEbotApprovalCallback(context.corp, payload);
console.error(`✓ 回调审批成功 (code ${result.code}): ${result.message}`);
console.error(
`👉 Next action: seal-use hose-ebot search <单号SN> --corp ${context.corp.id} 核对该单出站/回调记录`
);
return {
corpId: context.corp.id,
flowId: params.flowId,
nodeId: params.nodeId,
action: params.action,
ok: true,
...result
};
}
}
];
+5
View File
@@ -7,6 +7,7 @@ import { webhookCapabilities } from "./webhook.js";
import { approvalRunsCapabilities } from "./approval-runs.js";
import { simulationCapabilities } from "./simulation.js";
import { deployCapabilities } from "./deploy.js";
import { hoseCapabilities } from "./hose.js";
import { preferenceCapabilities } from "./preference.js";
import { reportCapabilities } from "./reports.js";
@@ -23,6 +24,7 @@ export const sealCapabilities = [
...approvalRunsCapabilities,
...simulationCapabilities,
...deployCapabilities,
...hoseCapabilities,
...preferenceCapabilities,
...reportCapabilities
];
@@ -90,6 +92,8 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealDeployHosecloudRequirements",
"sealDeployHosecloudStatus",
"sealExpensesList",
"sealHoseOutboundMessages",
"sealHoseOutboundSearch",
"sealInsightExport",
"sealInsightPerformanceGet",
"sealInsightRisksByTagGet",
@@ -138,6 +142,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
"sealDeployHosecloudConfigure",
"sealDeployHosecloudSync",
"sealDeployHosecloudTestOutbound",
"sealHoseApprovalCallback",
"sealInsightRecordAnalyze",
"sealPreferenceDecisionUpdate",
"sealPreferenceThinkingDepthPoliciesRemove",
+66 -10
View File
@@ -7,24 +7,38 @@ export const reportCapabilities = [
{
name: "sealReportMonthlyGet",
description:
"生成月度 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
"生成 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
parameters: z.object({
startDate: z
.string()
.optional()
.describe("统计起始日期 (YYYY-MM-DD)"),
endDate: z
.string()
.optional()
.describe("统计截止日期 (YYYY-MM-DD)"),
month: z
.string()
.regex(/^\d{4}-\d{2}$/)
.describe("统计月份,YYYY-MM"),
.optional()
.describe("统计月份 (YYYY-MM,可选快捷方式)"),
templates: z
.array(z.string())
.optional()
.describe("单据模板白名单列表(可选,未指定则统计全量单据模板)"),
templatePath: z
.string()
.optional()
.describe("自定义模板 Markdown 路径;缺省用随 CLI 内嵌的仓内 monthly.md,不依赖当前目录"),
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
ledgerPath: z.string().optional().describe("本地已编辑/已裁决的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源"),
maxRuns: z
.number()
.int()
.positive()
.max(500)
.max(100000)
.optional()
.describe("拉取审批运行明细分块的上限,默认 500"),
.describe("拉取审批运行明细分块的上限(可选,未指定时默认拉取指定时间区间内的全量单据,最大安全上限 100000)"),
allowUnreviewed: z
.boolean()
.optional()
@@ -32,11 +46,25 @@ export const reportCapabilities = [
}),
handler: async (
client: KyInstance,
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number; allowUnreviewed?: boolean },
params: {
startDate?: string;
endDate?: string;
month?: string;
templates?: string[];
ledgerPath?: string;
templatePath?: string;
reportId?: string;
maxRuns?: number;
allowUnreviewed?: boolean;
},
context: CapabilityContext
) =>
buildMonthlyReport(client, {
startDate: params.startDate,
endDate: params.endDate,
month: params.month,
templates: params.templates,
ledgerPath: params.ledgerPath,
corp: { id: context.corp.id, name: context.corp.name },
templatePath: params.templatePath,
reportId: params.reportId,
@@ -47,27 +75,55 @@ export const reportCapabilities = [
{
name: "sealReportDataGet",
description:
"获取月度 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
"获取 AI 审核报告的轻量纯结构化数据包(效能指标、分模板统计、风险标签、人机分歧单据列表与单个触发条件)。不依赖 Markdown 模板,供 Agent 交互复核或填充文档",
parameters: z.object({
startDate: z
.string()
.optional()
.describe("统计起始日期 (YYYY-MM-DD)"),
endDate: z
.string()
.optional()
.describe("统计截止日期 (YYYY-MM-DD)"),
month: z
.string()
.regex(/^\d{4}-\d{2}$/)
.describe("统计月份,YYYY-MM"),
.optional()
.describe("统计月份 (YYYY-MM,可选快捷方式)"),
templates: z
.array(z.string())
.optional()
.describe("单据模板白名单列表(可选,未指定则统计全量单据模板)"),
ledgerPath: z
.string()
.optional()
.describe("本地已编辑/已裁决的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源"),
maxRuns: z
.number()
.int()
.positive()
.max(500)
.max(100000)
.optional()
.describe("拉取审批运行明细分块的上限,默认 500")
.describe("拉取审批运行明细分块的上限(可选,未指定时默认拉取指定时间区间内的全量单据,最大安全上限 100000)")
}),
handler: async (
client: KyInstance,
params: { month: string; maxRuns?: number },
params: {
startDate?: string;
endDate?: string;
month?: string;
templates?: string[];
ledgerPath?: string;
maxRuns?: number;
},
context: CapabilityContext
) =>
getMonthlyReportData(client, {
startDate: params.startDate,
endDate: params.endDate,
month: params.month,
templates: params.templates,
ledgerPath: params.ledgerPath,
corp: { id: context.corp.id, name: context.corp.name },
maxRuns: params.maxRuns
})
+3 -2
View File
@@ -1,6 +1,6 @@
# Seal 报告生成与渲染域 (`src/domains/seal/reports`)
本模块为 `seal-use` 的离线报告引擎,负责企业 AI 审核月度准确率报告的**数据提取、Markdown 填充、格式校验、独立图表生成、自包含 HTML 编译与 A4 PDF 打印级导出**。全流程零 Python 依赖、零外部 OSS 水印图床依赖。
本模块为 `seal-use` 的离线报告引擎,负责企业 AI 审核报告(验收、上线、周期审计)的**数据提取、台账导出导入、Markdown 填充、格式校验、独立图表生成、自包含 HTML 编译与 A4 PDF 打印级导出**。全流程零 Python 依赖、零外部 OSS 水印图床依赖。
---
@@ -18,7 +18,7 @@ src/domains/seal/reports/
│ ├── describe.ts # 解析 Markdown 标题并反推各章节数据需求
│ ├── collect.ts # 通过 Seal API 抓取单据指标,合并人工复核记录
│ ├── render.ts # 模板占位填充与章节内容排版
│ ├── monthly.ts # 月度报告顶层调度器 (buildMonthlyReport)
│ ├── monthly.ts # 报告顶层调度器 (buildMonthlyReport / 支持 --ledger 离线台账)
│ ├── review-store.ts # 人工复核判定本地存储(JSONL 租户分片)
│ └── index.ts # 流水线出口
├── render/ # 渲染与排版引擎底层
@@ -31,6 +31,7 @@ src/domains/seal/reports/
│ └── index.ts # 校验门禁出口
├── export/ # 文件系统整包导出与资产收拢
│ ├── files.ts # 报告整包打包器 (exportReportPackage) 及文件保存
│ ├── ledger.ts # 明细台账双端依据导出 (Excel/CSV) 与自由裁量加载
│ └── index.ts # 导出器出口
├── templates/ # 模板与静态资源
│ ├── monthly.md # 标准月度报告 Markdown 模板
+40 -1
View File
@@ -210,6 +210,45 @@ describe("local report CLI", () => {
expect(result.exitCode).toBe(0);
expect(existsSync(join(packageDir, "报告.md.assets", "1-chart-4x.png"))).toBe(true);
expect(existsSync(join(packageDir, "报告.md.assets", "chart-4x.png"))).toBe(true);
}, 15000);
}, 35000);
test("CLI report ledger and --ledger options work seamlessly", async () => {
const dir = workspace();
const csvContent = [
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
'rec-1,SN-1,差旅报销,出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,领导特批,分歧,AI判断正确 / 人工判断错误,专家,依据合规,12',
'rec-2,SN-2,差旅报销,采购,李四,行政部,2026-08-16 11:00:00,同意,合规,同意,通过,一致,双方判断均正确,专家,无误,8'
].join("\n");
const csvFile = join(dir, "my-ledger.csv");
writeFileSync(csvFile, csvContent);
// 1. seal-use report ledger --ledger <file> --out <file.xlsx>
const xlsxOut = join(dir, "converted.xlsx");
const ledgerRes = await runCli(["report", "ledger", "--ledger", csvFile, "--out", xlsxOut, "--corp", "test-corp"]);
expect(ledgerRes.exitCode).toBe(0);
expect(existsSync(xlsxOut)).toBe(true);
// 2. seal-use report data --ledger <file> --corp test-corp
const dataRes = await runCli(["report", "data", "--ledger", csvFile, "--corp", "test-corp"]);
expect(dataRes.exitCode).toBe(0);
const parsedData = JSON.parse(dataRes.stdout);
expect(parsedData.templateGroups).toHaveLength(1);
expect(parsedData.templateGroups[0].template).toBe("差旅报销");
expect(parsedData.metrics.aiAccuracy).toBe(100);
// 3. seal-use report review import <file> --corp test-corp
const importRes = await runCli(["report", "review", "import", csvFile, "--corp", "test-corp"]);
expect(importRes.exitCode).toBe(0);
const parsedImport = JSON.parse(importRes.stdout);
expect(parsedImport.importedCount).toBe(2);
// 4. seal-use report generate --ledger <file> --out <report.md> --corp test-corp
const reportOut = join(dir, "generated-report.md");
const genRes = await runCli(["report", "generate", "--ledger", csvFile, "--out", reportOut, "--corp", "test-corp"]);
expect(genRes.exitCode).toBe(0);
expect(existsSync(reportOut)).toBe(true);
const md = readFileSync(reportOut, "utf8");
expect(md).toContain("差旅报销");
});
});
+1
View File
@@ -1 +1,2 @@
export * from "./files.js";
export * from "./ledger.js";
+383 -42
View File
@@ -1,7 +1,35 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import ExcelJS from "exceljs";
import type { ReportBlock, ReportData } from "../pipeline/collect.js";
import { validationError } from "../../../../core/errors.js";
import {
polarityOf,
populateReviewsAndMetrics,
type ReportBlock,
type ReportData
} from "../pipeline/collect.js";
import { ReviewsMap, type ReviewRecord } from "../pipeline/review-store.js";
function csvEscape(val: string | number | undefined): string {
export const REPORT_LEDGER_HEADERS = [
"审核ID(recordId)",
"单据编号(SN)",
"单据模板",
"单据标题/事由",
"提交人",
"费用承担部门",
"跑批时间",
"AI审批决策",
"AI审核完整意见与违规详情",
"人工审批结论",
"人工审批批注/驳回说明",
"人机一致性",
"复核定性裁决",
"复核人",
"复核批注说明",
"审批耗时(秒)"
] as const;
function csvEscape(val: string | number | undefined | null): string {
if (val === undefined || val === null) return "";
const str = String(val).replace(/\r?\n/g, " ").trim();
if (/[",\n]/.test(str)) {
@@ -10,47 +38,118 @@ function csvEscape(val: string | number | undefined): string {
return str;
}
function formatAgreement(agreement: ReportBlock["agreement"]): string {
export function formatAgreement(agreement: ReportBlock["agreement"]): string {
if (agreement === "agreed") return "一致";
if (agreement === "diverged") return "分歧";
return "未完结/流转中";
}
function formatVerdict(block: ReportBlock): string {
/**
* 将 AI 审核摘要与命中的具体规则风险详情合成为完整的审核意见文本
*/
export function formatAiOpinion(block: { aiSummary?: string; conditions?: string[] }): string {
const parts: string[] = [];
if (block.aiSummary && block.aiSummary.trim()) {
parts.push(block.aiSummary.trim());
}
if (block.conditions && block.conditions.length > 0) {
const condStr = block.conditions.map((c, i) => `${i + 1}. ${c}`).join("; ");
if (!parts.some((p) => p.includes(condStr))) {
parts.push(`【触发违规/风险项】${condStr}`);
}
}
return parts.join("\n") || "—";
}
/**
* 规范化复核裁决定性措辞:
* 严密区分「单据违规判定(通过/驳回)」与「审核行为复核(判断正确/判定误判)」,杜绝含混的“失准”造成歧义。
*/
export 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") return "AI 依规正确 / 人工失准 (D4)";
if (v === "human_correct") return "人工合理 / AI 失准";
if (v === "both_wrong") return "双方均失准";
if (v === "both_correct" || (!v && block.agreement === "agreed")) return "双方判断均正确";
if (v === "ai_correct") return "AI 判断正确 / 人工判断错误";
if (v === "human_correct") return "人工判断正确 / AI 判定误判";
if (v === "both_wrong") return "双方判定均误判";
if (v === "undecided") return "存疑待定";
return "待复核";
}
/**
* 构建带 UTF-8 BOM 的月度跑批与人工复核明细台账 CSV
* 解析人或 Agent 在 Excel/CSV 中填入的复核裁决定性文本,映射为标准 verdict
*/
export function parseVerdictText(text: string | number | undefined | null): ReviewRecord["verdict"] | undefined {
if (text === undefined || text === null) return undefined;
const str = String(text).trim();
if (!str || str === "—" || str === "-" || str === "待复核" || str === "待人工审批完结") return undefined;
const lower = str.toLowerCase();
// 1. ai_correct (AI判断正确 / 人工判断错误)
if (
lower.includes("ai_correct") ||
/ai.*(正确|依规|判对|看对)/i.test(str) ||
/人工.*(错误|误判|失准|漏审|看错|漏判)/i.test(str) ||
lower.includes("d4")
) {
if (/人工.*(正确|合理)/i.test(str) && /ai.*(错误|误判|失准)/i.test(str)) {
return "human_correct";
}
return "ai_correct";
}
// 2. human_correct (人工判断正确 / AI判定误判)
if (
lower.includes("human_correct") ||
/人工.*(正确|合理|判对|看对)/i.test(str) ||
/ai.*(误判|错误|失准|误报|漏报|漏审)/i.test(str)
) {
return "human_correct";
}
// 3. both_correct (双方判断均正确)
if (
lower.includes("both_correct") ||
/双方.*(正确|合理|无误)/i.test(str) ||
/一致.*正确/i.test(str) ||
lower.includes("d1") ||
lower.includes("d2")
) {
return "both_correct";
}
// 4. both_wrong (双方判定均误判)
if (
lower.includes("both_wrong") ||
/双方.*(误判|错误|失准)/i.test(str) ||
/都.*(错|误判)/i.test(str)
) {
return "both_wrong";
}
// 5. undecided (存疑待定)
if (
lower.includes("undecided") ||
/存疑|待定|暂不确定|无法判定/i.test(str)
) {
return "undecided";
}
return undefined;
}
/**
* 构建带 UTF-8 BOM 的跑批与人工复核明细台账 CSV
*/
export function buildReportLedgerCsv(data: ReportData): string {
const headers = [
"单据编号(SN)",
"单据模板",
"单据标题/事由",
"提交人",
"费用承担部门",
"跑批时间",
"AI审批决策",
"人工审批结论",
"人机一致性",
"复核定性结论",
"复核人",
"复核批注说明",
"审批耗时(秒)",
"AI审核意见摘要"
];
const headers = [...REPORT_LEDGER_HEADERS];
const rows = data.blocks.map((block) => {
const review = data.reviews.get(block.sn);
const review = data.reviews instanceof ReviewsMap
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
: (data.reviews as Map<string, ReviewRecord>).get(block.sn);
return [
block.recordId || "—",
block.sn,
block.template || "—",
block.title || "—",
@@ -58,13 +157,14 @@ export function buildReportLedgerCsv(data: ReportData): string {
block.department || "—",
block.createdAt || "—",
block.aiDecision || "—",
formatAiOpinion(block),
block.humanResult || "—",
block.humanComment || "—",
formatAgreement(block.agreement),
formatVerdict(block),
review?.reviewedBy || "—",
review?.note || "—",
block.durationSeconds ?? "",
block.aiSummary || "—"
review?.reviewedBy || block.reviewedBy || "—",
review?.note || block.reviewNote || "—",
block.durationSeconds ?? ""
].map(csvEscape).join(",");
});
@@ -72,7 +172,7 @@ export function buildReportLedgerCsv(data: ReportData): string {
}
/**
* 构建双 Sheet 的专业月度跑批与复核台账 Excel (.xlsx)
* 构建双 Sheet 的专业跑批与复核台账 Excel (.xlsx)
*/
export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
const workbook = new ExcelJS.Workbook();
@@ -84,20 +184,22 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
});
detailSheet.columns = [
{ header: "单据编号(SN)", key: "sn", width: 16 },
{ header: "审核ID(recordId)", key: "recordId", width: 28 },
{ header: "单据编号(SN)", key: "sn", width: 18 },
{ header: "单据模板", key: "template", width: 20 },
{ header: "单据标题/事由", key: "title", width: 32 },
{ header: "提交人", key: "submitter", width: 12 },
{ header: "费用承担部门", key: "department", width: 22 },
{ header: "跑批时间", key: "createdAt", width: 20 },
{ header: "AI审批决策", key: "aiDecision", width: 15 },
{ header: "人工审批结论", key: "humanResult", width: 16 },
{ header: "AI审批决策", key: "aiDecision", width: 14 },
{ header: "AI审核完整意见与违规详情", key: "aiOpinion", width: 55 },
{ header: "人工审批结论", key: "humanResult", width: 15 },
{ header: "人工审批批注/驳回说明", key: "humanComment", width: 38 },
{ header: "人机一致性", key: "agreement", width: 14 },
{ header: "复核定性结论", key: "verdict", width: 24 },
{ header: "复核定性裁决", key: "verdict", width: 26 },
{ header: "复核人", key: "reviewedBy", width: 14 },
{ header: "复核批注说明", key: "note", width: 38 },
{ header: "审批耗时(秒)", key: "durationSeconds", width: 14 },
{ header: "AI审核意见摘要", key: "aiSummary", width: 55 }
{ header: "审批耗时(秒)", key: "durationSeconds", width: 14 }
];
const headerRow = detailSheet.getRow(1);
@@ -107,8 +209,11 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
headerRow.height = 24;
for (const block of data.blocks) {
const review = data.reviews.get(block.sn);
const review = data.reviews instanceof ReviewsMap
? data.reviews.get({ recordId: block.recordId, sn: block.sn })
: (data.reviews as Map<string, ReviewRecord>).get(block.sn);
const row = detailSheet.addRow({
recordId: block.recordId || "—",
sn: block.sn,
template: block.template || "—",
title: block.title || "—",
@@ -116,13 +221,14 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
department: block.department || "—",
createdAt: block.createdAt || "—",
aiDecision: block.aiDecision || "—",
aiOpinion: formatAiOpinion(block),
humanResult: block.humanResult || "—",
humanComment: block.humanComment || "—",
agreement: formatAgreement(block.agreement),
verdict: formatVerdict(block),
reviewedBy: review?.reviewedBy || "—",
note: review?.note || "—",
durationSeconds: block.durationSeconds ?? "",
aiSummary: block.aiSummary || "—"
reviewedBy: review?.reviewedBy || block.reviewedBy || "—",
note: review?.note || block.reviewNote || "—",
durationSeconds: block.durationSeconds ?? ""
});
row.alignment = { vertical: "top", wrapText: true };
}
@@ -176,6 +282,241 @@ export async function buildReportLedgerXlsx(data: ReportData): Promise<Buffer> {
return Buffer.from(arrayBuffer);
}
/**
* 解析 CSV 行(支持引号转义与换行)
*/
function parseCsvRows(content: string): string[][] {
const rows: string[][] = [];
let currentRow: string[] = [];
let currentCell = "";
let inQuotes = false;
const text = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
for (let i = 0; i < text.length; i++) {
const char = text[i];
const next = text[i + 1];
if (inQuotes) {
if (char === '"') {
if (next === '"') {
currentCell += '"';
i++;
} else {
inQuotes = false;
}
} else {
currentCell += char;
}
} else {
if (char === '"') {
inQuotes = true;
} else if (char === ",") {
currentRow.push(currentCell.trim());
currentCell = "";
} else if (char === "\n" || (char === "\r" && next === "\n")) {
if (char === "\r") i++;
currentRow.push(currentCell.trim());
if (currentRow.some((c) => c !== "")) {
rows.push(currentRow);
}
currentRow = [];
currentCell = "";
} else if (char !== "\r") {
currentCell += char;
}
}
}
if (currentCell || currentRow.length > 0) {
currentRow.push(currentCell.trim());
if (currentRow.some((c) => c !== "")) {
rows.push(currentRow);
}
}
return rows;
}
/**
* 从本地已编辑/已裁剪的 Excel (.xlsx) 或 CSV 台账文件逆向解析载入 ReportData。
* 核心设计边界:
* 1. 严格以本地台账为唯一事实源,绝不越界回查云端接口;
* 2. Agent 从台账中剔除的模板和单据,完全不参与后续报告和指标统计;
* 3. 自动识别台账中填入的「复核定性裁决」,作为权威判定计算人机一致率与准确率;
* 4. 门禁校验仅校验当前台账内部剩余行的数据完备性。
*/
export async function loadReportDataFromLedger(
filePath: string,
options?: { corp?: { id: string; name: string } }
): Promise<ReportData> {
const resolvedPath = resolve(filePath);
if (!existsSync(resolvedPath)) {
throw validationError(`台账文件不存在: ${resolvedPath}`);
}
let rawRows: string[][] = [];
if (resolvedPath.endsWith(".xlsx")) {
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(resolvedPath);
const sheet = workbook.worksheets.find((w) => w.name.includes("明细")) ?? workbook.worksheets[0];
if (!sheet) {
throw validationError(`Excel 文件中未找到有效工作表: ${resolvedPath}`);
}
sheet.eachRow((row) => {
const values: string[] = [];
row.eachCell({ includeEmpty: true }, (cell) => {
let text = "";
if (cell.value !== null && cell.value !== undefined) {
if (typeof cell.value === "object" && "text" in cell.value) {
text = String(cell.value.text);
} else if (typeof cell.value === "object" && "result" in cell.value) {
text = String(cell.value.result);
} else {
text = String(cell.value);
}
}
values.push(text.trim());
});
rawRows.push(values);
});
} else {
const content = readFileSync(resolvedPath, "utf8");
rawRows = parseCsvRows(content);
}
if (rawRows.length < 2) {
throw validationError(`台账文件中没有有效数据行: ${resolvedPath}`);
}
const headerRow = rawRows[0]!;
const colMap: Record<string, number> = {};
headerRow.forEach((h, idx) => {
const clean = String(h).trim().toLowerCase();
if (clean.includes("审核id") || clean.includes("recordid")) colMap.recordId = idx;
else if (clean.includes("单据编号") || clean.includes("sn")) colMap.sn = idx;
else if (clean.includes("模板") || clean.includes("template")) colMap.template = idx;
else if (clean.includes("事由") || clean.includes("标题") || clean.includes("title")) colMap.title = idx;
else if (clean.includes("提交人") || clean.includes("submitter")) colMap.submitter = idx;
else if (clean.includes("部门") || clean.includes("department")) colMap.department = idx;
else if (clean.includes("时间") || clean.includes("createdat")) colMap.createdAt = idx;
else if (clean.includes("ai审批决策") || clean.includes("aidecision") || clean.includes("ai决策")) colMap.aiDecision = idx;
else if (clean.includes("ai审核") || clean.includes("ai意见") || clean.includes("aisummary") || clean.includes("违规详情")) colMap.aiSummary = idx;
else if (clean.includes("人工审批结论") || clean.includes("人工结论") || clean.includes("humanresult")) colMap.humanResult = idx;
else if (clean.includes("人工审批批注") || clean.includes("驳回说明") || clean.includes("驳回原因") || clean.includes("humancomment")) colMap.humanComment = idx;
else if (clean.includes("人机一致性") || clean.includes("一致性") || clean.includes("agreement")) colMap.agreement = idx;
else if (clean.includes("复核定性") || clean.includes("裁决") || clean.includes("verdict")) colMap.verdict = idx;
else if (clean.includes("复核人") || clean.includes("reviewedby")) colMap.reviewedBy = idx;
else if (clean.includes("复核批注") || clean.includes("批注说明") || clean.includes("reviewnote") || clean.includes("note")) colMap.reviewNote = idx;
else if (clean.includes("耗时") || clean.includes("duration")) colMap.durationSeconds = idx;
});
const blocks: ReportBlock[] = [];
const reviews = new ReviewsMap();
const createdDates: string[] = [];
for (let i = 1; i < rawRows.length; i++) {
const row = rawRows[i]!;
const sn = (colMap.sn !== undefined ? row[colMap.sn] : undefined) || `ROW-${i}`;
const recordId = colMap.recordId !== undefined && row[colMap.recordId] !== "—" ? row[colMap.recordId] : undefined;
const template = (colMap.template !== undefined ? row[colMap.template] : undefined) || "未标注模板";
const title = colMap.title !== undefined ? row[colMap.title] : undefined;
const submitter = colMap.submitter !== undefined ? row[colMap.submitter] : undefined;
const department = colMap.department !== undefined ? row[colMap.department] : undefined;
const createdAt = colMap.createdAt !== undefined ? row[colMap.createdAt] : undefined;
if (createdAt && createdAt !== "—") createdDates.push(createdAt.slice(0, 10));
const aiDecision = colMap.aiDecision !== undefined ? row[colMap.aiDecision] : undefined;
const aiSummary = colMap.aiSummary !== undefined ? row[colMap.aiSummary] : undefined;
const humanResult = colMap.humanResult !== undefined ? row[colMap.humanResult] : undefined;
const humanComment = colMap.humanComment !== undefined ? row[colMap.humanComment] : undefined;
let agreement: ReportBlock["agreement"] = "unknown";
const agreementText = colMap.agreement !== undefined ? row[colMap.agreement] ?? "" : "";
if (agreementText.includes("一致") || agreementText.toLowerCase() === "agreed") {
agreement = "agreed";
} else if (agreementText.includes("分歧") || agreementText.toLowerCase() === "diverged") {
agreement = "diverged";
} else if (agreementText.includes("未完结") || agreementText.includes("流转中")) {
agreement = "unknown";
} else {
const aiPol = polarityOf(aiDecision);
const humPol = polarityOf(humanResult);
if (aiPol === "unknown" || humPol === "unknown") agreement = "unknown";
else if (aiPol === humPol) agreement = "agreed";
else agreement = "diverged";
}
const rawVerdict = colMap.verdict !== undefined ? row[colMap.verdict] : undefined;
const verdict = parseVerdictText(rawVerdict);
const reviewedBy = colMap.reviewedBy !== undefined && row[colMap.reviewedBy] !== "—" ? row[colMap.reviewedBy] : undefined;
const reviewNote = colMap.reviewNote !== undefined && row[colMap.reviewNote] !== "—" ? row[colMap.reviewNote] : undefined;
if (verdict || reviewedBy || reviewNote) {
reviews.set({
recordId,
sn,
verdict: verdict ?? (agreement === "agreed" ? "both_correct" : "undecided"),
note: reviewNote,
reviewedBy,
recordedAt: new Date().toISOString()
});
}
const durVal = colMap.durationSeconds !== undefined ? Number(row[colMap.durationSeconds]) : undefined;
blocks.push({
recordId,
sn,
template,
title,
submitter,
department,
createdAt,
durationSeconds: Number.isFinite(durVal) ? durVal : undefined,
aiDecision,
humanResult,
agreement,
aiSummary,
humanComment,
verdict,
reviewedBy,
reviewNote
});
}
createdDates.sort();
const startIso = createdDates[0] ?? new Date().toISOString().slice(0, 10);
const endIso = createdDates[createdDates.length - 1] ?? startIso;
const periodLabel = startIso === endIso ? startIso : `${startIso} ~ ${endIso}`;
const metrics = populateReviewsAndMetrics(blocks, reviews);
return {
period: {
start: startIso,
end: endIso,
label: periodLabel,
month: startIso.slice(0, 7) === endIso.slice(0, 7) ? startIso.slice(0, 7) : undefined
},
corp: {
id: options?.corp?.id ?? "local-ledger",
name: options?.corp?.name ?? "本地台账企业"
},
fetched: {
blocks: true,
templateGroups: true,
performance: metrics.performance !== undefined,
riskStats: false,
riskDetails: false
},
blocks,
templateGroups: metrics.templateGroups,
reviews,
humanAccuracy: metrics.humanAccuracy,
notes: metrics.notes,
performance: metrics.performance
};
}
/**
* 当针对独立 Markdown 文件直接执行 report export 且无预生成台账时,从 Markdown 表格提取构建台账
*/
+268 -130
View File
@@ -1,14 +1,15 @@
import type { KyInstance } from "ky";
import * as api from "../../api.js";
import { formatBeijingIso } from "../../../../core/config/timestamps.js";
import { validationError } from "../../../../core/errors.js";
import type { ApprovalRun } from "../../types.js";
import type { ReportDemand } from "./describe.js";
import { loadReviews, type ReviewRecord } from "./review-store.js";
import { loadReviews, ReviewsMap, type ReviewRecord } from "./review-store.js";
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
type Polarity = "pass" | "reject" | "unknown";
function polarityOf(value: string | undefined): Polarity {
export function polarityOf(value: string | undefined): Polarity {
if (!value) return "unknown";
const text = value.trim();
if (/同意|通过|approve|pass|已支付|审批完成/i.test(text)) return "pass";
@@ -31,7 +32,7 @@ export type ReportBlock = {
aiSummary: string | undefined;
humanComment: string | undefined;
conditions?: string[];
/** 本地人工裁决结论(若该 SN 已 review),来自 review-store */
/** 本地人工裁决结论(来自 review-store,支持 recordId 与 sn 双键匹配) */
verdict?: ReviewRecord["verdict"];
reviewNote?: string;
reviewedBy?: string;
@@ -52,7 +53,7 @@ export type ReportTemplateGroup = {
export type ReportData = {
/** 报告信息表要用的上下文 */
period: { start: string; end: string; month: string };
period: { start: string; end: string; label?: string; month?: string };
corp: { id: string; name: string };
/** 需求 → 是否已按需取数(渲染器据此判断该章节数据完备度) */
fetched: Record<ReportDemand, boolean>;
@@ -71,8 +72,8 @@ export type ReportData = {
};
blocks: ReportBlock[];
templateGroups: ReportTemplateGroup[];
/** 该租户该月的人工裁决(SN → 记录),由 review-store 载入,用于回填人工准确率 */
reviews: Map<string, ReviewRecord>;
/** 该租户的人工裁决集合,由 review-store 载入 */
reviews: ReviewsMap | Map<string, ReviewRecord>;
/** 人工审核准确率(%):仅当本地裁决覆盖样本时有值 */
humanAccuracy?: number;
/** 章节数据完备性标记,渲染时逐节如实写入 */
@@ -88,34 +89,93 @@ export type ReportData = {
};
export type CollectOptions = {
month: string; // YYYY-MM
startDate?: string;
endDate?: string;
month?: string; // 兼容旧单月参数
corp: { id: string; name: string };
/** 用于拉明细分块的上限,防御性封顶 */
/** 单据模板白名单,未指定则拉取全量模板 */
templates?: string[];
/** 用于拉明细分块的上限(可选,未指定时默认拉取指定时间区间全量单据,最大安全上限 100000) */
maxRuns?: number;
/** 是否载入本地人工裁决(默认载入);关掉则 humanAccuracy 恒为不可得 */
loadReviews?: boolean;
};
function monthRange(month: string): { startDate: string; endDate: string; startIsoDate: string; endIsoDate: string } {
const [y, m] = month.split("-").map(Number);
if (!y || !m) throw new Error(`Invalid month "${month}", expected YYYY-MM`);
const start = Date.UTC(y, m - 1, 1);
const end = Date.UTC(y, m, 1) - 1;
const lastDay = new Date(y, m, 0).getDate();
const pad = (n: number) => String(n).padStart(2, "0");
const startIsoDate = `${y}-${pad(m)}-01`;
const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`;
return { startDate: String(start), endDate: String(end), startIsoDate, endIsoDate };
export function resolveReportPeriod(options: {
startDate?: string | number;
endDate?: string | number;
month?: string;
}): {
startDate: string;
endDate: string;
startIsoDate: string;
endIsoDate: string;
startBeijingIso: string;
endBeijingIso: string;
periodLabel: string;
month?: string;
} {
if (options.startDate && options.endDate) {
const sStr = String(options.startDate).slice(0, 10);
const eStr = String(options.endDate).slice(0, 10);
const sTs = Date.parse(`${sStr}T00:00:00+08:00`);
const eTs = Date.parse(`${eStr}T23:59:59.999+08:00`);
if (Number.isNaN(sTs) || Number.isNaN(eTs)) {
throw validationError(`Invalid date range: "${options.startDate}" to "${options.endDate}"`);
}
const startIsoDate = sStr;
const endIsoDate = eStr;
const startBeijingIso = formatBeijingIso(sTs);
const endBeijingIso = formatBeijingIso(eTs);
const periodLabel = `${startIsoDate} ~ ${endIsoDate}`;
const month = startIsoDate.slice(0, 7) === endIsoDate.slice(0, 7) ? startIsoDate.slice(0, 7) : `${startIsoDate.slice(0, 7)}~${endIsoDate.slice(0, 7)}`;
return {
startDate: String(sTs),
endDate: String(eTs),
startIsoDate,
endIsoDate,
startBeijingIso,
endBeijingIso,
periodLabel,
month
};
}
if (options.month) {
const [y, m] = options.month.split("-").map(Number);
if (!y || !m) throw validationError(`Invalid month "${options.month}", expected YYYY-MM`);
const start = Date.UTC(y, m - 1, 1);
const end = Date.UTC(y, m, 1) - 1;
const lastDay = new Date(y, m, 0).getDate();
const pad = (n: number) => String(n).padStart(2, "0");
const startIsoDate = `${y}-${pad(m)}-01`;
const endIsoDate = `${y}-${pad(m)}-${pad(lastDay)}`;
return {
startDate: String(start),
endDate: String(end),
startIsoDate,
endIsoDate,
startBeijingIso: formatBeijingIso(start),
endBeijingIso: formatBeijingIso(end),
periodLabel: `${startIsoDate} ~ ${endIsoDate}`,
month: options.month
};
}
throw validationError("缺少统计起止时间:请指定 startDate 和 endDate(如 2026-08-12 至 2026-09-18)");
}
/** 默认明细拉取安全兜底上限(100,000 笔),未指定限制时默认拉取全区间单据 */
export const DEFAULT_MAX_REPORT_RUNS = 100_000;
/** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */
export async function collectReportData(
client: KyInstance,
demands: Set<ReportDemand>,
options: CollectOptions
): Promise<ReportData> {
const range = monthRange(options.month);
const maxRuns = Math.min(options.maxRuns ?? 500, 500);
const range = resolveReportPeriod(options);
const maxRuns = options.maxRuns ?? DEFAULT_MAX_REPORT_RUNS;
const fetched: Record<ReportDemand, boolean> = {
performance: false,
riskStats: false,
@@ -126,17 +186,18 @@ export async function collectReportData(
const data: ReportData = {
period: {
start: formatBeijingIso(Number(range.startDate)),
end: formatBeijingIso(Number(range.endDate)),
month: options.month
start: range.startBeijingIso,
end: range.endBeijingIso,
label: range.periodLabel,
month: range.month
},
corp: options.corp,
fetched,
blocks: [],
templateGroups: [],
reviews: options.loadReviews === false
? new Map()
: loadReviews(options.corp.id, options.month),
? new ReviewsMap()
: loadReviews(options.corp.id),
notes: {
humanAccuracyAvailable: false,
failureRateAvailable: false,
@@ -196,20 +257,22 @@ export async function collectReportData(
let offset = 0;
try {
while (runs.length < maxRuns) {
const fetchLimit = Math.min(100, maxRuns - runs.length);
const page = await api.listApprovalRuns(client, {
offset,
limit: 100,
limit: fetchLimit,
startDate: range.startDate,
endDate: range.endDate
});
const records = page.records ?? [];
if (!records.length) break;
runs.push(...records);
const toTake = records.slice(0, maxRuns - runs.length);
runs.push(...toTake);
offset += records.length;
if (records.length < 100) break;
if (records.length < fetchLimit || runs.length >= maxRuns) break;
}
const blocks: ReportBlock[] = runs.map((record) => {
let blocks: ReportBlock[] = runs.map((record) => {
const summary = summarizeLocal(record);
const aiPolarity = polarityOf(summary.aiDecision);
const humanPolarity = polarityOf(summary.humanResult);
@@ -236,6 +299,12 @@ export async function collectReportData(
conditions: summary.conditions
};
});
if (options.templates && options.templates.length > 0) {
const allowed = new Set(options.templates.map((t) => t.trim()));
blocks = blocks.filter((b) => allowed.has(b.template));
}
data.blocks = blocks;
fetched.blocks = true;
} catch {
@@ -244,102 +313,151 @@ export async function collectReportData(
}
data.notes.failureRateAvailable = data.performance !== undefined;
data.notes.mismatchCategoriesAvailable = false; // 失准原因分类默认无上游字段,除非本地复核已全覆盖
data.notes.mismatchCategoriesAvailable = false;
// 4. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率与复核后的 AI 准确率
if (data.reviews.size > 0) {
let reviewed = 0;
let diverged = 0;
let aiRight = 0;
let humanRight = 0;
let completedCount = 0;
let completedReviewed = 0;
let completedAiRight = 0;
let completedHumanRight = 0;
for (const block of data.blocks) {
if (block.agreement !== "unknown") completedCount += 1;
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;
if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1;
if (block.agreement !== "unknown") {
completedReviewed += 1;
if (review.verdict === "human_correct" || review.verdict === "both_correct") completedHumanRight += 1;
if (review.verdict === "ai_correct" || review.verdict === "both_correct") completedAiRight += 1;
}
}
}
if (reviewed > 0) {
const useCompletedScope = completedCount > 0 && completedReviewed >= completedCount;
const denom = useCompletedScope ? completedReviewed : reviewed;
const hRight = useCompletedScope ? completedHumanRight : humanRight;
const aRight = useCompletedScope ? completedAiRight : aiRight;
data.notes.reviewedCount = denom;
data.notes.divergedCount = diverged;
data.humanAccuracy = Number(((hRight / denom) * 100).toFixed(2));
data.notes.humanAccuracyAvailable = true;
// 当本地复核已覆盖全量完结单据时,统一以完结复核口径(D1 + D2 + D4)更新 AI 准确率与有效样本量,消除“分歧单两头扣分”
if (useCompletedScope && data.performance) {
data.performance.approvalCount = denom;
data.performance.accuracy = Number(((aRight / denom) * 100).toFixed(2));
data.notes.mismatchCategoriesAvailable = true;
}
}
}
// 5. 分模板统计(在 review 挂载后聚合,以便携带分模板的 AI/人工准确率与同意:驳回比例)
if (demands.has("templateGroups") && data.blocks.length > 0) {
const byTemplate = new Map<string, ReportTemplateGroup>();
for (const block of data.blocks) {
const key = block.template || "未标注模板";
const group = byTemplate.get(key) ?? {
template: key,
total: 0,
agreed: 0,
diverged: 0,
evaluated: 0,
aiCorrect: 0,
humanCorrect: 0,
bothCorrect: 0,
humanPass: 0,
humanReject: 0
};
group.total += 1;
if (block.agreement === "agreed") group.agreed += 1;
if (block.agreement === "diverged") group.diverged += 1;
if (block.agreement !== "unknown") {
group.evaluated = (group.evaluated ?? 0) + 1;
const hp = polarityOf(block.humanResult);
if (hp === "pass") group.humanPass = (group.humanPass ?? 0) + 1;
if (hp === "reject") group.humanReject = (group.humanReject ?? 0) + 1;
const v = block.verdict;
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
group.bothCorrect = (group.bothCorrect ?? 0) + 1;
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
} else if (v === "human_correct") {
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
}
}
byTemplate.set(key, group);
}
data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total);
fetched.templateGroups = true;
}
// 4. 人工裁决回填与分模板指标聚合(支持 recordId 精确匹配与 sn 业务自然键匹配)
const metrics = populateReviewsAndMetrics(data.blocks, data.reviews, data.performance, data.notes);
data.templateGroups = metrics.templateGroups;
data.humanAccuracy = metrics.humanAccuracy;
data.notes = metrics.notes;
data.performance = metrics.performance;
fetched.templateGroups = demands.has("templateGroups") && data.templateGroups.length > 0;
return data;
}
/**
* 核心指标计算引擎:基于单据明细 blocks 与复核裁决集合 reviews,纯计算聚合各模板与全局指标。
* 供 collectReportData(云端拉取)与 loadReportDataFromLedger(本地 Excel/CSV 驱动)共享 100% 一致口径。
*/
export function populateReviewsAndMetrics(
blocks: ReportBlock[],
reviews: ReviewsMap | Map<string, ReviewRecord>,
initialPerformance?: ReportData["performance"],
initialNotes?: Partial<ReportData["notes"]>
): {
templateGroups: ReportTemplateGroup[];
humanAccuracy?: number;
notes: ReportData["notes"];
performance?: ReportData["performance"];
} {
const notes: ReportData["notes"] = {
humanAccuracyAvailable: false,
failureRateAvailable: initialPerformance !== undefined,
mismatchCategoriesAvailable: false,
...initialNotes
};
let performance = initialPerformance;
let reviewed = 0;
let diverged = 0;
let aiRight = 0;
let humanRight = 0;
let completedCount = 0;
for (const block of blocks) {
if (block.agreement !== "unknown") completedCount += 1;
const review = reviews instanceof ReviewsMap
? reviews.get({ recordId: block.recordId, sn: block.sn })
: 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;
} else if (block.verdict) {
reviewed += 1;
if (block.agreement === "diverged") diverged += 1;
}
if (block.agreement !== "unknown") {
const v = block.verdict;
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
aiRight += 1;
humanRight += 1;
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
aiRight += 1;
} else if (v === "human_correct") {
humanRight += 1;
}
}
}
let humanAccuracy: number | undefined;
if (reviewed > 0) {
const divergedCount = blocks.filter((b) => b.agreement === "diverged").length;
const unreviewedDiverged = blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
notes.reviewedCount = completedCount > 0 ? completedCount : reviewed;
notes.divergedCount = divergedCount;
if (completedCount > 0) {
humanAccuracy = Number(((humanRight / completedCount) * 100).toFixed(2));
notes.humanAccuracyAvailable = true;
if (!performance && unreviewedDiverged === 0) {
performance = {
approvalCount: completedCount,
accuracy: Number(((aiRight / completedCount) * 100).toFixed(2)),
sankey: { nodes: [], links: [] }
};
}
if (unreviewedDiverged === 0 && performance) {
performance.approvalCount = completedCount;
performance.accuracy = Number(((aiRight / completedCount) * 100).toFixed(2));
notes.mismatchCategoriesAvailable = true;
}
}
}
const byTemplate = new Map<string, ReportTemplateGroup>();
for (const block of blocks) {
const key = block.template || "未标注模板";
const group = byTemplate.get(key) ?? {
template: key,
total: 0,
agreed: 0,
diverged: 0,
evaluated: 0,
aiCorrect: 0,
humanCorrect: 0,
bothCorrect: 0,
humanPass: 0,
humanReject: 0
};
group.total += 1;
if (block.agreement === "agreed") group.agreed += 1;
if (block.agreement === "diverged") group.diverged += 1;
if (block.agreement !== "unknown") {
group.evaluated = (group.evaluated ?? 0) + 1;
const hp = polarityOf(block.humanResult);
if (hp === "pass") group.humanPass = (group.humanPass ?? 0) + 1;
if (hp === "reject") group.humanReject = (group.humanReject ?? 0) + 1;
const v = block.verdict;
if (v === "both_correct" || (!v && block.agreement === "agreed")) {
group.bothCorrect = (group.bothCorrect ?? 0) + 1;
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
} else if (v === "ai_correct" || (!v && block.agreement === "diverged")) {
group.aiCorrect = (group.aiCorrect ?? 0) + 1;
} else if (v === "human_correct") {
group.humanCorrect = (group.humanCorrect ?? 0) + 1;
}
}
byTemplate.set(key, group);
}
const templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total);
return {
templateGroups,
humanAccuracy,
notes,
performance
};
}
/** 局部摘要:避免依赖 capabilities/helpers 的深耦合,只取报告需要的字段。 */
function summarizeLocal(record: ApprovalRun): {
id: string;
@@ -358,20 +476,25 @@ function summarizeLocal(record: ApprovalRun): {
} {
const result = (record.result ?? {}) as Record<string, unknown>;
const document = (record.document ?? {}) as Record<string, unknown>;
const manual = record.manualApprovalRecord as Record<string, unknown> | undefined;
const manual =
(record.manualApprovalRecord as Record<string, unknown> | undefined) ??
(result.manualApprovalRecord as Record<string, unknown> | undefined) ??
(document.manualApprovalRecord as Record<string, unknown> | undefined);
const manualApproval = result.manualApproval as Record<string, unknown> | undefined;
const pipelineData = record.pipelineData as Record<string, unknown> | undefined;
const aiDecision =
firstString(result.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.decision) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.result);
firstString(manualApproval?.decision) ??
firstString(manualApproval?.result);
const manualStatusObj = manual?.status as { label?: string; type?: string } | undefined;
const humanResult =
firstString(manualStatusObj?.label) ??
firstString(manualStatusObj?.type) ??
firstString(result.humanResult) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.humanResult) ??
firstString(record.pipelineData && (record.pipelineData as Record<string, unknown>).humanResult);
firstString(manualApproval?.humanResult) ??
firstString(pipelineData?.humanResult);
const fields = (document.fields as Array<{ key?: string; label?: string; value?: unknown }> | undefined) ?? [];
const tField = fields.find(
@@ -396,6 +519,24 @@ function summarizeLocal(record: ApprovalRun): {
const createdAt = record.createdAt ? formatBeijingIso(Number(record.createdAt) || Date.parse(String(record.createdAt))).slice(0, 19).replace("T", " ") : undefined;
const durationSeconds = typeof record.durationMs === "number" ? Number((record.durationMs / 1000).toFixed(1)) : undefined;
const humanComment =
firstString(manual?.rejectComment) ??
firstString(manual?.comment) ??
firstString(manual?.comments) ??
firstString(manual?.opinion) ??
firstString(manual?.approvalComment) ??
firstString(manualApproval?.comment) ??
firstString(manualApproval?.rejectComment) ??
firstString(manualApproval?.opinion) ??
firstString(result.humanComment) ??
firstString(pipelineData?.rejectComment) ??
firstString(pipelineData?.comment);
const aiSummary =
firstString(result.summary) ??
firstString(result.reason) ??
firstString(result.explanation);
return {
id: record.id,
sn: record.sourceDocumentSN,
@@ -407,11 +548,8 @@ function summarizeLocal(record: ApprovalRun): {
durationSeconds,
aiDecision,
humanResult,
aiSummary: firstString(result.summary),
humanComment:
firstString(manual?.rejectComment) ??
firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
firstString(result.humanComment),
aiSummary,
humanComment,
conditions: extractTriggeredConditions(result)
};
}
+41 -17
View File
@@ -1,18 +1,26 @@
import type { KyInstance } from "ky";
import { collectReportData } from "./collect.js";
import { collectReportData, polarityOf } from "./collect.js";
import { loadReportDataFromLedger } from "../export/ledger.js";
import { renderVennAccuracySvg } from "../charts/venn.js";
export type MonthlyReportDataOptions = {
month: string; // YYYY-MM
export type ReportDataOptions = {
startDate?: string;
endDate?: string;
month?: string;
corp: { id: string; name: string };
templates?: string[];
ledgerPath?: string;
maxRuns?: number;
};
export type MonthlyReportDataOptions = ReportDataOptions;
export type MonthlyReportDataResult = {
period: {
month: string;
start: string;
end: string;
label?: string;
month?: string;
};
corp: {
id: string;
@@ -100,12 +108,12 @@ export type MonthlyReportDataResult = {
};
/**
* 获取月度报告的纯结构化数据包。
* 获取审核报告的纯结构化数据包。
* 不依赖 Markdown 模板,输出统一可直接消费的业务指标、分模板统计、待裁决分歧单据池与维恩图资产。
*/
export async function getMonthlyReportData(
client: KyInstance,
options: MonthlyReportDataOptions
options: ReportDataOptions
): Promise<MonthlyReportDataResult> {
const demands = new Set<"performance" | "riskStats" | "riskDetails" | "blocks" | "templateGroups">([
"performance",
@@ -115,11 +123,16 @@ export async function getMonthlyReportData(
"templateGroups"
]);
const data = await collectReportData(client, demands, {
month: options.month,
corp: options.corp,
maxRuns: options.maxRuns
});
const data = options.ledgerPath
? await loadReportDataFromLedger(options.ledgerPath, { corp: options.corp })
: await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
const total = data.performance?.approvalCount || data.blocks.length || 0;
const rawAiAcc = data.performance?.accuracy;
@@ -192,7 +205,7 @@ export async function getMonthlyReportData(
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 groupAiAccuracy = 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;
@@ -206,7 +219,7 @@ export async function getMonthlyReportData(
evaluated,
agreed: g.agreed,
diverged: g.diverged,
aiAccuracy,
aiAccuracy: groupAiAccuracy,
humanAccuracy,
automationRate,
humanPassRatio,
@@ -262,7 +275,8 @@ export async function getMonthlyReportData(
period: {
month: data.period.month,
start: data.period.start.slice(0, 10),
end: data.period.end.slice(0, 10)
end: data.period.end.slice(0, 10),
label: data.period.label
},
corp: data.corp,
metrics: {
@@ -272,7 +286,15 @@ export async function getMonthlyReportData(
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
riskInterceptCount:
data.performance?.riskCount ??
data.blocks.filter(
(b) =>
b.agreement === "diverged" &&
b.verdict === "ai_correct" &&
polarityOf(b.aiDecision) === "reject" &&
polarityOf(b.humanResult) === "pass"
).length
},
reviews: {
available: data.notes.humanAccuracyAvailable,
@@ -296,10 +318,12 @@ export async function getMonthlyReportData(
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}`,
reviewSet: `seal-use report review set --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> --corp ${data.corp.id}`,
reviewList: `seal-use report review list --corp ${data.corp.id}`,
validate: "seal-use report validate <报告文件.md>",
render: "seal-use report render <报告文件.md> --out build/<报告文件>"
}
};
}
export const getReportData = getMonthlyReportData;
+43 -16
View File
@@ -9,11 +9,17 @@ import { collectReportData, type ReportData } from "./collect.js";
import { renderMonthlyReport, type RenderOptions } from "./render.js";
import { renderVennAccuracySvg } from "../charts/venn.js";
import { buildReportLedgerCsv, buildReportLedgerXlsx } from "../export/ledger.js";
import { buildReportLedgerCsv, buildReportLedgerXlsx, loadReportDataFromLedger } from "../export/ledger.js";
export type MonthlyReportOptions = {
month: string; // YYYY-MM
export type ReportOptions = {
startDate?: string;
endDate?: string;
month?: string; // 兼容旧单月参数
corp: { id: string; name: string };
/** 单据模板白名单列表(可选,未指定则拉取全量模板) */
templates?: string[];
/** 外部直接传入已编辑的台账文件路径 (.xlsx 或 .csv),传入时直接以该台账为唯一事实源,不再查询云端 */
ledgerPath?: string;
/** 模板路径;缺省用仓内内置 monthly.md,随二进制内嵌 */
templatePath?: string;
reportId?: string;
@@ -22,8 +28,11 @@ export type MonthlyReportOptions = {
allowUnreviewed?: boolean;
};
export type MonthlyReportOptions = ReportOptions;
export type MonthlyReportResult = {
month: string;
period: ReportData["period"];
month?: string;
corpId: string;
reportId: string;
templatePath: string;
@@ -45,10 +54,10 @@ export type MonthlyReportResult = {
};
};
/** 一次调用产出填充好的月度报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
/** 一次调用产出填充好的审核报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
export async function buildMonthlyReport(
client: KyInstance,
options: MonthlyReportOptions
options: ReportOptions
): Promise<MonthlyReportResult> {
const templatePath = options.templatePath
? resolve(options.templatePath)
@@ -62,12 +71,20 @@ export async function buildMonthlyReport(
const template = options.templatePath ? readFileSync(templatePath, "utf8") : BUILTIN_MONTHLY_TEMPLATE;
const plans = describeTemplate(template);
const demands = new Set(plans.flatMap((plan) => plan.demands));
const data = await collectReportData(client, demands, {
month: options.month,
corp: options.corp,
maxRuns: options.maxRuns
});
let data: ReportData;
if (options.ledgerPath) {
data = await loadReportDataFromLedger(options.ledgerPath, { corp: options.corp });
} else {
const demands = new Set(plans.flatMap((plan) => plan.demands));
data = await collectReportData(client, demands, {
startDate: options.startDate,
endDate: options.endDate,
month: options.month,
corp: options.corp,
templates: options.templates,
maxRuns: options.maxRuns
});
}
const unreviewedDiverged = data.blocks.filter(
(b) => b.agreement === "diverged" && !b.verdict
@@ -75,17 +92,24 @@ export async function buildMonthlyReport(
if (unreviewedDiverged.length > 0 && !options.allowUnreviewed) {
const snList = unreviewedDiverged.slice(0, 3).map((b) => b.sn).join(", ");
const more = unreviewedDiverged.length > 3 ? ` 等共 ${unreviewedDiverged.length} 笔` : "";
const periodArg = options.startDate && options.endDate
? `--start-date ${options.startDate} --end-date ${options.endDate}`
: options.month ? `--month ${options.month}` : "";
const tip = options.ledgerPath
? `请在台账文件(${options.ledgerPath})中为这些单据填写“复核定性裁决”列(如:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),或直接剔除不需要的单据/模板行。`
: `请先执行 'seal-use report ledger ${periodArg} --corp ${options.corp.id}' 导出台账并在 Excel 中裁决,或通过 'seal-use report review set' 录入裁决结论。`;
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` +
`${tip}\n` +
`(若确需生成未定稿的内部预览草稿,请添加 --allow-unreviewed 参数继续)。`,
1,
`seal-use report data --month ${options.month} --corp ${options.corp.id}`
options.ledgerPath ? undefined : `seal-use report data ${periodArg} --corp ${options.corp.id}`
);
}
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-${randomBytes(3).toString("hex").toUpperCase()}`;
const dateTag = (data.period.month || `${data.period.start.slice(0, 10)}_${data.period.end.slice(0, 10)}`).replace(/[-~]/g, "");
const reportId = options.reportId ?? `RPT-${dateTag}-${randomBytes(3).toString("hex").toUpperCase()}`;
const renderOptions: RenderOptions = {
reportId,
corpName: options.corp.name
@@ -124,7 +148,8 @@ export async function buildMonthlyReport(
}
return {
month: options.month,
period: data.period,
month: data.period.month,
corpId: options.corp.id,
reportId,
templatePath,
@@ -143,3 +168,5 @@ export async function buildMonthlyReport(
}
};
}
export const buildReport = buildMonthlyReport;
+12 -7
View File
@@ -1,6 +1,7 @@
import { formatBeijingIso } from "../../../../core/config/timestamps.js";
import type { ReportData, ReportBlock } from "./collect.js";
import type { SectionPlan } from "./describe.js";
import { ReviewsMap } from "./review-store.js";
export type RenderOptions = {
/** 报告编号;未给则按 RPT-<YYYYMM>-<6位随机> 生成 */
@@ -55,7 +56,8 @@ export function renderMonthlyReport(
plans: SectionPlan[],
options: RenderOptions = {}
): string {
const reportId = options.reportId ?? `RPT-${data.period.month.replace("-", "")}-${randomSuffix()}`;
const dateTag = (data.period.month || `${data.period.start.slice(0, 10)}_${data.period.end.slice(0, 10)}`).replace(/[-~]/g, "");
const reportId = options.reportId ?? `RPT-${dateTag}-${randomSuffix()}`;
const corpName = options.corpName ?? data.corp.name;
const generatedAt = options.generatedAt ?? beijingToday();
const ctx: FillContext = { reportId, corpName, generatedAt, reportStatus: options.reportStatus };
@@ -103,7 +105,7 @@ export function renderMonthlyReport(
// 报告信息表:统计期间与生成日期按真实统计口径补齐
result = result.replace(
/(\| 统计期间 \| )[^\n|]+/,
`$1${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`
`$1${data.period.label || `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`}`
);
result = result.replace(/(\| 生成日期 \| )[^\n|]+/, `$1${ctx.generatedAt}`);
return result;
@@ -111,11 +113,14 @@ export function renderMonthlyReport(
function fillInline(text: string, data: ReportData, ctx: FillContext): string {
let result = text;
const monthNum = parseInt(data.period.month.slice(5), 10);
const monthNum = data.period.month ? parseInt(data.period.month.slice(5), 10) : NaN;
const monthStr = Number.isFinite(monthNum) ? `${monthNum}月` : "";
if (monthStr) {
result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】${monthStr}AI审核准确率报告`);
result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, `《${monthStr}单据审批质量审计报告_全量看板.xlsx》`);
} else {
result = result.replace(/# 【[^】]+】\d+月AI审核准确率报告/, `# 【${ctx.corpName}】AI审核准确率报告`);
result = result.replace(/《\d+月单据审批质量审计报告_全量看板\.xlsx》/g, "《单据审批质量审计报告_全量看板.xlsx》");
}
result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`);
result = result.replaceAll("模板企业", ctx.corpName);
@@ -440,7 +445,7 @@ function replacementRows(
: (dist ? `(${dist})` : "");
return [
["数据来源", "客户授权的已完成历史审批单据"],
["统计期间", `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)} 期间单据`],
["统计期间", `${data.period.label || `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`} 期间单据`],
["单据模板", data.templateGroups.length
? `涵盖 ${data.templateGroups.map((g) => g.template).slice(0, 6).join("、")} 等 **${data.templateGroups.length} 类**业务单据模板`
: "*(单据模板分布待取数)*"],
@@ -548,11 +553,11 @@ function replacementRows(
if (!diverged.length) return null;
return diverged.map((block) => {
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 category = isAiRight ? "**依规正确(计入 D4)**" : "**AI 判定误判(不计入分子)**";
const reviewNote = block.reviewNote ?? (data.reviews instanceof ReviewsMap ? data.reviews.get({ recordId: block.recordId, sn: block.sn }) : (data.reviews as Map<string, any>).get(block.sn))?.note;
const conclusion = (!isAiRight && reviewNote)
? `${reviewNote}(AI原判:${block.aiSummary || "—"})`
: (block.aiSummary || reviewNote || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报"));
: (block.aiSummary || reviewNote || (isAiRight ? "人工复核确认依规拦截风险" : "AI 误报/误判"));
return [
block.sn,
block.template || "—",
@@ -6,7 +6,14 @@ import { describeTemplate } from "./describe.js";
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 {
buildReportLedgerCsv,
buildReportLedgerXlsx,
loadReportDataFromLedger,
parseVerdictText,
formatVerdict,
formatAiOpinion
} from "../export/ledger.js";
import { getMonthlyReportData } from "./data.js";
import { buildMonthlyReport } from "./monthly.js";
@@ -339,13 +346,72 @@ describe("review store + human accuracy join", () => {
expect(data.humanAccuracy).toBe(50);
const csv = buildReportLedgerCsv(data);
expect(csv.startsWith("\uFEFF单据编号(SN),单据模板")).toBe(true);
expect(csv.startsWith("\uFEFF审核ID(recordId),单据编号(SN),单据模板")).toBe(true);
expect(csv).toContain("对公付款");
expect(csv).toContain("张山具体的报销单标题A");
const xlsx = await buildReportLedgerXlsx(data);
expect(xlsx.byteLength).toBeGreaterThan(1000);
});
test("fetches over 500 records across pages without being clamped when maxRuns is omitted", async () => {
// 模拟服务端有 650 条记录(7 页:6 页 100 条 + 1 页 50 条)
const totalRecords = 650;
const fakeClient = {
get: async (_url: string, opts?: { searchParams?: URLSearchParams }) => {
const offset = Number(opts?.searchParams?.get("offset") ?? 0);
const limit = Number(opts?.searchParams?.get("limit") ?? 100);
const count = Math.max(0, Math.min(limit, totalRecords - offset));
const records = Array.from({ length: count }, (_, i) => ({
id: `run-${offset + i}`,
sourceDocumentSN: `SN-${offset + i}`,
result: { decision: "同意" },
pipelineData: { humanResult: "同意" }
}));
return {
json: async () => ({ data: { records, total: totalRecords } })
};
}
} as never;
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
month: "2026-08",
corp: { id: "corp-a", name: "A" }
});
// 验证突破了原本的 500 条限制,全部 650 条完整拉出
expect(data.blocks).toHaveLength(650);
});
test("respects explicit maxRuns limit and slices precisely across pages", async () => {
const totalRecords = 500;
const fakeClient = {
get: async (_url: string, opts?: { searchParams?: URLSearchParams }) => {
const offset = Number(opts?.searchParams?.get("offset") ?? 0);
const limit = Number(opts?.searchParams?.get("limit") ?? 100);
const count = Math.max(0, Math.min(limit, totalRecords - offset));
const records = Array.from({ length: count }, (_, i) => ({
id: `run-${offset + i}`,
sourceDocumentSN: `SN-${offset + i}`,
result: { decision: "同意" },
pipelineData: { humanResult: "同意" }
}));
return {
json: async () => ({ data: { records, total: totalRecords } })
};
}
} as never;
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
month: "2026-08",
corp: { id: "corp-a", name: "A" },
maxRuns: 150
});
expect(data.blocks).toHaveLength(150);
expect(data.blocks[0]?.sn).toBe("SN-0");
expect(data.blocks[149]?.sn).toBe("SN-149");
});
});
describe("getMonthlyReportData", () => {
@@ -426,6 +492,43 @@ describe("getMonthlyReportData", () => {
expect(data.nextActions.validate).toBe("seal-use report validate <报告文件.md>");
});
test("riskInterceptCount fallback counts AI reject + human pass + ai_correct and excludes AI pass + human reject", async () => {
// 模拟离线台账场景(无 cloud performance.riskCount)
// DEMO-007: AI 驳回,人工同意,裁决 ai_correct → 真正的风险拦截!
// DEMO-008: AI 同意,人工驳回,裁决 ai_correct → 依规放行正确,非风险拦截!
writeReview("corp-test", { sn: "DEMO-007", month: "2026-08", verdict: "ai_correct" });
writeReview("corp-test", { sn: "DEMO-008", month: "2026-08", verdict: "ai_correct" });
const runs = [
{
id: "r1",
sourceDocumentSN: "DEMO-007",
result: { decision: "驳回", summary: "发票违规超标" },
pipelineData: { humanResult: "同意" },
document: { fields: [{ key: "specificationId", value: "一般费用报销" }] }
},
{
id: "r2",
sourceDocumentSN: "DEMO-008",
result: { decision: "同意", summary: "合规放行" },
pipelineData: { humanResult: "驳回" },
document: { fields: [{ key: "specificationId", value: "一般费用报销" }] }
}
];
const fakeClient = {
get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) })
} as never;
const data = await getMonthlyReportData(fakeClient, {
month: "2026-08",
corp: { id: "corp-test", name: "测试企业" }
});
// 只有 DEMO-007 算入风险拦截,DEMO-008 属于依规放行不虚增风险拦截
expect(data.metrics.riskInterceptCount).toBe(1);
});
test("blocks buildMonthlyReport when unreviewed diverged runs exist", async () => {
const runs = [
{ id: "r1", sourceDocumentSN: "DIVERGED-01", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } }
@@ -490,6 +593,279 @@ describe("getMonthlyReportData", () => {
expect(out).toContain("华南大区");
expect(out).toContain("缺失要求凭证");
});
test("supports custom date range (e.g. 2026-08-12 to 2026-09-18) without month constraint", async () => {
let calledStart = "";
let calledEnd = "";
const fakeClient = {
get: async (_url: string, opts?: { searchParams?: URLSearchParams }) => {
calledStart = opts?.searchParams?.get("startDate") ?? "";
calledEnd = opts?.searchParams?.get("endDate") ?? "";
return { json: async () => ({ data: { records: [], total: 0 } }) };
},
post: async () => ({ json: async () => ({ data: { approvalCount: 0 } }) })
} as never;
const res = await getMonthlyReportData(fakeClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
corp: { id: "corp-a", name: "A企业" }
});
expect(res.period.start).toBe("2026-08-12");
expect(res.period.end).toBe("2026-09-18");
expect(res.period.label).toBe("2026-08-12 ~ 2026-09-18");
expect(calledStart).toBe(String(Date.parse("2026-08-12T00:00:00+08:00")));
expect(calledEnd).toBe(String(Date.parse("2026-09-18T23:59:59.999+08:00")));
});
test("filters data.blocks and templateGroups by template whitelist at the source", async () => {
const runs = [
{ id: "r1", sourceDocumentSN: "SN1", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "差旅报销" }] } },
{ id: "r2", sourceDocumentSN: "SN2", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "采购付款" }] } },
{ id: "r3", sourceDocumentSN: "SN3", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "车辆津贴" }] } },
{ id: "r4", sourceDocumentSN: "SN4", result: { decision: "同意" }, pipelineData: { humanResult: "同意" }, document: { fields: [{ key: "specificationId", value: "招待费报销" }] } }
];
const fakeClient = {
get: async () => ({ json: async () => ({ data: { records: runs, total: 4 } }) }),
post: async () => ({ json: async () => ({ data: { approvalCount: 4 } }) })
} as never;
// 虽拉到 4 种模板,但指定只保留 2 种
const res = await getMonthlyReportData(fakeClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
corp: { id: "corp-a", name: "A企业" },
templates: ["差旅报销", "采购付款"]
});
expect(res.templateGroups).toHaveLength(2);
expect(res.templateGroups.map((g) => g.template).sort()).toEqual(["差旅报销", "采购付款"]);
expect(res.agreedRunsSample.every((b) => ["差旅报销", "采购付款"].includes(b.template))).toBe(true);
});
test("reviews by recordId specifically overrides an agreed block to AI correct and decrements human accuracy", async () => {
// 写入裁决:针对 r1 这条运行记录(AI 驳回,人工也驳回),指名道姓覆盖为 AI 正确、人工失准
writeReview("corp-override", {
recordId: "run-both-reject-1",
sn: "SN-AGREED",
verdict: "ai_correct",
note: "人工随口驳回,AI 依据合规条款驳回正确"
});
const runs = [
{
id: "run-both-reject-1",
sourceDocumentSN: "SN-AGREED",
result: { decision: "驳回", summary: "缺少合规凭证" },
pipelineData: { humanResult: "驳回" },
document: { fields: [{ key: "specificationId", value: "费用报销" }] }
},
{
id: "run-both-approve-2",
sourceDocumentSN: "SN-AGREED-2",
result: { decision: "同意" },
pipelineData: { humanResult: "同意" },
document: { fields: [{ key: "specificationId", value: "费用报销" }] }
}
];
const fakeClient = {
get: async () => ({ json: async () => ({ data: { records: runs, total: 2 } }) }),
post: async () => ({ json: async () => ({ data: { approvalCount: 2 } }) })
} as never;
const res = await getMonthlyReportData(fakeClient, {
startDate: "2026-08-12",
endDate: "2026-09-18",
corp: { id: "corp-override", name: "覆写测试企业" }
});
// run-both-reject-1 原本双方一致驳回,被覆盖为 ai_correct:
// AI 准确率 = 2/2 = 100%
// 人工准确率 = 1/2 = 50%
expect(res.metrics.aiAccuracy).toBe(100);
expect(res.metrics.humanAccuracy).toBe(50);
const group = res.templateGroups[0]!;
expect(group.aiAccuracy).toBe(100);
expect(group.humanAccuracy).toBe(50);
});
test("wording distinction: formatVerdict and parseVerdictText clearly separate document validity from audit correctness", () => {
expect(
formatVerdict({
sn: "1",
template: "T",
agreement: "diverged",
aiDecision: "驳回",
humanResult: "同意",
aiSummary: "超标",
humanComment: undefined,
verdict: "ai_correct"
})
).toBe("AI 判断正确 / 人工判断错误");
expect(
formatVerdict({
sn: "2",
template: "T",
agreement: "diverged",
aiDecision: "驳回",
humanResult: "同意",
aiSummary: "误报",
humanComment: undefined,
verdict: "human_correct"
})
).toBe("人工判断正确 / AI 判定误判");
expect(
formatVerdict({
sn: "3",
template: "T",
agreement: "agreed",
aiDecision: "同意",
humanResult: "同意",
aiSummary: "合规",
humanComment: undefined,
verdict: "both_correct"
})
).toBe("双方判断均正确");
expect(
formatVerdict({
sn: "4",
template: "T",
agreement: "agreed",
aiDecision: "同意",
humanResult: "同意",
aiSummary: "漏检",
humanComment: undefined,
verdict: "both_wrong"
})
).toBe("双方判定均误判");
expect(parseVerdictText("AI正确")).toBe("ai_correct");
expect(parseVerdictText("AI判断正确 / 人工判断错误")).toBe("ai_correct");
expect(parseVerdictText("人工错误")).toBe("ai_correct");
expect(parseVerdictText("人工合理")).toBe("human_correct");
expect(parseVerdictText("人工判断正确 / AI 判定误判")).toBe("human_correct");
expect(parseVerdictText("AI误判")).toBe("human_correct");
expect(parseVerdictText("双方判断均正确")).toBe("both_correct");
expect(parseVerdictText("双方判定均误判")).toBe("both_wrong");
expect(parseVerdictText("存疑待定")).toBe("undecided");
});
test("formatAiOpinion combines summary and triggered conditions into full audit rationale", () => {
const text = formatAiOpinion({
aiSummary: "发票金额超标",
conditions: ["发票金额超出城市报销标准(350元)", "缺少同行人名单"]
});
expect(text).toContain("发票金额超标");
expect(text).toContain("【触发违规/风险项】1. 发票金额超出城市报销标准(350元); 2. 缺少同行人名单");
});
test("ledger round-trip: buildReportLedgerXlsx exports full comments and loadReportDataFromLedger respects Agent edits", async () => {
const tmp = mkdtempSync(join(tmpdir(), "seal-ledger-test-"));
try {
const data = sampleData({
blocks: [
{
recordId: "rec-001",
sn: "SN-001",
template: "差旅报销",
title: "北京出差差旅",
submitter: "张三",
department: "技术部",
createdAt: "2026-08-15 10:00:00",
aiDecision: "驳回",
humanResult: "同意",
agreement: "diverged",
aiSummary: "住宿超标",
conditions: ["超标50元"],
humanComment: "领导特批放行",
verdict: undefined
},
{
recordId: "rec-002",
sn: "SN-002",
template: "采购付款",
title: "办公用品采购",
submitter: "李四",
department: "行政部",
createdAt: "2026-08-18 14:00:00",
aiDecision: "同意",
humanResult: "同意",
agreement: "agreed",
aiSummary: "凭证齐全",
humanComment: "核验无误",
verdict: undefined
}
]
});
// 1. 导出 Excel 台账
const buffer = await buildReportLedgerXlsx(data);
const xlsxFile = join(tmp, "台账.xlsx");
await Bun.write(xlsxFile, buffer);
// 2. 逆向加载台账
const loaded = await loadReportDataFromLedger(xlsxFile);
expect(loaded.blocks).toHaveLength(2);
expect(loaded.blocks[0]!.sn).toBe("SN-001");
expect(loaded.blocks[0]!.humanComment).toBe("领导特批放行");
expect(loaded.blocks[0]!.aiSummary).toContain("超标50元");
// 3. 模拟 Agent 自由编辑台账:直接在 CSV/Excel 中完成裁决,并剔除掉采购付款模板(仅留差旅报销)
const editedCsv = [
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
'rec-001,SN-001,差旅报销,北京出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,领导特批放行,分歧,AI判断正确 / 人工判断错误,王总监,特批应走线下签批流程不应线上直接放行,12'
].join("\n");
const csvFile = join(tmp, "台账-edited.csv");
await Bun.write(csvFile, editedCsv);
const loadedEdited = await loadReportDataFromLedger(csvFile);
// 严格尊重 Agent 裁剪:只剩下 1 笔差旅报销,完全没有采购付款
expect(loadedEdited.blocks).toHaveLength(1);
expect(loadedEdited.templateGroups).toHaveLength(1);
expect(loadedEdited.templateGroups[0]!.template).toBe("差旅报销");
// 权威识别已填写的裁决
expect(loadedEdited.blocks[0]!.verdict).toBe("ai_correct");
expect(loadedEdited.blocks[0]!.reviewedBy).toBe("王总监");
expect(loadedEdited.humanAccuracy).toBe(0); // 人工判断错误
expect(loadedEdited.performance?.accuracy).toBe(100); // AI判断正确
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
test("buildMonthlyReport driven directly by --ledger skips remote fetch and validates in-place", async () => {
const tmp = mkdtempSync(join(tmpdir(), "seal-report-ledger-test-"));
try {
// 构造已由 Agent 完成复核的台账
const csv = [
"审核ID(recordId),单据编号(SN),单据模板,单据标题/事由,提交人,费用承担部门,跑批时间,AI审批决策,AI审核完整意见与违规详情,人工审批结论,人工审批批注/驳回说明,人机一致性,复核定性裁决,复核人,复核批注说明,审批耗时(秒)",
'rec-001,SN-001,差旅报销,北京出差,张三,技术部,2026-08-15 10:00:00,驳回,超标,同意,无批注,分歧,AI判断正确 / 人工判断错误,评审专家,AI依据城市差旅标准拦截正确,12',
'rec-002,SN-002,差旅报销,上海出差,李四,市场部,2026-08-16 11:00:00,同意,合规,同意,通过,一致,双方判断均正确,评审专家,无误,8'
].join("\n");
const csvFile = join(tmp, "台账.csv");
await Bun.write(csvFile, csv);
const fakeClient = {} as never;
const report = await buildMonthlyReport(fakeClient, {
ledgerPath: csvFile,
corp: { id: "corp-ledger", name: "台账驱动测试企业" }
});
expect(report.content).toBeTruthy();
expect(report.notes.humanAccuracyAvailable).toBe(true);
expect(report.dynamicAssets?.["assets/图1-准确率对比.svg"]).toBeTruthy();
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
+120 -47
View File
@@ -1,16 +1,16 @@
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { validationError } from "../../../../core/errors.js";
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
/**
* 人工裁决的本地持久化(JSONL,按 租户 × 月份 分片)。
* 人工裁决的本地持久化(JSONL,按租户分片,支持 recordId 与 SN 双键检索)。
*
* 为什么是 JSONL:跨周 review 天然是**追加**场景——每审一批写一批,不整文件重写,
* 为什么是 JSONL:跨周期 review 天然是追加写入场景——每审一批写一批,不整文件重写,
* 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。
* 为什么按租户+月份分片:租户隔离、月度报告天然对应一个文件、文件不会无限膨胀。
*
* 一条记录 = 一个 SN 在某个月被人工裁决一次的结果。同一 SN 重复裁决时,
* 以**最后一条**为准(loadReviews 归并时后写覆盖先写)。
* 为什么按租户分片:租户天然数据隔离。
* 标识符规则:优先以具体审核运行 ID(recordId)精确定位单次审核;同时支持单据 SN 作为业务自然键。
* 后写覆盖先写。
*/
/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */
@@ -22,10 +22,12 @@ export type ReviewVerdict =
| "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判)
export type ReviewRecord = {
/** 合思/源单据 SN(裁决的自然键) */
sn: string;
/** 裁决所属统计月 YYYY-MM(与 report monthly 的 month 对齐) */
month: string;
/** 审核运行记录 ID(精确裁决键) */
recordId?: string;
/** 合思/源单据 SN(业务自然键) */
sn?: string;
/** 裁决所属统计周期或月份(可选留痕) */
month?: string;
verdict: ReviewVerdict;
/** 裁决人(可选,留痕用) */
reviewedBy?: string;
@@ -43,33 +45,76 @@ const VERDICTS: ReadonlySet<string> = new Set([
"undecided"
]);
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
export class ReviewsMap {
readonly byRecordId = new Map<string, ReviewRecord>();
readonly bySn = new Map<string, ReviewRecord>();
readonly records: ReviewRecord[] = [];
set(record: ReviewRecord): this;
set(key: string, record: ReviewRecord): this;
set(keyOrRecord: string | ReviewRecord, maybeRecord?: ReviewRecord): this {
const record = typeof keyOrRecord === "string" ? maybeRecord! : keyOrRecord;
const key = typeof keyOrRecord === "string" ? keyOrRecord : record.recordId ?? record.sn ?? "";
this.records.push(record);
if (record.recordId) this.byRecordId.set(record.recordId, record);
if (record.sn) this.bySn.set(record.sn, record);
if (!record.recordId && !record.sn && key) {
this.bySn.set(key, record);
}
return this;
}
get(key: { recordId?: string; sn?: string } | string | undefined): ReviewRecord | undefined {
if (!key) return undefined;
if (typeof key === "string") {
return this.byRecordId.get(key) ?? this.bySn.get(key);
}
if (key.recordId && this.byRecordId.has(key.recordId)) {
return this.byRecordId.get(key.recordId);
}
if (key.sn && this.bySn.has(key.sn)) {
return this.bySn.get(key.sn);
}
return undefined;
}
has(key: { recordId?: string; sn?: string } | string): boolean {
return this.get(key) !== undefined;
}
get size(): number {
return new Set([...this.byRecordId.keys(), ...this.bySn.keys()]).size;
}
values(): IterableIterator<ReviewRecord> {
const unique = new Map<string, ReviewRecord>();
for (const r of this.records) {
const id = r.recordId ? `rec:${r.recordId}` : `sn:${r.sn}`;
unique.set(id, r);
}
return unique.values();
}
}
const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR";
/** 裁决存储根目录:~/.config/seal-use/state/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
/** 裁决存储根目录:~/.config/seal-use/state/reviews/。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
export function reviewsDir(): string {
const configured = process.env[REVIEWS_DIR_ENV]?.trim();
if (configured) return configured;
return join(SEAL_STATE_DIR, "reviews");
}
/** 分片路径:<reviewsDir>/<corpId>-<YYYY-MM>.jsonl */
export function reviewFilePath(corpId: string, month: string): string {
return join(reviewsDir(), `${sanitizeCorpId(corpId)}-${month}.jsonl`);
/** 分片路径:<reviewsDir>/<corpId>[-<scope>].jsonl */
export function reviewFilePath(corpId: string, scope?: string): string {
const cleanCorp = sanitizeCorpId(corpId);
return scope ? join(reviewsDir(), `${cleanCorp}-${scope}.jsonl`) : join(reviewsDir(), `${cleanCorp}.jsonl`);
}
function sanitizeCorpId(corpId: string): string {
// corpId 可能含路径分隔符等非法字符,压成安全片段
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
function assertMonth(month: string): void {
if (!/^\d{4}-\d{2}$/.test(month)) {
throw validationError(`Invalid month "${month}", expected YYYY-MM`);
}
}
function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
if (!VERDICTS.has(verdict)) {
throw validationError(
@@ -79,59 +124,87 @@ function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
}
/**
* 读取某租户某月的全部裁决,按 SN 归并(同一 SN 后写覆盖先写)。文件不存在返回空 Map。
* 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片;否则读取该租户的主文件与各分片文件。按后写覆盖先写。
*/
export function loadReviews(corpId: string, month: string): Map<string, ReviewRecord> {
assertMonth(month);
const filePath = reviewFilePath(corpId, month);
const reviews = new Map<string, ReviewRecord>();
if (!existsSync(filePath)) return reviews;
export function loadReviews(corpId: string, scope?: string): ReviewsMap {
const reviews = new ReviewsMap();
const sanitized = sanitizeCorpId(corpId);
const targetDir = reviewsDir();
if (!existsSync(targetDir)) return reviews;
const lines = readFileSync(filePath, "utf8").split("\n");
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
const targetFile = reviewFilePath(corpId, scope);
const filesToRead: string[] = [];
if (scope) {
if (existsSync(targetFile)) filesToRead.push(targetFile);
} else {
if (existsSync(targetFile)) filesToRead.push(targetFile);
try {
const parsed = JSON.parse(trimmed) as ReviewRecord;
if (parsed && typeof parsed.sn === "string" && VERDICTS.has(parsed.verdict)) {
reviews.set(parsed.sn, parsed); // 后写覆盖先写
const allFiles = readdirSync(targetDir);
for (const f of allFiles) {
if (f.startsWith(`${sanitized}-`) && f.endsWith(".jsonl")) {
filesToRead.push(join(targetDir, f));
}
}
} catch {
// 跳过损坏行:单行坏数据不应让整个裁决集不可读
}
} catch {}
}
for (const filePath of filesToRead) {
try {
const lines = readFileSync(filePath, "utf8").split("\n");
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
const parsed = JSON.parse(trimmed) as ReviewRecord;
if (parsed && (parsed.recordId || parsed.sn) && VERDICTS.has(parsed.verdict)) {
reviews.set(parsed.recordId ?? parsed.sn!, parsed);
}
} catch {}
}
} catch {}
}
return reviews;
}
/**
* 追加写一条裁决到磁盘(真正的落盘入口)。corpId 由调用方显式传入(sn 与租户无关,文件按租户分片)。
* 追加写一条裁决到磁盘(支持 recordId 与 sn)。
*/
export function writeReview(
corpId: string,
input: {
sn: string;
month: string;
recordId?: string;
sn?: string;
month?: string;
scope?: string;
verdict: string;
reviewedBy?: string;
note?: string;
recordedAt?: string;
}
): ReviewRecord {
const recordId = input.recordId?.trim();
const sn = input.sn?.trim();
if (!sn) throw validationError("sn is required for a review record");
assertMonth(input.month);
if (!recordId && !sn) {
throw validationError("At least one of recordId or sn is required for a review record");
}
if (input.month && !/^\d{4}-\d{2}$/.test(input.month)) {
throw validationError(`Invalid month "${input.month}", expected YYYY-MM`);
}
assertVerdict(input.verdict);
const record: ReviewRecord = {
sn,
month: input.month,
...(recordId ? { recordId } : {}),
...(sn ? { sn } : {}),
...(input.month ? { month: input.month } : {}),
verdict: input.verdict,
...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}),
...(input.note?.trim() ? { note: input.note.trim() } : {}),
recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ")
};
const filePath = reviewFilePath(corpId, input.month);
const scope = input.scope ?? input.month;
const filePath = reviewFilePath(corpId, scope);
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
return record;
+10 -2
View File
@@ -1,6 +1,6 @@
# Report templates
月度 AI 审核准确率报告的模板与配套资产(供 `seal-use report monthly` 消费)。
企业 AI 审核报告(验收、上线、周期审计)的模板与配套资产(供 `seal-use report generate` / `report monthly` 消费)。
| 文件 | 用途 |
| --- | --- |
@@ -14,11 +14,19 @@
默认模板和配图由本仓库 Git 管理(位于 `src/domains/seal/reports/templates/`),构建时直接内嵌进二进制;无需外置模板目录或已安装的 Skill。模板修改通过 PR 合入,再随构建/发版分发。`--template` 仅用于显式覆盖。
```bash
seal-use report monthly --month 2026-08 --corp <corpId> --out 报告.md
# 模式 A (首选·Excel 台账自由裁量驱动):
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out 台账.xlsx
seal-use report generate --ledger 台账.xlsx --corp <corpId> --out 报告.md
# 模式 B (直接时间周期/月度提数驱动):
seal-use report generate --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out 报告.md
# 校验与多端渲染:
seal-use report validate 报告.md
seal-use report render 报告.md --out build/报告
```
`monthly --out` 保存 Markdown 和同目录的 `<报告名>.assets/` 配图目录,返回文件路径、数据缺口与后续命令;不指定 `--out` 时继续返回 `content`。自定义模板的本地配图也一并复制。已有文件默认拒绝覆盖,显式 `--overwrite` 才允许替换。通用 `--output-file` 仍只保存 JSON,与 `--out` 不同。
校验、渲染仅操作本地文件,不需要 `--corp`、登录或网络取数。校验失败返回结构化问题、退出码 1,并阻止导出。渲染成功返回产物路径、格式和字节数;HTML 内嵌本地配图及公式资源,可随产物移动。默认产出 HTML、完整长图 PNG、A4 分页 PDF;`--format html|png|pdf` 可选格式,PNG/PDF 同时保留 HTML。
@@ -161,7 +161,7 @@ export function validateReportDocument(file: string): ReportValidation {
if (detail) {
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 missed = detail.rows.filter((row) => row.cells.length > 4 && (row.cells[4]!.includes("失准") || 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} 行`)
+1 -1
View File
@@ -13,7 +13,7 @@ Release. On WSL, `seal-use-release-sync.timer` polls the latest release every
The first archive becomes available as soon as it is present in Gitea.
The remaining assets retry idempotently on later timer runs if needed.
Promotion only mirrors release assets; it does not update package-manager repositories.
Promotion mirrors all published release assets as well as Git repository branches and tags to the local Gitea mirror. It does not update package-manager repositories.
The WSL worker uses its local mihomo listener at `http://127.0.0.1:7897` only
for GitHub. It does not enable TUN or expose a LAN listener. Local Gitea
+34
View File
@@ -16,6 +16,7 @@ NO_PROXY_LIST="${NO_PROXY:-127.0.0.1,localhost,100.82.151.105,git.ying-qing.cn}"
GITHUB_TOKEN_FILE="${SEAL_USE_GITHUB_TOKEN_FILE:-$HOME/.config/seal-use/github-token}"
GITEA_TOKEN_FILE="${SEAL_USE_GITEA_TOKEN_FILE:-$HOME/.config/seal-use/gitea-token}"
LOCK_FILE="${SEAL_USE_SYNC_LOCK_FILE:-$STATE_DIR/sync.lock}"
GIT_MIRROR_DIR="${SEAL_USE_SYNC_GIT_MIRROR_DIR:-$STATE_DIR/repo.git}"
mkdir -p "$STATE_DIR" "$WORK_DIR"
exec 9>"$LOCK_FILE"
@@ -67,6 +68,39 @@ gitea_curl() {
return "$rc"
}
sync_git_repo() {
log "synchronizing Git repository refs (branches and tags) to Gitea"
if [ ! -d "$GIT_MIRROR_DIR" ]; then
log "initializing bare mirror repository at $GIT_MIRROR_DIR"
mkdir -p "$GIT_MIRROR_DIR"
git init --bare "$GIT_MIRROR_DIR" >/dev/null
fi
local gh_url="https://github.com/${GITHUB_REPO}.git"
local gitea_url="${GITEA_BASE}/${GITEA_REPO}.git"
log "fetching latest refs from GitHub ($GITHUB_REPO)"
if ! env HTTP_PROXY="$PROXY_URL" HTTPS_PROXY="$PROXY_URL" ALL_PROXY= NO_PROXY="$NO_PROXY_LIST" \
git --git-dir="$GIT_MIRROR_DIR" \
-c http.extraHeader="Authorization: Bearer ${GITHUB_TOKEN}" \
fetch --prune --tags --force "$gh_url" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >&2; then
log "warning: failed to fetch Git refs from GitHub; skipping Git mirror push this run"
return 0
fi
log "mirroring refs to Gitea ($GITEA_REPO)"
if ! env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY NO_PROXY="$NO_PROXY_LIST" \
git --git-dir="$GIT_MIRROR_DIR" \
-c http.extraHeader="Authorization: token ${GITEA_TOKEN}" \
push --prune --tags --force "$gitea_url" '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*' >&2; then
log "warning: failed to push Git refs to Gitea; will retry next timer"
return 0
fi
log "Git repository refs successfully synchronized to Gitea"
}
sync_git_repo
release_json=$(github_curl -H 'Accept: application/vnd.github+json' \
"https://api.github.com/repos/$GITHUB_REPO/releases/latest") || die "cannot read latest GitHub release"
tag=$(jq -r '.tag_name // empty' <<< "$release_json")
@@ -1,5 +1,5 @@
[Unit]
Description=Promote GitHub releases to Gitea
Description=Promote GitHub releases and mirror repository refs to Gitea
After=network-online.target docker.service mihomo.service
Wants=network-online.target
Requires=mihomo.service