Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bea6a9cf4e | ||
|
|
1209164cc8 | ||
|
|
b18f1d772b | ||
|
|
c6bd113fff | ||
|
|
077ecb050c | ||
|
|
64680cd4a0 | ||
|
|
135cd84e69 |
No files matched your search
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.9",
|
||||
"version": "0.11.10",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -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
|
||||
@@ -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`.
|
||||
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.9",
|
||||
"version": "0.11.10",
|
||||
"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
-11
@@ -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 "";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,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}`);
|
||||
@@ -141,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;
|
||||
@@ -170,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
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.9: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.10: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.9
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.9)
|
||||
version: 0.11.10
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.10)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -140,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。
|
||||
|
||||
@@ -166,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`。
|
||||
@@ -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% 逐字吻合
|
||||
@@ -63,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>]`.
|
||||
|
||||
@@ -1,178 +1,366 @@
|
||||
# 月度 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** | `单据编号 (SN)` | 单据业务自然键(如 `CL2608001`) | 业务单据主键 |
|
||||
| **B** | `审核记录ID (recordId)` | 单次 AI 审核运行的唯一主键,用于版本精确锁定 | 审批运行记录主键 |
|
||||
| **C** | `单据模板` | 单据所属表单类型(如 `差旅报销单`) | 业务单据属性 |
|
||||
| **D** | `提交人` | 单据发起员工姓名或工号 | 业务单据属性 |
|
||||
| **E** | `单据金额` | 单据报销或付款总金额(元) | 业务单据属性 |
|
||||
| **F** | `单据创建时间` | 单据在源系统创建的北京时间 | 业务单据属性 |
|
||||
| **G** | `AI审核时间` | AI 模型执行审核的北京时间 | 审批运行属性 |
|
||||
| **H** | `AI审核结论` | AI 给出的审批决策:`通过` / `驳回` | 审批运行结果 |
|
||||
| **I** | `AI审核完整意见与违规详情` | **核心证据列**:包含 AI 综合评语、触发的具体规则编号及违规条款细则 | 聚合 summary + conditions |
|
||||
| **J** | `人工审批操作` | 人工审批人实际操作:`同意` / `驳回` / `终止` | 人工操作记录 |
|
||||
| **K** | `人工审批批注/驳回说明` | **核心证据列**:人工审批人在系统后台填写的真实审批意见与驳回理由 | 提取 manualComment / rejectComment |
|
||||
| **L** | `结论是否同向` | `同向一致` 或 `存在分歧` | 逻辑比较 H 与 J |
|
||||
| **M** | `复核定性裁决` | **自由裁量填报列**:Agent/用户填写的定性结论(支持中英文口语化识别) | 人工/Agent 填报 |
|
||||
| **N** | `裁决依据说明` | 针对复核裁决填写的定性分析、归因说明与管理整改建议 | 人工/Agent 填报 |
|
||||
| **O** | `AI审核详情直达链接` | 带免密凭证的 Seal AI 审核页直达 URL | 动态生成穿透链接 |
|
||||
| **P** | `合思原单据直达链接` | 合思/易快报 Web 页面原单据直达 URL | 提取自 sourceExtendData |
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> **中文口语化智能解析**:在「复核定性裁决」列中,用户不仅可以填写规范枚举(`ai_correct`),也可以自由填写中文口语:“`AI判断正确 / 人工判断错误`”、“`AI正确`”、“`人工正确`”、“`AI误判`”、“`双方正确`”等,CLI 在加载时均能百分之百精准识别映射。
|
||||
|
||||
---
|
||||
|
||||
## 五、端到端人机协同作业流程
|
||||
|
||||
### 模式 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 中自由裁量,增删模板行并填入裁决;
|
||||
|
||||
# 步骤 3:严格以修改后的台账为唯一事实源,出具报告草稿
|
||||
seal-use report generate --ledger reports/明细台账.xlsx --corp <corpId> --out reports/审核报告.md
|
||||
|
||||
# 步骤 4:严格门禁校验(必须通过)
|
||||
seal-use report validate reports/审核报告.md
|
||||
|
||||
# 步骤 5:本地全格式编译渲染
|
||||
seal-use report render reports/审核报告.md --out build/审核报告/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 第一步:获取结构化数据包与模板骨架
|
||||
### 模式 B:CLI 命令行实时研讨驱动
|
||||
|
||||
1. **拉取当月纯结构化业务数据包 (JSON)**:
|
||||
适合小批量单据核查或纯命令行快速批处理:
|
||||
|
||||
1. **提取结构化数据包**:
|
||||
```bash
|
||||
seal-use report data --month <YYYY-MM> --corp <corpId>
|
||||
seal-use report data --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId>
|
||||
```
|
||||
*输出说明:返回纯 JSON,包含全月样本量、AI 准确率、采纳率、平均耗时、公式代入值、分模板统计、TOP 风险标签,以及全量分歧单据池(`divergedRuns`)。*
|
||||
返回纯 JSON 数据,包含全周期样本量、AI 准确率、采纳率、平均耗时、分模板统计及全量分歧单池(`divergedRuns`)。
|
||||
|
||||
2. **导出纯净标准模板骨架**:
|
||||
```bash
|
||||
seal-use report template --out reports/<企业名>-<YYYYMM>.md
|
||||
```
|
||||
|
||||
3. **动态生成准确率维恩图**:
|
||||
```bash
|
||||
mkdir -p reports/<企业名>-<YYYYMM>.assets
|
||||
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 第二步:分歧单据人机复核研讨 (Diverged Runs Review)
|
||||
|
||||
当 `reviews.divergedUnreviewedCount > 0` 时,存在 AI 放行但人工驳回、或 AI 驳回但人工放行的分歧单据。Agent 需主动在聊天中向用户汇总呈报并征询裁决。
|
||||
|
||||
**双链穿透规范 (Dual-Link Fast Traversal)**:
|
||||
呈报给用户裁决的每笔典型案例,Agent **必须同时生成并附带双端直达链接**,严禁让用户盲猜或手动去系统里翻查单据:
|
||||
- **🔗 Seal AI 审核页直达**:调用 `seal-use approval-runs url --sn <SN> --auto-login` 生成带临时免密凭证的直达链接,一键跳转到 Seal AI 查看完整判定快照、引用规则、卡口明细与 LLM 推理过程;
|
||||
- **📑 合思/易快报原单据直达**:调用 `hose-use bill link <SN>` 或从运行记录 `sourceExtendData.hosecloudViewUrl` 提取原单据 Web 链接,一键直达合思原单据查看发票原件影像、业务附件与人工审批操作历史。
|
||||
|
||||
1. **结构化向用户呈现典型案例**:
|
||||
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 聊天窗口设计,方便管理层在手机上顺滑滑动审阅。
|
||||
+175
-24
@@ -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,24 +95,113 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
|
||||
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
|
||||
}
|
||||
|
||||
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
|
||||
/** `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...>] [--max-runs <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: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
});
|
||||
}
|
||||
|
||||
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...>] [--max-runs <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,
|
||||
templates,
|
||||
ledgerPath,
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
}
|
||||
);
|
||||
@@ -103,17 +209,38 @@ export async function handleReportCommand(
|
||||
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...>] [--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),
|
||||
@@ -140,33 +267,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 +328,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.`);
|
||||
}
|
||||
+53
-23
@@ -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...>] [--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: "--max-runs <n>", description: "Cap approval-run fetch, default 500" }
|
||||
],
|
||||
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...>] [--max-runs <n>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ 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: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
],
|
||||
description: "Template-free data pack for Agent authoring: returns performance metrics, formula fractions, template groups, top risk tags, diverged runs with exact triggered conditions, and reviews."
|
||||
},
|
||||
{
|
||||
name: "template",
|
||||
summary: "Dump or save the built-in monthly report Markdown template",
|
||||
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-...>] [--max-runs <n>] [--allow-unreviewed] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" },
|
||||
{ flag: "--out <file>", description: "Save Markdown plus local images beside the report; stdout stays JSON (without the content field)" },
|
||||
{ flag: "--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: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<dateTag>-<random>" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" },
|
||||
{ flag: "--allow-unreviewed", description: "Bypass pre-flight adjudication gate to generate draft when unreviewed diverged runs exist" }
|
||||
],
|
||||
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
|
||||
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."
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+2
-2
@@ -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",
|
||||
@@ -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",
|
||||
|
||||
+10
-1
@@ -225,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;
|
||||
}
|
||||
|
||||
@@ -1263,6 +1263,18 @@ 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("差旅报销");
|
||||
});
|
||||
|
||||
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
|
||||
|
||||
@@ -7,17 +7,31 @@ 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()
|
||||
@@ -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,12 +75,29 @@ 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()
|
||||
@@ -63,11 +108,22 @@ export const reportCapabilities = [
|
||||
}),
|
||||
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
|
||||
})
|
||||
|
||||
@@ -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 模板
|
||||
|
||||
@@ -211,5 +211,44 @@ describe("local report CLI", () => {
|
||||
expect(existsSync(join(packageDir, "报告.md.assets", "1-chart-4x.png"))).toBe(true);
|
||||
expect(existsSync(join(packageDir, "报告.md.assets", "chart-4x.png"))).toBe(true);
|
||||
}, 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 +1,2 @@
|
||||
export * from "./files.js";
|
||||
export * from "./ledger.js";
|
||||
@@ -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 表格提取构建台账
|
||||
*/
|
||||
|
||||
@@ -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,24 +89,80 @@ export type ReportData = {
|
||||
};
|
||||
|
||||
export type CollectOptions = {
|
||||
month: string; // YYYY-MM
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
month?: string; // 兼容旧单月参数
|
||||
corp: { id: string; name: string };
|
||||
/** 单据模板白名单,未指定则拉取全量模板 */
|
||||
templates?: string[];
|
||||
/** 用于拉明细分块的上限,防御性封顶 */
|
||||
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)");
|
||||
}
|
||||
|
||||
/** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */
|
||||
@@ -114,7 +171,7 @@ export async function collectReportData(
|
||||
demands: Set<ReportDemand>,
|
||||
options: CollectOptions
|
||||
): Promise<ReportData> {
|
||||
const range = monthRange(options.month);
|
||||
const range = resolveReportPeriod(options);
|
||||
const maxRuns = Math.min(options.maxRuns ?? 500, 500);
|
||||
const fetched: Record<ReportDemand, boolean> = {
|
||||
performance: false,
|
||||
@@ -126,17 +183,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,
|
||||
@@ -209,7 +267,7 @@ export async function collectReportData(
|
||||
if (records.length < 100) 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 +294,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 +308,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 +471,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 +514,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 +543,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)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { collectReportData } 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: {
|
||||
@@ -296,10 +310,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;
|
||||
@@ -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;
|
||||
@@ -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,7 +346,7 @@ 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");
|
||||
|
||||
@@ -490,6 +497,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 });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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} 行`)
|
||||
|
||||
Reference in new issue
Block a user