Compare commits

...
37 Commits
Author SHA1 Message Date
yunyingk 45a576a18e Merge pull request #98 from yunyingk/codex/release-v0.10.20
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.20: Tenant doctor, rule regression matrix, and usage ranking
2026-09-13 23:40:42 +08:00
gitea d7aaf15c12 Release v0.10.20: Tenant doctor, rule regression matrix, and usage ranking 2026-09-13 23:38:35 +08:00
yunyingk 73f9bd4a5d Merge pull request #97 from yunyingk/codex/ai-native-test-regression-and-doctor
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add tenant contract doctor probe and automated regression test matrix
2026-09-13 22:09:49 +08:00
gitea 6c69dd78de Isolate regression test CLI unit tests with mock environment 2026-09-13 22:08:26 +08:00
gitea 733ede97d9 Add tenant contract doctor probe and automated regression test matrix 2026-09-13 22:02:39 +08:00
yunyingk 15e7044387 Merge pull request #96 from yunyingk/codex/corps-list-usage-ranking-and-limit
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add 7-day usage ranking and default 10-item limit to corps list
2026-09-13 21:55:06 +08:00
gitea fe325bc913 Add 7-day usage ranking and default 10-item limit to corps list 2026-09-13 21:51:55 +08:00
yunyingk e76af01480 Merge pull request #95 from yunyingk/codex/release-v0.10.19
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.19: Smart insights suite & Excel export, official rule linter isolation, and unified Seal HTTP client
2026-09-13 13:44:21 +08:00
gitea 41cc1ba8c5 Release v0.10.19: Smart insights suite & Excel export, official rule linter isolation, and unified Seal HTTP client 2026-09-13 13:43:18 +08:00
yunyingk 1b502b98b1 Merge pull request #94 from yunyingk/codex/unified-seal-http-client
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Unify Seal backend HTTP requests through client factory and propagate custom headers
2026-09-13 00:51:25 +08:00
gitea 61905b3d59 Unify Seal backend HTTP requests through client factory and propagate custom headers 2026-09-13 00:48:10 +08:00
yunyingk 4395d8a1aa Merge pull request #93 from yunyingk/codex/linter-official-isolation
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add official rule linter isolation, plaintext sync, and strict validator
2026-09-13 00:09:46 +08:00
gitea 9f413eb1e8 Add official rule linter isolation, plaintext sync, and strict validator 2026-09-13 00:07:48 +08:00
yunyingk 8ca1cca6ec Merge pull request #92 from yunyingk/codex/insight-excel-export
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add smart insights excel report export command and tool
2026-09-12 23:50:11 +08:00
gitea 780c4d0812 Add smart insights excel report export command and tool 2026-09-12 23:48:57 +08:00
yunyingk be26248b6b Merge pull request #91 from yunyingk/codex/smart-insights-full-suite
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add smart insights risks, performance, and analyze commands
2026-09-12 23:29:26 +08:00
gitea c929fd002c Add smart insights risks, performance, and analyze commands 2026-09-12 23:27:13 +08:00
yunyingk 1baeb3722f Merge pull request #90 from yunyingk/codex/webhook-replay-to-test
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add formal to test enterprise webhook replay capability
2026-09-12 23:19:16 +08:00
gitea 4bcb935d15 Clarify replay policies in skills and support force in replay-test 2026-09-12 23:12:51 +08:00
gitea 35a3374d27 Refine error hint for unbound corps in replay-test 2026-09-12 23:01:06 +08:00
gitea 35720fa36a Add formal to test enterprise webhook replay capability 2026-09-12 22:54:45 +08:00
yunyingk ce066206df Merge pull request #89 from yunyingk/codex/release-v0.10.18
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.18: System diagnostic doctor and intelligent fuzzy search
2026-09-11 18:13:40 +08:00
gitea f4929abb0c Release v0.10.18: System diagnostic doctor and intelligent fuzzy search 2026-09-11 18:12:36 +08:00
yunyingk f67e689463 Merge pull request #88 from yunyingk/codex/doctor-system-diagnostic
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add doctor command for read-only system diagnostic and embedded guide
2026-09-11 17:58:00 +08:00
gitea 4c8389bf0c Add doctor command for read-only system diagnostic and embedded guide
Embed system architecture and 10-tier directory specifications directly into the binary with zero disk footprint.
2026-09-11 17:57:41 +08:00
yunyingk 76d288b882 Merge pull request #87 from yunyingk/codex/corps-soft-fuzzy-search
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add intelligent soft fuzzy search to corps search command
2026-09-11 17:44:25 +08:00
gitea b6aa4efd09 Add intelligent soft fuzzy search to corps search command
Support Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance, and --strict exact mode fallback.
2026-09-11 17:43:58 +08:00
yunyingk 5a5c0c11a9 Merge pull request #86 from yunyingk/codex/enforce-corps-search-in-skill
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Enforce corps search over corps list when enterprise is known or hinted
2026-09-11 17:33:23 +08:00
gitea acdc2a301a Enforce corps search over corps list when enterprise is known or hinted 2026-09-11 17:32:19 +08:00
yunyingk 34c4ecfbaa Merge pull request #85 from yunyingk/codex/skill-cleanup-and-corps-search
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Enhance enterprise discovery and unify skill documentation
2026-09-11 17:27:57 +08:00
gitea 1297c56f3d Add corps get and search commands, audit and unify skill documentation 2026-09-11 17:26:57 +08:00
yunyingk 9ba049a85f Merge pull request #84 from yunyingk/codex/approval-runs-url-sso
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add approval run URL command with security-guarded SSO option
2026-09-11 17:15:12 +08:00
gitea bdb4a1dd9e Add approval run URL command with security-guarded SSO option 2026-09-11 17:13:35 +08:00
yunyingk d672ba447e Merge pull request #83 from yunyingk/codex/webhook-replay
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add approval run to webhook replay capability
2026-09-11 16:49:46 +08:00
gitea 770fd9d672 Add approval run to webhook replay capability 2026-09-11 16:48:43 +08:00
yunyingk 4adecf990d Merge pull request #82 from yunyingk/codex/corp-command-alias
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add corp compatibility alias for corps commands
2026-09-11 16:43:28 +08:00
gitea 8b2230e0aa Add corp compatibility alias for corps commands 2026-09-11 16:42:30 +08:00
62 changed files with 9034 additions and 453 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.17",
"version": "0.10.20",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+57
View File
@@ -7,6 +7,63 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.10.20] - 2026-09-13
### Added & Enhanced
- **Tenant Contract Doctor Probe (`seal-use doctor tenant`)**:
- Implemented 100% deterministic tenant contract probe `seal-use doctor tenant [--corp <corpId>] [--quiet]` with structured JSON on `stdout` and terminal diagnostic dashboard on `stderr`.
- Probes 5 critical tenant contracts: identity & admin roles (`getMe`), AI approval billing quota & point deductions (`getBillingStatus` balance, deductionAmount, estimated runs), active rules & unreleased draft safety (`listApprovalRules`), webhook integration readiness, and test environment pairing.
- **Automated Rule Regression Test Matrix (`seal-use test regression`)**:
- Added `seal-use test regression` (alias: `seal-use corps regression`) to run automated regression testing across paired production and test environments.
- Enforced Hard Red Line 1: strictly prohibits running directly against pure production enterprises; target MUST be a paired test enterprise (`environment: "test"`).
- Enforced Hard Red Line 2: pre-flight checks AI approval balance (`balance >= samples * deductionAmount`), blocking immediately if points are insufficient.
- Implemented outbound HTTPS polling for test run completion, eliminating any inbound port or public IP requirement in NAT/VPN corporate networks.
- Compares production vs. test decisions (`APPROVE`, `REJECT`, `MANUAL`, `ERROR`), detects decision flips, computes concordance rate, determines `safeToPublish`, and supports `--dry-run` and `--fail-on-flips` for CI/CD safety gates.
- **7-Day Enterprise Usage Tracking & List Optimization (`seal-use corps list`)**:
- Added enterprise usage tracker (`src/core/stats/usage-tracker.ts`) recording 7-day call frequencies and recency.
- `seal-use corps list` defaults to displaying the top 10 most frequently used enterprises in the last 7 days to prevent list dump spam for large enterprise catalogs.
- Supported `--all` to display the entire enterprise list, and `--sort <usage|name|id>` to customize ordering.
- **Skill & Guidance Modernization**:
- Synchronized `skills/seal-use/SKILL.md` and reference documentation with `doctor tenant`, `test regression`, and usage ranking.
## [0.10.19] - 2026-09-13
### Added & Enhanced
- **Smart Insights Full Suite & Multi-Sheet Excel Export**:
- Implemented complete Smart Insights analytics suite: `seal-use analytics risks` (risk tag frequency and interception trends), `seal-use analytics performance` (Sankey review throughput, adoption rates, avg duration), `seal-use analytics analyze` (on-demand rule/document risk diagnosis), and `seal-use analytics insight` (overview metrics).
- Added multi-sheet Excel export CLI `seal-use analytics export` (aliases: `report`, `download`) and MCP tool `seal_insight_export`. Generates styled `.xlsx` reports with 3 dedicated sheets (`审核效能与决策流向`, `Top 风险标签分析`, `风险单据穿透明细`), supporting `--downloads` to system downloads directory and custom `--out` paths.
- **Rule Linter Directory Restructuring & Official Isolation**:
- Structured `~/.config/seal-use/linters/` for custom user linters while isolating official linters in `~/.config/seal-use/linters/official/`.
- Added plaintext sync mechanism (`syncOfficialLinters`): writes human- and Agent-readable TypeScript source files (`builtin.ts` and `strict.ts`) with types and JSDoc, overwrites user modifications unconditionally, and prunes rogue files in `official/`.
- Added `strict.ts` linter: enforces quantitative boundaries (amounts, days, strict limits), catches vague expressions, errors on hanging exceptions without required notes/attachments, and enforces concrete approver roles.
- Added CLI `seal-use rules linters` to inspect available linters and updated `seal-use doctor paths` with `officialLintersDir`.
- **Unified Seal Backend HTTP Client & Enterprise Context Injection**:
- Enhanced `createSealClientForUrl` in `src/core/http/factory.ts` with optional Bearer token support, allowing pre-auth endpoints (SSO exchange, OAuth2 session, whoami) to use the unified client without sending invalid Authorization headers.
- Unified all outbound Seal backend HTTP calls across `auth.ts`, `corps.ts`, `hose.ts`, `api.ts`, `webhook-replay.ts`, and `material-pack/service.ts`, ensuring enterprise custom headers (`corp.seal.headers`) and gateway cookies (`corp.seal.cookies`) are consistently injected.
- **Test Enterprise Webhook Replay & Auto-Pairing**:
- Added `seal-use corps replay-test <sn>` and `seal-use webhook replay` for dry-run and live event replay against bound test enterprises.
- Automatically sanitizes payloads, strips incompatible reference structures, and enforces test target safeguards (`--force` required for non-test targets).
## [0.10.18] - 2026-09-11
### Added & Enhanced
- **System Diagnostic Doctor & Embedded Specification Whitepaper**:
- Added `seal-use doctor` for unified system health diagnostics, inspecting executable runtime, 8 core filesystem paths, enterprise assets, and health checks.
- Implemented `seal-use doctor guide` to output the full system architecture, 10-tier directory specifications, security guarantees, and capability matrix directly from binary memory with zero additional disk writes.
- Added `seal-use doctor paths` for compact JSON inspection of core directory status and descriptions.
- Adheres strictly to dual-channel protocol: typed JSON on `stdout` and terminal diagnostic dashboard on `stderr`.
- **Intelligent Soft Fuzzy Search for Enterprise Discovery**:
- Introduced dedicated fuzzy engine (`src/core/search/fuzzy.ts`) supporting case-insensitivity, Chinese homophones/allophones, pinyin initials (简拼), full pinyin, nasal/retroflex normalization, and Levenshtein typo tolerance.
- Enabled soft fuzzy search by default on `seal-use corps search <keyword>` and `seal-use corps list`, with `--strict` option for exact substring matching.
- Enforced `corps search` in Agent Skill guidelines over dumping entire enterprise lists when names or hints are known.
- **Dedicated Enterprise Lookup & Compatibility Alias**:
- Added `seal-use corps get <idOrName>` to inspect a single enterprise by ID, exact name, or unique prefix.
- Added `corp` as a first-class CLI compatibility alias for `corps` across command dispatching and help registry.
- **Approval Run Deep Link & SSO URL Generation**:
- Added `seal-use runs url <runId> [--sso] [--corp <corpId>]` to generate direct Web UI links and security-guarded SSO links for approval runs.
- **Approval Run to Webhook Replay**:
- Added `seal-use runs replay <runId> [--corp <corpId>] [--target <url>]` to reconstruct webhook payloads from historical runs for deterministic regression testing.
## [0.10.17] - 2026-09-11
### Added & Enhanced
+802 -247
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-use Wrapped API",
"version": "0.10.17",
"version": "0.10.20",
"description": "Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
+226
View File
@@ -0,0 +1,226 @@
# Seal-Use AI-Native Harness 架构演进与需求提案白皮书
> **设计核心哲学**:本系统的使用者与维护者主要为 AI 智能体(Agent Harness)。系统设计的首要目标不是人类的图形交互或阅读习惯,而是 **AI Agent 的极致易用性** —— **输入输出零歧义、上下文高信噪比、问题能够自动探查与感知、错误具备结构化自愈闭环(Self-Healing)**。
---
## 一、AI-Native vs Human-Centric 范式对比
| 维度 | 传统面向人类设计 (Human-Centric) | 面向 AI 智能体设计 (AI-Native Harness) |
| :--- | :--- | :--- |
| **交互输出** | 富文本、表格渲染、色彩斑斓的进度条、多步骤弹窗向导 | **`stdout` 纯严格 Schema JSON**,无冗余修饰,保证 LLM 解析 100% 稳定 |
| **故障提示** | 模糊的人类提示(如“操作失败,请检查网络或参数”) | **高密度诊断信道 (`stderr`) + 机器可执行的下一步命令**(`👉 Next action: seal-use ...`) |
| **错误定位** | 让人类打开 Web 控制台查看图表、肉眼比对单据差异 | **自动化断言探针 (`test regression`)**,自动计算混淆矩阵与决策翻转差异 |
| **变更验证** | 人工点选测试单据、口头确认“看起来没问题” | **数学与逻辑确定性**:规则死锁检测、定量边界检查、全量沙箱重放验证 |
| **容错机制** | 弹出警告等待人类决策 | **结构化修复建议与自动修复命令**(Exit Code 10 确认契约、Autofix Patch) |
---
## 二、测试环境与代码库深度 Review 现状剖析
针对当前测试环境(以 `xiezihao` 及绑定的生产租户 `LyG3iezucw03fs` 为基准)与整体代码库进行全链路审查,发现以下几个核心痛点与系统盲区:
### 1. 规则系统的“模糊地带”依然存在
- **实测现状**:
- 执行 `seal-use rules lint --corp xiezihao`:检出规则 13 存在 `适当`、`酌情` 等主观模糊词。
- 执行 `seal-use rules lint --corp xiezihao --linter strict`:检出 7 条规则缺乏定量指标(金额、天数)或绝对刚性边界词(规则 17、19、20、21、24、25、26)。
- **AI 视角的痛点**:
- 当规则中包含“适当放宽”、“结合实际情况酌情”时,大模型在自动审核时的判定置信度(Confidence)会产生明显波动,导致同一种单据今天通过、明天驳回,产生偶发性幻觉。
- AI Agent 目前只能“发现”问题,缺乏**标准化、无提示词漂移的自动修复工具**。
### 2. 规则迭代缺乏“防劣化回归测试闭环”
- **实测现状**:
- 目前已有 `corps sync-test`(同步配置到测试环境)和 `corps replay-test <sn>`(单笔单据重放测试)。
- **AI 视角的痛点**:
- 当 AI 修改了某条规则(例如将团建费规则的人均标准改为 60 元),AI 无法回答一个关键问题:**“这次修改是否会导致历史正常通过的单据被意外驳回?”**
- 当前缺乏批量回归能力,AI 必须逐笔单据拉取、重放、对比,耗费大量 Token 且容易由于大模型上下文窗口截断而遗漏决策翻转(Decision Flips)。
### 3. Webhook 异步回调链路“本地断链”
- **实测现状**:
- `corps replay-test` 将单据推入测试环境后,Seal 后端完成异步审核,会向配置的 `outgoingResultWebhook` 发送 HTTP POST 回调。
- 在测试租户中,回调地址往往是测试桩(如 `https://baidu.com` 或内网不可达地址)。
- **AI 视角的痛点**:
- AI 发送测试单据后,无法直接捕获后端的实际审核产物(决策结果、风险标签、审核理由),只能被动轮询 `runs list`。缺乏端到端的闭环测试能力。
### 4. 智能洞察(Analytics)目前是“被动拉取”,缺乏“主动哨兵”
- **实测现状**:
- 智能洞察已支持 `insight`、`risks`、`performance`、`analyze`、`export`。
- **AI 视角的痛点**:
- 返回的是全量统计数据(如 20 个标签、平均耗时等)。AI Agent 需要主动进行差分计算才能识别异常。
- 缺乏针对“异常激增”、“置信度暴跌”、“审核吞吐突降”的主动预警计算引擎。
---
## 三、六大 AI-Native 核心需求规划提案
为彻底落实“**能自动测出问题、专为 AI 好用**”的目标,建议演进以下六大功能模块:
### 需求提案 1: `seal-use test regression` —— 规则变更自动化回归测试矩阵
#### 业务价值与 AI 交互设计
- **目标**:AI 在修改规则草稿后,一键执行全自动历史单据回归验证,防止规则劣化。
- **命令行界面 (CLI)**:
```bash
seal-use test regression --corp <testCorpId> [--samples 20] [--draft]
```
- **工作机制**:
1. 自动从绑定的生产租户抓取最近 $N$ 笔已归档单据的原始输入与原始判定;
2. 将单据批量推入测试租户(使用当前未发布的 Draft 规则执行审核);
3. 自动比对两套判定,统计 **决策一致率** 与 **决策翻转明细 (Decision Flips)**;
- **AI 输出 Schema (`stdout`)**:
```json
{
"status": "COMPLETED",
"samples": 20,
"concordanceRate": 0.90,
"verdict": "REGRESSION_DETECTED",
"flips": [
{
"sn": "BX20260901001",
"title": "市场部团建费报销",
"prodDecision": "PASS",
"testDecision": "REJECT",
"flippedRuleId": "rule-13",
"reasonDiff": "+ 人均金额 65 元超过上限 50 元",
"riskTag": "B.1.1"
}
],
"safeToPublish": false
}
```
- **AI 友好特性**:`safeToPublish` 布尔标记直接给出确定性结论,AI Agent 无需自行阅读 20 份单据长文本即可判断是否可以发布上线。
---
### 需求提案 2: `seal-use rules check-conflicts` —— 规则语义冲突与死锁静态分析
#### 业务价值与 AI 交互设计
- **目标**:在规则发布前,自动探测规则集内部是否存在自相矛盾或相互死锁的逻辑。
- **命令行界面 (CLI)**:
```bash
seal-use rules check-conflicts --corp <corpId> [--draft]
```
- **核心检测模型**:
1. **作用域重叠冲突 (Scope Overlap)**:如规则 A 和规则 B 均适用于 `单据模板=费用报销单` 且 `费用类型=交通费`,但规则 A 判定“必须上传行程单(MUST_FOLLOW)”,规则 B 判定“无行程单可做建议通过(SUGGESTION)”。
2. **边界倒置 (Threshold Inversion)**:规则 A 规定“金额 > 5000 需总监审批”,规则 B 规定“金额 > 3000 需总经理审批”。
3. **循环依赖与前提悬空**:规则声明必须关联采购单,但同一单据类型根本无采购单关联字段。
- **AI 输出 Schema (`stdout`)**:
```json
{
"hasConflicts": true,
"conflicts": [
{
"type": "CONTRADICTORY_STRICTNESS",
"rules": [16, 21],
"scope": "单据模板=对公付款单",
"explanation": "规则 16 要求未开具发票必须直接驳回,而规则 21 允许待开发票通过并补充凭证",
"suggestedFix": "缩小规则 16 范围,排除税费缴纳类付款单"
}
]
}
```
---
### 需求提案 3: `seal-use rules autofix` —— 规则缺陷自动修补与 Patch 引擎
#### 业务价值与 AI 交互设计
- **目标**:将 Linter 发现的缺陷直接转为确定性的规范化重写建议,避免 AI Agent 自由发挥导致提示词漂移。
- **命令行界面 (CLI)**:
```bash
seal-use rules autofix --corp <corpId> --rule <ruleCode> [--dry-run] [--yes]
```
- **工作机制**:
- 针对 `VAGUE_WORD`(如“适当放宽”),自动基于企业既往审计偏好提供标准化替换模板(例如转换为明确的数值浮动比例或条件分支)。
- 自动规范化条款格式:标号化(`1️⃣ 2️⃣`)、前置条件与驳回动作明确分离。
- `--dry-run` 输出精准 Unified Diff;`--yes` 直接更新草稿。
- **AI 友好特性**:Agent 可直接通过 `--dry-run` 读取 Patch,确认无误后执行 `--yes`,形成全自动修复流水线。
---
### 需求提案 4: `seal-use doctor tenant` —— 租户全链路健康契约探针与自愈
#### 业务价值与 AI 交互设计
- **目标**:现有的 `seal-use doctor` 主要针对本地文件、二进制与 CLI 环境。新增租户级契约巡检,一键探测云端租户配置的完整性与可用性。
- **命令行界面 (CLI)**:
```bash
seal-use doctor tenant --corp <corpId> [--repair]
```
- **核心探针项目**:
1. **凭证存活性 (Auth Probe)**:OAuth/SSO 令牌剩余有效期、网关 Cookie 连通性、租户管理员权限完整度;
2. **版本一致性 (Draft State Probe)**:规则是否存在未发布的脏草稿?发布版本是否落后于生产环境?
3. **集成健康度 (Integration Probe)**:入向 Webhook URL 是否能够接收校验请求?出向 Webhook 是否存活(Ping 测试响应 2xx/3xx)?
4. **知识库引用有效性 (Knowledge Probe)**:规则描述中引用的制度文件名称是否在知识库中真实存在?
- **自动自愈 (`--repair`)**:
- 若发现配置漂移,自动调用同步逻辑修复缺失项,使测试环境瞬间恢复到健康可用状态。
---
### 需求提案 5: `seal-use webhook mock-sink` —— 闭环本地模拟回调接收器
#### 业务价值与 AI 交互设计
- **目标**:解决单据重放测试中“出向回调无人接收、测试无法闭环验证”的问题。
- **命令行界面 (CLI)**:
```bash
seal-use webhook mock-sink --corp <corpId> --listen 9999 --timeout 30s
```
- **工作机制**:
1. CLI 在本地启动一个微型 HTTP 监听端点;
2. 自动临时将测试租户的 `outgoingResultWebhook` 更新为该端点(通过隧道或直连网段);
3. 执行单据推送;
4. 捕获 Seal 后端推送过来的完整决策 JSON,校验签名,打印到 `stdout`;
5. 超时或收到结果后自动恢复原出向回调配置。
- **AI 友好特性**:让 Agent 具备端到端的异步调用验证能力,真正做到“单据进 -> 判定出 -> 自动断言”。
---
### 需求提案 6: `seal-use analytics alerts` —— 质效异动哨兵与规则关联归因
#### 业务价值与 AI 交互设计
- **目标**:将大盘数据的被动查询,升级为具备异常检测能力的“质量监控哨兵”。
- **命令行界面 (CLI)**:
```bash
seal-use analytics alerts --corp <corpId> [--window 7d]
```
- **检测算法**:
1. **低置信度突增预警**:检测置信度 $< 0.80$ 的风险标签占比是否超过 15%;
2. **高频驳回标签突增**:检测某类风险(如“发票要素不全”)在规则修改后出现倍增;
3. **归因推导**:将异常指标直接与具体的规则编号绑定,输出精准的修复建议。
- **AI 输出 Schema (`stdout`)**:
```json
{
"healthy": false,
"alerts": [
{
"severity": "HIGH",
"category": "CONFIDENCE_DROP",
"message": "标签 'A.1.2 关键业务信息缺失' 平均置信度仅为 0.72",
"affectedRules": [13, 21],
"suggestedAction": "seal-use rules lint --corp xiezihao --rule 13"
}
]
}
```
---
## 四、演进实施优先级与排期建议
| 优先级 | 需求模块 | 核心收益 | 实施复杂度 |
| :--- | :--- | :--- | :--- |
| **P0** | **`test regression` 自动化回归矩阵** | 解决 AI 修复规则时的“不敢改、不知改后是否破坏其他单据”的根本痛点 | 中(依赖已有的 Webhook Replay 与判定比较引擎) |
| **P0** | **`doctor tenant` 租户契约探针与自愈** | 彻底消除 AI 任务前置准备阶段因环境配置残缺导致的未知报错 | 低(基于现有 API 组合健康检测函数) |
| **P1** | **`rules check-conflicts` 规则死锁检测** | 提前在编译期/发布期拦截规则逻辑矛盾,杜绝 LLM 审核幻觉 | 中(建立 Scope 与 Strictness 的求交算法) |
| **P1** | **`rules autofix` 规则修补 Patch 引擎** | 减少 AI 自由造句引起的格式漂移,提供标准化的规则修正模板 | 低至中(基于正则与 AST 替换) |
| **P2** | **`analytics alerts` 质效异动哨兵** | 将分析报表升级为自动化质检闭环,主动通知 AI 优化特定规则 | 低(纯指标阈值与历史窗口滑动计算) |
| **P2** | **`webhook mock-sink` 异步回调接收器** | 打造完整的 E2E 本地测试闭环 | 中(涉及临时端点管理与测试租户出向地址动态绑定) |
---
## 五、总结
将 `seal-use` 从“人类可用的 CLI 工具”转变为“**AI Agent 专用的自愈型 Harness**”,核心在于把**问题探查的主动权从人类眼睛转移给自动化算法与断言矩阵**。
通过实现回归矩阵(`test regression`)、租户探针(`doctor tenant`)以及规则死锁检测(`rules check-conflicts`),未来的 AI Agent 在接到“某客户反馈规则误报”的需求时,可以全自主地完成:
$$\text{自动诊断} \longrightarrow \text{自动修复} \longrightarrow \text{批量回归验证} \longrightarrow \text{零劣化证明} \longrightarrow \text{发布上线}$$
全程无需人类介入,实现真正的自动化可信运维。
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.17
version: 0.10.20
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.17",
"version": "0.10.20",
"type": "module",
"module": "src/server.ts",
"bin": {
+38 -13
View File
@@ -1,12 +1,12 @@
---
name: seal-use
description: "v0.10.17: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.20: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.17
short-description: Seal tenant and Hose approval automation (v0.10.17)
version: 0.10.20
short-description: Seal tenant and Hose approval automation (v0.10.20)
---
# Seal Use (v0.10.17)
# Seal Use (v0.10.20)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -41,7 +41,7 @@ seal-use corps list
## First Rules
- Treat CLI/MCP as the Agent's execution channel, not the user's interface. Translate natural-language intent into commands yourself; never ask the user to compose CLI syntax, JSON payloads, placeholder values, or internal IDs.
- Before asking for enterprise parameters, run `seal-use corps list`. If the target is already configured, resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`.
- Before asking for enterprise parameters, resolve the target enterprise: when an enterprise is named, hinted, or keyword-identifiable, ALWAYS run `seal-use corps search <keyword>` (or `seal-use corps get <corpId>` if an exact ID is known) — DO NOT dump the entire enterprise catalog with `seal-use corps list` when the target is already known. Only run `seal-use corps list` (or `corps list --env <test|production>`) for initial discovery when zero enterprise context is known. Resolve its human name to the returned `id` and pass that value as `--corp`; do not ask the user to know `corpId`. Use `seal-use corps get <corpId>` to inspect rich enterprise attributes (URLs, tenant slugs, staff IDs, environment relations, and config file locations) with sensitive secrets safely redacted.
- If no enterprise is configured, the user is installing for the first time, or the user provides credentials, an assistance link, or a browser-copied cURL, read `references/enterprise-onboarding.md` before asking questions or running setup commands.
- When the user provides a Hose/合思 `thirdparty.html` assistance link, use `seal-use corps add-link <url> [--name ...]`; the command verifies the tenant and records the temporary Seal session without echoing the link token.
- Keep enterprise identity origin separate from credential acquisition. A Hose/合思-sourced Seal tenant can be accessed with standard Hose app credentials, an assistance link, or a captured web session; receiving a Seal Bearer token does not by itself prove the tenant is Seal-native.
@@ -49,7 +49,7 @@ seal-use corps list
- Prefer compact commands first: `pick`, `--summary`, `--fields`, `attachments --summary`, `rules count`, and `rules list --summary`.
- Parse JSON stdout. Do not scrape human text.
- Do not hand-edit enterprise configs for normal setup. Use `seal-use corps ...`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal `--dry-run` preview first (rules clear/push, `corps sync-test`, preferences, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use `--yes` only after reviewing its redacted `changesDiff`.
- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For supported configuration writes, prefer the universal `--dry-run` preview first (rules clear/push, `corps sync-test`, preference updates, thinking-depth policies, HoseCloud configure, and Webhook add/update/delete), then use `--yes` only after reviewing its redacted `changesDiff`.
- Knowledge document creation and deletion are now supported. Validate `contentType` and `scenarios` before creating; use `enabled: false` when the document should be withdrawn without deletion. For an explicit deletion, re-read the document and obtain confirmation before using the low-level `seal_approval_delete_document` tool.
- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of `description`; preserve `scope`, `strictness`, and unrelated clauses unless the user explicitly approves otherwise.
- Resolve and lock the target enterprise `corpId` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing.
@@ -58,35 +58,51 @@ seal-use corps list
- When returning ANY authorization, login, or delegation links (e.g. 合思授权链接, Seal授权链接/委托链接), ALWAYS provide BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- For delegation links, always prefer `seal-use delegation create` over `users delegation` for link generation to ensure persistent token tracking.
- Never treat “Seal 协助/Seal 授权/委托” as a 合思授权入口. They are different links and must use different commands.
- For approval run links (`seal-use approval-runs url <recordId> [--corp <corpId>]`):
- Always default to returning the clean deep link (`type: 'deep_link'`), which contains no credentials and requires no sensitive access. Users in their authorized browsers open it directly with zero token leakage risk.
- ONLY provide an SSO link (`--sso`) when the user explicitly requests an unauthenticated/cross-browser/no-login/免密 link and acknowledges risks.
- When returning an `--sso` link, the Agent MUST:
1. Declare the 4 mandatory security disclosures:
- 身份主体(Identity attribution: name and admin status)
- 权限范围(Full Seal AI operation permissions under this user)
- 时效性(2-hour provisional ticket TTL, 30-day session after opening)
- 安全与防扩散边界(No Hose main system access, strictly internal, never share to public/external groups)
2. Provide BOTH a code block (` ```text ... ``` `) and a clickable hyperlink.
- In the default stateless mode, every enterprise command requires `--corp <corpId>`. In stateful mode, omitting `--corp` uses the configured default enterprise and is unsafe for an explicitly named enterprise.
- For an explicitly named enterprise, first resolve it with `seal-use corps list`, then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link.
- 生产规则变更建议优先遵循“生产改草稿 -> 同步测试企业 -> 真实单据模拟验证 -> 生产发布投产”安全闭环;Agent 应主动提示并建议在测试环境中验证,但最终操作权与决策权在用户手中,绝不代替用户做决定。若用户明确要求直接在生产环境发布,尊重用户意图并严格执行。
- For an explicitly named enterprise, resolve it directly with `seal-use corps search <name>` (or `seal-use corps get <corpId>` if given an exact ID) rather than dumping all enterprises with `seal-use corps list`. Then pass its exact `corpId` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link.
- 生产规则变更建议优先遵循“生产改草稿 -> 同步测试企业 -> 自动化回归测试矩阵/真实单据模拟验证 -> 生产发布投产”安全闭环;Agent 应主动提示并建议在测试环境中验证,但最终操作权与决策权在用户手中,绝不代替用户做决定。若用户明确要求直接在生产环境发布,尊重用户意图并严格执行。
- 在对企业执行高风险操作、批量审批或发布前,优先运行 `seal-use doctor tenant --corp <corpId>` 校验租户健康契约:验证身份管理权限、AI 审核扣费点数余量(`balance` 与 `deductionAmount`)、活跃规则与未发布草稿箱、Webhook 通道以及测试环境绑定。
- 在测试企业完成规则同步后,强烈推荐运行 `seal-use test regression --corp <corpId> [--samples 10]` 执行自动化回归测试矩阵:自动采样生产历史单据并在测试靶场重放对比决策,核验决策翻转率(Flips)与一致率,确保 `safeToPublish: true` 后再行投产。硬性红线:回归测试严禁直接在纯生产企业运行(必须下挂测试靶场),且测试环境点数余额必须充足。
- 单据 Webhook 重放安全与用户自主权策略:单据重放建议优先在绑定的测试企业中验证(CLI 与 MCP 默认拦截向生产环境重放以防污染真实审批流或产生实际外发回调)。Agent 应主动向用户解释风险并优先建议在测试环境模拟;但工具绝不反客为主,最终决策权在用户手中。若用户未绑定测试企业,或明确要求直接向生产环境重放,Agent 应向用户客观说明可能污染生产审批流或触发真实外部回调的风险;在确认用户明确意图后,通过追加 `--force`(或 MCP `force: true`)严格执行,绝不擅自拒绝用户要求。
- 测试环境合思模拟安全隔离:`corps sync-test` 自动将生产企业合思凭证以 `assisted` 模式注入测试企业,名称格式为 `{企业名前缀}(Seal测)`。该配置仅保存在测试 Seal 侧,绝对不执行 `deploy hosecloud sync`,杜绝向生产合思费控推送 EBot 节点或创建外发 webhook。
## Route By Intent
- 生产规则安全演进、搭配配置与测试模拟闭环: read `references/staging-simulation-workflow.md`. 适用于:用户提出规则变更需求/客诉修复、生产与测试企业搭配接入与 1 对 1 绑定、生产环境仅改草稿隔离风险、`seal-use corps sync-test` 一键同步测试环境(含合思集成免配同步)、测试环境跑真实单据模拟验证、验证通过后才在生产正式发布的完整安全生命周期。
- 生产规则安全演进、搭配配置与测试模拟闭环: read `references/staging-simulation-workflow.md`. 适用于:用户提出规则变更需求/客诉修复、生产与测试企业搭配接入与 1 对 1 绑定、生产环境仅改草稿隔离风险、`seal-use corps sync-test` 一键同步测试环境(含合思集成免配同步)、测试靶场运行自动化规则回归测试矩阵(`test regression`)或真实单据模拟验证、验证通过后才在生产正式发布的完整安全生命周期。
- First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically.
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
- 自动化规则回归测试矩阵 (Automated Rule Regression Test Matrix): `seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips] [--prod-corp <id>] [--test-corp <id>]` (快捷别名 `seal-use corps regression`)。采样生产企业历史已完成单据,通过出站 HTTPS 轮询重放到配对测试靶场执行 AI 审核并对比双端决策,计算一致率(Concordance Rate),识别决策翻转(Decision Flips),给出 `safeToPublish` 综合判定。硬性红线:目标环境必须为测试企业且测试点数余额充足,严禁在纯生产环境发起。
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation status <batchId>` 单次查询状态, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation approval-definitions` 查询飞书审批定义, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
- 测试企业标记、关联与配置规则同步: `seal-use corps mark <corpId> --env <production|test> --confirm` (严格标记环境), `seal-use corps bind-test <prodCorpId> <testCorpId> --confirm` (严格1对1下挂,禁止多层级串联), `seal-use corps unbind-test <corpId> --confirm`, `seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]` (将正式企业的偏好、草稿规则和知识文档覆盖同步到测试企业并自动发布语义版本 `[Prod vN · #M -> Test vM]`,输出并本地缓存 `versionMapping`/`ruleMapping`,正式企业规则保持草稿态不发布), `seal-use rules map [--corp <corpId>] [--version <v|latest>] [--code <code>]` (离线毫秒级速查测试与生产规则对照映射)。
- 企业检索、详情查看、环境标记、关联与配置规则同步: `seal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict]` (列表与轻量检索,默认展示 7 天使用频次最高的 10 个租户;`--all` 展示全量;`--sort usage|name|id` 切换排序), `seal-use corps search <query> [--env <production|test>] [--strict]` (跨字段智能软搜索:默认支持同音字、前后鼻音、平翘舌音、拼音与简拼、拼音或字母缺漏容错;`--strict` 切换为严格子串匹配), `seal-use corps get <corpId>` (富属性安全查看,敏感信息脱敏), `seal-use corps mark <corpId> --env <production|test> --confirm` (严格标记环境), `seal-use corps bind-test <prodCorpId> <testCorpId> --confirm` (严格1对1下挂,禁止多层级串联), `seal-use corps unbind-test <corpId> --confirm`, `seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]` (将正式企业的偏好、草稿规则和知识文档覆盖同步到测试企业并自动发布语义版本 `[Prod vN · #M -> Test vM]`,输出并本地缓存 `versionMapping`/`ruleMapping`,正式企业规则保持草稿态不发布), `seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--force]` (将绑定的生产企业历史审批记录批量或单条重放到测试企业 Webhook 并做环境隔离与自动通道补齐;若未绑定测试企业可加 `--force` 直接重放), `seal-use rules map [--corp <corpId>] [--version <v|latest>] [--code <code>]` (离线毫秒级速查测试与生产规则对照映射)。
- 规则本地工作流: `seal-use rules pull` 导出草稿规则,`rules lint` 做质量检查,`rules push --dry-run` 预览增量更新,确认后用 `--yes` 写入;`rules map` 查询 `corps sync-test` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 `references/rule-lightweight.md` 和 `references/cli.md`。
- Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`; read `references/hose-enterprise-deploy.md`.
- 审核决策偏好与思考深度: `seal-use preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight`, 以及 `approval-runs export`(Excel 报表);需要追踪单据时再使用 `url` 或 `bridge`。
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp <corpId>`, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表);需要追踪单据时再使用 `url` 或 `bridge`。
- User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp <corpId> --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
- Delegation links management: `seal-use delegation list --corp <corpId>`, `create [--note ...] --corp <corpId>`, `create --from-link <url> [--note ...]`, `revoke <tokenId> --corp <corpId>`.
- User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-use users search [keyword] --corp <corpId>`, `users delegation <userIdOrPhone> --corp <corpId>` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate <userId> --corp <corpId>`, `users create --name ... --phone ... --corp <corpId>`, `users reset-password <userId> --corp <corpId>`, `users get <userId> --corp <corpId>`, `users delete <userId> --corp <corpId>`.
- 只读业务数据与组织发现: `seal-use contacts departments|children|users|sync-time --corp <corpId>`, `seal-use data expenses|invoices --corp <corpId>`, `seal-use analytics insight --corp <corpId>`, `seal-use context --corp <corpId>`, `seal-use source config --corp <corpId>`;这些查询优先用于定位企业结构、原始费用/发票和当前审核知识,不要把结果误当成写操作。
- 只读业务数据与组织发现: `seal-use contacts departments|children|users|sync-time --corp <corpId>`, `seal-use data expenses|invoices --corp <corpId>`, `seal-use analytics insight|risks|performance --corp <corpId>`, `seal-use context --corp <corpId>`, `seal-use source config --corp <corpId>`;这些查询优先用于定位企业结构、原始费用/发票和当前审核知识,不要把结果误当成写操作。
- LLM Model Config & Providers: `seal-use llm config --corp <corpId>`, `seal-use llm providers --corp <corpId>`.
- System Permissions Config: `seal-use permissions available --corp <corpId>`, `seal-use permissions configs --corp <corpId>`.
- Billing & Feature Quotas: `seal-use billing status --corp <corpId>`, `seal-use billing plans --corp <corpId>`, `seal-use billing features --corp <corpId>`.
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>` (别名 `status`) 检查企业环境、租户连通性、已激活通道与材料包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] --corp <corpId>` 检查企业环境、租户连通性、已激活通道与材料包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp <corpId>` 只做本地校验和解析(无网络请求);`... push <材料包.zip> [--webhook <idOrName>] --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Material Pack Workflow" 一节。它与 `simulation material_pack` 的官方服务端导入流程相互独立。
- 审批记录转 Webhook 重放 (Universal Record Replay): `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` 以及生产测专用快捷命令 `seal-use corps replay-test [<prodCorpId>] [--force]`。通用支持从历史审批记录(Webhook 来源、Hose 来源等)汲取结构化表单与明细字段,自动清洗规范化字段类型,支持按状态/数量批量重放到目标企业 Webhook 触发审批。默认推荐并导向测试企业(测试企业无 Webhook 时自动开通辅助模式通道并锁定环境隔离);若用户未绑定测试企业或明确要求向生产企业重放,支持通过 `--force` 显式执行,方便环境回归验证与 Bad Case 靶向调试。
- HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
- 审批规则质量校验 (Linter): `seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>`; read `references/rule-lint.md`. 全局配置默认关闭 (`config lint <enable|disable>`)。
- 系统自检、租户健康契约与内嵌架构规范白皮书: `seal-use doctor` (整机环境、目录状态、企业资产统计与健康自检,零磁盘写入), `seal-use doctor tenant [--corp <corpId>] [--quiet]` (企业租户级健康契约探针:身份/管理员角色、AI 审批点数余额与单次扣费、活跃规则数、草稿安全性、Webhook 通道与环境配对), `seal-use doctor guide` (纯内存只读输出内嵌白皮书与目录规范), `seal-use doctor paths` (紧凑型核心目录健康检查)。
- Full CLI inventory: read `references/cli.md`.
## Material-pack Webhook policy and recovery
@@ -107,6 +123,15 @@ push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附
## High-Value Commands
```bash
seal-use doctor
seal-use doctor tenant --corp <corpId>
seal-use doctor guide
seal-use test regression --corp <corpId> --dry-run
seal-use test regression --corp <corpId> --samples 10 --fail-on-flips
seal-use corps list [query] [--env production|test] [--limit 10] [--all] [--sort usage|name|id]
seal-use corps search <keyword> [--env production|test] [--strict]
seal-use corps get <corpId>
seal-use approval-runs url <recordId> --corp <corpId>
seal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest
seal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest --fields recordId,status,aiDecision,aiSummary
seal-use approval-runs get <recordId> --corp <corpId> --summary
@@ -84,6 +84,43 @@ seal-use approval-runs result <recordId> --corp <corpId> --summary
This is for decision, summary, risk point count, matched rule count, trace ID, and record ID.
## Approval Run Web Links & SSO Links
Use this when the user asks for a link to an approval run or wants to open the run directly in their browser:
```bash
# 默认推荐:生成干净的深度链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)
seal-use approval-runs url <recordId> --corp <corpId>
seal-use approval-runs url --sn <sourceDocumentSN> --corp <corpId>
# 仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带单次临时票据的 SSO 直登链接
seal-use approval-runs url <recordId> --sso [--expire 7200] --corp <corpId>
```
### SSO 链接安全与声明规范
当向用户返回 `--sso` 链接时,Agent **必须**在回答中明确说明以下 4 点:
1. **身份主体**:该链接代表哪个具体员工身份(如管理员姓名)登录。
2. **权限范围**:该身份在 Seal AI 平台的全部权限范围(如完全操作权限)。
3. **时效性**:临时 Ticket 换票时效(默认 2 小时,换票登录后会话有效 30 天)。
4. **安全与防扩散边界**:该链接仅在 Seal AI 租户内生效,不代表合思主系统权限;严禁在公开或外部群聊中传播。
> **链接输出要求**:无论返回普通深度链接还是 SSO 链接,必须同时提供纯文本代码块(` ```text ... ``` `)防止默认浏览器误点重定向,以及可点击的 Markdown 超链接。
## Replay Run into Webhook for Regression Testing
When diagnosing a bad case or verifying rule fixes, replay the historic run's structured fields and items back through a Webhook channel:
```bash
# 预览重放单据(无网络请求,清洗并规范化表单与明细类型)
seal-use webhook replay <recordId> --dry-run --corp <corpId>
# 执行重放,生成全新审批实例(支持自动附加单号后缀防重)
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId>
# 跨企业提取:从生产企业提取单据并推送至测试企业 Webhook 进行回归验证
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId>
```
## Output Discipline
If a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.
+56 -10
View File
@@ -52,6 +52,7 @@ seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205
seal-use rules search <keyword> [--version <versionId|versionNumber|latest>] [--maxResults 20] [--corp <corpId>]
seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]
seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]
seal-use rules linters [--corp <corpId>]
seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]
seal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]
seal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]
@@ -67,16 +68,24 @@ seal-use mcp-config
seal-use skill dump
seal-use skill install [--dir <path>|--local]
seal-use skill status
seal-use openapi
seal-use doctor [--quiet]
seal-use doctor tenant [--corp <corpId>] [--quiet]
seal-use doctor guide
seal-use doctor paths
seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]
seal-use probe [<corpId>]
seal-use tools list
seal-use corps list [--corp <corpId>]
seal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict] [--corp <corpId>]
seal-use corps search <query> [--env <production|test>] [--strict]
seal-use corps get <corpId>
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--force]
seal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
@@ -106,7 +115,6 @@ seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
@@ -114,6 +122,7 @@ seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode
seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
@@ -132,6 +141,10 @@ seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]
seal-use analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO>] [--limit <n>]
seal-use analytics risks <tagId> --corp <corpId> [--start-date <ISO>] [--end-date <ISO>]
seal-use analytics performance --corp <corpId> [--start-date <ISO|ms>] [--end-date <ISO|ms>]
seal-use analytics analyze <recordId> --corp <corpId>
seal-use analytics export --corp <corpId> [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>]
seal-use approval-runs count --corp <corpId> [--status APPROVED]
seal-use approval-runs export --corp <corpId> [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>]
seal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
@@ -139,9 +152,10 @@ seal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|documen
seal-use approval-runs attachments <recordId> --corp <corpId>
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] --corp <corpId>
seal-use approval-runs result <recordId> --corp <corpId> [--summary]
seal-use approval-runs url --corp <corpId>
seal-use approval-runs url <recordId> --corp <corpId>
seal-use approval-runs url --sourceDocumentSN <sourceDocumentSN> --corp <corpId>
seal-use approval-runs url <recordId> --sso [--expire 7200] --corp <corpId>
seal-use approval-runs url --sn <documentSN> [--sso] --corp <corpId>
seal-use approval-runs url --corp <corpId>
seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] --corp <corpId>
@@ -174,21 +188,35 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
`seal-use update` updates the git checkout, runs `bun install`, and restarts the local service if it was running.
Identity and session:
System diagnostic & embedded architecture specifications:
- `seal-use doctor [--quiet]` executes a comprehensive read-only environment diagnostic health check (runtime executable, filesystem paths health, enterprise assets summary, daemon status) with zero disk footprint.
- `seal-use doctor tenant [--corp <corpId>] [--quiet]` probes the tenant-level health contract: verifies user identity and administrative permissions, checks AI approval quota balance (`balance` and `deductionAmount`), inspects active rules count and unreleased draft safety, validates webhook integration readiness, and verifies 1-to-1 environment pairing with test staging. Outputs clean JSON on `stdout` and a visual terminal dashboard on `stderr`.
- `seal-use doctor guide` reads the complete embedded system architecture & directory specification whitepaper directly from binary memory without touching disk.
- `seal-use doctor paths` outputs compact JSON audit of all filesystem paths touched by the CLI.
Enterprise and tenant management:
- `seal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--sort <usage|name|id>] [--strict] [--corp <corpId>]` (defaults to displaying the top 10 most frequently used enterprises in the last 7 days; pass `--all` to display the entire enterprise catalog, `--sort <usage|name|id>` to toggle sort criteria)
- `seal-use corps search <query> [--env <production|test>] [--strict]` (intelligent soft search by default: case-insensitive, Chinese homophones, front/back nasal vowels, flat/retroflex consonants, initials, typo/missing letter tolerance; pass `--strict` for exact substring match)
- `seal-use corps get <corpId>` (rich enterprise attributes with sensitive secrets safely redacted)
- `seal-use corps current [--corp <corpId>]`
- `seal-use corps switch <corpId>`
- `seal-use auth diagnose --corp <corpId>`
- `seal-use corps list`
- `seal-use corps current`
Read-only discovery:
- `seal-use contacts departments|children|users|sync-time --corp <corpId>` queries the tenant's organization tree and last directory sync time.
- `seal-use data expenses|invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]` queries paginated raw expense or invoice records.
- `seal-use analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO>] [--limit <n>]` queries risk-tag statistics; omitted dates use the current month.
- `seal-use analytics risks <tagId> --corp <corpId> [--start-date <ISO>] [--end-date <ISO>]` queries detailed risks and cited documents under a specific risk tag.
- `seal-use analytics performance --corp <corpId> [--start-date <ISO|ms>] [--end-date <ISO|ms>]` queries approval performance metrics and Sankey decision flow.
- `seal-use analytics analyze <recordId> --corp <corpId>` triggers on-demand smart insight risk analysis for an approval record.
- `seal-use analytics export --corp <corpId> [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>]` exports a comprehensive multi-sheet Excel report covering performance KPIs, decision flow, top risk tags, and detailed risk citations.
- `seal-use context --corp <corpId> [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50]` aggregates rules, knowledge documents, and style preferences.
- `seal-use source config --corp <corpId>` resolves the live source-system configuration without changing it.
Test Enterprise Binding & Staging Synchronization:
Test Enterprise Binding, Staging Synchronization & Automated Regression Testing:
- **1-to-1 Association**: One production enterprise can only bind at most one test enterprise (`corps bind-test <prodCorpId> <testCorpId>`). Multi-tier chaining is rejected.
- **Marking & Rigorous Confirmation**: Marking (`corps mark <corpId> --env <production|test>`) and binding require explicit `--confirm`. Without confirmation, the CLI blocks with exit code `10` (`confirmationRequired`). Overwriting existing bindings requires `--force`.
@@ -198,6 +226,23 @@ Test Enterprise Binding & Staging Synchronization:
- **Semantic Version Naming**: Defaults to `Sync from <ProdCorp> [Prod v<N> · #<Iteration>]` tracking production baseline version and test draft iteration without redundant date strings.
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
- `--dry-run` previews the full preference diff, version mapping plan, and rule sync plan without sending mutations. Execution requires `--yes`.
- **Approval Run Replay to Test Enterprise (`corps replay-test`)**:
- Automatically identifies the bound test enterprise for `<prodCorpId>` (or current corp).
- Fetches original approval records from the production enterprise (`--record-id`, `--sn`, or batch via `--limit` / `--status`).
- Cleans and normalizes payload structure, appends customizable suffix (default `-REPLAY-TEST`) to avoid collision.
- Automatically provisions `(Seal测-回放通道)` with `assisted` mode on the test enterprise if no webhook integration exists.
- Replays documents safely to the test enterprise webhook endpoint. Targeting production is blocked by default; if the enterprise has no bound test corp or target is production, `--force` can be specified to allow direct replay.
- **Automated Rule Regression Test Matrix (`seal-use test regression` / `seal-use corps regression`)**:
- Runs an automated regression testing matrix across paired production and test enterprises before rule publication.
- Enforces **Red Line 1**: The replay target MUST be a test enterprise (`environment: "test"`). Running regression tests directly in pure production is strictly forbidden.
- Enforces **Red Line 2**: Pre-flight verification of target test enterprise AI approval balance (`balance >= samples * deductionAmount`). If balance is insufficient, execution is blocked immediately to avoid quota starvation.
- Samples historical completed production runs (`--samples <N>`, default 10).
- Replays sanitized documents into the test webhook integration.
- Uses **outbound HTTPS polling** for asynchronous test approval completion, eliminating any requirement for public IP or inbound webhook listeners behind NAT/VPNs.
- Normalizes and compares production vs. test decisions (`APPROVE`, `REJECT`, `MANUAL`, `ERROR`).
- Detects decision flips (e.g. production APPROVE becoming test REJECT), computes overall concordance rate, and computes boolean `safeToPublish`.
- Supports `--dry-run` to preview sampled documents and verify quota without executing mutations.
- Supports `--fail-on-flips` to terminate with a non-zero exit code (1) if any decision flip occurs, providing seamless integration with automated CI/CD safety gates.
Approval rule maintenance:
@@ -206,6 +251,7 @@ Approval rule maintenance:
- `seal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]` (reads local sync rule mapping snapshot)
- `seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]`
- `seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]`
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: `~/.config/seal-use/linters` and `official/`)
- `seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
- `seal-use rules clear [--corp <corpId>] [--dry-run|--yes]`
@@ -241,7 +287,6 @@ Approval knowledge documents & style:
Webhook integrations:
- `seal-use webhook ready [<材料包.zip|信息表.xlsx>] [--webhook <idOrName>] [--corp <corpId>]`
- `seal-use webhook status [<材料包.zip|信息表.xlsx>] [--corp <corpId>]`
- `seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]`
- `seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]`
- `seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]`
@@ -249,6 +294,7 @@ Webhook integrations:
- `seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]`
- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>`
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持)
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
@@ -34,9 +34,13 @@ Treat chat text as the customer's expected behavior, not proof of the current Se
## 2. Resolve and lock the enterprise
List configured enterprises first:
When the customer feedback mentions or hints at the enterprise name, resolve it directly with targeted search rather than dumping the full enterprise list:
```bash
# 优先:按已知企业名称/关键字精确定位目标企业
seal-use corps search <enterpriseName>
# 仅当企业名称完全未知且没有任何线索时才回退至全量列表
seal-use corps list
```
@@ -8,11 +8,21 @@ Run this before asking for setup parameters (if `seal-use` is not installed, fir
```bash
seal-use version
# 当用户已提及企业名称或关键字时,优先运行精准搜索:
seal-use corps search <keyword> [--env production|test]
# 仅在完全没有企业线索或初次安装引导时运行全量列表:
seal-use corps list
# 查看目标企业完整富属性(含 Seal 域名、租户 Slug、合思域名、配置来源路径等,安全脱敏):
seal-use corps get <corpId>
```
- If `seal-use` is not installed on the system, run the curl install script above to install it.
- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.
- If the user provided an enterprise name or keyword, prioritize `seal-use corps search <keyword>` to locate it without dumping all enterprises. Match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.
- If zero enterprise context is known, run `seal-use corps list`.
- To inspect full endpoint URLs, tenant slug, config file location, and staff bindings of a configured enterprise, run `seal-use corps get <corpId>`.
- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.
- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”
@@ -23,33 +23,48 @@
---
## 端到端标准演进闭环 (The 4-Stage Lifecycle)
## 端到端标准演进闭环 (The 5-Stage Lifecycle)
```mermaid
flowchart TD
A["Stage 1: 生产与测试环境接入与绑定"] --> B["Stage 2: 生产规则草稿修改 (Draft Only)"]
A["Stage 1: 租户健康契约自检与环境配对 (doctor tenant / corps bind-test)"] --> B["Stage 2: 生产规则草稿修改 (Draft Only)"]
B --> C["Stage 3: 一键安全同步测试环境 (corps sync-test)"]
C --> D["Stage 4: 测试环境单据模拟验证 (simulation create)"]
D --> E{"验证是否符合预期?"}
E -- 存在偏差/误伤 --> B
C --> D["Stage 4: 自动化规则回归测试矩阵与模拟验证 (test regression / simulation)"]
D --> E{"回归与模拟是否通过 (safeToPublish)?"}
E -- 存在偏差/翻转误伤 --> B
E -- 验证通过 --> F["Stage 5: 生产环境正式发布 (rules publish)"]
```
---
### 第一阶段:生产与测试企业搭配配置 (Pairing & Setup)
### 第一阶段:租户健康契约自检与环境配对 (Health Diagnosis & Pairing)
1. **发现并列出已有企业**:
1. **租户健康契约探针自检 (Pre-Flight Contract Probe)**:
在开始任何配置前,优先通过确定性探针核验租户身份、点数余额与规则状态:
```bash
seal-use doctor tenant --corp <prodCorpId>
seal-use doctor tenant --corp <testCorpId>
```
检查关键指标:
- 身份权限:管理员角色正常;
- 扣费余量:测试靶场 `ai-approval` 特性的 `balance`(点数余额)充足;
- 规则与草稿:活跃规则数与未发布草稿箱状态。
2. **定位并识别生产与测试企业**:
```bash
# 优先使用关键字搜索精准定位目标企业(避免全量列表冗余输出)
seal-use corps search <prodOrTestKeyword>
# 或查看常用企业列表(默认按7天使用热度排序展示前10条;--all 查看全部)
seal-use corps list
```
识别生产企业(`sourceType: "hose"` 或 `"seal"`)与测试企业(如专用的测试环境)。
2. **如果尚未接入企业**:
3. **如果尚未接入企业**:
- 合思标准凭证接入生产企业:`seal-use corps add-hose --json '{"appKey":"...","appSecurity":"...","domain":"..."}'`
- 或通过协助链接接入:`seal-use corps add-link <url>`
3. **环境严格标记与 1 对 1 绑定**:
4. **环境严格标记与 1 对 1 绑定**:
```bash
# 1. 明确标记企业环境属性
seal-use corps mark <prodCorpId> --env production --confirm
@@ -128,12 +143,47 @@ flowchart TD
```
确认返回的 `hosecloudIntegrations` 中包含目标企业的测试配置项(如 `钰泰半导体(Seal测)`)。
2. **创建模拟测试任务**:
针对目标真实单据号(或客诉单据)在测试环境发起模拟:
```bash
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>"
```
Seal 服务器会自动使用测试环境中保存的合思凭证,直接调用合思 OpenAPI 拉取单据详情,并通过测试环境中刚发布的规则版本执行 AI 预审判断。
2. **执行验证与对比测试 (三种验证方式)**:
- **方式 A:自动化规则回归测试矩阵 (Automated Regression Test Matrix,强烈推荐首选)**:
无需人工逐条单号录入,全自动从生产环境抽取历史已完成单据并重放到测试靶场,比对双端决策一致率与翻转率:
```bash
# 1. 预览采样单据与余额安全检查(不产生扣费与网络写入)
seal-use test regression --corp <testCorpId> --samples 10 --dry-run
# 2. 正式运行回归测试矩阵并对比决策
seal-use test regression --corp <testCorpId> --samples 10
# 3. 门禁模式(若出现决策翻转则非零退出,适用于自动化脚本)
seal-use test regression --corp <testCorpId> --samples 10 --fail-on-flips
```
> **红线保障**:系统硬性规定回归测试严禁在生产环境发起;且前置计算点数余额,余额不足直接拒绝执行;基于出站 HTTPS 轮询,客户端无公网 IP 亦可稳定工作。
- **方式 B:合思 OpenAPI 模拟任务 (Simulation Create)**:
针对目标真实单据号(或客诉单据)在测试环境发起模拟:
```bash
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>"
```
Seal 服务器会自动使用测试环境中保存的合思凭证,直接调用合思 OpenAPI 拉取单据详情,并通过测试环境中刚发布的规则版本执行 AI 预审判断。
- **方式 C:正式企业审批记录 Webhook 一键重放 (Webhook Replay)**:
直接将正式企业的特定单据/不良案例表单抽取并推送到测试企业 Webhook 通道:
```bash
# 预览重放(自动从绑定正式企业抽取单据、清洗字段类型并输出 Webhook Payload)
seal-use corps replay-test <prodCorpId> --limit 3 --dry-run
# 正式执行重放(支持批量与单号后缀防重)
seal-use corps replay-test <prodCorpId> --limit 3 --sn-suffix '_retest'
# 指定单号精准重放
seal-use corps replay-test <prodCorpId> --sn '<单据号>'
# 跨企业通用重放
seal-use webhook replay --limit 5 --status failed --prod-corp <prodCorpId> --test-corp <testCorpId>
# 未绑定测试企业 / 明确需要重放到生产企业(必须显式指定 --force 覆盖生产保护拦截)
seal-use webhook replay <recordId> --force
```
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
3. **轮询并检查判定结果**:
```bash
+66 -2
View File
@@ -1,12 +1,14 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { exportInsightReportToExcel } from "../../domains/seal/insight-export.js";
import { runTool } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleAnalyticsCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
@@ -26,5 +28,67 @@ export async function handleAnalyticsCommand(
return;
}
if (action === "risks" || action === "risks-by-tag" || action === "tag-risks") {
const tagId = maybeName ?? stringOption(args.options.tagId) ?? stringOption(args.options["tag-id"]);
if (!tagId) {
throw new Error("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
}
await runTool(
"seal_insight_risks_by_tag_get",
client,
corp,
{
tagId,
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"])
},
outputOptions(args.options)
);
return;
}
if (action === "performance" || action === "perf") {
await runTool(
"seal_insight_performance_get",
client,
corp,
{
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]) ?? numberOption(args.options.startDate) ?? numberOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]) ?? numberOption(args.options.endDate) ?? numberOption(args.options["end-date"])
},
outputOptions(args.options)
);
return;
}
if (action === "analyze" || action === "reanalyze") {
const recordId = maybeName ?? stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]);
if (!recordId) {
throw new Error("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
}
await runTool(
"seal_insight_record_analyze",
client,
corp,
{
recordId
},
outputOptions(args.options)
);
return;
}
if (action === "export" || action === "report" || action === "download") {
const result = await exportInsightReportToExcel(client, corp, {
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
limit: numberOption(args.options.limit),
outputFile: stringOption(args.options.out) ?? stringOption(args.options["output-file"]) ?? stringOption(args.options.outputFile),
toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options["to-downloads"])
});
printJson(result);
return;
}
throw new Error(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+15 -3
View File
@@ -10,6 +10,7 @@ import { runTool, runToolResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import { handleWebhookCommand } from "./webhook.js";
export async function handleApprovalRunsCommand(
action: string | undefined,
@@ -18,6 +19,11 @@ export async function handleApprovalRunsCommand(
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "replay") {
await handleWebhookCommand("replay", maybeName, client, corp, args);
return;
}
if (action === "summary") {
const result = await runToolResult(
"seal_approval_runs_summary",
@@ -272,14 +278,20 @@ export async function handleApprovalRunsCommand(
}
if (action === "url") {
const sso = booleanOption(args.options.sso) ?? false;
const expiresIn = numberOption(args.options.expire) ?? numberOption(args.options.expiresIn) ?? 7200;
const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN);
await runTool(
"seal_approval_run_url_get",
client,
corp,
{
recordId: maybeName,
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId)
recordId: maybeName ?? stringOption(args.options.id) ?? stringOption(args.options.recordId),
sourceDocumentSN: sn,
sourceDocumentId: stringOption(args.options.sourceDocumentId),
sso,
expiresIn
},
outputOptions(args.options)
);
+11 -14
View File
@@ -1,7 +1,8 @@
import { getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import type { CorpConfig } from "../../core/config/types.js";
import { createSealClient } from "../../core/http/factory.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { getMe } from "../../domains/seal/api.js";
import { numberOption } from "../parser.js";
import { printJson, redactSensitiveText } from "../printer.js";
@@ -114,12 +115,16 @@ async function diagnoseAuth(corp: CorpConfig) {
: skippedStage("hose.provisional");
stages.push(provisional.public);
const sealCustomHeaders = resolveSealCustomHeaders(corp.seal);
const provisionalToken = provisional.private?.token;
const sealSession = provisionalToken
? await runDiagnoseStage("seal.sso", async () => {
const json = await getJson(
`${sealUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&returnToken=1`
);
const client = createSealClientForUrl(sealUrl, undefined, sealCustomHeaders);
const json = await client
.get(
`api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&returnToken=1`
)
.json<Record<string, unknown>>();
const data = objectValue(json.data);
const token =
stringValue(json.token) ??
@@ -141,9 +146,8 @@ async function diagnoseAuth(corp: CorpConfig) {
const sealToken = sealSession.private?.token;
const whoami = sealToken
? await runDiagnoseStage("seal.whoami", async () => {
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
authorization: `Bearer ${sealToken}`
});
const client = createSealClientForUrl(sealUrl, sealToken, sealCustomHeaders);
const json = await client.get("api/v1/auth/me").json<Record<string, unknown>>();
const data = objectValue(json.data);
const user = objectValue(data.user ?? json.user);
const tenant = objectValue(data.tenant ?? json.tenant);
@@ -231,13 +235,6 @@ async function postJson(url: string, body: Record<string, unknown>): Promise<Rec
return parseJsonResponse(response);
}
async function getJson(url: string, headers: Record<string, string> = {}): Promise<Record<string, unknown>> {
const response = await fetch(url, {
headers
});
return parseJsonResponse(response);
}
async function parseJsonResponse(response: Response): Promise<Record<string, unknown>> {
const body = await response.text();
if (!response.ok) {
+103
View File
@@ -792,6 +792,109 @@ describe("corps list & current", () => {
});
});
describe("corps replay-test", () => {
test("fails if production corp has no bound test corp", async () => {
setupTestEnv();
const result = await runCli(["corps", "replay-test", "corp-test"]);
expect(result.isError).toBe(true);
expect(result.stderr).toContain("has no bound test enterprise");
expect(result.stderr).toContain("seal-use corps bind-test");
});
test("pulls production record and executes dry-run to bound test enterprise", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const mockRun = {
id: "run-prod-001",
sourceSystem: "hosecloud",
sourceDocumentSN: "BX-PROD-001",
sourceDocumentId: "DOC-PROD-001",
document: {
id: "DOC-PROD-001",
sn: "BX-PROD-001",
fields: [{ key: "f1", label: "项目", type: "TEXT", value: "团建" }]
}
};
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals")) {
return jsonResponse({ data: { records: [mockRun] } });
}
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
return jsonResponse({
data: {
integrations: [
{
type: "webhook",
id: "wh-1",
name: "测试通道",
mode: "assisted",
incomingDocumentWebhook: { id: "wh-1", url: "https://test.example/wh" },
outgoingResultWebhook: "https://test.example/out",
incomingManualResultWebhook: { id: "wh-1", url: "https://test.example/manual" },
secret: "sec"
}
]
}
});
}
return jsonResponse({ error: "not found" }, 404);
}) as any;
const result = await runCli(["corps", "replay-test", "corp-prod", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stderr).toContain("正式企业「Acme Production」");
expect(result.stderr).toContain("测试企业「Acme Staging Test」");
const parsed = JSON.parse(result.stdout);
expect(parsed.dryRun).toBe(true);
expect(parsed.sourceCorp.id).toBe("corp-prod");
expect(parsed.targetCorp.id).toBe("corp-test");
expect(parsed.document.documentSN).toBe("BX-PROD-001");
});
test("allows replay within production if --force is explicitly provided even without bound test corp", async () => {
setupTestEnv();
const mockRun = {
id: "run-prod-002",
sourceDocumentSN: "BX-PROD-002",
document: { id: "DOC-002", sn: "BX-PROD-002", fields: [] }
};
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals")) {
return jsonResponse({ data: { records: [mockRun] } });
}
return jsonResponse({
data: {
integrations: [
{
type: "webhook",
id: "wh-prod",
name: "生产通道",
mode: "assisted",
incomingDocumentWebhook: { id: "wh-prod", url: "https://prod.example/wh" }
}
]
}
});
}) as any;
const result = await runCli(["corps", "replay-test", "corp-prod", "--force", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.sourceCorp.id).toBe("corp-prod");
expect(parsed.targetCorp.id).toBe("corp-prod");
});
});
function mockSealSyncRequests(options: {
onMutation?: (method: string, path: string, body?: unknown) => void;
} = {}) {
+297 -2
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../runner.js";
@@ -7,7 +7,8 @@ import { runCli } from "../runner.js";
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
config: process.env.SEAL_USE_CONFIG_FILE,
tokenStore: process.env.SEAL_USE_TOKEN_STORE
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
usageFile: process.env.SEAL_USE_USAGE_FILE
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
@@ -16,6 +17,7 @@ afterEach(() => {
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
@@ -108,6 +110,226 @@ describe("corps link onboarding", () => {
});
});
describe("corp compatibility alias", () => {
test("seal-use corp list executes and resolves cleanly like seal-use corps", async () => {
setupConfigEnv();
const result = await runCli(["corp", "list"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(JSON.parse(result.stdout)).toEqual([]);
});
test("seal-use corp --help executes and resolves cleanly like seal-use corps", async () => {
const result = await runCli(["corp", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use corps - Enterprise and tenant management");
expect(result.stdout).toContain("seal-use corps list");
expect(result.stdout).not.toContain("seal-use webhook");
});
});
describe("corps get and search", () => {
test("corps get retrieves rich details with sensitive secrets safely redacted", async () => {
const enterprises = setupConfigEnv();
mkdirSync(enterprises, { recursive: true });
writeFileSync(
join(enterprises, "demo-hose.json"),
JSON.stringify({
id: "demo-hose",
name: "演示合思企业",
environment: "test",
seal: {
url: "https://demo-hose.sealai.cc",
tenantSlug: "demo-hose",
headers: { "x-custom-env": "staging" }
},
source: {
type: "hose",
domain: "https://dd2.hosecloud.com",
appKey: "myAppKey123456",
appSecurity: "superSecretAppSecurityValue",
corpId: "ID01VAdCnJEdFd",
staffId: "staff-xiezihao"
},
auth: { refreshTtl: 600 },
testCorpId: "demo-hose",
prodCorpId: "demo-prod"
})
);
const result = await runCli(["corps", "get", "demo-hose"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).not.toContain("superSecretAppSecurityValue");
const data = JSON.parse(result.stdout);
expect(data.id).toBe("demo-hose");
expect(data.name).toBe("演示合思企业");
expect(data.environment).toBe("test");
expect(data.configFile).toContain("demo-hose.json");
expect(data.seal.url).toBe("https://demo-hose.sealai.cc");
expect(data.seal.tenantSlug).toBe("demo-hose");
expect(data.seal.customHeaderNames).toEqual(["x-custom-env"]);
expect(data.source.type).toBe("hose");
expect(data.source.corpId).toBe("ID01VAdCnJEdFd");
expect(data.source.staffId).toBe("staff-xiezihao");
expect(data.source.hasAppSecurity).toBe(true);
expect(data.source.appKey).toContain("...");
expect(data.source.appKey).not.toBe("myAppKey123456");
expect(data.relations.prodCorpId).toBe("demo-prod");
expect(data.auth.refreshTtl).toBe(600);
});
test("corps show works as alias for corps get", async () => {
const enterprises = setupConfigEnv();
mkdirSync(enterprises, { recursive: true });
writeFileSync(
join(enterprises, "native-seal.json"),
JSON.stringify({
id: "native-seal",
name: "原生Seal租户",
environment: "production",
seal: {
url: "https://native.sealai.cc",
tenantSlug: "native-slug"
},
source: {
type: "seal",
sealUrl: "https://native.sealai.cc",
token: "veryLongSecretBearerToken1234567890",
expiresIn: 3600,
tenantSlug: "native-slug",
tenantName: "原生租户",
provider: "feishu"
},
auth: { refreshTtl: 300 }
})
);
const result = await runCli(["corps", "show", "native-seal"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).not.toContain("veryLongSecretBearerToken1234567890");
const data = JSON.parse(result.stdout);
expect(data.id).toBe("native-seal");
expect(data.source.type).toBe("seal");
expect(data.source.provider).toBe("feishu");
expect(data.source.hasToken).toBe(true);
expect(data.source.tokenMasked).toContain("...");
});
test("corps search filters across name, staffId, environment, and keywords", async () => {
const enterprises = setupConfigEnv();
mkdirSync(enterprises, { recursive: true });
writeFileSync(
join(enterprises, "corp-prod.json"),
JSON.stringify({
id: "corp-prod",
name: "生产正式企业",
environment: "production",
seal: { url: "https://prod.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key1",
appSecurity: "sec1",
corpId: "PROD001",
staffId: "admin-zhangsan"
},
auth: { refreshTtl: 300 }
})
);
writeFileSync(
join(enterprises, "corp-test.json"),
JSON.stringify({
id: "corp-test",
name: "测试演练企业",
environment: "test",
seal: { url: "https://test.sealai.cc" },
source: {
type: "hose",
domain: "https://dd2.hosecloud.com",
appKey: "key2",
appSecurity: "sec2",
corpId: "TEST002",
staffId: "tester-lisi"
},
auth: { refreshTtl: 300 }
})
);
// Search by name
const searchName = await runCli(["corps", "search", "演练"]);
expect(searchName.exitCode).toBe(0);
const resultsName = JSON.parse(searchName.stdout);
expect(resultsName.length).toBe(1);
expect(resultsName[0].id).toBe("corp-test");
expect(resultsName[0].staffId).toBe("tester-lisi");
// Search by staffId
const searchStaff = await runCli(["corps", "search", "zhangsan"]);
expect(searchStaff.exitCode).toBe(0);
const resultsStaff = JSON.parse(searchStaff.stdout);
expect(resultsStaff.length).toBe(1);
expect(resultsStaff[0].id).toBe("corp-prod");
// Search with --env test
const searchEnv = await runCli(["corps", "search", "--env", "test"]);
expect(searchEnv.exitCode).toBe(0);
const resultsEnv = JSON.parse(searchEnv.stdout);
expect(resultsEnv.length).toBe(1);
expect(resultsEnv[0].id).toBe("corp-test");
// corps find alias
const findResult = await runCli(["corps", "find", "PROD001"]);
expect(findResult.exitCode).toBe(0);
expect(JSON.parse(findResult.stdout).length).toBe(1);
// corps list with query positional arg
const listWithQuery = await runCli(["corps", "list", "演练"]);
expect(listWithQuery.exitCode).toBe(0);
expect(JSON.parse(listWithQuery.stdout).length).toBe(1);
// Soft search by homophone (盛产 -> 生产正式企业)
const softHomophone = await runCli(["corps", "search", "盛产"]);
expect(softHomophone.exitCode).toBe(0);
const softHResults = JSON.parse(softHomophone.stdout);
expect(softHResults.length).toBe(1);
expect(softHResults[0].id).toBe("corp-prod");
// Soft search by initials (sc -> 生产)
const softInitials = await runCli(["corps", "search", "sc"]);
expect(softInitials.exitCode).toBe(0);
const softIResults = JSON.parse(softInitials.stdout);
expect(softIResults.length).toBe(1);
expect(softIResults[0].id).toBe("corp-prod");
// Soft search with missing letter / typo (zhangsa -> admin-zhangsan)
const softTypo = await runCli(["corps", "search", "zhangsa"]);
expect(softTypo.exitCode).toBe(0);
const softTResults = JSON.parse(softTypo.stdout);
expect(softTResults.length).toBe(1);
expect(softTResults[0].id).toBe("corp-prod");
// Strict mode rejects fuzzy matches
const strictFuzzy = await runCli(["corps", "search", "盛产", "--strict"]);
expect(strictFuzzy.exitCode).toBe(0);
expect(JSON.parse(strictFuzzy.stdout).length).toBe(0);
expect(strictFuzzy.stderr).toContain("智能软搜索");
// Strict mode accepts exact substring
const strictExact = await runCli(["corps", "search", "生产", "--strict"]);
expect(strictExact.exitCode).toBe(0);
expect(JSON.parse(strictExact.stdout).length).toBe(1);
});
});
function setupConfigEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-link-cli-"));
const enterprises = join(root, "enterprises");
@@ -195,3 +417,76 @@ function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
describe("corps list sorting and limit", () => {
test("limits output to 10 by default and sorts by 7-day usage frequency", async () => {
const enterprisesDir = setupConfigEnv();
mkdirSync(enterprisesDir, { recursive: true });
const usageDir = mkdtempSync(join(tmpdir(), "seal-usage-test-"));
tempDirs.push(usageDir);
const usageFile = join(usageDir, "usage.json");
process.env.SEAL_USE_USAGE_FILE = usageFile;
// Create 12 corporations: corp-01 to corp-12
for (let i = 1; i <= 12; i++) {
const id = `corp-${String(i).padStart(2, "0")}`;
writeFileSync(
join(enterprisesDir, `${id}.json`),
JSON.stringify({
id,
name: `Enterprise ${id}`,
environment: "production",
seal: { url: `https://${id}.sealai.cc` },
source: {
type: "hose",
domain: "https://dd2.hosecloud.com",
appKey: "key",
appSecurity: "sec",
corpId: id,
staffId: id
},
auth: { refreshTtl: 300 }
})
);
}
// Record usage: corp-05 has 20 hits, corp-02 has 10 hits, corp-11 has 5 hits
const today = new Date().toISOString().slice(0, 10);
writeFileSync(
usageFile,
JSON.stringify({
"corp-05": { [today]: 20 },
"corp-02": { [today]: 10 },
"corp-11": { [today]: 5 }
})
);
// 1. Default list should limit to 10 and show hint in stderr
const defaultList = await runCli(["corps", "list"]);
expect(defaultList.isError).toBe(false);
const defaultItems = JSON.parse(defaultList.stdout);
expect(defaultItems.length).toBe(10);
expect(defaultItems[0].id).toBe("corp-05");
expect(defaultItems[1].id).toBe("corp-02");
expect(defaultItems[2].id).toBe("corp-11");
expect(defaultList.stderr).toContain("当前共有 12 家企业,已按最近 7 天使用频次展示前 10 家");
expect(defaultList.stderr).toContain("seal-use corps list --all");
// 2. --all should output all 12 without truncation
const allList = await runCli(["corps", "list", "--all"]);
expect(allList.isError).toBe(false);
const allItems = JSON.parse(allList.stdout);
expect(allItems.length).toBe(12);
expect(allItems[0].id).toBe("corp-05");
expect(allItems[1].id).toBe("corp-02");
expect(allItems[2].id).toBe("corp-11");
expect(allList.stderr).not.toContain("展示前 10 家");
// 3. Custom --limit should respect given number
const limitedList = await runCli(["corps", "list", "--limit", "3"]);
expect(limitedList.isError).toBe(false);
const limitedItems = JSON.parse(limitedList.stdout);
expect(limitedItems.length).toBe(3);
expect(limitedItems.map((c: any) => c.id)).toEqual(["corp-05", "corp-02", "corp-11"]);
});
});
+274 -26
View File
@@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto";
import { join } from "node:path";
import {
assertHoseAssistTenantMatches,
defaultSealUrl,
exchangeHoseAssistLink,
fetchHoseRoleDefGroups,
fetchHoseRoleStaffs,
@@ -13,14 +14,17 @@ import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
findCorpConfigFile,
loadCorpConfigs,
loadGlobalConfig,
resolveWritableEnterprisesDir,
saveGlobalConfig,
updateCorpConfig
} from "../../core/config/loader.js";
import { filterCorpsFuzzy } from "../../core/search/fuzzy.js";
import { sortCorpsByUsageAndRecency } from "../../core/stats/usage-tracker.js";
import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js";
import type { CorpConfig, CorpEnvironment } from "../../core/config/types.js";
import type { CorpConfig, CorpEnvironment, SealSource } from "../../core/config/types.js";
import * as api from "../../domains/seal/api.js";
import { getMe } from "../../domains/seal/api.js";
import {
@@ -28,6 +32,7 @@ import {
formatSyncVersionName,
saveRuleMappingSnapshot
} from "../../domains/seal/rule-mapping.js";
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../domains/seal/webhook-replay.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { selectCorp } from "../helpers.js";
import { confirmationRequired, usageError } from "../errors.js";
@@ -35,6 +40,7 @@ import {
inferCorpIdFromStaffId,
booleanOption,
jsonObject,
numberOption,
optionalNumber,
optionalString,
requiredString,
@@ -45,25 +51,130 @@ import {
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
function maskSecret(value: string | undefined): string | undefined {
if (!value) return undefined;
if (value.length <= 8) return "****";
return `${value.slice(0, 4)}...${value.slice(-4)}`;
}
function resolveCorpSealUrl(corp: CorpConfig): string | undefined {
if (corp.source.type === "hose") {
return defaultSealUrl(corp, corp.source);
}
return corp.seal.url ?? (corp.source as any).sealUrl;
}
function formatSafeSourceDetail(source: SealSource) {
if (source.type === "hose") {
const key = source.appKey ?? source.key;
return {
type: "hose",
provider: "hosecloud",
domain: source.domain,
corpId: source.corpId,
staffId: source.staffId,
appKey: maskSecret(key),
hasAppSecurity: Boolean(source.appSecurity ?? source.password),
sealUrl: source.sealUrl
};
}
if (source.type === "seal") {
return {
type: "seal",
provider: source.provider ?? "seal",
tenantId: source.tenantId,
tenantSlug: source.tenantSlug,
tenantName: source.tenantName,
providerUserId: source.providerUserId,
staffId: source.staffId,
corpId: source.corpId,
sealUrl: source.sealUrl,
hasToken: Boolean(source.token),
tokenMasked: maskSecret(source.token),
expiresIn: source.expiresIn
};
}
return {
type: "direct",
provider: "direct",
staffId: source.staffId,
corpId: source.corpId,
sealUrl: source.sealUrl,
hasToken: Boolean(source.token),
tokenMasked: maskSecret(source.token),
expiresIn: source.expiresIn
};
}
export async function handleCorpsCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
if (action === "list") {
if (!action || action === "list" || action === "search" || action === "find") {
const rawQuery = (
maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.q)
)?.trim();
const isStrict = booleanOption(args.options.strict) === true;
const envFilter = (
stringOption(args.options.env) ?? stringOption(args.options.environment)
)?.trim().toLowerCase();
if ((action === "search" || action === "find") && !rawQuery && !envFilter) {
throw usageError("Usage: seal-use corps search <query> [--env <production|test>] [--strict]");
}
const corpId = stringOption(args.options.corp);
const corps = loadCorpConfigs();
const allCorps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
const currentCorpId = corpId ?? (
globalConfig.stateful
? globalConfig.defaultCorpId ?? corps[0]?.id
? globalConfig.defaultCorpId ?? allCorps[0]?.id
: undefined
);
if (corps.length === 0) {
console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose 或 seal-use corps add-seal 添加企业,或运行 seal-use help 查看说明。");
let filtered = allCorps;
if (envFilter) {
filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter);
}
printJson(corps.map((item) => ({
if (rawQuery) {
filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict });
}
if (allCorps.length === 0) {
console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose 或 seal-use corps add-seal 添加企业,或运行 seal-use help 查看说明。");
} else if (isStrict && filtered.length === 0 && (action === "search" || action === "find") && rawQuery) {
console.error(`提示:未在严格模式下匹配到企业 "${rawQuery}"。可以尝试省略 --strict 进行智能软搜索。`);
}
const sorted = sortCorpsByUsageAndRecency(filtered, currentCorpId);
const isList = !action || action === "list";
const isAll = booleanOption(args.options.all) === true;
const limitOpt = numberOption(args.options.limit);
const defaultLimit = 10;
const effectiveLimit = limitOpt !== undefined ? Math.max(1, limitOpt) : (isList && !isAll ? defaultLimit : undefined);
let displayList = sorted;
if (effectiveLimit !== undefined && sorted.length > effectiveLimit) {
displayList = sorted.slice(0, effectiveLimit);
if (isList && !isAll && limitOpt === undefined) {
console.error(
`ℹ️ 当前共有 ${sorted.length} 家企业,已按最近 7 天使用频次展示前 ${effectiveLimit} 家。\n` +
`👉 查看全部请添加: seal-use corps list --all\n` +
`👉 检索指定企业请使用: seal-use corps search <keyword>`
);
}
}
printJson(displayList.map((item) => ({
id: item.id,
name: item.name,
environment: item.environment ?? "production",
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
staffId: item.source.staffId,
testCorpId: item.testCorpId,
prodCorpId: item.prodCorpId,
current: item.id === currentCorpId
@@ -71,6 +182,39 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
return;
}
if (action === "get" || action === "show") {
const targetCorpId = maybeName ?? stringOption(args.options.corp);
if (!targetCorpId) {
throw usageError("Usage: seal-use corps get <corpId>");
}
const corp = selectCorp(targetCorpId);
const configFile = findCorpConfigFile(corp.id);
const sealUrl = resolveCorpSealUrl(corp);
printJson({
id: corp.id,
name: corp.name,
environment: corp.environment ?? "production",
configFile,
seal: {
url: sealUrl,
tenantSlug: corp.seal.tenantSlug ?? (corp.source as any).tenantSlug,
customHeaderNames: corp.seal.headers ? Object.keys(corp.seal.headers) : [],
customCookieNames: corp.seal.cookies ? Object.keys(corp.seal.cookies) : [],
endpoints: corp.seal.endpoints
},
source: formatSafeSourceDetail(corp.source),
relations: {
testCorpId: corp.testCorpId,
prodCorpId: corp.prodCorpId
},
auth: {
refreshTtl: corp.auth.refreshTtl
}
});
return;
}
if (action === "current") {
const corp = selectCorp(stringOption(args.options.corp));
printJson({
@@ -79,6 +223,7 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
environment: corp.environment ?? "production",
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type,
staffId: corp.source.staffId,
testCorpId: corp.testCorpId,
prodCorpId: corp.prodCorpId
});
@@ -657,6 +802,124 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
return;
}
if (action === "replay-test") {
const targetCorpId =
maybeName ??
stringOption(args.options.corp) ??
stringOption(args.options.prodCorp) ??
stringOption(args.options["prod-corp"]);
const prodCorp = selectCorp(targetCorpId);
const force = booleanOption(args.options.force) === true;
let testCorp: CorpConfig;
if (!prodCorp.testCorpId) {
if (!force) {
throw usageError(
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` +
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,\n` +
`or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`
);
}
testCorp = prodCorp;
} else {
testCorp = selectCorp(prodCorp.testCorpId);
if (testCorp.environment !== "test" && !force) {
throw new Error(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`
);
}
}
const recordId =
stringOption(args.options.recordId) ??
stringOption(args.options["record-id"]) ??
stringOption(args.options.id);
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
const sn =
stringOption(args.options.sn) ??
stringOption(args.options.documentSn) ??
stringOption(args.options["document-sn"]);
const snsRaw = stringOption(args.options.sns) ?? stringOption(args.options["document-sns"]);
const sns = snsRaw ? snsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
const limit = numberOption(args.options.limit) ?? (!recordId && !recordIds && !sn && !sns ? 1 : undefined);
const status = stringOption(args.options.status);
const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]);
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
const prodClient = await createSealClient(prodCorp);
const testClient = prodCorp.id === testCorp.id ? prodClient : await createSealClient(testCorp);
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const snSuffix = stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]);
const snPrefix = stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]);
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
const query: ReplayRecordsQuery = {
recordId,
recordIds,
sn,
sns,
limit,
status,
startDate,
endDate
};
console.error(
`[corps-replay-test] 正式企业「${prodCorp.name}」(${prodCorp.id}) -> 测试企业「${testCorp.name}」(${testCorp.id})`
);
const result = await executeApprovalRunsReplay({
query,
sourceClient: prodClient,
targetClient: testClient,
sourceCorp: prodCorp,
targetCorp: testCorp,
webhookSelector: selector,
snPrefix,
snSuffix,
docIdPrefix,
docIdSuffix,
dryRun
});
if (dryRun) {
console.error(
`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`
);
console.log(JSON.stringify(result, null, 2));
return;
}
if (result.success) {
if (result.totalCount === 1 && result.replayedDocument) {
console.error(
`🟢 成功重放单据「${result.replayedDocument.documentSN}」至 ${testCorp.name} (${result.targetWebhook?.name ?? "Webhook 通道"})`
);
} else {
console.error(
`🟢 成功重放 ${result.successCount} 条单据(来自「${prodCorp.name}」)至「${testCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})`
);
}
} else {
console.error(
`🔴 单据重放部分或全部失败(成功 ${result.successCount} 条,失败 ${result.failureCount} 条)至「${testCorp.name}」`
);
}
console.error(`👉 Next action: seal-use approval-runs list --corp ${testCorp.id} --limit ${result.totalCount}`);
console.log(JSON.stringify(result, null, 2));
if (!result.success) {
process.exitCode = 1;
}
return;
}
if (action === "switch") {
const corpId = maybeName;
if (!corpId) throw new Error("Usage: seal-use corps switch <corpId>");
@@ -1244,29 +1507,14 @@ async function resolveHoseCorporation(domain: string, appKey: string, appSecurit
}
async function resolveSealWhoami(sealUrl: string, token: string, customHeaders: Record<string, string> = {}) {
const json = await getJson(`${sealUrl}/api/v1/auth/me`, {
...customHeaders,
authorization: `Bearer ${token}`
});
const data = objectValue(json.data);
const client = createSealClientForUrl(sealUrl, token, customHeaders);
const me = await getMe(client);
return {
user: objectValue(data.user ?? json.user),
tenant: objectValue(data.tenant ?? json.tenant)
user: (me.user ?? {}) as Record<string, unknown>,
tenant: (me.tenant ?? {}) as Record<string, unknown>
};
}
async function getJson(url: string, headers: Record<string, string> = {}): Promise<Record<string, unknown>> {
const response = await fetch(url, {
headers
});
const body = await response.text();
if (!response.ok) {
throw new Error(`${response.status} ${body}`);
}
const json = JSON.parse(body) as unknown;
return objectValue(json);
}
function objectValue(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, test } from "bun:test";
import { runCli } from "../runner.js";
describe("seal-use doctor CLI", () => {
test("runs full system diagnosis and outputs JSON to stdout and dashboard to stderr", async () => {
const result = await runCli(["doctor"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
// stdout must be clean, parseable JSON
const data = JSON.parse(result.stdout);
expect(["ok", "warning"]).toContain(data.doctor);
expect(data.runtime).toBeDefined();
expect(data.runtime.version).toBeDefined();
expect(data.directories).toBeDefined();
expect(data.directories.configDir).toBeDefined();
expect(data.enterprises).toBeDefined();
expect(data.knowledge).toBeDefined();
expect(data.knowledge.guideCommand).toBe("seal-use doctor guide");
// stderr must contain human-friendly dashboard
expect(result.stderr).toContain("Seal Use Doctor");
expect(result.stderr).toContain("【运行环境】");
expect(result.stderr).toContain("【核心路径状态】");
});
test("doctor guide dumps embedded documentation in Markdown", async () => {
const result = await runCli(["doctor", "guide"]);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("# Seal Use 系统架构与运行规范白皮书");
expect(result.stdout).toContain("系统目录全景规范");
expect(result.stdout).toContain("安全与数据隐私保证");
expect(result.stderr).toContain("纯内存只读");
});
test("doctor paths outputs compact directory specifications JSON", async () => {
const result = await runCli(["doctor", "paths"]);
expect(result.exitCode).toBe(0);
const paths = JSON.parse(result.stdout);
expect(paths.configDir).toBeDefined();
expect(paths.enterprisesDir).toBeDefined();
expect(paths.tokenStore).toBeDefined();
expect(paths.agentSkillDir).toBeDefined();
});
});
+64
View File
@@ -0,0 +1,64 @@
import { diagnoseSystem, formatDoctorDashboard } from "../../core/doctor/diagnose.js";
import { getEmbeddedGuideMarkdown } from "../../core/doctor/knowledge.js";
import { booleanOption } from "../parser.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleDoctorCommand(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
) {
const subAction = (action ?? maybeName ?? "").toLowerCase();
// 1. Output embedded guide / documentation
if (subAction === "guide" || subAction === "doc" || subAction === "knowledge" || subAction === "book") {
console.error("📖 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...\n");
console.log(getEmbeddedGuideMarkdown());
return;
}
// 2. Output compact directory specifications
if (subAction === "paths" || subAction === "dirs" || subAction === "directories") {
const diagnosis = diagnoseSystem();
printJson(diagnosis.directories);
return;
}
// 3. Output tenant-level health contract and quota diagnosis
if (subAction === "tenant" || subAction === "corp" || subAction === "enterprise") {
const { selectCorp } = await import("../helpers.js");
const { createSealClient } = await import("../../core/http/factory.js");
const { stringOption } = await import("../parser.js");
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../core/doctor/tenant-diagnose.js");
const corpSelector =
stringOption(args.options.corp) ??
(maybeName && maybeName !== subAction ? maybeName : undefined) ??
(args.command[2] && args.command[2] !== subAction ? args.command[2] : undefined);
const corp = selectCorp(corpSelector);
const client = await createSealClient(corp);
const diagnosis = await diagnoseTenantContract(client, corp);
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
if (!isQuiet) {
console.error(formatTenantDoctorDashboard(diagnosis));
}
printJson(diagnosis);
return;
}
// 3. Default: Full system diagnostic inspection
const diagnosis = diagnoseSystem();
// If quiet or json-only is not explicitly disabled, output formatted dashboard on stderr
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
if (!isQuiet) {
console.error(formatDoctorDashboard(diagnosis));
}
// Machine channel (stdout): clean, structured JSON
printJson(diagnosis);
}
+17 -1
View File
@@ -1,6 +1,11 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js";
import {
listAvailableLinters,
PRIMARY_LINTERS_DIR,
OFFICIAL_LINTERS_DIR
} from "../../domains/seal/linter/index.js";
import { runTool, runToolResult } from "../helpers.js";
import { confirmationRequired } from "../errors.js";
import {
@@ -215,6 +220,17 @@ export async function handleRulesCommand(
return;
}
if (action === "linters" || action === "linter-list") {
const linters = listAvailableLinters();
printJson({
primaryDirectory: PRIMARY_LINTERS_DIR,
officialDirectory: OFFICIAL_LINTERS_DIR,
totalLinters: linters.length,
linters
}, outputOptions(args.options));
return;
}
if (action === "map") {
const versionSelector = stringOption(args.options.version) ?? maybeName;
const code = stringOption(args.options.code) ?? stringOption(args.options.rule);
@@ -243,5 +259,5 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push, map. Run 'seal-use help' for available commands.`);
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, linters, pull, push, map. Run 'seal-use help' for available commands.`);
}
+231
View File
@@ -0,0 +1,231 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { CorpConfig } from "../../core/config/types.js";
import { runCli } from "../runner.js";
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
config: process.env.SEAL_USE_CONFIG_FILE,
tokenStore: process.env.SEAL_USE_TOKEN_STORE
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
const mockApprovalRuns = [
{
id: "run-001",
status: "completed",
sourceSystem: "hosecloud",
sourceDocumentSN: "BX9990001",
sourceDocumentId: "DOC-999",
createdAt: 1789115000000,
result: { decision: "APPROVE", summary: "合规通过" },
document: {
id: "DOC-999",
sn: "BX9990001",
fields: [
{ key: "cost_type", label: "费用类型", type: "TEXT", value: "打车" },
{ key: "amount", label: "金额", type: "AMOUNT", value: { amount: 120 } }
]
}
},
{
id: "run-002",
status: "completed",
sourceSystem: "hosecloud",
sourceDocumentSN: "BX9990002",
sourceDocumentId: "DOC-998",
createdAt: 1789115100000,
result: { decision: "REJECT", summary: "超标" },
document: {
id: "DOC-998",
sn: "BX9990002",
fields: [
{ key: "cost_type", label: "费用类型", type: "TEXT", value: "住宿" },
{ key: "amount", label: "金额", type: "AMOUNT", value: { amount: 800 } }
]
}
}
];
function setupTestEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-test-cli-"));
const enterprises = join(root, "enterprises");
mkdirSync(enterprises, { recursive: true });
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
const prodCorp: CorpConfig = {
id: "corp-prod",
name: "生产企业",
environment: "production",
testCorpId: "corp-test",
seal: {
url: "https://acme-prod.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "prod-token",
sealUrl: "https://acme-prod.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
const testCorp: CorpConfig = {
id: "corp-test",
name: "测试靶场企业",
environment: "test",
prodCorpId: "corp-prod",
seal: {
url: "https://acme-test.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "test-token",
sealUrl: "https://acme-test.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
const unpairedCorp: CorpConfig = {
id: "corp-unpaired",
name: "未配对企业",
environment: "production",
seal: {
url: "https://acme-unpaired.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "unpaired-token",
sealUrl: "https://acme-unpaired.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "corp-prod.json"), JSON.stringify(prodCorp, null, 2));
writeFileSync(join(enterprises, "corp-test.json"), JSON.stringify(testCorp, null, 2));
writeFileSync(join(enterprises, "corp-unpaired.json"), JSON.stringify(unpairedCorp, null, 2));
writeFileSync(
join(root, "config.json"),
JSON.stringify({ defaultCorpId: "corp-prod", stateful: true }, null, 2)
);
return { root, enterprises, prodCorp, testCorp, unpairedCorp };
}
function mockApiFetch() {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (url.includes("/api/v1/billing/status")) {
return new Response(
JSON.stringify({
data: {
features: [
{
code: "ai-approval",
balance: 5000,
deductionAmount: 100
}
]
}
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
if (url.includes("/api/v1/approvals")) {
return new Response(
JSON.stringify({
data: {
records: mockApprovalRuns,
total: mockApprovalRuns.length
}
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
}
describe("seal-use test regression CLI", () => {
test("fails with exit code 2 when unknown subaction is requested", async () => {
setupTestEnv();
const result = await runCli(["test", "invalid-action"]);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("未知的 test 子命令");
});
test("rejects when production enterprise has no bound test enterprise", async () => {
setupTestEnv();
const result = await runCli(["test", "regression", "--corp", "corp-unpaired"]);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("未绑定测试靶场企业");
expect(result.stderr).toContain("硬性规定:回归测试严禁在生产环境直接运行");
});
test("executes dry-run regression preview on paired test enterprise", async () => {
setupTestEnv();
mockApiFetch();
const result = await runCli(["test", "regression", "--corp", "corp-test", "--samples", "2", "--dry-run"]);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout);
expect(payload.ok).toBe(true);
expect(payload.verdict).toBe("DRY_RUN");
expect(payload.safeToPublish).toBe(true);
expect(payload.metrics.sampleCount).toBe(2);
expect(payload.sourceCorp.id).toBe("corp-prod");
expect(payload.targetCorp.id).toBe("corp-test");
expect(payload.records.length).toBe(2);
expect(result.stderr).toContain("规则回归测试矩阵");
expect(result.stderr).toContain("DRY-RUN");
});
test("corps regression alias routes to test regression command", async () => {
setupTestEnv();
mockApiFetch();
const result = await runCli(["corps", "regression", "--corp", "corp-test", "--samples", "2", "--dry-run"]);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout);
expect(payload.verdict).toBe("DRY_RUN");
expect(payload.targetCorp.id).toBe("corp-test");
});
});
+113
View File
@@ -0,0 +1,113 @@
import { CliError } from "../errors.js";
import { selectCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import { createSealClient } from "../../core/http/factory.js";
import {
formatRegressionDashboard,
runRegressionTest
} from "../../domains/seal/regression/service.js";
export async function handleTestCommand(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
) {
const subAction = (action ?? maybeName ?? "regression").toLowerCase();
if (subAction === "regression" || subAction === "regress" || subAction === "matrix") {
const corpSelector =
stringOption(args.options.corp) ??
(maybeName && maybeName !== subAction ? maybeName : undefined);
const baseCorp = selectCorp(corpSelector);
let sourceCorp = baseCorp;
let targetCorp = baseCorp;
if (baseCorp.environment === "test") {
targetCorp = baseCorp;
const sourceCorpId =
stringOption(args.options["prod-corp"]) ??
stringOption(args.options["prod"]) ??
baseCorp.prodCorpId;
if (!sourceCorpId) {
throw new CliError(
`测试企业「${baseCorp.name}」(${baseCorp.id}) 未绑定生产母企业,无法拉取历史样本。\n` +
`请建立绑定或通过 --prod-corp 参数指定生产企业来源。`,
2,
`seal-use corps bind-test <prodCorpId> ${baseCorp.id}`
);
}
sourceCorp = selectCorp(sourceCorpId);
} else {
sourceCorp = baseCorp;
const targetCorpId =
stringOption(args.options["test-corp"]) ??
stringOption(args.options["test"]) ??
baseCorp.testCorpId;
if (!targetCorpId) {
throw new CliError(
`生产企业「${baseCorp.name}」(${baseCorp.id}) 未绑定测试靶场企业。\n` +
`硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。`,
2,
`seal-use corps bind-test ${baseCorp.id} <testCorpId>`
);
}
targetCorp = selectCorp(targetCorpId);
}
const sourceClient = await createSealClient(sourceCorp);
const targetClient = await createSealClient(targetCorp);
const samples =
numberOption(args.options.samples) ??
numberOption(args.options.limit) ??
numberOption(args.options.n) ??
10;
const dryRun = booleanOption(args.options["dry-run"]);
const failOnFlips = booleanOption(args.options["fail-on-flips"]);
const pollIntervalMs = numberOption(args.options["poll-interval"]) ?? 2000;
const timeoutMs = numberOption(args.options.timeout) ?? 45000;
const snPrefix = stringOption(args.options["sn-prefix"]) ?? "REG_";
const result = await runRegressionTest({
sourceCorp,
targetCorp,
sourceClient,
targetClient,
samples,
dryRun,
pollIntervalMs,
timeoutMs,
snPrefix,
failOnFlips
});
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
if (!isQuiet) {
console.error(formatRegressionDashboard(result));
}
// Machine channel (stdout): clean, structured JSON
printJson(result);
if (failOnFlips && !result.ok) {
throw new CliError(
`回归测试发现 ${result.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,
1
);
}
return;
}
throw new CliError(
`未知的 test 子命令: "${subAction}"。\n可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,
2,
"seal-use test regression --help"
);
}
+429
View File
@@ -0,0 +1,429 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../runner.js";
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
config: process.env.SEAL_USE_CONFIG_FILE,
tokenStore: process.env.SEAL_USE_TOKEN_STORE
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
}
function setupMockEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-replay-cli-"));
const enterprises = join(root, "enterprises");
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
// Create enterprises dir
const fs = require("node:fs");
fs.mkdirSync(enterprises, { recursive: true });
// Write test enterprise config
const corpConfig = {
id: "test-corp-replay",
name: "测试企业重放",
environment: "test",
sourceType: "seal",
seal: {
url: "https://test-replay.sealai.cc",
tenantSlug: "test-replay",
endpoints: {
approvalStylePreferences: "api/v1/system/preferences/approval-style",
sourceStatus: "api/v1/source/status",
token: "api/v1/auth/token"
}
},
source: {
type: "seal",
token: "mock-token-xyz",
sealUrl: "https://test-replay.sealai.cc"
}
};
writeFileSync(join(enterprises, "test-corp-replay.json"), JSON.stringify(corpConfig, null, 2));
// Write global config
writeFileSync(
join(root, "config.json"),
JSON.stringify({ defaultCorpId: "test-corp-replay", stateful: true }, null, 2)
);
return enterprises;
}
const mockApprovalRun = {
id: "run-001",
status: "completed",
sourceSystem: "hosecloud",
sourceDocumentSN: "BX9990001",
sourceDocumentId: "DOC-999",
createdAt: 1789115000000,
document: {
id: "DOC-999",
sn: "BX9990001",
fields: [
{ key: "cost_type", label: "费用类型", type: "TEXT", value: "打车" },
{ key: "amount", label: "金额", type: "AMOUNT", value: { amount: 120 } },
{ key: "ref_doc", label: "关联申请", type: "REFERENCE", value: "SQ001" }
]
}
};
const mockWebhookIntegrations = [
{
type: "webhook",
id: "wh-integration-1",
name: "默认重放通道",
mode: "assisted",
incomingDocumentWebhook: {
id: "wh_endpoint_1",
url: "https://test-replay.sealai.cc/api/v1/integrations/webhook/wh_endpoint_1/document"
},
outgoingResultWebhook: "https://example.com/result",
incomingManualResultWebhook: {
id: "wh_endpoint_1",
url: "https://test-replay.sealai.cc/api/v1/integrations/webhook/wh_endpoint_1/manual-result"
},
secret: "mock-secret-456"
}
];
describe("seal-use webhook replay CLI", () => {
test("fails with usage error if neither recordId nor sn is provided", async () => {
setupMockEnv();
const result = await runCli(["webhook", "replay"]);
expect(result.isError).toBe(true);
expect(result.stderr).toContain("Usage: seal-use webhook replay");
});
test("executes dry-run preview and strips unallowed types like REFERENCE", async () => {
setupMockEnv();
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals/run-001")) {
return new Response(JSON.stringify({ data: mockApprovalRun }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
return new Response(
JSON.stringify({
data: { integrations: mockWebhookIntegrations }
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
const result = await runCli([
"webhook",
"replay",
"run-001",
"--dry-run",
"--sn-suffix",
"_replay"
]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stderr).toContain("预览模式");
const parsed = JSON.parse(result.stdout);
expect(parsed.dryRun).toBe(true);
expect(parsed.originalRecord.sourceDocumentSN).toBe("BX9990001");
expect(parsed.document.documentSN).toBe("BX9990001_replay");
expect(parsed.document.documentId).toBe("DOC-999_replay");
// REFERENCE must be normalized to TEXT
const refField = parsed.document.fields.find((f: any) => f.key === "ref_doc");
expect(refField.type).toBe("TEXT");
});
test("executes live webhook replay with successful response", async () => {
setupMockEnv();
let pushedBody: any = null;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals/run-001")) {
return new Response(JSON.stringify({ data: mockApprovalRun }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
return new Response(
JSON.stringify({
data: { integrations: mockWebhookIntegrations }
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
if (requestUrl.includes("/integrations/webhook/wh_endpoint_1/document")) {
let rawBody = init?.body;
if (typeof rawBody !== "string" && typeof input === "object" && "text" in input) {
rawBody = await (input as Request).clone().text();
}
pushedBody = JSON.parse(String(rawBody));
return new Response(
JSON.stringify({ data: { success: true, documentId: "spawned-run-doc-123" } }),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
const result = await runCli(["webhook", "replay", "run-001"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
expect(result.stderr).toContain("成功重放单据");
const parsed = JSON.parse(result.stdout);
expect(parsed.success).toBe(true);
expect(parsed.pushResult.data.success).toBe(true);
expect(pushedBody.documentSN).toBe("BX9990001");
});
test("approval-runs replay routes to webhook replay", async () => {
setupMockEnv();
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals/run-001")) {
return new Response(JSON.stringify({ data: mockApprovalRun }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
return new Response(
JSON.stringify({
data: { integrations: mockWebhookIntegrations }
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
const result = await runCli(["approval-runs", "replay", "run-001", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.dryRun).toBe(true);
});
test("executes batch replay with --limit 2", async () => {
setupMockEnv();
const mockRuns = [
mockApprovalRun,
{
...mockApprovalRun,
id: "run-002",
sourceDocumentSN: "BX9990002",
document: {
id: "DOC-998",
sn: "BX9990002",
fields: [{ key: "f1", label: "项目", type: "TEXT", value: "差旅" }]
}
}
];
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals")) {
return new Response(JSON.stringify({ data: { records: mockRuns } }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
return new Response(
JSON.stringify({
data: { integrations: mockWebhookIntegrations }
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
const result = await runCli(["webhook", "replay", "--limit", "2", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.dryRun).toBe(true);
expect(parsed.totalCount).toBe(2);
expect(parsed.records.length).toBe(2);
expect(parsed.records[0].document.documentSN).toBe("BX9990001");
expect(parsed.records[1].document.documentSN).toBe("BX9990002");
});
test("auto-infers bound test enterprise when running from production enterprise", async () => {
const enterprises = setupMockEnv();
// Create production corp bound to test-corp-replay
const prodCorpConfig = {
id: "prod-corp-main",
name: "正式生产企业",
environment: "production",
sourceType: "seal",
testCorpId: "test-corp-replay",
seal: {
url: "https://prod-main.sealai.cc",
tenantSlug: "prod-main",
endpoints: {
approvalStylePreferences: "api/v1/system/preferences/approval-style",
sourceStatus: "api/v1/source/status",
token: "api/v1/auth/token"
}
},
source: {
type: "seal",
token: "prod-token-123",
sealUrl: "https://prod-main.sealai.cc"
}
};
writeFileSync(join(enterprises, "prod-corp-main.json"), JSON.stringify(prodCorpConfig, null, 2));
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals/run-001")) {
return new Response(JSON.stringify({ data: mockApprovalRun }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
return new Response(
JSON.stringify({
data: { integrations: mockWebhookIntegrations }
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
// Running with --corp prod-corp-main: source should be prod, target auto-inferred as test-corp-replay
const result = await runCli(["webhook", "replay", "run-001", "--corp", "prod-corp-main", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.sourceCorp.id).toBe("prod-corp-main");
expect(parsed.targetCorp.id).toBe("test-corp-replay");
});
test("blocks replay targeting production enterprise unless --force is specified", async () => {
const enterprises = setupMockEnv();
const prodCorpConfig = {
id: "prod-corp-target",
name: "生产目标企业",
environment: "production",
sourceType: "seal",
seal: {
url: "https://prod-target.sealai.cc",
tenantSlug: "prod-target",
endpoints: {
approvalStylePreferences: "api/v1/system/preferences/approval-style",
sourceStatus: "api/v1/source/status",
token: "api/v1/auth/token"
}
},
source: {
type: "seal",
token: "prod-token-xyz",
sealUrl: "https://prod-target.sealai.cc"
}
};
writeFileSync(join(enterprises, "prod-corp-target.json"), JSON.stringify(prodCorpConfig, null, 2));
// Target is prod-corp-target without --force
const blockedResult = await runCli([
"webhook",
"replay",
"run-001",
"--target-corp",
"prod-corp-target",
"--dry-run"
]);
expect(blockedResult.isError).toBe(true);
expect(blockedResult.exitCode).toBe(1);
expect(blockedResult.stderr).toContain("标记为生产正式环境");
// With --force
globalThis.fetch = (async (input: RequestInfo | URL) => {
const requestUrl =
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (requestUrl.includes("/api/v1/approvals/run-001")) {
return new Response(JSON.stringify({ data: mockApprovalRun }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
if (requestUrl.includes("api/v1/system/preferences/approval-style")) {
return new Response(
JSON.stringify({
data: { integrations: mockWebhookIntegrations }
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as any;
const forceResult = await runCli([
"webhook",
"replay",
"run-001",
"--target-corp",
"prod-corp-target",
"--force",
"--dry-run"
]);
expect(forceResult.isError).toBe(false);
expect(forceResult.exitCode).toBe(0);
const parsed = JSON.parse(forceResult.stdout);
expect(parsed.targetCorp.id).toBe("prod-corp-target");
});
});
+129 -3
View File
@@ -1,10 +1,17 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { createSealClient as createNewSealClient } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { existsSync } from "node:fs";
import { runTool } from "../helpers.js";
import { runTool, selectCorp } from "../helpers.js";
import * as api from "../../domains/seal/api.js";
import { findWebhookIntegration } from "../../domains/seal/api.js";
import type { WebhookIntegration } from "../../domains/seal/types.js";
import type { ApprovalRun, WebhookIntegration } from "../../domains/seal/types.js";
import {
executeApprovalRunsReplay,
resolveReplayCorpPair,
type ReplayRecordsQuery
} from "../../domains/seal/webhook-replay.js";
import {
checkWebhookReadiness,
previewMaterialPack,
@@ -14,6 +21,7 @@ import {
import {
booleanOption,
materialPackFilePolicyOptions,
numberOption,
parseWebhookMode,
stringOption,
webhookRateOption,
@@ -76,6 +84,123 @@ export async function handleWebhookCommand(
return;
}
if (action === "replay") {
const recordId =
maybeName ??
stringOption(args.options.recordId) ??
stringOption(args.options["record-id"]) ??
stringOption(args.options.id);
const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]);
const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
const sn =
stringOption(args.options.sn) ??
stringOption(args.options.documentSn) ??
stringOption(args.options["document-sn"]);
const snsRaw = stringOption(args.options.sns) ?? stringOption(args.options["document-sns"]);
const sns = snsRaw ? snsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined;
const limit = numberOption(args.options.limit);
const status = stringOption(args.options.status);
const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]);
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
if (!recordId && !recordIds && !sn && !sns && limit === undefined) {
throw new Error(
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]"
);
}
const sourceCorpId =
stringOption(args.options.sourceCorp) ??
stringOption(args.options["source-corp"]) ??
stringOption(args.options.prodCorp) ??
stringOption(args.options["prod-corp"]);
const targetCorpId =
stringOption(args.options.targetCorp) ??
stringOption(args.options["target-corp"]) ??
stringOption(args.options.testCorp) ??
stringOption(args.options["test-corp"]);
const force = booleanOption(args.options.force) === true;
const { sourceCorp, targetCorp } = resolveReplayCorpPair(
{
sourceCorpId,
targetCorpId,
activeCorp: corp,
force
},
selectCorp
);
const sourceClient = sourceCorp.id === corp.id ? client : await createNewSealClient(sourceCorp);
const targetClient = targetCorp.id === corp.id ? client : await createNewSealClient(targetCorp);
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const snSuffix = stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]);
const snPrefix = stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]);
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
const query: ReplayRecordsQuery = {
recordId,
recordIds,
sn,
sns,
limit,
status,
startDate,
endDate
};
const result = await executeApprovalRunsReplay({
query,
sourceClient,
targetClient,
sourceCorp,
targetCorp,
webhookSelector: selector,
snPrefix,
snSuffix,
docIdPrefix,
docIdSuffix,
dryRun
});
if (dryRun) {
console.error(
`[webhook-replay] 预览模式:已成功从 ${sourceCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`
);
console.log(JSON.stringify(result, null, 2));
return;
}
if (result.success) {
if (result.totalCount === 1 && result.replayedDocument) {
console.error(
`🟢 成功重放单据「${result.replayedDocument.documentSN}」至 ${targetCorp.name} (${result.targetWebhook?.name ?? "Webhook 通道"})`
);
} else {
console.error(
`🟢 成功重放 ${result.successCount} 条单据(来自「${sourceCorp.name}」)至「${targetCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})`
);
}
} else {
console.error(
`🔴 单据重放部分或全部失败(成功 ${result.successCount} 条,失败 ${result.failureCount} 条)至「${targetCorp.name}」`
);
}
console.error(`👉 Next action: seal-use approval-runs list --corp ${targetCorp.id} --limit ${result.totalCount}`);
console.log(JSON.stringify(result, null, 2));
if (!result.success) {
process.exitCode = 1;
}
return;
}
if (action === "material-pack" || action === "material-pack-push") {
const operation = action === "material-pack-push" ? "push" : maybeName;
const filePath = action === "material-pack-push"
@@ -110,7 +235,8 @@ export async function handleWebhookCommand(
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret,
materialPackFilePolicy: integration.materialPackFilePolicy
materialPackFilePolicy: integration.materialPackFilePolicy,
customHeaders: resolveSealCustomHeaders(corp.seal)
});
console.log(JSON.stringify(result, null, 2));
return;
+38
View File
@@ -119,6 +119,44 @@ describe("CLI help execution via runCli", () => {
expect(result.stdout).not.toContain("seal-use simulation");
});
test("seal-use corp --help resolves to corps domain commands with exitCode 0", async () => {
const result = await runCli(["corp", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use corps - Enterprise and tenant management");
expect(result.stdout).toContain("seal-use corps list");
expect(result.stdout).toContain("seal-use corps bind-test");
expect(result.stdout).not.toContain("seal-use webhook");
expect(result.stdout).not.toContain("seal-use simulation");
});
test("seal-use webhook replay --help renders replay usage and options with exitCode 0", async () => {
const result = await runCli(["webhook", "replay", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use webhook replay");
expect(result.stdout).toContain("--sn-suffix");
expect(result.stdout).toContain("--dry-run");
});
test("seal-use approval-runs replay --help renders replay usage and options with exitCode 0", async () => {
const result = await runCli(["approval-runs", "replay", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use approval-runs replay");
expect(result.stdout).toContain("--sn-suffix");
expect(result.stdout).toContain("--dry-run");
});
test("seal-use corps replay-test --help renders replay-test usage and options with exitCode 0", async () => {
const result = await runCli(["corps", "replay-test", "--help"]);
expect(result.exitCode).toBe(0);
expect(result.isError).toBe(false);
expect(result.stdout).toContain("seal-use corps replay-test");
expect(result.stdout).toContain("--sn-suffix");
expect(result.stdout).toContain("--dry-run");
});
test("seal-use corps unknown-cmd --help exits with code 2", async () => {
const result = await runCli(["corps", "unknown-cmd", "--help"]);
expect(result.exitCode).toBe(2);
+199 -6
View File
@@ -30,8 +30,32 @@ export const HELP_REGISTRY: AreaHelp[] = [
commands: [
{
name: "list",
summary: "List all configured enterprises",
usage: ["seal-use corps list [--corp <corpId>]"]
summary: "List configured enterprises sorted by 7-day usage frequency",
usage: ["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],
options: [
{ flag: "--all", description: "Display all configured enterprises without the default 10-item limit" },
{ flag: "--limit <n>", description: "Maximum number of enterprises to display (defaults to 10)" },
{ flag: "--env <production|test>", description: "Filter enterprises by environment ('production' or 'test')" },
{ flag: "--strict", description: "Use strict exact substring matching instead of default soft fuzzy search" }
]
},
{
name: "search",
aliases: ["find"],
summary: "Search configured enterprises with intelligent soft fuzzy matching",
usage: ["seal-use corps search <query> [--env <production|test>] [--strict]"],
options: [
{ flag: "--env <production|test>", description: "Filter enterprises by environment ('production' or 'test')" },
{ flag: "--strict", description: "Use strict exact substring matching instead of default soft fuzzy search" }
],
description: "Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."
},
{
name: "get",
aliases: ["show"],
summary: "Get rich details and configuration of an enterprise",
usage: ["seal-use corps get <corpId>"],
description: "Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."
},
{
name: "current",
@@ -89,6 +113,24 @@ export const HELP_REGISTRY: AreaHelp[] = [
],
description: "Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new version on the test enterprise. Production rules remain safe in draft state."
},
{
name: "replay-test",
summary: "Replay approval records from production enterprise to bound test enterprise via Webhook",
usage: [
"seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--webhook <idOrName>] [--dry-run]"
],
options: [
{ flag: "<prodCorpId>", description: "Production enterprise ID (default: active enterprise)" },
{ flag: "--record-id <id>", description: "Replay a specific approval run ID" },
{ flag: "--sn <sn>", description: "Replay a specific document SN" },
{ flag: "--limit <n>", description: "Batch replay latest N records from production (default: 1)" },
{ flag: "--status <status>", description: "Filter records by status (e.g. completed, failed, rejected)" },
{ flag: "--webhook <idOrName>", description: "Target Webhook integration on test enterprise" },
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
{ flag: "--dry-run", description: "Preview payload without sending" }
],
description: "Pulls production approval records from the production enterprise and replays them into the bound test enterprise's Webhook channel for rule verification."
},
{
name: "add-hose",
summary: "Add a Hose/Ekuaibao enterprise configuration",
@@ -103,6 +145,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "add-link",
summary: "Import enterprise configuration from a Hose assistance link",
usage: ["seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]"]
},
{
name: "regression",
aliases: ["test-regression"],
summary: "Run automated rule regression test matrix against paired test enterprise",
usage: ["seal-use corps regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]"],
options: [
{ flag: "--samples <N>", description: "Number of historical production runs to replay (default: 10)" },
{ flag: "--dry-run", description: "Preview sample documents and verify quota without executing replayed audits" },
{ flag: "--fail-on-flips", description: "Exit with non-zero code if any decision flip is detected" }
]
}
]
},
@@ -160,6 +213,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
summary: "Lint rule text or rule file using builtin or custom linter",
usage: ["seal-use rules lint [--file <path>] [--linter <name|path>] [--min-score <score>] [--corp <corpId>]"]
},
{
name: "linters",
summary: "List available official and custom rule linters and directory locations",
usage: ["seal-use rules linters [--corp <corpId>]"]
},
{
name: "pull",
summary: "Export rules to local JSON file",
@@ -222,6 +280,28 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "material-pack push",
summary: "Upload and push a material pack to webhook endpoint",
usage: ["seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]"]
},
{
name: "replay",
usage: [
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
"seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
],
options: [
{ flag: "<recordId>", description: "Approval run record ID to replay" },
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN if recordId not given" },
{ flag: "--limit <n>", description: "Batch replay latest N records from source enterprise" },
{ flag: "--status <status>", description: "Filter records by status (e.g. completed, failed, rejected)" },
{ flag: "--webhook <idOrName>", description: "Target Webhook integration (auto-locks if only one exists)" },
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside (alias: --prod-corp)" },
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed (alias: --test-corp)" },
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN and documentId" },
{ flag: "--sn-prefix <str>", description: "Optional prefix prepended to documentSN and documentId" },
{ flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" },
{ flag: "--force", description: "Allow replaying to a production enterprise" }
],
description: "Extracts structured form fields from historical approval records (Webhook or Hose source), sanitizes field types, and pushes documents to the target Webhook channel. Automatically infers 1-to-1 bound test/production enterprise pairs."
}
]
},
@@ -291,17 +371,38 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "url",
summary: "Get web console URL for approval run",
summary: "Get web console URL for approval run (default deep link, or --sso for auto-login link)",
usage: [
"seal-use approval-runs url [--corp <corpId>]",
"seal-use approval-runs url <recordId> [--corp <corpId>]",
"seal-use approval-runs url --sourceDocumentSN B26022501 [--corp <corpId>]"
"seal-use approval-runs url <recordId> --sso [--expire 7200] [--corp <corpId>]",
"seal-use approval-runs url --sn <documentSN> [--sso] [--corp <corpId>]",
"seal-use approval-runs url [--corp <corpId>]"
]
},
{
name: "bridge",
summary: "Inspect browser bridge integration payload",
usage: ["seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp <corpId>]"]
},
{
name: "replay",
summary: "Replay approval run record into a Webhook integration",
usage: [
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
],
options: [
{ flag: "<recordId>", description: "Approval run record ID" },
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
{ flag: "--limit <n>", description: "Batch replay latest N records" },
{ flag: "--status <status>", description: "Filter records by status" },
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside" },
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed" },
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
{ flag: "--dry-run", description: "Preview payload without sending" }
]
}
]
},
@@ -669,8 +770,40 @@ export const HELP_REGISTRY: AreaHelp[] = [
commands: [
{
name: "insight",
summary: "Query AI audit insights and trends",
aliases: ["insight-stats", "stats"],
summary: "Query AI audit insights risk-tag statistics and analysis status",
usage: ["seal-use analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]"]
},
{
name: "risks",
aliases: ["risks-by-tag", "tag-risks"],
summary: "Query detailed risks and document citations under a specific risk tag",
usage: ["seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]"]
},
{
name: "performance",
aliases: ["perf"],
summary: "Query audit performance metrics (accuracy, automation rate) and Sankey flow",
usage: ["seal-use analytics performance [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--corp <corpId>]"]
},
{
name: "analyze",
aliases: ["reanalyze"],
summary: "Trigger on-demand smart insight risk analysis for an approval record",
usage: ["seal-use analytics analyze <recordId> [--corp <corpId>]"]
},
{
name: "export",
aliases: ["report", "download"],
summary: "Export smart insights risk report to high-fidelity Excel workbook",
usage: ["seal-use analytics export [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]"],
options: [
{ flag: "--downloads", description: "Save directly to the user's Downloads directory" },
{ flag: "--out <file>", description: "Custom destination file path" },
{ flag: "--start-date <ISO>", description: "Filter beginning time range" },
{ flag: "--end-date <ISO>", description: "Filter ending time range" },
{ flag: "--limit <n>", description: "Maximum risk tags to drill down into" }
]
}
]
},
@@ -864,6 +997,65 @@ export const HELP_REGISTRY: AreaHelp[] = [
usage: ["seal-use openapi"]
}
]
},
{
area: "doctor",
title: "System diagnostic and environment health check",
description: "Inspects runtime executable, filesystem paths, enterprise assets, and embedded specifications without modifying any files.",
commands: [
{
name: "",
summary: "Run complete system diagnostic health check",
usage: ["seal-use doctor [--quiet]"],
options: [
{ flag: "--quiet", description: "Suppress formatted human dashboard on stderr" }
]
},
{
name: "guide",
aliases: ["doc", "knowledge"],
summary: "Read embedded system architecture & directory specification whitepaper",
usage: ["seal-use doctor guide"]
},
{
name: "paths",
aliases: ["dirs"],
summary: "Inspect core filesystem paths and directory health",
usage: ["seal-use doctor paths"]
},
{
name: "tenant",
aliases: ["corp", "enterprise"],
summary: "Inspect tenant-level health contract, auth permissions, AI approval quota, and rules state",
usage: ["seal-use doctor tenant [--corp <corpId>] [--quiet]"],
options: [
{ flag: "--corp <corpId>", description: "Enterprise ID or selector to diagnose" },
{ flag: "--quiet", description: "Suppress formatted dashboard on stderr" }
]
}
]
},
{
area: "test",
title: "Automated test harnesses and rule regression matrix",
description: "Run automated regression tests and decision comparison matrix across paired production and test environments.",
commands: [
{
name: "regression",
aliases: ["regress", "matrix"],
summary: "Run automated rule regression test matrix against paired test enterprise",
usage: ["seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]"],
options: [
{ flag: "--corp <corpId>", description: "Target test enterprise or production parent (must be paired)" },
{ flag: "--samples <N>", description: "Number of historical production runs to replay (default: 10)" },
{ flag: "--dry-run", description: "Preview sample documents and verify quota without executing replayed audits" },
{ flag: "--fail-on-flips", description: "Exit with non-zero code if any decision flip is detected" },
{ flag: "--prod-corp <id>", description: "Explicit production enterprise source for sample documents" },
{ flag: "--test-corp <id>", description: "Explicit test enterprise target for replay" },
{ flag: "--quiet", description: "Suppress formatted summary dashboard on stderr" }
]
}
]
}
];
@@ -924,6 +1116,7 @@ export function renderHelp(target: string[] = []): string {
function normalizeArea(area: string): string {
const lower = area.toLowerCase();
if (lower === "corp") return "corps";
if (lower === "webhooks") return "webhook";
if (lower === "preferences") return "preference";
if (lower === "changelog") return "update";
+4 -1
View File
@@ -1,5 +1,6 @@
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig, resolveGlobalConfigFile } from "../core/config/loader.js";
import { resolveCorpConfig } from "../core/config/manager.js";
import { recordCorpUsage } from "../core/stats/usage-tracker.js";
import { createSealClient } from "../core/http/factory.js";
import { sealTools, type SealTool } from "../domains/seal/tools.js";
import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
@@ -9,7 +10,7 @@ import type { OutputOptions } from "./types.js";
export function selectCorp(corpId?: string): CorpConfig {
const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
return resolveCorpConfig(
const corp = resolveCorpConfig(
corps,
{
stateful: globalConfig.stateful,
@@ -18,6 +19,8 @@ export function selectCorp(corpId?: string): CorpConfig {
},
getEnterprisesDirCandidates()
);
recordCorpUsage(corp.id);
return corp;
}
export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) {
+22 -3
View File
@@ -16,6 +16,7 @@ import { handleContextCommand } from "./commands/context.js";
import { handleCorpsCommand } from "./commands/corps.js";
import { handleDelegationCommand, handleDelegationFromHoseLink } from "./commands/delegation.js";
import { handleDeployCommand } from "./commands/deploy.js";
import { handleDoctorCommand } from "./commands/doctor.js";
import { handleHttpCommand } from "./commands/http.js";
import { handleLlmCommand } from "./commands/llm.js";
import { handleMcpCommand, printMcpConfig } from "./commands/mcp.js";
@@ -28,6 +29,7 @@ import { handleServiceCommand } from "./commands/service.js";
import { handleSimulationCommand } from "./commands/simulation.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleSourceCommand } from "./commands/source.js";
import { handleTestCommand } from "./commands/test.js";
import { handleToolCommand } from "./commands/tool.js";
import { handleToolsListCommand } from "./commands/tools.js";
import { handleUpdateCommand } from "./commands/update.js";
@@ -62,6 +64,7 @@ export const KNOWN_AREAS = new Set([
"update",
"tools",
"corps",
"corp",
"tool",
"source",
"auth",
@@ -88,7 +91,9 @@ export const KNOWN_AREAS = new Set([
"skill",
"openapi",
"probe",
"changelog"
"doctor",
"changelog",
"test"
]);
export type { CliResult, CliRunOptions } from "./types.js";
@@ -220,6 +225,16 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "doctor") {
await handleDoctorCommand(action, maybeName, args);
return;
}
if (area === "test") {
await handleTestCommand(action, maybeName, args);
return;
}
if (area === "config") {
handleConfigCommand(action, maybeName, args);
return;
@@ -274,7 +289,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "corps") {
if (area === "corps" || area === "corp") {
if (action === "regression" || action === "test-regression") {
await handleTestCommand("regression", maybeName, args);
return;
}
await handleCorpsCommand(action, maybeName, args);
return;
}
@@ -371,7 +390,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
}
if (area === "analytics") {
await handleAnalyticsCommand(action, client, corp, args);
await handleAnalyticsCommand(action, maybeName, client, corp, args);
return;
}
+27 -9
View File
@@ -1,5 +1,7 @@
import ky, { HTTPError, KyInstance } from "ky";
import { CorpConfig, HoseSealSource } from "../config/types.js";
import { createSealClientForUrl } from "../http/factory.js";
import { resolveSealCustomHeaders } from "../http/request-headers.js";
import { getHoseAuthCache, setHoseAuthCache } from "./token-store.js";
import { SealEnterpriseConfig, SealSession, TokenEntry } from "./types.js";
@@ -154,17 +156,18 @@ export function parseHoseAssistLink(value: string): HoseAssistLink {
}
export async function exchangeHoseAssistLink(
value: string | HoseAssistLink
value: string | HoseAssistLink,
options?: { customHeaders?: Record<string, string> }
): Promise<HoseAssistSealSession> {
const link = typeof value === "string" ? parseHoseAssistLink(value) : normalizeHoseAssistLink(value);
const sealUrl = `https://${link.corpId}.sealai.cc`;
const sealResponse = await ky
.get(`${sealUrl}/api/auth/oauth2/session/oem-hosecloud`, {
const sealClient = createSealClientForUrl(sealUrl, undefined, options?.customHeaders);
const sealResponse = await sealClient
.get("api/auth/oauth2/session/oem-hosecloud", {
searchParams: {
token: link.accessToken,
returnToken: "1"
},
timeout: 30000
}
})
.json<SealTokenResponse>();
@@ -401,12 +404,25 @@ export async function getHoseProvisionalAuthLink(
corpId: string;
staffId: string;
url: string;
token?: string;
expiresIn: number;
}> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const cache = getHoseAuthCache(corp.id);
if (isFresh(cache.closeapi) && cache.closeapi.url && cache.closeapi.token) {
const remainingSeconds = Math.max(60, Math.floor((cache.closeapi.expiresAt - Date.now()) / 1000));
return {
corpId: corp.source.corpId,
staffId: corp.source.staffId,
url: cache.closeapi.url,
token: cache.closeapi.token,
expiresIn: Math.min(expiresIn, remainingSeconds)
};
}
const openapiToken = await ensureHoseOpenapiToken(corp);
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn);
if (!provisional.url) {
@@ -417,6 +433,7 @@ export async function getHoseProvisionalAuthLink(
corpId: corp.source.corpId,
staffId: corp.source.staffId,
url: provisional.url,
token: provisional.token,
expiresIn
};
}
@@ -428,14 +445,15 @@ export async function getHoseSealSession(corp: CorpConfig): Promise<SealSession>
const hoseAccess = await ensureHoseCloseApiToken(corp);
const sealUrl = defaultSealUrl(corp, corp.source);
const customHeaders = resolveSealCustomHeaders(corp.seal);
const sealClient = createSealClientForUrl(sealUrl, undefined, customHeaders);
const sealResponse = await ky
.get(`${normalizeBaseUrl(sealUrl)}/api/auth/oauth2/session/oem-hosecloud`, {
const sealResponse = await sealClient
.get("api/auth/oauth2/session/oem-hosecloud", {
searchParams: {
token: hoseAccess.token,
returnToken: "1"
},
timeout: 30000
}
})
.json<SealTokenResponse>();
+7
View File
@@ -85,6 +85,13 @@ describe("resolveCorpConfig", () => {
).id).toBe("corp-b");
});
test("resolves an explicit corp case-insensitively and by enterprise name", () => {
const corpA = { ...corp("corp-a"), name: "Alpha Corp" };
const corpB = { ...corp("corp-b"), name: "Beta Corp" };
expect(resolveCorpConfig([corpA, corpB], { stateful: false, corpId: "CORP-B" }).id).toBe("corp-b");
expect(resolveCorpConfig([corpA, corpB], { stateful: false, corpId: "alpha corp" }).id).toBe("corp-a");
});
test("resolves the configured default corp in stateful mode", () => {
expect(resolveCorpConfig(
[corp("corp-a"), corp("corp-b")],
+6 -2
View File
@@ -12,8 +12,12 @@ export function resolveCorpConfig(
const selectedCorpId = requestedCorpId ?? configuredCorpId;
if (selectedCorpId) {
const corp = corps.find((item) => item.id === selectedCorpId);
if (corp) return corp;
const exact = corps.find((item) => item.id === selectedCorpId);
if (exact) return exact;
const caseInsensitive = corps.find((item) => item.id.toLowerCase() === selectedCorpId.toLowerCase());
if (caseInsensitive) return caseInsensitive;
const byName = corps.find((item) => item.name.toLowerCase() === selectedCorpId.toLowerCase());
if (byName) return byName;
throw new Error(`No enterprise config found for ${selectedCorpId}`);
}
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, test } from "bun:test";
import { VERSION } from "../../version.js";
import { diagnoseSystem, formatDoctorDashboard } from "./diagnose.js";
import {
EMBEDDED_DIRECTORY_SPECS,
EMBEDDED_DOMAIN_CAPABILITIES,
EMBEDDED_SECURITY_POLICIES,
getEmbeddedGuideMarkdown
} from "./knowledge.js";
describe("Doctor Embedded Knowledge", () => {
test("EMBEDDED_DIRECTORY_SPECS defines core paths", () => {
expect(EMBEDDED_DIRECTORY_SPECS.length).toBeGreaterThanOrEqual(8);
const names = EMBEDDED_DIRECTORY_SPECS.map((s) => s.name);
expect(names).toContain("配置与状态根目录");
expect(names).toContain("企业配置文件目录");
expect(names).toContain("全局命令行程序");
expect(names).toContain("AI Agent 技能主目录");
});
test("EMBEDDED_SECURITY_POLICIES contains core privacy guarantees", () => {
expect(EMBEDDED_SECURITY_POLICIES.length).toBeGreaterThanOrEqual(3);
const topics = EMBEDDED_SECURITY_POLICIES.map((p) => p.topic);
expect(topics).toContain("敏感凭据脱敏保护");
expect(topics).toContain("正式环境与测试环境严格隔离");
});
test("EMBEDDED_DOMAIN_CAPABILITIES covers main CLI areas", () => {
const domains = EMBEDDED_DOMAIN_CAPABILITIES.map((d) => d.domain);
expect(domains.some((d) => d.startsWith("corps"))).toBe(true);
expect(domains.some((d) => d.startsWith("approval-runs"))).toBe(true);
expect(domains.some((d) => d.startsWith("rules"))).toBe(true);
expect(domains.some((d) => d.startsWith("doctor"))).toBe(true);
});
test("getEmbeddedGuideMarkdown renders complete Markdown documentation", () => {
const md = getEmbeddedGuideMarkdown();
expect(md).toContain("# Seal Use 系统架构与运行规范白皮书");
expect(md).toContain("系统目录全景规范");
expect(md).toContain("安全与数据隐私保证");
expect(md).toContain("业务域能力图谱");
expect(md).toContain("seal-use doctor guide");
});
});
describe("Doctor Diagnosis Engine", () => {
test("diagnoseSystem returns valid read-only diagnostic object without throwing", () => {
const diagnosis = diagnoseSystem();
expect(["ok", "warning"]).toContain(diagnosis.doctor);
expect(diagnosis.runtime.version).toBe(VERSION);
expect(diagnosis.runtime.executablePath.length).toBeGreaterThan(0);
expect(diagnosis.runtime.platform.length).toBeGreaterThan(0);
expect(diagnosis.directories.configDir).toBeDefined();
expect(diagnosis.directories.configDir!.path).toContain(".config");
expect(diagnosis.directories.enterprisesDir).toBeDefined();
expect(diagnosis.directories.agentSkillDir).toBeDefined();
expect(diagnosis.checks.length).toBeGreaterThanOrEqual(3);
expect(diagnosis.knowledge.directorySpecsCount).toBe(EMBEDDED_DIRECTORY_SPECS.length);
});
test("formatDoctorDashboard renders human-readable summary dashboard", () => {
const diagnosis = diagnoseSystem();
const dashboard = formatDoctorDashboard(diagnosis);
expect(dashboard).toContain("Seal Use Doctor");
expect(dashboard).toContain("【运行环境】");
expect(dashboard).toContain("【核心路径状态】");
expect(dashboard).toContain("【企业资产概览】");
expect(dashboard).toContain("【健康自检】");
expect(dashboard).toContain("seal-use doctor guide");
});
});
+341
View File
@@ -0,0 +1,341 @@
import { accessSync, constants, existsSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../../domains/seal/linter/loader.js";
import { VERSION } from "../../version.js";
import { loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
import { getDefaultGlobalSkillDir } from "../embedded-skill.js";
import {
EMBEDDED_DIRECTORY_SPECS,
EMBEDDED_DOMAIN_CAPABILITIES,
EMBEDDED_SECURITY_POLICIES
} from "./knowledge.js";
export interface DirectoryHealth {
name: string;
path: string;
exists: boolean;
writable?: boolean;
fileCount?: number;
description: string;
}
export interface HealthCheckItem {
id: string;
title: string;
status: "ok" | "warn" | "error";
message: string;
}
export interface DoctorDiagnosis {
doctor: "ok" | "warning";
timestamp: string;
runtime: {
version: string;
executablePath: string;
platform: string;
engine: string;
};
directories: Record<string, DirectoryHealth>;
enterprises: {
total: number;
productionCount: number;
testCount: number;
activeCorpId?: string;
activeCorpName?: string;
};
checks: HealthCheckItem[];
knowledge: {
summary: string;
directorySpecsCount: number;
securityPoliciesCount: number;
domainCapabilitiesCount: number;
guideCommand: string;
};
}
function countJsonFiles(dir: string): number {
if (!existsSync(dir)) return 0;
try {
return readdirSync(dir).filter((file) => file.endsWith(".json")).length;
} catch {
return 0;
}
}
function isPathWritable(path: string): boolean {
try {
accessSync(path, constants.W_OK);
return true;
} catch {
return false;
}
}
/**
* Pure, read-only system diagnostic and health inspection.
* Never creates, mutates, or deletes any files on the filesystem.
*/
export function diagnoseSystem(): DoctorDiagnosis {
const home = homedir();
const configDir = join(home, ".config", "seal-use");
const enterprisesDir = join(configDir, "enterprises");
const globalConfigFile = join(configDir, "config.json");
const tokenStore = join(configDir, "seal_tokens.json");
const mappingsDir = join(configDir, "mappings");
const agentSkillDir = getDefaultGlobalSkillDir();
const exportDir = join(home, "Downloads");
const globalBinaryCandidates = [
"/opt/homebrew/bin/seal-use",
"/usr/local/bin/seal-use",
join(home, ".local", "bin", "seal-use"),
join(home, "bin", "seal-use")
];
const detectedBinary = globalBinaryCandidates.find((p) => existsSync(p)) ?? process.execPath;
const directories: Record<string, DirectoryHealth> = {
configDir: {
name: "配置根目录",
path: configDir,
exists: existsSync(configDir),
writable: existsSync(configDir) ? isPathWritable(configDir) : false,
description: "用户持久化配置与企业状态根目录"
},
enterprisesDir: {
name: "企业配置目录",
path: enterprisesDir,
exists: existsSync(enterprisesDir),
writable: existsSync(enterprisesDir) ? isPathWritable(enterprisesDir) : false,
fileCount: countJsonFiles(enterprisesDir),
description: "企业连接配置(JSON)保存路径"
},
globalConfigFile: {
name: "全局配置文件",
path: globalConfigFile,
exists: existsSync(globalConfigFile),
description: "全局工作模式与默认企业配置"
},
tokenStore: {
name: "凭据缓存",
path: tokenStore,
exists: existsSync(tokenStore),
description: "会话凭据与令牌缓存"
},
mappingsDir: {
name: "规则版本映射快照",
path: mappingsDir,
exists: existsSync(mappingsDir),
fileCount: countJsonFiles(mappingsDir),
description: "生产与测试规则版本映射对照表"
},
agentSkillDir: {
name: "AI Agent 技能目录",
path: agentSkillDir,
exists: existsSync(join(agentSkillDir, "SKILL.md")),
description: "本地 Agent 技能主目录"
},
exportDefaultDir: {
name: "报表默认导出目录",
path: exportDir,
exists: existsSync(exportDir),
writable: existsSync(exportDir) ? isPathWritable(exportDir) : false,
description: "审核大盘报表默认写入目录"
},
lintersDir: {
name: "规则校验器目录 (用户自定义)",
path: PRIMARY_LINTERS_DIR,
exists: existsSync(PRIMARY_LINTERS_DIR),
writable: existsSync(PRIMARY_LINTERS_DIR) ? isPathWritable(PRIMARY_LINTERS_DIR) : false,
description: "用户私有规则校验脚本存放目录"
},
officialLintersDir: {
name: "官方内置规则校验器目录",
path: OFFICIAL_LINTERS_DIR,
exists: existsSync(OFFICIAL_LINTERS_DIR),
description: "官方标准与严格风控校验脚本目录 (系统自动保护与重写)"
},
globalBinary: {
name: "全局命令行二进制",
path: detectedBinary,
exists: existsSync(detectedBinary),
description: "系统全局命令执行入口"
}
};
// Safe read of loaded corps without side-effects
let corps: ReturnType<typeof loadCorpConfigs> = [];
try {
corps = loadCorpConfigs();
} catch {
corps = [];
}
const globalConfig = loadGlobalConfig();
const currentCorpId = globalConfig.defaultCorpId ?? corps[0]?.id;
const currentCorp = corps.find((c) => c.id === currentCorpId);
const testCount = corps.filter((c) => (c.environment ?? "production").toLowerCase() === "test").length;
const prodCount = corps.length - testCount;
// Build health checks
const checks: HealthCheckItem[] = [];
// Check 1: Executable
checks.push({
id: "executable",
title: "命令行二进制",
status: "ok",
message: `当前执行路径: ${process.execPath}`
});
// Check 2: Config Directory
if (directories.configDir?.exists && directories.configDir.writable) {
checks.push({
id: "config_dir",
title: "配置目录访问",
status: "ok",
message: `${configDir} (正常读写)`
});
} else if (directories.configDir?.exists) {
checks.push({
id: "config_dir",
title: "配置目录访问",
status: "warn",
message: `${configDir} (存在但可能不可写)`
});
} else {
checks.push({
id: "config_dir",
title: "配置目录访问",
status: "warn",
message: `未检测到配置目录 ${configDir},首次运行配置命令时将自动创建`
});
}
// Check 3: Enterprises Configured
if (corps.length > 0) {
checks.push({
id: "enterprises",
title: "企业接入状态",
status: "ok",
message: `已接入 ${corps.length} 家企业 (正式: ${prodCount}, 测试: ${testCount})`
});
} else {
checks.push({
id: "enterprises",
title: "企业接入状态",
status: "warn",
message: "当前未检测到企业配置,请使用 seal-use corps add-hose 或 add-seal 接入企业"
});
}
// Check 4: Agent Skill
if (directories.agentSkillDir?.exists) {
checks.push({
id: "agent_skill",
title: "AI Agent 技能",
status: "ok",
message: `已就绪于 ${agentSkillDir}`
});
} else {
checks.push({
id: "agent_skill",
title: "AI Agent 技能",
status: "warn",
message: `未在 ${agentSkillDir} 检测到技能,可运行 'seal-use skill sync' 安装`
});
}
const hasWarning = checks.some((c) => c.status === "warn" || c.status === "error");
const engine = typeof (globalThis as any).Bun !== "undefined"
? `Bun ${(globalThis as any).Bun.version}`
: `Node ${process.version}`;
return {
doctor: hasWarning ? "warning" : "ok",
timestamp: new Date().toISOString(),
runtime: {
version: VERSION,
executablePath: process.execPath,
platform: `${process.platform} (${process.arch})`,
engine
},
directories,
enterprises: {
total: corps.length,
productionCount: prodCount,
testCount,
activeCorpId: currentCorp?.id,
activeCorpName: currentCorp?.name
},
checks,
knowledge: {
summary: "内嵌系统架构与目录规范白皮书(纯内存只读,零写入依赖)",
directorySpecsCount: EMBEDDED_DIRECTORY_SPECS.length,
securityPoliciesCount: EMBEDDED_SECURITY_POLICIES.length,
domainCapabilitiesCount: EMBEDDED_DOMAIN_CAPABILITIES.length,
guideCommand: "seal-use doctor guide"
}
};
}
/**
* Formats a terminal-friendly, human-readable diagnostic dashboard for stderr.
*/
export function formatDoctorDashboard(diagnosis: DoctorDiagnosis): string {
const lines: string[] = [];
const symbol = diagnosis.doctor === "ok" ? "✨" : "⚠️";
lines.push(`🩺 [Seal Use Doctor] 系统健康诊断看板 ${symbol}`);
lines.push("─────────────────────────────────────────────────────────────");
// Runtime section
lines.push("【运行环境】");
lines.push(` 版本号: ${diagnosis.runtime.version}`);
lines.push(` 程序路径: ${diagnosis.runtime.executablePath}`);
lines.push(` 操作系统: ${diagnosis.runtime.platform}`);
lines.push(` 执行引擎: ${diagnosis.runtime.engine}`);
lines.push("");
// Directory section
lines.push("【核心路径状态】");
for (const [, dir] of Object.entries(diagnosis.directories)) {
const icon = dir.exists ? "✓" : "○";
const statusText = dir.exists
? dir.fileCount !== undefined
? `(${dir.fileCount} 个文件)`
: dir.writable
? "(就绪/可写)"
: "(存在)"
: "(未创建)";
lines.push(` ${icon} ${dir.name.padEnd(16, " ")}: ${dir.path} ${statusText}`);
}
lines.push("");
// Enterprise section
lines.push("【企业资产概览】");
lines.push(` 接入企业总计: ${diagnosis.enterprises.total} 家 (生产: ${diagnosis.enterprises.productionCount}, 测试: ${diagnosis.enterprises.testCount})`);
if (diagnosis.enterprises.activeCorpId) {
lines.push(` 当前激活企业: ${diagnosis.enterprises.activeCorpName} (${diagnosis.enterprises.activeCorpId})`);
} else {
lines.push(" 当前激活企业: 无默认企业 (无状态模式)");
}
lines.push("");
// Health checks section
lines.push("【健康自检】");
for (const c of diagnosis.checks) {
const icon = c.status === "ok" ? "✓" : c.status === "warn" ? "⚠️" : "✗";
lines.push(` ${icon} [${c.title}]: ${c.message}`);
}
lines.push("");
// Next steps hint
lines.push("─────────────────────────────────────────────────────────────");
lines.push("👉 查阅内嵌白皮书与目录规范: seal-use doctor guide");
lines.push("👉 检索企业: seal-use corps search <keyword>");
return lines.join("\n");
}
+240
View File
@@ -0,0 +1,240 @@
/**
* Embedded System Knowledge & Architectural Specifications
*
* This file contains static, read-only documentation and system contracts
* bundled directly into the standalone binary. It requires zero network access
* and performs zero disk writes.
*/
export interface DirectorySpec {
name: string;
category: "config" | "binary" | "skill" | "export" | "temp";
standardPath: string;
purpose: string;
accessMode: "read-write" | "executable" | "transient";
retention: "persistent" | "cache" | "ephemeral";
}
export interface SecurityPolicySpec {
topic: string;
guarantee: string;
enforcement: string;
}
export interface DomainCapabilitySpec {
domain: string;
summary: string;
primaryCommands: string[];
}
export const EMBEDDED_DIRECTORY_SPECS: DirectorySpec[] = [
{
name: "配置与状态根目录",
category: "config",
standardPath: "~/.config/seal-use",
purpose: "用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "企业配置文件目录",
category: "config",
standardPath: "~/.config/seal-use/enterprises",
purpose: "存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "全局配置文件",
category: "config",
standardPath: "~/.config/seal-use/config.json",
purpose: "维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "会话凭据安全缓存",
category: "config",
standardPath: "~/.config/seal-use/seal_tokens.json",
purpose: "缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",
accessMode: "read-write",
retention: "cache"
},
{
name: "规则版本映射快照",
category: "config",
standardPath: "~/.config/seal-use/mappings",
purpose: "存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "后台守护服务日志",
category: "config",
standardPath: "~/.config/seal-use/service.log",
purpose: "常驻后台 HTTP 服务守护进程运行输出日志。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "全局命令行程序",
category: "binary",
standardPath: "/opt/homebrew/bin/seal-use",
purpose: "macOS / Linux 全局独立单文件二进制程序;附带软链接 seal-home -> seal-use 兼容旧指令。",
accessMode: "executable",
retention: "persistent"
},
{
name: "AI Agent 技能主目录",
category: "skill",
standardPath: "~/.agents/skills/seal-use",
purpose: "面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "报表默认导出目录",
category: "export",
standardPath: "~/Downloads",
purpose: "执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",
accessMode: "read-write",
retention: "persistent"
},
{
name: "系统隔离临时目录",
category: "temp",
standardPath: "/tmp 或 /var/folders/.../T",
purpose: "自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",
accessMode: "transient",
retention: "ephemeral"
}
];
export const EMBEDDED_SECURITY_POLICIES: SecurityPolicySpec[] = [
{
topic: "敏感凭据脱敏保护",
guarantee: "appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",
enforcement: "CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"
},
{
topic: "正式环境与测试环境严格隔离",
guarantee: "正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",
enforcement: "corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"
},
{
topic: "跨环境规则同步安全基线",
guarantee: "corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",
enforcement: "规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"
},
{
topic: "只读诊断无副作用原则",
guarantee: "doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",
enforcement: "核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"
}
];
export const EMBEDDED_DOMAIN_CAPABILITIES: DomainCapabilitySpec[] = [
{
domain: "corps (企业管理)",
summary: "多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同步",
primaryCommands: ["corps list", "corps search <query>", "corps get <corpId>", "corps mark", "corps bind-test", "corps sync-test"]
},
{
domain: "approval-runs (审核大盘)",
summary: "AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、免登 SSO 深度链接",
primaryCommands: ["approval-runs list", "approval-runs stats", "approval-runs get", "approval-runs export", "approval-runs url"]
},
{
domain: "rules (规则治理)",
summary: "审核规则拉取、本地 Lint 质量检查、增量差量推送、离线版本与编号对照映射速查",
primaryCommands: ["rules pull", "rules lint", "rules push", "rules map", "rules count"]
},
{
domain: "preference (决策偏好)",
summary: "AI 审核偏好读取与更新、全局与分品类思考深度策略(medium/high)配置",
primaryCommands: ["preference get", "preference decision update", "preference thinking-depth set"]
},
{
domain: "simulation (模拟演练)",
summary: "合思单据指定、材料包导入、飞书/泛微三方审批定义演练、批次轮询等待与数据清理",
primaryCommands: ["simulation create", "simulation status", "simulation wait", "simulation clean"]
},
{
domain: "webhook (通道与重放)",
summary: "Webhook 回调通道配置、材料包校验推送、线上单据向 Webhook 通道测试重放",
primaryCommands: ["webhook list", "webhook add", "webhook replay", "webhook material-pack push"]
},
{
domain: "deploy (费控集成)",
summary: "Seal AI 智能审核能力发布到合思费控企业、对接要求检测与配置同步",
primaryCommands: ["deploy hosecloud requirements", "deploy hosecloud status", "deploy hosecloud sync"]
},
{
domain: "doctor (系统诊断)",
summary: "整机环境健康自检、目录全景体检看板、内置架构与规范白皮书离线查阅",
primaryCommands: ["doctor", "doctor guide", "doctor paths"]
}
];
/**
* Generates the full formatted embedded documentation in Markdown.
*/
export function getEmbeddedGuideMarkdown(): string {
return `# Seal Use 系统架构与运行规范白皮书
> 本文档由 \`seal-use\` 单文件二进制程序内嵌提供,纯内存只读,未向用户电脑写入任何临时文件。
---
## 1. 系统定位与设计哲学
\`seal-use\` 是合思与 Seal AI 体系的企业级智能审核、规则治理与模拟演练 CLI 工具包,兼具人类工程师命令行使用与 AI Agent Harness 自动化集成能力。
### 核心交互契约
- **机器通道 (\`stdout\`)**:所有命令默认在标准输出返回干净、严格类型化的 JSON 载荷,供自动化脚本及 AI Agent 解析。
- **指导与诊断通道 (\`stderr\`)**:标准错误专用于输出运行状态、网络探测日志、自愈指引以及显式的下一步动作建议(如 \`👉 Next action: seal-use ...\`)。
- **退出码契约**:成功为 \`0\`,参数校验失败、未确认拦截或上游 API 报错均赋予非零退出码(如 \`1\`、\`2\`、\`10\`),杜绝盲目吞错。
---
## 2. 系统目录全景规范
\`seal-use\` 在用户计算机上的所有文件访问严格收敛于以下明确定义的目录中:
| 目录名称 | 类别 | 规范路径 | 作用与生命周期 |
| :--- | :--- | :--- | :--- |
${EMBEDDED_DIRECTORY_SPECS.map(
(s) => `| **${s.name}** | \`${s.category}\` | \`${s.standardPath}\` | ${s.purpose} (${s.retention}) |`
).join("\n")}
---
## 3. 安全与数据隐私保证
${EMBEDDED_SECURITY_POLICIES.map(
(p, idx) => `### 3.${idx + 1} ${p.topic}
- **安全承诺**:${p.guarantee}
- **实现约束**:${p.enforcement}
`
).join("\n")}
---
## 4. 业务域能力图谱
${EMBEDDED_DOMAIN_CAPABILITIES.map(
(c) => `### \`seal-use ${c.domain}\`
* **能力定位**:${c.summary}
* **核心命令**:${c.primaryCommands.map((cmd) => `\`seal-use ${cmd}\``).join("、")}
`
).join("\n")}
---
## 5. 快速排错与健康诊断指引
- **环境自检**:运行 \`seal-use doctor\`,一键检查当前运行时版本、本地目录健康度、企业资产接入数量以及守护服务状态。
- **查看企业配置源文件**:运行 \`seal-use corps get <corpId>\`,可直接查看指定企业的本地 JSON 存储绝对路径。
- **查阅完整操作手册**:运行 \`seal-use doctor guide\` 随时在离线状态下查看本文档。
`;
}
+158
View File
@@ -0,0 +1,158 @@
import { describe, expect, test } from "bun:test";
import { diagnoseTenantContract, formatTenantDoctorDashboard } from "./tenant-diagnose.js";
import type { CorpConfig } from "../config/types.js";
function createMockClient(opts: {
whoami?: any;
billing?: any;
rules?: any;
webhooks?: any;
}) {
return {
get: async (url: string) => {
if (url === "api/v1/auth/me") {
return {
json: async () => ({
code: 0,
data: opts.whoami ?? {
user: { id: "u_admin", tenantId: "t_1", name: "Admin", isAdmin: true, permissions: ["*"] },
tenant: { id: "t_1", name: "Test Corp", tenantSlug: "testcorp" }
}
})
};
}
if (url === "api/v1/billing/status") {
return {
json: async () => ({
code: 0,
data: opts.billing ?? {
features: [
{ code: "ai-approval", balance: 5000, deductionAmount: 100 },
{ code: "approval-rules", quota: 100, used: 10, remaining: 90 }
]
}
})
};
}
if (url === "api/v1/rules") {
return {
json: async () => ({
code: 0,
data: opts.rules ?? {
rules: [
{ id: "r1", description: "Rule 1", scope: "all", strictness: "MUST_FOLLOW", status: "ACTIVE" },
{ id: "r2", description: "Rule 2", scope: "all", strictness: "SUGGESTION", status: "DISABLED" }
]
}
})
};
}
if (url === "api/v1/agent/ai-approval/config" || url === "api/v1/integrations/webhook") {
return {
json: async () => ({
code: 0,
data: {
integrations: opts.webhooks ?? [
{
type: "webhook",
id: "wh_1",
name: "回放测试通道",
mode: "assisted",
incomingDocumentWebhook: { id: "in_1", url: "https://test.com/in" },
outgoingResultWebhook: "https://test.com/out",
incomingManualResultWebhook: { id: "manual_1", url: "https://test.com/manual" },
secret: "sec_123"
}
]
}
})
};
}
throw new Error(`Unhandled mock GET url: ${url}`);
}
} as any;
}
describe("tenant-diagnose", () => {
test("diagnoses a healthy test tenant with sufficient quota and bindings", async () => {
const mockClient = createMockClient({});
const testCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
environment: "test",
prodCorpId: "prod-corp",
source: { type: "seal" },
seal: { url: "https://test.sealai.cc" }
} as any;
const result = await diagnoseTenantContract(mockClient, testCorp);
expect(result.ok).toBe(true);
expect(result.verdict).toBe("HEALTHY");
expect(result.quota.balance).toBe(5000);
expect(result.quota.estimatedRuns).toBe(50);
expect(result.quota.status).toBe("sufficient");
expect(result.rules.totalCount).toBe(2);
expect(result.rules.activeCount).toBe(1);
expect(result.webhooks.hasReplayChannel).toBe(true);
expect(result.summary.failedChecks).toBe(0);
const dashboard = formatTenantDoctorDashboard(result);
expect(dashboard).toContain("HEALTHY");
expect(dashboard).toContain("5000");
});
test("flags warning for low quota and unbound prod corp", async () => {
const mockClient = createMockClient({
billing: {
features: [
{ code: "ai-approval", balance: 500, deductionAmount: 100 }
]
},
rules: { rules: [] }
});
const unboundProdCorp: CorpConfig = {
id: "prod-corp",
name: "未绑定生产企业",
environment: "production",
source: { type: "seal" },
seal: { url: "https://prod.sealai.cc" }
} as any;
const result = await diagnoseTenantContract(mockClient, unboundProdCorp);
expect(result.ok).toBe(true);
expect(result.verdict).toBe("DEGRADED");
expect(result.quota.estimatedRuns).toBe(5);
expect(result.quota.status).toBe("low");
expect(result.rules.totalCount).toBe(0);
expect(result.summary.warningChecks).toBeGreaterThan(0);
});
test("flags fail when quota is exhausted or auth fails", async () => {
const mockClient = createMockClient({
billing: {
features: [
{ code: "ai-approval", balance: 0, deductionAmount: 100 }
]
}
});
const testCorp: CorpConfig = {
id: "test-corp",
name: "额度耗尽企业",
environment: "test",
prodCorpId: "prod-corp",
source: { type: "seal" },
seal: { url: "https://test.sealai.cc" }
} as any;
const result = await diagnoseTenantContract(mockClient, testCorp);
expect(result.ok).toBe(false);
expect(result.verdict).toBe("BLOCKED");
expect(result.quota.status).toBe("exhausted");
expect(result.summary.failedChecks).toBe(1);
});
});
+413
View File
@@ -0,0 +1,413 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../config/types.js";
import * as api from "../../domains/seal/api.js";
export interface TenantHealthCheck {
id: string;
name: string;
status: "pass" | "warn" | "fail";
summary: string;
details: Record<string, unknown>;
recommendation?: string;
}
export interface TenantDoctorDiagnosis {
ok: boolean;
verdict: "HEALTHY" | "DEGRADED" | "BLOCKED";
timestamp: string;
corp: {
id: string;
name: string;
environment: "production" | "test";
sourceType: string;
boundCorpId?: string;
boundCorpRole?: "prodParent" | "testTarget";
};
summary: {
totalChecks: number;
passedChecks: number;
warningChecks: number;
failedChecks: number;
};
checks: TenantHealthCheck[];
quota: {
featureCode: string;
balance: number;
deductionAmount: number;
estimatedRuns: number;
status: "sufficient" | "low" | "exhausted";
};
rules: {
totalCount: number;
activeCount: number;
quotaUsed?: number;
quotaRemaining?: number;
};
webhooks: {
integrationCount: number;
hasReplayChannel: boolean;
activeWebhookId?: string;
};
}
export async function diagnoseTenantContract(
client: KyInstance,
corp: CorpConfig
): Promise<TenantDoctorDiagnosis> {
const checks: TenantHealthCheck[] = [];
const environment = corp.environment === "test" ? "test" : "production";
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
// 1. Auth & Admin Probe
let userDetail: any = null;
let tenantDetail: any = null;
try {
const whoami = await api.getMe(client);
userDetail = whoami.user;
tenantDetail = whoami.tenant;
const isAdmin = Boolean(userDetail?.isAdmin || userDetail?.permissions?.includes("*"));
if (isAdmin) {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "pass",
summary: `已认证为管理员「${userDetail.name ?? "未知"}」(${userDetail.id ?? ""}),具备完整操作权限`,
details: {
userId: userDetail.id,
userName: userDetail.name,
isAdmin: true,
tenantSlug: tenantDetail?.tenantSlug,
permissions: userDetail.permissions
}
});
} else {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "warn",
summary: `已认证为普通用户「${userDetail.name ?? "未知"}」,非超级管理员,部分配置操作可能受限`,
details: {
userId: userDetail.id,
userName: userDetail.name,
isAdmin: false,
permissions: userDetail.permissions
},
recommendation: "建议使用具有管理权限的企业主账号执行规则修改与集成发布"
});
}
} catch (err) {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "fail",
summary: `鉴权握手失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) },
recommendation: `请执行 seal-use auth login --corp ${corp.id} 重新登录或更新 Token`
});
}
// 2. Billing & AI Approval Quota Probe
let quotaInfo = {
featureCode: "ai-approval",
balance: 0,
deductionAmount: 120,
estimatedRuns: 0,
status: "exhausted" as "sufficient" | "low" | "exhausted"
};
let ruleQuota = {
used: 0,
remaining: 0
};
try {
const billing = await api.getBillingStatus(client);
const features = Array.isArray(billing.features) ? billing.features : [];
// Find AI Approval feature
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
if (aiApproval) {
const balance = typeof aiApproval.balance === "number" ? aiApproval.balance : 0;
const deductionAmount = typeof aiApproval.deductionAmount === "number" && aiApproval.deductionAmount > 0
? aiApproval.deductionAmount
: 120;
const estimatedRuns = Math.floor(balance / deductionAmount);
quotaInfo.balance = balance;
quotaInfo.deductionAmount = deductionAmount;
quotaInfo.estimatedRuns = estimatedRuns;
if (balance <= 0) {
quotaInfo.status = "exhausted";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "fail",
summary: `当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试`,
details: { balance, deductionAmount, estimatedRuns },
recommendation: "请联系管理员为企业充值 AI 审批额度"
});
} else if (estimatedRuns < 10) {
quotaInfo.status = "low";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: `额度偏低:剩余 ${balance} 点 (单笔扣除 ${deductionAmount} 点),仅可支持约 ${estimatedRuns} 笔审核`,
details: { balance, deductionAmount, estimatedRuns },
recommendation: "建议在发起大规模自动化回归前充值补充额度"
});
} else {
quotaInfo.status = "sufficient";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "pass",
summary: `额度充裕:剩余 ${balance} 点,预估可支持 ${estimatedRuns} 笔审核单据`,
details: { balance, deductionAmount, estimatedRuns }
});
}
} else {
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: "未检索到「ai-approval」功能包额度明细,按默认通道运行",
details: { features: features.map((f: any) => f?.code) }
});
}
// Rule quota
const ruleFeat = features.find((f: any) => f?.code === "approval-rules");
if (ruleFeat) {
ruleQuota.used = typeof ruleFeat.used === "number" ? ruleFeat.used : 0;
ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0;
}
} catch (err) {
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 3. Rules & Draft State Probe
let rulesSummary = {
totalCount: 0,
activeCount: 0,
quotaUsed: ruleQuota.used,
quotaRemaining: ruleQuota.remaining
};
try {
const rulesData = await api.listApprovalRules(client);
const rules = Array.isArray(rulesData.rules) ? rulesData.rules : [];
rulesSummary.totalCount = rules.length;
rulesSummary.activeCount = rules.filter((r) => r.status === "ACTIVE").length;
if (rules.length === 0) {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "warn",
summary: "当前租户未配置任何审核规则 (规则数为 0)",
details: { totalCount: 0, activeCount: 0 },
recommendation: environment === "test" && boundCorpId
? `可运行 seal-use corps sync-test --corp ${boundCorpId} 从生产企业同步规则`
: "可运行 seal-use rules add 创建基础规则"
});
} else {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "pass",
summary: `审核规则健康:共 ${rulesSummary.totalCount} 条规则,其中生效活跃 ${rulesSummary.activeCount} 条`,
details: {
totalCount: rulesSummary.totalCount,
activeCount: rulesSummary.activeCount,
quotaUsed: ruleQuota.used,
quotaRemaining: ruleQuota.remaining
}
});
}
} catch (err) {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "fail",
summary: `拉取规则列表失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 4. Webhook Integration Probe
let webhooksSummary = {
integrationCount: 0,
hasReplayChannel: false,
activeWebhookId: undefined as string | undefined
};
try {
const integrations = await api.listWebhookIntegrations(client);
webhooksSummary.integrationCount = integrations.length;
const replayChannel = integrations.find(
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
);
webhooksSummary.hasReplayChannel = Boolean(replayChannel);
webhooksSummary.activeWebhookId = replayChannel?.id ?? integrations[0]?.id;
if (integrations.length === 0) {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "warn",
summary: "未配置任何 Webhook 集成通道,执行重放测试时将自动创建临时回放通道",
details: { integrationCount: 0 },
recommendation: "可运行 seal-use webhook add --name (回放通道) 手动注册专属通道"
});
} else {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "pass",
summary: `Webhook 集成通道就绪:共 ${integrations.length} 个通道${replayChannel ? ` (含专属回放通道「${replayChannel.name}」)` : ""}`,
details: {
integrationCount: integrations.length,
hasReplayChannel: webhooksSummary.hasReplayChannel,
activeWebhookId: webhooksSummary.activeWebhookId
}
});
}
} catch (err) {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "warn",
summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 5. Environment Pairing Probe
if (environment === "test") {
if (boundCorpId) {
checks.push({
id: "environment_binding",
name: "测试环境配对契约",
status: "pass",
summary: `测试租户已绑定生产母企业「${boundCorpId}」,具备样本拉取与配置同步能力`,
details: { environment, boundCorpId, boundCorpRole }
});
} else {
checks.push({
id: "environment_binding",
name: "测试环境配对契约",
status: "warn",
summary: "测试租户尚未绑定对应的生产母企业,无法直接拉取生产样本执行自动化回归",
details: { environment },
recommendation: `可运行 seal-use corps bind-test <prodCorpId> ${corp.id} 建立 1 对 1 绑定`
});
}
} else {
if (boundCorpId) {
checks.push({
id: "environment_binding",
name: "生产环境安全隔离契约",
status: "pass",
summary: `生产企业已绑定沙箱测试靶场「${boundCorpId}」,回归测试将严格限制在靶场中运行`,
details: { environment, boundCorpId, boundCorpRole }
});
} else {
checks.push({
id: "environment_binding",
name: "生产环境安全隔离契约",
status: "warn",
summary: "生产企业尚未绑定任何测试企业,所有回归测试功能将触发安全拦截",
details: { environment },
recommendation: `可运行 seal-use corps bind-test ${corp.id} <testCorpId> 为该生产租户绑定测试靶场`
});
}
}
// Compute overall verdict
const failedChecks = checks.filter((c) => c.status === "fail").length;
const warningChecks = checks.filter((c) => c.status === "warn").length;
const passedChecks = checks.filter((c) => c.status === "pass").length;
let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY";
if (failedChecks > 0) {
verdict = "BLOCKED";
} else if (warningChecks > 0) {
verdict = "DEGRADED";
}
return {
ok: failedChecks === 0,
verdict,
timestamp: new Date().toISOString(),
corp: {
id: corp.id,
name: corp.name,
environment,
sourceType: corp.source?.type ?? "native",
boundCorpId,
boundCorpRole
},
summary: {
totalChecks: checks.length,
passedChecks,
warningChecks,
failedChecks
},
checks,
quota: quotaInfo,
rules: rulesSummary,
webhooks: webhooksSummary
};
}
export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): string {
const { corp, verdict, summary, checks, quota, rules, webhooks } = diagnosis;
const verdictBadge =
verdict === "HEALTHY"
? "🟢 健康良好 (HEALTHY)"
: verdict === "DEGRADED"
? "🟡 亚健康降级 (DEGRADED)"
: "🔴 阻断受限 (BLOCKED)";
const lines: string[] = [
"",
`🏥 [Seal Use Doctor] 租户全链路契约体检: ${corp.name} (${corp.id})`,
` 状态: ${verdictBadge} · 环境: ${corp.environment.toUpperCase()} · 耗时: 实时探针`,
" " + "─".repeat(60)
];
// Core metrics overview
lines.push(
` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
);
if (corp.boundCorpId) {
lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`);
}
lines.push(" " + "─".repeat(60));
for (const check of checks) {
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗";
lines.push(` [${icon}] ${check.name}: ${check.summary}`);
if (check.recommendation) {
lines.push(` 👉 建议: ${check.recommendation}`);
}
}
lines.push(" " + "─".repeat(60));
lines.push(` 检查汇总: 通过 ${summary.passedChecks} · 告警 ${summary.warningChecks} · 失败 ${summary.failedChecks}`);
lines.push("");
return lines.join("\n");
}
+9 -5
View File
@@ -53,16 +53,20 @@ export async function createSealClientForToken(corp: CorpConfig, token: string):
export function createSealClientForUrl(
sealUrl: string,
token: string,
token?: string,
customHeaders: Record<string, string> = {}
): KyInstance {
const headers: Record<string, string> = {
...customHeaders
};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
return ky.create({
prefix: sealUrl.replace(/\/+$/, ""),
timeout: 30000,
headers: {
...customHeaders,
Authorization: `Bearer ${token}`
},
headers,
hooks: {
beforeError: [createBeforeErrorHook()]
}
+26
View File
@@ -61,4 +61,30 @@ describe("createSealClientForUrl", () => {
expect(sent?.get("cookie")).toBe("sdp_session=token");
expect(sent?.get("authorization")).toBe("Bearer session-token");
});
test("omits Authorization header when token is undefined or empty while preserving custom headers and cookies", async () => {
const originalFetch = globalThis.fetch;
let sent: Headers | undefined;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = input instanceof Request ? input : new Request(input, init);
sent = new Headers(request.headers);
return new Response(JSON.stringify({ data: { token: "sso-token-123" } }), {
headers: { "content-type": "application/json" }
});
}) as typeof fetch;
try {
const client = createSealClientForUrl("https://corp-a.sealai.cc", undefined, {
Cookie: "gateway_session=abc",
"X-Custom-Secret": "secret-val"
});
await client.get("api/auth/oauth2/session/oem-hosecloud");
} finally {
globalThis.fetch = originalFetch;
}
expect(sent?.get("cookie")).toBe("gateway_session=abc");
expect(sent?.get("x-custom-secret")).toBe("secret-val");
expect(sent?.get("authorization")).toBeNull();
});
});
+227
View File
@@ -0,0 +1,227 @@
import { describe, expect, test } from "bun:test";
import type { CorpConfig } from "../config/types.js";
import {
filterCorpsFuzzy,
fuzzyMatchString,
levenshteinDistance,
matchCorp,
minSubstringLevenshtein,
normalizeFuzzyPinyin
} from "./fuzzy.js";
function makeCorp(id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
id,
name,
environment: "production",
seal: {
tenantSlug: `${id}-slug`,
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "direct",
token: `${id}-token`,
sealUrl: `https://${id}.seal.test`,
expiresIn: 3600,
staffId: `staff-${id}`
},
auth: {
refreshTtl: 300
},
...overrides
};
}
describe("fuzzy search utilities", () => {
describe("levenshteinDistance", () => {
test("calculates distance correctly", () => {
expect(levenshteinDistance("", "")).toBe(0);
expect(levenshteinDistance("abc", "abc")).toBe(0);
expect(levenshteinDistance("abc", "ab")).toBe(1);
expect(levenshteinDistance("abc", "abcd")).toBe(1);
expect(levenshteinDistance("kitten", "sitting")).toBe(3);
});
});
describe("minSubstringLevenshtein", () => {
test("detects exact substring with distance 0", () => {
expect(minSubstringLevenshtein("abc", "xyzabcdef")).toBe(0);
});
test("detects missing letter with distance 1", () => {
expect(minSubstringLevenshtein("acm", "acme corp")).toBe(0); // acm is substring of acme
expect(minSubstringLevenshtein("xiezihao", "xieziha")).toBe(1); // target missing 'o'
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1); // query missing 'i'
});
test("detects single substitution typo with distance 1", () => {
expect(minSubstringLevenshtein("xiezhao", "xiezihao")).toBe(1);
});
});
describe("normalizeFuzzyPinyin", () => {
test("normalizes retroflex to flat consonants", () => {
expect(normalizeFuzzyPinyin("张")).toBe(normalizeFuzzyPinyin("詹")); // zhang -> zhang/zhan -> zan
expect(normalizeFuzzyPinyin("超")).toContain("cao");
expect(normalizeFuzzyPinyin("沙")).toContain("sa");
});
test("normalizes front and back nasals", () => {
expect(normalizeFuzzyPinyin("陈")).toBe(normalizeFuzzyPinyin("程")); // chen / cheng -> cen
expect(normalizeFuzzyPinyin("金")).toBe(normalizeFuzzyPinyin("京")); // jin / jing -> jin
});
test("normalizes homophones to identical representations", () => {
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("鞋子豪"));
expect(normalizeFuzzyPinyin("渠道")).toBe(normalizeFuzzyPinyin("渠到"));
});
});
describe("fuzzyMatchString", () => {
test("exact match", () => {
const res = fuzzyMatchString("谢子豪", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("exact");
expect(res.score).toBe(1.0);
});
test("substring match", () => {
const res = fuzzyMatchString("谢子", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("substring");
expect(res.score).toBe(0.95);
});
test("initials match (简拼)", () => {
const res = fuzzyMatchString("xzh", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("initials");
expect(res.score).toBe(0.9);
});
test("pinyin match (全拼)", () => {
const res = fuzzyMatchString("xiezihao", "谢子豪");
expect(res.matched).toBe(true);
expect(res.reason).toBe("pinyin");
});
test("homophones (同音字)", () => {
const res1 = fuzzyMatchString("鞋子豪", "谢子豪");
expect(res1.matched).toBe(true);
expect(res1.reason).toBe("fuzzy_pinyin");
const res2 = fuzzyMatchString("渠到", "渠道AI演示环境");
expect(res2.matched).toBe(true);
expect(res2.reason).toBe("fuzzy_pinyin");
});
test("front/back nasals & flat/retroflex (不区分前后鼻音和平翘舌)", () => {
const res1 = fuzzyMatchString("詹三", "张三");
expect(res1.matched).toBe(true);
const res2 = fuzzyMatchString("谢自豪", "谢子豪");
expect(res2.matched).toBe(true);
});
test("missing 1 letter or typo tolerance (缺失字母或轻微拼写错误)", () => {
const res1 = fuzzyMatchString("xieziha", "谢子豪");
expect(res1.matched).toBe(true);
const res2 = fuzzyMatchString("xiezhao", "谢子豪");
expect(res2.matched).toBe(true);
const res3 = fuzzyMatchString("acme", "acm corp");
expect(res3.matched).toBe(true);
expect(res3.reason).toBe("levenshtein");
});
test("strict mode rejects fuzzy / homophone / typo matches", () => {
expect(fuzzyMatchString("鞋子豪", "谢子豪", { strict: true }).matched).toBe(false);
expect(fuzzyMatchString("xzh", "谢子豪", { strict: true }).matched).toBe(false);
expect(fuzzyMatchString("xieziha", "谢子豪", { strict: true }).matched).toBe(false);
// But exact substring is allowed in strict mode
expect(fuzzyMatchString("谢子", "谢子豪", { strict: true }).matched).toBe(true);
expect(fuzzyMatchString("谢子豪", "谢子豪", { strict: true }).matched).toBe(true);
});
test("rejects completely unrelated terms", () => {
expect(fuzzyMatchString("alibaba", "谢子豪").matched).toBe(false);
expect(fuzzyMatchString("tencent", "ID01VAdCnJEdFd").matched).toBe(false);
expect(fuzzyMatchString("xyz", "渠道环境").matched).toBe(false);
});
});
describe("filterCorpsFuzzy", () => {
const corp1 = makeCorp("xiezihao", "谢子豪", {
testCorpId: "test-xzh"
});
const corp2 = makeCorp("ID01VAdCnJEdFd", "渠道AI演示环境", {
source: {
type: "hose",
corpId: "ID01VAdCnJEdFd",
staffId: "staff-channel",
domain: "https://app.ekuaibao.com"
} as any
});
const corp3 = makeCorp("acme-corp", "Acme Global", {
environment: "test"
});
const corps = [corp1, corp2, corp3];
test("finds enterprise by homophone", () => {
const results = filterCorpsFuzzy(corps, "鞋子豪");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by initials", () => {
const results = filterCorpsFuzzy(corps, "xzh");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by missing letter query", () => {
const results = filterCorpsFuzzy(corps, "xieziha");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("xiezihao");
});
test("finds enterprise by pinyin of Chinese name", () => {
const results = filterCorpsFuzzy(corps, "qudao");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
});
test("finds enterprise by hose corpId or staffId", () => {
const results = filterCorpsFuzzy(corps, "ID01VAdCnJEdFd");
expect(results.length).toBe(1);
expect(results[0]!.id).toBe("ID01VAdCnJEdFd");
const staffResults = filterCorpsFuzzy(corps, "staff-channel");
expect(staffResults.length).toBe(1);
expect(staffResults[0]!.id).toBe("ID01VAdCnJEdFd");
});
test("strict mode filtering excludes fuzzy homophone matches", () => {
const fuzzyRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: false });
expect(fuzzyRes.length).toBe(1);
const strictRes = filterCorpsFuzzy(corps, "鞋子豪", { strict: true });
expect(strictRes.length).toBe(0);
const strictExact = filterCorpsFuzzy(corps, "谢子豪", { strict: true });
expect(strictExact.length).toBe(1);
});
test("ranks exact match higher than fuzzy matches", () => {
const cExact = makeCorp("test-qudao", "渠道");
const cFuzzy = makeCorp("test-other", "渠到另外一家");
const ranked = filterCorpsFuzzy([cFuzzy, cExact], "渠道");
expect(ranked[0]!.id).toBe("test-qudao");
});
});
});
+325
View File
@@ -0,0 +1,325 @@
import { pinyin, match as pinyinMatch } from "pinyin-pro";
import type { CorpConfig } from "../config/types.js";
export interface FuzzyMatchOptions {
/**
* If true, disables fuzzy/soft matching and requires exact substring matching.
* Defaults to false (soft search by default).
*/
strict?: boolean;
/**
* Maximum edit distance allowed for typo / missing letter tolerance.
* Defaults based on query length:
* - length <= 2: 0 (no fuzzy edits)
* - length 3..5: 1 (missing 1 letter or 1 typo)
* - length >= 6: 2 (missing 1-2 letters)
*/
maxDistance?: number;
}
export type MatchReason =
| "exact"
| "substring"
| "initials"
| "pinyin"
| "fuzzy_pinyin"
| "levenshtein"
| "subsequence"
| "none";
export interface MatchScoreResult {
matched: boolean;
score: number;
reason: MatchReason;
}
/**
* Standard Levenshtein distance between two strings.
*/
export function levenshteinDistance(a: string, b: string): number {
const m = a.length;
const n = b.length;
if (m === 0) return n;
if (n === 0) return m;
let prevRow = Array.from({ length: n + 1 }, (_, j) => j);
let currRow = new Array<number>(n + 1).fill(0);
for (let i = 1; i <= m; i += 1) {
currRow[0] = i;
for (let j = 1; j <= n; j += 1) {
if (a[i - 1] === b[j - 1]) {
currRow[j] = prevRow[j - 1] ?? 0;
} else {
const sub = prevRow[j - 1] ?? 0;
const ins = currRow[j - 1] ?? 0;
const del = prevRow[j] ?? 0;
currRow[j] = Math.min(sub, ins, del) + 1;
}
}
const temp = prevRow;
prevRow = currRow;
currRow = temp;
}
return prevRow[n] ?? 0;
}
/**
* Finds the minimum Levenshtein distance between `query` and any sliding window substring in `target`.
* Supports queries missing a letter, having an extra letter, or having an internal typo.
*/
export function minSubstringLevenshtein(query: string, target: string): number {
if (!query || !target) return 999;
if (target.includes(query)) return 0;
const qLen = query.length;
if (target.length < qLen - 2) {
return levenshteinDistance(query, target);
}
let min = 999;
const minWindow = Math.max(1, qLen - 2);
const maxWindow = Math.min(target.length, qLen + 2);
for (let len = minWindow; len <= maxWindow; len += 1) {
for (let i = 0; i <= target.length - len; i += 1) {
const sub = target.slice(i, i + len);
const dist = levenshteinDistance(query, sub);
if (dist < min) min = dist;
if (min === 0) return 0;
}
}
return min;
}
/**
* Normalizes Chinese text to toneless pinyin with fuzzy sound rules:
* - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s
* - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan
* - Strips non-alphanumeric whitespace
*/
export function normalizeFuzzyPinyin(str: string): string {
if (!str) return "";
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
return pyTokens
.map((token) =>
token
.toLowerCase()
.replace(/zh/g, "z")
.replace(/ch/g, "c")
.replace(/sh/g, "s")
.replace(/iang/g, "ian")
.replace(/uang/g, "uan")
.replace(/ang/g, "an")
.replace(/eng/g, "en")
.replace(/ing/g, "in")
)
.join("");
}
/**
* Checks if all characters of `query` appear in order inside `target` (subsequence).
*/
export function isSubsequence(query: string, target: string): boolean {
if (!query || !target) return false;
let qIdx = 0;
for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) {
if (query[qIdx] === target[tIdx]) {
qIdx += 1;
}
}
return qIdx === query.length;
}
/**
* Core fuzzy string match engine:
* Evaluates match across exact, substring, initials, pinyin, homophone/fuzzy pinyin,
* sliding-window edit distance (missing/typo tolerance), and character subsequence.
*/
export function fuzzyMatchString(
query: string,
target: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const normQuery = query.trim().toLowerCase();
const normTarget = target.trim().toLowerCase();
if (!normQuery || !normTarget) {
return { matched: false, score: 0, reason: "none" };
}
// 1. Exact match
if (normTarget === normQuery) {
return { matched: true, score: 1.0, reason: "exact" };
}
// 2. Substring match
if (normTarget.includes(normQuery)) {
return { matched: true, score: 0.95, reason: "substring" };
}
// If strict mode is requested, only exact or substring matches are accepted.
if (options.strict) {
return { matched: false, score: 0, reason: "none" };
}
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
// 3. Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产")
if (targetHasChinese && normQuery.length >= 2) {
const targetInitials = pinyin(normTarget, { pattern: "first", toneType: "none", type: "array" })
.join("")
.toLowerCase();
if (targetInitials.includes(normQuery)) {
return { matched: true, score: 0.9, reason: "initials" };
}
}
// 4. Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets)
if (targetHasChinese) {
try {
const pm = pinyinMatch(normTarget, normQuery, { precision: "start" });
if (pm && pm.length > 0) {
return { matched: true, score: 0.88, reason: "pinyin" };
}
} catch {
// ignore match errors if non-standard regex chars
}
}
// 5. Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音)
let targetFuzzyPinyin = "";
let queryFuzzyPinyin = "";
if (targetHasChinese || queryHasChinese) {
targetFuzzyPinyin = normalizeFuzzyPinyin(normTarget);
queryFuzzyPinyin = normalizeFuzzyPinyin(normQuery);
if (queryFuzzyPinyin.length >= 2 && targetFuzzyPinyin.includes(queryFuzzyPinyin)) {
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
}
}
// 6. Missing letter / Typo tolerance (Levenshtein Distance)
// Determine allowed distance based on query length:
// - <= 2: 0 (no fuzzy edits to prevent excessive false positives)
// - 3..5: 1 (missing 1 letter or 1 typo)
// - >= 6: 2 (missing 1-2 letters)
const defaultMaxDist = normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2;
const maxAllowedDist = options.maxDistance ?? defaultMaxDist;
if (maxAllowedDist > 0) {
// Check raw string distance
const rawDist = minSubstringLevenshtein(normQuery, normTarget);
if (rawDist <= maxAllowedDist) {
return {
matched: true,
score: Math.max(0.6, 0.8 - rawDist * 0.1),
reason: "levenshtein"
};
}
// Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter)
if (
(targetHasChinese || queryHasChinese) &&
queryFuzzyPinyin.length >= 3 &&
targetFuzzyPinyin.length >= 3
) {
const pinyinDist = minSubstringLevenshtein(queryFuzzyPinyin, targetFuzzyPinyin);
if (pinyinDist <= maxAllowedDist) {
return {
matched: true,
score: Math.max(0.6, 0.78 - pinyinDist * 0.1),
reason: "levenshtein"
};
}
}
}
// 7. Subsequence match (loose character order, min query length 3)
if (normQuery.length >= 3) {
if (
isSubsequence(normQuery, normTarget) ||
((targetHasChinese || queryHasChinese) && isSubsequence(queryFuzzyPinyin, targetFuzzyPinyin))
) {
return { matched: true, score: 0.65, reason: "subsequence" };
}
}
return { matched: false, score: 0, reason: "none" };
}
/**
* Matches an enterprise (`CorpConfig`) against a query across all its searchable fields,
* returning the highest match score and reason.
*/
export function matchCorp(
corp: CorpConfig,
query: string,
options: FuzzyMatchOptions = {}
): MatchScoreResult {
const fields: Array<{ text: string | undefined; weight: number }> = [
{ text: corp.name, weight: 1.2 },
{ text: corp.id, weight: 1.1 },
{ text: corp.source.staffId, weight: 1.0 },
{ text: (corp.source as any).domain, weight: 1.0 },
{ text: (corp.source as any).corpId, weight: 1.0 },
{ text: corp.seal.tenantSlug, weight: 1.0 },
{ text: (corp.source as any).tenantSlug, weight: 1.0 },
{ text: (corp.source as any).tenantName, weight: 1.1 },
{ text: corp.testCorpId, weight: 1.0 },
{ text: corp.prodCorpId, weight: 1.0 },
{ text: corp.environment ?? "production", weight: 0.8 },
{ text: corp.source.type, weight: 0.8 },
{ text: (corp.source as any).provider, weight: 0.8 }
];
let bestScore = 0;
let bestReason: MatchReason = "none";
for (const field of fields) {
if (!field.text) continue;
const res = fuzzyMatchString(query, field.text, options);
if (res.matched) {
const weightedScore = res.score * field.weight;
if (weightedScore > bestScore) {
bestScore = weightedScore;
bestReason = res.reason;
}
}
}
return {
matched: bestScore > 0,
score: bestScore,
reason: bestReason
};
}
/**
* Filters a list of enterprises using soft fuzzy search (or strict search if requested),
* and automatically sorts the matching results from highest relevance to lowest.
*/
export function filterCorpsFuzzy(
corps: CorpConfig[],
query: string,
options: FuzzyMatchOptions = {}
): CorpConfig[] {
const trimmed = query.trim();
if (!trimmed) return corps;
const scored: Array<{ corp: CorpConfig; score: number }> = [];
for (const corp of corps) {
const res = matchCorp(corp, trimmed, options);
if (res.matched) {
scored.push({ corp, score: res.score });
}
}
// Sort by match score descending (highest confidence first)
scored.sort((a, b) => b.score - a.score);
return scored.map((item) => item.corp);
}
+114
View File
@@ -0,0 +1,114 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import {
computeWindowCutoff,
getRecentCorpUsageScores,
loadUsageStats,
pruneExpiredStats,
recordCorpUsage,
resolveUsageFilePath,
sortCorpsByUsageAndRecency,
toDateKey,
USAGE_FILE_ENV
} from "./usage-tracker.js";
describe("usage-tracker", () => {
const originalUsageFileEnv = process.env[USAGE_FILE_ENV];
let testDir: string;
let testUsageFile: string;
beforeEach(() => {
testDir = join(tmpdir(), `seal-use-usage-test-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`);
mkdirSync(testDir, { recursive: true });
testUsageFile = join(testDir, "usage.json");
process.env[USAGE_FILE_ENV] = testUsageFile;
});
afterEach(() => {
if (originalUsageFileEnv !== undefined) {
process.env[USAGE_FILE_ENV] = originalUsageFileEnv;
} else {
delete process.env[USAGE_FILE_ENV];
}
rmSync(testDir, { recursive: true, force: true });
});
test("resolves custom usage file path from env", () => {
expect(resolveUsageFilePath()).toBe(testUsageFile);
});
test("computes correct date keys and window cutoffs", () => {
const fixedDate = new Date("2026-09-13T12:00:00.000Z");
expect(toDateKey(fixedDate)).toBe("2026-09-13");
expect(computeWindowCutoff(7, fixedDate)).toBe("2026-09-07");
expect(computeWindowCutoff(1, fixedDate)).toBe("2026-09-13");
});
test("records usage and aggregates 7-day scores", () => {
const day1 = new Date("2026-09-10T10:00:00.000Z");
const day2 = new Date("2026-09-13T15:00:00.000Z");
recordCorpUsage("corp-a", day1);
recordCorpUsage("corp-a", day1);
recordCorpUsage("corp-a", day2);
recordCorpUsage("corp-b", day2);
const scores = getRecentCorpUsageScores(["corp-a", "corp-b", "corp-c"], 7, day2);
expect(scores.get("corp-a")).toBe(3);
expect(scores.get("corp-b")).toBe(1);
expect(scores.get("corp-c")).toBe(0);
});
test("prunes entries older than 7 days when recording new usage", () => {
const oldDay = new Date("2026-09-01T10:00:00.000Z");
const currentDay = new Date("2026-09-13T10:00:00.000Z");
recordCorpUsage("corp-old", oldDay);
const initialStats = loadUsageStats();
expect(initialStats["corp-old"]?.["2026-09-01"]).toBe(1);
// Recording on current day should prune the 2026-09-01 entry
recordCorpUsage("corp-new", currentDay);
const updatedStats = loadUsageStats();
expect(updatedStats["corp-new"]?.["2026-09-13"]).toBe(1);
expect(updatedStats["corp-old"]).toBeUndefined();
});
test("handles corrupted usage file gracefully without throwing", () => {
writeFileSync(testUsageFile, "not-valid-json{{{", "utf-8");
expect(() => recordCorpUsage("corp-safe")).not.toThrow();
const stats = loadUsageStats();
expect(stats["corp-safe"]).toBeDefined();
});
test("sorts corporations by current selection, usage score, then name", () => {
const corps = [
{ id: "corp-low", name: "低频企业" },
{ id: "corp-current", name: "当前企业" },
{ id: "corp-high", name: "高频企业" },
{ id: "corp-zero-b", name: "零频企业B" },
{ id: "corp-zero-a", name: "零频企业A" }
];
const scores = new Map<string, number>([
["corp-low", 2],
["corp-current", 1], // Even with lower score, currentCorpId should be on top
["corp-high", 20],
["corp-zero-b", 0],
["corp-zero-a", 0]
]);
const sorted = sortCorpsByUsageAndRecency(corps, "corp-current", scores);
expect(sorted.map((c) => c.id)).toEqual([
"corp-current",
"corp-high",
"corp-low",
"corp-zero-a",
"corp-zero-b"
]);
});
});
+157
View File
@@ -0,0 +1,157 @@
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
export const USAGE_FILE_ENV = "SEAL_USE_USAGE_FILE";
const DEFAULT_USAGE_FILE = join(homedir(), ".config", "seal-use", "usage.json");
const DEFAULT_WINDOW_DAYS = 7;
export type CorpUsageDailyStats = Record<string, number>;
export type CorpUsageStats = Record<string, CorpUsageDailyStats>;
export function resolveUsageFilePath(): string {
const custom = process.env[USAGE_FILE_ENV]?.trim();
if (custom) return custom;
return DEFAULT_USAGE_FILE;
}
export function toDateKey(date: Date = new Date()): string {
return date.toISOString().slice(0, 10);
}
export function computeWindowCutoff(windowDays: number = DEFAULT_WINDOW_DAYS, now: Date = new Date()): string {
const cutoffTime = now.getTime() - Math.max(0, windowDays - 1) * 86400000;
return new Date(cutoffTime).toISOString().slice(0, 10);
}
export function loadUsageStats(filePath: string = resolveUsageFilePath()): CorpUsageStats {
if (!existsSync(filePath)) {
return {};
}
try {
const raw = readFileSync(filePath, "utf-8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return parsed as CorpUsageStats;
}
return {};
} catch {
return {};
}
}
export function pruneExpiredStats(stats: CorpUsageStats, cutoffKey: string): CorpUsageStats {
const pruned: CorpUsageStats = {};
for (const [corpId, daily] of Object.entries(stats)) {
if (!daily || typeof daily !== "object") continue;
const keptDaily: CorpUsageDailyStats = {};
let hasKeys = false;
for (const [dateKey, count] of Object.entries(daily)) {
if (typeof count === "number" && count > 0 && dateKey >= cutoffKey) {
keptDaily[dateKey] = count;
hasKeys = true;
}
}
if (hasKeys) {
pruned[corpId] = keptDaily;
}
}
return pruned;
}
function saveUsageStatsAtomic(stats: CorpUsageStats, targetPath: string = resolveUsageFilePath()): void {
const dir = dirname(targetPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`;
try {
writeFileSync(tempPath, JSON.stringify(stats, null, 2), "utf-8");
renameSync(tempPath, targetPath);
} catch (err) {
try {
if (existsSync(tempPath)) unlinkSync(tempPath);
} catch {}
throw err;
}
}
export function recordCorpUsage(corpId: string, now: Date = new Date()): void {
if (!corpId || typeof corpId !== "string") return;
try {
const filePath = resolveUsageFilePath();
const stats = loadUsageStats(filePath);
const today = toDateKey(now);
const cutoffKey = computeWindowCutoff(DEFAULT_WINDOW_DAYS, now);
const pruned = pruneExpiredStats(stats, cutoffKey);
pruned[corpId] = pruned[corpId] || {};
pruned[corpId][today] = (pruned[corpId][today] ?? 0) + 1;
saveUsageStatsAtomic(pruned, filePath);
} catch {
// Fail-safe: recording stats must never throw or disrupt CLI commands.
}
}
export function getRecentCorpUsageScores(
corpIds?: string[],
windowDays: number = DEFAULT_WINDOW_DAYS,
now: Date = new Date()
): Map<string, number> {
const scores = new Map<string, number>();
try {
const stats = loadUsageStats();
const cutoffKey = computeWindowCutoff(windowDays, now);
const today = toDateKey(now);
const targets = corpIds ?? Object.keys(stats);
for (const id of targets) {
const daily = stats[id];
if (!daily) {
scores.set(id, 0);
continue;
}
let total = 0;
for (const [dateKey, count] of Object.entries(daily)) {
if (dateKey >= cutoffKey && dateKey <= today && typeof count === "number") {
total += count;
}
}
scores.set(id, total);
}
} catch {
if (corpIds) {
for (const id of corpIds) scores.set(id, 0);
}
}
return scores;
}
export function sortCorpsByUsageAndRecency<T extends { id: string; name?: string }>(
corps: T[],
currentCorpId?: string,
scores?: Map<string, number>
): T[] {
const usageScores = scores ?? getRecentCorpUsageScores(corps.map((c) => c.id));
return [...corps].sort((a, b) => {
if (currentCorpId) {
if (a.id === currentCorpId && b.id !== currentCorpId) return -1;
if (b.id === currentCorpId && a.id !== currentCorpId) return 1;
}
const scoreA = usageScores.get(a.id) ?? 0;
const scoreB = usageScores.get(b.id) ?? 0;
if (scoreA !== scoreB) {
return scoreB - scoreA;
}
const nameA = a.name ?? a.id;
const nameB = b.name ?? b.id;
const cmp = nameA.localeCompare(nameB, "zh-CN");
if (cmp !== 0) return cmp;
return a.id.localeCompare(b.id);
});
}
+105
View File
@@ -12,6 +12,9 @@ import {
getDepartment,
getContactsLastSyncTime,
getInsightStats,
getInsightRisksByTag,
getInsightPerformance,
analyzeInsightRecord,
listExpenses,
listInvoices,
listFeishuSimulationApprovalDefinitions,
@@ -139,6 +142,108 @@ describe("Seal contact API", () => {
);
});
test("forwards risks-by-tag parameters and parses response", async () => {
let requestedUrl = "";
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
return {
json: async () => ({
data: {
tagId: "B.1.6",
tagName: "缺少验收/签收证明",
tagPath: "凭证/附件问题 > 凭证缺失 > 缺少验收/签收证明",
tagDescription: "维修费等未提供验收单",
risks: [
{
riskId: "risk-01",
recordId: "rec-01",
riskDetails: "冰箱无验收单",
riskLevel: "warning",
documentType: "费用报销",
documentSN: "B26000011",
sourceSystem: "custom",
confidence: 0.95,
reasoning: "缺少签收",
createdAt: "2026-09-11T07:31:43.647Z"
}
],
total: 1
}
})
};
}
} as unknown as KyInstance;
const result = await getInsightRisksByTag(client, {
tagId: "B.1.6",
startDate: "2026-09-01T00:00:00Z",
endDate: "2026-09-30T23:59:59Z"
});
expect(result.tagId).toBe("B.1.6");
expect(result.risks.length).toBe(1);
expect(result.risks[0]?.documentSN).toBe("B26000011");
expect(requestedUrl).toBe(
"api/v1/insight/risks-by-tag?tagId=B.1.6&startDate=2026-09-01T00%3A00%3A00Z&endDate=2026-09-30T23%3A59%3A59Z"
);
});
test("normalizes performance date parameters to numeric timestamps", async () => {
let requestedUrl = "";
const client = {
get: (url: string, options?: { searchParams?: URLSearchParams }) => {
requestedUrl = `${url}?${options?.searchParams?.toString() ?? ""}`;
return {
json: async () => ({
data: {
metrics: {
approvalCount: { value: 24, trend: 0 },
accuracy: { value: 100, trend: 0 },
automationRate: { value: 75, trend: 0 },
riskCount: { value: 54, trend: 0 },
avgDuration: { value: 1041.4, trend: 0 }
},
sankeyData: {
nodes: [{ id: "辅助模式" }],
links: [{ source: "辅助模式", target: "添加评论", value: 24 }]
}
}
})
};
}
} as unknown as KyInstance;
const result = await getInsightPerformance(client, {
startDate: "2026-09-01T00:00:00.000Z",
endDate: "2026-09-30T23:59:59.000Z"
});
expect(result.metrics.approvalCount?.value).toBe(24);
expect(result.sankeyData.nodes[0]?.id).toBe("辅助模式");
const startTs = new Date("2026-09-01T00:00:00.000Z").getTime();
const endTs = new Date("2026-09-30T23:59:59.000Z").getTime();
expect(requestedUrl).toBe(
`api/v1/insight/performance?startDate=${startTs}&endDate=${endTs}`
);
});
test("posts to analyze insight record", async () => {
let postedUrl = "";
const client = {
post: async (url: string) => {
postedUrl = url;
return {
json: async () => ({ data: null })
};
}
} as unknown as KyInstance;
const result = await analyzeInsightRecord(client, "rec-test-123");
expect(result).toEqual({ success: true, recordId: "rec-test-123" });
expect(postedUrl).toBe("api/v1/insight/analyze/rec-test-123");
});
test("uses the frontend filter parameter names for expenses and invoices", async () => {
const requestedUrls: string[] = [];
const client = {
+70 -6
View File
@@ -8,6 +8,8 @@ import {
} from "./material-pack/policy.js";
import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
ApprovalDocumentListData,
ApprovalDocumentListDataSchema,
@@ -51,6 +53,10 @@ import {
SealContactsLastSyncTimeSchema,
InsightStats,
InsightStatsSchema,
InsightRisksByTag,
InsightRisksByTagSchema,
InsightPerformance,
InsightPerformanceSchema,
ExpenseListData,
ExpenseListDataSchema,
InvoiceListData,
@@ -676,7 +682,7 @@ export async function listApprovalRuns(
toTimestamp?: string;
startDate?: string;
endDate?: string;
status?: string;
status?: string | string[];
sourceSystem?: string;
taskMode?: string;
manualApprovalStatus?: string | string[];
@@ -693,7 +699,7 @@ export async function listApprovalRuns(
setOptional(searchParams, "toTimestamp", params.toTimestamp);
setOptional(searchParams, "startDate", params.startDate);
setOptional(searchParams, "endDate", params.endDate);
setOptional(searchParams, "status", params.status);
setArrayOptional(searchParams, "status", params.status);
setOptional(searchParams, "sourceSystem", params.sourceSystem);
setOptional(searchParams, "taskMode", params.taskMode);
setOptional(searchParams, "search", params.search);
@@ -1007,6 +1013,63 @@ export async function getInsightStats(
);
}
export async function getInsightRisksByTag(
client: KyInstance,
params: { tagId: string; startDate?: string; endDate?: string }
): Promise<InsightRisksByTag> {
const defaultRange = currentMonthDateRange();
const searchParams = new URLSearchParams();
searchParams.set("tagId", params.tagId);
searchParams.set("startDate", params.startDate ?? defaultRange.startDate);
searchParams.set("endDate", params.endDate ?? defaultRange.endDate);
return unwrap(
await client.get("api/v1/insight/risks-by-tag", { searchParams }),
InsightRisksByTagSchema
);
}
export async function getInsightPerformance(
client: KyInstance,
params: { startDate?: string | number; endDate?: string | number } = {}
): Promise<InsightPerformance> {
const defaultRange = currentMonthDateRange();
const startTs = normalizeToTimestamp(params.startDate ?? defaultRange.startDate);
const endTs = normalizeToTimestamp(params.endDate ?? defaultRange.endDate);
const searchParams = new URLSearchParams();
searchParams.set("startDate", String(startTs));
searchParams.set("endDate", String(endTs));
return unwrap(
await client.get("api/v1/insight/performance", { searchParams }),
InsightPerformanceSchema
);
}
export async function analyzeInsightRecord(
client: KyInstance,
recordId: string
): Promise<{ success: boolean; recordId: string }> {
await client.post(`api/v1/insight/analyze/${encodeURIComponent(recordId)}`);
return { success: true, recordId };
}
function normalizeToTimestamp(value: string | number): number {
if (typeof value === "number") {
return value < 1e11 ? value * 1000 : value;
}
const parsed = Number(value);
if (!isNaN(parsed) && value.trim() !== "") {
return parsed < 1e11 ? parsed * 1000 : parsed;
}
const date = new Date(value);
if (isNaN(date.getTime())) {
throw new Error(`Invalid date format: ${value}`);
}
return date.getTime();
}
function currentMonthDateRange(): { startDate: string; endDate: string } {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), 1);
@@ -1164,15 +1227,16 @@ export async function createDelegationForUser(
const closeapiToken = provisional.token;
const sealUrl = defaultSealUrl(corp, corp.source);
const customHeaders = resolveSealCustomHeaders(corp.seal);
const sealClient = createSealClientForUrl(sealUrl, undefined, customHeaders);
let sealResponse: { token?: string; accessToken?: string; data?: { token?: string } };
try {
sealResponse = await ky
.get(`${normalizeBaseUrl(sealUrl)}/api/auth/oauth2/session/oem-hosecloud`, {
sealResponse = await sealClient
.get("api/auth/oauth2/session/oem-hosecloud", {
searchParams: {
token: closeapiToken,
returnToken: "1"
},
timeout: 30000
}
})
.json<{ token?: string; accessToken?: string; data?: { token?: string } }>();
} catch (error: unknown) {
+160
View File
@@ -0,0 +1,160 @@
import { describe, expect, test } from "bun:test";
import { existsSync, unlinkSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import { type CorpConfig, CorpConfigSchema } from "../../core/config/types.js";
import { exportInsightReportToExcel, resolveInsightOutputFilePath } from "./insight-export.js";
describe("insight-export domain", () => {
test("resolveInsightOutputFilePath respects custom outputFile", () => {
const custom = "/tmp/test-insight-report.xlsx";
const res = resolveInsightOutputFilePath({
outputFile: custom,
corpName: "TestCorp"
});
expect(res).toBe(custom);
});
test("resolveInsightOutputFilePath respects toDownloads flag", () => {
const res = resolveInsightOutputFilePath({
toDownloads: true,
corpName: "渠道AI演示环境",
dateTag: "2026-09-12"
});
expect(res.startsWith(join(homedir(), "Downloads"))).toBe(true);
expect(res.endsWith("渠道AI演示环境_智能洞察报告_2026-09-12.xlsx")).toBe(true);
});
test("exportInsightReportToExcel generates valid multi-sheet Excel file", async () => {
const mockClient = {
get: (url: string) => {
if (url.includes("insight/stats")) {
return {
json: async () => ({
data: {
tagStats: [
{
tagId: "B.1.6",
tagName: "缺少验收/签收证明",
tagPath: "凭证/附件问题 > 凭证缺失 > 缺少验收/签收证明",
count: 7,
avgConfidence: 0.95,
errorCount: 5,
warningCount: 2
}
],
totalRisks: 7,
analyzedRisks: 7,
pendingRisks: 0
}
})
};
}
if (url.includes("insight/performance")) {
return {
json: async () => ({
data: {
metrics: {
approvalCount: { value: 24, trend: 0 },
accuracy: { value: 100, trend: 0 },
automationRate: { value: 75, trend: 0 },
riskCount: { value: 7, trend: 0 },
avgDuration: { value: 1041.4, trend: 0 }
},
sankeyData: {
nodes: [{ id: "辅助模式" }, { id: "添加评论" }],
links: [{ source: "辅助模式", target: "添加评论", value: 24 }]
}
}
})
};
}
if (url.includes("insight/risks-by-tag")) {
return {
json: async () => ({
data: {
tagId: "B.1.6",
tagName: "缺少验收/签收证明",
tagPath: "凭证/附件问题 > 凭证缺失 > 缺少验收/签收证明",
tagDescription: "维修费等未提供验收单",
risks: [
{
riskId: "risk-1",
recordId: "rec-1",
riskDetails: "【冰箱缺少验收单】无资产验收单",
riskLevel: "error",
documentType: "费用报销",
documentSN: "B26000009",
sourceSystem: "custom",
confidence: 0.95,
reasoning: "缺少零星采购验收单",
createdAt: "2026-09-11T06:31:01.616Z"
}
],
total: 1
}
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as unknown as KyInstance;
const mockCorp: CorpConfig = CorpConfigSchema.parse({
id: "test-corp",
name: "测试演示企业",
seal: {
url: "https://seal.example.com",
tenantSlug: "test"
},
source: {
type: "direct",
token: "fake-token",
sealUrl: "https://seal.example.com"
}
});
const outPath = `/tmp/test-insight-export-${Date.now()}.xlsx`;
try {
const result = await exportInsightReportToExcel(mockClient, mockCorp, {
outputFile: outPath,
startDate: "2026-09-01T00:00:00Z",
endDate: "2026-09-30T23:59:59Z"
});
expect(result.filePath).toBe(outPath);
expect(result.corpId).toBe("test-corp");
expect(result.totalRisks).toBe(7);
expect(result.tagCount).toBe(1);
expect(result.riskDetailCount).toBe(1);
expect(result.fileSizeBytes).toBeGreaterThan(0);
expect(existsSync(outPath)).toBe(true);
// Verify Excel Workbook content
const wb = new ExcelJS.Workbook();
await wb.xlsx.readFile(outPath);
expect(wb.worksheets.length).toBe(3);
const sheetNames = wb.worksheets.map((w) => w.name);
expect(sheetNames).toContain("审核效能与决策流向");
expect(sheetNames).toContain("Top 风险标签分析");
expect(sheetNames).toContain("风险单据穿透明细");
const overview = wb.getWorksheet("审核效能与决策流向");
expect(overview).toBeDefined();
const tags = wb.getWorksheet("Top 风险标签分析");
expect(tags?.rowCount).toBeGreaterThanOrEqual(2);
const details = wb.getWorksheet("风险单据穿透明细");
expect(details?.rowCount).toBeGreaterThanOrEqual(2);
} finally {
if (existsSync(outPath)) {
unlinkSync(outPath);
}
}
});
});
+386
View File
@@ -0,0 +1,386 @@
import { existsSync, mkdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, resolve } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import type { InsightPerformance } from "./types.js";
export interface InsightExportOptions {
startDate?: string | number;
endDate?: string | number;
limit?: number;
outputFile?: string;
toDownloads?: boolean;
}
export interface InsightExportResult {
filePath: string;
corpId: string;
corpName: string;
totalRisks: number;
tagCount: number;
riskDetailCount: number;
fileSizeBytes: number;
exportedAt: string;
}
export function resolveInsightOutputFilePath(options: {
outputFile?: string;
toDownloads?: boolean;
corpName?: string;
corpId?: string;
dateTag?: string;
}): string {
if (options.outputFile) {
const customPath = resolve(options.outputFile);
const parentDir = dirname(customPath);
if (!existsSync(parentDir)) {
mkdirSync(parentDir, { recursive: true });
}
return customPath;
}
const name = options.corpName || options.corpId || "企业";
const safeCorpName = name.replace(/[/\\?%*:|"<>]/g, "_").trim() || "企业";
const dateTag = options.dateTag || new Date().toISOString().slice(0, 10);
const fileName = `${safeCorpName}_智能洞察报告_${dateTag}.xlsx`;
let targetDir: string;
if (options.toDownloads) {
targetDir = resolve(homedir(), "Downloads");
} else {
targetDir = resolve(process.cwd(), "exports");
}
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
return resolve(targetDir, fileName);
}
export async function exportInsightReportToExcel(
client: KyInstance,
corp: CorpConfig,
options: InsightExportOptions = {}
): Promise<InsightExportResult> {
const corpName = corp.name || corp.id;
const targetFilePath = resolveInsightOutputFilePath({
outputFile: options.outputFile,
toDownloads: options.toDownloads,
corpName,
corpId: corp.id
});
const exportedAt = new Date().toISOString();
// 1. 并发拉取基础统计与性能指标
const [stats, perf] = await Promise.all([
api.getInsightStats(client, {
startDate: options.startDate ? String(options.startDate) : undefined,
endDate: options.endDate ? String(options.endDate) : undefined,
limit: options.limit ?? 100
}),
api.getInsightPerformance(client, {
startDate: options.startDate,
endDate: options.endDate
}).catch((): InsightPerformance => ({
metrics: {},
sankeyData: { nodes: [], links: [] }
}))
]);
// 2. 按标签下钻拉取具体的风险单据明细
const tagStats = stats.tagStats || [];
const riskDetailRows: Array<{
tagId: string;
tagName: string;
documentSN: string;
documentType: string;
riskLevel: string;
confidence: number;
riskDetails: string;
reasoning: string;
sourceDocumentURL?: string | null;
createdAt?: string | number | Date;
}> = [];
const maxTagsForDetails = Math.min(tagStats.length, options.limit ?? 50);
for (let i = 0; i < maxTagsForDetails; i++) {
const tag = tagStats[i];
if (!tag?.tagId) continue;
try {
const risksResult = await api.getInsightRisksByTag(client, {
tagId: tag.tagId,
startDate: options.startDate ? String(options.startDate) : undefined,
endDate: options.endDate ? String(options.endDate) : undefined
});
for (const r of risksResult.risks || []) {
riskDetailRows.push({
tagId: tag.tagId,
tagName: tag.tagName || tag.tagId,
documentSN: r.documentSN || "-",
documentType: r.documentType || "-",
riskLevel: r.riskLevel || "warning",
confidence: r.confidence ?? 0,
riskDetails: r.riskDetails || "-",
reasoning: r.reasoning || "-",
sourceDocumentURL: r.sourceDocumentURL,
createdAt: r.createdAt
});
}
} catch {
// 容错处理:单个标签下钻失败不中断整个报表生成
}
}
// 3. 构建 Excel Workbook
const workbook = new ExcelJS.Workbook();
workbook.creator = "seal-use";
workbook.lastModifiedBy = "seal-use";
workbook.created = new Date();
workbook.modified = new Date();
const headerFill: ExcelJS.Fill = {
type: "pattern",
pattern: "solid",
fgColor: { argb: "FF1E293B" } // Slate 800
};
const headerFont: Partial<ExcelJS.Font> = {
name: "Microsoft YaHei",
size: 11,
bold: true,
color: { argb: "FFFFFFFF" }
};
const borderStyle: Partial<ExcelJS.Borders> = {
top: { style: "thin", color: { argb: "FFE2E8F0" } },
bottom: { style: "thin", color: { argb: "FFE2E8F0" } },
left: { style: "thin", color: { argb: "FFE2E8F0" } },
right: { style: "thin", color: { argb: "FFE2E8F0" } }
};
// -------------------------------------------------------------
// Sheet 1: 审核效能概览与决策流向
// -------------------------------------------------------------
const overviewSheet = workbook.addWorksheet("审核效能与决策流向", {
views: [{ showGridLines: true }]
});
overviewSheet.columns = [
{ header: "分类", key: "category", width: 20 },
{ header: "指标名称", key: "name", width: 28 },
{ header: "数值", key: "val", width: 22 },
{ header: "环比/趋势", key: "trend", width: 18 },
{ header: "说明", key: "desc", width: 36 }
];
overviewSheet.getRow(1).height = 28;
overviewSheet.getRow(1).font = headerFont;
overviewSheet.getRow(1).fill = headerFill;
overviewSheet.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
const m = perf.metrics || {};
const overviewData = [
{ category: "基本信息", name: "企业名称", val: corpName, trend: "-", desc: `企业 ID: ${corp.id}` },
{ category: "基本信息", name: "报告生成时间", val: new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }), trend: "-", desc: "Seal AI 自动生成" },
{ category: "风险大盘", name: "发现风险总数", val: stats.totalRisks ?? 0, trend: "-", desc: `已分析 ${stats.analyzedRisks ?? 0} 项,待处理 ${stats.pendingRisks ?? 0} 项` },
{ category: "核心效能", name: "累计审核单据量", val: m.approvalCount?.value ?? "-", trend: m.approvalCount?.trend !== undefined ? `${m.approvalCount.trend}%` : "-", desc: "所选统计周期内" },
{ category: "核心效能", name: "AI 审核准确率", val: m.accuracy?.value !== undefined ? `${m.accuracy.value}%` : "-", trend: m.accuracy?.trend !== undefined ? `${m.accuracy.trend}%` : "-", desc: "人工与 AI 决策一致比率" },
{ category: "核心效能", name: "自动审核采纳率", val: m.automationRate?.value !== undefined ? `${m.automationRate.value}%` : "-", trend: m.automationRate?.trend !== undefined ? `${m.automationRate.trend}%` : "-", desc: "自动通过或无需人工干预占比" },
{ category: "核心效能", name: "平均审核耗时", val: m.avgDuration?.value !== undefined ? `${Math.round(m.avgDuration.value * 10) / 10} 秒` : "-", trend: m.avgDuration?.trend !== undefined ? `${m.avgDuration.trend}%` : "-", desc: "单张单据审核端到端耗时" }
];
for (const item of overviewData) {
const row = overviewSheet.addRow(item);
row.height = 22;
row.eachCell((cell) => {
cell.border = borderStyle;
cell.font = { name: "Microsoft YaHei", size: 10 };
cell.alignment = { vertical: "middle" };
});
}
const links = perf.sankeyData?.links || [];
if (links.length > 0) {
overviewSheet.addRow({});
const sankeyHeaderRow = overviewSheet.addRow(["决策流向", "流向阶段 (起点)", "走向阶段 (终点)", "流转单据数", "占比/流向说明"]);
sankeyHeaderRow.height = 24;
sankeyHeaderRow.font = { name: "Microsoft YaHei", size: 10, bold: true, color: { argb: "FF0F172A" } };
sankeyHeaderRow.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFE2E8F0" } };
sankeyHeaderRow.eachCell((cell) => {
cell.border = borderStyle;
cell.alignment = { vertical: "middle", horizontal: "center" };
});
for (const link of links) {
const row = overviewSheet.addRow({
category: "决策流向",
name: link.source,
val: link.target,
trend: link.value,
desc: "流向连接"
});
row.height = 20;
row.eachCell((cell) => {
cell.border = borderStyle;
cell.font = { name: "Microsoft YaHei", size: 9 };
cell.alignment = { vertical: "middle" };
});
}
}
// -------------------------------------------------------------
// Sheet 2: Top 风险标签分析
// -------------------------------------------------------------
const tagSheet = workbook.addWorksheet("Top 风险标签分析", {
views: [{ showGridLines: true }]
});
tagSheet.columns = [
{ header: "标签编号", key: "tagId", width: 14 },
{ header: "风险标签名称", key: "tagName", width: 26 },
{ header: "风险分类路径", key: "tagPath", width: 44 },
{ header: "风险出现次数", key: "count", width: 16 },
{ header: "严重错误数 (Error)", key: "errorCount", width: 20 },
{ header: "合规预警数 (Warning)", key: "warningCount", width: 22 },
{ header: "平均置信度", key: "avgConfidence", width: 16 }
];
tagSheet.getRow(1).height = 28;
tagSheet.getRow(1).font = headerFont;
tagSheet.getRow(1).fill = headerFill;
tagSheet.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
for (const tag of tagStats) {
const row = tagSheet.addRow({
tagId: tag.tagId || "-",
tagName: tag.tagName || "-",
tagPath: tag.tagPath || "-",
count: tag.count ?? 0,
errorCount: tag.errorCount ?? 0,
warningCount: tag.warningCount ?? 0,
avgConfidence: tag.avgConfidence ? `${Math.round(tag.avgConfidence * 100)}%` : "-"
});
row.height = 22;
row.eachCell((cell, colNumber) => {
cell.border = borderStyle;
cell.font = { name: "Microsoft YaHei", size: 10 };
cell.alignment = {
vertical: "middle",
horizontal: [1, 4, 5, 6, 7].includes(colNumber) ? "center" : "left"
};
if (colNumber === 5 && (tag.errorCount ?? 0) > 0) {
cell.font = { name: "Microsoft YaHei", size: 10, bold: true, color: { argb: "FFDC2626" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
}
if (colNumber === 6 && (tag.warningCount ?? 0) > 0) {
cell.font = { name: "Microsoft YaHei", size: 10, bold: true, color: { argb: "FFD97706" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
}
});
}
// -------------------------------------------------------------
// Sheet 3: 风险单据穿透明细
// -------------------------------------------------------------
const detailSheet = workbook.addWorksheet("风险单据穿透明细", {
views: [{ showGridLines: true }]
});
detailSheet.columns = [
{ header: "序号", key: "idx", width: 8 },
{ header: "风险标签", key: "tag", width: 24 },
{ header: "关联单据流水号", key: "documentSN", width: 20 },
{ header: "单据类型", key: "documentType", width: 16 },
{ header: "风险等级", key: "riskLevel", width: 14 },
{ header: "置信度", key: "confidence", width: 12 },
{ header: "风险具体描述", key: "riskDetails", width: 48 },
{ header: "AI 审核判断依据", key: "reasoning", width: 48 },
{ header: "单据链接", key: "sourceDocumentURL", width: 30 },
{ header: "发现时间", key: "createdAt", width: 22 }
];
detailSheet.getRow(1).height = 28;
detailSheet.getRow(1).font = headerFont;
detailSheet.getRow(1).fill = headerFill;
detailSheet.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
let rowIdx = 1;
for (const item of riskDetailRows) {
let createdAtStr = "-";
if (item.createdAt) {
const d = new Date(item.createdAt);
if (!isNaN(d.getTime())) {
createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
}
}
const row = detailSheet.addRow({
idx: rowIdx++,
tag: `${item.tagName} (${item.tagId})`,
documentSN: item.documentSN,
documentType: item.documentType,
riskLevel: item.riskLevel === "error" ? "严重错误" : "合规预警",
confidence: `${Math.round(item.confidence * 100)}%`,
riskDetails: item.riskDetails,
reasoning: item.reasoning,
sourceDocumentURL: item.sourceDocumentURL || "-",
createdAt: createdAtStr
});
row.height = 36;
row.eachCell((cell, colNumber) => {
cell.border = borderStyle;
cell.font = { name: "Microsoft YaHei", size: 9 };
cell.alignment = {
vertical: "middle",
horizontal: [1, 3, 4, 5, 6, 10].includes(colNumber) ? "center" : "left",
wrapText: [7, 8].includes(colNumber)
};
if (colNumber === 5) {
if (item.riskLevel === "error") {
cell.font = { name: "Microsoft YaHei", size: 9, bold: true, color: { argb: "FFDC2626" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
} else {
cell.font = { name: "Microsoft YaHei", size: 9, bold: true, color: { argb: "FFD97706" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
}
}
});
}
// 4. 写入本地文件
let dateTag: string | undefined;
if (options.startDate) {
const raw = String(options.startDate).slice(0, 10).replace(/[-:]/g, "");
dateTag = `${raw}至今`;
}
const targetPath = resolveInsightOutputFilePath({
outputFile: options.outputFile,
toDownloads: options.toDownloads,
corpName,
dateTag
});
await workbook.xlsx.writeFile(targetPath);
console.error(`智能洞察 Excel 报告已成功保存至: ${targetPath}`);
const stat = statSync(targetPath);
return {
filePath: targetPath,
corpId: corp.id,
corpName,
totalRisks: stats.totalRisks ?? 0,
tagCount: tagStats.length,
riskDetailCount: riskDetailRows.length,
fileSizeBytes: stat.size,
exportedAt
};
}
+2
View File
@@ -1,4 +1,6 @@
export * from "./types.js";
export * from "./builtin.js";
export * from "./strict.js";
export * from "./official-templates.js";
export * from "./loader.js";
export * from "./service.js";
+96
View File
@@ -109,4 +109,100 @@ describe("Rule Linter", () => {
expect(summaryRes.issues.length).toBe(2);
expect(summaryRes.issues.map((i) => i.ruleCode)).toEqual(["#0002", "#0003"]);
});
test("strictRuleLinter enforces higher standards for quantitative constraints, approvers, and exceptions", async () => {
const { strictRuleLinter } = await import("./strict.js");
// 1. 少于 10 字告警
const shortRes = strictRuleLinter({ description: "不能报销打车费" });
expect(shortRes.issues.some((i) => i.code === "SHORT_DESCRIPTION")).toBe(true);
// 2. 严格主观模糊词
const vagueRes = strictRuleLinter({ description: "出差打车费用差不多就行,必要时可报销" });
expect(vagueRes.issues.some((i) => i.code === "VAGUE_WORD" && i.snippet === "差不多")).toBe(true);
expect(vagueRes.issues.some((i) => i.code === "VAGUE_WORD" && i.snippet === "必要时")).toBe(true);
// 3. 严格例外条款直接判定为 Error
const exceptionRes = strictRuleLinter({ description: "差旅住宿单日不超过500元,特殊情况除外" });
const hanging = exceptionRes.issues.find((i) => i.code === "HANGING_EXCEPTION");
expect(hanging).toBeDefined();
expect(hanging?.level).toBe("error");
// 4. 缺少量化指标或刚性边界词
const noQuantRes = strictRuleLinter({ description: "出差应选择舒适快捷的交通工具前往" });
expect(noQuantRes.issues.some((i) => i.code === "LACKS_EXPLICIT_CONSTRAINT")).toBe(true);
// 5. 模糊审批人角色
const vagueApproverRes = strictRuleLinter({ description: "差旅住宿单日不超过500元,经领导同意可上浮并在【单据备注】说明" });
expect(vagueApproverRes.issues.some((i) => i.code === "AMBIGUOUS_APPROVER")).toBe(true);
// 6. 严格合格规则 (满分 100)
const strictPassRes = strictRuleLinter({
description: "差旅住宿费每人每日上限不得超过500元。若遇旺季超标,需经【部门总监】审批邮件同意,并在【单据备注】中说明原因且在【附件】中上传截图。"
});
expect(strictPassRes.passed).toBe(true);
expect(strictPassRes.score).toBe(100);
expect(strictPassRes.issues.length).toBe(0);
});
test("syncOfficialLinters writes plaintext files, overwrites modifications, and prunes rogue files", async () => {
const { syncOfficialLinters } = await import("./loader.js");
const { readFileSync } = await import("node:fs");
const testOfficialDir = join(tmpdir(), `seal-official-linter-test-${Date.now()}`);
try {
// 1. 首次同步:生成 builtin.ts 与 strict.ts 明文文件
const firstSync = syncOfficialLinters(testOfficialDir);
expect(firstSync.synced.sort()).toEqual(["builtin.ts", "strict.ts"]);
expect(existsSync(join(testOfficialDir, "builtin.ts"))).toBe(true);
expect(existsSync(join(testOfficialDir, "strict.ts"))).toBe(true);
const builtinPlaintext = readFileSync(join(testOfficialDir, "builtin.ts"), "utf8");
expect(builtinPlaintext).toContain("Seal 官方标准规则校验器");
expect(builtinPlaintext).toContain("export function lintRule");
const strictPlaintext = readFileSync(join(testOfficialDir, "strict.ts"), "utf8");
expect(strictPlaintext).toContain("Seal 官方严格风控规则校验器");
expect(strictPlaintext).toContain("STRICT_QUANTITATIVE_INDICATORS");
// 2. 模拟客户私自篡改 official/builtin.ts
writeFileSync(join(testOfficialDir, "builtin.ts"), "// HACKED CONTENT", "utf8");
expect(readFileSync(join(testOfficialDir, "builtin.ts"), "utf8")).toBe("// HACKED CONTENT");
// 3. 模拟客户在 official/ 下私自创建了多余的文件和子目录
writeFileSync(join(testOfficialDir, "my-custom-rule.ts"), "// Should be deleted", "utf8");
writeFileSync(join(testOfficialDir, "random.txt"), "garbage", "utf8");
mkdirSync(join(testOfficialDir, "extra-subfolder"), { recursive: true });
// 4. 再次执行同步:篡改的内容必须被官方重写,多余文件和子目录必须全部被干掉
const secondSync = syncOfficialLinters(testOfficialDir);
expect(secondSync.synced.sort()).toEqual(["builtin.ts", "strict.ts"]);
expect(secondSync.pruned.sort()).toEqual(["extra-subfolder", "my-custom-rule.ts", "random.txt"]);
// 验证官方文件已恢复明文
const restoredContent = readFileSync(join(testOfficialDir, "builtin.ts"), "utf8");
expect(restoredContent).toContain("Seal 官方标准规则校验器");
expect(restoredContent).not.toContain("// HACKED CONTENT");
// 验证多余文件已被清理干掉
expect(existsSync(join(testOfficialDir, "my-custom-rule.ts"))).toBe(false);
expect(existsSync(join(testOfficialDir, "random.txt"))).toBe(false);
expect(existsSync(join(testOfficialDir, "extra-subfolder"))).toBe(false);
} finally {
const { rmSync } = await import("node:fs");
rmSync(testOfficialDir, { recursive: true, force: true });
}
});
test("loadRuleLinter loads strict linter and isolates official directory from custom linters", async () => {
const loadedStrict = await loadRuleLinter("strict");
expect(loadedStrict.name).toBe("strict");
expect(loadedStrict.type).toBe("official");
const res = await loadedStrict.linter({ description: "原则上差旅住宿费尽量控制在500元以内" });
expect(res.passed).toBe(false);
expect(res.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
});
});
+212 -65
View File
@@ -1,38 +1,137 @@
import { existsSync, readdirSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { builtinRuleLinter } from "./builtin.js";
import { OFFICIAL_LINTER_TEMPLATES } from "./official-templates.js";
import { strictRuleLinter } from "./strict.js";
import type { RuleLintContext, RuleLintResult, RuleLintTarget, RuleLinterFn } from "./types.js";
export const PRIMARY_LINTERS_DIR = join(homedir(), ".config", "seal-use", "linters");
export const OFFICIAL_SUBDIR_NAME = "official";
export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, OFFICIAL_SUBDIR_NAME);
export const LOCAL_LINTERS_DIR = join(process.cwd(), "linters");
export interface LoadedLinter {
name: string;
type: "builtin" | "custom";
type: "builtin" | "official" | "custom";
filePath?: string;
linter: RuleLinterFn;
}
export function listAvailableLinters(): Array<{ name: string; type: "builtin" | "custom"; path?: string }> {
const list: Array<{ name: string; type: "builtin" | "custom"; path?: string }> = [
{ name: "builtin", type: "builtin" }
export interface AvailableLinterItem {
name: string;
type: "builtin" | "official" | "custom";
path?: string;
description?: string;
}
/**
* 强制同步官方内置校验器明文文件,并清理 official 子目录下的任何非官方多余文件。
* 用户 AI Agent 可直接阅读 official/ 下的源码;用户在 official/ 内所作的修改会被自动覆盖。
*/
export function syncOfficialLinters(officialDir = OFFICIAL_LINTERS_DIR): {
synced: string[];
pruned: string[];
} {
const synced: string[] = [];
const pruned: string[] = [];
try {
if (!existsSync(officialDir)) {
mkdirSync(officialDir, { recursive: true });
}
const officialFiles = Object.keys(OFFICIAL_LINTER_TEMPLATES);
// 1. 强制写入/覆盖官方校验器明文源码
for (const [filename, templateContent] of Object.entries(OFFICIAL_LINTER_TEMPLATES)) {
const targetPath = join(officialDir, filename);
let needsWrite = true;
if (existsSync(targetPath)) {
try {
const currentContent = readFileSync(targetPath, "utf8");
if (currentContent === templateContent) {
needsWrite = false;
}
} catch {
needsWrite = true;
}
}
if (needsWrite) {
writeFileSync(targetPath, templateContent, "utf8");
}
synced.push(filename);
}
// 2. 清理 official/ 目录下用户误建或第三方写入的多余文件/子目录
const existingEntries = readdirSync(officialDir, { withFileTypes: true });
for (const entry of existingEntries) {
if (!officialFiles.includes(entry.name)) {
const fullPath = join(officialDir, entry.name);
try {
if (entry.isDirectory()) {
rmSync(fullPath, { recursive: true, force: true });
} else {
unlinkSync(fullPath);
}
pruned.push(entry.name);
} catch {
// 忽略单项清理异常
}
}
}
} catch {
// 忽略目录无法创建或受限异常
}
return { synced, pruned };
}
/**
* 列出所有可用的规则校验器:包括 official/ 目录下的官方规则和外层目录下的用户自定义规则。
*/
export function listAvailableLinters(options: { syncOfficial?: boolean } = { syncOfficial: true }): AvailableLinterItem[] {
if (options.syncOfficial !== false) {
syncOfficialLinters();
}
const list: AvailableLinterItem[] = [
{
name: "builtin",
type: "builtin",
path: join(OFFICIAL_LINTERS_DIR, "builtin.ts"),
description: "Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"
},
{
name: "strict",
type: "official",
path: join(OFFICIAL_LINTERS_DIR, "strict.ts"),
description: "Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"
}
];
// 扫描用户自定义规则(仅扫描外层目录,忽略 official 子目录)
const searchDirs = [PRIMARY_LINTERS_DIR, LOCAL_LINTERS_DIR];
for (const dir of searchDirs) {
if (existsSync(dir)) {
try {
const files = readdirSync(dir);
for (const file of files) {
const entries = readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
// 排除 official 子目录及任何其他子目录
continue;
}
const file = entry.name;
if (file.endsWith(".ts") || file.endsWith(".js") || file.endsWith(".mjs")) {
const baseName = file.replace(/\.(ts|js|mjs)$/, "");
if (!list.some((item) => item.name === baseName)) {
list.push({
name: baseName,
type: "custom",
path: join(dir, file)
path: join(dir, file),
description: `用户自定义规则校验器 (${file})`
});
}
}
@@ -46,49 +145,96 @@ export function listAvailableLinters(): Array<{ name: string; type: "builtin" |
return list;
}
function resolveLinterPath(nameOrPath: string): string | undefined {
if (!nameOrPath || nameOrPath === "builtin") {
return undefined;
}
// 1. 绝对路径或显式相对路径
if (isAbsolute(nameOrPath) || nameOrPath.startsWith("./") || nameOrPath.startsWith("../")) {
const absPath = resolve(nameOrPath);
if (existsSync(absPath)) return absPath;
for (const ext of [".ts", ".js", ".mjs"]) {
if (existsSync(`${absPath}${ext}`)) return `${absPath}${ext}`;
}
}
// 2. 搜索预设目录
const candidates = [
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.ts`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.js`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.mjs`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.ts`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.js`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.mjs`)
];
for (const path of candidates) {
if (existsSync(path)) return path;
}
return undefined;
}
export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter> {
if (!nameOrPath || nameOrPath === "builtin") {
export function resolveLinterPath(nameOrPath: string): {
path?: string;
isOfficial?: boolean;
officialKind?: "builtin" | "strict";
} {
const norm = (nameOrPath || "").trim();
if (!norm || norm === "builtin" || norm === "default" || norm === "official/builtin" || norm === "official/builtin.ts") {
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
path: join(OFFICIAL_LINTERS_DIR, "builtin.ts"),
isOfficial: true,
officialKind: "builtin"
};
}
const resolvedPath = resolveLinterPath(nameOrPath);
if (norm === "strict" || norm === "official/strict" || norm === "official/strict.ts") {
return {
path: join(OFFICIAL_LINTERS_DIR, "strict.ts"),
isOfficial: true,
officialKind: "strict"
};
}
// 显式相对或绝对路径
if (isAbsolute(norm) || norm.startsWith("./") || norm.startsWith("../")) {
const absPath = resolve(norm);
if (existsSync(absPath)) return { path: absPath };
for (const ext of [".ts", ".js", ".mjs"]) {
if (existsSync(`${absPath}${ext}`)) return { path: `${absPath}${ext}` };
}
}
// 自定义规则名称:仅在外层目录中搜索,绝不在 official/ 子目录中搜索
const candidates = [
join(PRIMARY_LINTERS_DIR, `${norm}.ts`),
join(PRIMARY_LINTERS_DIR, `${norm}.js`),
join(PRIMARY_LINTERS_DIR, `${norm}.mjs`),
join(LOCAL_LINTERS_DIR, `${norm}.ts`),
join(LOCAL_LINTERS_DIR, `${norm}.js`),
join(LOCAL_LINTERS_DIR, `${norm}.mjs`)
];
for (const cPath of candidates) {
if (existsSync(cPath)) return { path: cPath };
}
return {};
}
export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter> {
// 每次加载前同步官方文件与清理多余文件
syncOfficialLinters();
const resolution = resolveLinterPath(nameOrPath ?? "builtin");
// 1. 处理官方内置校验器 (builtin / strict)
if (resolution.isOfficial) {
const fallbackFn = resolution.officialKind === "strict" ? strictRuleLinter : builtinRuleLinter;
const kind = resolution.officialKind === "strict" ? "official" : "builtin";
const officialPath = resolution.path;
if (officialPath && existsSync(officialPath)) {
try {
const fileUrl = pathToFileURL(officialPath).href;
const mod = await import(fileUrl);
const candidateFn = mod.default ?? mod.lintRule ?? mod.linter ?? mod.lint;
if (typeof candidateFn === "function") {
return {
name: resolution.officialKind ?? "builtin",
type: kind,
filePath: officialPath,
linter: wrapSafeLinter(candidateFn, fallbackFn)
};
}
} catch {
// 动态加载失败(如沙箱环境)安全回退至代码内置实现
}
}
return {
name: resolution.officialKind ?? "builtin",
type: kind,
filePath: officialPath,
linter: fallbackFn
};
}
// 2. 处理用户自定义校验器
const resolvedPath = resolution.path;
if (!resolvedPath) {
console.error(`⚠️ [linter] 未找到自定义校验器 "${nameOrPath}",已自动安全降级至内置校验器。`);
console.error(`⚠️ [linter] 未找到自定义校验器 "${nameOrPath}",已自动安全降级至内置标准校验器。`);
return {
name: "builtin",
type: "builtin",
@@ -103,7 +249,7 @@ export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter>
if (typeof candidateFn !== "function") {
console.error(
`⚠️ [linter] 自定义校验器 "${resolvedPath}" 未导出标准函数 (default / lintRule),已安全降级至内置校验器。`
`⚠️ [linter] 自定义校验器 "${resolvedPath}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`
);
return {
name: "builtin",
@@ -112,30 +258,15 @@ export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter>
};
}
// 执行期安全包装器:捕获用户自定义函数在运行期间可能抛出的任何未捕获异常
const safeLinter: RuleLinterFn = async (rule: RuleLintTarget, context?: RuleLintContext): Promise<RuleLintResult> => {
try {
const result = await candidateFn(rule, context);
if (result && typeof result === "object" && typeof result.score === "number" && Array.isArray(result.issues)) {
return result;
}
console.error(`⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。`);
return builtinRuleLinter(rule);
} catch (runtimeErr) {
console.error(`⚠️ [linter] 自定义校验器执行异常:`, runtimeErr);
return builtinRuleLinter(rule);
}
};
return {
name: nameOrPath,
name: nameOrPath ?? "custom",
type: "custom",
filePath: resolvedPath,
linter: safeLinter
linter: wrapSafeLinter(candidateFn, builtinRuleLinter)
};
} catch (err: any) {
console.error(
`⚠️ [linter] 加载自定义校验器脚本 "${resolvedPath}" 失败(语法错误或依赖缺失: ${err?.message ?? err}),已自动安全降级至内置校验器。`
`⚠️ [linter] 加载自定义校验器脚本 "${resolvedPath}" 失败(语法错误或依赖缺失: ${err?.message ?? err}),已自动安全降级至内置标准校验器。`
);
return {
name: "builtin",
@@ -144,3 +275,19 @@ export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter>
};
}
}
function wrapSafeLinter(candidateFn: any, fallbackFn: RuleLinterFn): RuleLinterFn {
return async (rule: RuleLintTarget, context?: RuleLintContext): Promise<RuleLintResult> => {
try {
const result = await candidateFn(rule, context);
if (result && typeof result === "object" && typeof result.score === "number" && Array.isArray(result.issues)) {
return result;
}
console.error(`⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。`);
return fallbackFn(rule, context);
} catch (runtimeErr) {
console.error(`⚠️ [linter] 自定义校验器执行异常:`, runtimeErr);
return fallbackFn(rule, context);
}
};
}
@@ -0,0 +1,337 @@
/**
* 官方内置规则校验器源码模板。
* 这些文件以明文 TypeScript 格式写入 ~/.config/seal-use/linters/official/ 目录,
* 供用户和 AI Agent 直接阅读、学习和执行。
*/
export const OFFICIAL_BUILTIN_LINTER_SOURCE = `/**
* ==============================================================================
* Seal 官方标准规则校验器 (Official Standard Rule Linter)
* ==============================================================================
*
* 存放路径: ~/.config/seal-use/linters/official/builtin.ts
* 维护说明: 本文件由 seal-use 官方自动同步并保护。
* 每次运行时系统会自动重写本文件并清理 official/ 目录下的非官方文件。
* 若您需要编写企业私有规则校验器,请将自定义 .ts 文件放置在外层的用户目录:
* ~/.config/seal-use/linters/ 即可,系统将自动识别并加载。
*/
export interface RuleLintTarget {
id?: string;
code?: string;
name?: string;
description: string;
scope?: string;
strictness?: string;
}
export interface RuleLintIssue {
level: "error" | "warning";
code: string;
message: string;
snippet?: string;
suggestion?: string;
}
export interface RuleLintResult {
score: number;
passed: boolean;
issues: RuleLintIssue[];
}
export const BUILTIN_VAGUE_WORDS = [
"原则上",
"尽量",
"适当",
"酌情",
"一般情况下",
"尽可能",
"合理控制",
"视情况",
"视具体情况"
];
export const BUILTIN_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const BUILTIN_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票"
];
export function lintRule(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则过短检查
if (text.length < 5) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",
suggestion: "请补充具体的费用类型、核验条件与限制标准"
});
}
// 2. 主观模糊词拦截
for (const word of BUILTIN_VAGUE_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "VAGUE_WORD",
snippet: word,
message: \`包含主观模糊词 "\${word}",容易导致大模型判定标准产生波动与幻觉\`,
suggestion: \`建议移除 "\${word}",改为具体的金额上限、枚举范围或刚性判定条件\`
});
}
}
// 3. 悬空例外条款检测
const matchedTrigger = BUILTIN_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = BUILTIN_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "warning",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: \`包含例外条款 "\${matchedTrigger}",但未指定 AI 从何处核验该例外成立的依据\`,
suggestion: "建议补充明确的凭据来源(例如:需在【单据备注】中说明原因,或在【附件】中上传审批截图)"
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 25 - warningCount * 10);
return {
score,
passed: errorCount === 0,
issues
};
}
export default lintRule;
`;
export const OFFICIAL_STRICT_LINTER_SOURCE = `/**
* ==============================================================================
* Seal 官方严格风控规则校验器 (Official Strict Risk Rule Linter)
* ==============================================================================
*
* 存放路径: ~/.config/seal-use/linters/official/strict.ts
* 维护说明: 本文件由 seal-use 官方自动同步并保护。
* 每次运行时系统会自动重写本文件并清理 official/ 目录下的非官方文件。
* 若您需要编写企业私有规则校验器,请将自定义 .ts 文件放置在外层的用户目录:
* ~/.config/seal-use/linters/ 即可,系统将自动识别并加载。
*/
export interface RuleLintTarget {
id?: string;
code?: string;
name?: string;
description: string;
scope?: string;
strictness?: string;
}
export interface RuleLintIssue {
level: "error" | "warning";
code: string;
message: string;
snippet?: string;
suggestion?: string;
}
export interface RuleLintResult {
score: number;
passed: boolean;
issues: RuleLintIssue[];
}
export const STRICT_VAGUE_WORDS = [
"原则上",
"尽量",
"适当",
"酌情",
"一般情况下",
"尽可能",
"合理控制",
"视情况",
"视具体情况",
"必要时",
"及时",
"适量",
"差不多",
"相关部门"
];
export const STRICT_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const STRICT_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票"
];
export const STRICT_QUANTITATIVE_INDICATORS = [
"¥",
"$",
"€",
"元",
"不得超过",
"不超过",
"超过",
"低于",
"不低于",
"最高",
"封顶",
"限额",
"禁止",
"严禁",
"必须",
"不予",
"仅限",
"每人",
"每日",
"每月",
"每年",
"每次",
"单笔"
];
export const STRICT_SPECIFIC_APPROVERS = [
"总监",
"VP",
"总经理",
"直接上级",
"部门负责人",
"项目经理",
"财务",
"分管领导",
"HR",
"CEO"
];
export function lintRule(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则长度检查 (严格模式下少于 10 字进行警告)
if (text.length < 5) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",
suggestion: "请补充具体的费用类型、核验条件与限制标准"
});
} else if (text.length < 10) {
issues.push({
level: "warning",
code: "SHORT_DESCRIPTION",
message: "规则描述偏短(少于 10 个字),可能缺少适用的单据范围或执行细节",
suggestion: "建议扩充核验场景、限制标准或异常处理方式"
});
}
// 2. 主观模糊词拦截(严格词库)
for (const word of STRICT_VAGUE_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "VAGUE_WORD",
snippet: word,
message: \`包含主观模糊词 "\${word}",在严格风控模式下容易引起审核判定分歧\`,
suggestion: \`请移除 "\${word}",明确量化标准或枚举具体允许的情形\`
});
}
}
// 3. 例外条款与凭据要求(严格模式下无凭据直接判定为 Error 阻断)
const matchedTrigger = STRICT_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = STRICT_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "error",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: \`包含例外条款 "\${matchedTrigger}",但未指定 AI 从何处核验该例外成立的凭证依据\`,
suggestion: "严格模式要求必须补充明确的核验来源(如:需在【单据备注】中说明原因,或在【附件】中提供审批截图)"
});
}
// 4. 定量约束或刚性边界检查
const hasNumber = /\\d+/.test(text);
const hasConstraint = STRICT_QUANTITATIVE_INDICATORS.some((kw) => text.includes(kw));
if (!hasNumber && !hasConstraint) {
issues.push({
level: "warning",
code: "LACKS_EXPLICIT_CONSTRAINT",
message: "规则缺乏明确的定量标准(如金额、天数、频次)或绝对刚性边界词(如不得、禁止、仅限)",
suggestion: "建议设定具体数值阈值或明确的禁止/准入条件,以便大模型精确判定"
});
}
// 5. 审批角色具体化检查
const mentionsApproval = /经(批准|审批|领导同意|领导签字)|审批通过/.test(text);
const hasSpecificApprover = STRICT_SPECIFIC_APPROVERS.some((approver) => text.includes(approver));
if (mentionsApproval && !hasSpecificApprover) {
issues.push({
level: "warning",
code: "AMBIGUOUS_APPROVER",
message: "规则提及审批例外,但未明确指定具体的审批角色(如部门总监、直接上级、财务负责人)",
suggestion: "建议明确审批人角色(例如:经【部门总监】批准,经【直接上级】邮件确认)"
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 30 - warningCount * 15);
return {
score,
passed: errorCount === 0,
issues
};
}
export default lintRule;
`;
export const OFFICIAL_LINTER_TEMPLATES: Record<string, string> = {
"builtin.ts": OFFICIAL_BUILTIN_LINTER_SOURCE,
"strict.ts": OFFICIAL_STRICT_LINTER_SOURCE
};
+166
View File
@@ -0,0 +1,166 @@
import type { RuleLintIssue, RuleLintResult, RuleLintTarget } from "./types.js";
export const STRICT_VAGUE_WORDS = [
"原则上",
"尽量",
"适当",
"酌情",
"一般情况下",
"尽可能",
"合理控制",
"视情况",
"视具体情况",
"必要时",
"及时",
"适量",
"差不多",
"相关部门"
];
export const STRICT_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const STRICT_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票"
];
export const STRICT_QUANTITATIVE_INDICATORS = [
"¥",
"$",
"€",
"元",
"不得超过",
"不超过",
"超过",
"低于",
"不低于",
"最高",
"封顶",
"限额",
"禁止",
"严禁",
"必须",
"不予",
"仅限",
"每人",
"每日",
"每月",
"每年",
"每次",
"单笔"
];
export const STRICT_SPECIFIC_APPROVERS = [
"总监",
"VP",
"总经理",
"直接上级",
"部门负责人",
"项目经理",
"财务",
"分管领导",
"HR",
"CEO"
];
export function strictRuleLinter(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则长度检查
if (text.length < 5) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",
suggestion: "请补充具体的费用类型、核验条件与限制标准"
});
} else if (text.length < 10) {
issues.push({
level: "warning",
code: "SHORT_DESCRIPTION",
message: "规则描述偏短(少于 10 个字),可能缺少适用的单据范围或执行细节",
suggestion: "建议扩充核验场景、限制标准或异常处理方式"
});
}
// 2. 主观模糊词拦截(严格集合)
for (const word of STRICT_VAGUE_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "VAGUE_WORD",
snippet: word,
message: `包含主观模糊词 "${word}",在严格风控模式下容易引起审核判定分歧`,
suggestion: `请移除 "${word}",明确量化标准或枚举具体允许的情形`
});
}
}
// 3. 例外条款与凭据要求(严格模式下无凭证直接判定为 error)
const matchedTrigger = STRICT_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = STRICT_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "error",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: `包含例外条款 "${matchedTrigger}",但未指定 AI 从何处核验该例外成立的凭证依据`,
suggestion: `严格模式要求必须补充明确的核验来源(如:"需在【单据备注】中说明原因" 或 "需在【附件】中提供审批截图")`
});
}
// 4. 定量约束或刚性边界检查
const hasNumber = /\d+/.test(text);
const hasConstraint = STRICT_QUANTITATIVE_INDICATORS.some((kw) => text.includes(kw));
if (!hasNumber && !hasConstraint) {
issues.push({
level: "warning",
code: "LACKS_EXPLICIT_CONSTRAINT",
message: "规则缺乏明确的定量标准(如金额、天数、频次)或绝对刚性边界词(如不得、禁止、仅限)",
suggestion: "建议设定具体数值阈值或明确的禁止/准入条件,以便大模型精确判定"
});
}
// 5. 审批角色具体化检查
const mentionsApproval = /经(批准|审批|领导同意|领导签字)|审批通过/.test(text);
const hasSpecificApprover = STRICT_SPECIFIC_APPROVERS.some((approver) => text.includes(approver));
if (mentionsApproval && !hasSpecificApprover) {
issues.push({
level: "warning",
code: "AMBIGUOUS_APPROVER",
message: "规则提及审批例外,但未明确指定具体的审批角色(如部门总监、直接上级、财务负责人)",
suggestion: "建议明确审批人角色(例如:经【部门总监】批准,经【直接上级】邮件确认)"
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 30 - warningCount * 15);
return {
score,
passed: errorCount === 0,
issues
};
}
export default strictRuleLinter;
+1 -1
View File
@@ -26,7 +26,7 @@ export const RuleLintItemResultSchema = z.object({
export const RuleLintBatchResultSchema = z.object({
linter: z.string(),
linterType: z.enum(["builtin", "custom"]),
linterType: z.enum(["builtin", "official", "custom"]),
totalRules: z.number(),
healthyCount: z.number(),
issueCount: z.number(),
+14 -2
View File
@@ -97,6 +97,7 @@ export async function pushMaterialPack(
secret: string;
docIdSuffix?: string;
materialPackFilePolicy?: MaterialPackFilePolicyPatch;
customHeaders?: Record<string, string>;
}
): Promise<MaterialPackPushResult> {
const prepared = await prepare(fileBuffer, fileName, config.materialPackFilePolicy)
@@ -127,7 +128,14 @@ export async function pushMaterialPack(
body.append("files", new File([new Uint8Array(attachment)], baseName))
const response = await fetch(
`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/attachments`,
{ method: "POST", headers: webhookHeaders({}, config.secret), body }
{
method: "POST",
headers: {
...(config.customHeaders ?? {}),
...webhookHeaders({}, config.secret)
},
body
}
)
if (!response.ok) throw new Error(`附件上传失败 ${response.status}: ${await response.text()}`)
const json = await response.json() as { data?: unknown; attachments?: Array<{ data: unknown }> }
@@ -142,7 +150,11 @@ export async function pushMaterialPack(
`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`,
{
method: "POST",
headers: { "Content-Type": "application/json", ...webhookHeaders({ webhookId, ...document }, config.secret) },
headers: {
...(config.customHeaders ?? {}),
"Content-Type": "application/json",
...webhookHeaders({ webhookId, ...document }, config.secret)
},
body: JSON.stringify(document),
}
)
+302
View File
@@ -0,0 +1,302 @@
import { describe, expect, test } from "bun:test";
import type { CorpConfig } from "../../../core/config/types.js";
import { formatRegressionDashboard, runRegressionTest } from "./service.js";
const mockSourceCorp: CorpConfig = {
id: "prod-corp",
name: "母企业",
environment: "production",
testCorpId: "test-corp",
source: { type: "seal" },
seal: { url: "https://prod.sealai.cc" }
} as any;
const mockTargetCorp: CorpConfig = {
id: "test-corp",
name: "测试靶场",
environment: "test",
prodCorpId: "prod-corp",
source: { type: "seal" },
seal: { url: "https://test.sealai.cc" }
} as any;
describe("regression service", () => {
test("enforces Red Line 1: rejects when target is not a test enterprise", async () => {
const invalidTarget: CorpConfig = {
...mockTargetCorp,
environment: "production"
} as any;
expect(
runRegressionTest({
sourceCorp: mockSourceCorp,
targetCorp: invalidTarget,
sourceClient: {} as any,
targetClient: {} as any,
samples: 5
})
).rejects.toThrow("非测试环境");
});
test("enforces Red Line 2: blocks when quota balance is insufficient", async () => {
const mockTargetClient = {
get: async (url: string) => {
if (url === "api/v1/billing/status") {
return {
json: async () => ({
code: 0,
data: {
features: [
{ code: "ai-approval", balance: 200, deductionAmount: 100 }
]
}
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
expect(
runRegressionTest({
sourceCorp: mockSourceCorp,
targetCorp: mockTargetCorp,
sourceClient: {} as any,
targetClient: mockTargetClient,
samples: 5 // requires 5 * 100 = 500 > 200
})
).rejects.toThrow("AI 审批额度不足");
});
test("executes dry-run preview and returns sample records without network mutations", async () => {
const mockSourceClient = {
get: async (url: string) => {
if (url.startsWith("api/v1/approvals")) {
return {
json: async () => ({
code: 0,
data: {
records: [
{
id: "run_1",
sourceDocumentSN: "SN001",
result: { decision: "APPROVE", summary: "通过" }
},
{
id: "run_2",
sourceDocumentSN: "SN002",
result: { decision: "REJECT", summary: "超标驳回" }
}
]
}
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const mockTargetClient = {
get: async (url: string) => {
if (url === "api/v1/billing/status") {
return {
json: async () => ({
code: 0,
data: {
features: [
{ code: "ai-approval", balance: 5000, deductionAmount: 100 }
]
}
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const result = await runRegressionTest({
sourceCorp: mockSourceCorp,
targetCorp: mockTargetCorp,
sourceClient: mockSourceClient,
targetClient: mockTargetClient,
samples: 2,
dryRun: true
});
expect(result.ok).toBe(true);
expect(result.verdict).toBe("DRY_RUN");
expect(result.safeToPublish).toBe(true);
expect(result.metrics.sampleCount).toBe(2);
expect(result.records[0]!.sn).toBe("SN001");
expect(result.records[0]!.prodDecision).toBe("APPROVE");
expect(result.records[1]!.sn).toBe("SN002");
expect(result.records[1]!.prodDecision).toBe("REJECT");
const dashboard = formatRegressionDashboard(result);
expect(dashboard).toContain("DRY-RUN");
expect(dashboard).toContain("2");
});
test("executes live regression, detects decision flips, and calculates concordance", async () => {
const mockSourceClient = {
get: async (url: string) => {
if (url === "api/v1/approvals/run_1") {
return {
json: async () => ({
code: 0,
data: {
id: "run_1",
sourceDocumentSN: "SN001",
document: { fields: [{ key: "f1", label: "事由", type: "TEXT", value: "团建" }] }
}
})
};
}
if (url === "api/v1/approvals/run_2") {
return {
json: async () => ({
code: 0,
data: {
id: "run_2",
sourceDocumentSN: "SN002",
document: { fields: [{ key: "f1", label: "事由", type: "TEXT", value: "招待" }] }
}
})
};
}
if (url.startsWith("api/v1/approvals")) {
return {
json: async () => ({
code: 0,
data: {
records: [
{
id: "run_1",
sourceDocumentSN: "SN001",
result: { decision: "APPROVE", summary: "原生产通过" }
},
{
id: "run_2",
sourceDocumentSN: "SN002",
result: { decision: "APPROVE", summary: "原生产通过" }
}
]
}
})
};
}
throw new Error(`Unexpected source url: ${url}`);
}
} as any;
const mockTargetClient = {
get: async (url: string, opts?: any) => {
const fullUrl = opts?.searchParams ? `${url}?${opts.searchParams.toString()}` : url;
if (url === "api/v1/billing/status") {
return {
json: async () => ({
code: 0,
data: {
features: [
{ code: "ai-approval", balance: 5000, deductionAmount: 100 }
]
}
})
};
}
if (url === "api/v1/agent/ai-approval/config" || url === "api/v1/integrations/webhook") {
return {
json: async () => ({
code: 0,
data: {
integrations: [
{
type: "webhook",
id: "wh_test",
name: "回放通道",
mode: "assisted",
incomingDocumentWebhook: { id: "in_1", url: "https://test.sealai.cc/api/v1/integrations/webhook/wh_test/document" },
outgoingResultWebhook: "https://test.sealai.cc/out",
incomingManualResultWebhook: { id: "man_1", url: "https://test.sealai.cc/man" },
secret: "sec123"
}
]
}
})
};
}
if (fullUrl.includes("sourceDocumentSN=REG_SN001")) {
return {
json: async () => ({
code: 0,
data: {
records: [
{
id: "test_run_1",
status: "completed",
result: { decision: "APPROVE", summary: "测试规则依然通过" }
}
]
}
})
};
}
if (fullUrl.includes("sourceDocumentSN=REG_SN002")) {
return {
json: async () => ({
code: 0,
data: {
records: [
{
id: "test_run_2",
status: "completed",
result: { decision: "REJECT", summary: "测试新规则判定超标驳回" }
}
]
}
})
};
}
throw new Error(`Unexpected target url: ${fullUrl}`);
}
} as any;
const mockFetch = async (url: string) => {
return {
ok: true,
status: 200,
json: async () => ({ success: true })
} as any;
};
const result = await runRegressionTest({
sourceCorp: mockSourceCorp,
targetCorp: mockTargetCorp,
sourceClient: mockSourceClient,
targetClient: mockTargetClient,
samples: 2,
pollIntervalMs: 5,
timeoutMs: 1000,
fetchFn: mockFetch as unknown as typeof fetch
});
expect(result.ok).toBe(false);
expect(result.verdict).toBe("REGRESSIONS_DETECTED");
expect(result.safeToPublish).toBe(false);
expect(result.metrics.sampleCount).toBe(2);
expect(result.metrics.matchCount).toBe(1);
expect(result.metrics.flipCount).toBe(1);
expect(result.metrics.concordanceRate).toBe(0.5);
expect(result.flips.length).toBe(1);
expect(result.flips[0]!.sn).toBe("SN002");
expect(result.flips[0]!.prodDecision).toBe("APPROVE");
expect(result.flips[0]!.testDecision).toBe("REJECT");
const dashboard = formatRegressionDashboard(result);
expect(dashboard).toContain("REGRESSIONS_DETECTED");
expect(dashboard).toContain("SN002");
expect(dashboard).toContain("50.0%");
});
});
+402
View File
@@ -0,0 +1,402 @@
import type { KyInstance } from "ky";
import { CliError } from "../../../cli/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import * as api from "../api.js";
import type { ApprovalRun } from "../types.js";
import {
ensureTestWebhookIntegration,
pushWebhookDocument,
transformApprovalRunToWebhookDocument
} from "../webhook-replay.js";
export interface RegressionTestOptions {
sourceCorp: CorpConfig;
targetCorp: CorpConfig;
sourceClient: KyInstance;
targetClient: KyInstance;
samples?: number;
dryRun?: boolean;
pollIntervalMs?: number;
timeoutMs?: number;
snPrefix?: string;
failOnFlips?: boolean;
fetchFn?: typeof fetch;
}
export interface RegressionSampleRecord {
sn: string;
sourceRecordId: string;
prodDecision: string;
prodSummary?: string;
testRecordId?: string;
testDecision?: string;
testSummary?: string;
status: "MATCHED" | "FLIPPED" | "FAILED" | "DRY_RUN";
diff?: {
from: string;
to: string;
reasonDiff?: string;
};
durationMs?: number;
error?: string;
}
export interface RegressionTestResult {
ok: boolean;
verdict: "CLEAN" | "REGRESSIONS_DETECTED" | "DRY_RUN";
safeToPublish: boolean;
timestamp: string;
sourceCorp: { id: string; name: string; environment: string };
targetCorp: { id: string; name: string; environment: string };
quota: {
featureCode: string;
balanceBefore: number;
deductionAmount: number;
estimatedRequired: number;
balanceAfter?: number;
};
metrics: {
sampleCount: number;
successCount: number;
failureCount: number;
matchCount: number;
flipCount: number;
concordanceRate: number;
};
flips: RegressionSampleRecord[];
records: RegressionSampleRecord[];
}
function normalizeDecision(val: unknown): string {
if (typeof val !== "string" || !val.trim()) return "UNKNOWN";
const upper = val.toUpperCase().trim();
if (upper === "APPROVE" || upper === "PASS") return "APPROVE";
if (upper === "REJECT" || upper === "DENIED") return "REJECT";
if (upper === "MANUAL" || upper === "ASSISTED") return "MANUAL";
if (upper === "ERROR" || upper === "FAILED") return "ERROR";
return upper;
}
export async function runRegressionTest(
options: RegressionTestOptions
): Promise<RegressionTestResult> {
const {
sourceCorp,
targetCorp,
sourceClient,
targetClient,
samples = 10,
dryRun = false,
pollIntervalMs = 2000,
timeoutMs = 45000,
snPrefix = "REG_",
fetchFn = fetch
} = options;
// 1. Red Line 1: Enterprise Isolation Guard
if (targetCorp.environment !== "test") {
throw new CliError(
`重放目标企业「${targetCorp.name}」(${targetCorp.id}) 的环境为「${targetCorp.environment}」,非测试环境!\n` +
`硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。`,
2,
`seal-use corps bind-test ${sourceCorp.id} <testCorpId>`
);
}
// 2. Red Line 2: Quota Pre-Flight Check
const billing = await api.getBillingStatus(targetClient);
const features = Array.isArray(billing.features) ? billing.features : [];
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
const balance = typeof aiApproval?.balance === "number" ? aiApproval.balance : 0;
const deductionAmount =
typeof aiApproval?.deductionAmount === "number" && aiApproval.deductionAmount > 0
? aiApproval.deductionAmount
: 120;
const estimatedRequired = samples * deductionAmount;
if (balance < estimatedRequired) {
throw new CliError(
`测试企业「${targetCorp.name}」AI 审批额度不足:当前剩余 ${balance} 点,本次回归抽样 ${samples} 笔需要约 ${estimatedRequired} 点。\n` +
`为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。`,
2,
`请为测试企业「${targetCorp.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1, Math.floor(balance / deductionAmount))})`
);
}
// 3. Extract Historical Production Samples
const runsResponse = await api.listApprovalRuns(sourceClient, {
limit: samples,
status: "completed"
});
let sourceRuns = Array.isArray(runsResponse.records) ? runsResponse.records : [];
if (sourceRuns.length === 0) {
// Fall back to any status if completed is empty
const fallbackResponse = await api.listApprovalRuns(sourceClient, { limit: samples });
sourceRuns = Array.isArray(fallbackResponse.records) ? fallbackResponse.records : [];
}
if (sourceRuns.length === 0) {
throw new CliError(
`在母企业「${sourceCorp.name}」(${sourceCorp.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,
2
);
}
// Slice to requested samples
sourceRuns = sourceRuns.slice(0, samples);
// Dry-run mode: return preview without network mutation
if (dryRun) {
const dryRunRecords: RegressionSampleRecord[] = sourceRuns.map((r) => {
const sn = r.sourceDocumentSN ?? r.id;
const rawDecision = (r as any)?.result?.decision ?? r.aiDecision ?? (r as any)?.decision;
const decision = normalizeDecision(rawDecision);
const prodSummary = (r as any)?.result?.summary ?? r.aiSummary;
return {
sn,
sourceRecordId: r.id,
prodDecision: decision,
prodSummary,
status: "DRY_RUN"
};
});
return {
ok: true,
verdict: "DRY_RUN",
safeToPublish: true,
timestamp: new Date().toISOString(),
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment ?? "production" },
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment ?? "test" },
quota: {
featureCode: "ai-approval",
balanceBefore: balance,
deductionAmount,
estimatedRequired
},
metrics: {
sampleCount: dryRunRecords.length,
successCount: dryRunRecords.length,
failureCount: 0,
matchCount: dryRunRecords.length,
flipCount: 0,
concordanceRate: 1.0
},
flips: [],
records: dryRunRecords
};
}
// 4. Resolve Target Webhook Channel in Test Corp
const targetWebhook = await ensureTestWebhookIntegration(targetClient, targetCorp);
// 5. Execute Batch Replay & HTTPS Run Polling
const records: RegressionSampleRecord[] = [];
for (const sourceSummaryRun of sourceRuns) {
const startTime = Date.now();
const originalSN = sourceSummaryRun.sourceDocumentSN ?? sourceSummaryRun.id;
const prodDecision = normalizeDecision(
(sourceSummaryRun as any)?.result?.decision ??
sourceSummaryRun.aiDecision ??
(sourceSummaryRun as any)?.decision
);
const prodSummary = (sourceSummaryRun as any)?.result?.summary ?? sourceSummaryRun.aiSummary;
try {
// Fetch full source run details with document fields
const fullSourceRun = await api.getApprovalRun(sourceClient, sourceSummaryRun.id);
// Reconstruct clean webhook document payload
const replayedSN = `${snPrefix}${originalSN}`;
const webhookDoc = transformApprovalRunToWebhookDocument(fullSourceRun, {
snPrefix,
docIdPrefix: snPrefix
});
// Push into target test enterprise webhook
await pushWebhookDocument(
targetWebhook.incomingDocumentWebhook.url,
targetWebhook.secret,
webhookDoc,
fetchFn,
resolveSealCustomHeaders(targetCorp.seal)
);
// Poll target enterprise for completion
let testRun: ApprovalRun | null = null;
const pollStart = Date.now();
while (Date.now() - pollStart < timeoutMs) {
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
const searchRes = await api.listApprovalRuns(targetClient, {
sourceDocumentSN: replayedSN,
limit: 1
});
if (searchRes.records && searchRes.records.length > 0) {
const candidate = searchRes.records[0]!;
if (candidate.status === "completed" || candidate.status === "failed") {
testRun = candidate;
break;
}
}
}
if (!testRun) {
records.push({
sn: originalSN,
sourceRecordId: sourceSummaryRun.id,
prodDecision,
prodSummary,
status: "FAILED",
error: `测试租户单据审核超时 (${Math.round(timeoutMs / 1000)}s 未完成)`,
durationMs: Date.now() - startTime
});
continue;
}
const testDecision = normalizeDecision(
(testRun as any)?.result?.decision ??
testRun.aiDecision ??
(testRun as any)?.decision ??
(testRun.status === "completed" ? "APPROVE" : "ERROR")
);
const testSummary = (testRun as any)?.result?.summary ?? testRun.aiSummary;
const isMatched = prodDecision === testDecision;
const sampleStatus: "MATCHED" | "FLIPPED" = isMatched ? "MATCHED" : "FLIPPED";
const recordItem: RegressionSampleRecord = {
sn: originalSN,
sourceRecordId: sourceSummaryRun.id,
prodDecision,
prodSummary,
testRecordId: testRun.id,
testDecision,
testSummary,
status: sampleStatus,
durationMs: Date.now() - startTime
};
if (!isMatched) {
recordItem.diff = {
from: prodDecision,
to: testDecision,
reasonDiff: testSummary && prodSummary && testSummary !== prodSummary
? `生产: ${prodSummary.slice(0, 60)}... -> 测试: ${testSummary.slice(0, 60)}...`
: undefined
};
}
records.push(recordItem);
} catch (err) {
records.push({
sn: originalSN,
sourceRecordId: sourceSummaryRun.id,
prodDecision,
prodSummary,
status: "FAILED",
error: err instanceof Error ? err.message : String(err),
durationMs: Date.now() - startTime
});
}
}
// 6. Aggregate Metrics & Verdict
const successRecords = records.filter((r) => r.status === "MATCHED" || r.status === "FLIPPED");
const matchRecords = records.filter((r) => r.status === "MATCHED");
const flipRecords = records.filter((r) => r.status === "FLIPPED");
const failureCount = records.filter((r) => r.status === "FAILED").length;
const matchCount = matchRecords.length;
const flipCount = flipRecords.length;
const totalEvaluated = matchCount + flipCount;
const concordanceRate = totalEvaluated > 0 ? matchCount / totalEvaluated : 0;
const hasRegressions = flipCount > 0;
const verdict: "CLEAN" | "REGRESSIONS_DETECTED" = hasRegressions ? "REGRESSIONS_DETECTED" : "CLEAN";
const safeToPublish = !hasRegressions && failureCount === 0;
// Post-check remaining balance if possible
let balanceAfter: number | undefined;
try {
const postBilling = await api.getBillingStatus(targetClient);
const postFeatures = Array.isArray(postBilling.features) ? postBilling.features : [];
const postAi = postFeatures.find((f: any) => f?.code === "ai-approval");
if (typeof postAi?.balance === "number") {
balanceAfter = postAi.balance;
}
} catch {
// optional post-check
}
return {
ok: !hasRegressions && failureCount === 0,
verdict,
safeToPublish,
timestamp: new Date().toISOString(),
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment ?? "production" },
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment ?? "test" },
quota: {
featureCode: "ai-approval",
balanceBefore: balance,
deductionAmount,
estimatedRequired,
balanceAfter
},
metrics: {
sampleCount: records.length,
successCount: successRecords.length,
failureCount,
matchCount,
flipCount,
concordanceRate: Number(concordanceRate.toFixed(4))
},
flips: flipRecords,
records
};
}
export function formatRegressionDashboard(result: RegressionTestResult): string {
const { sourceCorp, targetCorp, verdict, safeToPublish, metrics, quota, flips, records } = result;
const verdictBadge =
verdict === "CLEAN"
? "🟢 决策完全一致 (CLEAN - 无回归)"
: verdict === "DRY_RUN"
? "⚪ 预演模式 (DRY-RUN)"
: "🔴 发现决策翻转 (REGRESSIONS_DETECTED)";
const lines: string[] = [
"",
`🧪 [Seal Use Test] 规则回归测试矩阵: 生产「${sourceCorp.name}」-> 测试靶场「${targetCorp.name}」`,
` 判定: ${verdictBadge} · 准许发布: ${safeToPublish ? "YES (可安全上线)" : "NO (存在行为偏离/待复核)"}`,
" " + "─".repeat(65),
` 样本总数: ${metrics.sampleCount} | 一致通过: ${metrics.matchCount} | 决策翻转: ${metrics.flipCount} | 异常失败: ${metrics.failureCount}`,
` 一致率: ${(metrics.concordanceRate * 100).toFixed(1)}% | 消耗预估: ${quota.estimatedRequired} 点 (余量: ${quota.balanceBefore}${quota.balanceAfter !== undefined ? ` -> ${quota.balanceAfter}` : ""})`,
" " + "─".repeat(65)
];
if (flips.length > 0) {
lines.push(` ⚠️ 决策翻转清单 (${flips.length} 笔单据在新规则下结果改变):`);
for (const flip of flips) {
lines.push(` • 单据 [${flip.sn}]: 原生产判定「${flip.prodDecision}」 ➔ 测试新判定「${flip.testDecision}」`);
if (flip.diff?.reasonDiff) {
lines.push(` 理由差异: ${flip.diff.reasonDiff}`);
}
}
lines.push(" " + "─".repeat(65));
lines.push(" 👉 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。");
} else if (verdict === "CLEAN") {
lines.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% 吻合,无任何意外误杀或漏判。");
lines.push(` 👉 下一步操作: seal-use deploy hosecloud sync <signKey> 或发布正式版本`);
}
lines.push("");
return lines.join("\n");
}
+53 -2
View File
@@ -92,8 +92,12 @@ describe("sealTools", () => {
expect(sealTools.find((item) => item.name === "seal_contacts_last_sync_time_get")).toBeDefined();
});
test("includes the read-only insight stats tool", () => {
test("includes the read-only insight stats and analytics tools", () => {
expect(sealTools.find((item) => item.name === "seal_insight_stats_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_insight_risks_by_tag_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_insight_performance_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_insight_record_analyze")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_insight_export")).toBeDefined();
});
test("includes read-only financial data tools", () => {
@@ -121,6 +125,7 @@ describe("sealTools", () => {
expect(sealTools.find((item) => item.name === "seal_webhook_add")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_webhook_update")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_webhook_delete")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_webhook_replay")).toBeDefined();
});
test("includes deploy hosecloud tools", () => {
@@ -660,6 +665,9 @@ describe("sealTools", () => {
};
expect(result).toMatchObject({
url: "https://hose-corp-a.sealai.cc/approval-result/run-1",
sealResultUrl: "https://hose-corp-a.sealai.cc/approval-result/run-1",
type: "deep_link",
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
hoseDomain: "https://app.ekuaibao.com",
@@ -705,11 +713,54 @@ describe("sealTools", () => {
fakeApprovalRunsClient(requests),
{ sourceDocumentSN: "B26001965" },
fakeHoseContext()
) as { documentUrl?: string };
) as { documentUrl?: string; url?: string; type?: string };
expect(requests[0]).toContain("search=B26001965");
expect(requests[1]).toBe("api/v1/approvals/run-1");
expect(result.documentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
expect(result.type).toBe("deep_link");
expect(result.url).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
});
test("approval run url returns SSO link with identity, expiration, and warning when sso=true", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
expect(tool).toBeDefined();
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
const handler = tool!.handler as ToolHandler;
const result = (await handler(
fakeApprovalRunsClient(),
{ recordId: "run-1", sso: true, expiresIn: 3600 },
fakeHoseContext()
)) as {
url?: string;
ssoUrl?: string;
type?: string;
expiresIn?: number;
warning?: string;
identity?: { staffId?: string };
};
expect(result.type).toBe("sso_link");
expect(result.expiresIn).toBe(3600);
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
expect(result.url).toContain("path=%2Fapproval-result%2Frun-1");
expect(result.warning).toContain("安全警示");
expect(result.identity?.staffId).toBe("staff-a");
});
test("approval run url throws clear error when sso=true is used on non-hose enterprise", async () => {
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
await expect(
handler(
fakeApprovalRunsClient(),
{ recordId: "run-1", sso: true },
fakeContext()
)
).rejects.toThrow("SSO direct links currently support Hose-integrated enterprises");
});
test("approval run summary filters by local date and returns compact aggregates", async () => {
+225 -8
View File
@@ -3,11 +3,14 @@ import { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "./api.js";
import { defaultSealUrl, getHoseEnterpriseUrl, probeHoseDomain } from "../../core/auth/hose.js";
import { defaultSealUrl, getHoseEnterpriseUrl, getHoseProvisionalAuthLink, probeHoseDomain } from "../../core/auth/hose.js";
import { CorpConfig } from "../../core/config/types.js";
import { loadGlobalConfig } from "../../core/config/loader.js";
import { createSealClientForToken } from "../../core/http/factory.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../core/config/loader.js";
import { resolveCorpConfig } from "../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { searchApprovalContent } from "./search.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "./webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
import {
loadLocalRulesFile,
@@ -26,6 +29,7 @@ import {
extractApprovalRunAttachments
} from "./attachments.js";
import { exportApprovalRunsToExcel } from "./approval-runs-export.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "./insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
@@ -217,6 +221,58 @@ export const sealTools = [
params: { startDate?: string; endDate?: string; limit?: number }
) => api.getInsightStats(client, params)
},
{
name: "seal_insight_risks_by_tag_get",
description: "按风险标签查询智能洞察风险单据明细及 AI 分析依据",
parameters: z.object({
tagId: z.string().describe("风险标签 ID(如 B.1.1、B.1.6)"),
startDate: z.string().optional().describe("统计开始时间(ISO 8601)"),
endDate: z.string().optional().describe("统计结束时间(ISO 8601)")
}),
handler: async (
client: KyInstance,
params: { tagId: string; startDate?: string; endDate?: string }
) => api.getInsightRisksByTag(client, params)
},
{
name: "seal_insight_performance_get",
description: "查询智能洞察审核效能指标(自动化率、准确率等)及决策流向桑基图",
parameters: z.object({
startDate: z.union([z.string(), z.number()]).optional().describe("统计开始时间(ISO 8601 或毫秒时间戳)"),
endDate: z.union([z.string(), z.number()]).optional().describe("统计结束时间(ISO 8601 或毫秒时间戳)")
}),
handler: async (
client: KyInstance,
params: { startDate?: string | number; endDate?: string | number }
) => api.getInsightPerformance(client, params)
},
{
name: "seal_insight_record_analyze",
description: "对指定的审批单运行记录按需触发智能洞察风险分析",
parameters: z.object({
recordId: z.string().describe("审批单运行记录 ID (recordId)")
}),
handler: async (
client: KyInstance,
params: { recordId: string }
) => api.analyzeInsightRecord(client, params.recordId)
},
{
name: "seal_insight_export",
description: "导出智能洞察风险研报为高保真 Excel 文件(含效能概览、Top风险标签、风险单据穿透明细)",
parameters: z.object({
startDate: z.string().optional().describe("统计开始时间(ISO 8601 或时间戳)"),
endDate: z.string().optional().describe("统计结束时间(ISO 8601 或时间戳)"),
limit: z.number().int().positive().optional().describe("最多下钻分析的风险标签数量"),
outputFile: z.string().optional().describe("自定义 Excel 保存路径"),
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录")
}),
handler: async (
client: KyInstance,
params: InsightExportOptions,
context: ToolContext
) => exportInsightReportToExcel(client, context.corp, params)
},
{
name: "seal_expenses_list",
description: "分页查询费用明细",
@@ -1214,6 +1270,84 @@ export const sealTools = [
};
}
},
{
name: "seal_webhook_replay",
description: "将正式(生产)企业或指定企业的审批记录通过 Webhook 渠道重放到测试企业进行规则回归与模拟验证",
parameters: z.object({
recordId: z.string().optional().describe("待重放的单条审批记录 ID"),
sn: z.string().optional().describe("待重放的单据编号 (sourceDocumentSN)"),
sourceCorpId: z.string().optional().describe("单据来源企业 ID (若省略,基于绑定关系自动解析为正式企业)"),
targetCorpId: z.string().optional().describe("重放目标企业 ID (若省略,基于绑定关系自动解析为测试企业)"),
webhook: z.string().optional().describe("目标 Webhook 通道 ID 或名称"),
limit: z.number().optional().describe("批量重放单据数量 (默认 1)"),
status: z.string().optional().describe("单据状态过滤 (例如 completed, failed 等)"),
snPrefix: z.string().optional().describe("重放单号前缀"),
snSuffix: z.string().optional().describe("重放单号后缀"),
dryRun: z.boolean().optional().describe("是否仅执行预检转换而不实际推送 (默认 false)"),
force: z.boolean().optional().describe("若目标为生产环境,强制执行重放")
}),
handler: async (
client: KyInstance,
params: {
recordId?: string;
sn?: string;
sourceCorpId?: string;
targetCorpId?: string;
webhook?: string;
limit?: number;
status?: string;
snPrefix?: string;
snSuffix?: string;
dryRun?: boolean;
force?: boolean;
},
context: ToolContext
) => {
const selectCorpFn = (id?: string) => {
const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
return resolveCorpConfig(
corps,
{
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId,
corpId: id
},
getEnterprisesDirCandidates()
);
};
const { sourceCorp, targetCorp } = resolveReplayCorpPair(
{
sourceCorpId: params.sourceCorpId,
targetCorpId: params.targetCorpId,
activeCorp: context.corp,
force: params.force
},
selectCorpFn
);
const sourceClient = sourceCorp.id === context.corp.id ? client : await createSealClient(sourceCorp);
const targetClient = targetCorp.id === context.corp.id ? client : await createSealClient(targetCorp);
return executeApprovalRunsReplay({
query: {
recordId: params.recordId,
sn: params.sn,
limit: params.limit,
status: params.status
},
sourceClient,
targetClient,
sourceCorp,
targetCorp,
webhookSelector: params.webhook,
snPrefix: params.snPrefix,
snSuffix: params.snSuffix,
dryRun: params.dryRun
});
}
},
{
name: "seal_approval_runs_search",
description: "查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段",
@@ -1450,15 +1584,23 @@ export const sealTools = [
},
{
name: "seal_approval_run_url_get",
description: "获取合思企业协助链接,按需附带单据链接;支持只取企业协助链接,或按 Seal recordId/合思 sourceDocumentSN 查询单据链接",
description: "获取审批单的 Web 控制台直达链接或合思企业协助链接,支持纯深度链接与带安全警告的免密 SSO 链接",
parameters: z.object({
recordId: z.string().optional().describe("Seal approval run record ID"),
sourceDocumentSN: z.string().optional().describe("合思/易快报单号"),
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID")
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID"),
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (SSO link)"),
expiresIn: z.number().optional().describe("SSO 免密凭证有效秒数,默认 7200 (2小时)")
}),
handler: async (
client: KyInstance,
params: { recordId?: string; sourceDocumentSN?: string; sourceDocumentId?: string },
params: {
recordId?: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
sso?: boolean;
expiresIn?: number;
},
context: ToolContext
) => {
const hasDocumentLookup = Boolean(params.recordId || params.sourceDocumentSN || params.sourceDocumentId);
@@ -1467,7 +1609,68 @@ export const sealTools = [
const enterpriseAssistUrl = source.type === "hose" ? await getHoseEnterpriseUrl(context.corp) : undefined;
const documentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
const sealBaseUrl = resolveSealBaseUrl(context.corp);
const sealResultUrl = record?.id ? `${sealBaseUrl}/approval-result/${record.id}` : undefined;
let ssoUrl: string | undefined;
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
let warning: string | undefined;
const expiresIn = params.expiresIn ?? 7200;
if (params.sso) {
if (!record?.id) {
throw new Error("recordId or sourceDocumentSN is required to generate an SSO approval result URL");
}
if (source.type !== "hose") {
throw new Error(
`SSO direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use delegation create' for authorized access.`
);
}
const linkInfo = await getHoseProvisionalAuthLink(context.corp, expiresIn);
const provisionalToken = new URL(linkInfo.url).searchParams.get("accessToken");
if (!provisionalToken) {
throw new Error("Failed to obtain Hose provisional authentication token");
}
const targetPath = `/approval-result/${record.id}`;
ssoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
try {
const me = await api.getMe(client);
identity = {
name: me.user.name,
staffId: source.staffId,
isAdmin: me.user.isAdmin,
providerUserId: me.user.providerUserId
};
} catch {
identity = {
staffId: source.staffId
};
}
const userName = identity.name ?? "企业成员";
const roleLabel = identity.isAdmin ? " (管理员)" : "";
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
console.error(
`⚠️ 安全警示 (SSO 强化免密链接):\n` +
`• 身份主体:${userName}${roleLabel}\n` +
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
`• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!`
);
}
return {
url: params.sso ? ssoUrl : sealResultUrl,
sealResultUrl,
ssoUrl,
type: params.sso ? "sso_link" : "deep_link",
expiresIn: params.sso ? expiresIn : undefined,
identity,
warning,
enterpriseAssistUrl,
enterpriseUrl: enterpriseAssistUrl,
hoseDomain: source.type === "hose" ? normalizeUrl(source.domain) : undefined,
@@ -1788,7 +1991,11 @@ export const sealTools = [
mode: z.enum(["preview", "push"]).default("preview"),
webhook: z.string().optional().describe("Webhook ID 或名称;当租户仅配置 1 个通道时可省略")
}),
handler: async (client: KyInstance, params: { filePath: string; mode?: "preview" | "push"; webhook?: string }) => {
handler: async (
client: KyInstance,
params: { filePath: string; mode?: "preview" | "push"; webhook?: string },
context: ToolContext
) => {
const input = readMaterialPackFile(params.filePath);
if (params.mode !== "push") return previewMaterialPack(input.fileBuffer, input.fileName);
const integrations = await api.listWebhookIntegrations(client);
@@ -1806,7 +2013,8 @@ export const sealTools = [
return pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret,
materialPackFilePolicy: integration.materialPackFilePolicy
materialPackFilePolicy: integration.materialPackFilePolicy,
customHeaders: resolveSealCustomHeaders(context.corp.seal)
});
}
},
@@ -3218,6 +3426,15 @@ async function resolveApprovalRunForUrl(
return api.getApprovalRun(client, record.id);
}
function resolveSealBaseUrl(corp: CorpConfig): string {
if (corp.seal?.url) return corp.seal.url.replace(/\/+$/, "");
if (corp.source.type === "hose") return defaultSealUrl(corp, corp.source).replace(/\/+$/, "");
if ("sealUrl" in corp.source && typeof corp.source.sealUrl === "string" && corp.source.sealUrl) {
return corp.source.sealUrl.replace(/\/+$/, "");
}
return `https://${corp.id.toLowerCase()}.sealai.cc`;
}
function normalizeUrl(value: string): string {
return value.replace(/\/+$/, "");
}
+60 -1
View File
@@ -314,7 +314,15 @@ export const SealContactsLastSyncTimeSchema = z.object({
lastSyncTime: z.union([z.string(), z.number(), z.null()])
}).passthrough();
export const InsightTagStatsSchema = z.record(z.string(), z.unknown());
export const InsightTagStatsSchema = z.object({
tagId: z.string().optional(),
tagName: z.string().optional(),
tagPath: z.string().optional(),
count: z.number().default(0),
avgConfidence: z.number().default(0),
errorCount: z.number().default(0),
warningCount: z.number().default(0)
}).passthrough();
export const InsightStatsSchema = z.object({
tagStats: z.array(InsightTagStatsSchema).default([]),
@@ -323,6 +331,52 @@ export const InsightStatsSchema = z.object({
pendingRisks: z.number().default(0)
}).passthrough();
export const InsightRiskItemSchema = z.object({
riskId: z.string().optional(),
recordId: z.string().optional(),
riskDetails: z.string().default(""),
riskLevel: z.string().default("warning"),
documentType: z.string().default(""),
documentSN: z.string().default(""),
sourceSystem: z.string().default(""),
sourceDocumentURL: z.string().nullable().optional(),
confidence: z.number().default(0),
reasoning: z.string().default(""),
createdAt: z.union([z.string(), z.number(), z.date()]).optional()
}).passthrough();
export const InsightRisksByTagSchema = z.object({
tagId: z.string(),
tagName: z.string().default(""),
tagPath: z.string().default(""),
tagDescription: z.string().default(""),
risks: z.array(InsightRiskItemSchema).default([]),
total: z.number().default(0)
}).passthrough();
export const InsightPerformanceMetricSchema = z.object({
value: z.number().default(0),
trend: z.number().default(0)
}).passthrough();
export const InsightPerformanceSchema = z.object({
metrics: z.object({
approvalCount: InsightPerformanceMetricSchema.optional(),
accuracy: InsightPerformanceMetricSchema.optional(),
automationRate: InsightPerformanceMetricSchema.optional(),
riskCount: InsightPerformanceMetricSchema.optional(),
avgDuration: InsightPerformanceMetricSchema.optional()
}).passthrough().default({}),
sankeyData: z.object({
nodes: z.array(z.object({ id: z.string() }).passthrough()).default([]),
links: z.array(z.object({
source: z.string(),
target: z.string(),
value: z.number().default(0)
}).passthrough()).default([])
}).passthrough().default({ nodes: [], links: [] })
}).passthrough();
const DataRecordSchema = z.record(z.string(), z.unknown());
export const ExpenseListDataSchema = z.object({
@@ -593,7 +647,12 @@ export type SealDepartment = z.infer<typeof SealDepartmentSchema>;
export type SealDepartmentListData = z.infer<typeof SealDepartmentListDataSchema>;
export type SealDepartmentUsersData = z.infer<typeof SealDepartmentUsersDataSchema>;
export type SealContactsLastSyncTime = z.infer<typeof SealContactsLastSyncTimeSchema>;
export type InsightTagStats = z.infer<typeof InsightTagStatsSchema>;
export type InsightStats = z.infer<typeof InsightStatsSchema>;
export type InsightRiskItem = z.infer<typeof InsightRiskItemSchema>;
export type InsightRisksByTag = z.infer<typeof InsightRisksByTagSchema>;
export type InsightPerformanceMetric = z.infer<typeof InsightPerformanceMetricSchema>;
export type InsightPerformance = z.infer<typeof InsightPerformanceSchema>;
export type ExpenseListData = z.infer<typeof ExpenseListDataSchema>;
export type InvoiceListData = z.infer<typeof InvoiceListDataSchema>;
export type SimulationApprovalDefinition = z.infer<typeof SimulationApprovalDefinitionSchema>;
+363
View File
@@ -0,0 +1,363 @@
import { describe, expect, test } from "bun:test";
import {
transformApprovalRunToWebhookDocument,
sanitizeFieldForWebhook,
extractWebhookInfo,
pushWebhookDocument,
selectWebhookIntegration,
resolveReplayCorpPair,
ensureTestWebhookIntegration,
executeApprovalRunsReplay,
ALLOWED_WEBHOOK_FIELD_TYPES
} from "./webhook-replay.js";
import type { ApprovalRun, WebhookIntegration } from "./types.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("webhook-replay domain", () => {
const mockWebhookIntegration: WebhookIntegration = {
type: "webhook",
id: "wh-int-1",
name: "测试通道",
mode: "assisted",
incomingDocumentWebhook: {
id: "wh_hook_abc123",
url: "https://example.sealai.cc/api/v1/integrations/webhook/wh_hook_abc123/document"
},
outgoingResultWebhook: "https://example.com/callback",
incomingManualResultWebhook: {
id: "wh_hook_abc123",
url: "https://example.sealai.cc/api/v1/integrations/webhook/wh_hook_abc123/manual-result"
},
secret: "test-secret-key-xyz",
materialPackFilePolicy: {
minFileSizeBytes: 500,
allowedExtensions: [".pdf"]
}
};
test("sanitizeFieldForWebhook preserves allowed types and normalizes unknown types", () => {
// Known allowed types
for (const type of ALLOWED_WEBHOOK_FIELD_TYPES) {
const field = { key: "f1", label: "F1", type, value: "val" };
expect(sanitizeFieldForWebhook(field, 0)).toEqual({
key: "f1",
label: "F1",
type,
value: "val"
});
}
// Hose REFERENCE type -> TEXT
const refField = {
key: "ref",
label: "关联单据",
type: "REFERENCE",
value: "DOC123"
};
expect(sanitizeFieldForWebhook(refField, 1)).toEqual({
key: "ref",
label: "关联单据",
type: "TEXT",
value: "DOC123"
});
// Object value with unknown type -> OBJECT
const objField = {
key: "extra",
label: "附加信息",
type: "CUSTOM_UNKNOWN",
value: { foo: "bar" }
};
expect(sanitizeFieldForWebhook(objField, 2)).toEqual({
key: "extra",
label: "附加信息",
type: "OBJECT",
value: { foo: "bar" }
});
// Recursive LIST fields normalization
const listField = {
key: "items",
label: "明细列表",
type: "LIST",
value: [
[
{ key: "cost", label: "金额", type: "AMOUNT", value: { amount: 50 } },
{ key: "subRef", label: "引用", type: "REFERENCE", value: "R1" }
]
]
};
const sanitizedList = sanitizeFieldForWebhook(listField, 3);
expect(sanitizedList.type).toBe("LIST");
const rows = sanitizedList.value as any[][];
expect(rows[0]![0].type).toBe("AMOUNT");
expect(rows[0]![1].type).toBe("TEXT");
});
test("transformApprovalRunToWebhookDocument builds clean document payload with prefix/suffix support", () => {
const run: ApprovalRun = {
id: "run-uuid-1",
status: "failed",
sourceSystem: "hosecloud",
sourceDocumentSN: "BX2026090001",
sourceDocumentId: "ID01DocABC",
createdAt: 1789115000000,
document: {
id: "doc-uuid-1",
sn: "BX2026090001",
fields: [
{ key: "title", label: "标题", type: "TEXT", value: "出差报销" },
{ key: "supplement", label: "补充说明", type: "REFERENCE", value: "none" }
]
}
};
// Default transformation
const doc = transformApprovalRunToWebhookDocument(run);
expect(doc.type).toBe("document");
expect(doc.documentSN).toBe("BX2026090001");
expect(doc.documentId).toBe("ID01DocABC");
expect(doc.startTime).toBe(1789115000);
expect(doc.fields.length).toBe(2);
expect(doc.fields[0]!.type).toBe("TEXT");
expect(doc.fields[1]!.type).toBe("TEXT");
// With prefix and suffix
const modified = transformApprovalRunToWebhookDocument(run, {
snPrefix: "TEST_",
snSuffix: "_v2"
});
expect(modified.documentSN).toBe("TEST_BX2026090001_v2");
expect(modified.documentId).toBe("TEST_ID01DocABC_v2");
});
test("extractWebhookInfo extracts webhookId, baseUrl, and documentEndpoint", () => {
const info = extractWebhookInfo("https://staging.sealai.cc/api/v1/integrations/webhook/wh_abc_123/document");
expect(info.baseUrl).toBe("https://staging.sealai.cc");
expect(info.webhookId).toBe("wh_abc_123");
expect(info.documentEndpoint).toBe("https://staging.sealai.cc/api/v1/integrations/webhook/wh_abc_123/document");
expect(() => extractWebhookInfo("https://staging.sealai.cc/invalid/path")).toThrow(
/Webhook URL 必须包含/
);
});
test("pushWebhookDocument signs and posts payload", async () => {
let capturedUrl = "";
let capturedMethod = "";
let capturedHeaders: Record<string, string> = {};
let capturedBody = "";
const mockFetch = (async (url: any, init: any) => {
capturedUrl = String(url);
capturedMethod = init.method;
capturedHeaders = init.headers;
capturedBody = init.body;
return new Response(JSON.stringify({ data: { success: true, documentId: "doc-out-1" } }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}) as any;
const doc = {
type: "document" as const,
documentId: "doc-1",
documentSN: "SN-1",
startTime: 123456,
fields: [{ key: "f1", label: "L1", type: "TEXT", value: "v1" }]
};
const res = await pushWebhookDocument(
mockWebhookIntegration.incomingDocumentWebhook.url,
mockWebhookIntegration.secret,
doc,
mockFetch
);
expect(capturedUrl).toBe(mockWebhookIntegration.incomingDocumentWebhook.url);
expect(capturedMethod).toBe("POST");
expect(capturedHeaders["Authorization"]).toBe(`Bearer ${mockWebhookIntegration.secret}`);
expect(capturedHeaders["x-webhook-signature"]).toBeDefined();
expect(capturedHeaders["x-webhook-timestamp"]).toBeDefined();
expect(capturedHeaders["x-webhook-nonce"]).toBeDefined();
expect(JSON.parse(capturedBody)).toEqual(doc);
expect(res).toEqual({ data: { success: true, documentId: "doc-out-1" } });
});
test("pushWebhookDocument throws error when endpoint returns failure status", async () => {
const mockFetch = (async () => {
return new Response("Invalid parameter: missing field", { status: 400 });
}) as any;
const doc = {
type: "document" as const,
documentId: "doc-1",
documentSN: "SN-1",
startTime: null,
fields: []
};
expect(
pushWebhookDocument(
mockWebhookIntegration.incomingDocumentWebhook.url,
mockWebhookIntegration.secret,
doc,
mockFetch
)
).rejects.toThrow(/Webhook 单据推送失败 \(400\)/);
});
test("selectWebhookIntegration auto-locks single integration and selects by query", () => {
// Single integration
expect(selectWebhookIntegration([mockWebhookIntegration])).toBe(mockWebhookIntegration);
// Multiple integrations - select by name
const second: WebhookIntegration = {
...mockWebhookIntegration,
id: "wh-int-2",
name: "备用通道"
};
expect(selectWebhookIntegration([mockWebhookIntegration, second], "备用通道")).toBe(second);
expect(selectWebhookIntegration([mockWebhookIntegration, second], "wh-int-1")).toBe(mockWebhookIntegration);
// Ambiguous without selector
expect(() => selectWebhookIntegration([mockWebhookIntegration, second])).toThrow(/存在多个 Webhook 通道/);
// Empty integrations
expect(() => selectWebhookIntegration([])).toThrow(/未配置任何 Webhook 集成通道/);
});
describe("resolveReplayCorpPair", () => {
const prodCorp = {
id: "corp-prod",
name: "生产企业",
environment: "production",
sourceType: "hose",
testCorpId: "corp-test",
seal: {
url: "https://prod.sealai.cc",
tenantSlug: "prod",
endpoints: { approvalStylePreferences: "api/pref" }
},
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
staffId: "s1",
corpId: "c1",
appKey: "k",
appSecurity: "s"
}
} as unknown as CorpConfig;
const testCorp = {
id: "corp-test",
name: "测试企业",
environment: "test",
sourceType: "seal",
prodCorpId: "corp-prod",
seal: {
url: "https://test.sealai.cc",
tenantSlug: "test",
endpoints: { approvalStylePreferences: "api/pref" }
},
source: {
type: "seal",
token: "tok",
sealUrl: "https://test.sealai.cc",
expiresIn: 3600,
staffId: "seal"
}
} as unknown as CorpConfig;
const dummyCorpMap = new Map<string, CorpConfig>([
["corp-prod", prodCorp],
["corp-test", testCorp]
]);
const mockSelectCorp = (id?: string): CorpConfig => {
const found = id ? dummyCorpMap.get(id) : undefined;
if (!found) throw new Error(`Unknown corp: ${id}`);
return found;
};
test("auto-infers testCorp as target when activeCorp is production and has testCorpId", () => {
const pair = resolveReplayCorpPair({ activeCorp: prodCorp }, mockSelectCorp);
expect(pair.sourceCorp.id).toBe("corp-prod");
expect(pair.targetCorp.id).toBe("corp-test");
});
test("auto-infers prodCorp as source when activeCorp is test and has prodCorpId", () => {
const pair = resolveReplayCorpPair({ activeCorp: testCorp }, mockSelectCorp);
expect(pair.sourceCorp.id).toBe("corp-prod");
expect(pair.targetCorp.id).toBe("corp-test");
});
test("respects explicit sourceCorpId and targetCorpId", () => {
const pair = resolveReplayCorpPair(
{ sourceCorpId: "corp-prod", targetCorpId: "corp-test", activeCorp: prodCorp },
mockSelectCorp
);
expect(pair.sourceCorp.id).toBe("corp-prod");
expect(pair.targetCorp.id).toBe("corp-test");
});
test("blocks pushing to production enterprise when target is production and force is false", () => {
expect(() =>
resolveReplayCorpPair(
{ sourceCorpId: "corp-test", targetCorpId: "corp-prod", activeCorp: testCorp, force: false },
mockSelectCorp
)
).toThrow(/标记为生产正式环境/);
});
test("permits pushing to production enterprise when force is true", () => {
const pair = resolveReplayCorpPair(
{ sourceCorpId: "corp-test", targetCorpId: "corp-prod", activeCorp: testCorp, force: true },
mockSelectCorp
);
expect(pair.targetCorp.id).toBe("corp-prod");
});
});
describe("ensureTestWebhookIntegration", () => {
test("automatically provisions assisted test webhook if none exist in test corp", async () => {
let savedIntegration: any = null;
const testCorp = {
id: "corp-test",
name: "测试企业",
environment: "test",
sourceType: "seal",
seal: {
url: "https://test.sealai.cc",
tenantSlug: "test",
endpoints: { approvalStylePreferences: "api/pref" }
},
source: {
type: "seal",
token: "tok",
sealUrl: "https://test.sealai.cc",
expiresIn: 3600,
staffId: "seal"
}
} as unknown as CorpConfig;
const mockClient: any = {
get: () => ({
json: async () => ({ data: { integrations: [] } })
}),
post: (_url: string, opts: any) => {
savedIntegration = opts.json.integrations[0];
return {
json: async () => ({ data: { success: true } })
};
}
};
const integration = await ensureTestWebhookIntegration(mockClient, testCorp);
expect(integration.name).toBe("(Seal测-回放通道)");
expect(integration.mode).toBe("assisted");
expect(savedIntegration).toBeDefined();
expect(savedIntegration.name).toBe("(Seal测-回放通道)");
});
});
});
+594
View File
@@ -0,0 +1,594 @@
import type { KyInstance } from "ky";
import type { ApprovalRun, WebhookIntegration } from "./types.js";
import type { MaterialField } from "./material-pack/types.js";
import { webhookHeaders } from "./material-pack/signature.js";
import { CliError } from "../../cli/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import * as api from "./api.js";
export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([
"TEXT",
"NUMBER",
"DATE",
"AMOUNT",
"PERSON",
"ATTACHMENT",
"DATE_RANGE",
"DEPARTMENT",
"LIST",
"CITY",
"OBJECT"
]);
export interface WebhookReplayDocument {
type: "document";
documentId: string;
documentSN: string;
startTime: number | null;
fields: MaterialField[];
}
export interface WebhookReplayTransformOptions {
snSuffix?: string;
snPrefix?: string;
docIdSuffix?: string;
docIdPrefix?: string;
}
export function sanitizeFieldForWebhook(field: unknown, index: number): MaterialField {
const f = field && typeof field === "object" ? (field as Record<string, unknown>) : {};
const rawType = typeof f.type === "string" ? f.type.toUpperCase().trim() : "";
const key =
typeof f.key === "string" && f.key.trim()
? f.key.trim()
: typeof f.label === "string" && f.label.trim()
? f.label.trim()
: `field_${index}`;
const label = typeof f.label === "string" && f.label.trim() ? f.label.trim() : key;
let value = f.value !== undefined ? f.value : null;
// Recursively sanitize rows inside LIST fields
if (rawType === "LIST" && Array.isArray(value)) {
value = value.map((row) => {
if (Array.isArray(row)) {
return row.map((nested, nestedIdx) => sanitizeFieldForWebhook(nested, nestedIdx));
}
return row;
});
}
let type = rawType;
if (!ALLOWED_WEBHOOK_FIELD_TYPES.has(type)) {
if (Array.isArray(value)) {
type = "LIST";
} else if (value && typeof value === "object") {
type = "OBJECT";
} else if (typeof value === "number") {
type = "NUMBER";
} else {
type = "TEXT";
}
}
return {
key,
label,
type,
value
};
}
export function transformApprovalRunToWebhookDocument(
record: ApprovalRun,
options: WebhookReplayTransformOptions = {}
): WebhookReplayDocument {
const rawDoc = record.document as Record<string, unknown> | undefined;
const originalSN =
record.sourceDocumentSN ??
(typeof rawDoc?.sn === "string" ? rawDoc.sn : undefined) ??
(typeof rawDoc?.sourceDocumentSN === "string" ? rawDoc.sourceDocumentSN : undefined) ??
record.id;
const originalDocId =
record.sourceDocumentId ??
(typeof rawDoc?.id === "string" ? rawDoc.id : undefined) ??
(typeof rawDoc?.sourceDocumentId === "string" ? rawDoc.sourceDocumentId : undefined) ??
record.documentId ??
record.id;
const snPrefix = options.snPrefix ?? "";
const snSuffix = options.snSuffix ?? "";
const docIdPrefix = options.docIdPrefix ?? snPrefix;
const docIdSuffix = options.docIdSuffix ?? snSuffix;
const documentSN = `${snPrefix}${originalSN}${snSuffix}`;
const documentId = `${docIdPrefix}${originalDocId}${docIdSuffix}`;
const startTime =
typeof rawDoc?.sourceStartTime === "number"
? rawDoc.sourceStartTime
: typeof record.createdAt === "number"
? Math.floor(record.createdAt / 1000)
: null;
const rawFields = Array.isArray(rawDoc?.fields) ? rawDoc.fields : [];
const fields = rawFields.map((field, idx) => sanitizeFieldForWebhook(field, idx));
return {
type: "document",
documentId,
documentSN,
startTime,
fields
};
}
export function extractWebhookInfo(url: string): { baseUrl: string; webhookId: string; documentEndpoint: string } {
const parsed = new URL(url);
const match = parsed.pathname.match(/\/webhook\/([^/]+)/);
if (!match) {
throw new Error(`Webhook URL 必须包含 /webhook/{webhookId}/document,收到: ${url}`);
}
const webhookId = match[1]!;
const baseUrl = `${parsed.protocol}//${parsed.host}`;
const documentEndpoint = `${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`;
return { baseUrl, webhookId, documentEndpoint };
}
export async function pushWebhookDocument(
endpointUrl: string,
secret: string,
document: WebhookReplayDocument,
fetchFn: typeof fetch = fetch,
customHeaders: Record<string, string> = {}
): Promise<unknown> {
const { webhookId, documentEndpoint } = extractWebhookInfo(endpointUrl);
const headers = {
...customHeaders,
"Content-Type": "application/json",
...webhookHeaders({ webhookId, ...document }, secret)
};
const response = await fetchFn(documentEndpoint, {
method: "POST",
headers,
body: JSON.stringify(document)
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Webhook 单据推送失败 (${response.status}): ${errorText}`);
}
return response.json();
}
export function selectWebhookIntegration(
integrations: WebhookIntegration[],
selector?: string,
corpId?: string
): WebhookIntegration {
if (selector) {
const normalized = selector.trim().toLowerCase();
const found = integrations.find(
(item) =>
item.id.toLowerCase() === normalized ||
item.name.toLowerCase() === normalized ||
item.incomingDocumentWebhook.id.toLowerCase() === normalized
);
if (!found) {
const available = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`未找到匹配 "${selector}" 的 Webhook 集成通道。可用通道: [${available}]`);
}
return found;
}
if (integrations.length === 1) {
return integrations[0]!;
}
if (integrations.length > 1) {
const replayHook = integrations.find(
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
);
if (replayHook) {
return replayHook;
}
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
}
throw new CliError(
"当前租户未配置任何 Webhook 集成通道。",
1,
`seal-use webhook add --name <name> --result-url <url>${corpId ? ` --corp ${corpId}` : ""}`
);
}
export interface ResolveReplayCorpPairOptions {
sourceCorpId?: string;
targetCorpId?: string;
activeCorp: CorpConfig;
force?: boolean;
}
export interface ReplayCorpPair {
sourceCorp: CorpConfig;
targetCorp: CorpConfig;
}
export function resolveReplayCorpPair(
options: ResolveReplayCorpPairOptions,
selectCorpFn: (id?: string) => CorpConfig
): ReplayCorpPair {
let sourceCorp: CorpConfig;
let targetCorp: CorpConfig;
const { sourceCorpId, targetCorpId, activeCorp, force } = options;
if (sourceCorpId && targetCorpId) {
sourceCorp = selectCorpFn(sourceCorpId);
targetCorp = selectCorpFn(targetCorpId);
} else if (sourceCorpId && !targetCorpId) {
sourceCorp = selectCorpFn(sourceCorpId);
if (sourceCorp.testCorpId) {
targetCorp = selectCorpFn(sourceCorp.testCorpId);
} else if (activeCorp.id !== sourceCorp.id && activeCorp.environment === "test") {
targetCorp = activeCorp;
} else {
targetCorp = activeCorp;
}
} else if (!sourceCorpId && targetCorpId) {
targetCorp = selectCorpFn(targetCorpId);
if (targetCorp.prodCorpId) {
sourceCorp = selectCorpFn(targetCorp.prodCorpId);
} else if (activeCorp.id !== targetCorp.id) {
sourceCorp = activeCorp;
} else {
sourceCorp = activeCorp;
}
} else {
// Neither source nor target explicitly given
if (activeCorp.environment === "test") {
targetCorp = activeCorp;
if (activeCorp.prodCorpId) {
sourceCorp = selectCorpFn(activeCorp.prodCorpId);
} else {
sourceCorp = activeCorp;
}
} else if (activeCorp.environment === "production") {
sourceCorp = activeCorp;
if (activeCorp.testCorpId) {
targetCorp = selectCorpFn(activeCorp.testCorpId);
} else {
targetCorp = activeCorp;
}
} else {
sourceCorp = activeCorp;
targetCorp = activeCorp;
}
}
// Safety guard: prevent pushing replay test records to production
if (targetCorp.environment === "production" && !force) {
throw new CliError(
`目标企业「${targetCorp.name}」(${targetCorp.id}) 标记为生产正式环境 (production)。\n` +
`为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。`,
1,
`seal-use webhook replay --target-corp <testCorpId>${sourceCorp.id !== targetCorp.id ? ` --source-corp ${sourceCorp.id}` : ""}`
);
}
return { sourceCorp, targetCorp };
}
export async function ensureTestWebhookIntegration(
client: KyInstance,
corp: CorpConfig,
selector?: string
): Promise<WebhookIntegration> {
const endpoint = corp.seal?.endpoints?.approvalStylePreferences ?? "api/v1/agent/ai-approval/config";
const integrations = await api.listWebhookIntegrations(client, endpoint);
if (selector || integrations.length > 0) {
return selectWebhookIntegration(integrations, selector, corp.id);
}
// If 0 integrations and target is a test enterprise: automatically provision an assisted replay channel
if (corp.environment === "test" || corp.id.toLowerCase().includes("test")) {
console.error(`[webhook-replay] 测试企业「${corp.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);
const sealUrl = (corp.seal.url ?? (corp.source as any)?.sealUrl ?? `https://${corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const created = await api.addWebhookIntegration(
client,
sealUrl,
{
name: "(Seal测-回放通道)",
mode: "assisted",
outgoingResultWebhook: `${sealUrl}/api/v1/integrations/webhook/replay-mock-callback`
},
corp.seal.endpoints.approvalStylePreferences
);
return created;
}
throw new CliError(
`当前租户「${corp.name}」未配置任何 Webhook 集成通道。`,
1,
`seal-use webhook add --name <name> --result-url <url> --corp ${corp.id}`
);
}
export interface ReplayRecordsQuery {
recordId?: string;
recordIds?: string[];
sn?: string;
sns?: string[];
limit?: number;
status?: string;
startDate?: string;
endDate?: string;
}
export interface ReplayApprovalRunsOptions {
query: ReplayRecordsQuery;
sourceClient: KyInstance;
targetClient: KyInstance;
sourceCorp: CorpConfig;
targetCorp: CorpConfig;
webhookSelector?: string;
snPrefix?: string;
snSuffix?: string;
docIdPrefix?: string;
docIdSuffix?: string;
dryRun?: boolean;
fetchFn?: typeof fetch;
}
export interface ReplayExecutionRecord {
originalRecord: {
id: string;
sourceSystem?: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
};
replayedDocument?: {
documentSN: string;
documentId: string;
fieldCount: number;
};
document?: WebhookReplayDocument;
success: boolean;
error?: string;
pushResult?: unknown;
}
export interface ReplayExecutionResult {
success: boolean;
dryRun: boolean;
sourceCorp: { id: string; name: string; environment?: string };
targetCorp: { id: string; name: string; environment?: string };
targetWebhook?: {
id: string;
name: string;
mode: string;
incomingDocumentWebhookUrl: string;
};
totalCount: number;
successCount: number;
failureCount: number;
// Backward-compatible fields for single-record replay
originalRecord?: {
id: string;
sourceSystem?: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
};
replayedDocument?: {
documentSN: string;
documentId: string;
fieldCount: number;
};
document?: WebhookReplayDocument;
pushResult?: unknown;
records: ReplayExecutionRecord[];
}
export async function executeApprovalRunsReplay(
options: ReplayApprovalRunsOptions
): Promise<ReplayExecutionResult> {
const {
query,
sourceClient,
targetClient,
sourceCorp,
targetCorp,
webhookSelector,
snPrefix,
snSuffix,
docIdPrefix,
docIdSuffix,
dryRun,
fetchFn = fetch
} = options;
let runs: ApprovalRun[] = [];
if (query.recordId) {
const run = await api.getApprovalRun(sourceClient, query.recordId);
runs.push(run);
} else if (query.recordIds && query.recordIds.length > 0) {
for (const id of query.recordIds) {
runs.push(await api.getApprovalRun(sourceClient, id));
}
} else if (query.sn) {
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: query.sn, limit: 1 });
if (!search.records.length) {
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${query.sn}」的审批记录。`);
}
runs.push(search.records[0]!);
} else if (query.sns && query.sns.length > 0) {
for (const sn of query.sns) {
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: sn, limit: 1 });
if (!search.records.length) {
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${sn}」的审批记录。`);
}
runs.push(search.records[0]!);
}
} else if (query.limit !== undefined) {
const search = await api.listApprovalRuns(sourceClient, {
limit: query.limit,
status: query.status,
startDate: query.startDate,
endDate: query.endDate
});
if (!search.records.length) {
throw new Error(`在企业「${sourceCorp.name}」中未检索到符合条件的审批记录。`);
}
runs = search.records;
} else {
throw new Error(
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]"
);
}
const docs = runs.map((run) => ({
run,
doc: transformApprovalRunToWebhookDocument(run, {
snPrefix,
snSuffix,
docIdPrefix,
docIdSuffix
})
}));
if (dryRun) {
let integrationInfo = {
id: "preview-webhook",
name: webhookSelector ?? "预览目标通道",
mode: "assisted",
incomingDocumentWebhookUrl: `${targetCorp.seal.url}/api/v1/integrations/webhook/preview`
};
try {
const integrations = await api.listWebhookIntegrations(
targetClient,
targetCorp.seal.endpoints.approvalStylePreferences
);
if (integrations.length > 0) {
const matched = selectWebhookIntegration(integrations, webhookSelector, targetCorp.id);
integrationInfo = {
id: matched.id,
name: matched.name,
mode: matched.mode,
incomingDocumentWebhookUrl: matched.incomingDocumentWebhook.url
};
}
} catch {
// In dryRun, keep preview info if list fails
}
const records: ReplayExecutionRecord[] = docs.map(({ run, doc }) => ({
originalRecord: {
id: run.id,
sourceSystem: run.sourceSystem,
sourceDocumentSN: run.sourceDocumentSN,
sourceDocumentId: run.sourceDocumentId
},
document: doc,
success: true
}));
const isSingle = records.length === 1;
return {
dryRun: true,
success: true,
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment },
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment },
targetWebhook: integrationInfo,
totalCount: records.length,
successCount: records.length,
failureCount: 0,
originalRecord: isSingle ? records[0]!.originalRecord : undefined,
document: isSingle ? records[0]!.document : undefined,
records
};
}
const integration = await ensureTestWebhookIntegration(targetClient, targetCorp, webhookSelector);
const targetWebhook = {
id: integration.id,
name: integration.name,
mode: integration.mode,
incomingDocumentWebhookUrl: integration.incomingDocumentWebhook.url
};
const records: ReplayExecutionRecord[] = [];
let successCount = 0;
let failureCount = 0;
for (const { run, doc } of docs) {
console.error(`[webhook-replay] 正在向 Webhook 通道「${integration.name}」推送单据: ${doc.documentSN}...`);
try {
const pushResult = await pushWebhookDocument(
integration.incomingDocumentWebhook.url,
integration.secret,
doc,
fetchFn,
resolveSealCustomHeaders(targetCorp.seal)
);
records.push({
originalRecord: {
id: run.id,
sourceSystem: run.sourceSystem,
sourceDocumentSN: run.sourceDocumentSN,
sourceDocumentId: run.sourceDocumentId
},
replayedDocument: {
documentSN: doc.documentSN,
documentId: doc.documentId,
fieldCount: doc.fields.length
},
pushResult,
success: true
});
successCount += 1;
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
records.push({
originalRecord: {
id: run.id,
sourceSystem: run.sourceSystem,
sourceDocumentSN: run.sourceDocumentSN,
sourceDocumentId: run.sourceDocumentId
},
replayedDocument: {
documentSN: doc.documentSN,
documentId: doc.documentId,
fieldCount: doc.fields.length
},
error: errorMsg,
success: false
});
failureCount += 1;
}
}
const isSingle = records.length === 1;
return {
success: failureCount === 0,
dryRun: false,
sourceCorp: { id: sourceCorp.id, name: sourceCorp.name, environment: sourceCorp.environment },
targetCorp: { id: targetCorp.id, name: targetCorp.name, environment: targetCorp.environment },
targetWebhook,
totalCount: records.length,
successCount,
failureCount,
originalRecord: isSingle ? records[0]!.originalRecord : undefined,
replayedDocument: isSingle ? records[0]!.replayedDocument : undefined,
pushResult: isSingle ? records[0]!.pushResult : undefined,
records
};
}