Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d00fa1b960 | ||
|
|
4541f9c4fb | ||
|
|
fed0a8464c | ||
|
|
ed57c0cd42 | ||
|
|
4c4a80b10c | ||
|
|
3ae39bcc08 | ||
|
|
b49f25a2bc | ||
|
|
b1769d8a25 | ||
|
|
0582bc7898 | ||
|
|
6d310ba945 | ||
|
|
41e0bfba71 | ||
|
|
b5dd3560b6 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.13",
|
||||
"version": "0.11.15",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.15] - 2026-10-23
|
||||
|
||||
### Added
|
||||
- Merge pull request #261 from yunyingk/mac15/simulation-local-search
|
||||
- Add local search for simulation batches
|
||||
- Merge pull request #260 from yunyingk/mac15/approval-raw-json
|
||||
- Add native JSON fallback for approval record details
|
||||
|
||||
|
||||
## [0.11.14] - 2026-10-22
|
||||
|
||||
### Added
|
||||
- 审核记录 `list/search` 新增 `--has-extra-risk`,按系统检测的 `warning/error` 筛选额外风险,返回风险明细、数量与无法判断的记录数;沿用现有查询条件和分页,100 条为共享单页上限,没有独立的总量限制(#257)。
|
||||
|
||||
### Fixed
|
||||
- 合思与 Seal 协助链接自动返回实际人员姓名及已核实的角色或权限;身份查询失败明确标记未核实,Skill 要求汇报人员姓名、目标系统、权限和有效期(#258)。
|
||||
|
||||
## [0.11.13] - 2026-10-20
|
||||
|
||||
### Added
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.13",
|
||||
"version": "0.11.15",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.13: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.15: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.13
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.13)
|
||||
version: 0.11.15
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.15)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -123,7 +123,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| --- | --- | --- |
|
||||
| 第一次接入、不会找凭据、需要截图 | `references/first-time-user.md` | 用户交付材料后,再读 `enterprise-onboarding.md` 做来源决策 |
|
||||
| 判断材料来源、Token 边界、cURL、Hose 提权 | `references/enterprise-onboarding.md` | 需要具体域名/员工探测时,再读 `hose-enterprise-init.md` |
|
||||
| Hose 登录检查、认证失败、生成授权链接 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
|
||||
| Hose 登录检查、认证失败、合思/Seal 协助链接及登录人员身份 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
|
||||
| Hose 域名探测、角色/员工发现、管理员选择 | `references/hose-enterprise-init.md` | 不要先加载部署或规则文档 |
|
||||
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
|
||||
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
|
||||
|
||||
@@ -16,6 +16,31 @@ Default output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDo
|
||||
|
||||
If there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.
|
||||
|
||||
## Find Runs With Extra Risks
|
||||
|
||||
审核结果区分 `result.rulesResult[].findings`(绑定规则的检查发现)与 `result.otherFindings[]`(额外发现)。额外发现中的 `warning` / `error` 计为额外风险,`info` 仅为提示;不根据最终审批结论或摘要文本推断额外风险。
|
||||
|
||||
前端将规则内发现映射为 `source: "rule"`,额外发现映射为 `source: "system"` 并标注“系统检测”。这是展示层根据字段来源派生的分类,不是当前审核列表接口已接入的筛选参数。“系统检测”也可能是 `info`,因此不能将全部系统检测项都计为风险。原始等级枚举为 `info / warning / error`;页面的“需复核”还可能由规则的 `UNCERTAIN` 结论派生。
|
||||
|
||||
```bash
|
||||
# 从最近一页 100 条记录中筛出含额外风险的记录
|
||||
seal-use approval-runs list --has-extra-risk --limit 100 --corp <corpId>
|
||||
|
||||
# 在时间、运行状态、人工结果等条件下筛选
|
||||
seal-use approval-runs search --has-extra-risk --status completed --startDate 2026-10-01 --endDate 2026-10-22 --limit 100 --corp <corpId>
|
||||
|
||||
# 继续检查下一页;offset 按上游记录数推进,不按 matched 推进
|
||||
seal-use approval-runs list --has-extra-risk --limit 100 --offset 100 --corp <corpId>
|
||||
```
|
||||
|
||||
- `limit` 是筛选前读取的页大小(默认 50,最多 100),不会为凑满命中数自动翻页。`offset` 同样作用于上游结果集。
|
||||
- `scanned` 是本页上游返回的条数,`matched` 是所有本地筛选后的返回条数。`total` 保留上游筛选条件下的记录总数,**不是额外风险单据总数**。
|
||||
- 启用筛选时,`unknown` 是通过其他本地条件后,因结果缺失或格式异常而无法判断额外风险的条数。这些记录不混入命中列表;无筛选读取时,可通过 `extraFindingsStatus: "unknown"` 定位。
|
||||
- 记录摘要包含 `otherFindingCount`(含 info 的额外发现总数)、`extraRiskCount`、`hasExtraRisk`、`extraFindingsStatus`。空数组表示已知无额外发现;缺失/异常数据的数量和布尔值为 `null`。
|
||||
- 本筛选读取结构化的 `otherFindings`。前端还会转换旧版结果中的 `otherRisks` 等字段,但本筛选不推断旧版关联关系;未提供 `otherFindings` 的历史记录计为 `unknown`。
|
||||
- 启用筛选时,每条命中记录附带 `extraRisks`,含风险标题、等级和描述。一次审核可能有多个风险,`matched` 按审核记录计数;同一单据多次审核也可能返回多条记录。
|
||||
- `approval-runs result <recordId> --summary` 和 `get <recordId> --summary` 的 AI 结果也返回上述计数字段。查看全部额外发现可用 `get <recordId> --fields result.otherFindings`。
|
||||
|
||||
## Read Compact Run Detail
|
||||
|
||||
Use `--summary` for most diagnosis and support questions.
|
||||
@@ -35,6 +60,25 @@ seal-use approval-runs get <recordId> --corp <corpId> --fields document.keyField
|
||||
|
||||
Avoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.
|
||||
|
||||
## Native JSON Compatibility Fallback
|
||||
|
||||
日常读取优先使用 `--summary`、`--fields` 及专用查询命令。只有后台字段结构变化导致常规解析失败,或确需原生响应供本地脚本处理时,使用以下兜底入口:
|
||||
|
||||
```bash
|
||||
# 原生响应写入文件,适合大数据和脚本处理
|
||||
seal-use approval-runs get <recordId> --raw-json --output-file ./approval-raw.json --corp <corpId>
|
||||
|
||||
# 明确需要完整终端输出时
|
||||
seal-use approval-runs get <recordId> --raw-json --full --corp <corpId>
|
||||
```
|
||||
|
||||
- 常规 `get` 未指定 `--summary/--fields` 时已经返回完整记录,但会解开上游 `data` 包装、校验已知字段类型,并添加 `aliases`、`humanResult` 等派生字段;这不等于原生响应。
|
||||
- `--raw-json` 保留上游响应的 JSON 结构(包括 `data` 包装、嵌套内容、新字段及上游同名字段),绕过审核记录的业务 schema 校验,不额外添加或覆盖字段。它仍只调用同一条只读审核详情接口,沿用企业认证和 HTTP 错误处理。
|
||||
- 该模式解析并重新序列化 JSON,缩进等文本格式可能变化,不是 HTTP 响应的字节级副本。上游未返回的内容不会补查;无效 JSON、网络错误或 HTTP 失败仍按原协议报错。
|
||||
- 输出不会静默截断。共享的 stdout 大小保护超过 200,000 字节时返回退出码 12;`--full` 或 `--output-file` 可输出完整内容。`--full` 只控制大小保护,不会绕过字段校验,也不会撤销 `--summary/--fields`。
|
||||
- `--raw-json` 不能与 `--summary`、`--fields` 或 `--flow` 同用;这些参数会改写结构或切换接口,CLI 会以退出码 2 明确拒绝。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
|
||||
- 不把兜底入口作为默认查询,也不将大段原生 JSON 直接贴给用户;Agent 可按需读取文件中的特定字段。
|
||||
|
||||
## Understand The Case First
|
||||
|
||||
Before pulling the full document, use:
|
||||
|
||||
@@ -98,9 +98,9 @@ seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sou
|
||||
seal-use approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--corp <corpId>]
|
||||
seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]
|
||||
seal-use approval-runs hose-flow <recordId|SN> [--corp <corpId>]
|
||||
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
|
||||
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]
|
||||
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
|
||||
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
|
||||
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]
|
||||
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
|
||||
seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]
|
||||
seal-use approval-runs document-summary <recordId> [--corp <corpId>]
|
||||
@@ -137,7 +137,9 @@ seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp
|
||||
seal-use simulation clean <batchId> --yes [--corp <corpId>]
|
||||
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
|
||||
seal-use simulation approval-definitions [--corp <corpId>]
|
||||
seal-use simulation list [--limit 50] [--corp <corpId>]
|
||||
seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]
|
||||
seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
|
||||
seal-use simulation search "任务 fe1993e4" --since 2026-10-01 [--corp <corpId>]
|
||||
seal-use simulation get <batchId> [--corp <corpId>]
|
||||
seal-use simulation templates [--corp <corpId>]
|
||||
seal-use simulation integrations [--corp <corpId>]
|
||||
@@ -420,7 +422,8 @@ Approval runs, simulations, and Langfuse bridge:
|
||||
- `seal-use simulation approval-definitions --corp <corpId>` lists available Feishu approval definitions so an `approvalCode` can be selected before creating a batch.
|
||||
- `seal-use simulation wait <batchId> --corp <corpId>`
|
||||
- `seal-use simulation clean <batchId> --yes --corp <corpId>`
|
||||
- `seal-use simulation list --corp <corpId>`
|
||||
- `seal-use simulation list [--query <text>] [--since <time>] [--until <time>] [--all] --corp <corpId>` (过滤在本地完成,见下方“本地聚合”说明)
|
||||
- `seal-use simulation search "<关键词>" [--since 7d] [--all] --corp <corpId>` (**本地聚合检索,非云端原生**;先按 limit/offset 拉取批次再过滤,响应 `retrieval.serverSideSearch: false`)
|
||||
- `seal-use simulation get <batchId> --corp <corpId>`
|
||||
- `seal-use simulation batch-records <batchId> --corp <corpId>`
|
||||
- `seal-use simulation templates --corp <corpId>`
|
||||
@@ -521,8 +524,12 @@ seal-use simulation get <batchId> --corp <corpId>
|
||||
seal-use simulation batch-records <batchId> --corp <corpId>
|
||||
seal-use simulation templates --corp <corpId>
|
||||
seal-use simulation integrations --corp <corpId>
|
||||
# 本地检索批次(服务端无原生 search): 界面「任务 fe1993e4」可直接粘贴
|
||||
seal-use simulation search "任务 fe1993e4" --since 7d --all --corp <corpId>
|
||||
```
|
||||
|
||||
> **本地聚合,不是云端原生检索**:`/api/v1/simulation/batches` 只有 `limit`/`offset`,没有名称或关键词检索,批次对象也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。`list --query/--since/--until` 与 `search` 都是 CLI 先把批次拉到本地再过滤,返回体固定带 `retrieval: { mode: "local_scan", serverSideSearch: false, scanned }`;命中范围以 `scanned` 为准,不覆盖未扫描的批次(`truncated: true` 时用 `--all` 或调大 `--max-scan`)。不要把它当作服务端能力向用户描述。
|
||||
|
||||
## Failure Handling
|
||||
|
||||
- If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`.
|
||||
|
||||
@@ -67,8 +67,21 @@ Important:
|
||||
- `seal-use auth check` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
|
||||
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <duration>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default `2h`, e.g. `7d` or `7200`).
|
||||
- **Formatting Requirement**: When returning a Hose authorization link (`auth hose-link`) to the user, directly use the CLI JSON output:
|
||||
1. The operator identity: directly display the returned `staffId` (or `staffName` if present in output; do NOT make additional network calls or auth checks to search for personal names),
|
||||
1. The operator identity: **always report the person's name from `staffName`**. The CLI automatically looks up the exact Hose employee for `auth hose-link`, and the actual Seal session user for `auth link`. Do not use `staffId` as a person's name, infer a name from an ID, or assume both systems use the same person. If `identityStatus` is `unresolved` (`staffName: null`), explicitly report that the identity name could not be verified; do not silently omit it or guess,
|
||||
2. The exact expiration time in Beijing time (`expiresAt`),
|
||||
3. BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
|
||||
- **Seal AI Platform Direct Link**: If the user needs a delegation link for the Seal AI audit platform (`https://*.sealai.cc`) instead of Hose/易快报, use `seal-use auth link --corp <corpId> [--note <note>]`.
|
||||
|
||||
## Assistance link identity and reporting contract
|
||||
|
||||
This contract applies to both `auth hose-link` and `auth link`, including `auth link --from-link`.
|
||||
|
||||
- `staffName` is the verified person's name, or `null`; `identityStatus` is `resolved` / `unresolved`. Identity lookups do not switch the configured employee, modify enterprise configuration, reset a password, or request additional privileges.
|
||||
- Hose links return `roleNames` from that exact employee's role assignments. `null` means role names could not be verified; an empty array means the employee response explicitly contained no roles. Never infer “主管理员” merely because the CLI can generate a link.
|
||||
- Seal links return the actual session user's `isAdmin` and `permissions`. Report administrative access only when confirmed by those fields; `null` means the lookup failed. Seal permissions describe Seal access and must not be presented as Hose permissions.
|
||||
- If an identity lookup fails, the generated link remains usable, the command returns `staffName: null` / `identityStatus: "unresolved"`, and a diagnostic is written to `stderr`. Additional role-lookup failure preserves a verified name but returns `roleNames: null`. Never claim that an unresolved identity is an administrator.
|
||||
- A user-facing link report must include **enterprise name, person's name, verified role/permissions (or explicitly unknown), target system, and exact Beijing expiration time**. Include both a code block and a clickable link. If returning Hose and Seal links together, report identity and permissions separately for each.
|
||||
- Do not show raw tokens, full phone numbers, or internal IDs as explanatory prose. Do not fetch or list unrelated administrator candidates just to describe the identity of an existing link.
|
||||
|
||||
Example presentation: “企业:示例公司;合思登录身份:张三(主管理员);有效期至北京时间 …”;“Seal 登录身份:李四(依据 CLI 返回的管理员标记及权限说明);有效期至北京时间 …”。The names may differ; use each command's actual output.
|
||||
|
||||
@@ -170,6 +170,8 @@ flowchart TD
|
||||
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>" --wait
|
||||
```
|
||||
> **打断/重发防重复扣费**:批次创建默认幂等——复用窗口(默认 5 分钟,`--reuse-window` 可调)内对同一组 `--flow-ids`/`--package-ids` 再次执行 `simulation create` 会直接返回既有批次(`reused: true`),不会重复扣费。若 `--wait` 挂起期间命令被用户消息打断或后台 task 被 kill,**先执行 `seal-use simulation list --limit 3` 查最近批次**(同单批次可能已在服务端跑完),拿到批次 ID 后用 `status`/`batch-records` 取结果;确认无在途同单批次再决定重发。确需立刻重跑同组单号时显式加 `--force`。
|
||||
>
|
||||
> **按界面名称找历史批次**:模拟测试服务端没有名称/关键词检索,批次也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。用 `seal-use simulation search "任务 fe1993e4" --since 7d` 或 `seal-use simulation list --query <关键词> --since <时间>`;这是 **CLI 本地聚合检索**(先按 `limit`/`offset` 拉取再过滤,响应带 `retrieval.serverSideSearch: false`),命中范围以 `scanned` 为准,需要覆盖更早批次时加 `--all`(可用 `--max-scan` 控上限)。
|
||||
|
||||
- **方式 C:Webhook 原始报文重放 (Webhook Replay,仅限事件通知调测)**:
|
||||
直接将正式企业的特定单据/不良案例表单抽取并推送到测试企业 Webhook 通道:
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_DISABLE_BG_UPDATE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
const oldFetch = globalThis.fetch
|
||||
let dir: string
|
||||
let requests: Request[]
|
||||
let rawResponse: unknown
|
||||
let rawStatus: number
|
||||
|
||||
const fixtures = [
|
||||
{ id: "warning", result: { decision: "APPROVE", otherFindings: [
|
||||
{ title: "说明", description: "仅说明", level: "info" },
|
||||
{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }
|
||||
] } },
|
||||
{ id: "error", result: { decision: "REJECT", otherFindings: [{ title: "金额差异", description: "金额不一致", level: "error" }] } },
|
||||
{ id: "info", result: { otherFindings: [{ title: "说明", description: "无需处理", level: "info" }] } },
|
||||
{ id: "rule-only", result: { rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }], otherFindings: [] } },
|
||||
{ id: "missing", result: {} },
|
||||
{ id: "malformed", result: { otherFindings: "bad" } }
|
||||
].map((record, index) => ({
|
||||
...record, sourceDocumentSN: `SN-${index}`, status: "completed", createdAt: 1792639007830 - index,
|
||||
pipelineData: { humanResult: index === 0 ? "驳回" : "通过" },
|
||||
sourceExtendData: { _langfuseTraceId: `trace-${index}` }
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-extra-risk-cli-"))
|
||||
const enterprises = join(dir, "enterprises")
|
||||
mkdirSync(enterprises)
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
||||
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
|
||||
process.env.SEAL_DISABLE_BG_UPDATE = "1"
|
||||
writeFileSync(join(enterprises, "extra-risk-test.json"), JSON.stringify({
|
||||
id: "extra-risk-test", name: "Extra Risk Test", environment: "test",
|
||||
seal: { url: "https://extra-risk.example.test" },
|
||||
source: { type: "seal", token: "test-token", sealUrl: "https://extra-risk.example.test", staffId: "fixture" }
|
||||
}))
|
||||
requests = []
|
||||
rawResponse = { data: { id: 123, status: { future: true }, document: { fields: "changed-shape" }, addedByBackend: [1, { nested: null }] }, responseMetadata: { future: true } }
|
||||
rawStatus = 200
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
requests.push(request)
|
||||
const url = new URL(request.url)
|
||||
if (request.method !== "GET") return Response.json({ error: "unexpected mutation" }, { status: 405 })
|
||||
if (url.pathname === "/api/v1/approvals/raw-fixture") return Response.json(rawResponse, { status: rawStatus })
|
||||
if (url.pathname === "/api/v1/approvals") {
|
||||
const offset = Number(url.searchParams.get("offset") ?? 0)
|
||||
const limit = Number(url.searchParams.get("limit") ?? 50)
|
||||
return Response.json({ data: { records: fixtures.slice(offset, offset + limit), total: 1000 } })
|
||||
}
|
||||
const record = fixtures.find(item => url.pathname === `/api/v1/approvals/${item.id}`)
|
||||
return record ? Response.json({ data: record }) : Response.json({ error: "unexpected read" }, { status: 404 })
|
||||
}) as typeof fetch
|
||||
})
|
||||
|
||||
describe("approval run native JSON fallback", () => {
|
||||
test("preserves upstream envelopes and schema changes that normal get cannot parse", async () => {
|
||||
const normal = await cli("get", "raw-fixture", "--full")
|
||||
expect(normal.exitCode).toBe(13)
|
||||
const raw = await cli("get", "raw-fixture", "--raw-json")
|
||||
expect(raw.exitCode).toBe(0)
|
||||
expect(JSON.parse(raw.stdout)).toEqual(rawResponse)
|
||||
expect(requests.map(request => new URL(request.url).pathname)).toEqual([
|
||||
"/api/v1/approvals/raw-fixture", "/api/v1/approvals/raw-fixture"
|
||||
])
|
||||
expect(requests.every(request => request.method === "GET")).toBe(true)
|
||||
})
|
||||
|
||||
test("preserves bare responses and upstream fields that would otherwise be CLI-derived", async () => {
|
||||
rawResponse = { id: "raw-fixture", aliases: { fromServer: true }, humanResult: { original: true }, result: { future: { nested: [false, 0, ""] } } }
|
||||
const result = await cli("get", "raw-fixture", "--raw-json")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toEqual(rawResponse)
|
||||
})
|
||||
|
||||
test("returns complete large payloads with full/file and uses the shared size error otherwise", async () => {
|
||||
rawResponse = { data: { id: "raw-fixture", result: { text: "x".repeat(210_000) + "END-OF-UPSTREAM-JSON" } } }
|
||||
const guarded = await cli("get", "raw-fixture", "--raw-json")
|
||||
expect(guarded.exitCode).toBe(12)
|
||||
expect(guarded.stdout).toBe("")
|
||||
const full = await cli("get", "raw-fixture", "--raw-json", "--full")
|
||||
expect(full.exitCode).toBe(0)
|
||||
expect(JSON.parse(full.stdout)).toEqual(rawResponse)
|
||||
const path = join(dir, "raw.json")
|
||||
const file = await cli("get", "raw-fixture", "--raw-json", "--output-file", path)
|
||||
expect(file.exitCode).toBe(0)
|
||||
expect(JSON.parse(file.stdout)).toEqual({ outputFile: path, bytes: Buffer.byteLength(readFileSync(path)) })
|
||||
expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(rawResponse)
|
||||
})
|
||||
|
||||
test("rejects transformations and flow routing before sending any request", async () => {
|
||||
for (const flags of [["--summary"], ["--fields", "result"], ["--flow"]]) {
|
||||
const result = await cli("get", "raw-fixture", "--raw-json", ...flags)
|
||||
expect(result.exitCode).toBe(2)
|
||||
expect(result.stdout).toBe("")
|
||||
expect(result.stderr).toContain("--raw-json cannot be combined")
|
||||
}
|
||||
expect(requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("keeps HTTP authentication and upstream failures as errors", async () => {
|
||||
for (const [status, exitCode] of [[401, 11], [400, 1]] as const) {
|
||||
rawStatus = status
|
||||
rawResponse = { error: "Upstream rejected request" }
|
||||
const result = await cli("get", "raw-fixture", "--raw-json")
|
||||
expect(result.exitCode).toBe(exitCode)
|
||||
expect(result.stdout).toBe("")
|
||||
}
|
||||
})
|
||||
|
||||
test("accepts the camelCase alias and explicit false retains normal behavior", async () => {
|
||||
const raw = await cli("get", "raw-fixture", "--rawJson")
|
||||
expect(raw.exitCode).toBe(0)
|
||||
expect(JSON.parse(raw.stdout)).toEqual(rawResponse)
|
||||
const normal = await cli("get", "warning", "--raw-json=false")
|
||||
expect(normal.exitCode).toBe(0)
|
||||
expect(JSON.parse(normal.stdout)).toHaveProperty("aliases")
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of envKeys) {
|
||||
if (oldEnv[key] === undefined) delete process.env[key]
|
||||
else process.env[key] = oldEnv[key]
|
||||
}
|
||||
globalThis.fetch = oldFetch
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function cli(...argv: string[]) { return runCli(["approval-runs", ...argv, "--corp", "extra-risk-test"]) }
|
||||
|
||||
describe("approval run extra risk CLI", () => {
|
||||
test("filters the fetched page, preserves upstream totals and aligns bridge to matches", async () => {
|
||||
const response = await cli("list", "--has-extra-risk", "--limit", "100", "--includeBridge")
|
||||
expect(response.exitCode).toBe(0)
|
||||
const data = JSON.parse(response.stdout)
|
||||
expect(data).toMatchObject({ scanned: 6, matched: 2, unknown: 2, total: 1000 })
|
||||
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning", "error"])
|
||||
expect(data.records[0]).toMatchObject({
|
||||
otherFindingCount: 2, extraRiskCount: 1, hasExtraRisk: true, extraFindingsStatus: "known",
|
||||
extraRisks: [{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }]
|
||||
})
|
||||
expect(data.bridge).toHaveLength(2)
|
||||
expect(requests).toHaveLength(1)
|
||||
const url = new URL(requests[0]!.url)
|
||||
expect(url.searchParams.get("limit")).toBe("100")
|
||||
expect(url.searchParams.has("hasExtraRisk")).toBe(false)
|
||||
expect(requests.every(request => request.method === "GET")).toBe(true)
|
||||
})
|
||||
|
||||
test("limit and offset apply before filtering without fetching more pages", async () => {
|
||||
const response = await cli("search", "--has-extra-risk", "--limit", "2", "--offset", "2")
|
||||
expect(response.exitCode).toBe(0)
|
||||
expect(JSON.parse(response.stdout)).toMatchObject({ scanned: 2, matched: 0, unknown: 0, total: 1000, records: [] })
|
||||
expect(requests).toHaveLength(1)
|
||||
expect(new URL(requests[0]!.url).searchParams.get("offset")).toBe("2")
|
||||
})
|
||||
|
||||
test("combines with human-result filtering and forwards time and status conditions", async () => {
|
||||
const response = await cli("search", "--has-extra-risk", "--humanResult", "驳回", "--status", "completed", "--startDate", "2026-10-01", "--endDate", "2026-10-22")
|
||||
expect(response.exitCode).toBe(0)
|
||||
const data = JSON.parse(response.stdout)
|
||||
expect(data).toMatchObject({ scanned: 6, matched: 1, unknown: 0 })
|
||||
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning"])
|
||||
const params = new URL(requests[0]!.url).searchParams
|
||||
expect(params.get("status[0]")).toBe("completed")
|
||||
expect(params.get("manualApprovalStatus[0]")).toBe("TERMINATED")
|
||||
expect(params.get("startDate")).toBe(String(Date.parse("2026-10-01T00:00:00+08:00")))
|
||||
expect(params.get("endDate")).toBe(String(Date.parse("2026-10-22T23:59:59.999+08:00")))
|
||||
})
|
||||
|
||||
test("unfiltered lists preserve unknown and negative records with compact counts", async () => {
|
||||
const response = await cli("list")
|
||||
expect(response.exitCode).toBe(0)
|
||||
const data = JSON.parse(response.stdout)
|
||||
expect(data).toMatchObject({ scanned: 6, matched: 6, total: 1000 })
|
||||
expect(data).not.toHaveProperty("unknown")
|
||||
expect(data.records[2]).toMatchObject({ otherFindingCount: 1, extraRiskCount: 0, hasExtraRisk: false })
|
||||
expect(data.records[3]).toMatchObject({ otherFindingCount: 0, extraRiskCount: 0, hasExtraRisk: false })
|
||||
expect(data.records[4]).toMatchObject({ extraFindingsStatus: "unknown", otherFindingCount: null, extraRiskCount: null, hasExtraRisk: null })
|
||||
expect(data.records[0]).not.toHaveProperty("extraRisks")
|
||||
})
|
||||
|
||||
test("result and detail summaries expose extra risk counts without replacing existing counts", async () => {
|
||||
const result = await cli("result", "warning", "--summary")
|
||||
expect(result.exitCode).toBe(0)
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ decision: "APPROVE", extraRiskCount: 1, otherFindingCount: 2, hasExtraRisk: true })
|
||||
const detail = await cli("get", "warning", "--summary")
|
||||
expect(detail.exitCode).toBe(0)
|
||||
expect(JSON.parse(detail.stdout).aiResult).toMatchObject({ extraRiskCount: 1, hasExtraRisk: true })
|
||||
})
|
||||
|
||||
test("supports the camelCase alias and explicit false without filtering", async () => {
|
||||
const filtered = await cli("list", "--hasExtraRisk")
|
||||
expect(filtered.exitCode).toBe(0)
|
||||
expect(JSON.parse(filtered.stdout).matched).toBe(2)
|
||||
const unfiltered = await cli("list", "--has-extra-risk=false")
|
||||
expect(unfiltered.exitCode).toBe(0)
|
||||
expect(JSON.parse(unfiltered.stdout).matched).toBe(6)
|
||||
})
|
||||
})
|
||||
@@ -125,6 +125,7 @@ export async function handleApprovalRunsCommand(
|
||||
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
|
||||
sourceDocumentId: stringOption(args.options.sourceDocumentId),
|
||||
humanResult: stringOption(args.options.humanResult),
|
||||
hasExtraRisk: booleanOption(args.options["has-extra-risk"]) ?? booleanOption(args.options.hasExtraRisk),
|
||||
query: stringOption(args.options.query),
|
||||
includeBridge: booleanOption(args.options.includeBridge)
|
||||
},
|
||||
@@ -174,6 +175,10 @@ export async function handleApprovalRunsCommand(
|
||||
if (action === "get") {
|
||||
const recordId = args.command[2];
|
||||
if (!recordId) throw new Error("Missing approval run recordId");
|
||||
const rawJson = booleanOption(args.options["raw-json"]) ?? booleanOption(args.options.rawJson);
|
||||
if (rawJson && (booleanOption(args.options.flow) || booleanOption(args.options.summary) || stringOption(args.options.fields) !== undefined)) {
|
||||
throw usageError("--raw-json cannot be combined with --flow, --summary or --fields");
|
||||
}
|
||||
if (booleanOption(args.options.flow)) {
|
||||
await runCapability(
|
||||
"sealApprovalRunFlowGet",
|
||||
@@ -191,7 +196,8 @@ export async function handleApprovalRunsCommand(
|
||||
{
|
||||
recordId,
|
||||
fields: stringOption(args.options.fields),
|
||||
summary: booleanOption(args.options.summary)
|
||||
summary: booleanOption(args.options.summary),
|
||||
rawJson
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
|
||||
@@ -62,6 +62,12 @@ describe("auth links", () => {
|
||||
? input.toString()
|
||||
: input.url;
|
||||
const url = new URL(requestUrl);
|
||||
if (url.pathname === "/api/v1/auth/me") {
|
||||
return Response.json({ data: {
|
||||
user: { id: "session-user", tenantId: "tenant", name: "当前Seal人员", isAdmin: true, permissions: ["*"] },
|
||||
tenant: { id: "tenant", name: "原生 Seal 企业" }
|
||||
} });
|
||||
}
|
||||
if (url.pathname === "/api/v1/delegation/create") {
|
||||
return new Response(JSON.stringify({
|
||||
data: {
|
||||
@@ -86,10 +92,15 @@ describe("auth links", () => {
|
||||
corpId: "native-corp",
|
||||
corpName: "原生 Seal 企业",
|
||||
staffId: "native-staff",
|
||||
staffName: "当前Seal人员",
|
||||
identityStatus: "resolved",
|
||||
isAdmin: true,
|
||||
permissions: ["*"],
|
||||
link: "https://native.seal.test/delegation?token=delegation-token",
|
||||
token: "delegation-token"
|
||||
});
|
||||
expect(parsed.url).toBeUndefined();
|
||||
expect(result.stderr).not.toContain("未能核实");
|
||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||
});
|
||||
|
||||
@@ -163,6 +174,8 @@ describe("auth links", () => {
|
||||
expiresInHours: 1
|
||||
});
|
||||
expect(floorResult.stderr).toContain("已自动向下取整为 1 小时 (1h)");
|
||||
expect(JSON.parse(floorResult.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", isAdmin: null, permissions: null });
|
||||
expect(floorResult.stderr).toContain("未能核实实际登录人员姓名");
|
||||
|
||||
// Test reject exceeding 7 days (168 hours)
|
||||
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
|
||||
@@ -220,6 +233,12 @@ describe("auth links", () => {
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/openapi/v1/staffs/getStaffIds") {
|
||||
return Response.json({ items: [{ id: "HOSE-CORP:STAFF-1", name: "当前合思人员", active: true, roles: [{ roleDefId: "HOSE-CORP:admin" }] }] });
|
||||
}
|
||||
if (url.pathname === "/api/openapi/v1/roleDefGroups") {
|
||||
return Response.json({ items: [{ id: "system", name: "系统", roleDefs: [{ id: "HOSE-CORP:admin", name: "主管理员" }] }] });
|
||||
}
|
||||
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||
status: 404,
|
||||
headers: { "content-type": "application/json" }
|
||||
@@ -234,6 +253,9 @@ describe("auth links", () => {
|
||||
corpId: "HOSE-CORP",
|
||||
corpName: "合思测试企业",
|
||||
staffId: "HOSE-CORP:STAFF-1",
|
||||
staffName: "当前合思人员",
|
||||
identityStatus: "resolved",
|
||||
roleNames: ["主管理员"],
|
||||
link: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-xyz",
|
||||
token: "provisional-token-xyz"
|
||||
});
|
||||
@@ -315,6 +337,8 @@ describe("auth links", () => {
|
||||
expireDate: 7200
|
||||
});
|
||||
expect(result2.stderr).toContain("已按 2 小时 (7200s) 自动换算");
|
||||
expect(JSON.parse(result2.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", roleNames: null });
|
||||
expect(result2.stderr).toContain("未能核实实际登录人员姓名");
|
||||
});
|
||||
|
||||
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { CliError, validationError, usageError } from "../../core/errors.js";
|
||||
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||
import { createDelegation, getMe } from "../../domains/seal/api.js";
|
||||
import { resolveHoseLinkIdentity, resolveSealLinkIdentity, summarizeSealLinkIdentity } from "../../domains/seal/enterprise/assist-identity.js";
|
||||
import {
|
||||
booleanOption,
|
||||
parseDelegationExpireHours,
|
||||
@@ -59,6 +60,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
const delegation = await createDelegation(client, { note, expiresInHours });
|
||||
|
||||
printJson({
|
||||
...summarizeSealLinkIdentity(me.user),
|
||||
tenant: {
|
||||
id: me.tenant.id,
|
||||
name: me.tenant.name,
|
||||
@@ -115,14 +117,15 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
||||
}
|
||||
const delegationRecord = delegation as Record<string, unknown>;
|
||||
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
||||
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
|
||||
const identity = await resolveSealLinkIdentity(client);
|
||||
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
|
||||
printJson({
|
||||
id: delegationRecord.id,
|
||||
corpId: corp.source.corpId ?? corp.id,
|
||||
corpName: corp.name,
|
||||
staffId: corp.source.staffId,
|
||||
...(staffName ? { staffName } : {}),
|
||||
...identity,
|
||||
link: delegationRecord.link,
|
||||
expiresAt,
|
||||
token: delegationRecord.token
|
||||
@@ -138,13 +141,14 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
booleanOption(args.options.refresh) === true ||
|
||||
booleanOption(args.options.f) === true;
|
||||
const provisional = await getHoseProvisionalAuthLink(corp, expiresIn, { force });
|
||||
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
||||
const expiresAt = formatBeijingIso(Date.now() + expiresIn * 1000);
|
||||
const identity = await resolveHoseLinkIdentity(corp);
|
||||
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
|
||||
printJson({
|
||||
corpId: corp.source.corpId ?? corp.id,
|
||||
corpName: corp.name,
|
||||
staffId: corp.source.staffId,
|
||||
...(staffName ? { staffName } : {}),
|
||||
...identity,
|
||||
link: provisional.url,
|
||||
expiresAt,
|
||||
token: provisional.token
|
||||
|
||||
@@ -80,6 +80,8 @@ describe("corps link onboarding", () => {
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
staffName: "Support User",
|
||||
identityStatus: "resolved",
|
||||
tenant: {
|
||||
corpId: "acme-01",
|
||||
tenantSlug: "acme-01"
|
||||
|
||||
@@ -76,6 +76,85 @@ function trackMutationRequests() {
|
||||
return mutations;
|
||||
}
|
||||
|
||||
function mockSimulationBatches() {
|
||||
const requested: string[] = [];
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
requested.push(url);
|
||||
const body = url.includes("/api/v1/simulation/batches")
|
||||
? {
|
||||
data: [
|
||||
{
|
||||
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
|
||||
status: "completed",
|
||||
approvalCode: "hosecloud",
|
||||
sourceSystem: "hosecloud",
|
||||
createdAt: "2026-10-10T06:38:17.757Z"
|
||||
},
|
||||
{
|
||||
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
|
||||
status: "completed",
|
||||
approvalCode: "hosecloud",
|
||||
sourceSystem: "hosecloud",
|
||||
createdAt: "2026-10-09T02:56:58.000Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
: { data: {} };
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}) as typeof fetch;
|
||||
return requested;
|
||||
}
|
||||
|
||||
describe("simulation local search", () => {
|
||||
test("search matches the console「任务 fe1993e4」label locally", async () => {
|
||||
setupMockEnv();
|
||||
const requested = mockSimulationBatches();
|
||||
|
||||
const result = await runCli(["simulation", "search", "任务 fe1993e4"]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const payload = JSON.parse(result.stdout) as {
|
||||
count: number;
|
||||
scanned: number;
|
||||
retrieval: { mode: string; serverSideSearch: boolean };
|
||||
batches: Array<{ id: string }>;
|
||||
};
|
||||
expect(payload.count).toBe(1);
|
||||
expect(payload.retrieval).toMatchObject({ mode: "local_scan", serverSideSearch: false });
|
||||
expect(payload.batches[0]?.id).toBe("01a12488-a69d-74c4-88b1-118bfe1993e4");
|
||||
expect(result.stderr).toContain("本地聚合检索");
|
||||
expect(requested.every((url) => url.includes("/api/v1/simulation/batches"))).toBe(true);
|
||||
});
|
||||
|
||||
test("search respects a local time window", async () => {
|
||||
setupMockEnv();
|
||||
mockSimulationBatches();
|
||||
|
||||
const result = await runCli(["simulation", "search", "任务", "--since", "2026-10-09", "--until", "2026-10-09"]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const payload = JSON.parse(result.stdout) as { count: number; batches: Array<{ id: string }> };
|
||||
expect(payload.count).toBe(1);
|
||||
expect(payload.batches[0]?.id).toBe("01a123be-0742-743a-ac16-87f7c4e121c7");
|
||||
});
|
||||
|
||||
test("search without a keyword is a usage error", async () => {
|
||||
setupMockEnv();
|
||||
const requested = mockSimulationBatches();
|
||||
|
||||
const result = await runCli(["simulation", "search"]);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(requested).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("simulation command confirmation gates", () => {
|
||||
test("simulation clean refuses without --yes and never reaches the API", async () => {
|
||||
setupMockEnv();
|
||||
|
||||
@@ -205,13 +205,32 @@ export async function handleSimulationCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "list") {
|
||||
if (action === "list" || action === "search") {
|
||||
const query =
|
||||
stringOption(args.options.query) ??
|
||||
stringOption(args.options.q) ??
|
||||
(action === "search" ? maybeName : undefined);
|
||||
if (action === "search" && (!query || !query.trim())) {
|
||||
throw usageError(
|
||||
"Usage: seal-use simulation search <keyword> [--since 7d] [--until <time>] [--all]"
|
||||
);
|
||||
}
|
||||
|
||||
const limit = numberOption(args.options.limit);
|
||||
// search 默认扫到底(受 --max-scan 保护), 避免只搜到最近 50 个;显式 --limit 时按用户范围
|
||||
const all = booleanOption(args.options.all) ?? (action === "search" ? limit === undefined : false);
|
||||
|
||||
await runCapability(
|
||||
"sealSimulationBatchesList",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
limit: numberOption(args.options.limit)
|
||||
limit,
|
||||
all,
|
||||
maxScan: numberOption(args.options.maxScan) ?? numberOption(args.options["max-scan"]),
|
||||
query,
|
||||
since: stringOption(args.options.since) ?? stringOption(args.options["created-after"]),
|
||||
until: stringOption(args.options.until) ?? stringOption(args.options["created-before"])
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
|
||||
+25
-7
@@ -515,7 +515,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
name: "list",
|
||||
aliases: ["search"],
|
||||
summary: "Search approval records by keyword, dates, or decision status",
|
||||
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]"]
|
||||
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--has-extra-risk", description: "Filter the fetched page to records with warning/error in result.otherFindings; info is excluded. Includes extraRisks with titles, levels and descriptions." },
|
||||
{ flag: "--limit <n>", description: "Records to scan before local filtering (default 50, maximum 100); no automatic pagination to fill matches" },
|
||||
{ flag: "--offset <n>", description: "Offset in the upstream result set before local filtering" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "pick",
|
||||
@@ -525,7 +530,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
name: "get",
|
||||
summary: "Get detailed approval record payload",
|
||||
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]"]
|
||||
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary, --fields and --flow" },
|
||||
{ flag: "--full", description: "Bypass the shared 200,000-byte stdout size guard; this does not change payload structure" },
|
||||
{ flag: "--output-file <path>", description: "Write the complete JSON payload to a file, bypassing the stdout size guard" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "cited-rules",
|
||||
@@ -762,7 +772,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
area: "simulation",
|
||||
title: "Simulation testing engine",
|
||||
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules.",
|
||||
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules. Note: batch search is a local scan over the list API — the server exposes no name/keyword search.",
|
||||
commands: [
|
||||
{
|
||||
name: "batch-records",
|
||||
@@ -805,8 +815,16 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "list",
|
||||
summary: "List recent simulation batches",
|
||||
usage: ["seal-use simulation list [--limit 50] [--corp <corpId>]"]
|
||||
summary: "List recent simulation batches (filtering is LOCAL only: batches are pulled by limit/offset, the server has no query API)",
|
||||
usage: ["seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "search",
|
||||
summary: "Search simulation batches LOCALLY (not a server-side/native search): scans batches then filters by UI name fragment, document SN, package/template or time window",
|
||||
usage: [
|
||||
"seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]",
|
||||
"seal-use simulation search \"任务 fe1993e4\" --since 2026-10-01 [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "get",
|
||||
@@ -1032,7 +1050,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
|
||||
],
|
||||
description:
|
||||
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。主体作用于 Seal 审核后台。"
|
||||
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。返回实际会话人员 staffName、identityStatus、isAdmin 和 permissions;姓名查询失败时明确标记为未核实。主体作用于 Seal 审核后台。"
|
||||
},
|
||||
{
|
||||
name: "link list",
|
||||
@@ -1054,7 +1072,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
|
||||
],
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。自动查询绑定员工的 staffName、identityStatus 和 roleNames;未能核实的姓名或角色明确标记为未知。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
},
|
||||
{
|
||||
name: "hose-openapi-token",
|
||||
|
||||
+2
-2
@@ -29,10 +29,10 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
||||
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
||||
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
|
||||
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
|
||||
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
|
||||
|
||||
@@ -53,6 +53,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"specifications",
|
||||
"approval-definitions",
|
||||
"list",
|
||||
"search",
|
||||
"get",
|
||||
"templates",
|
||||
"integrations"
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
getInsightStats,
|
||||
getInsightRisksByTag,
|
||||
getInsightPerformance,
|
||||
getApprovalRunRawJson,
|
||||
analyzeInsightRecord,
|
||||
listExpenses,
|
||||
listInvoices,
|
||||
@@ -25,6 +26,21 @@ import {
|
||||
updateWebhookIntegration
|
||||
} from "./api.js";
|
||||
|
||||
describe("native approval JSON", () => {
|
||||
test("preserves the JSON response without schema validation or unwrapping and encodes the record ID", async () => {
|
||||
let path = "";
|
||||
const response = { data: null, futureEnvelope: { nested: [1, false, ""] } };
|
||||
const client = {
|
||||
get: (url: string) => {
|
||||
path = url;
|
||||
return { json: async () => response };
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
expect(await getApprovalRunRawJson(client, "record/with?reserved#chars")).toEqual(response);
|
||||
expect(path).toBe("api/v1/approvals/record%2Fwith%3Freserved%23chars");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Seal contact API", () => {
|
||||
test("sends the contact search term as query", async () => {
|
||||
let requestedUrl = "";
|
||||
|
||||
@@ -736,6 +736,11 @@ export async function getApprovalRun(client: KyInstance, runId: string): Promise
|
||||
return unwrap(await client.get(`api/v1/approvals/${runId}`), ApprovalRunSchema);
|
||||
}
|
||||
|
||||
/** Compatibility escape hatch: preserve the JSON response envelope without business-schema parsing. */
|
||||
export async function getApprovalRunRawJson(client: KyInstance, runId: string): Promise<unknown> {
|
||||
return client.get(`api/v1/approvals/${encodeURIComponent(runId)}`).json<unknown>();
|
||||
}
|
||||
|
||||
export async function listSimulationBatchRecords(
|
||||
client: KyInstance,
|
||||
batchId: string
|
||||
@@ -775,12 +780,12 @@ export async function createMaterialPackBatch(
|
||||
|
||||
export async function listSimulationBatches(
|
||||
client: KyInstance,
|
||||
opts: { limit?: number } = {}
|
||||
opts: { limit?: number; offset?: number } = {}
|
||||
): Promise<SimulationBatch[]> {
|
||||
const searchParams: Record<string, string> = { limit: String(opts.limit ?? 50) };
|
||||
if (opts.offset !== undefined && opts.offset > 0) searchParams.offset = String(opts.offset);
|
||||
const json = (await client
|
||||
.get("api/v1/simulation/batches", {
|
||||
searchParams: { limit: String(opts.limit ?? 50) }
|
||||
})
|
||||
.get("api/v1/simulation/batches", { searchParams })
|
||||
.json()) as { data?: unknown };
|
||||
const data = json.data ?? json;
|
||||
return z.array(SimulationBatchSchema).parse(data);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { summarizeExtraFindings } from "./extra-findings.js"
|
||||
|
||||
describe("extra findings", () => {
|
||||
test("counts warning/error separately from info and ignores rule-bound findings", () => {
|
||||
const summary = summarizeExtraFindings({
|
||||
id: "run-1",
|
||||
result: {
|
||||
decision: "APPROVE",
|
||||
rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }],
|
||||
otherFindings: [
|
||||
{ title: "说明", description: "仅作说明", level: "info" },
|
||||
{ title: "待核实", description: "凭证主体不同", level: "warning", location: { scope: "FORM", refId: "" } },
|
||||
{ title: "异常", description: "金额不符", level: "error" }
|
||||
]
|
||||
}
|
||||
}, true)
|
||||
expect(summary).toEqual({
|
||||
extraFindingsStatus: "known", otherFindingCount: 3, extraRiskCount: 2, hasExtraRisk: true,
|
||||
extraRisks: [
|
||||
{ title: "待核实", description: "凭证主体不同", level: "warning" },
|
||||
{ title: "异常", description: "金额不符", level: "error" }
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
test("empty arrays and info-only findings are known negatives regardless of decision", () => {
|
||||
for (const otherFindings of [[], [{ title: "说明", description: "无需处理", level: "info" }]]) {
|
||||
expect(summarizeExtraFindings({ id: "run", result: { decision: "REJECT", otherFindings } }, true)).toEqual({
|
||||
extraFindingsStatus: "known", otherFindingCount: otherFindings.length,
|
||||
extraRiskCount: 0, hasExtraRisk: false, extraRisks: []
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("missing, unsupported and partially malformed results remain unknown", () => {
|
||||
for (const result of [
|
||||
undefined, null, "{}", [], {}, { riskPoints: ["风险"] },
|
||||
{ otherFindings: null }, { otherFindings: {} }, { otherFindings: [null] },
|
||||
{ otherFindings: [{ title: "标题", description: "内容", level: "critical" }] },
|
||||
{ otherFindings: [{ level: "warning" }] },
|
||||
{ otherFindings: [{ title: "标题", description: "内容", level: "warning" }, "bad"] }
|
||||
]) {
|
||||
expect(summarizeExtraFindings({ id: "run", result }, true)).toEqual({
|
||||
extraFindingsStatus: "unknown", otherFindingCount: null,
|
||||
extraRiskCount: null, hasExtraRisk: null, extraRisks: null
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test("default summaries omit risk detail", () => {
|
||||
expect(summarizeExtraFindings({ id: "run", result: { otherFindings: [] } })).not.toHaveProperty("extraRisks")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
import { z } from "zod"
|
||||
import type { ApprovalRun } from "../types.js"
|
||||
|
||||
const extraFindingSchema = z.object({
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
level: z.enum(["info", "warning", "error"])
|
||||
})
|
||||
const extraFindingsSchema = z.array(extraFindingSchema)
|
||||
|
||||
export type ExtraRisk = z.infer<typeof extraFindingSchema>
|
||||
|
||||
export type ExtraFindingsSummary = {
|
||||
extraFindingsStatus: "known" | "unknown";
|
||||
otherFindingCount: number | null;
|
||||
extraRiskCount: number | null;
|
||||
hasExtraRisk: boolean | null;
|
||||
extraRisks?: ExtraRisk[] | null;
|
||||
}
|
||||
|
||||
/** Only otherFindings classifies rule-independent discoveries; missing data is not a negative. */
|
||||
export function summarizeExtraFindings(record: ApprovalRun, includeRisks = false): ExtraFindingsSummary {
|
||||
const result = record.result
|
||||
const raw = result && typeof result === "object" && !Array.isArray(result)
|
||||
? (result as Record<string, unknown>).otherFindings
|
||||
: undefined
|
||||
const parsed = extraFindingsSchema.safeParse(raw)
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
extraFindingsStatus: "unknown",
|
||||
otherFindingCount: null,
|
||||
extraRiskCount: null,
|
||||
hasExtraRisk: null,
|
||||
...(includeRisks ? { extraRisks: null } : {})
|
||||
}
|
||||
}
|
||||
|
||||
const risks = parsed.data.filter(finding => finding.level === "warning" || finding.level === "error")
|
||||
return {
|
||||
extraFindingsStatus: "known",
|
||||
otherFindingCount: parsed.data.length,
|
||||
extraRiskCount: risks.length,
|
||||
hasExtraRisk: risks.length > 0,
|
||||
...(includeRisks ? { extraRisks: risks } : {})
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { validationError } from "../../../core/errors.js";
|
||||
import { usageError, validationError } from "../../../core/errors.js";
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
@@ -6,6 +6,7 @@ import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
|
||||
import { summarizeExtraFindings } from "../approval-runs/extra-findings.js";
|
||||
import {
|
||||
alignApprovalRunsWithHoseFlow,
|
||||
createHoseOpenClient,
|
||||
@@ -64,6 +65,7 @@ export const approvalRunsCapabilities = [
|
||||
sourceDocumentSN: z.string().optional(),
|
||||
sourceDocumentId: z.string().optional(),
|
||||
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
|
||||
hasExtraRisk: z.boolean().optional().describe("读取当前页后筛选 otherFindings 含 warning/error 的记录;limit 是扫描条数,缺失或异常结果计入 unknown"),
|
||||
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配"),
|
||||
includeBridge: z.boolean().optional().describe("是否返回完整 bridge 数组;默认 false,避免长输出")
|
||||
}),
|
||||
@@ -82,6 +84,7 @@ export const approvalRunsCapabilities = [
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
humanResult?: string;
|
||||
hasExtraRisk?: boolean;
|
||||
query?: string;
|
||||
includeBridge?: boolean;
|
||||
}
|
||||
@@ -93,13 +96,21 @@ export const approvalRunsCapabilities = [
|
||||
endDate: normalizeTimestamp(params.endDate, true),
|
||||
search: query
|
||||
}));
|
||||
const records = await prepareApprovalRuns(client, data.records, {
|
||||
const prepared = await prepareApprovalRuns(client, data.records, {
|
||||
humanResult: params.humanResult
|
||||
});
|
||||
const analyzed = prepared.map(record => ({ record, findings: summarizeExtraFindings(record, params.hasExtraRisk === true) }));
|
||||
const selected = params.hasExtraRisk
|
||||
? analyzed.filter(({ findings }) => findings.hasExtraRisk === true)
|
||||
: analyzed;
|
||||
const records = selected.map(({ record }) => record);
|
||||
|
||||
return {
|
||||
...data,
|
||||
records: records.map(summarizeApprovalRun),
|
||||
scanned: data.records.length,
|
||||
matched: records.length,
|
||||
...(params.hasExtraRisk ? { unknown: analyzed.filter(({ findings }) => findings.extraFindingsStatus === "unknown").length } : {}),
|
||||
records: selected.map(({ record, findings }) => ({ ...summarizeApprovalRun(record), ...findings })),
|
||||
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
|
||||
};
|
||||
}
|
||||
@@ -205,12 +216,19 @@ export const approvalRunsCapabilities = [
|
||||
parameters: z.object({
|
||||
recordId: z.string().describe("Seal approval run record ID"),
|
||||
fields: z.union([z.string(), z.array(z.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary"),
|
||||
summary: z.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号")
|
||||
summary: z.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号"),
|
||||
rawJson: z.boolean().optional().describe("兼容兜底:返回上游原生 JSON 响应,保留包装和未知字段,不做业务 schema 校验或派生;不能与 summary/fields 同用")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { recordId: string; fields?: string | string[]; summary?: boolean }
|
||||
params: { recordId: string; fields?: string | string[]; summary?: boolean; rawJson?: boolean }
|
||||
) => {
|
||||
if (params.rawJson) {
|
||||
if (params.summary || params.fields !== undefined) {
|
||||
throw usageError("--raw-json cannot be combined with --summary or --fields");
|
||||
}
|
||||
return api.getApprovalRunRawJson(client, params.recordId);
|
||||
}
|
||||
const record = await api.getApprovalRun(client, params.recordId);
|
||||
if (params.summary) return summarizeApprovalRunDetail(record);
|
||||
const full = {
|
||||
|
||||
@@ -24,6 +24,7 @@ import type {
|
||||
WebhookIntegration
|
||||
} from "../types.js";
|
||||
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
|
||||
import { summarizeExtraFindings, type ExtraFindingsSummary } from "../approval-runs/extra-findings.js";
|
||||
import type { LocalRuleItem } from "../rules/local.js";
|
||||
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
|
||||
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
|
||||
@@ -55,7 +56,7 @@ export function getConfiguredSealBaseUrl(corp: CorpConfig): string {
|
||||
return corp.source.sealUrl;
|
||||
}
|
||||
|
||||
export type ApprovalRunSummary = {
|
||||
export type ApprovalRunSummary = ExtraFindingsSummary & {
|
||||
id: string;
|
||||
tenantId?: string;
|
||||
agentId?: string;
|
||||
@@ -500,6 +501,7 @@ export function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
|
||||
humanResultPath: humanResult?.path,
|
||||
aiDecision: ai.decision,
|
||||
aiSummary: ai.summary,
|
||||
...summarizeExtraFindings(record),
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt
|
||||
};
|
||||
@@ -596,6 +598,7 @@ export function summarizeApprovalRunDetail(record: ApprovalRun) {
|
||||
export function summarizeApprovalRunResult(record: ApprovalRun) {
|
||||
const result = asRecord(record.result);
|
||||
return {
|
||||
...summarizeExtraFindings(record),
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
sourceDocumentId: record.sourceDocumentId,
|
||||
|
||||
@@ -745,6 +745,77 @@ describe("simulation tool handlers", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("list tool scans pages and filters locally by UI name and time window", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const newer = {
|
||||
...hosecloudBatchFixture,
|
||||
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
|
||||
createdAt: "2026-10-10T06:38:17.757Z"
|
||||
};
|
||||
const older = {
|
||||
...hosecloudBatchFixture,
|
||||
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
|
||||
createdAt: "2026-10-09T02:56:58.000Z"
|
||||
};
|
||||
const calls: string[] = [];
|
||||
const client = {
|
||||
get: (_url: string, options: { searchParams: Record<string, string> }) => {
|
||||
const limit = Number(options.searchParams.limit);
|
||||
const offset = Number(options.searchParams.offset ?? 0);
|
||||
calls.push(`${limit}@${offset}`);
|
||||
const all = [newer, older];
|
||||
return { json: async () => ({ data: all.slice(offset, offset + limit) }) };
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
|
||||
const handler = tool!.handler as CapabilityHandler;
|
||||
const result = await handler(
|
||||
client,
|
||||
{ query: "任务 fe1993e4", since: "2026-10-10", until: "2026-10-10" },
|
||||
fakeContext()
|
||||
) as Record<string, unknown>;
|
||||
|
||||
expect(calls).toEqual(["50@0"]);
|
||||
expect(result).toMatchObject({
|
||||
retrieval: { mode: "local_scan", serverSideSearch: false, scanned: 2 },
|
||||
scanned: 2,
|
||||
truncated: false,
|
||||
count: 1,
|
||||
filters: {
|
||||
query: "任务 fe1993e4",
|
||||
since: "2026-10-10T00:00:00+08:00",
|
||||
until: "2026-10-10T23:59:59+08:00"
|
||||
}
|
||||
});
|
||||
expect((result.batches as Array<{ id: string }>)[0]?.id).toBe(newer.id);
|
||||
});
|
||||
|
||||
test("list tool paginates when all=true is requested", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
|
||||
const calls: string[] = [];
|
||||
const client = {
|
||||
get: (_url: string, options: { searchParams: Record<string, string> }) => {
|
||||
const limit = Number(options.searchParams.limit);
|
||||
const offset = Number(options.searchParams.offset ?? 0);
|
||||
calls.push(`${limit}@${offset}`);
|
||||
// Every page comes back full so the scanner keeps advancing until maxScan.
|
||||
const data = Array.from({ length: limit }, (_, index) => ({
|
||||
...hosecloudBatchFixture,
|
||||
id: `batch-${offset + index}`
|
||||
}));
|
||||
return { json: async () => ({ data }) };
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
|
||||
const handler = tool!.handler as CapabilityHandler;
|
||||
const result = await handler(client, { all: true, maxScan: 250 }, fakeContext()) as Record<string, unknown>;
|
||||
|
||||
expect(calls).toEqual(["100@0", "100@100", "50@200"]);
|
||||
expect(result).toMatchObject({ scanned: 250, scanLimit: 250, truncated: true, count: 250 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("simulation response schemas", () => {
|
||||
|
||||
@@ -2,12 +2,21 @@ import { validationError } from "../../../core/errors.js";
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import * as api from "../api.js";
|
||||
import {
|
||||
type SimulationBatch
|
||||
} from "../types.js";
|
||||
import * as helpers from "./helpers.js";
|
||||
import { parseDurationMs } from "../../../core/duration.js";
|
||||
import {
|
||||
collectSimulationBatches,
|
||||
DEFAULT_SIMULATION_MAX_SCAN,
|
||||
DEFAULT_SIMULATION_SCAN_LIMIT,
|
||||
filterSimulationBatches,
|
||||
MAX_SIMULATION_SCAN,
|
||||
parseSimulationTimeBound
|
||||
} from "../simulation/batch-search.js";
|
||||
|
||||
const {
|
||||
buildSimulationBatchParams,
|
||||
@@ -187,18 +196,80 @@ export const simulationCapabilities = [
|
||||
},
|
||||
{
|
||||
name: "sealSimulationBatchesList",
|
||||
description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",
|
||||
description: "【本地聚合检索, 非云端原生能力】列出或检索 Seal 模拟测试批次摘要。服务端 /simulation/batches 只支持 limit/offset, 没有名称/关键词检索, 批次对象也没有 name 字段(界面上的「任务 fe1993e4」是 UUID 末 8 位)。CLI 先把批次拉到本地再按关键词与时间窗过滤, 结果完整度取决于 scanned 范围: 默认扫描最近 50 个批次, all=true 分页扫到底。返回体带 retrieval.mode=local_scan / serverSideSearch=false 标记, 不要把它当成服务端搜索。",
|
||||
parameters: z.object({
|
||||
limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")
|
||||
limit: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional()
|
||||
.describe(`本地扫描的最近批次数量(不是返回条数上限), 默认 ${DEFAULT_SIMULATION_SCAN_LIMIT}`),
|
||||
all: z.boolean().optional()
|
||||
.describe(`分页扫描到底(仍受 maxScan 保护), 用于检索较早批次`),
|
||||
maxScan: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional()
|
||||
.describe(`all=true 时的扫描上限, 默认 ${DEFAULT_SIMULATION_MAX_SCAN}`),
|
||||
query: z.string().optional()
|
||||
.describe("本地关键词检索(CLI 端过滤, 非服务端): 空格/逗号分隔的多个关键词同时命中(AND); 匹配批次 ID(含无连字符形式)、界面「任务」后缀、单号、材料包/模板、条件摘要等"),
|
||||
since: z.string().optional()
|
||||
.describe("创建时间下界(含): ISO、YYYY-MM-DD、毫秒, 或相对时长如 7d"),
|
||||
until: z.string().optional()
|
||||
.describe("创建时间上界(含): 格式同 since")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { limit?: number }) => {
|
||||
const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 });
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
limit?: number;
|
||||
all?: boolean;
|
||||
maxScan?: number;
|
||||
query?: string;
|
||||
since?: string;
|
||||
until?: string;
|
||||
}
|
||||
) => {
|
||||
const sinceMs = parseSimulationTimeBound(params.since, { endOfDay: false });
|
||||
const untilMs = parseSimulationTimeBound(params.until, { endOfDay: true });
|
||||
const scanLimit = params.all
|
||||
? (params.maxScan ?? DEFAULT_SIMULATION_MAX_SCAN)
|
||||
: (params.limit ?? DEFAULT_SIMULATION_SCAN_LIMIT);
|
||||
|
||||
const { batches, capped } = await collectSimulationBatches(client, scanLimit);
|
||||
const matched = filterSimulationBatches(batches, {
|
||||
query: params.query,
|
||||
sinceMs,
|
||||
untilMs
|
||||
});
|
||||
const searching = Boolean(params.query?.trim()) || sinceMs !== undefined || untilMs !== undefined;
|
||||
|
||||
if (searching) {
|
||||
console.error(
|
||||
`ℹ️ [Simulation] 本地聚合检索(非云端原生): 服务端无关键词/名称检索, 已拉取最近 ${batches.length} 个批次并在本地过滤。`
|
||||
);
|
||||
}
|
||||
if (capped) {
|
||||
console.error(
|
||||
`🔎 [Simulation] 已扫描 ${batches.length} 个批次(达到扫描上限), 更早的批次未参与检索; 可用 --all 或调大 --max-scan。`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
count: batches.length,
|
||||
batches: batches.map(summarizeSimulationBatch),
|
||||
retrieval: {
|
||||
mode: "local_scan",
|
||||
serverSideSearch: false,
|
||||
scanned: batches.length,
|
||||
note: searching
|
||||
? "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次结果是 CLI 本地拉取后过滤, 命中范围以 scanned 为准, 不代表服务端全量。"
|
||||
: "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次仅列出最近 scanned 个批次, 不代表服务端全量。"
|
||||
},
|
||||
scanned: batches.length,
|
||||
scanLimit,
|
||||
truncated: capped,
|
||||
filters: {
|
||||
query: params.query ?? null,
|
||||
since: sinceMs === undefined ? null : formatBeijingIso(sinceMs),
|
||||
until: untilMs === undefined ? null : formatBeijingIso(untilMs)
|
||||
},
|
||||
count: matched.length,
|
||||
batches: matched.map(summarizeSimulationBatch),
|
||||
next: {
|
||||
getBatch: "seal-use simulation get <batchId>",
|
||||
getRecords: "seal-use simulation batch-records <batchId>"
|
||||
getRecords: "seal-use simulation batch-records <batchId>",
|
||||
search: "seal-use simulation search <关键词> [--since 7d] [--all] (本地检索)"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdtempSync, rmSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import type { KyInstance } from "ky"
|
||||
import { CorpConfigSchema } from "../../../core/config/types.js"
|
||||
import { resolveHoseLinkIdentity, resolveSealLinkIdentity } from "./assist-identity.js"
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalStore = process.env.SEAL_USE_TOKEN_STORE
|
||||
let dir: string
|
||||
let requests: Array<{ path: string; body?: unknown }>
|
||||
let staffItems: unknown[]
|
||||
let roleResponseFails: boolean
|
||||
let staffResponseFails: boolean
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "seal-assist-identity-"))
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
|
||||
requests = []
|
||||
staffItems = [{ id: "CORP:STAFF", name: "实际合思员工", roles: [{ roleDefId: "CORP:admin" }] }]
|
||||
roleResponseFails = false
|
||||
staffResponseFails = false
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const request = new Request(input, init)
|
||||
const path = new URL(request.url).pathname
|
||||
const body = request.method === "POST" ? await request.json() : undefined
|
||||
requests.push({ path, body })
|
||||
if (path === "/api/openapi/v1/auth/getAccessToken") return Response.json({ value: { accessToken: "test-openapi", expireTime: 7200 } })
|
||||
if (path === "/api/openapi/v1/staffs/getStaffIds") {
|
||||
return staffResponseFails ? Response.json({ error: "unavailable" }, { status: 403 }) : Response.json({ items: staffItems })
|
||||
}
|
||||
if (path === "/api/openapi/v1/roleDefGroups") {
|
||||
return roleResponseFails ? Response.json({ error: "unavailable" }, { status: 403 }) : Response.json({ items: [
|
||||
{ id: "roles", name: "系统角色", roleDefs: [{ id: "CORP:admin", name: "主管理员" }] }
|
||||
] })
|
||||
}
|
||||
throw new Error(`Unexpected identity request: ${path}`)
|
||||
}) as typeof fetch
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
if (originalStore === undefined) delete process.env.SEAL_USE_TOKEN_STORE
|
||||
else process.env.SEAL_USE_TOKEN_STORE = originalStore
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function hoseCorp(staffId = "STAFF") {
|
||||
return CorpConfigSchema.parse({
|
||||
id: "identity-test", name: "Fixture", seal: {},
|
||||
source: { type: "hose", corpId: "CORP", staffId, domain: "https://hose.example.test", appKey: "key", appSecurity: "secret" }
|
||||
})
|
||||
}
|
||||
|
||||
describe("assistance link identity", () => {
|
||||
test("resolves the exact Hose employee and verified role, without unrelated staff or link requests", async () => {
|
||||
const identity = await resolveHoseLinkIdentity(hoseCorp())
|
||||
expect(identity).toEqual({ staffName: "实际合思员工", identityStatus: "resolved", roleNames: ["主管理员"] })
|
||||
expect(requests.find(request => request.path.endsWith("getStaffIds"))?.body).toEqual({ type: "STAFFID", conditionIds: ["CORP:STAFF"] })
|
||||
expect(requests.map(request => request.path)).toEqual([
|
||||
"/api/openapi/v1/auth/getAccessToken", "/api/openapi/v1/staffs/getStaffIds", "/api/openapi/v1/roleDefGroups"
|
||||
])
|
||||
})
|
||||
|
||||
test("canonicalizes bare and qualified staff IDs but rejects other companies and ambiguous matches", async () => {
|
||||
staffItems = [{ id: "STAFF", name: "短ID员工", roles: [] }]
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp("CORP:STAFF"))).toMatchObject({ staffName: "短ID员工", roleNames: [] })
|
||||
for (const items of [
|
||||
[{ id: "OTHER:STAFF", name: "其他企业员工" }],
|
||||
[{ id: "CORP:OTHER", name: "其他管理员" }],
|
||||
[{ id: "STAFF", name: "甲" }, { id: "CORP:STAFF", name: "乙" }],
|
||||
[{ id: "STAFF", name: " " }]
|
||||
]) {
|
||||
staffItems = items
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: null, identityStatus: "unresolved", roleNames: null })
|
||||
}
|
||||
})
|
||||
|
||||
test("role lookup failure and unknown role IDs preserve a verified name without inventing permissions", async () => {
|
||||
roleResponseFails = true
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: "实际合思员工", identityStatus: "resolved", roleNames: null })
|
||||
roleResponseFails = false
|
||||
staffItems = [{ id: "STAFF", name: "员工", roles: [{ roleDefId: "not-visible" }] }]
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: "员工", identityStatus: "resolved", roleNames: null })
|
||||
})
|
||||
|
||||
test("missing staff visibility is explicitly unresolved", async () => {
|
||||
staffResponseFails = true
|
||||
expect(await resolveHoseLinkIdentity(hoseCorp())).toEqual({ staffName: null, identityStatus: "unresolved", roleNames: null })
|
||||
})
|
||||
|
||||
test("Seal identity comes from the actual session and includes its own permission scope", async () => {
|
||||
const client = { get: () => ({ json: async () => ({ data: {
|
||||
user: { id: "seal-user", tenantId: "tenant", name: "Seal实际人员", isAdmin: true, permissions: ["*"] },
|
||||
tenant: { id: "tenant", name: "企业" }
|
||||
} }) }) } as unknown as KyInstance
|
||||
expect(await resolveSealLinkIdentity(client)).toEqual({
|
||||
staffName: "Seal实际人员", identityStatus: "resolved", isAdmin: true, permissions: ["*"]
|
||||
})
|
||||
})
|
||||
|
||||
test("Seal identity failure returns unknown values, not a guessed employee or administrator", async () => {
|
||||
const client = { get: () => { throw new Error("private upstream details") } } as unknown as KyInstance
|
||||
expect(await resolveSealLinkIdentity(client)).toEqual({
|
||||
staffName: null, identityStatus: "unresolved", isAdmin: null, permissions: null
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { KyInstance } from "ky"
|
||||
import { ensureHoseOpenapiToken, fetchHoseRoleDefGroups, fetchHoseStaffDetails } from "../../../core/auth/hose.js"
|
||||
import type { CorpConfig } from "../../../core/config/types.js"
|
||||
import { getMe } from "../api.js"
|
||||
import type { MeData } from "../types.js"
|
||||
|
||||
type LinkIdentity = {
|
||||
staffName: string | null;
|
||||
identityStatus: "resolved" | "unresolved";
|
||||
}
|
||||
|
||||
/** Use the actual Seal session user, which may differ from the configured Hose employee. */
|
||||
export function summarizeSealLinkIdentity(user: MeData["user"]) {
|
||||
const staffName = user.name.trim() || null
|
||||
return {
|
||||
staffName,
|
||||
identityStatus: staffName ? "resolved" as const : "unresolved" as const,
|
||||
isAdmin: user.isAdmin,
|
||||
permissions: user.permissions
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveSealLinkIdentity(client: KyInstance) {
|
||||
try {
|
||||
return summarizeSealLinkIdentity((await getMe(client)).user)
|
||||
} catch {
|
||||
// Identity enrichment must not discard an otherwise valid assistance link.
|
||||
return { staffName: null, identityStatus: "unresolved" as const, isAdmin: null, permissions: null }
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveHoseLinkIdentity(corp: CorpConfig): Promise<LinkIdentity & { roleNames: string[] | null }> {
|
||||
const unresolved = { staffName: null, identityStatus: "unresolved" as const, roleNames: null }
|
||||
if (corp.source.type !== "hose") return unresolved
|
||||
const source = corp.source
|
||||
const canonicalId = (id: string) => id.includes(":") ? id : `${source.corpId}:${id}`
|
||||
const targetId = canonicalId(source.staffId)
|
||||
try {
|
||||
const token = await ensureHoseOpenapiToken(corp)
|
||||
const staffs = await fetchHoseStaffDetails(source.domain, token, [targetId])
|
||||
const matches = staffs.filter(staff => typeof staff.id === "string" && canonicalId(staff.id) === targetId)
|
||||
const staff = matches.length === 1 ? matches[0] : undefined
|
||||
if (!staff || typeof staff.name !== "string" || !staff.name.trim()) return unresolved
|
||||
|
||||
let roleNames: string[] | null = null
|
||||
if (Array.isArray(staff.roles)) {
|
||||
if (staff.roles.length === 0) roleNames = []
|
||||
else {
|
||||
try {
|
||||
const roles = (await fetchHoseRoleDefGroups(source.domain, token)).flatMap(group => group.roleDefs)
|
||||
const names = staff.roles.map(role => roles.find(item => item.id === role.roleDefId)?.name)
|
||||
if (names.every((name): name is string => typeof name === "string" && name.trim().length > 0)) {
|
||||
roleNames = [...new Set(names)]
|
||||
}
|
||||
} catch {
|
||||
// Missing role visibility does not make a verified employee name unknown.
|
||||
}
|
||||
}
|
||||
}
|
||||
return { staffName: staff.name.trim(), identityStatus: "resolved", roleNames }
|
||||
} catch {
|
||||
return unresolved
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { KyInstance } from "ky";
|
||||
import { CliError } from "../../../core/errors.js";
|
||||
import { SimulationBatch } from "../types.js";
|
||||
import {
|
||||
collectSimulationBatches,
|
||||
filterSimulationBatches,
|
||||
parseSimulationTimeBound,
|
||||
simulationQueryTokens
|
||||
} from "./batch-search.js";
|
||||
|
||||
function batch(id: string, createdAt: string, extra: Partial<SimulationBatch> = {}): SimulationBatch {
|
||||
return {
|
||||
id,
|
||||
status: "completed",
|
||||
approvalCode: "hosecloud",
|
||||
sourceSystem: "hosecloud",
|
||||
totalCount: 1,
|
||||
processedCount: 1,
|
||||
successCount: 1,
|
||||
failedCount: 0,
|
||||
createdCount: 1,
|
||||
createFailedCount: 0,
|
||||
createdAt,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
const fe1993e4 = batch("01a12488-a69d-74c4-88b1-118bfe1993e4", "2026-10-10T06:38:17.757Z", {
|
||||
params: {
|
||||
approvalCode: "hosecloud",
|
||||
flowIds: ["S26002992"],
|
||||
packageLabel: "会议材料包.zip"
|
||||
},
|
||||
requestSummary: {
|
||||
mode: "指定单号",
|
||||
conditions: [{ label: "驳回节点", value: "出纳支付" }]
|
||||
}
|
||||
});
|
||||
const older = batch("01a123be-0742-743a-ac16-87f7c4e121c7", "2026-10-09T02:56:58.000Z", {
|
||||
params: { approvalCode: "hosecloud", flowIds: ["B26017701"] }
|
||||
});
|
||||
|
||||
describe("simulationQueryTokens", () => {
|
||||
test("strips the UI 任务 prefix and punctuation", () => {
|
||||
expect(simulationQueryTokens("任务 fe1993e4")).toEqual(["fe1993e4"]);
|
||||
expect(simulationQueryTokens("任务:fe1993e4")).toEqual(["fe1993e4"]);
|
||||
expect(simulationQueryTokens("任务fe1993e4")).toEqual(["fe1993e4"]);
|
||||
});
|
||||
|
||||
test("drops standalone noise words and splits on commas", () => {
|
||||
expect(simulationQueryTokens("任务, fe1993e4, 出纳")).toEqual(["fe1993e4", "出纳"]);
|
||||
expect(simulationQueryTokens("task")).toEqual([]);
|
||||
expect(simulationQueryTokens(undefined)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterSimulationBatches", () => {
|
||||
test("matches the last 8 hex chars shown in the console UI", () => {
|
||||
expect(filterSimulationBatches([fe1993e4, older], { query: "任务 fe1993e4" })).toEqual([fe1993e4]);
|
||||
});
|
||||
|
||||
test("matches hyphen-less UUID fragments", () => {
|
||||
expect(filterSimulationBatches([fe1993e4, older], { query: "01a12488a69d" })).toEqual([fe1993e4]);
|
||||
});
|
||||
|
||||
test("matches document SN, package label and request summary values", () => {
|
||||
expect(filterSimulationBatches([fe1993e4, older], { query: "S26002992" })).toEqual([fe1993e4]);
|
||||
expect(filterSimulationBatches([fe1993e4, older], { query: "会议材料包" })).toEqual([fe1993e4]);
|
||||
expect(filterSimulationBatches([fe1993e4, older], { query: "出纳支付" })).toEqual([fe1993e4]);
|
||||
});
|
||||
|
||||
test("requires every keyword to match (AND semantics)", () => {
|
||||
expect(filterSimulationBatches([fe1993e4, older], { query: "任务 fe1993e4 出纳" })).toEqual([fe1993e4]);
|
||||
expect(filterSimulationBatches([fe1993e4, older], { query: "fe1993e4 B26017701" })).toEqual([]);
|
||||
});
|
||||
|
||||
test("filters by createdAt window, inclusive", () => {
|
||||
const since = Date.parse("2026-10-10T00:00:00+08:00");
|
||||
const until = Date.parse("2026-10-10T23:59:59.999+08:00");
|
||||
expect(filterSimulationBatches([fe1993e4, older], { sinceMs: since, untilMs: until })).toEqual([fe1993e4]);
|
||||
});
|
||||
|
||||
test("returns everything without filters", () => {
|
||||
expect(filterSimulationBatches([fe1993e4, older])).toEqual([fe1993e4, older]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSimulationTimeBound", () => {
|
||||
test("reads Beijing-local dates, epoch millis and ISO timestamps", () => {
|
||||
expect(parseSimulationTimeBound("2026-10-10")).toBe(Date.parse("2026-10-10T00:00:00+08:00"));
|
||||
expect(parseSimulationTimeBound("2026-10-10", { endOfDay: true })).toBe(
|
||||
Date.parse("2026-10-10T23:59:59.999+08:00")
|
||||
);
|
||||
expect(parseSimulationTimeBound("1759000000000")).toBe(1759000000000);
|
||||
expect(parseSimulationTimeBound("2026-10-10T06:38:17.757Z")).toBe(Date.parse("2026-10-10T06:38:17.757Z"));
|
||||
});
|
||||
|
||||
test("interprets relative durations as now minus the offset", () => {
|
||||
const now = Date.parse("2026-10-23T16:00:00+08:00");
|
||||
expect(parseSimulationTimeBound("7d", { nowMs: now })).toBe(now - 7 * 86400_000);
|
||||
expect(parseSimulationTimeBound("90m", { nowMs: now })).toBe(now - 90 * 60_000);
|
||||
});
|
||||
|
||||
test("rejects unparseable bounds with the validation exit code", () => {
|
||||
let error: unknown;
|
||||
try {
|
||||
parseSimulationTimeBound("上周三");
|
||||
} catch (caught) {
|
||||
error = caught;
|
||||
}
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectSimulationBatches", () => {
|
||||
function pagedClient(total: number) {
|
||||
const calls: Array<{ limit: number; offset: number }> = [];
|
||||
const all = Array.from({ length: total }, (_, index) =>
|
||||
batch(`batch-${index}`, new Date(Date.UTC(2026, 9, 10, 0, index)).toISOString())
|
||||
);
|
||||
const client = {
|
||||
get: (_url: string, options: { searchParams: Record<string, string> }) => {
|
||||
const limit = Number(options.searchParams.limit);
|
||||
const offset = Number(options.searchParams.offset ?? 0);
|
||||
calls.push({ limit, offset });
|
||||
return { json: async () => ({ data: all.slice(offset, offset + limit) }) };
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
return { client, calls };
|
||||
}
|
||||
|
||||
test("paginates with offset until the scan limit is reached", async () => {
|
||||
const { client, calls } = pagedClient(250);
|
||||
const result = await collectSimulationBatches(client, 250);
|
||||
|
||||
expect(result.batches).toHaveLength(250);
|
||||
expect(result.capped).toBe(true);
|
||||
expect(calls.map((call) => [call.limit, call.offset])).toEqual([
|
||||
[100, 0],
|
||||
[100, 100],
|
||||
[50, 200]
|
||||
]);
|
||||
});
|
||||
|
||||
test("stops when the server returns a short page", async () => {
|
||||
const { client, calls } = pagedClient(30);
|
||||
const result = await collectSimulationBatches(client, 500);
|
||||
|
||||
expect(result.batches).toHaveLength(30);
|
||||
expect(result.capped).toBe(false);
|
||||
expect(calls).toEqual([{ limit: 100, offset: 0 }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { durationSeconds, tokenizeDuration } from "../../../core/duration.js";
|
||||
import { validationError } from "../../../core/errors.js";
|
||||
import * as api from "../api.js";
|
||||
import type { SimulationBatch } from "../types.js";
|
||||
|
||||
/**
|
||||
* 原生模拟测试没有服务端检索: `/api/v1/simulation/batches` 只接受 limit/offset,
|
||||
* 批次对象也没有 name 字段(界面上的「任务 fe1993e4」是前端取 UUID 末 8 位拼的)。
|
||||
* 因此检索放在本地: 先按 limit/offset 把批次扫进内存, 再按关键词与时间窗过滤。
|
||||
*/
|
||||
|
||||
export const SIMULATION_SCAN_PAGE_SIZE = 100;
|
||||
export const DEFAULT_SIMULATION_SCAN_LIMIT = 50;
|
||||
export const DEFAULT_SIMULATION_MAX_SCAN = 500;
|
||||
export const MAX_SIMULATION_SCAN = 2000;
|
||||
|
||||
export type SimulationBatchFilter = {
|
||||
query?: string;
|
||||
sinceMs?: number;
|
||||
untilMs?: number;
|
||||
};
|
||||
|
||||
const STANDALONE_NOISE_TOKENS = new Set([
|
||||
"任务",
|
||||
"批次",
|
||||
"模拟测试",
|
||||
"测试",
|
||||
"task",
|
||||
"batch",
|
||||
"test",
|
||||
"simulation"
|
||||
]);
|
||||
|
||||
// 界面名称形如「任务 fe1993e4」「任务:fe1993e4」, 直接粘贴时把中文前缀剥掉
|
||||
const GLUED_NOISE_PREFIXES = ["模拟测试", "任务", "批次"];
|
||||
|
||||
function stripGluedNoise(token: string): string {
|
||||
let value = token;
|
||||
for (const prefix of GLUED_NOISE_PREFIXES) {
|
||||
if (value.length > prefix.length && value.startsWith(prefix)) {
|
||||
value = value.slice(prefix.length);
|
||||
}
|
||||
}
|
||||
return value.replace(/^[\s::#\-_]+/, "");
|
||||
}
|
||||
|
||||
export function simulationQueryTokens(query?: string): string[] {
|
||||
if (!query) return [];
|
||||
const raw = query
|
||||
.split(/[\s,,;;、]+/)
|
||||
.map((token) => token.trim())
|
||||
.filter(Boolean)
|
||||
.map((token) => token.toLowerCase())
|
||||
.filter((token) => !STANDALONE_NOISE_TOKENS.has(token));
|
||||
|
||||
return raw
|
||||
.map((token) => stripGluedNoise(token))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function batchHaystack(batch: SimulationBatch): string {
|
||||
const params = batch.params;
|
||||
const values: Array<string | number | null | undefined> = [
|
||||
batch.id,
|
||||
batch.id.replace(/-/g, ""),
|
||||
batch.approvalCode,
|
||||
batch.nodeId,
|
||||
batch.sourceSystem,
|
||||
batch.status,
|
||||
batch.requestSummary?.mode,
|
||||
batch.resultSummary?.message,
|
||||
params?.packageLabel,
|
||||
params?.templateId,
|
||||
params?.signKey,
|
||||
params?.rejectNodeName,
|
||||
params?.dataCollectionMode,
|
||||
...(params?.flowIds ?? []),
|
||||
...(params?.packageIds ?? []),
|
||||
...(batch.requestSummary?.conditions ?? []).flatMap((condition) => [
|
||||
condition.label,
|
||||
condition.value
|
||||
])
|
||||
];
|
||||
|
||||
return values
|
||||
.filter((value): value is string | number => value !== undefined && value !== null && value !== "")
|
||||
.map((value) => String(value).toLowerCase())
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function batchCreatedAtMs(batch: SimulationBatch): number | null {
|
||||
if (batch.createdAt === undefined) return null;
|
||||
const ms = typeof batch.createdAt === "number" ? batch.createdAt : Date.parse(batch.createdAt);
|
||||
return Number.isFinite(ms) ? ms : null;
|
||||
}
|
||||
|
||||
export function filterSimulationBatches(
|
||||
batches: SimulationBatch[],
|
||||
filter: SimulationBatchFilter = {}
|
||||
): SimulationBatch[] {
|
||||
const tokens = simulationQueryTokens(filter.query);
|
||||
|
||||
return batches.filter((batch) => {
|
||||
if (filter.sinceMs !== undefined || filter.untilMs !== undefined) {
|
||||
const createdAtMs = batchCreatedAtMs(batch);
|
||||
if (createdAtMs === null) return false;
|
||||
if (filter.sinceMs !== undefined && createdAtMs < filter.sinceMs) return false;
|
||||
if (filter.untilMs !== undefined && createdAtMs > filter.untilMs) return false;
|
||||
}
|
||||
|
||||
if (tokens.length === 0) return true;
|
||||
const haystack = batchHaystack(batch);
|
||||
return tokens.every((token) => haystack.includes(token));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析时间下界/上界: 支持 ISO、`YYYY-MM-DD`、10/13 位毫秒、以及相对时长(`7d` / `24h` / `90m`)。
|
||||
* 相对时长按「现在往前推」解释, 便于 `--since 7d` 这类用法。
|
||||
*/
|
||||
export function parseSimulationTimeBound(
|
||||
raw: string | undefined,
|
||||
options: { endOfDay?: boolean; nowMs?: number } = {}
|
||||
): number | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
const value = raw.trim();
|
||||
if (!value) return undefined;
|
||||
|
||||
if (/^\d{10,13}$/.test(value)) {
|
||||
return value.length === 10 ? Number(value) * 1000 : Number(value);
|
||||
}
|
||||
|
||||
const relative = tokenizeDuration(value);
|
||||
if (relative?.unit) {
|
||||
const offsetMs = Math.round(durationSeconds(relative, "d") * 1000);
|
||||
return (options.nowMs ?? Date.now()) - offsetMs;
|
||||
}
|
||||
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||
const timeSuffix = options.endOfDay ? "T23:59:59.999+08:00" : "T00:00:00.000+08:00";
|
||||
const parsed = new Date(`${value}${timeSuffix}`).getTime();
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
|
||||
const parsed = new Date(value).getTime();
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
|
||||
throw validationError(
|
||||
`无法解析时间 "${raw}"。支持 ISO 时间、YYYY-MM-DD、10/13 位毫秒, 或相对时长(如 7d / 24h / 90m)。`
|
||||
);
|
||||
}
|
||||
|
||||
export async function collectSimulationBatches(
|
||||
client: KyInstance,
|
||||
scanLimit: number
|
||||
): Promise<{ batches: SimulationBatch[]; capped: boolean }> {
|
||||
const target = Math.max(1, Math.min(scanLimit, MAX_SIMULATION_SCAN));
|
||||
const batches: SimulationBatch[] = [];
|
||||
let offset = 0;
|
||||
|
||||
while (batches.length < target) {
|
||||
const pageSize = Math.min(SIMULATION_SCAN_PAGE_SIZE, target - batches.length);
|
||||
const page = await api.listSimulationBatches(client, { limit: pageSize, offset });
|
||||
batches.push(...page);
|
||||
// 服务端已无更多批次
|
||||
if (page.length < pageSize) return { batches, capped: false };
|
||||
offset += page.length;
|
||||
}
|
||||
|
||||
// 达到扫描上限: 更早的批次未进入检索
|
||||
return { batches, capped: true };
|
||||
}
|
||||
@@ -463,7 +463,8 @@ export const SimulationBatchParamsSchema = z.object({
|
||||
nodeId: z.string().optional(),
|
||||
// 合思指定单号模式
|
||||
flowIds: z.array(z.string()).max(100).optional(),
|
||||
limit: z.number().int().positive().max(100).optional(),
|
||||
// 历史批次存在 limit=0(取数模式不按条数限制)与超过 100 的回显值,读路径不能因此整页失败
|
||||
limit: z.number().int().nonnegative().optional(),
|
||||
dataCollectionMode: z.string().optional(),
|
||||
signKey: z.string().optional(),
|
||||
rejectNodeName: z.string().nullable().optional(),
|
||||
|
||||
Reference in new issue
Block a user