Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11780f7fe4 | ||
|
|
4583dcc090 | ||
|
|
d069e7232e | ||
|
|
45011c8333 | ||
|
|
e2410e6923 | ||
|
|
fb8a48ea3c | ||
|
|
0a71674c64 | ||
|
|
3918e3de43 | ||
|
|
d4fb3828b7 | ||
|
|
2724ea5490 | ||
|
|
e542c0a5f2 | ||
|
|
8329b294e5 | ||
|
|
e72803ba3c | ||
|
|
e4b1eea5a9 | ||
|
|
482ebf57b5 | ||
|
|
ada91c6c76 | ||
|
|
686b397846 | ||
|
|
e5644db726 | ||
|
|
d3c44e02d7 | ||
|
|
2ee15bb0d6 |
No files matched your search
@@ -0,0 +1,32 @@
|
||||
---
|
||||
description: "本设备创建分支的命名规范(设备前缀)与 git hook 机械强制"
|
||||
trigger: "always"
|
||||
---
|
||||
|
||||
# 分支命名规范 (设备前缀 + 机械强制)
|
||||
|
||||
为了让"哪台设备/哪个 Agent 开的分支"一眼可辨,本仓库的分支命名按创建设备加前缀。规则文档随仓库走,前缀的值留在各设备本地。
|
||||
|
||||
## 1. 命名规则
|
||||
|
||||
- **格式**:`<设备键>/<小写连字符主题>`。本机(这台 Mac)的设备键是 `mac15`,例如:`mac15/improve-corp-search`。
|
||||
- **设备键声明**:每个克隆只声明一次,写入本地 git 配置(存于 `.git/config`,不提交、随设备走):
|
||||
```bash
|
||||
git config seal.branchPrefix mac15 # 这台 Mac;其他设备换自己的键,不设置则本规则休眠
|
||||
```
|
||||
- **Agent 行为要求**:任何 Agent(Codex/ZCode/Claude 等)创建分支前,先执行 `git config seal.branchPrefix`;有值则分支名必须以 `<值>/` 开头,没有值时用普通主题名即可。
|
||||
|
||||
## 2. 保留名(不受设备前缀约束)
|
||||
|
||||
- `main`:主分支。
|
||||
- `codex/release-vX.Y.Z`:发版自动化专用(`bun run release` 创建),沿用既有约定。
|
||||
|
||||
## 3. 机械强制(不依赖 Agent 自觉)
|
||||
|
||||
- 钩子:`.githooks/pre-commit` 与 `.githooks/pre-push` 通过 `.githooks/branch-guard.sh` 校验分支名,违规即拒绝并给出改名命令。`package.json` 的 `prepare` 脚本在 `bun install` 时自动设置 `core.hooksPath=.githooks`,新克隆无需手动接线。
|
||||
- **存量分支豁免**:已存在于 origin 的旧分支(如云端 Agent 创建的 `codex/*`)不拦,避免影响在途 PR。
|
||||
- **逃生门**:`git commit --no-verify` / `git push --no-verify` 可一次性绕过,仅用于特殊情况,不要养成习惯。
|
||||
|
||||
## 4. 相关规则
|
||||
|
||||
- 分支/工作树清理见 `.agents/rules/workspace-hygiene.md`;PR 工作流见 `.agents/rules/issue-pr-workflow.md`。
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
# Shared branch-naming guard: .agents/rules/branch-naming.md
|
||||
# Devices opt in per clone: git config seal.branchPrefix <device-key> (e.g. mac15)
|
||||
# Sourced by pre-commit and pre-push.
|
||||
|
||||
# guard_branch_name <branch> — returns 1 with guidance when the name breaks the rule.
|
||||
guard_branch_name() {
|
||||
local branch="$1"
|
||||
[ -n "$branch" ] || return 0
|
||||
|
||||
# Reserved names: mainline branches and the release automation.
|
||||
case "$branch" in
|
||||
main|master|develop) return 0 ;;
|
||||
codex/release-*) return 0 ;;
|
||||
esac
|
||||
|
||||
# Enforcement is opt-in per device; without a configured prefix this guard is dormant.
|
||||
local prefix
|
||||
prefix="$(git config seal.branchPrefix 2>/dev/null || true)"
|
||||
[ -n "$prefix" ] || return 0
|
||||
|
||||
case "$branch" in
|
||||
"$prefix"/*) return 0 ;;
|
||||
esac
|
||||
|
||||
# Branches that already exist on origin (created elsewhere, e.g. cloud agents) stay usable.
|
||||
if git rev-parse -q --verify "refs/remotes/origin/$branch" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "" >&2
|
||||
echo "🛑 [branch-guard] Branch '$branch' violates the device branch-prefix rule (.agents/rules/branch-naming.md)." >&2
|
||||
echo " Branches created on this device must start with '${prefix}/'." >&2
|
||||
echo " 👉 Rename and retry: git branch -m '${prefix}/${branch##*/}'" >&2
|
||||
echo " (One-off bypass: git commit --no-verify / git push --no-verify)" >&2
|
||||
echo "" >&2
|
||||
return 1
|
||||
}
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
# Git pre-commit hook: enforce the device branch-prefix rule
|
||||
# (.agents/rules/branch-naming.md) via .githooks/branch-guard.sh
|
||||
source "$(dirname "$0")/branch-guard.sh"
|
||||
|
||||
guard_branch_name "$(git branch --show-current)"
|
||||
@@ -1,12 +1,24 @@
|
||||
#!/bin/bash
|
||||
# Git pre-push hook: Prevent accidental direct push to origin/main or GitHub/main
|
||||
# Enforces the PR workflow required by AGENTS.md & .agents/rules/issue-pr-workflow.md
|
||||
# Also enforces the device branch-prefix rule via .githooks/branch-guard.sh
|
||||
|
||||
source "$(dirname "$0")/branch-guard.sh"
|
||||
|
||||
remote="$1"
|
||||
url="$2"
|
||||
zero="0000000000000000000000000000000000000000"
|
||||
|
||||
while read local_ref local_oid remote_ref remote_oid; do
|
||||
# Device branch-prefix rule (.agents/rules/branch-naming.md); deletions are exempt
|
||||
case "$local_ref" in
|
||||
refs/heads/*)
|
||||
if [ "$local_oid" != "$zero" ]; then
|
||||
guard_branch_name "${local_ref#refs/heads/}" || exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
# If pushing the main branch (or pushing to remote main)
|
||||
if [ "$remote_ref" = "refs/heads/main" ] || [ "$local_ref" = "refs/heads/main" ]; then
|
||||
# When pushing to origin or GitHub (main repository)
|
||||
|
||||
@@ -72,6 +72,14 @@ jobs:
|
||||
run: bun test
|
||||
|
||||
- name: Compile multi-target binaries
|
||||
# Langfuse read-only credentials are injected at compile time from
|
||||
# repository secrets and inlined into the binaries; they never appear in
|
||||
# the repository or in the workflow logs.
|
||||
env:
|
||||
SEAL_BUILD_LANGFUSE_BASE_URL: ${{ secrets.LANGFUSE_BASE_URL }}
|
||||
SEAL_BUILD_LANGFUSE_PUBLIC_KEY: ${{ secrets.LANGFUSE_PUBLIC_KEY }}
|
||||
SEAL_BUILD_LANGFUSE_SECRET_KEY: ${{ secrets.LANGFUSE_SECRET_KEY }}
|
||||
SEAL_BUILD_LANGFUSE_PROJECT_ID: ${{ secrets.LANGFUSE_PROJECT_ID }}
|
||||
run: |
|
||||
mkdir -p dist/bin
|
||||
node scripts/build-binary.mjs --all
|
||||
|
||||
@@ -12,5 +12,11 @@ dist/bin/
|
||||
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
||||
.local/
|
||||
|
||||
# Developer-only build-time credentials for compile-time injection — never committed
|
||||
.env.langfuse
|
||||
|
||||
# ZCode session plan artifacts (workspace-local, never committed)
|
||||
.zcode/plans/
|
||||
|
||||
# One-off export harnesses dropped in scripts/ while exporting
|
||||
scripts/export-*.ts
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.0",
|
||||
"version": "0.11.3",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Project Structure & Module Organization
|
||||
|
||||
This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP server (`seal-use mcp`). Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and logic is under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` holds the shared handlers dispatched by the CLI (`runCapability`) and allow-listed by the MCP gateways. Capability IDs are camelCase internal registry identifiers (for example `sealApprovalContextGet`) — the MCP surface only ever exposes the `seal_use` / `seal_use_write` gateway pair, never these names (see README "One registry, two doors").
|
||||
This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP server (`seal-use mcp`). Entry points are `src/cli.ts`, `src/server.ts`, and `src/probe.ts`. Shared config, auth, token, and HTTP code is under `src/core/`. Seal-specific API and logic is under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` holds the shared handlers dispatched by the CLI (`runCapability`) and allow-listed by the MCP gateways. Capability IDs are camelCase internal registry identifiers (for example `sealApprovalContextGet`) — the MCP surface only ever exposes the `seal_use` / `seal_use_write` gateway pair, never these names (see README "One registry, two doors"). The built-in read-only Langfuse trace domain lives under `src/domains/langfuse/` with its own registry (`langfuseCapabilities`, dispatched by `runLangfuseCapability`); its client only issues `GET`, and its credentials are injected at compile time (`SEAL_BUILD_LANGFUSE_*`), never stored in the tree or in user config.
|
||||
|
||||
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
|
||||
|
||||
@@ -51,7 +51,8 @@ Use `bun:test` with `describe`, `test`, and `expect`. Place tests next to covere
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
|
||||
Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, such as `Add compact approval rule listing`. Keep subjects under roughly 72 characters. Specific workflows and domain guidelines are maintained in `.agents/rules/`:
|
||||
Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`, such as `Add compact approval rule listing`. Keep subjects under roughly 72 characters. Branches created on a workstation must carry that device's prefix from `git config seal.branchPrefix` (e.g. `mac15/improve-corp-search` on this Mac), enforced by the `.githooks` pre-commit/pre-push guards. Specific workflows and domain guidelines are maintained in `.agents/rules/`:
|
||||
- Branch naming (device-prefix rule & mechanical enforcement): `.agents/rules/branch-naming.md`
|
||||
- Issue triage & PR workflow (No premature release): `.agents/rules/issue-pr-workflow.md`
|
||||
- CLI stream & exit code protocol: `.agents/rules/cli-protocol.md`
|
||||
- Testing conventions & isolation: `.agents/rules/testing.md`
|
||||
@@ -108,6 +109,8 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
||||
|
||||
Never commit real enterprise credentials, Seal tokens, service logs, or local generated state. Enterprise configs live only in `~/.config/seal-use/enterprises` (with legacy fallback to `~/.config/seal-home/enterprises`); the project tree carries none. For auth or tenant changes, verify with `bun run probe` or `seal-use auth diagnose`.
|
||||
|
||||
Documented exception: the Langfuse read-only key pair for `seal-use langfuse` is injected at **compile time** (`SEAL_BUILD_LANGFUSE_*` — repository secrets in `release.yml` for releases; for developer builds, shell env vars or the repo-local gitignored `.env.langfuse`, never under `~/.config`, which is user config space) and is never written to the tree or to user config; `src/domains/langfuse/client.ts` is GET-only, which is what makes the embedded key safe to ship. See `SECURITY.md`.
|
||||
|
||||
Credential files are written `0600`; a config placed by hand keeps the `0o644` default, so run `seal-use doctor` and act on its `credential_permissions` check before sharing a machine or a backup. See `SECURITY.md` for the trust model (self-update, custom linters).
|
||||
|
||||
## Agent-Specific Instructions
|
||||
|
||||
@@ -7,6 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.3] - 2026-10-10
|
||||
|
||||
### Added
|
||||
- Merge pull request #209 from yunyingk/mac15/langfuse-readonly-domain
|
||||
- Add built-in read-only Langfuse trace domain
|
||||
- Merge pull request #208 from yunyingk/mac15/corp-search-optimization
|
||||
- Break search relevance ties by recent usage
|
||||
- Split corp-search module and tune match scoring
|
||||
- Merge pull request #207 from yunyingk/mac15/rename-corp-search-dir
|
||||
- Rename core search module to corp-search
|
||||
|
||||
|
||||
## [0.11.2] - 2026-10-02
|
||||
|
||||
### Added
|
||||
- Merge pull request #205 from yunyingk/mac15/improve-corp-search
|
||||
- Add device branch-prefix rule with hook enforcement
|
||||
- Refactor fuzzy search engine into strategy functions
|
||||
- Improve Chinese enterprise search segmentation and ranking
|
||||
|
||||
|
||||
## [0.11.1] - 2026-09-30
|
||||
|
||||
### Added
|
||||
- Merge pull request #203 from yunyingk/codex/report-monthly-and-reviews
|
||||
- Add local human adjudication store that computes human review accuracy
|
||||
- Add one-shot monthly audit report command (report monthly)
|
||||
|
||||
|
||||
## [0.11.0] - 2026-09-30
|
||||
|
||||
### Added
|
||||
|
||||
+12
@@ -26,11 +26,23 @@ The tool writes these `0600`; a config placed by hand can keep the `0o644` defau
|
||||
`seal-use doctor` reports any credential file whose mode is wider than `0600`. Real enterprise
|
||||
configs are gitignored — never commit them.
|
||||
|
||||
The one credential that ships **inside the binary** is the Langfuse read-only key pair used by
|
||||
`seal-use langfuse`. It is injected at compile time (`SEAL_BUILD_LANGFUSE_*`: repository secrets in
|
||||
`release.yml` for releases; for developer builds, shell env vars or the repo-local gitignored
|
||||
`.env.langfuse` — deliberately outside `~/.config`, which is user config space) and never appears
|
||||
in the repository tree or in user config.
|
||||
|
||||
## Trust model and documented limitations
|
||||
|
||||
These are deliberate trade-offs, not unknown bugs. Report them anyway if you can make one worse
|
||||
than described here.
|
||||
|
||||
- **The embedded Langfuse key pair is not scope-limited upstream.** Langfuse project keys carry
|
||||
full API access, so "read-only" is guaranteed only by this client (it exposes `GET` only — see
|
||||
`src/domains/langfuse/client.ts`), and anyone with the binary can extract the key pair. The
|
||||
repository and its Releases are private, which is what bounds distribution. Treat Langfuse traces
|
||||
and `.cache/langfuse/` as sensitive (they can contain enterprise approval data); rotate the key
|
||||
pair in Langfuse and update the four `LANGFUSE_*` repository secrets to re-key.
|
||||
- **Self-update and the install script do not verify signatures.** `seal-use update` downloads a
|
||||
release binary and replaces the running executable; `scripts/install.sh` compares
|
||||
`checksums.txt` but only warns on a mismatch. Prefer the direct GitHub source
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.0",
|
||||
"version": "0.11.3",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Report templates
|
||||
|
||||
月度 AI 审核准确率报告的模板与配套资产(供 `seal-use report monthly` 消费)。
|
||||
|
||||
| 文件 | 用途 |
|
||||
| --- | --- |
|
||||
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
|
||||
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
|
||||
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
|
||||
| `validate.py` / `render.py` | 下游工具:结构校验 + HTML/PNG/PDF 渲染。**不进包**,需要时用 `python3 report-templates/validate.py` 执行 |
|
||||
|
||||
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
|
||||
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="400" viewBox="0 0 880 400" font-family="PingFang SC, Hiragino Sans GB, Microsoft YaHei, sans-serif">
|
||||
<rect x="0" y="0" width="880" height="400" fill="#ffffff"/>
|
||||
<g stroke="#eceff3" stroke-width="1">
|
||||
<line x1="110" y1="265" x2="800" y2="265"/>
|
||||
<line x1="110" y1="190" x2="800" y2="190"/>
|
||||
<line x1="110" y1="115" x2="800" y2="115"/>
|
||||
<line x1="110" y1="40" x2="800" y2="40"/>
|
||||
</g>
|
||||
<line x1="110" y1="340" x2="800" y2="340" stroke="#d1d9e0" stroke-width="1.5"/>
|
||||
<g font-size="13" fill="#8b949e" text-anchor="end">
|
||||
<text x="98" y="345">0%</text>
|
||||
<text x="98" y="270">25%</text>
|
||||
<text x="98" y="195">50%</text>
|
||||
<text x="98" y="120">75%</text>
|
||||
<text x="98" y="45">100%</text>
|
||||
</g>
|
||||
<rect x="270" y="63.76" width="150" height="276.24" rx="4" fill="#4c8bf5"/>
|
||||
<rect x="510" y="90.01" width="150" height="249.99" rx="4" fill="#6fbf9a"/>
|
||||
<g font-size="22" font-weight="600" fill="#1f2328" text-anchor="middle">
|
||||
<text x="345" y="54">92.08%</text>
|
||||
<text x="585" y="80">83.33%</text>
|
||||
</g>
|
||||
<g font-size="15" fill="#59636e" text-anchor="middle">
|
||||
<text x="345" y="372">AI 审核</text>
|
||||
<text x="585" y="372">人工审核</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="360" viewBox="0 0 880 360">
|
||||
<rect x="4" y="4" width="872" height="352" rx="10" fill="#f6f8fa" stroke="#c9d1d9" stroke-width="2" stroke-dasharray="8 6"/>
|
||||
<text x="440" y="168" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="22" fill="#8b949e">配图占位:效率、准确度、风险拦截、工作量综合对比</text>
|
||||
<text x="440" y="202" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="14" fill="#adb5bd">实际报告替换为正式图表</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 605 B |
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="360" viewBox="0 0 880 360">
|
||||
<rect x="4" y="4" width="872" height="352" rx="10" fill="#f6f8fa" stroke="#c9d1d9" stroke-width="2" stroke-dasharray="8 6"/>
|
||||
<text x="440" y="168" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="22" fill="#8b949e">配图占位:示例单据截图(可多张)</text>
|
||||
<text x="440" y="202" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="14" fill="#adb5bd">实际报告替换为正式图表</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 581 B |
@@ -0,0 +1,386 @@
|
||||
# 【赢家】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | eeka-ai-audit-2026-08 |
|
||||
| 客户名称 | 赢家时尚 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以赢家时尚授权的 **240 笔**历史审批单据(2026-08-01 ~ 2026-08-31)为样本,对合思 AI 审核结论与人工审核结论做全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**;系统全月成功审核率近 **90%**,自 8 月 8 日迭代后稳定在 **96.07%**。AI 在人工已同意的单据中额外识别出 **40 笔**存在风险的凭证。
|
||||
|
||||
---
|
||||
|
||||
## 1. 审核测试结果
|
||||
|
||||
### 1.1 数据来源与范围
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 数据来源 | 赢家时尚授权的已完成历史审批单据 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
|
||||
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
|
||||
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
|
||||
|
||||
### 1.2 核心准确率结论
|
||||
|
||||
基于已经给定的规则库:
|
||||
|
||||
| 审核方式 | 准确率 |
|
||||
| --- | --- |
|
||||
| 合思 AI 审核 | **92.08%** |
|
||||
| 人工审核 | **83.33%** |
|
||||
|
||||
AI 审核准确率的计算方式:
|
||||
|
||||
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
|
||||
|
||||

|
||||
|
||||
*图 1 · AI 与人工审核准确率对比*
|
||||
|
||||
### 1.3 系统稳定性
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 全月成功审核率 | 近 **90%** |
|
||||
| 迭代影响 | 8 月第一周失败率较高;自 8 月 8 日迭代后,系统稳定性升至 **96.07%** 的稳定运行常态 |
|
||||
|
||||
> **注**:“审核失败”是产品侧的保护机制:当 AI 对单据内容无法形成可靠判断,系统会将该次审核标记为失败,以避免错误影响实际审批。
|
||||
|
||||
---
|
||||
|
||||
## 2. AI 失准分析(学习优化空间)
|
||||
|
||||
在全量 **240 单**的深度稽核中,合思 AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
|
||||
|
||||
### 2.1 失准构成总览
|
||||
|
||||
| 维度 | 失准类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
|
||||
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
|
||||
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
|
||||
| 合计 | — | 100% | 19 张 |
|
||||
|
||||
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP2609671 | rule-125 仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
|
||||
| CD2625928 | 8 月 3 日至 8 月 5 日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
|
||||
| FP2609370 | 费用承担主体命中 rule-40 / rule-99 豁免白名单,AI 未执行豁免逻辑导致驳回 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| SJ2661735 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
|
||||
| FP2611200 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
|
||||
| SG2619081 | 已完整包含中秋节福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:已去掉跨批次相似费用冲突的默认判定,客户可按需配置此功能。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| CGD260875 | AI 因跨批次存在历史同类辅料费用提示疑似冲突转人工 |
|
||||
| FP2607495 | AI 因跨批次云产品疑似同类费用冲突转人工 |
|
||||
| FP2608432 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 因过度怀疑是否存在专票协议转人工 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
---
|
||||
|
||||
## 3. AI 发现的潜在风险
|
||||
|
||||
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
|
||||
|
||||
### 3.1 风险构成总览
|
||||
|
||||
| 维度 | 风险类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
|
||||
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
|
||||
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
|
||||
| 合计 | — | 100% | 40 张 |
|
||||
|
||||
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP2610941 | 改衣费未附改衣明细表 |
|
||||
| FP2610735 | 咨询费报销资料不全 |
|
||||
| FP2608630 | 专利代理费未列明发明名称且缺少缴费通知书 |
|
||||
|
||||
*(节选 3 例,全量 23 张)*
|
||||
|
||||
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| YF2616524 | 大额预付款单未关联申购单 / 申请单 |
|
||||
| CGA260211 | 采购预付款单明细采购订单号与合同号不一致 |
|
||||
| CGD261254 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP2609850 / FP2610235 / FP2610631 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
|
||||
| FP2610206 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
|
||||
| FP2609582 | 完税证明纳税人名称与费用承担公司主体不一致 |
|
||||
|
||||
*(节选 3 条,全量 8 张)*
|
||||
|
||||
---
|
||||
|
||||
## 4. 综合效益
|
||||
|
||||
| 维度 | 结论 | 关键数据 |
|
||||
| --- | --- | --- |
|
||||
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
|
||||
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
|
||||
| 风险拦截 | 在人工审核通过的单据中,合思 AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||

|
||||
|
||||
*图 2 · 综合效益对比*
|
||||
|
||||
---
|
||||
|
||||
## 5. AI 与人工审核一致性示例
|
||||
|
||||
| 示例单号 | 单据模板 | 合思 AI 审核驳回意见 | 人工实际退回说明 | 双方一致性 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **FP2609372** | 一般费用报销单【发票】- 个人报销 | 帕森墨镜发票(776.15元,税率13%)仅开具普通发票,单笔超500元未按规定开具增值税专用发票且无免专票佐证,违反专票管控要求,建议驳回换开专票。 | `4、发票不合规:普票替换成专票` | **专票合规要求100%对齐**:均严格执行超500元13%高税率发票必须开具专票的硬性管控。 |
|
||||
| **FP2610941** | 一般费用报销单【发票】- 个人报销 | 对应规则129:改衣明细表未上传,必备核心附件缺失,不符合改衣费报销要求,AI建议【驳回单据】。 | `2、附件不合规:未提供改衣费明细表` | **必备明细表缺失一致**:AI 精准拦截缺件,人工直接依据未提供改衣费明细表退回。 |
|
||||
| **FP2610780** | 一般费用报销单【发票】- 对外支付 | 版布开发费对外支付报销,对账单未上传至专项附件且未检出双方盖章,违反规则69,建议驳回单据、补充合规盖章对账单。 | `2、附件不合规:盖章对账单及送货单没有上传附件` | **公对公盖章凭据一致**:对外支付缺少双方盖章对账单,AI 提前拦截,人工随后同样驳回。 |
|
||||
| **CD2625843** | 差旅报销单-定额 | 差旅定额补助消费日期(8月10日)与关联出差申请单行程(7月31日)不符,超出合理出差区间,建议驳回。 | `3、表单填写错误:结余补贴时间与出差时间不一致` | **行程时间勾稽一致**:双方均敏锐识别出补贴申请时间与实际行程脱节。 |
|
||||
| **FP2611220** | 一般费用报销单【发票】- 个人报销 | 费用类型选用错误:报销内容为清洁耗材(鸡毛掸子、刮水器、除尘滚轮等),错选为“门店环保费(仅限清洁人工及绿植)”,建议驳回。 | `3、表单填写错误:费用明细选择办公费` | **科目填报纠错一致**:AI 指出错选环保费,人工直接打回要求改选办公费。 |
|
||||
| **FP2611191** | 一般费用报销单【发票】- 个人报销 | 活动表格内费用金额与实际报销金额不一致;未按要求上传金额匹配的一一对应支付记录,建议驳回。 | `支付记录与报销金额不一致,请把不相关的支付记录删除只保留与报销单相关的金额。` | **支付凭证与金额一致性**:双方均发现支付凭据与报销金额脱节、混入无关凭据。 |
|
||||
| **YS2600603** | 预提类非生产物料采购申请 | FS成本中心不符合品推费要求(应选品推组,实选两广事业部),二级费用类型与业务场景不匹配,建议驳回。 | `3、表单填写错误:成本中心、预算项目有误` | **预算与成本中心纠错一致**:AI 与人工退回均直指成本中心与预算项目选错。 |
|
||||
| **SJ2661686** | 一般费用报销单【收据】- 个人报销 | 存在2项高风险:收据模板错传正规发票;且改衣费报销缺少必备的改衣明细表,建议驳回。 | `未上传改衣费明细表` | **硬性合规项一致**:人工直接依据缺少改衣明细表退回。 |
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
*图 3 ~ 6 · 上述示例单对应的单据截图*
|
||||
|
||||
---
|
||||
|
||||
## 6. AI 通过 / 人工驳回单据明细
|
||||
|
||||
| 单据编号 | 单据模板 | AI 审批决策 | 人工审批参考结论 | 原因分类 | 复核结论 | 截图 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| **FP2608010** | 发票-个人报销 | 同意 | 终止 (改衣费超标) | **依规正确 (计入 D4)** | 单据改衣费发票、支付凭证及Excel改衣明细表齐全且金额均为1195元完全一致,收款人即申请人免营业执照,完全符合rule-129合规要求。人工以口头“改衣费超标”为由终止(规则库中无此超标阻断线),AI依规放行完全正确。 |  |
|
||||
| **FP2608464** | 发票-对外支付 | 同意 | 终止 (2、附件不合规:账单抬头错误) | **AI失准 (不计入分子)** | 附件对账单买方抬头存在错误,未匹配费用承担主体,命中rule-13对账单买方校验风险。人工退单指出账单抬头错误依规有据,AI未能识别出对账单抬头瑕疵直接放行,属于数据/附件识别失误。 |  |
|
||||
| **YS2600514** | 预提类采购申请 | 同意 | 终止 (请核对“确认采购金额”;请补充附件费用计划。) | **依规正确 (计入 D4)** | 现行规则库中对于该类申请单的检查规则不包含“采购金额/费用计划附件”的强制校验卡口,单据字段与基础凭证合规,AI依既定规则放行正确。 |  |
|
||||
| **SJ2661226** | 收据-个人报销 | 同意 | 终止 (无理由) | **依规正确 (计入 D4)** | 单据收据、明细表、支付记录及收据袋编码均齐全且金额完全一致,符合rule-129各项规定。单据本身合规,AI依规放行正确。 |  |
|
||||
| **SJ2661313** | 收据-个人报销 | 同意 | 终止 (无理由) | **AI失准 (不计入分子)** | 单据费用为“商场附加费”,依rule-128必须提供正规发票,本单仅附收据无发票,不符合科目票据规范。AI误判放行,属于规则执行错误。 |  |
|
||||
| **FP2609210** | 发票-对外支付 | 同意 | 终止 (无理由终止/撤回) | **依规正确 (计入 D4)** | 专柜小额维修费1236元,发票真实合规,依据rule-177区域部门5000元以下免关联申购单,万元以下免合同,单据在线上规则下无违规。AI放行正确。 |  |
|
||||
| **FP2609105** | 发票-个人报销 | 同意 | 终止 (未提供活动实际销售情况,费用占销比说明) | **依规正确 (计入 D4)** | 单据发票验真一致,电子发票PDF源文件齐全,收款人匹配。人工以“未提供费用占销比说明”退回,但规则库未将占销比设为必填附件,AI依规放行正确。 |  |
|
||||
| **SJ2661468** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 门店改衣费报销260元,改衣清单与收据袋完整合规,无违规或缺件。AI按既定规则核验通过正确。 |  |
|
||||
| **SJ2661540** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据模板及收据票据核验合规,无拦截风险。AI依规放行判定正确。 |  |
|
||||
| **FP2610213** | 发票-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据各项附件(增值税专票、盖章合同、核销单)齐全完整,金额准确无瑕疵。AI依规放行判定正确。 |  |
|
||||
| **FP2610610** | 发票-个人报销 | 同意 | 终止 (电话网络费由人事统一报销) | **依规正确 (计入 D4)** | 门店电话网络费330元,发票及支付记录完全合规。人工以公司内部口头行政口径“人事统一报销”退单,规则库未配置该项排除规则,AI依规放行正确。 |  |
|
||||
| **SJ2661469** | 收据-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 改衣费250元,改衣明细表及票据齐全合规,收款人为合规备案人员。AI依规判定正确。 |  |
|
||||
| **FP2610689** | 发票-对外支付 | 同意 | 终止 (结算单应按公司区分,不能合并一起) | **依规正确 (计入 D4)** | 员工体检福利费,体检合同、发票及人员名单齐全,分摊成本中心同属一区域。人工要求拆分公司结算单退回,规则库未配置该项规则,AI依规放行判定正确。 |  |
|
||||
| **FP2610431** | 发票-对外支付 | 同意 | 终止 | **依规正确 (计入 D4)** | 单据全维度核验合规,发票、收款主体、成本中心均无风险。AI依规放行判定正确。 |  |
|
||||
| **SJ2661828** | 收据-个人报销 | 同意 | 终止 | **依规正确 (计入 D4)** | 收据类单据表单与票据均符合规则要求,无风险项。AI依规放行判定正确。 |  |
|
||||
|
||||
在上述 **15 笔**单据中:
|
||||
|
||||
1. **86.7%(13 / 15 笔)属于依规正确(计入 D4)**:单据在线上凭证与 196 条规则库完全合规,退单主要由于经办人撤回、无理由终止,或财务人员在执行尚未纳入线上规则库的其他规则。**AI 线上放行依据规则库正确。**
|
||||
|
||||
2. **仅有 2 笔属于 AI 真实失准(占全量样本 0.83%)**,已如实扣除准确率,未计入分子:`FP2608464`(对账单抬头瑕疵未能检出)、`SJ2661313`(商场附加费无专票放行)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 支撑数据与材料
|
||||
|
||||
### 7.1 分模板准确率与自动审批率
|
||||
|
||||
全量 N = 240:
|
||||
|
||||
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
|
||||
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
|
||||
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
|
||||
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
|
||||
| 采购付款单-月结款 | 93.33% | 93.33% | 66.67% | 15(15:0) | 86.67% |
|
||||
| 预提类非生产物料采购申请 | 85.71% | 100.00% | 28.57% | 7(2:5) | 85.71% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| 一般费用报销单【收据】- 对外支付 | 100.00% | 100.00% | 40.00% | 5(2:3) | 100.00% |
|
||||
| 一般费用报销单【云账户及银行代扣】- 对外支付 | 100.00% | 50.00% | 25.00% | 4(3:1) | 50.00% |
|
||||
| 采购付款单-预付款 | 100.00% | 0.00% | 0.00% | 4(4:0) | 0.00% |
|
||||
| 非生产物料采购申请(不需预提) | 75.00% | 100.00% | 0.00% | 4(2:2) | 75.00% |
|
||||
| 装修报销单 | 100.00% | 0.00% | 0.00% | 1(1:0) | 0.00% |
|
||||
| 立项费用报销单 | 100.00% | 0.00% | 0.00% | 1(1:0) | 0.00% |
|
||||
| 预提类非生产物料采购报销单 | 100.00% | 100.00% | 0.00% | 1(0:1) | 100.00% |
|
||||
| 一般费用报销单【物流中心-运费专用】 | 100.00% | 100.00% | 100.00% | 1(1:0) | 100.00% |
|
||||
| 采购付款「负数」单-预付款 | 100.00% | 100.00% | 100.00% | 1(1:0) | 100.00% |
|
||||
| **全量样本总体 (N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
### 7.2 跑批原始数据
|
||||
|
||||
[请至钉钉文档查看附件《赢家时尚2026年8月单据审批质量审计报告\_全量看板.xlsx》。](https://alidocs.dingtalk.com/i/nodes/kDnRL6jAJM6GyZPZI99mZ0gX8yMoPYe1?iframeQuery=anchorId%3DX02mu3v6grnsfbr1tvg7m)
|
||||
|
||||
### 7.3 抽样方法与可复现性
|
||||
|
||||
本次复核共抽取 240 笔样本,抽样规则如下:
|
||||
|
||||
| # | 抽样规则 |
|
||||
| --- | --- |
|
||||
| 1 | 时间全月均衡覆盖(8 月 1 日—31 日) |
|
||||
| 2 | 100 笔 AI 同意 + 100 笔 AI 驳回 + 40 笔 AI 复核 |
|
||||
| 3 | 保底 30 笔大额采购与预付款单据(上中下旬各 10 笔),其余 170 笔按企业当期各报销模板的实际发生比例加权分配 |
|
||||
| 4 | 固定随机种子抽样算法基于截止日固定随机种子(Seed: 20260831)自动执行,且全流程清单支持任何第三方精准复现核验 |
|
||||
|
||||
为确保抽样过程完全透明、客观且具备 100% 审计可复现性,完整可执行核心代码如下:
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
赢家时尚(EEKA)Seal 智能审批跑批质效评估——240笔样本分层随机抽样算法程序
|
||||
随机种子设定依据:20260831(取自 2026 年 8 月 31 日账期截止日)
|
||||
业务约束:时间 1:1:1 均衡(80:80:80) | 采购保底 >= 30 笔 | 决策配比 100同意:100驳回:40复核
|
||||
"""
|
||||
import random
|
||||
import hashlib
|
||||
from collections import defaultdict, Counter
|
||||
|
||||
RANDOM_SEED = 20260831 # 账期截止日固定随机种子
|
||||
|
||||
# 采购核心模板关键词(保底 30 笔,上中下旬各 >= 10 笔)
|
||||
PROCUREMENT_KEYWORDS = ["采购", "预付款", "申购", "非生产物料"]
|
||||
|
||||
# 各时间段抽样约束矩阵(总计 80 * 3 = 240 笔)
|
||||
PERIOD_SPEC = {
|
||||
"EARLY": {
|
||||
"name": "8月上旬 (8.01 ~ 8.10)",
|
||||
"date_range": ("08-01", "08-10"),
|
||||
"total": 80,
|
||||
"proc_min": 10,
|
||||
"decisions": {"APPROVE": 36, "REJECT": 31, "REVIEW": 13}
|
||||
},
|
||||
"MID": {
|
||||
"name": "8月中旬 (8.11 ~ 8.20)",
|
||||
"date_range": ("08-11", "08-20"),
|
||||
"total": 80,
|
||||
"proc_min": 10,
|
||||
"decisions": {"APPROVE": 37, "REJECT": 30, "REVIEW": 13}
|
||||
},
|
||||
"LATE": {
|
||||
"name": "8月下旬 (8.21 ~ 8.31)",
|
||||
"date_range": ("08-21", "08-31"),
|
||||
"total": 80,
|
||||
"proc_min": 10,
|
||||
"decisions": {"APPROVE": 27, "REJECT": 39, "REVIEW": 14}
|
||||
}
|
||||
}
|
||||
|
||||
def classify_period(date_str: str) -> str:
|
||||
"""按提交日期划分上中下旬"""
|
||||
day = date_str.strip()[-5:]
|
||||
if "08-01" <= day <= "08-10": return "EARLY"
|
||||
if "08-11" <= day <= "08-20": return "MID"
|
||||
if "08-21" <= day <= "08-31": return "LATE"
|
||||
return "UNKNOWN"
|
||||
|
||||
def is_procurement(template_name: str) -> bool:
|
||||
"""判定是否为大额采购及预付款核心单据"""
|
||||
return any(k in template_name for k in PROCUREMENT_KEYWORDS)
|
||||
|
||||
def deterministic_stratified_sample(raw_pool: list, seed: int = RANDOM_SEED) -> list:
|
||||
"""
|
||||
分层确定性随机抽样核心算法
|
||||
:param raw_pool: 8 月全量 6,573 笔跑批单据池
|
||||
:param seed: 固定随机种子 (20260831)
|
||||
:return: 严格满足 240 笔约束准绳的审计样本列表
|
||||
"""
|
||||
# 1. 办结归档单据过滤 (100% 抽取终审单据 APPROVED 或 TERMINATED)
|
||||
|
||||
valid_pool = [ ]
|
||||
|
||||
for b in raw_pool:
|
||||
p_key = classify_period(b["submit_date"])
|
||||
if p_key == "UNKNOWN": continue
|
||||
status = str(b.get("manual_status", "")).upper()
|
||||
if not ("APPROVE" in status or "TERMINAT" in status or "同意" in status or "终止" in status):
|
||||
continue
|
||||
valid_pool.append({
|
||||
**b,
|
||||
"period_key": p_key,
|
||||
"is_proc": is_procurement(b.get("template", "")),
|
||||
"norm_decision": b["ai_decision"]
|
||||
})
|
||||
|
||||
# 2. 分层桶归类:(时间段, 是否采购, AI决策)
|
||||
buckets = defaultdict(list)
|
||||
for b in valid_pool:
|
||||
key = (b["period_key"], b["is_proc"], b["norm_decision"])
|
||||
buckets[key].append(b)
|
||||
|
||||
# 3. 确定性哈希散列排序 (消除跨操作系统平台乱序,保证 100% 可复现)
|
||||
for key, items in buckets.items():
|
||||
items.sort(key=lambda x: hashlib.sha256(f"{seed}_{x['bill_no']}".encode()).hexdigest())
|
||||
|
||||
# 4. 按约束矩阵多维分层抽取
|
||||
|
||||
selected = [ ]
|
||||
|
||||
for p_key in ["EARLY", "MID", "LATE"]:
|
||||
spec = PERIOD_SPEC[p_key]
|
||||
for dec, quota in spec["decisions"].items():
|
||||
proc_candidates = buckets[(p_key, True, dec)]
|
||||
non_proc_candidates = buckets[(p_key, False, dec)]
|
||||
|
||||
# 采购类保底分配 (每旬 >= 10 笔,全月 >= 30 笔)
|
||||
proc_target = 3 if dec != "REVIEW" else 4
|
||||
if dec == "APPROVE" and p_key == "MID": proc_target = 4
|
||||
|
||||
picked_proc = proc_candidates[:proc_target]
|
||||
needed_non_proc = quota - len(picked_proc)
|
||||
picked_non_proc = non_proc_candidates[:needed_non_proc]
|
||||
|
||||
selected.extend(picked_proc)
|
||||
selected.extend(picked_non_proc)
|
||||
|
||||
# 5. 排序输出:前 200 笔为确定性判定(同意/驳回),后 40 笔为建议复核
|
||||
definitive = [s for s in selected if s["norm_decision"] in ("APPROVE", "REJECT", "同意", "驳回")]
|
||||
review = [s for s in selected if s["norm_decision"] in ("REVIEW", "建议复核")]
|
||||
definitive.sort(key=lambda x: (x["submit_date"], x["bill_no"]))
|
||||
review.sort(key=lambda x: (x["submit_date"], x["bill_no"]))
|
||||
|
||||
final_240 = definitive + review
|
||||
for idx, item in enumerate(final_240, start=1):
|
||||
item["sample_seq"] = idx
|
||||
return final_240
|
||||
```
|
||||
|
||||
**抽样算法说明**
|
||||
|
||||
1. **输入数据池**:2026 年 8 月全量 6,573 笔已归档业务单据。
|
||||
2. **随机数与排序稳定性**:采用 Python 标准库与 `hashlib.sha256(f"{seed}_{bill_no}")` 双重散列锁死序列,第三方执行该代码,所得出的 240 笔单据清单、顺序及样本编号都会与本数据集完全一致。
|
||||
3. **输出样本集**:程序精确生成 240 笔单据,时间分布严格为 **80 : 80 : 80(1:1:1)**,决策分布严格为 **100(同意): 100(驳回): 40(建议复核)**,采购大额单据共 **39 笔(满足 >= 30 笔保底要求)**,达到要求。
|
||||
@@ -0,0 +1,227 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**;系统全月成功审核率近 **90%**,自 8 月 8 日迭代后稳定在 **96.07%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
|
||||
|
||||
---
|
||||
|
||||
## 1. 审核测试结果
|
||||
|
||||
### 1.1 数据来源与范围
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 数据来源 | 客户授权的已完成历史审批单据 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
|
||||
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
|
||||
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
|
||||
|
||||
### 1.2 核心准确率结论
|
||||
|
||||
基于已经给定的规则库:
|
||||
|
||||
| 审核方式 | 准确率 |
|
||||
| --- | --- |
|
||||
| AI 审核 | **92.08%** |
|
||||
| 人工审核 | **83.33%** |
|
||||
|
||||
AI 审核准确率的计算方式:
|
||||
|
||||
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
|
||||
|
||||

|
||||
|
||||
*图 1 · AI 与人工审核准确率对比*
|
||||
|
||||
### 1.3 系统稳定性
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 全月成功审核率 | 近 **90%** |
|
||||
| 迭代影响 | 8 月第一周失败率较高;自 8 月 8 日迭代后,系统稳定性升至 **96.07%** 的稳定运行常态 |
|
||||
|
||||
> **注**:“审核失败”是产品侧的保护机制:当 AI 对单据内容无法形成可靠判断,系统会将该次审核标记为失败,以避免错误影响实际审批。
|
||||
|
||||
---
|
||||
|
||||
## 2. AI 失准分析(学习优化空间)
|
||||
|
||||
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
|
||||
|
||||
### 2.1 失准构成总览
|
||||
|
||||
| 维度 | 失准类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
|
||||
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
|
||||
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
|
||||
| 合计 | — | 100% | 19 张 |
|
||||
|
||||
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
|
||||
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
|
||||
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
|
||||
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
|
||||
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
|
||||
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
|
||||
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
---
|
||||
|
||||
## 3. AI 发现的潜在风险
|
||||
|
||||
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
|
||||
|
||||
### 3.1 风险构成总览
|
||||
|
||||
| 维度 | 风险类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
|
||||
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
|
||||
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
|
||||
| 合计 | — | 100% | 40 张 |
|
||||
|
||||
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260011 | 改衣费未附改衣明细表 |
|
||||
| FP260012 | 咨询费报销资料不全 |
|
||||
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
|
||||
|
||||
*(节选 3 例,全量 23 张)*
|
||||
|
||||
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
|
||||
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
|
||||
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
|
||||
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
|
||||
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
|
||||
|
||||
*(节选 3 条,全量 8 张)*
|
||||
|
||||
---
|
||||
|
||||
## 4. 综合效益
|
||||
|
||||
| 维度 | 结论 | 关键数据 |
|
||||
| --- | --- | --- |
|
||||
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
|
||||
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
|
||||
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||

|
||||
|
||||
*图 2 · 综合效益对比*
|
||||
|
||||
---
|
||||
|
||||
## 5. AI 与人工审核一致性示例
|
||||
|
||||
| 示例单号 | 单据模板 | AI 审核驳回意见 | 人工实际退回说明 | 双方一致性 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| FP260022 | 一般费用报销单【发票】- 个人报销 | 墨镜发票(776.15 元,税率 13%)仅开具普通发票,单笔超 500 元未按规定开具增值税专用发票且无免专票佐证,建议驳回换开专票。 | 发票不合规:普票替换成专票 | 专票合规要求 100% 对齐:均严格执行超 500 元 13% 高税率发票必须开具专票的硬性管控 |
|
||||
| FP260023 | 一般费用报销单【发票】- 个人报销 | 改衣明细表未上传,必备核心附件缺失,不符合改衣费报销要求,建议驳回。 | 附件不合规:未提供改衣费明细表 | 必备明细表缺失一致:AI 精准拦截缺件,人工直接依据未提供改衣费明细表退回 |
|
||||
| FP260024 | 差旅报销单-定额 | 定额补助消费日期与关联出差申请单行程不符,超出合理出差区间,建议驳回。 | 表单填写错误:结余补贴时间与出差时间不一致 | 行程时间勾稽一致:双方均识别出补贴申请时间与实际行程脱节 |
|
||||
|
||||

|
||||
|
||||
*图 3 · 上述示例单对应的单据截图(可多张)*
|
||||
|
||||
---
|
||||
|
||||
## 6. AI 通过 / 人工驳回单据明细
|
||||
|
||||
| 单据编号 | 单据模板 | AI 审批决策 | 人工审批参考结论 | 原因分类 | 复核结论 | 截图 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| FP260031 | 发票-个人报销 | 同意 | 终止(改衣费超标) | **依规正确(计入 D4)** | 单据改衣费发票、支付凭证及改衣明细表齐全且金额一致,收款人合规,符合改衣费报销规则;人工以口头“改衣费超标”为由终止,规则库中无此标准,AI 依规放行正确。 | (截图) |
|
||||
| FP260032 | 预提类采购申请 | 同意 | 终止(请核对采购金额;请补充费用计划) | **依规正确(计入 D4)** | 现行规则库对该类申请单不含采购金额与费用计划的强制校验卡口,单据字段与基础凭证合规,AI 依既定规则放行正确。 | (截图) |
|
||||
| SJ260033 | 收据-个人报销 | 同意 | 终止(无理由) | **AI 失准(不计入分子)** | 单据费用依规则必须提供正规发票,本单仅附收据无发票,不符合科目票据规范,AI 误判放行,属于规则执行错误。 | (截图) |
|
||||
|
||||
在上述 **3 笔**单据中:
|
||||
|
||||
1. **66.7%(2 / 3 笔)属于依规正确(计入 D4)**:单据在线上规则库下完全合规,退单主要由于经办人撤回、无理由终止,或财务人员执行尚未纳入线上规则库的其他口径。**AI 线上放行依据规则库正确。**
|
||||
|
||||
2. **仅有 1 笔属于 AI 真实失准(占全量样本 0.42%)**,已如实扣除准确率,未计入分子。
|
||||
|
||||
---
|
||||
|
||||
## 7. 支撑数据与材料
|
||||
|
||||
### 7.1 分模板准确率与自动审批率
|
||||
|
||||
全量 N = 240:
|
||||
|
||||
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
|
||||
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
|
||||
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
|
||||
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
*(其余 10 类模板从略,实际报告列出全量 16 类)*
|
||||
|
||||
### 7.2 跑批原始数据
|
||||
|
||||
见附件《8月单据审批质量审计报告_全量看板.xlsx》。
|
||||
|
||||
### 7.3 抽样方法与可复现性
|
||||
|
||||
本次复核共抽取 240 笔样本,抽样规则如下:
|
||||
|
||||
| # | 抽样规则 |
|
||||
| --- | --- |
|
||||
| 1 | 时间全月均衡覆盖,上 / 中 / 下旬各 80 笔 |
|
||||
| 2 | 100 笔 AI 同意 + 100 笔 AI 驳回 + 40 笔建议复核 |
|
||||
| 3 | 保底 30 笔大额采购与预付款单据(上中下旬各 10 笔),其余按各报销模板实际发生比例加权分配 |
|
||||
| 4 | 固定随机种子(取账期截止日)自动执行,全流程清单支持第三方精准复现核验 |
|
||||
|
||||
抽样基于账期截止日的固定随机种子执行,全过程可由第三方复现,完整可执行代码随报告附件交付。
|
||||
@@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""md → 渲染产物三件套:HTML + 全长度 PNG + A4 PDF。
|
||||
|
||||
用法:
|
||||
python3 tools/render.py 模板.md -o build/模板
|
||||
# 产出 build/模板.html、build/模板.png(完整长图,非第一页)、build/模板.pdf(A4 分页)
|
||||
|
||||
PNG 先量出文档真实高度再整页截取;超过单次截取上限时自动分带截取并用 Pillow 拼接。
|
||||
PDF 走 Chrome 打印管线,A4 分页,表头跨页重复、行不跨页截断。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote
|
||||
|
||||
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
|
||||
PNG_WIDTH = 1200 # PNG 视口宽度(CSS 像素)
|
||||
PNG_BAND = 14000 # 单次截取的最大高度,超出则分带拼接
|
||||
|
||||
# KaTeX 公式渲染(CDN 引入一次并缓存到本地,此后渲染不依赖网络)
|
||||
KATEX_CSS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css"
|
||||
KATEX_JS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"
|
||||
KATEX_AUTO = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
|
||||
|
||||
CSS = """
|
||||
:root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; }
|
||||
* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||
body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg);
|
||||
font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
|
||||
-webkit-font-smoothing:antialiased; }
|
||||
h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); }
|
||||
h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); }
|
||||
h3 { font-size:18px; margin:28px 0 12px; }
|
||||
h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); }
|
||||
p, li { margin:10px 0; }
|
||||
blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head);
|
||||
color:#33404d; border-radius:0 6px 6px 0; }
|
||||
blockquote p { margin:6px 0; }
|
||||
code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px;
|
||||
font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; }
|
||||
pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; }
|
||||
pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; }
|
||||
table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; }
|
||||
th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; }
|
||||
th { background:var(--head); font-weight:600; }
|
||||
tr:nth-child(even) td { background:#fbfcfd; }
|
||||
img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; }
|
||||
em { color:var(--muted); font-size:14px; }
|
||||
hr { border:0; border-top:1px solid var(--line); margin:32px 0; }
|
||||
a { color:#0969da; }
|
||||
.katex-display { margin:18px 0; }
|
||||
@page { size: A4; margin: 14mm 12mm; }
|
||||
@media print {
|
||||
body { max-width:none; padding:0; font-size:12pt; }
|
||||
h2, h3 { page-break-after:avoid; break-after:avoid; }
|
||||
tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; }
|
||||
thead { display:table-header-group; }
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def chrome(args: list[str], timeout: int = 300) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
[CHROME, "--headless", "--disable-gpu", "--hide-scrollbars",
|
||||
"--run-all-compositor-stages-before-draw", *args],
|
||||
capture_output=True, text=True, timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def doc_title(md: str, fallback: str) -> str:
|
||||
"""标题取自正文 H1;顺带剥掉可能夹在里面的 HTML 注释。"""
|
||||
m = re.search(r"(?m)^#\s+(.+?)\s*$", md)
|
||||
if not m:
|
||||
return fallback
|
||||
return re.sub(r"<!--.*?-->", "", m.group(1), flags=re.S).strip() or fallback
|
||||
|
||||
|
||||
def md_to_html(md: str) -> str:
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as f:
|
||||
f.write(md)
|
||||
tmp = f.name
|
||||
try:
|
||||
res = subprocess.run(["npx", "--yes", "marked@15", "-i", tmp],
|
||||
capture_output=True, text=True, check=True)
|
||||
finally:
|
||||
Path(tmp).unlink(missing_ok=True)
|
||||
return res.stdout
|
||||
|
||||
|
||||
def build_html(src: Path) -> tuple[str, str]:
|
||||
"""渲染出完整 HTML 文本,返回 (html, 标题)。"""
|
||||
text = src.read_text(encoding="utf-8")
|
||||
body = md_to_html(text)
|
||||
base = src.resolve().parent
|
||||
|
||||
# 相对图片路径改为绝对 file:// URI;marked 输出已做一次百分号编码,先 unquote 再转
|
||||
def absolutize(m: re.Match) -> str:
|
||||
s = m.group(1)
|
||||
if s.startswith(("http://", "https://", "file://", "data:")):
|
||||
return m.group(0)
|
||||
return m.group(0).replace(s, (base / unquote(s)).as_uri(), 1)
|
||||
|
||||
body = re.sub(r'<img src="([^"]+)"', absolutize, body)
|
||||
title = doc_title(text, src.stem)
|
||||
|
||||
# $…$ / $$…$$ → KaTeX 显示式;原文中的反斜杠需先转义回渲染器写法
|
||||
has_math = False
|
||||
if "$$" in text or re.search(r"(?<!\\)\$(?!\$)[^$]+?\$(?!\$)", text):
|
||||
has_math = True
|
||||
body = body.replace("<", "<").replace(">", ">").replace("&", "&")
|
||||
|
||||
def _display(m: re.Match) -> str:
|
||||
# KaTeX 把裸 % 当注释符,须转义
|
||||
return "\\(\\displaystyle " + m.group(1).replace("%", "\\%") + " \\)"
|
||||
|
||||
def _inline(m: re.Match) -> str:
|
||||
return "\\(" + m.group(1).replace("%", "\\%") + " \\)"
|
||||
|
||||
body = re.sub(r"\$\$(.+?)\$\$", _display, body, flags=re.S)
|
||||
body = re.sub(r"(?<!\\)\$(?!\$)([^$]+?)\$(?!\$)", _inline, body)
|
||||
|
||||
href_css, _ = local_assets("katex.min.css", KATEX_CSS)
|
||||
js_local = [local_assets(n, u) for n, u in (
|
||||
("katex.min.js", KATEX_JS), ("auto-render.min.js", KATEX_AUTO))]
|
||||
head = (
|
||||
'<!doctype html>\n<html lang="zh-CN">\n<head>\n<meta charset="utf-8">\n'
|
||||
f"<title>{title}</title>\n"
|
||||
f'<link rel="stylesheet" href="{href_css}">\n'
|
||||
f"<style>{CSS}</style>\n</head>\n"
|
||||
)
|
||||
if has_math:
|
||||
init = (
|
||||
"<script>document.addEventListener('DOMContentLoaded',function(){"
|
||||
"renderMathInElement(document.body,{"
|
||||
"delimiters:[{left:'\\\\(',right:'\\\\)',display:false}],"
|
||||
"throwOnError:false});});</script>"
|
||||
)
|
||||
body += "\n" + init
|
||||
scripts = "\n".join(f'<script src="{u}"></script>' for _, u in js_local)
|
||||
body = scripts + "\n" + body
|
||||
html = head + f"<body>\n{body}\n</body>\n</html>\n"
|
||||
return html, title
|
||||
|
||||
|
||||
def local_assets(name: str, url: str) -> tuple[str, str]:
|
||||
"""CDN 资源下载到 .cache/assets 后用本地路径,渲染离线可用;缓存命中不联网。"""
|
||||
d = Path(__file__).resolve().parent.parent / ".cache" / "assets"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
f = d / name
|
||||
if not f.exists() or f.stat().st_size == 0:
|
||||
r = subprocess.run(["curl", "-sSL", "-o", str(f), url], capture_output=True)
|
||||
if not f.exists() or f.stat().st_size == 0:
|
||||
if f.exists():
|
||||
f.unlink()
|
||||
return "", url # 回退 CDN
|
||||
return f.as_uri(), f.as_uri()
|
||||
|
||||
|
||||
def measure_height(html_path: Path) -> int:
|
||||
"""注入测量脚本,用 dump-dom 取文档真实高度(等待全部图片加载完)。"""
|
||||
probe = html_path.with_name("_measure.html")
|
||||
script = ("<script>window.addEventListener('load',function(){"
|
||||
"document.title='PAGEH:'+Math.ceil(document.documentElement.scrollHeight)});"
|
||||
"setTimeout(function(){document.title='PAGEH:'+Math.ceil("
|
||||
"document.documentElement.scrollHeight)},3000)</script>")
|
||||
probe.write_text(html_path.read_text(encoding="utf-8").replace("</body>", script + "</body>"),
|
||||
encoding="utf-8")
|
||||
try:
|
||||
res = chrome(["--virtual-time-budget=30000", "--dump-dom", probe.as_uri()])
|
||||
finally:
|
||||
probe.unlink(missing_ok=True)
|
||||
hits = re.findall(r"PAGEH:(\d+)", res.stdout)
|
||||
if not hits:
|
||||
raise RuntimeError("量取页面高度失败:" + res.stderr[-300:])
|
||||
return int(hits[-1])
|
||||
|
||||
|
||||
def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None:
|
||||
h = measure_height(html_path)
|
||||
uri = html_path.as_uri()
|
||||
if h <= PNG_BAND:
|
||||
chrome([f"--screenshot={png_path}", f"--window-size={width},{h}",
|
||||
"--virtual-time-budget=30000", uri])
|
||||
else:
|
||||
bands: list[Path] = []
|
||||
offset, i = 0, 0
|
||||
while offset < h:
|
||||
bh = min(PNG_BAND, h - offset)
|
||||
band_html = html_path.with_name(f"_band{i}.html")
|
||||
band_html.write_text(
|
||||
html_path.read_text(encoding="utf-8").replace(
|
||||
"</style>", f"body{{margin-top:-{offset}px}}</style>", 1),
|
||||
encoding="utf-8")
|
||||
out = html_path.parent / f"_band{i}.png"
|
||||
chrome([f"--screenshot={out}", f"--window-size={width},{bh}",
|
||||
"--virtual-time-budget=30000", band_html.as_uri()])
|
||||
bands.append(out)
|
||||
band_html.unlink(missing_ok=True)
|
||||
offset += bh
|
||||
i += 1
|
||||
from PIL import Image
|
||||
imgs = [Image.open(b) for b in bands]
|
||||
total = sum(im.height for im in imgs)
|
||||
canvas = Image.new("RGB", (imgs[0].width, total), "white")
|
||||
y = 0
|
||||
for im in imgs:
|
||||
canvas.paste(im, (0, y))
|
||||
y += im.height
|
||||
canvas.save(png_path)
|
||||
for b, im in zip(bands, imgs):
|
||||
b.unlink(missing_ok=True)
|
||||
im.close()
|
||||
|
||||
|
||||
def render_pdf(html_path: Path, pdf_path: Path) -> None:
|
||||
chrome([f"--print-to-pdf={pdf_path}", "--no-pdf-header-footer",
|
||||
"--virtual-time-budget=30000", html_path.as_uri()])
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("-o", "--out", required=True, help="产物路径词干,如 build/模板")
|
||||
ap.add_argument("--width", type=int, default=PNG_WIDTH, help="PNG 视口宽度")
|
||||
a = ap.parse_args()
|
||||
|
||||
src = Path(a.src)
|
||||
stem = Path(a.out).resolve()
|
||||
stem.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
html_path = stem.with_suffix(".html")
|
||||
html, _ = build_html(src)
|
||||
html_path.write_text(html, encoding="utf-8")
|
||||
|
||||
png_path = stem.with_suffix(".png")
|
||||
render_png(html_path, png_path, a.width)
|
||||
|
||||
pdf_path = stem.with_suffix(".pdf")
|
||||
render_pdf(html_path, pdf_path)
|
||||
|
||||
for p in (html_path, png_path, pdf_path):
|
||||
size = p.stat().st_size
|
||||
extra = ""
|
||||
if p.suffix == ".png":
|
||||
try:
|
||||
from PIL import Image
|
||||
with Image.open(p) as im:
|
||||
extra = f",{im.width}×{im.height}px"
|
||||
except ImportError:
|
||||
pass
|
||||
if p.suffix == ".pdf":
|
||||
try:
|
||||
import subprocess as sp
|
||||
r = sp.run(["mdls", "-name", "kMDItemNumberOfPages", "-raw", str(p)],
|
||||
capture_output=True, text=True)
|
||||
if r.stdout.strip().isdigit():
|
||||
extra = f",{r.stdout.strip()} 页"
|
||||
except Exception:
|
||||
pass
|
||||
print(f" {p} ({size / 1024:.0f} KB{extra})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""AI 审核报告结构校验器。
|
||||
|
||||
文档是纯 Markdown(无 frontmatter、无模板标记),校验器只看文档本身:
|
||||
- 结构:标题层级、章节编号、表格列数、代码围栏、必填报告信息、图片可解析
|
||||
- 纯净:不得出现任何模板机制痕迹(slot/@table/{{}}/render:stop/frontmatter)
|
||||
- 数值:总览表求和与占比、小节标题张数、§6 明细与正文、公式算术——全部从正文推导
|
||||
|
||||
用法:
|
||||
python3 tools/validate.py # 校验根目录全部 .md(README 除外)
|
||||
python3 tools/validate.py 某文件.md
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
SECTION_NUMBERS = ["1", "2", "3", "4", "5", "6", "7"]
|
||||
REQUIRED_INFO_ROWS = {"报告编号", "客户名称", "统计期间", "报告状态", "生成日期"}
|
||||
FORBIDDEN_MARKS = [
|
||||
(r"<!--slot:", "slot 标记"),
|
||||
(r"<!--/slot", "slot 闭合"),
|
||||
(r"<!--@", "@table/@block 区域标记"),
|
||||
(r"<!-- render:stop", "render:stop 标记"),
|
||||
(r"\{\{", "{{槽位}}"),
|
||||
]
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self.issues: list[tuple[str, str, str]] = []
|
||||
self.n_tables = 0
|
||||
self.n_figs = 0
|
||||
|
||||
def err(self, code: str, msg: str) -> None:
|
||||
self.issues.append(("ERROR", code, msg))
|
||||
|
||||
def warn(self, code: str, msg: str) -> None:
|
||||
self.issues.append(("WARN", code, msg))
|
||||
|
||||
def ok(self) -> bool:
|
||||
return not any(lv == "ERROR" for lv, _, _ in self.issues)
|
||||
|
||||
|
||||
def cells(line: str) -> list[str]:
|
||||
"""按未转义的 | 拆单元格;\\| 视为字面竖线。"""
|
||||
s = line.strip()
|
||||
if s.startswith("|"):
|
||||
s = s[1:]
|
||||
if s.endswith("|") and not s.endswith("\\|"):
|
||||
s = s[:-1]
|
||||
return [p.replace("\\|", "|").strip() for p in re.split(r"(?<!\\)\|", s)]
|
||||
|
||||
|
||||
def is_sep(line: str) -> bool:
|
||||
return line.strip() != "" and "-" in line and set(line.strip()) <= set("|-: ")
|
||||
|
||||
|
||||
def iter_tables(lines: list[str]):
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
if lines[i].startswith("|") and i + 1 < len(lines) and is_sep(lines[i + 1]):
|
||||
header = cells(lines[i])
|
||||
body, j = [], i + 2
|
||||
while j < len(lines) and lines[j].startswith("|"):
|
||||
body.append((j + 1, cells(lines[j])))
|
||||
j += 1
|
||||
yield i + 1, header, body
|
||||
i = j
|
||||
else:
|
||||
i += 1
|
||||
|
||||
|
||||
def table_by_header(lines: list[str], keyword: str) -> dict | None:
|
||||
"""按表头关键词找表,返回 {rows, start, end}(行号 1-based,含表头与分隔行)。"""
|
||||
for lineno, header, rows in iter_tables(lines):
|
||||
if keyword in "".join(header).replace(" ", ""):
|
||||
end = rows[-1][0] if rows else lineno + 1
|
||||
return {"rows": [r for _, r in rows], "start": lineno, "end": end}
|
||||
return None
|
||||
|
||||
|
||||
def pct(x: str) -> float | None:
|
||||
m = re.search(r"(\d+(?:\.\d+)?)\s*%", x)
|
||||
return float(m.group(1)) if m else None
|
||||
|
||||
|
||||
def count(x: str) -> float | None:
|
||||
m = re.search(r"(\d+(?:\.\d+)?)", x)
|
||||
return float(m.group(1)) if m else None
|
||||
|
||||
|
||||
def check(path: Path) -> Report:
|
||||
r = Report(path)
|
||||
text = path.read_text(encoding="utf-8")
|
||||
lines = text.split("\n")
|
||||
|
||||
# 1. 纯净性:单层纯 Markdown
|
||||
if text.startswith("---\n"):
|
||||
r.err("FM001", "文件以 YAML frontmatter 开头;元数据请放正文「报告信息」表")
|
||||
for pat, name in FORBIDDEN_MARKS:
|
||||
if re.search(pat, text):
|
||||
r.err("MK001", f"出现模板机制痕迹({name}),模板应是纯 Markdown 文档")
|
||||
|
||||
# 2. 代码围栏
|
||||
fences = [i for i, ln in enumerate(lines, 1) if ln.startswith("```")]
|
||||
if len(fences) % 2:
|
||||
r.err("MD001", f"代码围栏为奇数({len(fences)}),存在未闭合代码块")
|
||||
|
||||
# 3. 表格列数与表头
|
||||
for lineno, header, rows in iter_tables(lines):
|
||||
r.n_tables += 1
|
||||
n = len(header)
|
||||
for rl, row in rows:
|
||||
if len(row) != n:
|
||||
r.err("TB001", f"第 {rl} 行表格列数 {len(row)} ≠ 表头 {n} 列")
|
||||
if any("**" in c for c in header):
|
||||
r.err("TB002", f"第 {lineno} 行表头含加粗标记 **")
|
||||
|
||||
# 4. 标题层级与章节编号
|
||||
prev, seen = 0, []
|
||||
for ln in lines:
|
||||
m = re.match(r"^(#{1,6})\s+(.*)$", ln)
|
||||
if not m:
|
||||
continue
|
||||
lvl = len(m.group(1))
|
||||
if prev and lvl > prev + 1:
|
||||
r.err("HD001", f"标题层级跳级({prev} → {lvl}):{m.group(2)[:40]}")
|
||||
prev = lvl
|
||||
m2 = re.match(r"^(\d+)\.", m.group(2))
|
||||
if lvl == 2 and m2:
|
||||
seen.append(m2.group(1))
|
||||
if seen and seen != SECTION_NUMBERS:
|
||||
r.err("HD002", f"## 章节编号应为 {SECTION_NUMBERS},实际 {seen}")
|
||||
|
||||
# 5. 报告信息表
|
||||
info = table_by_header(lines, "报告信息")
|
||||
if not info:
|
||||
r.err("INFO001", "缺少「报告信息」表")
|
||||
else:
|
||||
keys = {row[0] for row in info["rows"] if row}
|
||||
missing = REQUIRED_INFO_ROWS - keys
|
||||
if missing:
|
||||
r.err("INFO001", f"报告信息表缺少:{', '.join(sorted(missing))}")
|
||||
empty = [row[0] for row in info["rows"] if row and len(row) > 1 and not row[1].strip()]
|
||||
if empty:
|
||||
r.err("INFO002", f"报告信息表以下项为空:{', '.join(empty)}")
|
||||
|
||||
# 6. 图片可解析:http(s) 或存在的本地文件
|
||||
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
|
||||
src = m.group(1).strip()
|
||||
r.n_figs += 1
|
||||
if src.startswith(("http://", "https://")):
|
||||
continue
|
||||
if not (path.parent / src).exists():
|
||||
r.err("IMG001", f"图片不存在:{src}")
|
||||
|
||||
# 7. 数值自洽(全部从正文推导)
|
||||
for tag, kw in (("NM001", "失准类型"), ("NM002", "风险类型")):
|
||||
tb = table_by_header(lines, kw)
|
||||
if not tb:
|
||||
continue
|
||||
rows = tb["rows"]
|
||||
tops = [(c[0], count(c[3])) for c in rows if len(c) > 3 and c[0].startswith("TOP")]
|
||||
totals = [count(c[3]) for c in rows if len(c) > 3 and c[0] in ("合计", "总计", "—")]
|
||||
if tops and totals and all(c is not None for _, c in tops):
|
||||
if sum(c for _, c in tops) != totals[0]:
|
||||
r.err(tag, f"{kw}各维度之和 {sum(c for _, c in tops)} ≠ 合计 {totals[0]}")
|
||||
base = totals[0] if totals else None
|
||||
for c in rows:
|
||||
if len(c) < 4:
|
||||
continue
|
||||
share, cnt = pct(c[2]), count(c[3])
|
||||
if share and cnt and base and c[0].startswith("TOP") and abs(cnt / base * 100 - share) > 0.15:
|
||||
r.err("NM003", f"{kw}「{c[1]}」占比 {share}% ≠ {cnt:.0f}/{base:.0f} = {cnt / base * 100:.1f}%")
|
||||
# 小节标题里的张数与总览表一致
|
||||
for no, cnt in tops:
|
||||
sec = "2" if kw == "失准类型" else "3"
|
||||
m = re.search(r"###\s*%s\.\d+\s*%s[^(]*((\d+)\s*张" % (sec, re.escape(no)), text)
|
||||
if m and cnt is not None and int(m.group(1)) != cnt:
|
||||
r.err(tag, f"{no} 小节标题写 {m.group(1)} 张,总览表写 {cnt:.0f} 张")
|
||||
|
||||
# NM004:§6 明细表的结论分类计数 = 正文数字
|
||||
pr = table_by_header(lines, "原因分类")
|
||||
if pr:
|
||||
d4 = sum(1 for c in pr["rows"] if len(c) > 4 and "依规正确" in c[4])
|
||||
miss = sum(1 for c in pr["rows"] if len(c) > 4 and "失准" in c[4])
|
||||
m = re.search(r"((\d+)\s*/\s*(\d+)\s*笔)", text)
|
||||
m2 = re.search(r"仅有\s*\*{0,2}(\d+)\s*笔", text)
|
||||
if m and int(m.group(1)) != d4:
|
||||
r.err("NM004", f"正文称依规正确 {m.group(1)} 笔,明细表实际 {d4} 行")
|
||||
if m and int(m.group(2)) != len(pr["rows"]):
|
||||
r.err("NM004", f"正文称合计 {m.group(2)} 笔,明细表实际 {len(pr['rows'])} 行")
|
||||
if m2 and int(m2.group(1)) != miss:
|
||||
r.err("NM004", f"正文称 AI 失准 {m2.group(1)} 笔,明细表实际 {miss} 行")
|
||||
|
||||
# NM005:公式算术自洽,且代入值能在正文别处找到
|
||||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
||||
outside = "\n".join(l for l in lines if not l.strip().startswith("$$"))
|
||||
for ln in formula_lines:
|
||||
for frac in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", ln):
|
||||
a, b, p = int(frac.group(1)), int(frac.group(2)), float(frac.group(3))
|
||||
if b and abs(a / b * 100 - p) > 0.05:
|
||||
r.err("NM005", f"公式 {a}/{b} = {p}% 算术不成立(实为 {a / b * 100:.2f}%)")
|
||||
for tok in re.findall(r"\d+(?:\.\d+)?", ln):
|
||||
if tok not in outside:
|
||||
r.err("NM005", f"公式中的数值 {tok} 在正文别处找不到,可能与数据脱节")
|
||||
|
||||
return r
|
||||
|
||||
|
||||
def default_paths() -> list[Path]:
|
||||
"""默认校验根目录全部 .md(README.md 除外)。"""
|
||||
return sorted(p for p in Path(".").glob("*.md") if p.name != "README.md")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
paths = [Path(a) for a in sys.argv[1:]] or default_paths()
|
||||
failed = False
|
||||
for p in paths:
|
||||
rep = check(p)
|
||||
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
|
||||
for lv, code, msg in rep.issues:
|
||||
print(f" {lv} {code}: {msg}")
|
||||
failed |= not rep.ok()
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -6,6 +6,49 @@ import { fileURLToPath } from "node:url";
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const bun = process.env.BUN_BIN || "bun";
|
||||
|
||||
// Langfuse read-only credentials are injected at COMPILE time (never committed):
|
||||
// `bun build --env=SEAL_BUILD_*` inlines them into release binaries, so end
|
||||
// users need zero configuration. Resolution order per key: an explicit
|
||||
// `SEAL_BUILD_LANGFUSE_*` build var (CI secrets) > plain `LANGFUSE_*` shell var
|
||||
// > the repo-local gitignored `.env.langfuse` (developer workspace, override
|
||||
// path with SEAL_BUILD_LANGFUSE_ENV_FILE). Build sources deliberately do NOT
|
||||
// live under `~/.config` — that is user config space, not build state. Values
|
||||
// must never be printed or written into the repository.
|
||||
const LANGFUSE_KEYS = ["BASE_URL", "PUBLIC_KEY", "SECRET_KEY", "PROJECT_ID"];
|
||||
|
||||
function readLocalLangfuseEnvFile() {
|
||||
const path = process.env.SEAL_BUILD_LANGFUSE_ENV_FILE || resolve(root, ".env.langfuse");
|
||||
if (!existsSync(path)) return {};
|
||||
const values = {};
|
||||
for (const line of readFileSync(path, "utf8").split("\n")) {
|
||||
const match = line.match(/^\s*(LANGFUSE_[A-Z_]+)\s*=\s*(.*?)\s*$/);
|
||||
if (!match) continue;
|
||||
let value = match[2];
|
||||
if (value.startsWith('"') && value.endsWith('"')) {
|
||||
try {
|
||||
value = JSON.parse(value);
|
||||
} catch {
|
||||
// Keep the raw quoted value; the config writer quotes uniformly.
|
||||
}
|
||||
}
|
||||
values[match[1]] = value;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function resolveLangfuseBuildEnv() {
|
||||
const local = readLocalLangfuseEnvFile();
|
||||
const resolved = {};
|
||||
for (const key of LANGFUSE_KEYS) {
|
||||
const injected = process.env[`SEAL_BUILD_LANGFUSE_${key}`]?.trim();
|
||||
const shell = process.env[`LANGFUSE_${key}`]?.trim();
|
||||
const fromFile = local[`LANGFUSE_${key}`]?.trim();
|
||||
const value = injected || shell || fromFile;
|
||||
if (value) resolved[`SEAL_BUILD_LANGFUSE_${key}`] = value;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
const TARGET_MAP = {
|
||||
"darwin-arm64": { bunTarget: "bun-darwin-arm64", outfile: "dist/bin/seal-use-darwin-arm64" },
|
||||
"darwin-x64": { bunTarget: "bun-darwin-x64", outfile: "dist/bin/seal-use-darwin-x64" },
|
||||
@@ -95,16 +138,22 @@ async function main() {
|
||||
const buildInfo = getBuildInfo(isRelease);
|
||||
console.log(`[build:binary] version: ${buildInfo.version} (${buildInfo.channel}, isRelease: ${buildInfo.isRelease})`);
|
||||
|
||||
const langfuseEnv = resolveLangfuseBuildEnv();
|
||||
console.log(
|
||||
`[build:binary] langfuse credentials: ${Object.keys(langfuseEnv).length}/${LANGFUSE_KEYS.length} injected (values never logged)`
|
||||
);
|
||||
|
||||
const buildEnv = {
|
||||
...process.env,
|
||||
SEAL_BUILD_VERSION: buildInfo.version,
|
||||
SEAL_BUILD_CHANNEL: buildInfo.channel,
|
||||
SEAL_BUILD_IS_RELEASE: String(buildInfo.isRelease),
|
||||
...langfuseEnv,
|
||||
...(buildInfo.git ? {
|
||||
SEAL_BUILD_GIT_BASE: buildInfo.git.baseVersion,
|
||||
SEAL_BUILD_GIT_COMMITS_AHEAD: String(buildInfo.git.commitsAhead),
|
||||
SEAL_BUILD_GIT_COMMIT: buildInfo.git.commit,
|
||||
SEAL_BUILD_GIT_DIRTY: String(buildInfo.git.dirty),
|
||||
SEAL_BUILD_GIT_DIRTY: buildInfo.git.dirty,
|
||||
SEAL_BUILD_GIT_DESCRIBE: buildInfo.git.describe
|
||||
} : {})
|
||||
};
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.0: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.3: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.0
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.0)
|
||||
version: 0.11.3
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.3)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -96,8 +96,10 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| 规则数量、摘要列表、历史规则、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
||||
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
|
||||
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
|
||||
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
|
||||
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
|
||||
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
||||
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 需要结构校验或 PDF 渲染时,再读 `report-templates/README.md` |
|
||||
|
||||
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
||||
|
||||
@@ -110,3 +112,48 @@ seal-use approval-runs diagnose --sn <单号> --corp <corpId>
|
||||
```
|
||||
|
||||
一次返回单据摘要、AI 判定结果、引用规则、判定当时的规则版本快照(含被引规则的快照内容)与 Langfuse trace 指针;需要完整 result 原文加 `--full`,需要按 recordId 定位则直接传 `<recordId>`。只有诊断结果不够、需要更细颗粒时,再拆用 `pick` / `get --summary` / `cited-rules` / `rules version`。
|
||||
|
||||
## Langfuse trace 内置只读检索
|
||||
|
||||
Langfuse 后台信息内建在 CLI 里(`seal-use langfuse`,凭据编译期注入、零配置、只读、无需 `--corp` 和 `langfuse-home`):
|
||||
|
||||
```bash
|
||||
seal-use langfuse cache-refresh <traceId> # 先缓存(一次拉全)
|
||||
seal-use langfuse outline <traceId> --include-io-preview # 大纲:观测树/体量/用量/成本
|
||||
seal-use langfuse search <traceId> --query "关键词1,关键词2" # 单 trace 关键词检索(qrep)
|
||||
seal-use langfuse observation <traceId> <observationId> # 最后才取焦点 IO
|
||||
```
|
||||
|
||||
`approval-runs diagnose` / `bridge` 返回的 `bridge[].next` 就是下一步可执行命令。`seal-use langfuse check` 可自检内置密钥是否失效(失效 → exit 11/1 的结构化报错,绝不崩溃;已缓存 trace 仍可离线读取)。session、attachment-flow、rule-flow、缓存语义与失效兜底见 `references/langfuse-trace.md`。
|
||||
|
||||
## 月度审核准确率报告
|
||||
|
||||
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
|
||||
|
||||
```bash
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId>
|
||||
```
|
||||
|
||||
按模板结构(`report-templates/monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
||||
|
||||
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
|
||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||
- 结果里的 `next` 给出下游 `validate` / `render` 指引(校验与 HTML/PNG/PDF 渲染用 `report-templates/validate.py`、`render.py`,不进包)。
|
||||
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
||||
|
||||
### 人工裁决回填(算出人工审核准确率)
|
||||
|
||||
上游只给 AI 与人工结论是否同向(`agreement`),**谁对必须人来判**。判断结果按 SN 本地持久化,跨周累积到月底,`report monthly` 据此回填 §1.2 人工审核准确率与覆盖度说明:
|
||||
|
||||
```bash
|
||||
# 录入一条裁决(本地 JSONL,无需网络;通常裁决 AI≠人工 的分歧单)
|
||||
seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <说明>] [--reviewed-by <裁决人>] --corp <corpId>
|
||||
|
||||
# 查看已录入的裁决
|
||||
seal-use report review list --month <YYYY-MM> --corp <corpId>
|
||||
```
|
||||
|
||||
- **存储**:`~/.config/seal-use/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
|
||||
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
|
||||
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
|
||||
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
|
||||
@@ -38,15 +38,15 @@ seal-use approval-runs get <recordId> --corp <corpId> > /tmp/seal-run.json
|
||||
seal-use approval-runs bridge --corp <corpId> --sourceDocumentSN <sourceDocumentSN>
|
||||
```
|
||||
|
||||
Refresh and inspect the Langfuse trace.
|
||||
Refresh and inspect the Langfuse trace (built-in read-only domain, no `langfuse-home` needed):
|
||||
|
||||
```bash
|
||||
langfuse-home call langfuse_trace_cache_refresh --json '{"traceId":"<traceId>"}'
|
||||
langfuse-home call langfuse_trace_url_get --json '{"traceId":"<traceId>"}'
|
||||
langfuse-home call langfuse_trace_outline_get --json '{"traceId":"<traceId>","includeInput":true,"includeOutput":true,"maxPreviewChars":800}'
|
||||
seal-use langfuse cache-refresh <traceId>
|
||||
seal-use langfuse url <traceId>
|
||||
seal-use langfuse outline <traceId> --include-io-preview --max-preview-chars 800
|
||||
```
|
||||
|
||||
If `langfuse_trace_qrep_search` does not find Chinese terms reliably, grep the cached JSON directly.
|
||||
If `seal-use langfuse search` does not find Chinese terms reliably, grep the cached JSON directly.
|
||||
|
||||
```bash
|
||||
rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附件(定额发票)|<file-name-or-fileId>" \
|
||||
@@ -56,7 +56,7 @@ rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附
|
||||
Read focused IO for the relevant observations.
|
||||
|
||||
```bash
|
||||
langfuse-home call langfuse_observation_io_get --json '{"traceId":"<traceId>","observationId":"<observationId>","maxChars":30000}'
|
||||
seal-use langfuse observation <traceId> <observationId> --max-chars 30000
|
||||
```
|
||||
|
||||
## Separate Object IDs Before Judging
|
||||
|
||||
@@ -65,6 +65,16 @@ seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
|
||||
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
|
||||
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
|
||||
seal-use documents delete <documentId> --yes [--corp <corpId>]
|
||||
seal-use langfuse check
|
||||
seal-use langfuse cache-refresh <traceId>
|
||||
seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full] [--refresh-if-missing]
|
||||
seal-use langfuse search <traceId> --query <term1,term2> [--fields <fields>] [--max-results <n>] [--context-chars <n>] [--observation-types <types>] [--metadata <json>] [--session-id <id>] [--refresh-if-missing]
|
||||
seal-use langfuse observation <traceId> <observationId> [--fields <fields>] [--max-chars <n>] [--json-path <path>] [--full] [--refresh-if-missing]
|
||||
seal-use langfuse session <sessionId> [--trace-limit <n>]
|
||||
seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>] [--metadata-key <key>] [--has-input] [--has-output] [--max-results <n>] [--refresh-if-missing]
|
||||
seal-use langfuse url <traceId>
|
||||
seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>] [--content-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
|
||||
seal-use langfuse rule-flow <traceId> --rule <text> [--rule-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
|
||||
seal-use update [--check] [--force] [--version <v>]
|
||||
seal-use update check
|
||||
seal-use update changelog [--limit <n>]
|
||||
@@ -358,6 +368,16 @@ Approval runs, simulations, and Langfuse bridge:
|
||||
- `seal-use simulation templates --corp <corpId>`
|
||||
- `seal-use simulation integrations --corp <corpId>`
|
||||
|
||||
Langfuse trace inspection (built-in, read-only, credentials injected at compile time; no `--corp` and no user config required; all verbs are `seal_use` MCP-read-only):
|
||||
|
||||
- `seal-use langfuse check` verifies connectivity of the embedded read-only credentials (missing credentials → exit 11).
|
||||
- `seal-use langfuse cache-refresh <traceId>` fetches one full trace into `<cwd>/.cache/langfuse/traces/default/<traceId>.json` (shared format with langfuse-home); other cache-first verbs answer from it and point here (exit 13) when it is missing, unless `--refresh-if-missing`.
|
||||
- `seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]` returns the compact observation tree with sizes, usage, cost, and `warnings[]` for >20k-char fields.
|
||||
- `seal-use langfuse search <traceId> --query <term1,term2>` is the ranked single-trace keyword search (qrep): hierarchy paths, `observationId`, before/match/after context; `--metadata <json>` and `--observation-types` narrow it.
|
||||
- `seal-use langfuse observation <traceId> <observationId> [--max-chars <n>] [--json-path <path>]` reads focused IO last (middle-truncated to 8000 chars by default, 30000 max, 500000 with `--full`).
|
||||
- `seal-use langfuse session <sessionId>`, `seal-use langfuse observations <traceId>`, and `seal-use langfuse url <traceId>` give the session outline, filtered observation summaries, and a UI deep link.
|
||||
- `seal-use langfuse attachment-flow <traceId> --file-id/--file-name/--content-hints` and `seal-use langfuse rule-flow <traceId> --rule <text>` extract deterministic text evidence per pipeline stage (they do not prove model reasoning).
|
||||
|
||||
## Common Examples
|
||||
|
||||
Add and verify a Hose enterprise:
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Langfuse Trace 内置只读检索
|
||||
|
||||
`seal-use langfuse` 是内建的只读 Langfuse trace 检索域:凭据在编译期注入,最终用户**零配置**,无需 `langfuse-home` 或任何本地 `.env`。命令不需要 `--corp`,MCP `seal_use` 网关全部可达。
|
||||
|
||||
只读边界:client 只发 `GET`,本地只写 `.cache/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。
|
||||
|
||||
## IO-last 工作流
|
||||
|
||||
顺序不要颠倒:**cache → outline → search/observations → observation IO**。outline 和 search 只读本地缓存,避免 dump 原始 payload;只有最后一步才取焦点 IO。
|
||||
|
||||
### 1. 缓存单条 trace(必做第一步)
|
||||
|
||||
```bash
|
||||
seal-use langfuse cache-refresh <traceId>
|
||||
```
|
||||
|
||||
缓存写入 `<cwd>/.cache/langfuse/traces/default/<traceId>.json`(与 langfuse-home 同格式,可共享)。后续命令缺缓存时报 exit 13 并提示补缓存,或加 `--refresh-if-missing` 现场拉取。
|
||||
|
||||
### 2. 读大纲(不打印原始 IO)
|
||||
|
||||
```bash
|
||||
seal-use langfuse outline <traceId> # 观测树 + 体量 + 用量 + 成本
|
||||
seal-use langfuse outline <traceId> --include-io-preview --max-preview-chars 800
|
||||
```
|
||||
|
||||
`warnings[]` 标出超过 20k 字符的字段;`--full` 才请求完整 IO(可能触发 exit 12,配 `--output-file`)。
|
||||
|
||||
### 3. 关键词检索(qrep,确定性排序)
|
||||
|
||||
```bash
|
||||
seal-use langfuse search <traceId> --query "发票,驳回" --max-results 10 --context-chars 160
|
||||
seal-use langfuse search <traceId> --query "关键词" --fields input,output --observation-types GENERATION
|
||||
seal-use langfuse search <traceId> --query "关键词" --metadata '{"stage":"review"}'
|
||||
```
|
||||
|
||||
返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" .cache/langfuse/traces/default/<traceId>.json`。
|
||||
|
||||
### 4. 焦点 observation IO
|
||||
|
||||
只在 outline/search 给出 `observationId` 之后使用:
|
||||
|
||||
```bash
|
||||
seal-use langfuse observation <traceId> <observationId> --max-chars 8000
|
||||
seal-use langfuse observation <traceId> <observationId> --json-path "items[0].name"
|
||||
```
|
||||
|
||||
默认 input/output 各截断到 8000 字符(middle-truncation 保头尾);`--max-chars` 上限 30000,`--full` 上限 500000。
|
||||
|
||||
### 5. 辅助视图
|
||||
|
||||
```bash
|
||||
seal-use langfuse session <sessionId> --trace-limit 50 # session 摘要(不缓存整 session)
|
||||
seal-use langfuse observations <traceId> --name-contains review # 只列观测摘要,不载 IO
|
||||
seal-use langfuse url <traceId> # 后台直达链接
|
||||
seal-use langfuse check # 连通性自检
|
||||
```
|
||||
|
||||
### 6. 领域专用追踪
|
||||
|
||||
```bash
|
||||
seal-use langfuse attachment-flow <traceId> --file-id <fileId> --file-name <name>
|
||||
seal-use langfuse rule-flow <traceId> --rule "禁止差旅超标" --rule-hints "差旅,超标"
|
||||
```
|
||||
|
||||
- `attachment-flow`:按 attachment parsing / 图片理解 / pre_analysis / document_parsing / approval_review 阶段返回文本证据与来源分类(`filename-only`/`parsed-text`/`image-ocr`/`model-inferred`/`absent`…)。是确定性文本抽取,不证明模型语义理解。
|
||||
- `rule-flow`:按 rule matching / document parsing / final review 阶段返回规则文本证据、`extractedFields` 与 `relatedObservationIds`。同样不推断隐藏推理。
|
||||
|
||||
## 与审批诊断的衔接
|
||||
|
||||
`seal-use approval-runs diagnose` 和 `... bridge` 的 `bridge[].next` 直接给出可执行的下一步:
|
||||
|
||||
```bash
|
||||
seal-use approval-runs diagnose --sn <单号> --corp <corpId> # bridge[].next → langfuse outline ...
|
||||
seal-use langfuse outline <traceId> --include-io-preview
|
||||
```
|
||||
|
||||
trace 缺失时 `resolution: "session-fallback"`,`next` 指向 `seal-use langfuse session hosecloud-<SN>`。
|
||||
|
||||
## 内置密钥失效:兜底与不崩溃契约
|
||||
|
||||
内置 key 有失效的可能(轮换、上游清理、某个发行版注入了坏值)。约定如下:
|
||||
|
||||
- **自检**:`seal-use langfuse check` 是内置健康检查,一秒发现失效——密钥无效 → `Langfuse API 401/403` + exit 11(附"检查注入的密钥"下一步提示);凭据未注入 → exit 11 并说明注入方式;网络不通、代理返回非 JSON、上游 5xx → exit 1。全部是结构化报错 + 稳定退出码,**不会崩溃、不会栈溢出、不会挂住**。
|
||||
- **影响面隔离**:`langfuse` 域是懒加载的,失效只影响这 10 个动词本身;其它命令、MCP 网关完全不受影响(`version`/`corps` 等照常)。
|
||||
- **cache-first 自动降级**:outline / search / observation / observations / url / attachment-flow / rule-flow 只读本地缓存——**即使 key 当场失效,已缓存过的 trace 依然能离线读取**;只有 `check` / `cache-refresh` / `session` 这类必须联网的动词会失败。
|
||||
- **处置**:不要在本地补 key(用户配置不参与本域);拿新版 `seal-use update`(轮换密钥后会随新发行版注入),期间改用 Langfuse Web 后台。
|
||||
|
||||
## 安全
|
||||
|
||||
trace 的 input/output/metadata 可能包含企业审批数据,按敏感数据对待:不贴大段 prompt/输出,不跨受众分享缓存 JSON。凭据内嵌于二进制、只读由 client 保证,详见 `SECURITY.md`。
|
||||
@@ -349,6 +349,32 @@ describe("corps get and search", () => {
|
||||
expect(data.source.tokenMasked).toContain("...");
|
||||
});
|
||||
|
||||
test("corps search ranks a Chinese name typo above industry-only matches", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
for (const [id, name] of [
|
||||
["corp-yutai", "钰泰半导体股份有限公司"],
|
||||
["corp-other", "华芯半导体股份有限公司"]
|
||||
]) {
|
||||
writeFileSync(join(enterprises, `${id}.json`), JSON.stringify({
|
||||
id,
|
||||
name,
|
||||
seal: { url: `https://${id}.seal.test` },
|
||||
source: { type: "hose", appKey: "fixture-key", appSecurity: "fixture-secret", corpId: id, staffId: "fixture-staff" },
|
||||
auth: { refreshTtl: 300 }
|
||||
}));
|
||||
}
|
||||
|
||||
for (const query of ["瑞泰半导体", "瑞泰 半导体"]) {
|
||||
const result = await runCli(["corps", "search", query]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).map((corp: { id: string }) => corp.id)).toEqual(["corp-yutai"]);
|
||||
}
|
||||
const strict = await runCli(["corps", "search", "瑞泰半导体", "--strict"]);
|
||||
expect(strict.exitCode).toBe(0);
|
||||
expect(JSON.parse(strict.stdout)).toEqual([]);
|
||||
});
|
||||
|
||||
test("corps search filters across name, staffId, environment, and keywords", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
|
||||
@@ -5,8 +5,11 @@ import {
|
||||
saveGlobalConfig,
|
||||
updateCorpConfig
|
||||
} from "../../../core/config/loader.js";
|
||||
import { filterCorpsFuzzy } from "../../../core/search/fuzzy.js";
|
||||
import { sortCorpsByUsageAndRecency } from "../../../core/stats/usage-tracker.js";
|
||||
import { filterCorpsFuzzy } from "../../../core/corp-search/rank.js";
|
||||
import {
|
||||
getRecentCorpUsageScores,
|
||||
sortCorpsByUsageAndRecency
|
||||
} from "../../../core/stats/usage-tracker.js";
|
||||
import type { CorpEnvironment } from "../../../core/config/types.js";
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { confirmationRequired, usageError } from "../../errors.js";
|
||||
@@ -48,7 +51,10 @@ export async function handleCorpOverview(
|
||||
filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter);
|
||||
}
|
||||
if (rawQuery) {
|
||||
filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict });
|
||||
// Equal-relevance results are ordered by recent usage so frequent corps
|
||||
// surface on ties without ever beating a better match.
|
||||
const usageScores = getRecentCorpUsageScores(filtered.map((item) => item.id));
|
||||
filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict }, usageScores);
|
||||
}
|
||||
|
||||
if (allCorps.length === 0) {
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { validationError } from "../../core/errors.js";
|
||||
import { booleanOption, numberOption, splitOption, stringOption } from "../parser.js";
|
||||
import { runLangfuseCapability } from "../helpers.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/**
|
||||
* `seal-use langfuse <verb>` — read-only Langfuse trace inspection.
|
||||
*
|
||||
* The trace/session id is a positional argument (flag fallback accepted), all
|
||||
* tuning knobs are flags. JSON goes to stdout via `runLangfuseCapability`
|
||||
* (size-capped: `--full` / `--output-file` escape hatches); unknown verbs throw
|
||||
* so the runner assigns exit 2.
|
||||
*/
|
||||
export async function handleLangfuseCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
const options = args.options;
|
||||
const out = outputOptions(options);
|
||||
const traceId = () => maybeName ?? stringOption(options["trace-id"]);
|
||||
const refreshIfMissing = () => booleanOption(options["refresh-if-missing"]);
|
||||
|
||||
if (action === "check") {
|
||||
await runLangfuseCapability("sealLangfuseConnectionCheck", {}, out);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "cache-refresh") {
|
||||
await runLangfuseCapability("sealLangfuseTraceCacheRefresh", { traceId: traceId() }, out);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "url") {
|
||||
await runLangfuseCapability("sealLangfuseTraceUrlGet", { traceId: traceId() }, out);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "outline") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseTraceOutlineGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
includeIoPreview: booleanOption(options["include-io-preview"]),
|
||||
full: booleanOption(options.full),
|
||||
maxPreviewChars: numberOption(options["max-preview-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "search") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseTraceQrepSearch",
|
||||
{
|
||||
traceId: traceId(),
|
||||
query: splitOption(options.query),
|
||||
sessionId: stringOption(options["session-id"]),
|
||||
fields: splitOption(options.fields),
|
||||
observationTypes: splitOption(options["observation-types"]),
|
||||
metadata: parseMetadataOption(stringOption(options.metadata)),
|
||||
maxResults: numberOption(options["max-results"]),
|
||||
contextChars: numberOption(options["context-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "observation") {
|
||||
const observationId = args.command[3] ?? stringOption(options["observation-id"]);
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseObservationIoGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
observationId,
|
||||
fields: splitOption(options.fields),
|
||||
maxChars: numberOption(options["max-chars"]),
|
||||
full: booleanOption(options.full),
|
||||
jsonPath: stringOption(options["json-path"]) ?? stringOption(options.path),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "session") {
|
||||
const sessionId = maybeName ?? stringOption(options["session-id"]);
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseSessionOutlineGet",
|
||||
{
|
||||
sessionId,
|
||||
traceLimit: numberOption(options["trace-limit"])
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "observations") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseObservationsFind",
|
||||
{
|
||||
traceId: traceId(),
|
||||
nameContains: stringOption(options["name-contains"]),
|
||||
type: stringOption(options.type),
|
||||
metadataKey: stringOption(options["metadata-key"]),
|
||||
hasInput: booleanOption(options["has-input"]),
|
||||
hasOutput: booleanOption(options["has-output"]),
|
||||
maxResults: numberOption(options["max-results"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "attachment-flow") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseAttachmentFlowGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
fileId: stringOption(options["file-id"]),
|
||||
fileName: stringOption(options["file-name"]),
|
||||
contentHints: splitOption(options["content-hints"]),
|
||||
contextChars: numberOption(options["context-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "rule-flow") {
|
||||
await runLangfuseCapability(
|
||||
"sealLangfuseTraceRuleFlowGet",
|
||||
{
|
||||
traceId: traceId(),
|
||||
rule: stringOption(options.rule),
|
||||
ruleHints: splitOption(options["rule-hints"]),
|
||||
contextChars: numberOption(options["context-chars"]),
|
||||
refreshIfMissing: refreshIfMissing()
|
||||
},
|
||||
out
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`
|
||||
);
|
||||
}
|
||||
|
||||
function parseMetadataOption(raw: string | undefined): Record<string, string | number | boolean> | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
throw validationError(`无效的 --metadata:需要 JSON 对象,例如 '{"key":"value"}'`);
|
||||
}
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
throw validationError("无效的 --metadata:需要 JSON 对象,例如 '{\"key\":\"value\"}'");
|
||||
}
|
||||
return parsed as Record<string, string | number | boolean>;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
|
||||
export async function handleReportCommand(
|
||||
action: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "monthly" || action === "month") {
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
|
||||
}
|
||||
await runCapability(
|
||||
"sealReportMonthlyGet",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
month,
|
||||
templatePath: stringOption(args.options.template),
|
||||
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "review") {
|
||||
const sub = args.command[2]; // set | list
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report review <set|list> --month <YYYY-MM> [--sn <SN> --verdict <v>] [--corp <corpId>]");
|
||||
}
|
||||
|
||||
if (sub === "list") {
|
||||
const reviews = loadReviews(corp.id, month);
|
||||
printJson({
|
||||
corpId: corp.id,
|
||||
month,
|
||||
file: reviewFilePath(corp.id, month),
|
||||
count: reviews.size,
|
||||
reviews: [...reviews.values()]
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === "set") {
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
|
||||
const verdict = stringOption(args.options.verdict);
|
||||
if (!sn || !verdict) {
|
||||
throw new Error(
|
||||
"Usage: seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
|
||||
);
|
||||
}
|
||||
const record = writeReview(corp.id, {
|
||||
sn,
|
||||
month,
|
||||
verdict,
|
||||
note: stringOption(args.options.note),
|
||||
reviewedBy: stringOption(args.options["reviewed-by"]) ?? stringOption(args.options.reviewedBy)
|
||||
});
|
||||
printJson({ corpId: corp.id, file: reviewFilePath(corp.id, month), record });
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
|
||||
}
|
||||
|
||||
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
|
||||
}
|
||||
+153
@@ -600,6 +600,48 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "report",
|
||||
title: "Monthly audit accuracy reports",
|
||||
description: "Generate the monthly AI audit accuracy report (Markdown) from a mutable template plus live tenant data.",
|
||||
commands: [
|
||||
{
|
||||
name: "monthly",
|
||||
aliases: ["month"],
|
||||
summary: "Fill the monthly report template with performance, risk, and approval-run data",
|
||||
usage: ["seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to report-templates/monthly.md" },
|
||||
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
],
|
||||
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
|
||||
},
|
||||
{
|
||||
name: "review set",
|
||||
summary: "Record one human adjudication (who was right: AI or human) for a document",
|
||||
usage: ["seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" },
|
||||
{ flag: "--sn <SN>", description: "Document SN to adjudicate (required)" },
|
||||
{ flag: "--verdict <v>", description: "ai_correct | human_correct | both_correct | both_wrong | undecided (required)" },
|
||||
{ flag: "--note <text>", description: "Optional adjudication note" },
|
||||
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
|
||||
],
|
||||
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
|
||||
},
|
||||
{
|
||||
name: "review list",
|
||||
summary: "List human adjudications recorded for a tenant+month",
|
||||
usage: ["seal-use report review list --month <YYYY-MM> [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" }
|
||||
],
|
||||
description: "Reads the local JSONL store and returns all adjudications keyed by SN."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "simulation",
|
||||
title: "Simulation testing engine",
|
||||
@@ -1128,6 +1170,111 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "langfuse",
|
||||
title: "Langfuse trace inspection (read-only)",
|
||||
description:
|
||||
"Inspect Langfuse traces/sessions with the built-in read-only credentials: cache once, then outline → search → observation IO. No tenant or user config required.",
|
||||
commands: [
|
||||
{
|
||||
name: "check",
|
||||
summary: "Check connectivity of the built-in Langfuse read-only credentials",
|
||||
usage: ["seal-use langfuse check"]
|
||||
},
|
||||
{
|
||||
name: "cache-refresh",
|
||||
summary: "Fetch one full trace into the local cache for offline inspection",
|
||||
usage: ["seal-use langfuse cache-refresh <traceId> [--trace-id <traceId>]"],
|
||||
options: [{ flag: "--trace-id <id>", description: "Trace id when not given as a positional" }]
|
||||
},
|
||||
{
|
||||
name: "outline",
|
||||
summary: "Read a compact observation tree with sizes, usage, cost, and optional IO previews",
|
||||
usage: ["seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]"],
|
||||
options: [
|
||||
{ flag: "--include-io-preview", description: "Include short input/output previews on the trace and observations" },
|
||||
{ flag: "--max-preview-chars <n>", description: "Preview length per field, 20-5000 (default 160)" },
|
||||
{ flag: "--full", description: "Return full IO instead of previews (large output)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "search",
|
||||
summary: "Ranked keyword search inside one cached trace (qrep)",
|
||||
usage: ["seal-use langfuse search <traceId> --query <term1,term2> [--fields input,output] [--max-results <n>]"],
|
||||
options: [
|
||||
{ flag: "--query <terms>", description: "Comma-separated terms; earliest best match wins per field" },
|
||||
{ flag: "--fields <fields>", description: "Comma-separated fields: name,input,output,metadata,userId,sessionId" },
|
||||
{ flag: "--observation-types <types>", description: "Comma-separated observation type filter (e.g. GENERATION,SPAN)" },
|
||||
{ flag: "--metadata <json>", description: "Exact metadata filter as a JSON object" },
|
||||
{ flag: "--max-results <n>", description: "Maximum ranked results, 1-30 (default 10)" },
|
||||
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 120)" },
|
||||
{ flag: "--session-id <id>", description: "Only match when the trace belongs to this session" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "observation",
|
||||
summary: "Read focused input/output/metadata of one observation",
|
||||
usage: ["seal-use langfuse observation <traceId> <observationId> [--fields input,output] [--max-chars <n>]"],
|
||||
options: [
|
||||
{ flag: "--fields <fields>", description: "Comma-separated fields to read: input,output,metadata (default input,output)" },
|
||||
{ flag: "--max-chars <n>", description: "Per-field character cap, 100-30000 (default 8000)" },
|
||||
{ flag: "--json-path <path>", description: "Read one nested value, e.g. items[0].name" },
|
||||
{ flag: "--full", description: "Raise the cap to 500000 chars (large output)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "session",
|
||||
summary: "Read a compact session outline with trace summaries",
|
||||
usage: ["seal-use langfuse session <sessionId> [--trace-limit <n>]"],
|
||||
options: [{ flag: "--trace-limit <n>", description: "Maximum traces to summarize, 1-200 (default 50)" }]
|
||||
},
|
||||
{
|
||||
name: "observations",
|
||||
summary: "Filter cached observations by name/type/metadata without loading IO",
|
||||
usage: ["seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>]"],
|
||||
options: [
|
||||
{ flag: "--name-contains <text>", description: "Substring match on observation name" },
|
||||
{ flag: "--type <type>", description: "Exact observation type filter" },
|
||||
{ flag: "--metadata-key <key>", description: "Only observations whose metadata has this key" },
|
||||
{ flag: "--has-input", description: "Only observations with non-empty input" },
|
||||
{ flag: "--has-output", description: "Only observations with non-empty output" },
|
||||
{ flag: "--max-results <n>", description: "Maximum summaries, 1-200 (default 50)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
summary: "Build the Langfuse UI deep link for one trace",
|
||||
usage: ["seal-use langfuse url <traceId>"]
|
||||
},
|
||||
{
|
||||
name: "attachment-flow",
|
||||
summary: "Trace text evidence of a file id/name through attachment and review stages",
|
||||
usage: ["seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>]"],
|
||||
options: [
|
||||
{ flag: "--file-id <id>", description: "File id to look for (at least one hint required)" },
|
||||
{ flag: "--file-name <name>", description: "File name to look for (at least one hint required)" },
|
||||
{ flag: "--content-hints <hints>", description: "Comma-separated extra content hints" },
|
||||
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 120)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "rule-flow",
|
||||
summary: "Trace text evidence of one rule through matching, parsing, and review stages",
|
||||
usage: ["seal-use langfuse rule-flow <traceId> --rule <规则内容>"],
|
||||
options: [
|
||||
{ flag: "--rule <text>", description: "Rule text to trace (required)" },
|
||||
{ flag: "--rule-hints <hints>", description: "Comma-separated extra rule hints" },
|
||||
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 300)" },
|
||||
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
area: "mcp",
|
||||
title: "Model Context Protocol (MCP) server",
|
||||
@@ -1276,6 +1423,12 @@ export function renderHelp(target: string[] = []): string {
|
||||
const matchedCommand = findCommandInArea(areaEntry, actionPath, rest);
|
||||
|
||||
if (!matchedCommand) {
|
||||
// 前缀命令(如 `report review` 覆盖 `review set`/`review list`):列出该组子命令而非报错
|
||||
const groupPrefix = `${actionPath} `;
|
||||
const subcommands = areaEntry.commands.filter((cmd) => cmd.name?.startsWith(groupPrefix));
|
||||
if (subcommands.length > 0) {
|
||||
return renderAreaHelp({ ...areaEntry, commands: subcommands });
|
||||
}
|
||||
throw usageError(`Unknown ${areaEntry.area} command: ${rest.join(" ")}. Run 'seal-use ${areaEntry.area} --help' for available commands.`);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@ import { resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { recordCorpUsage } from "../core/stats/usage-tracker.js";
|
||||
import { createSealClient } from "../core/http/factory.js";
|
||||
import { sealCapabilities, parseCapabilityParams, type SealCapability } from "../domains/seal/capabilities.js";
|
||||
import { createLangfuseService, findLangfuseCapability } from "../domains/langfuse/capabilities.js";
|
||||
import type { LangfuseService } from "../domains/langfuse/service.js";
|
||||
import { validationError } from "../core/errors.js";
|
||||
import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
@@ -67,3 +70,34 @@ export async function runCapabilityResult(
|
||||
const handler = tool.handler as SealCapability["handler"];
|
||||
return handler(client, compactParams as never, { corp });
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches one read-only Langfuse capability and prints its JSON payload.
|
||||
*
|
||||
* Same contract as `runCapability` minus the tenant: no Seal client, no
|
||||
* corp — Langfuse access relies solely on the compile-time injected key pair.
|
||||
* Params are gated by the capability's Zod schema (missing/invalid → exit 13)
|
||||
* before the handler sees them.
|
||||
*/
|
||||
export async function runLangfuseCapability(
|
||||
name: string,
|
||||
params: Record<string, unknown>,
|
||||
options: OutputOptions = {}
|
||||
) {
|
||||
const tool = findLangfuseCapability(name);
|
||||
if (!tool) throw new Error(`Unknown Langfuse tool: ${name}`);
|
||||
|
||||
const compactParams = Object.fromEntries(
|
||||
Object.entries(params).filter(([, value]) => value !== undefined)
|
||||
);
|
||||
const parsed = tool.parameters.safeParse(compactParams);
|
||||
if (!parsed.success) {
|
||||
const detail = parsed.error.issues
|
||||
.map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`)
|
||||
.join("; ");
|
||||
throw validationError(`Invalid parameters for ${tool.name}: ${detail}`);
|
||||
}
|
||||
|
||||
const handler = tool.handler as (params: never, service: LangfuseService) => Promise<unknown>;
|
||||
printJson(await handler(compactParams as never, createLangfuseService()), options);
|
||||
}
|
||||
+36
-23
@@ -26,11 +26,11 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
|
||||
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
||||
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
||||
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "help",
|
||||
"hose", "hose-sso", "hoseSso", "include-deleted", "include-simulation", "include-unchanged",
|
||||
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
|
||||
"hose", "hose-sso", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
|
||||
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "recode", "refresh", "reveal", "rotate-secret", "rotateSecret",
|
||||
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-flow",
|
||||
@@ -41,38 +41,45 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
export const VALUE_FLAGS = new Set([
|
||||
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
||||
"code", "concurrency", "content", "content-file", "content-type", "contentFile",
|
||||
"contentType", "contextLines", "corp", "corp-id", "corpId", "date",
|
||||
"code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "date",
|
||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
||||
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
|
||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||
"environment", "expire", "expiresIn", "fields", "file", "flow-concurrency",
|
||||
"environment", "expire", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
|
||||
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
|
||||
"from-link", "host", "humanResult", "id", "input", "integration",
|
||||
"json", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
||||
"n", "name", "note", "o", "offset", "out",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "name-contains", "note", "observation-id", "observation-types", "o", "offset", "out",
|
||||
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
||||
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"report-id",
|
||||
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
|
||||
"reuseWindow", "rule", "rule-id", "ruleId", "ruleVersion", "runtime-id",
|
||||
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id",
|
||||
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
|
||||
"sealUrl", "search", "secret", "selector", "sign-key", "signKey",
|
||||
"sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey",
|
||||
"simulationBatchId", "since", "sn", "sn-prefix", "sn-suffix", "snPrefix",
|
||||
"snSuffix", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||
"sourceDocumentSN", "sourceSystem", "staff-id", "staff-name", "staff-phone", "staffId",
|
||||
"staffName", "staffPhone", "start", "start-date", "start-time", "startDate",
|
||||
"startTime", "state", "status", "strictness", "tag", "tag-id",
|
||||
"tagId", "tags", "target", "target-corp", "targetCorp", "task-mode",
|
||||
"template",
|
||||
"taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth",
|
||||
"timeout", "timezone", "title", "to", "token", "tokenId",
|
||||
"trace-id", "trace-limit",
|
||||
"type", "until", "url", "userId", "version-name", "versionName",
|
||||
"verdict",
|
||||
"webhook", "workflow-type-id", "workflowTypeId"
|
||||
]);
|
||||
|
||||
@@ -83,7 +90,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
||||
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
|
||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
||||
"content-file", "content-type", "contentFile", "contentType", "contextLines", "corp",
|
||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
|
||||
"default", "departmentId", "dept", "desc", "description", "description-file",
|
||||
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
|
||||
@@ -92,27 +99,31 @@ export const KNOWN_FLAGS = new Set([
|
||||
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
|
||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||
"environment", "exclude-deleted", "expire", "expiresIn", "f", "fail-on-flips",
|
||||
"fields", "file", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
|
||||
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
|
||||
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
||||
"full", "h", "help", "hose", "hose-sso", "hoseSso",
|
||||
"host", "humanResult", "id", "include-deleted", "include-simulation", "include-unchanged",
|
||||
"full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso",
|
||||
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
||||
"key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
|
||||
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
||||
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
|
||||
"note", "o", "offset", "out", "out-dir", "outDir",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait",
|
||||
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir",
|
||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
||||
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
|
||||
"query", "quiet", "r", "recode", "record-id", "record-ids",
|
||||
"recordId", "recordIds", "refresh", "reject-node", "rejectNode", "repo",
|
||||
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "repo",
|
||||
"report-id",
|
||||
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
||||
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
|
||||
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
||||
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
|
||||
"selector", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
|
||||
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
||||
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||
@@ -120,10 +131,12 @@ export const KNOWN_FLAGS = new Set([
|
||||
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
|
||||
"startDate", "startTime", "state", "status", "strict", "strictness",
|
||||
"summary", "tag", "tag-id", "tagId", "tags", "target",
|
||||
"template",
|
||||
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
|
||||
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
|
||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "type",
|
||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
||||
"until", "url", "userId", "v", "version", "version-name",
|
||||
"verdict",
|
||||
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
@@ -61,6 +61,10 @@ describe("CLI read-only classification", () => {
|
||||
["deploy", "hosecloud", "status", "--corp", "corp-a"],
|
||||
["preferences", "get"],
|
||||
["doctor", "tenant", "--corp", "corp-a"],
|
||||
["langfuse", "check"],
|
||||
["langfuse", "outline", "trace-1", "--include-io-preview"],
|
||||
["langfuse", "search", "trace-1", "--query", "发票"],
|
||||
["langfuse", "observation", "trace-1", "obs-1"],
|
||||
["version"],
|
||||
["mcp-config"]
|
||||
]) {
|
||||
@@ -97,6 +101,7 @@ describe("CLI read-only classification", () => {
|
||||
["auth", "keys"],
|
||||
["analytics", "analyze", "record-1"],
|
||||
["tool", "sealApprovalRuleCreate", "--json", "{}"],
|
||||
["langfuse", "unknown-verb"],
|
||||
["totally-unknown", "list"],
|
||||
[]
|
||||
]) {
|
||||
|
||||
@@ -78,9 +78,23 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
|
||||
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
|
||||
analytics: ["insight", "risks", "performance", "export"],
|
||||
report: ["monthly", "review list"],
|
||||
source: ["config"],
|
||||
skill: ["dump", "status"],
|
||||
doctor: ["", "guide", "paths", "tenant", "auth"],
|
||||
// The whole Langfuse area is read-only: the embedded client issues GET only.
|
||||
langfuse: [
|
||||
"check",
|
||||
"cache-refresh",
|
||||
"outline",
|
||||
"search",
|
||||
"observation",
|
||||
"session",
|
||||
"url",
|
||||
"observations",
|
||||
"attachment-flow",
|
||||
"rule-flow"
|
||||
],
|
||||
// Bare form only; the optional trailing `<corpId>` selector is handled by
|
||||
// SELECTOR_POSITIONAL_AREAS below, since a bare entry matches no tokens.
|
||||
probe: [""]
|
||||
|
||||
@@ -53,6 +53,7 @@ export const KNOWN_AREAS = new Set([
|
||||
"rules",
|
||||
"approval-runs",
|
||||
"analytics",
|
||||
"report",
|
||||
"simulation",
|
||||
"deploy",
|
||||
"preference",
|
||||
@@ -63,6 +64,7 @@ export const KNOWN_AREAS = new Set([
|
||||
"skill",
|
||||
"probe",
|
||||
"doctor",
|
||||
"langfuse",
|
||||
"changelog",
|
||||
"test"
|
||||
]);
|
||||
@@ -222,6 +224,14 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Langfuse trace inspection needs no tenant: it authenticates with the
|
||||
// compile-time injected read-only key pair, so it dispatches before corp
|
||||
// selection (like probe/doctor) and never touches a Seal client.
|
||||
if (area === "langfuse") {
|
||||
await (await import("./commands/langfuse.js")).handleLangfuseCommand(action, maybeName, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "test") {
|
||||
await (await import("./commands/test.js")).handleTestCommand(action, maybeName, args);
|
||||
return;
|
||||
@@ -386,6 +396,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "report") {
|
||||
await (await import("./commands/report.js")).handleReportCommand(action, client, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "simulation") {
|
||||
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { fuzzyMatchString } from "./engine.js";
|
||||
import { isSubsequence } from "./distance.js";
|
||||
import { matchTokenizedQuery } from "./tokens.js";
|
||||
import type { FuzzyMatchOptions, MatchReason, MatchScoreResult } from "./types.js";
|
||||
|
||||
interface CorpField {
|
||||
text: string | undefined;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
function corpSearchFields(corp: CorpConfig): CorpField[] {
|
||||
return [
|
||||
{ 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 }
|
||||
];
|
||||
}
|
||||
|
||||
interface WeightedMatch {
|
||||
score: number;
|
||||
reason: MatchReason;
|
||||
}
|
||||
|
||||
/** Keeps the higher-scoring candidate; ties stay with the earlier match. */
|
||||
function strongerMatch(current: WeightedMatch, candidate: WeightedMatch): WeightedMatch {
|
||||
return candidate.score > current.score ? candidate : current;
|
||||
}
|
||||
|
||||
function matchCorpFields(
|
||||
fields: CorpField[],
|
||||
query: string,
|
||||
options: FuzzyMatchOptions
|
||||
): WeightedMatch {
|
||||
let best: WeightedMatch = { score: 0, reason: "none" };
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = fuzzyMatchString(query, field.text, options);
|
||||
if (res.matched) {
|
||||
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* When a long Chinese query contains a compact enterprise name in order (for
|
||||
* example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
|
||||
* retain that candidate as a lower-confidence abbreviation match. This is
|
||||
* deliberately below exact/substring/pinyin matches and disabled in strict mode.
|
||||
*/
|
||||
function matchCorpAbbreviation(fields: CorpField[], query: string): WeightedMatch {
|
||||
let best: WeightedMatch = { score: 0, reason: "none" };
|
||||
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
if (queryChinese.length < 3) return best;
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
const prefix = targetChinese.slice(0, 2);
|
||||
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
|
||||
|
||||
best = strongerMatch(best, { score: 0.74 * field.weight, reason: "abbreviation" });
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function matchCorpTokens(fields: CorpField[], query: string): WeightedMatch {
|
||||
let best: WeightedMatch = { score: 0, reason: "none" };
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = matchTokenizedQuery(query, field.text);
|
||||
if (res.matched) {
|
||||
best = strongerMatch(best, { score: res.score * field.weight, reason: res.reason });
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = corpSearchFields(corp);
|
||||
|
||||
let best = matchCorpFields(fields, query, options);
|
||||
if (!options.strict) {
|
||||
best = strongerMatch(best, matchCorpAbbreviation(fields, query));
|
||||
best = strongerMatch(best, matchCorpTokens(fields, query));
|
||||
}
|
||||
|
||||
return {
|
||||
matched: best.score > 0,
|
||||
score: best.score,
|
||||
reason: best.reason
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { levenshteinDistance, minSubstringLevenshtein } from "./distance.js";
|
||||
|
||||
describe("distance primitives", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* 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: number[] = Array.from({ length: n + 1 }, () => 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { fuzzyMatchString } from "./engine.js";
|
||||
|
||||
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("prefix substring keeps the 0.95 band", () => {
|
||||
const res = fuzzyMatchString("谢子", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
expect(res.score).toBe(0.95);
|
||||
});
|
||||
|
||||
test("mid-string substring ranks below prefix hits", () => {
|
||||
const res = fuzzyMatchString("子豪", "谢子豪");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
expect(res.score).toBe(0.92);
|
||||
});
|
||||
|
||||
test("normalizes full-width characters (NFKC)", () => {
|
||||
const res = fuzzyMatchString("GB", "GB科技");
|
||||
expect(res.matched).toBe(true);
|
||||
expect(res.reason).toBe("substring");
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { pinyin, match as pinyinMatch } from "pinyin-pro";
|
||||
import { isSubsequence, minSubstringLevenshtein } from "./distance.js";
|
||||
import { normalizeFuzzyPinyin } from "./pinyin.js";
|
||||
import type { FuzzyMatchOptions, MatchScoreResult } from "./types.js";
|
||||
|
||||
/** Normalizes NFKC (full-width -> half-width), trims, and lowercases. */
|
||||
function normalizeText(value: string): string {
|
||||
return value.normalize("NFKC").trim().toLowerCase();
|
||||
}
|
||||
|
||||
function noMatch(): MatchScoreResult {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
interface PinyinPair {
|
||||
query: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Precomputed per (query, target) pair so every strategy can share the work.
|
||||
*/
|
||||
interface MatchContext {
|
||||
targetHasChinese: boolean;
|
||||
queryHasChinese: boolean;
|
||||
/** Fuzzy pinyin of both sides, or null when neither side contains Chinese. */
|
||||
fuzzyPinyin: PinyinPair | null;
|
||||
maxDistance: number;
|
||||
}
|
||||
|
||||
function buildMatchContext(
|
||||
normQuery: string,
|
||||
normTarget: string,
|
||||
options: FuzzyMatchOptions
|
||||
): MatchContext {
|
||||
const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget);
|
||||
const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery);
|
||||
return {
|
||||
targetHasChinese,
|
||||
queryHasChinese,
|
||||
fuzzyPinyin:
|
||||
targetHasChinese || queryHasChinese
|
||||
? { target: normalizeFuzzyPinyin(normTarget), query: normalizeFuzzyPinyin(normQuery) }
|
||||
: null,
|
||||
// Allowed edit 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)
|
||||
maxDistance: options.maxDistance ?? (normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2)
|
||||
};
|
||||
}
|
||||
|
||||
/** Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产"). */
|
||||
function matchByInitials(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
|
||||
if (!ctx.targetHasChinese || query.length < 2) return null;
|
||||
const targetInitials = pinyin(target, { pattern: "first", toneType: "none", type: "array" })
|
||||
.join("")
|
||||
.toLowerCase();
|
||||
if (targetInitials.includes(query)) {
|
||||
return { matched: true, score: 0.9, reason: "initials" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets). */
|
||||
function matchByPinyin(query: string, target: string, ctx: MatchContext): MatchScoreResult | null {
|
||||
if (!ctx.targetHasChinese) return null;
|
||||
try {
|
||||
const pm = pinyinMatch(target, query, { precision: "start" });
|
||||
if (pm && pm.length > 0) {
|
||||
return { matched: true, score: 0.88, reason: "pinyin" };
|
||||
}
|
||||
} catch {
|
||||
// ignore match errors if non-standard regex chars
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音). */
|
||||
function matchByFuzzyPinyin(ctx: MatchContext): MatchScoreResult | null {
|
||||
const pair = ctx.fuzzyPinyin;
|
||||
if (!pair || pair.query.length < 2) return null;
|
||||
if (pair.target.includes(pair.query)) {
|
||||
return { matched: true, score: 0.85, reason: "fuzzy_pinyin" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Missing letter / Typo tolerance (Levenshtein Distance), on raw strings then on fuzzy pinyin. */
|
||||
function matchByEditDistance(
|
||||
query: string,
|
||||
target: string,
|
||||
ctx: MatchContext
|
||||
): MatchScoreResult | null {
|
||||
if (ctx.maxDistance <= 0) return null;
|
||||
|
||||
// Check raw string distance
|
||||
const rawDist = minSubstringLevenshtein(query, target);
|
||||
if (rawDist <= ctx.maxDistance) {
|
||||
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)
|
||||
const pair = ctx.fuzzyPinyin;
|
||||
if (pair && pair.query.length >= 3 && pair.target.length >= 3) {
|
||||
const pinyinDist = minSubstringLevenshtein(pair.query, pair.target);
|
||||
if (pinyinDist <= ctx.maxDistance) {
|
||||
return { matched: true, score: Math.max(0.6, 0.78 - pinyinDist * 0.1), reason: "levenshtein" };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Subsequence match (loose character order, min query length 3). */
|
||||
function matchBySubsequence(
|
||||
query: string,
|
||||
target: string,
|
||||
ctx: MatchContext
|
||||
): MatchScoreResult | null {
|
||||
if (query.length < 3) return null;
|
||||
if (isSubsequence(query, target)) {
|
||||
return { matched: true, score: 0.65, reason: "subsequence" };
|
||||
}
|
||||
const pair = ctx.fuzzyPinyin;
|
||||
if (pair && isSubsequence(pair.query, pair.target)) {
|
||||
return { matched: true, score: 0.65, reason: "subsequence" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Core fuzzy string match engine:
|
||||
* Evaluates match across exact, substring (prefix hits outrank mid-string hits),
|
||||
* initials, pinyin, homophone/fuzzy pinyin, sliding-window edit distance
|
||||
* (missing/typo tolerance), and character subsequence.
|
||||
* Strategies run in priority order; the first hit wins.
|
||||
*/
|
||||
export function fuzzyMatchString(
|
||||
query: string,
|
||||
target: string,
|
||||
options: FuzzyMatchOptions = {}
|
||||
): MatchScoreResult {
|
||||
const normQuery = normalizeText(query);
|
||||
const normTarget = normalizeText(target);
|
||||
|
||||
if (!normQuery || !normTarget) {
|
||||
return noMatch();
|
||||
}
|
||||
|
||||
// Exact match
|
||||
if (normTarget === normQuery) {
|
||||
return { matched: true, score: 1.0, reason: "exact" };
|
||||
}
|
||||
|
||||
// Substring match: a query that opens the target is stronger evidence than a
|
||||
// mid-string hit, so it keeps the historical 0.95 band while mid-string drops to 0.92.
|
||||
if (normTarget.startsWith(normQuery)) {
|
||||
return { matched: true, score: 0.95, reason: "substring" };
|
||||
}
|
||||
if (normTarget.includes(normQuery)) {
|
||||
return { matched: true, score: 0.92, reason: "substring" };
|
||||
}
|
||||
|
||||
// If strict mode is requested, only exact or substring matches are accepted.
|
||||
if (options.strict) {
|
||||
return noMatch();
|
||||
}
|
||||
|
||||
const context = buildMatchContext(normQuery, normTarget, options);
|
||||
return (
|
||||
matchByInitials(normQuery, normTarget, context) ??
|
||||
matchByPinyin(normQuery, normTarget, context) ??
|
||||
matchByFuzzyPinyin(context) ??
|
||||
matchByEditDistance(normQuery, normTarget, context) ??
|
||||
matchBySubsequence(normQuery, normTarget, context) ??
|
||||
noMatch()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import type { FuzzyMatchOptions } from "./types.js";
|
||||
import { filterCorpsFuzzy } from "./rank.js";
|
||||
|
||||
// Golden evaluation set for corp search: real-shaped (query -> expected result)
|
||||
// pairs collected from usage regressions and CLI tests. Every tuning change to
|
||||
// scores/thresholds must keep this green; grow it with every real-world
|
||||
// mis-hit or miss instead of re-tuning against a single complaint.
|
||||
|
||||
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: "seal",
|
||||
token: `${id}-token`,
|
||||
sealUrl: `https://${id}.seal.test`,
|
||||
expiresIn: 3600,
|
||||
staffId: `staff-${id}`
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
const HOSE_SOURCE = {
|
||||
type: "hose",
|
||||
corpId: "ID01VAdCnJEdFd",
|
||||
staffId: "staff-channel",
|
||||
domain: "https://app.ekuaibao.com"
|
||||
} as any;
|
||||
|
||||
const CORPUS: CorpConfig[] = [
|
||||
makeCorp("corp-xiezihao", "谢子豪"),
|
||||
makeCorp("corp-qudao", "渠道AI演示环境", { source: HOSE_SOURCE }),
|
||||
makeCorp("corp-acme", "Acme Global", { environment: "test" }),
|
||||
makeCorp("corp-yuance", "园测信息科技股份有限公司"),
|
||||
makeCorp("corp-yutai", "钰泰半导体股份有限公司"),
|
||||
makeCorp("corp-huaxin", "华芯半导体股份有限公司"),
|
||||
makeCorp("corp-nanjing", "南京测绘"),
|
||||
makeCorp("corp-pingan", "中国平安人寿保险股份有限公司"),
|
||||
makeCorp("corp-gb", "GB国际(集团)有限公司"),
|
||||
makeCorp("corp-shengchan", "生产正式企业", {
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "shengchan-token",
|
||||
sealUrl: "https://shengchan.seal.test",
|
||||
expiresIn: 3600,
|
||||
staffId: "admin-zhangsan"
|
||||
} as any
|
||||
})
|
||||
];
|
||||
|
||||
interface GoldenCase {
|
||||
query: string;
|
||||
/** The id that must rank first. */
|
||||
top?: string;
|
||||
/** Ids that must appear somewhere in the results. */
|
||||
includes?: string[];
|
||||
/** Ids that must not appear (noise suppression checks). */
|
||||
excludes?: string[];
|
||||
/** No corp may match at all. */
|
||||
empty?: boolean;
|
||||
options?: FuzzyMatchOptions;
|
||||
}
|
||||
|
||||
const GOLDEN: GoldenCase[] = [
|
||||
// Exact & substring bands
|
||||
{ query: "园测信息科技股份有限公司", top: "corp-yuance" },
|
||||
{ query: "园测信息", top: "corp-yuance" },
|
||||
{ query: "信息科技", top: "corp-yuance" },
|
||||
{ query: "平安", top: "corp-pingan" },
|
||||
{ query: "渠道", top: "corp-qudao" },
|
||||
// Initials / pinyin / homophones
|
||||
{ query: "xzh", top: "corp-xiezihao" },
|
||||
{ query: "xiezihao", top: "corp-xiezihao" },
|
||||
{ query: "鞋子豪", top: "corp-xiezihao" },
|
||||
{ query: "谢自豪", top: "corp-xiezihao" },
|
||||
{ query: "qudao", top: "corp-qudao" },
|
||||
{ query: "sc", top: "corp-shengchan" },
|
||||
{ query: "盛产", top: "corp-shengchan" },
|
||||
{ query: "yuan-ce", top: "corp-yuance" },
|
||||
// Typo tolerance
|
||||
{ query: "xieziha", top: "corp-xiezihao" },
|
||||
{ query: "zhangsa", top: "corp-shengchan" },
|
||||
// Tokenized Chinese queries with a contextual typo
|
||||
{ query: "瑞泰半导体", top: "corp-yutai", excludes: ["corp-huaxin"] },
|
||||
{ query: "瑞泰 半导体", top: "corp-yutai", excludes: ["corp-huaxin"] },
|
||||
{ query: "半导体 瑞泰", top: "corp-yutai", excludes: ["corp-huaxin"] },
|
||||
{ query: "钰泰 半导体", top: "corp-yutai" },
|
||||
// Compact name inside a long query (abbreviation + weak suppression)
|
||||
{ query: "苏州园区测绘", top: "corp-yuance", excludes: ["corp-nanjing"] },
|
||||
// Identifier fields
|
||||
{ query: "staff-channel", top: "corp-qudao" },
|
||||
{ query: "ID01VAdCnJEdFd", top: "corp-qudao" },
|
||||
{ query: "test", top: "corp-acme" },
|
||||
// Full-width / half-width (NFKC)
|
||||
{ query: "GB", top: "corp-gb" },
|
||||
{ query: "gb", top: "corp-gb" },
|
||||
// Strict mode
|
||||
{ query: "钰泰半导体", options: { strict: true }, top: "corp-yutai" },
|
||||
{ query: "瑞泰半导体", options: { strict: true }, empty: true },
|
||||
{ query: "苏州园区测绘", options: { strict: true }, empty: true },
|
||||
// Unrelated queries match nothing
|
||||
{ query: "alibaba", empty: true },
|
||||
{ query: "腾讯", empty: true }
|
||||
];
|
||||
|
||||
describe("corp search golden set", () => {
|
||||
for (const golden of GOLDEN) {
|
||||
const label = `golden: ${golden.query}${golden.options?.strict ? " --strict" : ""}`;
|
||||
test(label, () => {
|
||||
const results = filterCorpsFuzzy(CORPUS, golden.query, golden.options ?? {});
|
||||
const ids = results.map((corp) => corp.id);
|
||||
|
||||
if (golden.empty) {
|
||||
expect(ids).toEqual([]);
|
||||
}
|
||||
if (golden.top) {
|
||||
expect(ids[0]).toBe(golden.top);
|
||||
}
|
||||
for (const id of golden.includes ?? []) {
|
||||
expect(ids).toContain(id);
|
||||
}
|
||||
for (const id of golden.excludes ?? []) {
|
||||
expect(ids).not.toContain(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { normalizeFuzzyPinyin } from "./pinyin.js";
|
||||
|
||||
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("渠到"));
|
||||
});
|
||||
|
||||
test("memoizes repeated inputs", () => {
|
||||
expect(normalizeFuzzyPinyin("谢子豪")).toBe(normalizeFuzzyPinyin("谢子豪"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { pinyin } from "pinyin-pro";
|
||||
|
||||
// Query and target strings repeat across corps and fields within one search run
|
||||
// (one query × N corps × 13 fields), so memoize by raw input. Bounded: queries
|
||||
// per process are few, but clear instead of growing without limit.
|
||||
const fuzzyPinyinCache = new Map<string, string>();
|
||||
const PINYIN_CACHE_LIMIT = 128;
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
const cached = fuzzyPinyinCache.get(str);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
let normalized = "";
|
||||
if (str) {
|
||||
const pyTokens = pinyin(str, { toneType: "none", type: "array" });
|
||||
normalized = 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("");
|
||||
}
|
||||
|
||||
if (fuzzyPinyinCache.size >= PINYIN_CACHE_LIMIT) fuzzyPinyinCache.clear();
|
||||
fuzzyPinyinCache.set(str, normalized);
|
||||
return normalized;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { filterCorpsFuzzy } from "./rank.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: "seal",
|
||||
token: `${id}-token`,
|
||||
sealUrl: `https://${id}.seal.test`,
|
||||
expiresIn: 3600,
|
||||
staffId: `staff-${id}`
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
test("finds a compact enterprise name inside a longer Chinese query", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const unrelated = makeCorp("corp-other", "南京测绘");
|
||||
const results = filterCorpsFuzzy([unrelated, compactName], "苏州园区测绘");
|
||||
|
||||
expect(results[0]!.id).toBe("corp-yuan-ce");
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("keeps strict search limited to exact substrings", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const results = filterCorpsFuzzy([compactName], "苏州园区测绘", { strict: true });
|
||||
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
|
||||
test("matches Chinese name and industry words despite a contextual name typo", () => {
|
||||
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
|
||||
const sameIndustry = makeCorp("corp-other", "华芯半导体股份有限公司");
|
||||
for (const query of ["瑞泰半导体", "瑞泰 半导体", "半导体 瑞泰", "钰泰 半导体"]) {
|
||||
expect(filterCorpsFuzzy([sameIndustry, target], query).map((corp) => corp.id))
|
||||
.toEqual([target.id]);
|
||||
}
|
||||
});
|
||||
|
||||
test("requires another matching word before tolerating a typo in a short Chinese name", () => {
|
||||
const target = makeCorp("corp-yutai", "钰泰半导体股份有限公司");
|
||||
expect(filterCorpsFuzzy([target], "瑞泰")).toEqual([]);
|
||||
expect(filterCorpsFuzzy([target], "瑞泰 半导体", { strict: true })).toEqual([]);
|
||||
expect(filterCorpsFuzzy([target], "钰泰半导体", { strict: true })).toEqual([target]);
|
||||
});
|
||||
|
||||
test("breaks relevance ties by recent usage", () => {
|
||||
const a = makeCorp("corp-a", "匹配企业甲");
|
||||
const b = makeCorp("corp-b", "匹配企业乙");
|
||||
// Both names prefix-match at the same score; higher usage wins even against
|
||||
// input order and zh-CN name collation (甲 < 乙 alphabetically).
|
||||
const usage = new Map([["corp-a", 1], ["corp-b", 5]]);
|
||||
const results = filterCorpsFuzzy([a, b], "匹配企业", {}, usage);
|
||||
expect(results.map((corp) => corp.id)).toEqual(["corp-b", "corp-a"]);
|
||||
});
|
||||
|
||||
test("usage never outranks a better match", () => {
|
||||
const weak = makeCorp("corp-weak", "匹配企业甲");
|
||||
const strong = makeCorp("corp-strong", "匹配企业");
|
||||
const usage = new Map([["corp-weak", 99]]);
|
||||
const results = filterCorpsFuzzy([weak, strong], "匹配企业", {}, usage);
|
||||
expect(results[0]!.id).toBe("corp-strong");
|
||||
});
|
||||
|
||||
test("falls back to name and id order when usage is absent", () => {
|
||||
const second = makeCorp("corp-b", "匹配企业乙");
|
||||
const first = makeCorp("corp-a", "匹配企业甲");
|
||||
const results = filterCorpsFuzzy([second, first], "匹配企业");
|
||||
expect(results.map((corp) => corp.id)).toEqual(["corp-a", "corp-b"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { matchCorp } from "./corp.js";
|
||||
import type { FuzzyMatchOptions } from "./types.js";
|
||||
|
||||
/**
|
||||
* Once a strong candidate exists, suppress weak token-only suggestions. This
|
||||
* keeps a query such as "苏州园区测绘" focused on the compact-name match
|
||||
* instead of also returning every enterprise that merely contains "测绘".
|
||||
*/
|
||||
function suppressWeakMatches(scored: Array<{ corp: CorpConfig; score: number }>): CorpConfig[] {
|
||||
const strongMatches = scored.filter((item) => item.score >= 0.8);
|
||||
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* `usageScores` (optional, from `getRecentCorpUsageScores`) only breaks ties among
|
||||
* equally-relevant results — recent usage can lift a corp within a score band but
|
||||
* never above a better match.
|
||||
*/
|
||||
export function filterCorpsFuzzy(
|
||||
corps: CorpConfig[],
|
||||
query: string,
|
||||
options: FuzzyMatchOptions = {},
|
||||
usageScores?: ReadonlyMap<string, number>
|
||||
): 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); relevance ties
|
||||
// fall back to recent usage, then name, then id for stable ordering.
|
||||
scored.sort((a, b) => {
|
||||
if (a.score !== b.score) return b.score - a.score;
|
||||
const usageA = usageScores?.get(a.corp.id) ?? 0;
|
||||
const usageB = usageScores?.get(b.corp.id) ?? 0;
|
||||
if (usageA !== usageB) return usageB - usageA;
|
||||
const byName = (a.corp.name ?? a.corp.id).localeCompare(b.corp.name ?? b.corp.id, "zh-CN");
|
||||
if (byName !== 0) return byName;
|
||||
return a.corp.id.localeCompare(b.corp.id);
|
||||
});
|
||||
|
||||
return suppressWeakMatches(scored);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Chinese query segmentation: word-level via Intl.Segmenter (with adjacent
|
||||
// single-character run merging for uncommon enterprise names) and term-level
|
||||
// via overlapping two-character windows.
|
||||
|
||||
let wordSegmenter: Intl.Segmenter | undefined;
|
||||
|
||||
// The same query string is segmented once per corp × field without memoization;
|
||||
// cache by raw input (bounded like the pinyin cache).
|
||||
const wordsCache = new Map<string, string[]>();
|
||||
const termsCache = new Map<string, string[]>();
|
||||
const SEGMENT_CACHE_LIMIT = 64;
|
||||
|
||||
function cached(key: string, cache: Map<string, string[]>, compute: () => string[]): string[] {
|
||||
const hit = cache.get(key);
|
||||
if (hit !== undefined) return hit;
|
||||
const value = compute();
|
||||
if (cache.size >= SEGMENT_CACHE_LIMIT) cache.clear();
|
||||
cache.set(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function searchTerms(value: string): string[] {
|
||||
return cached(value, termsCache, () => {
|
||||
const normalized = value.normalize("NFKC").trim().toLowerCase();
|
||||
const chunks = normalized.match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? [];
|
||||
return chunks.flatMap((chunk) => {
|
||||
if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk];
|
||||
if (chunk.length <= 2) return [chunk];
|
||||
|
||||
const terms: string[] = [];
|
||||
for (let index = 0; index < chunk.length - 1; index += 1) {
|
||||
terms.push(chunk.slice(index, index + 2));
|
||||
}
|
||||
return terms;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function searchWords(value: string): string[] {
|
||||
return cached(value, wordsCache, () => {
|
||||
wordSegmenter ??= new Intl.Segmenter("zh", { granularity: "word" });
|
||||
const words: string[] = [];
|
||||
let nameChars = "";
|
||||
const flushName = () => {
|
||||
if (nameChars) words.push(nameChars);
|
||||
nameChars = "";
|
||||
};
|
||||
|
||||
for (const part of wordSegmenter.segment(value.normalize("NFKC").trim().toLowerCase())) {
|
||||
// Uncommon enterprise names are often segmented into individual characters.
|
||||
if (part.isWordLike && /^[\u4e00-\u9fa5]$/.test(part.segment)) {
|
||||
nameChars += part.segment;
|
||||
} else {
|
||||
flushName();
|
||||
if (part.isWordLike) words.push(part.segment);
|
||||
}
|
||||
}
|
||||
flushName();
|
||||
return words;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { minSubstringLevenshtein } from "./distance.js";
|
||||
import { fuzzyMatchString } from "./engine.js";
|
||||
import { searchTerms, searchWords } from "./segment.js";
|
||||
import type { MatchScoreResult } from "./types.js";
|
||||
|
||||
function noMatch(): MatchScoreResult {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
/** Word-level pass: every segmented word matches the target (one typo tolerated via context). */
|
||||
function matchQueryWords(queryWords: string[], target: string): MatchScoreResult | null {
|
||||
if (queryWords.length < 2) return null;
|
||||
|
||||
const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched);
|
||||
if (wordMatches.filter(Boolean).length < queryWords.length - 1) return null;
|
||||
|
||||
const allWordsMatch = queryWords.every((word, index) => wordMatches[index] || (
|
||||
// A second matching word supplies context for a typo in a two-character
|
||||
// name, e.g. "瑞泰 半导体" -> "钰泰半导体". Single-word searches stay conservative.
|
||||
/^[\u4e00-\u9fa5]{2}$/.test(word) && minSubstringLevenshtein(word, target) <= 1
|
||||
));
|
||||
if (!allWordsMatch) return null;
|
||||
|
||||
return { matched: true, score: 0.76, reason: "tokens" };
|
||||
}
|
||||
|
||||
/** Term-coverage pass: overlapping two-character terms of the query hit the target. */
|
||||
function matchQueryTerms(
|
||||
query: string,
|
||||
queryWordCount: number,
|
||||
target: string
|
||||
): MatchScoreResult | null {
|
||||
const queryTerms = searchTerms(query);
|
||||
if (queryTerms.length < 2) return null;
|
||||
|
||||
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
|
||||
if (matchedTerms.length === 0) return null;
|
||||
|
||||
const coverage = matchedTerms.length / queryTerms.length;
|
||||
return {
|
||||
matched: true,
|
||||
score: queryWordCount >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2,
|
||||
reason: "tokens"
|
||||
};
|
||||
}
|
||||
|
||||
export function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
|
||||
if (!/[\u4e00-\u9fa5]/.test(query)) {
|
||||
return noMatch();
|
||||
}
|
||||
|
||||
const queryWords = searchWords(query);
|
||||
return matchQueryWords(queryWords, target) ?? matchQueryTerms(query, queryWords.length, target) ?? noMatch();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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"
|
||||
| "tokens"
|
||||
| "abbreviation"
|
||||
| "none";
|
||||
|
||||
export interface MatchScoreResult {
|
||||
matched: boolean;
|
||||
score: number;
|
||||
reason: MatchReason;
|
||||
}
|
||||
@@ -18,10 +18,11 @@ import file14 from "../../skills/seal-use/references/first-time-user.md" with {
|
||||
import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
|
||||
import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
|
||||
import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
|
||||
import file18 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
|
||||
import file19 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file22 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"SKILL.md": file0,
|
||||
@@ -36,10 +37,11 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||
"references/hose-enterprise-auth.md": file15,
|
||||
"references/hose-enterprise-deploy.md": file16,
|
||||
"references/hose-enterprise-init.md": file17,
|
||||
"references/rule-lightweight.md": file18,
|
||||
"references/rule-lint.md": file19,
|
||||
"references/staging-simulation-workflow.md": file20,
|
||||
"references/webhook-resource-pack.md": file21,
|
||||
"references/langfuse-trace.md": file18,
|
||||
"references/rule-lightweight.md": file19,
|
||||
"references/rule-lint.md": file20,
|
||||
"references/staging-simulation-workflow.md": file21,
|
||||
"references/webhook-resource-pack.md": file22,
|
||||
};
|
||||
|
||||
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
|
||||
@@ -70,6 +72,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
|
||||
"references/hose-enterprise-auth.md",
|
||||
"references/hose-enterprise-deploy.md",
|
||||
"references/hose-enterprise-init.md",
|
||||
"references/langfuse-trace.md",
|
||||
"references/rule-lightweight.md",
|
||||
"references/rule-lint.md",
|
||||
"references/staging-simulation-workflow.md",
|
||||
|
||||
@@ -15,6 +15,7 @@ export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken|appSecurity|signKey|secret)=)[^&\s]+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/(Basic\s+)[A-Za-z0-9+/=]+/gi, "$1<redacted>")
|
||||
.replace(
|
||||
/("(?:appSecurity|password|secret|signKey|closeToken|refreshToken|accessToken|authorization)"\s*:\s*")[^"]*(")/gi,
|
||||
"$1<redacted>$2"
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import {
|
||||
filterCorpsFuzzy,
|
||||
fuzzyMatchString,
|
||||
levenshteinDistance,
|
||||
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: "seal",
|
||||
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");
|
||||
});
|
||||
|
||||
test("finds a compact enterprise name inside a longer Chinese query", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const unrelated = makeCorp("corp-other", "南京测绘");
|
||||
const results = filterCorpsFuzzy([unrelated, compactName], "苏州园区测绘");
|
||||
|
||||
expect(results[0]!.id).toBe("corp-yuan-ce");
|
||||
expect(results).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("keeps strict search limited to exact substrings", () => {
|
||||
const compactName = makeCorp("corp-yuan-ce", "园测信息科技股份有限公司");
|
||||
const results = filterCorpsFuzzy([compactName], "苏州园区测绘", { strict: true });
|
||||
|
||||
expect(results).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,400 +0,0 @@
|
||||
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"
|
||||
| "tokens"
|
||||
| "abbreviation"
|
||||
| "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: number[] = Array.from({ length: n + 1 }, () => 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;
|
||||
}
|
||||
|
||||
function searchTerms(value: string): string[] {
|
||||
const chunks = value.trim().toLowerCase().match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? [];
|
||||
return chunks.flatMap((chunk) => {
|
||||
if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk];
|
||||
if (chunk.length <= 2) return [chunk];
|
||||
|
||||
const terms: string[] = [];
|
||||
for (let index = 0; index < chunk.length - 1; index += 1) {
|
||||
terms.push(chunk.slice(index, index + 2));
|
||||
}
|
||||
return terms;
|
||||
});
|
||||
}
|
||||
|
||||
function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
|
||||
if (!/[\u4e00-\u9fa5]/.test(query)) {
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
const queryTerms = searchTerms(query);
|
||||
if (queryTerms.length < 2) return { matched: false, score: 0, reason: "none" };
|
||||
|
||||
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
|
||||
if (matchedTerms.length > 0) {
|
||||
const coverage = matchedTerms.length / queryTerms.length;
|
||||
return {
|
||||
matched: true,
|
||||
score: 0.56 + coverage * 0.2,
|
||||
reason: "tokens"
|
||||
};
|
||||
}
|
||||
|
||||
return { matched: false, score: 0, reason: "none" };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// When a long Chinese query contains a compact enterprise name in order (for
|
||||
// example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"),
|
||||
// retain that candidate as a lower-confidence abbreviation match. This is
|
||||
// deliberately below exact/substring/pinyin matches and disabled in strict mode.
|
||||
if (!options.strict) {
|
||||
const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
if (queryChinese.length >= 3) {
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? "";
|
||||
const prefix = targetChinese.slice(0, 2);
|
||||
if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue;
|
||||
|
||||
const weightedScore = 0.74 * field.weight;
|
||||
if (weightedScore > bestScore) {
|
||||
bestScore = weightedScore;
|
||||
bestReason = "abbreviation";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.text) continue;
|
||||
const res = matchTokenizedQuery(query, field.text);
|
||||
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);
|
||||
|
||||
// Once a strong candidate exists, suppress weak token-only suggestions. This
|
||||
// keeps a query such as "苏州园区测绘" focused on the compact-name match
|
||||
// instead of also returning every enterprise that merely contains "测绘".
|
||||
const strongMatches = scored.filter((item) => item.score >= 0.8);
|
||||
return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { LangfuseClient } from "./client.js";
|
||||
import type { LangfuseProject, LangfuseSession, LangfuseTraceSummary } from "./types.js";
|
||||
|
||||
/**
|
||||
* Langfuse Public API surface used by this domain. Deliberately tiny: every
|
||||
* method maps to a single `GET`, mirroring the read-only client contract.
|
||||
*/
|
||||
export class LangfuseApi {
|
||||
constructor(private readonly client: LangfuseClient) {}
|
||||
|
||||
async getProject(): Promise<LangfuseProject[]> {
|
||||
const response = await this.client.getJson<{ data?: LangfuseProject[] }>(
|
||||
"/api/public/projects"
|
||||
);
|
||||
return response.data ?? [];
|
||||
}
|
||||
|
||||
async getTrace(traceId: string, params: { fields?: string } = {}): Promise<LangfuseTraceSummary> {
|
||||
return await this.client.getJson<LangfuseTraceSummary>(
|
||||
`/api/public/traces/${encodeURIComponent(traceId)}`,
|
||||
{ fields: params.fields }
|
||||
);
|
||||
}
|
||||
|
||||
async getSession(sessionId: string): Promise<LangfuseSession> {
|
||||
return await this.client.getJson<LangfuseSession>(
|
||||
`/api/public/sessions/${encodeURIComponent(sessionId)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import type { CachedTrace, LangfuseTraceSummary } from "./types.js";
|
||||
|
||||
const CACHE_VERSION = 1;
|
||||
const CACHE_ROOT = ".cache/langfuse/traces";
|
||||
// Single-project domain: the cache segment stays "default", which keeps this
|
||||
// cache byte-compatible with `langfuse-home` (same cwd-relative layout), so the
|
||||
// two tools share cached traces instead of re-fetching them.
|
||||
const PROJECT_SEGMENT = "default";
|
||||
|
||||
export type TraceCacheProject = {
|
||||
baseUrl: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Single-trace JSON cache keyed by traceId, written under `<cwd>/.cache`
|
||||
* (gitignored). Holds the FULL raw trace (including observation IO) so outline,
|
||||
* search, observation and flow tools can answer without touching the network.
|
||||
* No TTL: `cache-refresh` overwrites explicitly.
|
||||
*/
|
||||
export class TraceCache {
|
||||
constructor(private readonly project: TraceCacheProject) {}
|
||||
|
||||
path(traceId: string): string {
|
||||
return resolve(
|
||||
process.cwd(),
|
||||
CACHE_ROOT,
|
||||
PROJECT_SEGMENT,
|
||||
`${sanitizeSegment(traceId)}.json`
|
||||
);
|
||||
}
|
||||
|
||||
async exists(traceId: string): Promise<boolean> {
|
||||
try {
|
||||
await stat(this.path(traceId));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async read(traceId: string): Promise<CachedTrace | undefined> {
|
||||
try {
|
||||
const content = await readFile(this.path(traceId), "utf8");
|
||||
const parsed = JSON.parse(content) as CachedTrace;
|
||||
return parsed.cacheVersion === CACHE_VERSION ? parsed : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async write(traceId: string, trace: LangfuseTraceSummary): Promise<CachedTrace> {
|
||||
const cached: CachedTrace = {
|
||||
cacheVersion: CACHE_VERSION,
|
||||
cachedAt: new Date().toISOString(),
|
||||
project: {
|
||||
key: PROJECT_SEGMENT,
|
||||
projectId: trace.projectId ?? this.project.projectId ?? "",
|
||||
baseUrl: this.project.baseUrl
|
||||
},
|
||||
trace
|
||||
};
|
||||
|
||||
const path = this.path(traceId);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, `${JSON.stringify(cached, null, 2)}\n`, "utf8");
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeSegment(value: string): string {
|
||||
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
LANGFUSE_READ_ONLY_CAPABILITIES,
|
||||
findLangfuseCapability,
|
||||
langfuseCapabilities
|
||||
} from "./capabilities.js";
|
||||
|
||||
describe("langfuse capability registry", () => {
|
||||
test("every capability is classified read-only, exhaustively and without overlap", () => {
|
||||
const names = langfuseCapabilities.map((capability) => capability.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
expect([...LANGFUSE_READ_ONLY_CAPABILITIES].sort()).toEqual(names.slice().sort());
|
||||
});
|
||||
|
||||
test("every capability carries a description and a parameter schema", () => {
|
||||
for (const capability of langfuseCapabilities) {
|
||||
expect({ name: capability.name, described: capability.description.length > 0 }).toEqual({
|
||||
name: capability.name,
|
||||
described: true
|
||||
});
|
||||
expect(typeof capability.handler).toBe("function");
|
||||
expect(capability.parameters.safeParse({}).success).toBeTypeOf("boolean");
|
||||
}
|
||||
});
|
||||
|
||||
test("unknown capability names resolve to undefined", () => {
|
||||
expect(findLangfuseCapability("sealLangfuseDoesNotExist")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("required params gate before any handler runs", () => {
|
||||
expect(findLangfuseCapability("sealLangfuseTraceCacheRefresh")!.parameters.safeParse({}).success).toBe(false);
|
||||
expect(
|
||||
findLangfuseCapability("sealLangfuseTraceCacheRefresh")!.parameters.safeParse({ traceId: "t-1" }).success
|
||||
).toBe(true);
|
||||
expect(findLangfuseCapability("sealLangfuseTraceRuleFlowGet")!.parameters.safeParse({ traceId: "t-1" }).success).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("ranges and refinements reject out-of-contract values", () => {
|
||||
const outline = findLangfuseCapability("sealLangfuseTraceOutlineGet")!.parameters;
|
||||
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 10 }).success).toBe(false);
|
||||
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 100 }).success).toBe(true);
|
||||
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 9_999 }).success).toBe(false);
|
||||
|
||||
const search = findLangfuseCapability("sealLangfuseTraceQrepSearch")!.parameters;
|
||||
expect(search.safeParse({ traceId: "t-1", query: "发票" }).success).toBe(true);
|
||||
expect(search.safeParse({ traceId: "t-1", maxResults: 0 }).success).toBe(false);
|
||||
expect(search.safeParse({ traceId: "t-1", query: ["a"], fields: ["bogus"] }).success).toBe(false);
|
||||
|
||||
const attachment = findLangfuseCapability("sealLangfuseAttachmentFlowGet")!.parameters;
|
||||
expect(attachment.safeParse({ traceId: "t-1" }).success).toBe(false);
|
||||
expect(attachment.safeParse({ traceId: "t-1", fileName: "a.pdf" }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import { z } from "zod";
|
||||
import { resolveLangfuseConfig, type LangfuseConfig } from "./config.js";
|
||||
import { LangfuseService } from "./service.js";
|
||||
|
||||
/**
|
||||
* Registry of read-only Langfuse capabilities.
|
||||
*
|
||||
* Separate from `sealCapabilities` on purpose: these handlers need no Seal
|
||||
* tenant, no `CorpConfig` and no Seal HTTP client — they talk to Langfuse with
|
||||
* the compile-time injected key pair. They share the same shape (name /
|
||||
* description / Zod `parameters` / `handler`) so the CLI dispatch helper can
|
||||
* treat them uniformly.
|
||||
*
|
||||
* Naming keeps the `sealLangfuse*` prefix because these are internal registry
|
||||
* identifiers for dispatch and allow-lists; the MCP surface only ever exposes
|
||||
* the `seal_use` / `seal_use_write` gateway pair (see README "One registry,
|
||||
* two doors").
|
||||
*
|
||||
* Every entry is read-only by construction: the underlying `LangfuseClient`
|
||||
* issues `GET` requests only. `LANGFUSE_READ_ONLY_CAPABILITIES` lists the names
|
||||
* explicitly so a newly added capability fails `capabilities.test.ts` until it
|
||||
* is classified here.
|
||||
*/
|
||||
export const langfuseCapabilities = [
|
||||
{
|
||||
name: "sealLangfuseConnectionCheck",
|
||||
description: "检查内置 Langfuse 只读凭据的连通性,返回项目信息",
|
||||
parameters: z.object({}),
|
||||
handler: async (_params: Record<string, never>, service: LangfuseService) =>
|
||||
service.connectionCheck()
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceCacheRefresh",
|
||||
description: "按 traceId 拉取完整 Langfuse trace 并写入本地缓存,供离线 outline/search 使用",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1)
|
||||
}),
|
||||
handler: async (params: { traceId: string }, service: LangfuseService) =>
|
||||
service.refreshTraceCache(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceUrlGet",
|
||||
description: "构建单条 trace 的 Langfuse 后台直达链接(优先使用缓存中的 projectId)",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1)
|
||||
}),
|
||||
handler: async (params: { traceId: string }, service: LangfuseService) =>
|
||||
service.getTraceUrl(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceOutlineGet",
|
||||
description: "读取缓存 trace 的紧凑大纲:观测树、体量、用量、成本与可选 IO 预览",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
includeIoPreview: z.boolean().optional(),
|
||||
includeInput: z.boolean().optional(),
|
||||
includeOutput: z.boolean().optional(),
|
||||
full: z.boolean().optional(),
|
||||
maxPreviewChars: z.number().int().min(20).max(5_000).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
includeIoPreview?: boolean;
|
||||
includeInput?: boolean;
|
||||
includeOutput?: boolean;
|
||||
full?: boolean;
|
||||
maxPreviewChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getTraceOutline(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceQrepSearch",
|
||||
description: "在单条缓存 trace 内做层级感知的关键词检索,返回带上下文的排序片段",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
query: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
|
||||
sessionId: z.string().optional(),
|
||||
fields: z
|
||||
.array(z.enum(["name", "input", "output", "metadata", "userId", "sessionId"]))
|
||||
.optional(),
|
||||
observationTypes: z.array(z.string().min(1)).optional(),
|
||||
metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
|
||||
maxResults: z.number().int().min(1).max(30).optional(),
|
||||
contextChars: z.number().int().min(20).max(500).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
query: string | string[];
|
||||
sessionId?: string;
|
||||
fields?: Array<"name" | "input" | "output" | "metadata" | "userId" | "sessionId">;
|
||||
observationTypes?: string[];
|
||||
metadata?: Record<string, string | number | boolean>;
|
||||
maxResults?: number;
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.searchTrace(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseObservationIoGet",
|
||||
description: "读取指定 observation 的聚焦 input/output/metadata,支持 jsonPath 定点取值",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
observationId: z.string().min(1),
|
||||
fields: z.array(z.enum(["input", "output", "metadata"])).optional(),
|
||||
maxChars: z.number().int().min(100).max(500_000).optional(),
|
||||
full: z.boolean().optional(),
|
||||
jsonPath: z.string().optional(),
|
||||
path: z.string().optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
observationId: string;
|
||||
fields?: Array<"input" | "output" | "metadata">;
|
||||
maxChars?: number;
|
||||
full?: boolean;
|
||||
jsonPath?: string;
|
||||
path?: string;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getObservationIo(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseSessionOutlineGet",
|
||||
description: "获取 Langfuse session 的紧凑 trace 摘要列表(不缓存整 session)",
|
||||
parameters: z.object({
|
||||
sessionId: z.string().min(1),
|
||||
traceLimit: z.number().int().min(1).max(200).optional()
|
||||
}),
|
||||
handler: async (params: { sessionId: string; traceLimit?: number }, service: LangfuseService) =>
|
||||
service.getSessionOutline(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseObservationsFind",
|
||||
description: "按名称/类型/metadata 键/是否含 IO 过滤缓存 trace 内的 observation,只返回摘要",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
nameContains: z.string().optional(),
|
||||
type: z.string().optional(),
|
||||
metadataKey: z.string().optional(),
|
||||
hasInput: z.boolean().optional(),
|
||||
hasOutput: z.boolean().optional(),
|
||||
maxResults: z.number().int().min(1).max(200).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
nameContains?: string;
|
||||
type?: string;
|
||||
metadataKey?: string;
|
||||
hasInput?: boolean;
|
||||
hasOutput?: boolean;
|
||||
maxResults?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.findObservations(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseAttachmentFlowGet",
|
||||
description: "在缓存 trace 中追踪附件文件 id/名称/提示词经解析与审核阶段的文本证据",
|
||||
parameters: z
|
||||
.object({
|
||||
traceId: z.string().min(1),
|
||||
fileId: z.string().optional(),
|
||||
fileName: z.string().optional(),
|
||||
contentHints: z.array(z.string().min(1)).optional(),
|
||||
contextChars: z.number().int().min(20).max(500).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
})
|
||||
.refine(
|
||||
(value) => Boolean(value.fileId || value.fileName || value.contentHints?.length),
|
||||
{ message: "Provide at least one of fileId, fileName, or contentHints" }
|
||||
),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
fileId?: string;
|
||||
fileName?: string;
|
||||
contentHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getAttachmentFlow(params)
|
||||
},
|
||||
{
|
||||
name: "sealLangfuseTraceRuleFlowGet",
|
||||
description: "在缓存 trace 中追踪一条规则经规则匹配、文档解析、最终审核阶段的文本证据",
|
||||
parameters: z.object({
|
||||
traceId: z.string().min(1),
|
||||
rule: z.string().min(1),
|
||||
ruleHints: z.array(z.string().min(1)).optional(),
|
||||
contextChars: z.number().int().min(20).max(500).optional(),
|
||||
refreshIfMissing: z.boolean().optional()
|
||||
}),
|
||||
handler: async (
|
||||
params: {
|
||||
traceId: string;
|
||||
rule: string;
|
||||
ruleHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
},
|
||||
service: LangfuseService
|
||||
) => service.getTraceRuleFlow(params)
|
||||
}
|
||||
];
|
||||
|
||||
export type LangfuseCapability = (typeof langfuseCapabilities)[number];
|
||||
|
||||
export const LANGFUSE_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealLangfuseConnectionCheck",
|
||||
"sealLangfuseTraceCacheRefresh",
|
||||
"sealLangfuseTraceUrlGet",
|
||||
"sealLangfuseTraceOutlineGet",
|
||||
"sealLangfuseTraceQrepSearch",
|
||||
"sealLangfuseObservationIoGet",
|
||||
"sealLangfuseSessionOutlineGet",
|
||||
"sealLangfuseObservationsFind",
|
||||
"sealLangfuseAttachmentFlowGet",
|
||||
"sealLangfuseTraceRuleFlowGet"
|
||||
]);
|
||||
|
||||
export function findLangfuseCapability(name: string): LangfuseCapability | undefined {
|
||||
return langfuseCapabilities.find((capability) => capability.name === name);
|
||||
}
|
||||
|
||||
/** Built lazily per invocation so tests can swap env vars before first use. */
|
||||
export function createLangfuseService(config?: LangfuseConfig): LangfuseService {
|
||||
return new LangfuseService(config ?? resolveLangfuseConfig());
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
import { LangfuseClient } from "./client.js";
|
||||
|
||||
type ServedRequest = {
|
||||
method: string;
|
||||
authorization: string | undefined;
|
||||
url: string;
|
||||
};
|
||||
|
||||
async function withServer(
|
||||
respond: (request: ServedRequest) => Response,
|
||||
run: (client: LangfuseClient, requests: ServedRequest[]) => Promise<void>
|
||||
) {
|
||||
const requests: ServedRequest[] = [];
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
const served: ServedRequest = {
|
||||
method: request.method,
|
||||
authorization: request.headers.get("authorization") ?? undefined,
|
||||
url: request.url
|
||||
};
|
||||
requests.push(served);
|
||||
return respond(served);
|
||||
}
|
||||
});
|
||||
|
||||
const config: LangfuseConfig = {
|
||||
baseUrl: `http://127.0.0.1:${server.port}`,
|
||||
publicKey: "pk-lf-test",
|
||||
secretKey: "sk-lf-test"
|
||||
};
|
||||
|
||||
try {
|
||||
await run(new LangfuseClient(config), requests);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
}
|
||||
|
||||
describe("LangfuseClient read-only contract", () => {
|
||||
test("issues GET with Basic auth and returns parsed JSON", async () => {
|
||||
await withServer(
|
||||
() => Response.json({ data: [{ id: "proj-1" }] }),
|
||||
async (client, requests) => {
|
||||
const result = await client.getJson<{ data: Array<{ id: string }> }>("/api/public/projects", {
|
||||
limit: 5,
|
||||
skipped: undefined
|
||||
});
|
||||
|
||||
expect(result.data[0]?.id).toBe("proj-1");
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0]?.method).toBe("GET");
|
||||
expect(requests[0]?.authorization).toBe(
|
||||
`Basic ${Buffer.from("pk-lf-test:sk-lf-test", "utf8").toString("base64")}`
|
||||
);
|
||||
const url = new URL(requests[0]!.url);
|
||||
expect(url.pathname).toBe("/api/public/projects");
|
||||
expect(url.searchParams.get("limit")).toBe("5");
|
||||
expect(url.searchParams.has("skipped")).toBe(false);
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("the class exposes no method that could mutate remote state", () => {
|
||||
const methods = Object.getOwnPropertyNames(LangfuseClient.prototype).sort();
|
||||
// Getters (`baseUrl`, `getProjectId`) are prototype properties too; anything
|
||||
// beyond this allow-list would need a read-only review before shipping.
|
||||
expect(methods).toEqual(["baseUrl", "constructor", "getJson", "getProjectId"]);
|
||||
});
|
||||
|
||||
test("401 maps to exit 11 and never echoes the secret", async () => {
|
||||
await withServer(
|
||||
() => new Response("token invalid", { status: 401, statusText: "Unauthorized" }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/projects");
|
||||
expect.unreachable("401 should throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(11);
|
||||
expect((error as CliError).message).toContain("401");
|
||||
expect((error as CliError).message).not.toContain("sk-lf-test");
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("403 also maps to exit 11", async () => {
|
||||
await withServer(
|
||||
() => new Response("forbidden", { status: 403, statusText: "Forbidden" }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/traces/x");
|
||||
expect.unreachable("403 should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(11);
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("other upstream failures map to exit 1", async () => {
|
||||
await withServer(
|
||||
() => new Response("boom", { status: 500, statusText: "Internal Server Error" }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/traces/x");
|
||||
expect.unreachable("500 should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(1);
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("a 200 non-JSON body degrades to exit 1 instead of a parse crash", async () => {
|
||||
await withServer(
|
||||
() => new Response("<html>captive portal</html>", { status: 200, headers: { "content-type": "text/html" } }),
|
||||
async (client) => {
|
||||
try {
|
||||
await client.getJson("/api/public/projects");
|
||||
expect.unreachable("non-JSON body should throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(1);
|
||||
expect((error as CliError).message).toContain("non-JSON");
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test("network errors map to exit 1 with a Basic-redacted message", async () => {
|
||||
const config: LangfuseConfig = {
|
||||
// Reserved port with nothing listening: connection refused, no DNS.
|
||||
baseUrl: "http://127.0.0.1:9",
|
||||
publicKey: "pk-lf-test",
|
||||
secretKey: "sk-lf-test"
|
||||
};
|
||||
const client = new LangfuseClient(config);
|
||||
try {
|
||||
await client.getJson("/api/public/projects");
|
||||
expect.unreachable("connection failure should throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(1);
|
||||
expect((error as CliError).message).toContain("unreachable");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { redactSensitiveText } from "../../core/redact.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
|
||||
export type HttpQuery = Record<string, string | number | boolean | undefined>;
|
||||
|
||||
/**
|
||||
* Read-only Langfuse Public API client.
|
||||
*
|
||||
* The embedded key pair is not scope-limited upstream (Langfuse project keys
|
||||
* carry full API access), so "read-only" is a guarantee of THIS client: it
|
||||
* exposes `getJson` only, issues `GET` exclusively, and has no method that can
|
||||
* mutate remote state. Keep it that way — adding a POST/PUT/DELETE helper here
|
||||
* breaks the documented trust boundary in SECURITY.md.
|
||||
*
|
||||
* Failures map to the CLI exit-code contract: 401/403 → 11 (authentication),
|
||||
* any other upstream failure → 1 (upstream API failure). Messages pass through
|
||||
* `redactSensitiveText` so the Basic credential can never leak via an error.
|
||||
*/
|
||||
export class LangfuseClient {
|
||||
constructor(private readonly config: LangfuseConfig) {}
|
||||
|
||||
get baseUrl(): string {
|
||||
return this.config.baseUrl;
|
||||
}
|
||||
|
||||
getProjectId(): string | undefined {
|
||||
return this.config.projectId;
|
||||
}
|
||||
|
||||
async getJson<T>(path: string, query: HttpQuery = {}): Promise<T> {
|
||||
const url = new URL(`${this.config.baseUrl}${path}`);
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
if (value !== undefined) url.searchParams.set(key, String(value));
|
||||
}
|
||||
|
||||
const credential = Buffer.from(
|
||||
`${this.config.publicKey}:${this.config.secretKey}`,
|
||||
"utf8"
|
||||
).toString("base64");
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Basic ${credential}`,
|
||||
Accept: "application/json"
|
||||
},
|
||||
signal: AbortSignal.timeout(30_000)
|
||||
});
|
||||
} catch (error) {
|
||||
const detail = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
throw new CliError(`Langfuse API unreachable: ${detail}`, 1);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = redactSensitiveText(await response.text());
|
||||
const detail = `Langfuse API ${response.status} ${response.statusText}: ${body.slice(0, 500)}`;
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new CliError(detail, 11, "检查注入的 Langfuse 密钥是否仍然有效");
|
||||
}
|
||||
throw new CliError(detail, 1);
|
||||
}
|
||||
|
||||
// A 200 that is not JSON (captive portal, HTML error page from a proxy)
|
||||
// must degrade like any other upstream failure — exit 1, never a raw
|
||||
// SyntaxError bubbling up as a misleading "invalid config" exit 13.
|
||||
try {
|
||||
return (await response.json()) as T;
|
||||
} catch {
|
||||
throw new CliError(
|
||||
"Langfuse API returned a non-JSON response (upstream or network proxy problem).",
|
||||
1,
|
||||
"用 seal-use langfuse check 复测连通性,或改用 Langfuse Web 后台"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { hasLangfuseCredentials, resolveLangfuseConfig } from "./config.js";
|
||||
|
||||
const KEYS = [
|
||||
"SEAL_BUILD_LANGFUSE_BASE_URL",
|
||||
"SEAL_BUILD_LANGFUSE_PUBLIC_KEY",
|
||||
"SEAL_BUILD_LANGFUSE_SECRET_KEY",
|
||||
"SEAL_BUILD_LANGFUSE_PROJECT_ID",
|
||||
"LANGFUSE_BASE_URL",
|
||||
"LANGFUSE_PUBLIC_KEY",
|
||||
"LANGFUSE_SECRET_KEY",
|
||||
"LANGFUSE_PROJECT_ID"
|
||||
] as const;
|
||||
|
||||
const original = new Map<string, string | undefined>(KEYS.map((key) => [key, process.env[key]]));
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of KEYS) {
|
||||
const value = original.get(key);
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
function clearAll() {
|
||||
for (const key of KEYS) delete process.env[key];
|
||||
}
|
||||
|
||||
describe("langfuse config resolution", () => {
|
||||
test("prefers compile-time injected vars and normalizes the base URL", () => {
|
||||
clearAll();
|
||||
process.env.SEAL_BUILD_LANGFUSE_BASE_URL = "https://cloud.langfuse.com/";
|
||||
process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY = "pk-lf-build";
|
||||
process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY = "sk-lf-build";
|
||||
process.env.LANGFUSE_BASE_URL = "https://dev.example";
|
||||
process.env.LANGFUSE_PUBLIC_KEY = "pk-lf-dev";
|
||||
|
||||
const config = resolveLangfuseConfig();
|
||||
expect(config).toEqual({
|
||||
baseUrl: "https://cloud.langfuse.com",
|
||||
publicKey: "pk-lf-build",
|
||||
secretKey: "sk-lf-build"
|
||||
});
|
||||
});
|
||||
|
||||
test("falls back to plain LANGFUSE_* shell vars for source runs", () => {
|
||||
clearAll();
|
||||
process.env.LANGFUSE_BASE_URL = "https://cloud.langfuse.com";
|
||||
process.env.LANGFUSE_PUBLIC_KEY = "pk-lf-dev";
|
||||
process.env.LANGFUSE_SECRET_KEY = "sk-lf-dev";
|
||||
process.env.LANGFUSE_PROJECT_ID = "proj-1";
|
||||
|
||||
expect(hasLangfuseCredentials()).toBe(true);
|
||||
expect(resolveLangfuseConfig()).toEqual({
|
||||
baseUrl: "https://cloud.langfuse.com",
|
||||
publicKey: "pk-lf-dev",
|
||||
secretKey: "sk-lf-dev",
|
||||
projectId: "proj-1"
|
||||
});
|
||||
});
|
||||
|
||||
test("throws exit 11 when no credentials exist in the build", () => {
|
||||
clearAll();
|
||||
expect(hasLangfuseCredentials()).toBe(false);
|
||||
try {
|
||||
resolveLangfuseConfig();
|
||||
expect.unreachable("resolveLangfuseConfig should throw without credentials");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CliError);
|
||||
expect((error as CliError).exitCode).toBe(11);
|
||||
expect((error as CliError).message).toContain("SEAL_BUILD_LANGFUSE_BASE_URL");
|
||||
}
|
||||
});
|
||||
|
||||
test("incomplete credentials are treated as missing", () => {
|
||||
clearAll();
|
||||
process.env.SEAL_BUILD_LANGFUSE_BASE_URL = "https://cloud.langfuse.com";
|
||||
expect(hasLangfuseCredentials()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { CliError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* Langfuse connection settings resolved at runtime.
|
||||
*
|
||||
* Credentials are injected at COMPILE time, never stored in this repository or
|
||||
* in user config: `scripts/build-binary.mjs` copies them into the build
|
||||
* environment as `SEAL_BUILD_LANGFUSE_*`, and `bun build --env=SEAL_BUILD_*`
|
||||
* embeds them into release binaries. End users therefore need zero setup.
|
||||
*
|
||||
* Precedence: injected build vars → plain `LANGFUSE_*` shell vars (development
|
||||
* convenience when running from source) → nothing. Reading user config files is
|
||||
* deliberately absent: this domain must work without any local configuration.
|
||||
*/
|
||||
export type LangfuseConfig = {
|
||||
baseUrl: string;
|
||||
publicKey: string;
|
||||
secretKey: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
function pick(...candidates: Array<string | undefined>): string | undefined {
|
||||
for (const candidate of candidates) {
|
||||
const trimmed = candidate?.trim();
|
||||
if (trimmed) return trimmed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(baseUrl: string): string {
|
||||
return baseUrl.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function hasLangfuseCredentials(): boolean {
|
||||
const { baseUrl, publicKey, secretKey } = readLangfuseCredentials();
|
||||
return Boolean(baseUrl && publicKey && secretKey);
|
||||
}
|
||||
|
||||
/** Returns the credential set, or `undefined` parts when a build has none. */
|
||||
function readLangfuseCredentials(): {
|
||||
baseUrl?: string;
|
||||
publicKey?: string;
|
||||
secretKey?: string;
|
||||
projectId?: string;
|
||||
} {
|
||||
// Literal `process.env.X` accesses on purpose: `bun build --env=SEAL_BUILD_*`
|
||||
// inlines static property reads at compile time, while a computed key
|
||||
// (`process.env["SEAL_BUILD_" + name]`) stays a runtime lookup and comes back
|
||||
// empty from a release binary. Reads happen per call so tests and dev shells
|
||||
// can change the environment between invocations. The `LANGFUSE_*` fallbacks
|
||||
// are deliberately outside the SEAL_BUILD_ prefix: they are never inlined and
|
||||
// remain live shell-env vars for development runs from source.
|
||||
return {
|
||||
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL),
|
||||
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY),
|
||||
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY),
|
||||
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID)
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveLangfuseConfig(): LangfuseConfig {
|
||||
const { baseUrl, publicKey, secretKey, projectId } = readLangfuseCredentials();
|
||||
|
||||
if (!baseUrl || !publicKey || !secretKey) {
|
||||
throw new CliError(
|
||||
"Langfuse credentials are missing in this build: SEAL_BUILD_LANGFUSE_BASE_URL / SEAL_BUILD_LANGFUSE_PUBLIC_KEY / SEAL_BUILD_LANGFUSE_SECRET_KEY were not injected at compile time.",
|
||||
11,
|
||||
"使用官方发行版二进制(seal-use update),或在构建时注入 SEAL_BUILD_LANGFUSE_* 环境变量"
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
baseUrl: normalizeBaseUrl(baseUrl),
|
||||
publicKey,
|
||||
secretKey,
|
||||
...(projectId ? { projectId } : {})
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import type {
|
||||
LangfuseObservationSummary,
|
||||
LangfuseSearchResult,
|
||||
LangfuseTraceSummary,
|
||||
SearchField
|
||||
} from "./types.js";
|
||||
|
||||
const DEFAULT_FIELDS: SearchField[] = ["name", "input", "output", "metadata", "userId", "sessionId"];
|
||||
|
||||
/**
|
||||
* Deterministic ranked search inside ONE cached trace (the "qrep" engine).
|
||||
* Case-insensitive substring matching — no embeddings, no LLM. Matches are
|
||||
* scored (output > metadata > name; trace scope and review-stage observations
|
||||
* rank higher) and returned with a hierarchy path plus before/match/after
|
||||
* context so callers can decide which observation to open next.
|
||||
*/
|
||||
export function searchTrace(
|
||||
projectId: string,
|
||||
trace: LangfuseTraceSummary,
|
||||
query: string | string[],
|
||||
options: {
|
||||
maxResults: number;
|
||||
contextChars: number;
|
||||
fields?: SearchField[];
|
||||
observationTypes?: string[];
|
||||
metadata?: Record<string, string | number | boolean>;
|
||||
}
|
||||
): LangfuseSearchResult[] {
|
||||
const terms = normalizeTerms(query);
|
||||
if (terms.length === 0) return [];
|
||||
if (!metadataMatches(trace.metadata, options.metadata)) return [];
|
||||
|
||||
const fields = options.fields?.length ? options.fields : DEFAULT_FIELDS;
|
||||
const observations = trace.observations ?? [];
|
||||
const pathByObservationId = buildObservationPaths(trace, observations);
|
||||
const allowedTypes = new Set(options.observationTypes?.map((type) => type.toUpperCase()));
|
||||
const results: Array<LangfuseSearchResult & { score: number }> = [];
|
||||
|
||||
for (const field of searchableFields(trace, fields)) {
|
||||
const match = makeMatch(field.value, terms, options.contextChars);
|
||||
if (!match) continue;
|
||||
|
||||
results.push({
|
||||
score: scoreMatch("trace", field.name),
|
||||
projectId,
|
||||
sessionId: trace.sessionId,
|
||||
traceId: trace.id,
|
||||
traceName: trace.name,
|
||||
timestamp: trace.timestamp,
|
||||
path: buildTracePath(trace, field.name),
|
||||
field: field.name,
|
||||
snippet: formatSnippet(match),
|
||||
matchedField: field.name,
|
||||
matchedText: match.match,
|
||||
context: match,
|
||||
hierarchy: {
|
||||
session: trace.sessionId ? { id: trace.sessionId } : undefined,
|
||||
trace: { id: trace.id, name: trace.name, userId: trace.userId }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const observation of observations) {
|
||||
if (allowedTypes.size > 0 && observation.type && !allowedTypes.has(observation.type.toUpperCase())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const field of searchableFields(observation, fields)) {
|
||||
const match = makeMatch(field.value, terms, options.contextChars);
|
||||
if (!match) continue;
|
||||
|
||||
results.push({
|
||||
score: scoreMatch("observation", field.name, observation.name),
|
||||
projectId,
|
||||
sessionId: trace.sessionId ?? observation.sessionId,
|
||||
traceId: trace.id,
|
||||
traceName: trace.name,
|
||||
timestamp: observation.startTime ?? trace.timestamp,
|
||||
path: [...(pathByObservationId.get(observation.id) ?? buildObservationPath(trace, observation)), field.name],
|
||||
observationId: observation.id,
|
||||
observationName: observation.name,
|
||||
observationType: observation.type,
|
||||
field: field.name,
|
||||
snippet: formatSnippet(match),
|
||||
matchedField: `observations.${observation.id}.${field.name}`,
|
||||
matchedText: match.match,
|
||||
context: match,
|
||||
hierarchy: {
|
||||
session: trace.sessionId ? { id: trace.sessionId } : undefined,
|
||||
trace: { id: trace.id, name: trace.name, userId: trace.userId },
|
||||
observation: {
|
||||
id: observation.id,
|
||||
type: observation.type,
|
||||
name: observation.name
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
.sort((left, right) => right.score - left.score)
|
||||
.slice(0, options.maxResults)
|
||||
.map(({ score: _score, ...result }) => result);
|
||||
}
|
||||
|
||||
function searchableFields(
|
||||
entity: Record<string, unknown>,
|
||||
fields: SearchField[]
|
||||
): Array<{ name: SearchField; value: string }> {
|
||||
return fields
|
||||
.map((field) => ({ name: field, value: stringifyValue(entity[field]) }))
|
||||
.filter((field) => field.value.length > 0);
|
||||
}
|
||||
|
||||
export function stringifyValue(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "string") return value;
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTerms(query: string | string[]): string[] {
|
||||
const values = Array.isArray(query) ? query : [query];
|
||||
return values.map((value) => value.trim().toLowerCase()).filter(Boolean);
|
||||
}
|
||||
|
||||
function makeMatch(
|
||||
text: string,
|
||||
terms: string[],
|
||||
contextChars: number
|
||||
): { before: string; match: string; after: string } | undefined {
|
||||
const normalizedText = text.toLowerCase();
|
||||
let best: { term: string; index: number } | undefined;
|
||||
|
||||
for (const term of terms) {
|
||||
const index = normalizedText.indexOf(term);
|
||||
if (index < 0) continue;
|
||||
if (!best || index < best.index) best = { term, index };
|
||||
}
|
||||
|
||||
if (!best) return undefined;
|
||||
|
||||
const start = Math.max(0, best.index - contextChars);
|
||||
const end = Math.min(text.length, best.index + best.term.length + contextChars);
|
||||
|
||||
return {
|
||||
before: text.slice(start, best.index),
|
||||
match: text.slice(best.index, best.index + best.term.length),
|
||||
after: text.slice(best.index + best.term.length, end)
|
||||
};
|
||||
}
|
||||
|
||||
function formatSnippet(match: { before: string; match: string; after: string }): string {
|
||||
return `${match.before}${match.match}${match.after}`;
|
||||
}
|
||||
|
||||
function scoreMatch(scope: "trace" | "observation", fieldName: string, observationName?: string): number {
|
||||
const fieldWeight = fieldName === "output" ? 30 : fieldName === "metadata" ? 20 : fieldName === "name" ? 10 : 5;
|
||||
const scopeWeight = scope === "trace" ? 15 : 0;
|
||||
const finalReviewWeight =
|
||||
observationName?.includes("approval_review") || observationName?.includes("审核") ? 10 : 0;
|
||||
return fieldWeight + scopeWeight + finalReviewWeight;
|
||||
}
|
||||
|
||||
function buildTracePath(trace: LangfuseTraceSummary, fieldName: string): string[] {
|
||||
return [...(trace.sessionId ? [`session:${trace.sessionId}`] : []), `trace:${trace.name ?? trace.id}`, fieldName];
|
||||
}
|
||||
|
||||
function buildObservationPaths(
|
||||
trace: LangfuseTraceSummary,
|
||||
observations: LangfuseObservationSummary[]
|
||||
): Map<string, string[]> {
|
||||
const byId = new Map(observations.map((observation) => [observation.id, observation]));
|
||||
const paths = new Map<string, string[]>();
|
||||
|
||||
for (const observation of observations) {
|
||||
paths.set(observation.id, resolveObservationPath(trace, observation, byId, paths));
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
function resolveObservationPath(
|
||||
trace: LangfuseTraceSummary,
|
||||
observation: LangfuseObservationSummary,
|
||||
byId: Map<string, LangfuseObservationSummary>,
|
||||
paths: Map<string, string[]>
|
||||
): string[] {
|
||||
const cached = paths.get(observation.id);
|
||||
if (cached) return cached;
|
||||
|
||||
const current = `${observation.type?.toLowerCase() ?? "observation"}:${observation.name ?? observation.id}`;
|
||||
const parent = observation.parentObservationId ? byId.get(observation.parentObservationId) : undefined;
|
||||
const path = parent
|
||||
? [...resolveObservationPath(trace, parent, byId, paths), current]
|
||||
: [...buildTracePath(trace, "observations").slice(0, -1), current];
|
||||
|
||||
paths.set(observation.id, path);
|
||||
return path;
|
||||
}
|
||||
|
||||
function buildObservationPath(trace: LangfuseTraceSummary, observation: LangfuseObservationSummary): string[] {
|
||||
return [
|
||||
...(trace.sessionId ? [`session:${trace.sessionId}`] : []),
|
||||
`trace:${trace.name ?? trace.id}`,
|
||||
`${observation.type?.toLowerCase() ?? "observation"}:${observation.name ?? observation.id}`
|
||||
];
|
||||
}
|
||||
|
||||
function metadataMatches(metadata: unknown, filters?: Record<string, string | number | boolean>): boolean {
|
||||
if (!filters || Object.keys(filters).length === 0) return true;
|
||||
if (!metadata || typeof metadata !== "object") return false;
|
||||
|
||||
const record = metadata as Record<string, unknown>;
|
||||
return Object.entries(filters).every(([key, expected]) => record[key] === expected);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, realpathSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { TraceCache } from "./cache.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
import { LangfuseService } from "./service.js";
|
||||
import { searchTrace } from "./search.js";
|
||||
import type { LangfuseTraceSummary } from "./types.js";
|
||||
|
||||
const CONFIG: LangfuseConfig = {
|
||||
baseUrl: "https://langfuse.invalid",
|
||||
publicKey: "pk-lf-test",
|
||||
secretKey: "sk-lf-test",
|
||||
projectId: "proj-1"
|
||||
};
|
||||
|
||||
function sampleTrace(): LangfuseTraceSummary {
|
||||
return {
|
||||
id: "trace-1",
|
||||
name: "approval 驳回 run",
|
||||
projectId: "proj-1",
|
||||
sessionId: "sess-1",
|
||||
userId: "user-1",
|
||||
timestamp: "2026-10-01T00:00:00+08:00",
|
||||
input: "申请单 A",
|
||||
output: "已通过",
|
||||
observations: [
|
||||
{
|
||||
id: "obs-root",
|
||||
traceId: "trace-1",
|
||||
type: "SPAN",
|
||||
name: "document_parsing",
|
||||
input: { items: [{ name: "invoice.pdf" }] },
|
||||
output: "解析完成",
|
||||
metadata: { stage: "parsing" }
|
||||
},
|
||||
{
|
||||
id: "obs-review",
|
||||
traceId: "trace-1",
|
||||
parentObservationId: "obs-root",
|
||||
type: "GENERATION",
|
||||
name: "approval_review",
|
||||
input: "上下文",
|
||||
output: "驳回:材料不全",
|
||||
usageDetails: { input: 10 },
|
||||
totalCost: 0.01
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
let originalCwd: string;
|
||||
let workdir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
workdir = mkdtempSync(join(tmpdir(), "seal-langfuse-test-"));
|
||||
process.chdir(workdir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function seedCache(trace: LangfuseTraceSummary = sampleTrace()) {
|
||||
const cache = new TraceCache({ baseUrl: CONFIG.baseUrl, projectId: CONFIG.projectId });
|
||||
await cache.write(trace.id, trace);
|
||||
return cache;
|
||||
}
|
||||
|
||||
describe("trace cache", () => {
|
||||
test("writes the langfuse-home compatible path and round-trips", async () => {
|
||||
const cache = await seedCache();
|
||||
// process.cwd() resolves symlinks, so compare against the physical tmpdir
|
||||
// (macOS /var -> /private/var).
|
||||
const physicalWorkdir = realpathSync(workdir);
|
||||
expect(cache.path("trace-1")).toBe(
|
||||
join(physicalWorkdir, ".cache", "langfuse", "traces", "default", "trace-1.json")
|
||||
);
|
||||
|
||||
const read = await new TraceCache({ baseUrl: CONFIG.baseUrl }).read("trace-1");
|
||||
expect(read?.cacheVersion).toBe(1);
|
||||
expect(read?.trace.id).toBe("trace-1");
|
||||
expect(read?.project.baseUrl).toBe(CONFIG.baseUrl);
|
||||
});
|
||||
|
||||
test("returns undefined for a missing or version-mismatched entry", async () => {
|
||||
const cache = new TraceCache({ baseUrl: CONFIG.baseUrl });
|
||||
expect(await cache.read("missing")).toBeUndefined();
|
||||
await cache.write("trace-1", sampleTrace());
|
||||
expect(await cache.exists("trace-1")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("service outline and observation IO (offline, cache-first)", () => {
|
||||
test("builds the observation tree from the cached trace", async () => {
|
||||
await seedCache();
|
||||
const service = new LangfuseService(CONFIG);
|
||||
|
||||
const outline = await service.getTraceOutline({ traceId: "trace-1" });
|
||||
expect(outline.projectId).toBe("proj-1");
|
||||
expect(outline.flatObservationCount).toBe(2);
|
||||
expect(outline.observations).toHaveLength(1);
|
||||
expect(outline.observations[0]?.id).toBe("obs-root");
|
||||
expect(outline.observations[0]?.children[0]?.id).toBe("obs-review");
|
||||
// Size-before-content: lengths instead of bodies.
|
||||
expect(outline.observations[0]?.outputLength).toBe(4);
|
||||
expect(JSON.stringify(outline)).not.toContain("解析完成");
|
||||
});
|
||||
|
||||
test("reading a missing observation or an uncached trace fails with exit 13 guidance", async () => {
|
||||
await seedCache();
|
||||
const service = new LangfuseService(CONFIG);
|
||||
|
||||
try {
|
||||
await service.getObservationIo({ traceId: "trace-1", observationId: "nope" });
|
||||
expect.unreachable("missing observation should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(13);
|
||||
}
|
||||
|
||||
try {
|
||||
await service.getTraceOutline({ traceId: "trace-other" });
|
||||
expect.unreachable("uncached trace should throw");
|
||||
} catch (error) {
|
||||
expect((error as CliError).exitCode).toBe(13);
|
||||
expect((error as CliError).message).toContain("seal-use langfuse cache-refresh");
|
||||
}
|
||||
});
|
||||
|
||||
test("jsonPath selects one nested value and maxChars truncates with a warning", async () => {
|
||||
await seedCache();
|
||||
const service = new LangfuseService(CONFIG);
|
||||
|
||||
const picked = await service.getObservationIo({
|
||||
traceId: "trace-1",
|
||||
observationId: "obs-root",
|
||||
fields: ["input"],
|
||||
jsonPath: "items[0].name"
|
||||
});
|
||||
// `input`/`output`/`metadata` are dynamic keys filled per requested field.
|
||||
expect((picked as Record<string, unknown>).input).toBe("invoice.pdf");
|
||||
|
||||
const long = sampleTrace();
|
||||
long.observations![1]!.output = "驳回理由".repeat(500);
|
||||
await new TraceCache({ baseUrl: CONFIG.baseUrl }).write("trace-1", long);
|
||||
|
||||
const truncated = await service.getObservationIo({
|
||||
traceId: "trace-1",
|
||||
observationId: "obs-review",
|
||||
maxChars: 200
|
||||
});
|
||||
expect((truncated.warnings ?? []).join(" ")).toContain("truncated");
|
||||
expect(String((truncated as Record<string, unknown>).output).length).toBeLessThan(2_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("qrep search", () => {
|
||||
test("ranks an observation output match above the trace-level name match", () => {
|
||||
const trace = sampleTrace();
|
||||
const results = searchTrace("proj-1", trace, ["驳回"], {
|
||||
maxResults: 10,
|
||||
contextChars: 50
|
||||
});
|
||||
|
||||
expect(results.length).toBeGreaterThanOrEqual(2);
|
||||
expect(results[0]?.observationId).toBe("obs-review");
|
||||
expect(results[0]?.field).toBe("output");
|
||||
expect(results[0]?.hierarchy.trace.id).toBe("trace-1");
|
||||
expect(results[0]?.context.match).toBe("驳回");
|
||||
expect(results.some((result) => result.observationId === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
test("filters by observation type and metadata", () => {
|
||||
const trace = sampleTrace();
|
||||
|
||||
const typed = searchTrace("proj-1", trace, "解析", {
|
||||
maxResults: 10,
|
||||
contextChars: 50,
|
||||
observationTypes: ["GENERATION"]
|
||||
});
|
||||
expect(typed.every((result) => result.observationType === "GENERATION" || result.observationId === undefined)).toBe(true);
|
||||
|
||||
const empty = searchTrace("proj-1", trace, "驳回", {
|
||||
maxResults: 10,
|
||||
contextChars: 50,
|
||||
metadata: { stage: "review" }
|
||||
});
|
||||
expect(empty).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,772 @@
|
||||
import { validationError } from "../../core/errors.js";
|
||||
import { LangfuseApi } from "./api.js";
|
||||
import { TraceCache } from "./cache.js";
|
||||
import type { LangfuseConfig } from "./config.js";
|
||||
import { LangfuseClient } from "./client.js";
|
||||
import { searchTrace, stringifyValue } from "./search.js";
|
||||
import type {
|
||||
AttachmentFlowInput,
|
||||
CachedTrace,
|
||||
LangfuseObservationSummary,
|
||||
LangfuseSearchResult,
|
||||
LangfuseTraceSummary,
|
||||
ObservationIoInput,
|
||||
ObservationsFindInput,
|
||||
ObservationOutlineNode,
|
||||
SearchInput,
|
||||
SessionOutlineInput,
|
||||
TraceCacheRefreshInput,
|
||||
TraceOutline,
|
||||
TraceOutlineInput,
|
||||
TraceRuleFlowInput,
|
||||
TraceUrlInput
|
||||
} from "./types.js";
|
||||
|
||||
const DEFAULT_MAX_RESULTS = 10;
|
||||
const DEFAULT_CONTEXT_CHARS = 120;
|
||||
const DEFAULT_IO_CHARS = 8_000;
|
||||
const DEFAULT_PREVIEW_CHARS = 160;
|
||||
const FULL_OUTPUT_WARNING_THRESHOLD = 30_000;
|
||||
const OUTLINE_FULL_FIELD_THRESHOLD = 20_000;
|
||||
const ATTACHMENT_STAGES = [
|
||||
"attachment parsing",
|
||||
"image/document understanding",
|
||||
"pre_analysis",
|
||||
"document_parsing",
|
||||
"approval_review"
|
||||
] as const;
|
||||
const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const;
|
||||
|
||||
/**
|
||||
* Read-only Langfuse trace service, ported from langfuse-home.
|
||||
*
|
||||
* The whole surface is cache-first by design (the "IO-last" workflow): fetch a
|
||||
* trace once via `refreshTraceCache`, then outline / search / observations /
|
||||
* flows read the local cache; `refreshIfMissing` opts into an on-demand fetch.
|
||||
* All output is size-before-content: summaries carry lengths, bytes, usage and
|
||||
* cost instead of bodies, previews middle-truncate, and oversized fields return
|
||||
* an actionable warning instead of a wall of text.
|
||||
*/
|
||||
export class LangfuseService {
|
||||
private readonly client: LangfuseClient;
|
||||
private readonly api: LangfuseApi;
|
||||
private readonly cache: TraceCache;
|
||||
|
||||
constructor(private readonly config: LangfuseConfig) {
|
||||
this.client = new LangfuseClient(config);
|
||||
this.api = new LangfuseApi(this.client);
|
||||
this.cache = new TraceCache({ baseUrl: config.baseUrl, projectId: config.projectId });
|
||||
}
|
||||
|
||||
async connectionCheck() {
|
||||
const projects = await this.api.getProject();
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
checkedPath: "/api/public/projects",
|
||||
projectId: this.config.projectId,
|
||||
baseUrl: this.config.baseUrl,
|
||||
projects
|
||||
};
|
||||
}
|
||||
|
||||
async refreshTraceCache(input: TraceCacheRefreshInput) {
|
||||
const trace = await this.api.getTrace(input.traceId);
|
||||
const cached = await this.cache.write(input.traceId, trace);
|
||||
|
||||
return {
|
||||
projectId: this.config.projectId,
|
||||
traceId: input.traceId,
|
||||
cache: {
|
||||
path: this.cache.path(input.traceId),
|
||||
exists: true,
|
||||
cachedAt: cached.cachedAt,
|
||||
refreshed: true
|
||||
},
|
||||
trace: summarizeTrace(trace),
|
||||
observationCount: trace.observations?.length ?? 0
|
||||
};
|
||||
}
|
||||
|
||||
async getTraceUrl(input: TraceUrlInput) {
|
||||
const cached = await this.cache.read(input.traceId);
|
||||
let source = "config";
|
||||
let traceProjectId = cached?.trace.projectId;
|
||||
let cachedAt = cached?.cachedAt;
|
||||
let refreshed = false;
|
||||
|
||||
if (traceProjectId) {
|
||||
source = "cache";
|
||||
} else {
|
||||
const trace = await this.api.getTrace(input.traceId, { fields: "core" });
|
||||
const refreshedCache = await this.cache.write(input.traceId, trace);
|
||||
traceProjectId = trace.projectId;
|
||||
cachedAt = refreshedCache.cachedAt;
|
||||
refreshed = true;
|
||||
source = traceProjectId ? "trace-api" : "config";
|
||||
}
|
||||
|
||||
const projectId = traceProjectId ?? this.config.projectId;
|
||||
if (!projectId) {
|
||||
throw validationError("Langfuse projectId is unknown: the trace carried none and no project was injected.");
|
||||
}
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
projectId,
|
||||
baseUrl: this.config.baseUrl,
|
||||
url: buildTraceUrl(this.config.baseUrl, projectId, input.traceId),
|
||||
source,
|
||||
cache: {
|
||||
path: this.cache.path(input.traceId),
|
||||
exists: Boolean(cached) || refreshed,
|
||||
cachedAt,
|
||||
refreshed
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async searchTrace(input: SearchInput): Promise<LangfuseSearchResult[]> {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
|
||||
if (input.sessionId && trace.sessionId !== input.sessionId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return searchTrace(this.projectIdFor(trace), trace, input.query, {
|
||||
maxResults: clamp(input.maxResults ?? DEFAULT_MAX_RESULTS, 1, 30),
|
||||
contextChars: clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500),
|
||||
fields: input.fields,
|
||||
observationTypes: input.observationTypes,
|
||||
metadata: input.metadata
|
||||
});
|
||||
}
|
||||
|
||||
async getTraceOutline(input: TraceOutlineInput): Promise<TraceOutline> {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
const maxPreviewChars = clamp(input.maxPreviewChars ?? DEFAULT_PREVIEW_CHARS, 20, 5_000);
|
||||
const includeInput = input.includeInput ?? input.includeIoPreview ?? false;
|
||||
const includeOutput = input.includeOutput ?? input.includeIoPreview ?? false;
|
||||
const warnings = buildOutlineWarnings(trace, includeInput, includeOutput, input.full ?? false);
|
||||
|
||||
return {
|
||||
projectId: this.projectIdFor(trace),
|
||||
trace: {
|
||||
id: trace.id,
|
||||
projectId: trace.projectId,
|
||||
name: trace.name,
|
||||
sessionId: trace.sessionId,
|
||||
userId: trace.userId,
|
||||
timestamp: trace.timestamp,
|
||||
environment: trace.environment,
|
||||
tags: trace.tags,
|
||||
inputPreview: includeInput
|
||||
? guardedPreview(trace.input, maxPreviewChars, input.full ?? false)
|
||||
: undefined,
|
||||
outputPreview: includeOutput
|
||||
? guardedPreview(trace.output, maxPreviewChars, input.full ?? false)
|
||||
: undefined,
|
||||
metadata: trace.metadata,
|
||||
latency: trace.latency,
|
||||
totalCost: trace.totalCost
|
||||
},
|
||||
observations: buildObservationTree(trace.observations ?? [], {
|
||||
includeInput,
|
||||
includeOutput,
|
||||
maxPreviewChars,
|
||||
full: input.full ?? false
|
||||
}),
|
||||
flatObservationCount: trace.observations?.length ?? 0,
|
||||
warnings: warnings.length ? warnings : undefined,
|
||||
cache: {
|
||||
path: this.cache.path(input.traceId),
|
||||
exists: true,
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async findObservations(input: ObservationsFindInput) {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const maxResults = clamp(input.maxResults ?? 50, 1, 200);
|
||||
const nameNeedle = input.nameContains?.toLowerCase();
|
||||
const typeNeedle = input.type?.toLowerCase();
|
||||
|
||||
const observations = (cached.trace.observations ?? []).filter((observation) => {
|
||||
if (nameNeedle && !observation.name?.toLowerCase().includes(nameNeedle)) return false;
|
||||
if (typeNeedle && observation.type?.toLowerCase() !== typeNeedle) return false;
|
||||
if (input.metadataKey && !objectKeys(observation.metadata).includes(input.metadataKey)) return false;
|
||||
if (input.hasInput !== undefined && hasValue(observation.input) !== input.hasInput) return false;
|
||||
if (input.hasOutput !== undefined && hasValue(observation.output) !== input.hasOutput) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
totalMatches: observations.length,
|
||||
observations: observations.slice(0, maxResults).map(summarizeObservation),
|
||||
truncated: observations.length > maxResults,
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async getSessionOutline(input: SessionOutlineInput) {
|
||||
const session = await this.api.getSession(input.sessionId);
|
||||
const traceLimit = clamp(input.traceLimit ?? 50, 1, 200);
|
||||
|
||||
return {
|
||||
projectId: session.projectId ?? this.config.projectId,
|
||||
session: {
|
||||
id: session.id,
|
||||
projectId: session.projectId,
|
||||
createdAt: session.createdAt
|
||||
},
|
||||
traces: (session.traces ?? []).slice(0, traceLimit).map(summarizeTrace),
|
||||
totalReturnedTraces: Math.min(session.traces?.length ?? 0, traceLimit),
|
||||
note: "Session outline uses the Langfuse session endpoint and returns compact trace summaries only."
|
||||
};
|
||||
}
|
||||
|
||||
async getObservationIo(input: ObservationIoInput) {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const observation = (cached.trace.observations ?? []).find(
|
||||
(candidate) => candidate.id === input.observationId
|
||||
);
|
||||
|
||||
if (!observation) {
|
||||
throw validationError(
|
||||
`Observation not found in cached trace: ${input.observationId}. Refresh the trace or check the observationId from outline/search.`
|
||||
);
|
||||
}
|
||||
|
||||
const maxChars = clamp(input.maxChars ?? DEFAULT_IO_CHARS, 100, input.full ? 500_000 : 30_000);
|
||||
const fields = input.fields?.length ? input.fields : (["input", "output"] as const);
|
||||
const path = input.jsonPath ?? input.path;
|
||||
const values: Record<string, unknown> = {};
|
||||
const warnings: string[] = [];
|
||||
|
||||
for (const field of fields) {
|
||||
const rawValue = observation[field];
|
||||
const selectedValue = path ? readPath(rawValue, path) : rawValue;
|
||||
const rendered = stringifyValue(selectedValue);
|
||||
const guarded = guardLargeText(rendered, maxChars, input.full ?? false);
|
||||
values[field] = guarded.value;
|
||||
if (guarded.warning) warnings.push(`${field}: ${guarded.warning}`);
|
||||
}
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
observationId: input.observationId,
|
||||
observation: summarizeObservation(observation),
|
||||
fields,
|
||||
path,
|
||||
...values,
|
||||
warnings: warnings.length ? warnings : undefined,
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async getAttachmentFlow(input: AttachmentFlowInput) {
|
||||
if (!input.fileId && !input.fileName && !input.contentHints?.length) {
|
||||
throw validationError("Provide at least one of fileId, fileName, or contentHints.");
|
||||
}
|
||||
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
const contextChars = clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500);
|
||||
const needles = [input.fileId, input.fileName, ...(input.contentHints ?? [])].filter(
|
||||
(value): value is string => Boolean(value?.trim())
|
||||
);
|
||||
const observations = trace.observations ?? [];
|
||||
const stages = ATTACHMENT_STAGES.map((stage) =>
|
||||
inspectAttachmentStage(stage, observations, needles, input.fileId, input.fileName, contextChars)
|
||||
);
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
fileId: input.fileId,
|
||||
fileName: input.fileName,
|
||||
contentHints: input.contentHints,
|
||||
stages,
|
||||
note:
|
||||
"Attachment flow is deterministic text evidence extraction from cached Langfuse fields. Source labels describe where the matched text appears to come from; they do not prove hidden model reasoning or semantic understanding.",
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async getTraceRuleFlow(input: TraceRuleFlowInput) {
|
||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||
const trace = cached.trace;
|
||||
const contextChars = clamp(input.contextChars ?? 300, 20, 500);
|
||||
const needles = uniqueStrings([input.rule, ...(input.ruleHints ?? [])]);
|
||||
const observations = trace.observations ?? [];
|
||||
const stageResults = RULE_FLOW_STAGES.map((stage) =>
|
||||
inspectRuleStage(stage, observations, needles, contextChars)
|
||||
);
|
||||
const allEvidence = stageResults.flatMap((stage) => stage.evidence);
|
||||
const relatedObservationIds = uniqueStrings(allEvidence.map((item) => item.observationId));
|
||||
|
||||
return {
|
||||
traceId: input.traceId,
|
||||
rule: input.rule,
|
||||
ruleHints: input.ruleHints,
|
||||
stages: {
|
||||
ruleMatching: stageResults[0],
|
||||
documentParsing: stageResults[1],
|
||||
finalReview: stageResults[2]
|
||||
},
|
||||
relatedObservationIds,
|
||||
evidenceCount: allEvidence.length,
|
||||
note:
|
||||
"Rule flow is deterministic text evidence extraction from cached Langfuse fields. It reports where the rule or hints appear; it does not infer hidden model reasoning or prove causality beyond the recorded trace text.",
|
||||
cache: {
|
||||
cachedAt: cached.cachedAt
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private projectIdFor(trace: LangfuseTraceSummary): string {
|
||||
return trace.projectId ?? this.config.projectId ?? "";
|
||||
}
|
||||
|
||||
private async getCachedTrace(traceId: string, refreshIfMissing: boolean): Promise<CachedTrace> {
|
||||
const cached = await this.cache.read(traceId);
|
||||
if (cached) return cached;
|
||||
|
||||
if (!refreshIfMissing) {
|
||||
throw validationError(
|
||||
`Trace cache missing for ${traceId}. Run "seal-use langfuse cache-refresh --traceId ${traceId}" first or pass --refresh-if-missing.`
|
||||
);
|
||||
}
|
||||
|
||||
const trace = await this.api.getTrace(traceId);
|
||||
return await this.cache.write(traceId, trace);
|
||||
}
|
||||
}
|
||||
|
||||
function buildObservationTree(
|
||||
observations: LangfuseObservationSummary[],
|
||||
options: {
|
||||
includeInput: boolean;
|
||||
includeOutput: boolean;
|
||||
maxPreviewChars: number;
|
||||
full: boolean;
|
||||
}
|
||||
): ObservationOutlineNode[] {
|
||||
const nodes = new Map<string, ObservationOutlineNode>();
|
||||
const roots: ObservationOutlineNode[] = [];
|
||||
|
||||
for (const observation of observations) {
|
||||
nodes.set(observation.id, {
|
||||
id: observation.id,
|
||||
parentObservationId: observation.parentObservationId,
|
||||
type: observation.type,
|
||||
name: observation.name,
|
||||
level: observation.level,
|
||||
startTime: observation.startTime,
|
||||
endTime: observation.endTime,
|
||||
latency: observation.latency,
|
||||
model: observation.providedModelName ?? observation.model,
|
||||
inputLength: stringifyValue(observation.input).length,
|
||||
outputLength: stringifyValue(observation.output).length,
|
||||
inputBytes: byteLength(stringifyValue(observation.input)),
|
||||
outputBytes: byteLength(stringifyValue(observation.output)),
|
||||
metadataKeys: objectKeys(observation.metadata),
|
||||
usageDetails: observation.usageDetails,
|
||||
costDetails: observation.costDetails,
|
||||
totalCost: observation.totalCost,
|
||||
inputPreview: options.includeInput
|
||||
? guardedPreview(observation.input, options.maxPreviewChars, options.full)
|
||||
: undefined,
|
||||
outputPreview: options.includeOutput
|
||||
? guardedPreview(observation.output, options.maxPreviewChars, options.full)
|
||||
: undefined,
|
||||
children: []
|
||||
});
|
||||
}
|
||||
|
||||
for (const observation of observations) {
|
||||
const node = nodes.get(observation.id);
|
||||
if (!node) continue;
|
||||
|
||||
const parent = observation.parentObservationId ? nodes.get(observation.parentObservationId) : undefined;
|
||||
if (parent) {
|
||||
parent.children.push(node);
|
||||
} else {
|
||||
roots.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
function buildOutlineWarnings(
|
||||
trace: LangfuseTraceSummary,
|
||||
includeInput: boolean,
|
||||
includeOutput: boolean,
|
||||
full: boolean
|
||||
): string[] {
|
||||
if (full) return [];
|
||||
const warnings: string[] = [];
|
||||
const check = (label: string, value: unknown) => {
|
||||
const length = stringifyValue(value).length;
|
||||
if (length > OUTLINE_FULL_FIELD_THRESHOLD) {
|
||||
warnings.push(
|
||||
`${label} is ${length} chars. Trace IO is large. Use --max-preview-chars, observationId, or search. Pass --full to request the full value.`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if (includeInput) check("trace.input", trace.input);
|
||||
if (includeOutput) check("trace.output", trace.output);
|
||||
|
||||
for (const observation of trace.observations ?? []) {
|
||||
if (includeInput) check(`observation.${observation.id}.input`, observation.input);
|
||||
if (includeOutput) check(`observation.${observation.id}.output`, observation.output);
|
||||
}
|
||||
|
||||
return warnings.slice(0, 20);
|
||||
}
|
||||
|
||||
function summarizeTrace(trace: LangfuseTraceSummary) {
|
||||
return {
|
||||
id: trace.id,
|
||||
name: trace.name,
|
||||
projectId: trace.projectId,
|
||||
sessionId: trace.sessionId,
|
||||
userId: trace.userId,
|
||||
timestamp: trace.timestamp,
|
||||
environment: trace.environment,
|
||||
tags: trace.tags,
|
||||
inputLength: stringifyValue(trace.input).length,
|
||||
outputLength: stringifyValue(trace.output).length,
|
||||
metadata: trace.metadata,
|
||||
latency: trace.latency,
|
||||
totalCost: trace.totalCost
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeObservation(observation: LangfuseObservationSummary) {
|
||||
return {
|
||||
id: observation.id,
|
||||
traceId: observation.traceId,
|
||||
parentObservationId: observation.parentObservationId,
|
||||
type: observation.type,
|
||||
name: observation.name,
|
||||
startTime: observation.startTime,
|
||||
endTime: observation.endTime,
|
||||
model: observation.providedModelName ?? observation.model,
|
||||
inputLength: stringifyValue(observation.input).length,
|
||||
outputLength: stringifyValue(observation.output).length,
|
||||
inputBytes: byteLength(stringifyValue(observation.input)),
|
||||
outputBytes: byteLength(stringifyValue(observation.output)),
|
||||
metadataKeys: objectKeys(observation.metadata),
|
||||
usageDetails: observation.usageDetails,
|
||||
costDetails: observation.costDetails,
|
||||
totalCost: observation.totalCost
|
||||
};
|
||||
}
|
||||
|
||||
function buildTraceUrl(baseUrl: string, projectId: string, traceId: string): string {
|
||||
const url = new URL(
|
||||
`/project/${encodeURIComponent(projectId)}/traces/${encodeURIComponent(traceId)}`,
|
||||
baseUrl
|
||||
);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function guardedPreview(value: unknown, maxChars: number, full: boolean): string | undefined {
|
||||
const text = stringifyValue(value);
|
||||
if (!text) return undefined;
|
||||
if (!full && text.length > OUTLINE_FULL_FIELD_THRESHOLD && maxChars >= text.length) {
|
||||
return "Trace IO is large. Use maxPreviewChars, observationId, or search. Pass full=true to request the full value.";
|
||||
}
|
||||
return full ? text : truncateMiddle(text, maxChars);
|
||||
}
|
||||
|
||||
function guardLargeText(text: string, maxChars: number, full: boolean): { value: string; warning?: string } {
|
||||
if (!text) return { value: "" };
|
||||
if (!full && text.length > FULL_OUTPUT_WARNING_THRESHOLD && maxChars >= text.length) {
|
||||
return {
|
||||
value: truncateMiddle(text, DEFAULT_IO_CHARS),
|
||||
warning:
|
||||
"Trace IO is large. Use maxChars, observationId, fields, jsonPath/path, or search. Pass full=true to request more."
|
||||
};
|
||||
}
|
||||
if (!full && text.length > maxChars) {
|
||||
return {
|
||||
value: truncateMiddle(text, maxChars),
|
||||
warning: `Value truncated from ${text.length} chars to ${maxChars} chars. Pass full=true to request more.`
|
||||
};
|
||||
}
|
||||
return { value: text };
|
||||
}
|
||||
|
||||
function readPath(value: unknown, path: string): unknown {
|
||||
const segments = parsePath(path);
|
||||
let current = value;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (current === undefined || current === null) return undefined;
|
||||
if (typeof segment === "number") {
|
||||
current = Array.isArray(current) ? current[segment] : undefined;
|
||||
continue;
|
||||
}
|
||||
if (typeof current !== "object") return undefined;
|
||||
current = (current as Record<string, unknown>)[segment];
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
function parsePath(path: string): Array<string | number> {
|
||||
const normalized = path
|
||||
.trim()
|
||||
.replace(/^\$\.?/, "")
|
||||
.replace(/^(input|output|metadata)\.?/, "");
|
||||
if (!normalized) return [];
|
||||
|
||||
const segments: Array<string | number> = [];
|
||||
for (const part of normalized.split(".")) {
|
||||
const matches = part.matchAll(/([^[\]]+)|\[(\d+)\]/g);
|
||||
for (const match of matches) {
|
||||
if (match[1]) segments.push(match[1]);
|
||||
if (match[2]) segments.push(Number(match[2]));
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
function inspectAttachmentStage(
|
||||
stage: (typeof ATTACHMENT_STAGES)[number],
|
||||
observations: LangfuseObservationSummary[],
|
||||
needles: string[],
|
||||
fileId: string | undefined,
|
||||
fileName: string | undefined,
|
||||
contextChars: number
|
||||
) {
|
||||
const stageTerms = stageSearchTerms(stage);
|
||||
const candidates = observations.filter((observation) => {
|
||||
const name = observation.name?.toLowerCase() ?? "";
|
||||
return stageTerms.some((term) => name.includes(term));
|
||||
});
|
||||
const evidence = candidates.flatMap((observation) =>
|
||||
collectAttachmentEvidence(observation, needles, contextChars)
|
||||
);
|
||||
const source = classifyAttachmentEvidence(evidence, fileId, fileName);
|
||||
|
||||
return {
|
||||
stage,
|
||||
source,
|
||||
status: source === "absent" ? "absent" : "seen",
|
||||
observations: candidates.map(summarizeObservation),
|
||||
evidence
|
||||
};
|
||||
}
|
||||
|
||||
function stageSearchTerms(stage: (typeof ATTACHMENT_STAGES)[number]): string[] {
|
||||
switch (stage) {
|
||||
case "attachment parsing":
|
||||
return ["attachment", "附件", "parse_attachment", "attachment_parsing"];
|
||||
case "image/document understanding":
|
||||
return ["understanding", "vision", "image", "document_understanding", "文档理解", "图片理解"];
|
||||
case "pre_analysis":
|
||||
return ["pre_analysis", "pre-analysis", "预分析"];
|
||||
case "document_parsing":
|
||||
return ["document_parsing", "document parsing", "文档解析"];
|
||||
case "approval_review":
|
||||
return ["approval_review", "approval review", "审核"];
|
||||
}
|
||||
}
|
||||
|
||||
function collectAttachmentEvidence(
|
||||
observation: LangfuseObservationSummary,
|
||||
needles: string[],
|
||||
contextChars: number
|
||||
): Array<{
|
||||
observationId: string;
|
||||
name?: string;
|
||||
field: "input" | "output" | "metadata";
|
||||
matched: string;
|
||||
snippet: string;
|
||||
}> {
|
||||
const fields = [
|
||||
["input", stringifyValue(observation.input)],
|
||||
["output", stringifyValue(observation.output)],
|
||||
["metadata", stringifyValue(observation.metadata)]
|
||||
] as const;
|
||||
const evidence: ReturnType<typeof collectAttachmentEvidence> = [];
|
||||
|
||||
for (const [field, text] of fields) {
|
||||
const normalized = text.toLowerCase();
|
||||
for (const needle of needles) {
|
||||
const index = normalized.indexOf(needle.toLowerCase());
|
||||
if (index < 0) continue;
|
||||
evidence.push({
|
||||
observationId: observation.id,
|
||||
name: observation.name,
|
||||
field,
|
||||
matched: text.slice(index, index + needle.length),
|
||||
snippet: text.slice(
|
||||
Math.max(0, index - contextChars),
|
||||
Math.min(text.length, index + needle.length + contextChars)
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return evidence.slice(0, 10);
|
||||
}
|
||||
|
||||
function classifyAttachmentEvidence(
|
||||
evidence: Array<{ matched: string; snippet: string; field?: string }>,
|
||||
fileId: string | undefined,
|
||||
fileName: string | undefined
|
||||
): "filename-only" | "file-id-only" | "parsed-text" | "image-ocr" | "model-inferred" | "absent" | "unknown" {
|
||||
if (evidence.length === 0) return "absent";
|
||||
const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false;
|
||||
const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false;
|
||||
const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName);
|
||||
if (hasOtherHint) {
|
||||
const joined = evidence
|
||||
.map((item) => item.snippet)
|
||||
.join("\n")
|
||||
.toLowerCase();
|
||||
if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr";
|
||||
if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred";
|
||||
return "parsed-text";
|
||||
}
|
||||
if (hasFileName && !hasOtherHint) return "filename-only";
|
||||
if (hasFileId && !hasOtherHint) return "file-id-only";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function inspectRuleStage(
|
||||
stage: (typeof RULE_FLOW_STAGES)[number],
|
||||
observations: LangfuseObservationSummary[],
|
||||
needles: string[],
|
||||
contextChars: number
|
||||
) {
|
||||
const stageTerms = ruleStageSearchTerms(stage);
|
||||
const candidates = observations.filter((observation) => {
|
||||
const name = observation.name?.toLowerCase() ?? "";
|
||||
return stageTerms.some((term) => name.includes(term));
|
||||
});
|
||||
const candidatePool = candidates.length ? candidates : observations;
|
||||
const evidence = candidatePool
|
||||
.flatMap((observation) => collectRuleEvidence(observation, needles, contextChars))
|
||||
.slice(0, 20);
|
||||
const matchedObservationIds = uniqueStrings(evidence.map((item) => item.observationId));
|
||||
|
||||
return {
|
||||
stage,
|
||||
matched: evidence.length > 0,
|
||||
matchedObservationIds,
|
||||
observations: candidates.map(summarizeObservation),
|
||||
extractedFields: summarizeEvidenceFields(evidence),
|
||||
evidence
|
||||
};
|
||||
}
|
||||
|
||||
function ruleStageSearchTerms(stage: (typeof RULE_FLOW_STAGES)[number]): string[] {
|
||||
switch (stage) {
|
||||
case "rule matching":
|
||||
return ["rule", "规则", "policy", "match", "matching", "命中"];
|
||||
case "document parsing":
|
||||
return ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"];
|
||||
case "final review":
|
||||
return ["approval_review", "approval review", "review", "审核", "结论", "final"];
|
||||
}
|
||||
}
|
||||
|
||||
function collectRuleEvidence(
|
||||
observation: LangfuseObservationSummary,
|
||||
needles: string[],
|
||||
contextChars: number
|
||||
): Array<{
|
||||
observationId: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
field: "input" | "output" | "metadata";
|
||||
matched: string;
|
||||
snippet: string;
|
||||
}> {
|
||||
const fields = [
|
||||
["input", stringifyValue(observation.input)],
|
||||
["output", stringifyValue(observation.output)],
|
||||
["metadata", stringifyValue(observation.metadata)]
|
||||
] as const;
|
||||
const evidence: ReturnType<typeof collectRuleEvidence> = [];
|
||||
|
||||
for (const [field, text] of fields) {
|
||||
const normalized = text.toLowerCase();
|
||||
for (const needle of needles) {
|
||||
const index = normalized.indexOf(needle.toLowerCase());
|
||||
if (index < 0) continue;
|
||||
evidence.push({
|
||||
observationId: observation.id,
|
||||
name: observation.name,
|
||||
type: observation.type,
|
||||
field,
|
||||
matched: text.slice(index, index + needle.length),
|
||||
snippet: text.slice(
|
||||
Math.max(0, index - contextChars),
|
||||
Math.min(text.length, index + needle.length + contextChars)
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return evidence;
|
||||
}
|
||||
|
||||
function summarizeEvidenceFields(
|
||||
evidence: Array<{ field: "input" | "output" | "metadata"; matched: string }>
|
||||
): Record<string, { count: number; matched: string[] }> {
|
||||
const summary: Record<string, { count: number; matched: string[] }> = {};
|
||||
for (const item of evidence) {
|
||||
const entry = summary[item.field];
|
||||
if (entry) {
|
||||
entry.count += 1;
|
||||
if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched);
|
||||
} else {
|
||||
summary[item.field] = { count: 1, matched: [item.matched] };
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
function uniqueStrings(values: Array<string | undefined>): string[] {
|
||||
return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))];
|
||||
}
|
||||
|
||||
function hasValue(value: unknown): boolean {
|
||||
return stringifyValue(value).length > 0;
|
||||
}
|
||||
|
||||
function truncateMiddle(text: string, maxChars: number): string {
|
||||
if (text.length <= maxChars) return text;
|
||||
const head = Math.floor((maxChars - 20) / 2);
|
||||
const tail = Math.max(0, maxChars - 20 - head);
|
||||
return `${text.slice(0, head)}\n...<truncated>...\n${text.slice(text.length - tail)}`;
|
||||
}
|
||||
|
||||
function objectKeys(value: unknown): string[] {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
|
||||
}
|
||||
|
||||
function byteLength(value: string): number {
|
||||
return Buffer.byteLength(value, "utf8");
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.max(min, Math.min(max, value));
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// Ported from langfuse-home (`src/domains/langfuse/types.ts`), adapted to the
|
||||
// single-project seal-use domain: per-input `projectKey`/`projectId` lookups are
|
||||
// gone (one injected project), and compat-only inputs were dropped.
|
||||
|
||||
export type SearchInput = {
|
||||
query: string | string[];
|
||||
traceId: string;
|
||||
sessionId?: string;
|
||||
fields?: SearchField[];
|
||||
observationTypes?: string[];
|
||||
metadata?: Record<string, string | number | boolean>;
|
||||
maxResults?: number;
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type TraceOutlineInput = {
|
||||
traceId: string;
|
||||
includeIoPreview?: boolean;
|
||||
includeInput?: boolean;
|
||||
includeOutput?: boolean;
|
||||
full?: boolean;
|
||||
maxPreviewChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type SessionOutlineInput = {
|
||||
sessionId: string;
|
||||
traceLimit?: number;
|
||||
};
|
||||
|
||||
export type ObservationIoInput = {
|
||||
traceId: string;
|
||||
observationId: string;
|
||||
fields?: ObservationIoField[];
|
||||
maxChars?: number;
|
||||
full?: boolean;
|
||||
jsonPath?: string;
|
||||
path?: string;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type ObservationIoField = "input" | "output" | "metadata";
|
||||
|
||||
export type ObservationsFindInput = {
|
||||
traceId: string;
|
||||
nameContains?: string;
|
||||
type?: string;
|
||||
metadataKey?: string;
|
||||
hasInput?: boolean;
|
||||
hasOutput?: boolean;
|
||||
maxResults?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type AttachmentFlowInput = {
|
||||
traceId: string;
|
||||
fileId?: string;
|
||||
fileName?: string;
|
||||
contentHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type TraceRuleFlowInput = {
|
||||
traceId: string;
|
||||
rule: string;
|
||||
ruleHints?: string[];
|
||||
contextChars?: number;
|
||||
refreshIfMissing?: boolean;
|
||||
};
|
||||
|
||||
export type TraceCacheRefreshInput = {
|
||||
traceId: string;
|
||||
};
|
||||
|
||||
export type TraceUrlInput = {
|
||||
traceId: string;
|
||||
};
|
||||
|
||||
export type SearchField = "name" | "input" | "output" | "metadata" | "userId" | "sessionId";
|
||||
|
||||
export type LangfuseSearchResult = {
|
||||
projectId: string;
|
||||
sessionId?: string;
|
||||
traceId: string;
|
||||
traceName?: string;
|
||||
timestamp?: string;
|
||||
path: string[];
|
||||
observationId?: string;
|
||||
observationName?: string;
|
||||
observationType?: string;
|
||||
field: SearchField;
|
||||
snippet: string;
|
||||
matchedField: string;
|
||||
matchedText: string;
|
||||
context: {
|
||||
before: string;
|
||||
match: string;
|
||||
after: string;
|
||||
};
|
||||
hierarchy: {
|
||||
session?: {
|
||||
id: string;
|
||||
};
|
||||
trace: {
|
||||
id: string;
|
||||
name?: string;
|
||||
userId?: string;
|
||||
};
|
||||
observation?: {
|
||||
id: string;
|
||||
type?: string;
|
||||
name?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
export type LangfuseTraceSummary = {
|
||||
id: string;
|
||||
name?: string;
|
||||
projectId?: string;
|
||||
environment?: string;
|
||||
tags?: string[];
|
||||
sessionId?: string;
|
||||
userId?: string;
|
||||
timestamp?: string;
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
metadata?: unknown;
|
||||
latency?: number;
|
||||
totalCost?: number;
|
||||
observations?: LangfuseObservationSummary[];
|
||||
scores?: unknown[];
|
||||
};
|
||||
|
||||
export type LangfuseObservationSummary = {
|
||||
id: string;
|
||||
traceId: string;
|
||||
parentObservationId?: string;
|
||||
type?: string;
|
||||
name?: string;
|
||||
level?: string;
|
||||
statusMessage?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
metadata?: unknown;
|
||||
environment?: string;
|
||||
userId?: string;
|
||||
sessionId?: string;
|
||||
traceName?: string;
|
||||
providedModelName?: string;
|
||||
model?: string;
|
||||
modelParameters?: unknown;
|
||||
usageDetails?: Record<string, unknown>;
|
||||
costDetails?: Record<string, unknown>;
|
||||
totalCost?: number;
|
||||
latency?: number;
|
||||
timeToFirstToken?: number;
|
||||
promptId?: string;
|
||||
promptName?: string;
|
||||
promptVersion?: number;
|
||||
};
|
||||
|
||||
export type LangfuseProject = {
|
||||
id: string;
|
||||
name: string;
|
||||
organization: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
metadata?: Record<string, unknown>;
|
||||
retentionDays?: number | null;
|
||||
};
|
||||
|
||||
export type LangfuseSession = {
|
||||
id: string;
|
||||
projectId?: string;
|
||||
createdAt?: string;
|
||||
traces?: LangfuseTraceSummary[];
|
||||
};
|
||||
|
||||
export type ObservationOutlineNode = {
|
||||
id: string;
|
||||
parentObservationId?: string;
|
||||
type?: string;
|
||||
name?: string;
|
||||
level?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
latency?: number;
|
||||
model?: string;
|
||||
inputLength: number;
|
||||
outputLength: number;
|
||||
inputBytes: number;
|
||||
outputBytes: number;
|
||||
metadataKeys: string[];
|
||||
usageDetails?: Record<string, unknown>;
|
||||
costDetails?: Record<string, unknown>;
|
||||
totalCost?: number;
|
||||
inputPreview?: string;
|
||||
outputPreview?: string;
|
||||
children: ObservationOutlineNode[];
|
||||
};
|
||||
|
||||
export type TraceOutline = {
|
||||
projectId: string;
|
||||
trace: {
|
||||
id: string;
|
||||
projectId?: string;
|
||||
name?: string;
|
||||
sessionId?: string;
|
||||
userId?: string;
|
||||
timestamp?: string;
|
||||
environment?: string;
|
||||
tags?: string[];
|
||||
inputPreview?: string;
|
||||
outputPreview?: string;
|
||||
metadata?: unknown;
|
||||
latency?: number;
|
||||
totalCost?: number;
|
||||
};
|
||||
observations: ObservationOutlineNode[];
|
||||
flatObservationCount: number;
|
||||
warnings?: string[];
|
||||
cache?: TraceCacheInfo;
|
||||
};
|
||||
|
||||
export type CachedTrace = {
|
||||
cacheVersion: 1;
|
||||
cachedAt: string;
|
||||
project: {
|
||||
key: string;
|
||||
projectId: string;
|
||||
baseUrl: string;
|
||||
};
|
||||
trace: LangfuseTraceSummary;
|
||||
};
|
||||
|
||||
export type TraceCacheInfo = {
|
||||
path: string;
|
||||
exists: boolean;
|
||||
cachedAt?: string;
|
||||
refreshed?: boolean;
|
||||
};
|
||||
@@ -891,6 +891,11 @@ export function findKeywordLines(text: string, keywords: string[], limit: number
|
||||
export function summarizeRunBridge(records: ApprovalRun[]) {
|
||||
return records.map((record) => {
|
||||
const summary = summarizeApprovalRun(record);
|
||||
const resolution = summary.langfuseTraceId
|
||||
? "trace"
|
||||
: summary.langfuseSessionFallback
|
||||
? "session-fallback"
|
||||
: "unresolved";
|
||||
return {
|
||||
recordId: summary.id,
|
||||
tenantId: summary.tenantId,
|
||||
@@ -903,12 +908,13 @@ export function summarizeRunBridge(records: ApprovalRun[]) {
|
||||
ruleSetVersionNumber: summary.ruleSetVersionNumber,
|
||||
ruleSetPublishedAt: summary.ruleSetPublishedAt,
|
||||
ruleSetPublishedByName: summary.ruleSetPublishedByName,
|
||||
resolution:
|
||||
summary.langfuseTraceId
|
||||
? "trace"
|
||||
: summary.langfuseSessionFallback
|
||||
? "session-fallback"
|
||||
: "unresolved"
|
||||
resolution,
|
||||
// Ready-to-run handoff into the built-in read-only Langfuse domain.
|
||||
...(summary.langfuseTraceId
|
||||
? { next: `seal-use langfuse outline ${summary.langfuseTraceId} --include-io-preview` }
|
||||
: summary.langfuseSessionFallback
|
||||
? { next: `seal-use langfuse session ${summary.langfuseSessionFallback}` }
|
||||
: {})
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { approvalRunsCapabilities } from "./approval-runs.js";
|
||||
import { simulationCapabilities } from "./simulation.js";
|
||||
import { deployCapabilities } from "./deploy.js";
|
||||
import { preferenceCapabilities } from "./preference.js";
|
||||
import { reportCapabilities } from "./reports.js";
|
||||
|
||||
export * from "./helpers.js";
|
||||
export * from "./validate.js";
|
||||
@@ -22,7 +23,8 @@ export const sealCapabilities = [
|
||||
...approvalRunsCapabilities,
|
||||
...simulationCapabilities,
|
||||
...deployCapabilities,
|
||||
...preferenceCapabilities
|
||||
...preferenceCapabilities,
|
||||
...reportCapabilities
|
||||
];
|
||||
|
||||
export type SealCapability = (typeof sealCapabilities)[number];
|
||||
@@ -99,6 +101,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
|
||||
"sealPermissionsConfigsList",
|
||||
"sealPreferenceGet",
|
||||
"sealPreferenceThinkingDepthPoliciesList",
|
||||
"sealReportMonthlyGet",
|
||||
"sealSessionGet",
|
||||
"sealSimulationBatchGet",
|
||||
"sealSimulationBatchRecordsGet",
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { buildMonthlyReport } from "../reports/monthly.js";
|
||||
import type { CapabilityContext } from "./helpers.js";
|
||||
|
||||
export const reportCapabilities = [
|
||||
{
|
||||
name: "sealReportMonthlyGet",
|
||||
description:
|
||||
"生成月度 AI 审核准确率报告(Markdown)。按模板结构从效能/风险/审批运行接口取数填充,返回填充后的内容与各章节数据完备度;无法从上游取得的口径(人工准确率、失准原因分类)如实标注而非编造",
|
||||
parameters: z.object({
|
||||
month: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}$/)
|
||||
.describe("统计月份,YYYY-MM"),
|
||||
templatePath: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("自定义模板 Markdown 路径;缺省用 report-templates/monthly.md"),
|
||||
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
|
||||
maxRuns: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(500)
|
||||
.optional()
|
||||
.describe("拉取审批运行明细分块的上限,默认 500")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { month: string; templatePath?: string; reportId?: string; maxRuns?: number },
|
||||
context: CapabilityContext
|
||||
) =>
|
||||
buildMonthlyReport(client, {
|
||||
month: params.month,
|
||||
corp: { id: context.corp.id, name: context.corp.name },
|
||||
templatePath: params.templatePath,
|
||||
reportId: params.reportId,
|
||||
maxRuns: params.maxRuns
|
||||
})
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,311 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "../api.js";
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import type { ApprovalRun } from "../types.js";
|
||||
import type { ReportDemand } from "./describe.js";
|
||||
import { loadReviews, type ReviewRecord } from "./review-store.js";
|
||||
|
||||
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
|
||||
type Polarity = "pass" | "reject" | "unknown";
|
||||
|
||||
function polarityOf(value: string | undefined): Polarity {
|
||||
if (!value) return "unknown";
|
||||
const text = value.trim();
|
||||
if (/同意|通过|approve|pass/i.test(text)) return "pass";
|
||||
if (/驳回|拒绝|终止|退回|reject|deny/i.test(text)) return "reject";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export type ReportBlock = {
|
||||
sn: string;
|
||||
template: string;
|
||||
aiDecision: string | undefined;
|
||||
humanResult: string | undefined;
|
||||
agreement: "agreed" | "diverged" | "unknown";
|
||||
aiSummary: string | undefined;
|
||||
humanComment: string | undefined;
|
||||
/** 本地人工裁决结论(若该 SN 已 review),来自 review-store */
|
||||
verdict?: ReviewRecord["verdict"];
|
||||
};
|
||||
|
||||
export type ReportTemplateGroup = {
|
||||
template: string;
|
||||
total: number;
|
||||
agreed: number;
|
||||
diverged: number;
|
||||
};
|
||||
|
||||
export type ReportData = {
|
||||
/** 报告信息表要用的上下文 */
|
||||
period: { start: string; end: string; month: string };
|
||||
corp: { id: string; name: string };
|
||||
/** 需求 → 是否已按需取数(渲染器据此判断该章节数据完备度) */
|
||||
fetched: Record<ReportDemand, boolean>;
|
||||
performance?: {
|
||||
approvalCount?: number;
|
||||
accuracy?: number;
|
||||
accuracyTrend?: number;
|
||||
automationRate?: number;
|
||||
riskCount?: number;
|
||||
/** 平均耗时(秒);上游给秒就传秒 */
|
||||
avgDurationSeconds?: number;
|
||||
sankey: { nodes: Array<{ id: string }>; links: Array<{ source: string; target: string; value: number }> };
|
||||
};
|
||||
riskStats?: {
|
||||
tags: Array<{ id?: string; name?: string; count?: number }>;
|
||||
};
|
||||
blocks: ReportBlock[];
|
||||
templateGroups: ReportTemplateGroup[];
|
||||
/** 该租户该月的人工裁决(SN → 记录),由 review-store 载入,用于回填人工准确率 */
|
||||
reviews: Map<string, ReviewRecord>;
|
||||
/** 人工审核准确率(%):仅当本地裁决覆盖样本时有值 */
|
||||
humanAccuracy?: number;
|
||||
/** 章节数据完备性标记,渲染时逐节如实写入 */
|
||||
notes: {
|
||||
/** 人工准确率是否可得(有本地裁决) */
|
||||
humanAccuracyAvailable: boolean;
|
||||
failureRateAvailable: boolean;
|
||||
mismatchCategoriesAvailable: boolean;
|
||||
/** 裁决样本数 / 分歧样本数,供报告如实说明覆盖度 */
|
||||
reviewedCount?: number;
|
||||
divergedCount?: number;
|
||||
};
|
||||
};
|
||||
|
||||
export type CollectOptions = {
|
||||
month: string; // YYYY-MM
|
||||
corp: { id: string; name: string };
|
||||
/** 用于拉明细分块的上限,防御性封顶 */
|
||||
maxRuns?: number;
|
||||
/** 是否载入本地人工裁决(默认载入);关掉则 humanAccuracy 恒为不可得 */
|
||||
loadReviews?: boolean;
|
||||
};
|
||||
|
||||
function monthRange(month: string): { startDate: string; endDate: string } {
|
||||
const [y, m] = month.split("-").map(Number);
|
||||
if (!y || !m) throw new Error(`Invalid month "${month}", expected YYYY-MM`);
|
||||
const start = Date.UTC(y, m - 1, 1);
|
||||
const end = Date.UTC(y, m, 1) - 1;
|
||||
return { startDate: String(start), endDate: String(end) };
|
||||
}
|
||||
|
||||
/** 拉取报告所需数据。只取 demand 需要的部分,模板没提到的章节不发请求。 */
|
||||
export async function collectReportData(
|
||||
client: KyInstance,
|
||||
demands: Set<ReportDemand>,
|
||||
options: CollectOptions
|
||||
): Promise<ReportData> {
|
||||
const range = monthRange(options.month);
|
||||
const maxRuns = Math.min(options.maxRuns ?? 500, 500);
|
||||
const fetched: Record<ReportDemand, boolean> = {
|
||||
performance: false,
|
||||
riskStats: false,
|
||||
riskDetails: false,
|
||||
blocks: false,
|
||||
templateGroups: false
|
||||
};
|
||||
|
||||
const data: ReportData = {
|
||||
period: {
|
||||
start: formatBeijingIso(Number(range.startDate)),
|
||||
end: formatBeijingIso(Number(range.endDate)),
|
||||
month: options.month
|
||||
},
|
||||
corp: options.corp,
|
||||
fetched,
|
||||
blocks: [],
|
||||
templateGroups: [],
|
||||
reviews: options.loadReviews === false
|
||||
? new Map()
|
||||
: loadReviews(options.corp.id, options.month),
|
||||
notes: {
|
||||
humanAccuracyAvailable: false,
|
||||
failureRateAvailable: false,
|
||||
mismatchCategoriesAvailable: false
|
||||
}
|
||||
};
|
||||
|
||||
// 1. 效能指标(§1 / §4)
|
||||
if (demands.has("performance")) {
|
||||
try {
|
||||
const perf = await api.getInsightPerformance(client, {
|
||||
startDate: range.startDate,
|
||||
endDate: range.endDate
|
||||
});
|
||||
const metrics = (perf.metrics ?? {}) as Record<string, { value?: number; trend?: number } | undefined>;
|
||||
data.performance = {
|
||||
approvalCount: metrics.approvalCount?.value,
|
||||
accuracy: metrics.accuracy?.value,
|
||||
accuracyTrend: metrics.accuracy?.trend,
|
||||
automationRate: metrics.automationRate?.value,
|
||||
riskCount: metrics.riskCount?.value,
|
||||
avgDurationSeconds: metrics.avgDuration?.value,
|
||||
sankey: perf.sankeyData ?? { nodes: [], links: [] }
|
||||
};
|
||||
fetched.performance = true;
|
||||
} catch {
|
||||
// 指标接口不可达:章节保持模板原文并在填充时标注数据未取到
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 风险标签统计(§3 / §4 风险拦截)
|
||||
if (demands.has("riskStats") || demands.has("riskDetails")) {
|
||||
try {
|
||||
const stats = await api.getInsightStats(client, {
|
||||
startDate: range.startDate,
|
||||
endDate: range.endDate,
|
||||
limit: 50
|
||||
});
|
||||
const rawList = ((stats as { tags?: unknown }).tags ?? (stats as { list?: unknown }).list ?? []) as Array<Record<string, unknown>>;
|
||||
data.riskStats = {
|
||||
tags: rawList.slice(0, 20).map((tag) => ({
|
||||
id: typeof tag.id === "string" ? tag.id : undefined,
|
||||
name: typeof tag.name === "string" ? tag.name : typeof tag.title === "string" ? tag.title : undefined,
|
||||
count: typeof tag.count === "number" ? tag.count : typeof tag.value === "number" ? tag.value : undefined
|
||||
}))
|
||||
};
|
||||
fetched.riskStats = true;
|
||||
fetched.riskDetails = data.riskStats.tags.length > 0;
|
||||
} catch {
|
||||
// 风险统计不可达
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 决策分块(§2 / §5 / §6)与分模板统计(§7.1)
|
||||
if (demands.has("blocks") || demands.has("templateGroups")) {
|
||||
const runs: ApprovalRun[] = [];
|
||||
let offset = 0;
|
||||
try {
|
||||
while (runs.length < maxRuns) {
|
||||
const page = await api.listApprovalRuns(client, {
|
||||
offset,
|
||||
limit: 100,
|
||||
startDate: range.startDate,
|
||||
endDate: range.endDate
|
||||
});
|
||||
const records = page.records ?? [];
|
||||
if (!records.length) break;
|
||||
runs.push(...records);
|
||||
offset += records.length;
|
||||
if (records.length < 100) break;
|
||||
}
|
||||
|
||||
const blocks: ReportBlock[] = runs.map((record) => {
|
||||
const summary = summarizeLocal(record);
|
||||
const aiPolarity = polarityOf(summary.aiDecision);
|
||||
const humanPolarity = polarityOf(summary.humanResult);
|
||||
const agreement =
|
||||
aiPolarity === "unknown" || humanPolarity === "unknown"
|
||||
? "unknown"
|
||||
: aiPolarity === humanPolarity
|
||||
? "agreed"
|
||||
: "diverged";
|
||||
return {
|
||||
sn: summary.sn ?? summary.id,
|
||||
template: summary.template,
|
||||
aiDecision: summary.aiDecision,
|
||||
humanResult: summary.humanResult,
|
||||
agreement,
|
||||
aiSummary: summary.aiSummary,
|
||||
humanComment: summary.humanComment
|
||||
};
|
||||
});
|
||||
data.blocks = blocks;
|
||||
fetched.blocks = true;
|
||||
|
||||
if (demands.has("templateGroups")) {
|
||||
const byTemplate = new Map<string, ReportTemplateGroup>();
|
||||
for (const block of blocks) {
|
||||
const key = block.template || "未标注模板";
|
||||
const group = byTemplate.get(key) ?? { template: key, total: 0, agreed: 0, diverged: 0 };
|
||||
group.total += 1;
|
||||
if (block.agreement === "agreed") group.agreed += 1;
|
||||
if (block.agreement === "diverged") group.diverged += 1;
|
||||
byTemplate.set(key, group);
|
||||
}
|
||||
data.templateGroups = [...byTemplate.values()].sort((a, b) => b.total - a.total);
|
||||
fetched.templateGroups = true;
|
||||
}
|
||||
} catch {
|
||||
// 分块拉取失败:章节保持模板原文
|
||||
}
|
||||
}
|
||||
|
||||
data.notes.failureRateAvailable = data.performance !== undefined;
|
||||
data.notes.mismatchCategoriesAvailable = false; // 失准原因分类无上游字段,需人工归类
|
||||
|
||||
// 3. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率
|
||||
if (data.reviews.size > 0) {
|
||||
let reviewed = 0;
|
||||
let diverged = 0;
|
||||
let aiRight = 0;
|
||||
let humanRight = 0;
|
||||
for (const block of data.blocks) {
|
||||
const review = data.reviews.get(block.sn);
|
||||
if (review) {
|
||||
block.verdict = review.verdict;
|
||||
reviewed += 1;
|
||||
if (block.agreement === "diverged") diverged += 1;
|
||||
// 人工正确:human_correct 或 both_correct;AI 正确:ai_correct 或 both_correct
|
||||
if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1;
|
||||
if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1;
|
||||
}
|
||||
}
|
||||
if (reviewed > 0) {
|
||||
data.notes.reviewedCount = reviewed;
|
||||
data.notes.divergedCount = diverged;
|
||||
// 人工准确率 = 被裁决为"人工对"的单数 / 被裁决总单数
|
||||
data.humanAccuracy = Number(((humanRight / reviewed) * 100).toFixed(2));
|
||||
data.notes.humanAccuracyAvailable = true;
|
||||
// AI 准确率同样可从裁决侧复核(供对照),但 §1.2 主准确率仍用上游 performance
|
||||
void aiRight;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 局部摘要:避免依赖 capabilities/helpers 的深耦合,只取报告需要的字段。 */
|
||||
function summarizeLocal(record: ApprovalRun): {
|
||||
id: string;
|
||||
sn?: string;
|
||||
template: string;
|
||||
aiDecision?: string;
|
||||
humanResult?: string;
|
||||
aiSummary?: string;
|
||||
humanComment?: string;
|
||||
} {
|
||||
const result = (record.result ?? {}) as Record<string, unknown>;
|
||||
const document = (record.document ?? {}) as Record<string, unknown>;
|
||||
|
||||
const aiDecision =
|
||||
firstString(result.decision) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.decision) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.result);
|
||||
|
||||
const humanResult =
|
||||
firstString(result.humanResult) ??
|
||||
firstString((result.manualApproval as Record<string, unknown> | undefined)?.humanResult) ??
|
||||
firstString(record.pipelineData && (record.pipelineData as Record<string, unknown>).humanResult);
|
||||
|
||||
const template =
|
||||
firstString(document.templateName) ??
|
||||
firstString(document.title) ??
|
||||
firstString(document.name) ??
|
||||
"";
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
sn: record.sourceDocumentSN,
|
||||
template,
|
||||
aiDecision,
|
||||
humanResult,
|
||||
aiSummary: firstString(result.summary),
|
||||
humanComment: firstString((result.manualApproval as Record<string, unknown> | undefined)?.comment) ??
|
||||
firstString(result.humanComment)
|
||||
};
|
||||
}
|
||||
|
||||
function firstString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* 模板 → 数据需求 分析器。
|
||||
*
|
||||
* 报告模板是可变的皮:章节标题允许增删、改名、重排。
|
||||
* 这里不硬编码任何章节,而是扫描模板的 `##`/`###` 标题,用关键词规则反推每个章节
|
||||
* 需要哪些数据(demand)。渲染器逐节按 demand 取数——模板改了,只需调整或新增规则,
|
||||
* 编排器(collect/render)不用动。
|
||||
*/
|
||||
|
||||
export type ReportDemand =
|
||||
/** 审核效能指标(准确率、自动化率、平均耗时、审批量) */
|
||||
| "performance"
|
||||
/** 风险标签统计(§3 风险构成) */
|
||||
| "riskStats"
|
||||
/** 风险标签下的单据明细(§3 TOP 小节) */
|
||||
| "riskDetails"
|
||||
/** AI 与人工的决策分块(§2 失准、§5 一致性、§6 通过/驳回明细) */
|
||||
| "blocks"
|
||||
/** 分模板(单据模板)维度的分组统计(§7.1) */
|
||||
| "templateGroups";
|
||||
|
||||
export type SectionPlan = {
|
||||
/** 章节的 ## 标题原文 */
|
||||
heading: string;
|
||||
/** 是否为二级章节(## 为 true,### 为 false) */
|
||||
level: 2 | 3;
|
||||
/** 该章节声明的需求;为空表示保持模板原文(纯叙述章节) */
|
||||
demands: ReportDemand[];
|
||||
/** 章节序号(## 级别从 1 递增;### 归属最近的 ##) */
|
||||
chapter: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* 标题关键词 → 数据需求。规则即契约:命中一个关键词就声明一个需求,多命中取并集。
|
||||
* 顺序无关;`avoid` 关键词优先(防止"人工审核准确率"这类词把一致性章节误判成效能章节)。
|
||||
*/
|
||||
const TITLE_RULES: Array<{ pattern: RegExp; demand: ReportDemand; avoid?: RegExp }> = [
|
||||
{ pattern: /AI 失准|失准分析|误判|失准构成/, demand: "blocks" },
|
||||
{ pattern: /风险|潜在/, demand: "riskStats" },
|
||||
{ pattern: /TOP \d|构成总览|小节|明细/, demand: "riskDetails" },
|
||||
{ pattern: /准确率|时效|耗时|效能|稳定性|审核测试结果|样本/, demand: "performance", avoid: /一致性示例/ },
|
||||
{ pattern: /一致性|一致示例|通过 \/ 人工驳回|通过\/人工驳回|通过 \/ 人工驳回/, demand: "blocks" },
|
||||
{ pattern: /分模板|单据模板.*率/, demand: "templateGroups" },
|
||||
{ pattern: /风险拦截/, demand: "riskStats" }
|
||||
];
|
||||
|
||||
/** 汇总一个 `##` 章节内所有标题(含自身)命中的需求。 */
|
||||
function demandsFor(titles: string[]): ReportDemand[] {
|
||||
const demands = new Set<ReportDemand>();
|
||||
for (const title of titles) {
|
||||
for (const rule of TITLE_RULES) {
|
||||
if (rule.avoid && rule.avoid.test(title)) continue;
|
||||
if (rule.pattern.test(title)) demands.add(rule.demand);
|
||||
}
|
||||
}
|
||||
return [...demands];
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描模板文本,产出逐节执行计划。
|
||||
* 同时返回模板正文里出现过的 `data:` 元数据行(如 `数据来源`、`统计期间` 行)供填充使用。
|
||||
*/
|
||||
export function describeTemplate(template: string): SectionPlan[] {
|
||||
const lines = template.split("\n");
|
||||
const plans: SectionPlan[] = [];
|
||||
let chapter = 0;
|
||||
/** 当前 ## 章节内累积的标题(## 标题 + 其下 ### 标题),到下一个 ## 时结算 */
|
||||
let pendingTitles: string[] = [];
|
||||
let pendingHeading = "";
|
||||
let pendingLevel: 2 | 3 = 2;
|
||||
let pendingChapter = 0;
|
||||
|
||||
const flush = () => {
|
||||
if (!pendingHeading) return;
|
||||
plans.push({
|
||||
heading: pendingHeading,
|
||||
level: pendingLevel,
|
||||
demands: demandsFor(pendingTitles),
|
||||
chapter: pendingChapter
|
||||
});
|
||||
};
|
||||
|
||||
for (const line of lines) {
|
||||
const h2 = line.match(/^## (.+)$/);
|
||||
const h3 = line.match(/^### (.+)$/);
|
||||
if (h2) {
|
||||
flush();
|
||||
chapter += 1;
|
||||
pendingHeading = h2[1]!.trim();
|
||||
pendingLevel = 2;
|
||||
pendingChapter = chapter;
|
||||
pendingTitles = [pendingHeading];
|
||||
} else if (h3) {
|
||||
if (pendingHeading) pendingTitles.push(h3[1]!.trim());
|
||||
else {
|
||||
// `###` 出现在任何 `##` 之前:作为独立段落登记,序号并入后续章节
|
||||
pendingHeading = h3[1]!.trim();
|
||||
pendingLevel = 3;
|
||||
pendingChapter = chapter;
|
||||
pendingTitles = [pendingHeading];
|
||||
}
|
||||
}
|
||||
}
|
||||
flush();
|
||||
|
||||
return plans;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { isCompiledBinary } from "../../../core/runtime.js";
|
||||
import { describeTemplate } from "./describe.js";
|
||||
import { collectReportData, type ReportData } from "./collect.js";
|
||||
import { renderMonthlyReport, type RenderOptions } from "./render.js";
|
||||
|
||||
export type MonthlyReportOptions = {
|
||||
month: string; // YYYY-MM
|
||||
corp: { id: string; name: string };
|
||||
/** 模板路径;缺省用仓内 report-templates/monthly.md */
|
||||
templatePath?: string;
|
||||
reportId?: string;
|
||||
maxRuns?: number;
|
||||
};
|
||||
|
||||
export type MonthlyReportResult = {
|
||||
month: string;
|
||||
corpId: string;
|
||||
reportId: string;
|
||||
templatePath: string;
|
||||
/** 模板各章节声明的数据需求与取数结果,供 agent 判断哪些章节可直接用、哪些需人工补 */
|
||||
sections: Array<{ heading: string; demands: string[]; fetched: string[] }>;
|
||||
notes: ReportData["notes"];
|
||||
/** 报告 Markdown 本体 */
|
||||
content: string;
|
||||
next: {
|
||||
validate: string;
|
||||
render: string;
|
||||
};
|
||||
};
|
||||
|
||||
function defaultTemplatePath(): string {
|
||||
if (isCompiledBinary()) {
|
||||
// 模板不进包;编译产物用 cwd(与 rules lint --file 的相对路径解析一致)
|
||||
return join(process.cwd(), "report-templates", "monthly.md");
|
||||
}
|
||||
// dev: src/domains/seal/reports → 仓库根
|
||||
return join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md");
|
||||
}
|
||||
|
||||
/** 一次调用产出填充好的月度报告 Markdown。模板皮与数据骨解耦:见 describe.ts。 */
|
||||
export async function buildMonthlyReport(
|
||||
client: KyInstance,
|
||||
options: MonthlyReportOptions
|
||||
): Promise<MonthlyReportResult> {
|
||||
const templatePath = options.templatePath
|
||||
? resolve(options.templatePath)
|
||||
: defaultTemplatePath();
|
||||
if (!existsSync(templatePath)) {
|
||||
throw new Error(
|
||||
`未找到报告模板: ${templatePath}\n` +
|
||||
`可用 --template <file> 指定路径,或在 report-templates/ 目录下运行。`
|
||||
);
|
||||
}
|
||||
const template = readFileSync(templatePath, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
|
||||
const demands = new Set(plans.flatMap((plan) => plan.demands));
|
||||
const data = await collectReportData(client, demands, {
|
||||
month: options.month,
|
||||
corp: options.corp,
|
||||
maxRuns: options.maxRuns
|
||||
});
|
||||
|
||||
const renderOptions: RenderOptions = {
|
||||
reportId: options.reportId,
|
||||
corpName: options.corp.name
|
||||
};
|
||||
const content = renderMonthlyReport(template, data, plans, renderOptions);
|
||||
|
||||
const reportId = options.reportId ?? `RPT-${options.month.replace("-", "")}-XXXXXX`;
|
||||
return {
|
||||
month: options.month,
|
||||
corpId: options.corp.id,
|
||||
reportId,
|
||||
templatePath,
|
||||
sections: plans.map((plan) => ({
|
||||
heading: plan.heading,
|
||||
demands: plan.demands,
|
||||
fetched: plan.demands.filter((demand) => data.fetched[demand])
|
||||
})),
|
||||
notes: data.notes,
|
||||
content,
|
||||
next: {
|
||||
validate: `python3 tools/validate.py <报告文件.md>(校验器与渲染器见 ai-audit-report-template 仓库)`,
|
||||
render: `python3 tools/render.py <报告文件.md> -o build/<报告文件>(产出 HTML / PNG / A4 PDF 三件套)`
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||
import type { ReportData, ReportBlock } from "./collect.js";
|
||||
import type { SectionPlan } from "./describe.js";
|
||||
|
||||
export type RenderOptions = {
|
||||
/** 报告编号;未给则按 RPT-<YYYYMM>-<6位随机> 生成 */
|
||||
reportId?: string;
|
||||
corpName?: string;
|
||||
/** 生成日期(YYYY-MM-DD),默认北京时间今天 */
|
||||
generatedAt?: string;
|
||||
reportStatus?: string;
|
||||
};
|
||||
|
||||
function pct(value: number | undefined, digits = 2): string {
|
||||
if (value === undefined || Number.isNaN(value)) return "—";
|
||||
return `${value.toFixed(digits)}%`;
|
||||
}
|
||||
|
||||
function escapeCell(value: string | number | undefined): string {
|
||||
if (value === undefined || value === null) return "—";
|
||||
return String(value).replace(/\|/g, "\\|").replace(/\n/g, " ");
|
||||
}
|
||||
|
||||
function parseRow(line: string): string[] {
|
||||
return line
|
||||
.trim()
|
||||
.replace(/^\|/, "")
|
||||
.replace(/\|$/, "")
|
||||
.split("|")
|
||||
.map((cell) => cell.trim());
|
||||
}
|
||||
|
||||
/** 当前统计口径不可得时,模板示例数据一律不冒充真实值;空串表示"保持模板原文并知会"。 */
|
||||
const HUMAN_ACCURACY_NOTE =
|
||||
"> ⚠️ **数据说明**:上游暂无人工审核准确率口径,本表人工一行为模板示例值,请业务侧核算后替换。";
|
||||
|
||||
type FillContext = {
|
||||
reportId: string;
|
||||
corpName: string;
|
||||
generatedAt: string;
|
||||
reportStatus?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 用数据填充模板,产出报告 Markdown。
|
||||
*
|
||||
* 约定(模板是可变的皮):
|
||||
* - 表格:表头两行保留,数据行整体替换;识别不了的表原样保留。
|
||||
* - 叙述行:按句子改写占位数字,不按行号——模板重排段落不受影响。
|
||||
* - 上游没有的口径(人工准确率、失准原因分类)不编造:表格留模板示例并追加 ⚠️ 数据说明。
|
||||
*/
|
||||
export function renderMonthlyReport(
|
||||
template: string,
|
||||
data: ReportData,
|
||||
plans: SectionPlan[],
|
||||
options: RenderOptions = {}
|
||||
): string {
|
||||
const reportId = options.reportId ?? `RPT-${data.period.month.replace("-", "")}-${randomSuffix()}`;
|
||||
const corpName = options.corpName ?? data.corp.name;
|
||||
const generatedAt = options.generatedAt ?? beijingToday();
|
||||
const ctx: FillContext = { reportId, corpName, generatedAt, reportStatus: options.reportStatus };
|
||||
|
||||
const lines = template.split("\n");
|
||||
const out: string[] = [];
|
||||
let planIndex = 0;
|
||||
let tableBuffer: string[] = [];
|
||||
let lastH2 = "";
|
||||
let lastHeading = "";
|
||||
|
||||
const flushTable = () => {
|
||||
if (tableBuffer.length) {
|
||||
out.push(...transformTable(tableBuffer, data, lastHeading, lastH2));
|
||||
tableBuffer = [];
|
||||
}
|
||||
};
|
||||
|
||||
for (const raw of lines) {
|
||||
const h2 = raw.match(/^## (.+)$/);
|
||||
const h3 = raw.match(/^### (.+)$/);
|
||||
if (h2 || h3) {
|
||||
flushTable();
|
||||
const heading = (h2?.[1] ?? h3?.[1] ?? "").trim();
|
||||
const plan = plans.find((item, idx) => idx >= planIndex && item.heading === heading);
|
||||
if (plan) planIndex = plans.indexOf(plan) + 1;
|
||||
if (h2) lastH2 = heading;
|
||||
lastHeading = heading;
|
||||
out.push(raw);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (raw.trim().startsWith("|")) {
|
||||
tableBuffer.push(raw);
|
||||
continue;
|
||||
}
|
||||
|
||||
flushTable();
|
||||
out.push(fillInline(raw, data, ctx));
|
||||
}
|
||||
flushTable();
|
||||
|
||||
let result = out.join("\n");
|
||||
result = fillInline(result, data, ctx);
|
||||
// 报告信息表:统计期间与生成日期按真实统计口径补齐
|
||||
result = result.replace(
|
||||
/(\| 统计期间 \| )[^\n|]+/,
|
||||
`$1${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)}`
|
||||
);
|
||||
result = result.replace(/(\| 生成日期 \| )[^\n|]+/, `$1${ctx.generatedAt}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
function fillInline(text: string, data: ReportData, ctx: FillContext): string {
|
||||
let result = text;
|
||||
result = result.replace(/【[^】]+】(?=\S*月)/, `【${ctx.corpName}】`);
|
||||
result = result.replace(/RPT-\d{6}-[A-Z0-9]+/, ctx.reportId);
|
||||
if (ctx.reportStatus) result = result.replace(/(报告状态\s*\|\s*)[^\n|]+/, `$1${ctx.reportStatus}`);
|
||||
|
||||
const perf = data.performance;
|
||||
if (!data.fetched.performance || !perf) return result;
|
||||
|
||||
const total = perf.approvalCount;
|
||||
const acc = perf.accuracy;
|
||||
const correct = total !== undefined && acc !== undefined ? Math.round((total * acc) / 100) : undefined;
|
||||
const wrong = total !== undefined && correct !== undefined ? total - correct : undefined;
|
||||
|
||||
// §1 摘要与叙述行:把模板里的占位样本量/准确率换成真实值
|
||||
if (total !== undefined && acc !== undefined && correct !== undefined && wrong !== undefined) {
|
||||
result = result.replace(/\*\*\d+ 笔\*\*/, `**${total} 笔**`);
|
||||
result = result.replace(/\*\*\d{3} 笔\*\*/, `**${total} 笔**`);
|
||||
result = result.replace(/\*\*9\d\.\d\d%\*\*/g, `**${pct(acc)}**`);
|
||||
result = result.replace(/92\.08%/g, pct(acc));
|
||||
result = result.replace(/240 笔/g, `${total} 笔`);
|
||||
// §2 叙述:模板里"依规综合正确 N 单(X%)"与"失准共 M 单(Y%)"是硬编码占位,
|
||||
// 用结构化模式匹配(不依赖具体数字),换成真实 correct/wrong。
|
||||
result = result.replace(
|
||||
/依规综合正确 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g,
|
||||
`依规综合正确 **${correct} 单(${pct(acc)})**`
|
||||
);
|
||||
result = result.replace(
|
||||
/综合失准共 \*\*\d+ 单(\d+(?:\.\d+)?%)\*\*/g,
|
||||
`综合失准共 **${wrong} 单(${pct(100 - acc)})**`
|
||||
);
|
||||
// 无加粗的裸形式
|
||||
result = result.replace(
|
||||
/依规综合正确 \d+ 单(\d+(?:\.\d+)?%)/g,
|
||||
`依规综合正确 ${correct} 单(${pct(acc)})`
|
||||
);
|
||||
result = result.replace(
|
||||
/综合失准共 \d+ 单(\d+(?:\.\d+)?%)/g,
|
||||
`综合失准共 ${wrong} 单(${pct(100 - acc)})`
|
||||
);
|
||||
result = result.replace(/\*\*\d+ 单\*\*的深度稽核中/g, `**${total} 单**的深度稽核中`);
|
||||
result = result.replace(/\d+ 单的深度稽核中/g, `${total} 单的深度稽核中`);
|
||||
// 公式代入值:\frac{N}{M} = X% 结构化匹配
|
||||
result = result.replace(
|
||||
/= \\frac\{\d+\}\{\d+\} = \d+(?:\.\d+)?\\?%/g,
|
||||
`= \\frac{${correct}}{${total}} = ${acc.toFixed(2)}\\%`
|
||||
);
|
||||
result = result.replace(
|
||||
/\d+\/\d+ = \d+(?:\.\d+)?%/g,
|
||||
`${correct}/${total} = ${pct(acc)}`
|
||||
);
|
||||
result = result.replace(/N = 240/g, `N = ${total}`);
|
||||
// 样本总量:真实单量 + 决策分布(无人工明细时只报总样本)
|
||||
const dist = distributionOf(data.blocks);
|
||||
result = result.replace(
|
||||
/\*\*\d+ 张\*\*([^)]*)/,
|
||||
`**${total} 张**${dist ? `(${dist})` : ""}`
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function distributionOf(blocks: ReportBlock[]): string | undefined {
|
||||
if (!blocks.length) return undefined;
|
||||
const counts = { pass: 0, reject: 0, unknown: 0 };
|
||||
for (const block of blocks) {
|
||||
const ai = (block.aiDecision ?? "").trim();
|
||||
if (/同意|通过|approve/i.test(ai)) counts.pass += 1;
|
||||
else if (/驳回|拒绝|终止|退回|reject/i.test(ai)) counts.reject += 1;
|
||||
else counts.unknown += 1;
|
||||
}
|
||||
const parts = [`${counts.pass} 张同意`, `${counts.reject} 张驳回`];
|
||||
if (counts.unknown) parts.push(`${counts.unknown} 张未定`);
|
||||
return parts.join(" + ");
|
||||
}
|
||||
|
||||
/** 表格块变换:保留表头两行,按所在章节 + 表头识别语义后重写数据行。 */
|
||||
function transformTable(
|
||||
block: string[],
|
||||
data: ReportData,
|
||||
heading: string,
|
||||
lastH2: string
|
||||
): string[] {
|
||||
if (block.length < 2) return block;
|
||||
const header = block[0]!;
|
||||
const separator = block[1]!;
|
||||
const sampleRows = block.slice(2);
|
||||
const columns = parseRow(header);
|
||||
if (!columns.length) return block;
|
||||
|
||||
const notes = noteAfter(columns, heading, lastH2, data);
|
||||
const rows = replacementRows(columns, sampleRows, data, heading);
|
||||
// 无论是否替换数据行,缺口径说明都要追加(模板保留时同样需要知会)
|
||||
if (!rows) return [...block, ...notes];
|
||||
return [header, separator, ...rows.map((row) => `| ${row.map(escapeCell).join(" | ")} |`), ...notes];
|
||||
}
|
||||
|
||||
/** 表后追加的数据说明(人工准确率缺口径时)。 */
|
||||
function noteAfter(columns: string[], heading: string, lastH2: string, data: ReportData): string[] {
|
||||
if (columns.includes("审核方式") && columns.includes("准确率")) {
|
||||
if (data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined) {
|
||||
const reviewed = data.notes.reviewedCount ?? 0;
|
||||
const diverged = data.notes.divergedCount ?? 0;
|
||||
return ["", `> ℹ️ **数据说明**:人工审核准确率由本地人工裁决回填(已裁决 ${reviewed} 笔,其中分歧 ${diverged} 笔);AI 准确率为上游效能口径。`, ""];
|
||||
}
|
||||
return ["", HUMAN_ACCURACY_NOTE, ""];
|
||||
}
|
||||
if (heading.includes("失准构成总览") && lastH2.includes("失准") && data.fetched.performance) {
|
||||
return ["", "> ⚠️ **数据说明**:失准原因分类(规则执行/识别/查重等维度)无上游字段,上表为模板示例分类,需人工归类后替换。", ""];
|
||||
}
|
||||
// §6:明细表保留模板示例行时(无分歧单据可填),必须标注是示例而非真实数据
|
||||
if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) {
|
||||
return ["", "> ⚠️ **数据说明**:本期无 AI 与人工分歧的单据可填,或「原因分类/复核结论」需人工归类;上表为模板示例行,请以真实明细替换。", ""];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function replacementRows(
|
||||
columns: string[],
|
||||
sampleRows: string[],
|
||||
data: ReportData,
|
||||
heading: string
|
||||
): Array<Array<string | number>> | null {
|
||||
const perf = data.performance;
|
||||
|
||||
// 报告信息表:fillInline 已处理,行保留
|
||||
if (columns.includes("报告编号")) return null;
|
||||
|
||||
// §1.2 准确率结论表(表头 2 列:审核方式|准确率;示例行 AI/人工 两行)
|
||||
if (columns.includes("审核方式") && columns.includes("准确率") && columns.length === 2) {
|
||||
if (!data.fetched.performance || !perf) return null;
|
||||
const humanCell = data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined
|
||||
? `**${pct(data.humanAccuracy)}**`
|
||||
: sampleRows.length > 1
|
||||
? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*")
|
||||
: "*(口径待业务提供)*";
|
||||
return [
|
||||
["AI 审核", `**${pct(perf.accuracy)}**`],
|
||||
["人工审核", humanCell]
|
||||
];
|
||||
}
|
||||
|
||||
// §1.1 数据来源与范围
|
||||
if (columns.includes("项目") && columns.includes("内容") && heading.includes("数据来源")) {
|
||||
if (!perf) return null;
|
||||
const dist = distributionOf(data.blocks) ?? "";
|
||||
return [
|
||||
["数据来源", "客户授权的已完成历史审批单据"],
|
||||
["统计期间", `${data.period.start.slice(0, 10)} ~ ${data.period.end.slice(0, 10)} 期间单据`],
|
||||
["单据模板", data.templateGroups.length
|
||||
? `涵盖 ${data.templateGroups.map((g) => g.template).slice(0, 6).join("、")} 等 **${data.templateGroups.length} 类**业务单据模板`
|
||||
: "*(单据模板分布待取数)*"],
|
||||
["样本总量", `**${perf.approvalCount ?? "—"} 张**${dist ? `(${dist})` : ""}`]
|
||||
];
|
||||
}
|
||||
|
||||
// §1.3 系统稳定性
|
||||
if (columns.includes("项目") && columns.includes("内容") && heading.includes("系统稳定性")) {
|
||||
if (!perf) return null;
|
||||
return [
|
||||
["全月成功审核率", `近 **${pct(perf.automationRate, 0)}**(自动化审核采纳率口径)`],
|
||||
["迭代影响", `*(迭代影响需业务口径补充;本月自动化采纳率 ${pct(perf.automationRate)})*`]
|
||||
];
|
||||
}
|
||||
|
||||
// §4 综合效益
|
||||
if (columns.includes("维度") && columns.includes("结论") && columns.includes("关键数据") && perf) {
|
||||
return [
|
||||
["准确度", "除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率", `**${pct(perf.accuracy)}**`],
|
||||
["时效", "AI 审核单张单据平均耗时", perf.avgDurationSeconds !== undefined ? `平均 **${perf.avgDurationSeconds.toFixed(1)} 秒**` : "—"],
|
||||
["风险拦截", "在人工审核通过的单据中,AI 有效防堵的凭证与资金隐患", perf.riskCount !== undefined ? `${perf.riskCount} 笔` : "—"],
|
||||
["工作量", "协助财务人员弥补遗漏、聚焦高价值工作", "—"]
|
||||
];
|
||||
}
|
||||
|
||||
// §2.1 / §3.x 构成总览(维度 | …类型 | 占比 | 单数)
|
||||
if (columns.includes("维度") && columns.includes("单数") && columns.includes("占比")) {
|
||||
const isRisk = columns.some((col) => col.includes("风险"));
|
||||
if (isRisk) {
|
||||
if (!data.fetched.riskStats || !data.riskStats?.tags.length) return null;
|
||||
const tags = data.riskStats.tags.filter((tag) => tag.count !== undefined).slice(0, 3);
|
||||
const total = tags.reduce((sum, tag) => sum + (tag.count ?? 0), 0) || 1;
|
||||
const typeIdx = Math.max(1, columns.findIndex((col) => col.includes("风险")));
|
||||
const pctIdx = columns.indexOf("占比");
|
||||
const countIdx = columns.indexOf("单数");
|
||||
const rows: Array<Array<string | number>> = tags.map((tag, idx) => {
|
||||
const row: Array<string | number> = Array.from({ length: columns.length }, () => "—");
|
||||
row[0] = `TOP ${idx + 1}`;
|
||||
row[typeIdx] = tag.name ?? tag.id ?? "未命名风险";
|
||||
row[pctIdx] = pct(((tag.count ?? 0) / total) * 100, 1);
|
||||
row[countIdx] = `${tag.count} 张`;
|
||||
return row;
|
||||
});
|
||||
const totalRow: Array<string | number> = Array.from({ length: columns.length }, () => "—");
|
||||
totalRow[0] = "合计";
|
||||
totalRow[pctIdx] = "100%";
|
||||
totalRow[countIdx] = `${total} 张`;
|
||||
rows.push(totalRow);
|
||||
return rows;
|
||||
}
|
||||
// 失准构成:无上游分类 → 留模板原文
|
||||
return null;
|
||||
}
|
||||
|
||||
// §6 AI 通过 / 人工驳回明细(7 列:单据编号|模板|AI|人工|原因分类|复核结论|截图)
|
||||
if (columns.includes("单据编号") && columns.some((col) => col.includes("原因分类"))) {
|
||||
if (!data.blocks.length) return null;
|
||||
const diverged = data.blocks.filter((block) => block.agreement === "diverged").slice(0, 10);
|
||||
if (!diverged.length) return null;
|
||||
return diverged.map((block) => [
|
||||
block.sn,
|
||||
block.template || "—",
|
||||
block.aiDecision ?? "—",
|
||||
block.humanResult ?? "—",
|
||||
"*(原因分类待人工归类)*",
|
||||
block.aiSummary ?? "—",
|
||||
"(截图)"
|
||||
]);
|
||||
}
|
||||
|
||||
// §7.1 分模板统计(只认明确带"模板"或 6 列且有"AI 准确率"的表头;不吃掉一致性示例的 5 列表)
|
||||
if (
|
||||
(columns.includes("单据模板") || columns[0] === "模板") &&
|
||||
(columns.includes("AI 准确率") || columns.includes("自动审批率") || columns.includes("单量"))
|
||||
) {
|
||||
if (!data.fetched.templateGroups) return null;
|
||||
if (!data.templateGroups.length) return null;
|
||||
return data.templateGroups.slice(0, 20).map((group) => {
|
||||
const agreement = group.total ? (group.agreed / group.total) * 100 : 0;
|
||||
if (columns.includes("AI 准确率")) {
|
||||
// 分模板的"准确率"应为逐单判定正确率,无判定字段时以 AI/人工一致率占位并说明
|
||||
const row: Array<string | number> = Array.from({ length: columns.length }, () => "—");
|
||||
row[0] = group.template;
|
||||
row[columns.indexOf("AI 准确率")] = pct(agreement);
|
||||
const manualIdx = columns.findIndex((col) => col.includes("人工"));
|
||||
if (manualIdx >= 0 && columns[manualIdx] === "人工同意:驳回") {
|
||||
row[manualIdx] = `${group.total} 笔`;
|
||||
}
|
||||
return row;
|
||||
}
|
||||
if (columns.length >= 2) return [group.template, group.total];
|
||||
return [group.template];
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function beijingToday(): string {
|
||||
return formatBeijingIso().slice(0, 10);
|
||||
}
|
||||
|
||||
function randomSuffix(): string {
|
||||
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let out = "";
|
||||
for (let i = 0; i < 6; i++) out += alphabet[Math.floor(Math.random() * alphabet.length)]!;
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describeTemplate } from "./describe.js";
|
||||
import { collectReportData, type ReportData } from "./collect.js";
|
||||
import { renderMonthlyReport } from "./render.js";
|
||||
import { loadReviews, writeReview, reviewFilePath } from "./review-store.js";
|
||||
|
||||
const TEMPLATE = join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md");
|
||||
|
||||
function sampleData(overrides: Partial<ReportData> = {}): ReportData {
|
||||
return {
|
||||
period: { start: "2026-08-01T00:00:00+08:00", end: "2026-08-31T23:59:59+08:00", month: "2026-08" },
|
||||
corp: { id: "corp-a", name: "赢家时尚" },
|
||||
fetched: { performance: true, riskStats: true, riskDetails: true, blocks: true, templateGroups: true },
|
||||
performance: {
|
||||
approvalCount: 240,
|
||||
accuracy: 92.08,
|
||||
automationRate: 41.67,
|
||||
riskCount: 40,
|
||||
avgDurationSeconds: 445.4,
|
||||
sankey: { nodes: [], links: [] }
|
||||
},
|
||||
riskStats: {
|
||||
tags: [
|
||||
{ id: "B.1.1", name: "缺失要求凭证", count: 23 },
|
||||
{ id: "B.2.3", name: "大额预付与采购口径偏差", count: 9 },
|
||||
{ id: "B.3.1", name: "票据合规与专票强制违规", count: 8 },
|
||||
{ id: "B.4.1", name: "长尾风险", count: 30 }
|
||||
]
|
||||
},
|
||||
blocks: [
|
||||
{ sn: "FP260001", template: "费用报销", aiDecision: "同意", humanResult: "驳回", agreement: "diverged", aiSummary: "合规放行", humanComment: "超标" },
|
||||
{ sn: "FP260002", template: "费用报销", aiDecision: "同意", humanResult: "同意", agreement: "agreed", aiSummary: "合规放行", humanComment: undefined }
|
||||
],
|
||||
templateGroups: [
|
||||
{ template: "费用报销", total: 100, agreed: 92, diverged: 8 },
|
||||
{ template: "差旅报销", total: 140, agreed: 130, diverged: 10 }
|
||||
],
|
||||
reviews: new Map(),
|
||||
notes: { humanAccuracyAvailable: false, failureRateAvailable: true, mismatchCategoriesAvailable: false },
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe("describeTemplate", () => {
|
||||
test("infers data demands from section headings without hard-coding chapters", () => {
|
||||
const template = [
|
||||
"# x",
|
||||
"## 1. 审核测试结果",
|
||||
"### 1.2 核心准确率结论",
|
||||
"## 2. AI 失准分析",
|
||||
"## 3. AI 发现的潜在风险",
|
||||
"### 3.1 风险构成总览",
|
||||
"## 4. 综合效益",
|
||||
"## 5. AI 与人工审核一致性示例",
|
||||
"## 6. AI 通过 / 人工驳回单据明细",
|
||||
"### 7.1 分模板准确率与自动审批率"
|
||||
].join("\n");
|
||||
|
||||
const plans = describeTemplate(template);
|
||||
const byHeading = new Map(plans.map((plan) => [plan.heading, plan.demands]));
|
||||
|
||||
// 每个 ## 章节一条 plan;### 子标题的需求并入所属章节
|
||||
expect(byHeading.get("1. 审核测试结果")).toContain("performance");
|
||||
expect(byHeading.get("2. AI 失准分析")).toContain("blocks");
|
||||
expect(byHeading.get("3. AI 发现的潜在风险")).toContain("riskStats");
|
||||
expect(byHeading.get("3. AI 发现的潜在风险")).toContain("riskDetails"); // 由 ### 3.1 并入
|
||||
expect(byHeading.get("5. AI 与人工审核一致性示例")).toContain("blocks");
|
||||
expect(byHeading.get("6. AI 通过 / 人工驳回单据明细")).toContain("blocks");
|
||||
// "人工审核准确率" 不应把一致性章节误判为效能章节
|
||||
expect(byHeading.get("5. AI 与人工审核一致性示例")).not.toContain("performance");
|
||||
// 子标题不单独成 plan
|
||||
expect(byHeading.has("3.1 风险构成总览")).toBe(false);
|
||||
});
|
||||
|
||||
test("renaming a chapter keeps working when keywords still match", () => {
|
||||
// 模板可变:章节改名后只要关键词仍命中就能取到需求
|
||||
const template = "## 1. 月度测试结果\n## 2. 误判分析\n## 3. 风险扫描";
|
||||
const plans = describeTemplate(template);
|
||||
expect(plans).toHaveLength(3);
|
||||
expect(plans[0]!.demands).toEqual([]); // "月度测试结果" 不含既有规则关键词
|
||||
expect(plans[1]!.demands).toContain("blocks"); // "误判" 命中规则
|
||||
expect(plans[2]!.demands).toContain("riskStats");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderMonthlyReport", () => {
|
||||
test("fills identity, period, and performance facts from real data", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans, { reportId: "RPT-202608-TEST01" });
|
||||
|
||||
expect(out).toContain("【赢家时尚】8月AI审核准确率报告");
|
||||
expect(out).toContain("RPT-202608-TEST01");
|
||||
expect(out).toContain("2026-08-01 ~ 2026-08-31");
|
||||
// §1.2 AI 准确率用真实值
|
||||
expect(out).toContain("**92.08%**");
|
||||
// §1.1 样本总量 = 真实审批量 + blocks 的决策分布(fixture: 2 同意 0 驳回)
|
||||
expect(out).toContain("**240 张**(2 张同意 + 0 张驳回)");
|
||||
// §4 关键数据
|
||||
expect(out).toContain("平均 **445.4 秒**");
|
||||
expect(out).toContain("40 笔");
|
||||
// §7.1 分模板:模板名 + 一致率占位
|
||||
expect(out).toContain("差旅报销");
|
||||
expect(out).toContain("92.86%"); // 130/140 一致率
|
||||
expect(out).toContain("费用报销");
|
||||
});
|
||||
|
||||
test("keeps template sample values and adds a warning note when a metric has no upstream source", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans);
|
||||
|
||||
// 人工审核准确率:无上游口径 → 模板示例值保留 + ⚠️ 数据说明
|
||||
expect(out).toContain("人工审核准确率");
|
||||
expect(out).toContain("数据说明");
|
||||
expect(out).toContain("人工准确率");
|
||||
// 失准原因分类:无上游字段 → 不编造
|
||||
expect(out).toContain("失准原因分类");
|
||||
// 不应把示例值(83.33%)冒充为真实抓取结果的同时又丢失说明
|
||||
expect(out).toContain("**83.33%**");
|
||||
});
|
||||
|
||||
test("replaces the sample mismatch narrative with real counts", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans);
|
||||
// 221/240 与 19 单 是模板示例;真实数据 240 * 92.08% = 221, 失准 19 → 数字仍成立,
|
||||
// 关键是失准构成总览不冒充分类(已由 noteAfter 标注),且叙述句不残留 92.08% 之外的错误样本量
|
||||
expect(out).toContain("221 单(92.08%)");
|
||||
expect(out).toContain("19 单(7.92%)");
|
||||
});
|
||||
|
||||
test("custom template path drives the same pipeline (skin is swappable)", () => {
|
||||
const template = [
|
||||
"# 【X】月报",
|
||||
"",
|
||||
"| 报告信息 | 内容 |",
|
||||
"| --- | --- |",
|
||||
"| 报告编号 | RPT-202608-PLACE |",
|
||||
"| 客户名称 | 占位 |",
|
||||
"| 统计期间 | 占位 |",
|
||||
"| 生成日期 | 占位 |",
|
||||
"",
|
||||
"## 1. 审核测试结果",
|
||||
"",
|
||||
"本月样本 **0 笔**。",
|
||||
"",
|
||||
"| 审核方式 | 准确率 |",
|
||||
"| --- | --- |",
|
||||
"| AI 审核 | **0%** |",
|
||||
"| 人工审核 | **0%** |"
|
||||
].join("\n");
|
||||
|
||||
const plans = describeTemplate(template);
|
||||
const out = renderMonthlyReport(template, sampleData(), plans, { reportId: "RPT-202608-CUSTOM" });
|
||||
|
||||
expect(out).toContain("RPT-202608-CUSTOM");
|
||||
expect(out).toContain("**92.08%**");
|
||||
expect(out).toContain("**240 笔**");
|
||||
// 表头保留
|
||||
expect(out).toContain("| 审核方式 | 准确率 |");
|
||||
// ⚠️ 说明在表后追加
|
||||
expect(out).toContain("⚠️ **数据说明**");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("review store + human accuracy join", () => {
|
||||
const originalEnv = process.env.SEAL_USE_REVIEWS_DIR;
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = mkdtempSync(join(tmpdir(), "seal-reviews-test-"));
|
||||
process.env.SEAL_USE_REVIEWS_DIR = testDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv === undefined) delete process.env.SEAL_USE_REVIEWS_DIR;
|
||||
else process.env.SEAL_USE_REVIEWS_DIR = originalEnv;
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("writeReview appends and loadReviews merges by SN (last write wins)", () => {
|
||||
writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "human_correct" });
|
||||
writeReview("corp-a", { sn: "FP2", month: "2026-08", verdict: "ai_correct" });
|
||||
// 同一 SN 改判:后写覆盖先写
|
||||
writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "both_correct" });
|
||||
|
||||
const reviews = loadReviews("corp-a", "2026-08");
|
||||
expect(reviews.size).toBe(2);
|
||||
expect(reviews.get("FP1")?.verdict).toBe("both_correct");
|
||||
expect(reviews.get("FP2")?.verdict).toBe("ai_correct");
|
||||
|
||||
// 文件按租户+月份分片,追加式 JSONL
|
||||
expect(reviewFilePath("corp-a", "2026-08")).toContain("corp-a-2026-08.jsonl");
|
||||
const content = readFileSync(reviewFilePath("corp-a", "2026-08"), "utf8").trim().split("\n");
|
||||
expect(content).toHaveLength(3); // 3 次写入(含改判)
|
||||
});
|
||||
|
||||
test("loadReviews isolates tenants and months, skips corrupt lines", () => {
|
||||
writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" });
|
||||
writeReview("corp-b", { sn: "B1", month: "2026-08", verdict: "human_correct" });
|
||||
writeReview("corp-a", { sn: "A2", month: "2026-09", verdict: "ai_correct" });
|
||||
// 写入一行损坏数据
|
||||
const fs = require("node:fs") as typeof import("node:fs");
|
||||
fs.appendFileSync(reviewFilePath("corp-a", "2026-08"), "{corrupt json}\n", "utf8");
|
||||
|
||||
expect(loadReviews("corp-a", "2026-08").size).toBe(1);
|
||||
expect(loadReviews("corp-b", "2026-08").size).toBe(1);
|
||||
expect(loadReviews("corp-a", "2026-09").size).toBe(1);
|
||||
expect(loadReviews("corp-a", "2026-07").size).toBe(0);
|
||||
});
|
||||
|
||||
test("rejects invalid month and verdict with exit 13 validation error", () => {
|
||||
expect(() => writeReview("corp-a", { sn: "X", month: "bad", verdict: "ai_correct" })).toThrow();
|
||||
expect(() => writeReview("corp-a", { sn: "X", month: "2026-08", verdict: "wrong" })).toThrow();
|
||||
expect(() => writeReview("corp-a", { sn: " ", month: "2026-08", verdict: "ai_correct" })).toThrow();
|
||||
});
|
||||
|
||||
test("collectReportData joins reviews onto fetched blocks and computes human accuracy", async () => {
|
||||
// 写入裁决:3 个 SN,其中 1 个分歧单被判人工对
|
||||
writeReview("corp-a", { sn: "D1", month: "2026-08", verdict: "human_correct" }); // 分歧,人工对
|
||||
writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" }); // 一致,AI 对
|
||||
writeReview("corp-a", { sn: "A2", month: "2026-08", verdict: "both_correct" }); // 一致,双方对
|
||||
|
||||
// 伪客户端:只返回 3 条审批运行(SN 对应裁决),不发真网络
|
||||
const runs = [
|
||||
{ id: "r1", sourceDocumentSN: "D1", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } },
|
||||
{ id: "r2", sourceDocumentSN: "A1", result: { decision: "驳回" }, pipelineData: { humanResult: "驳回" } },
|
||||
{ id: "r3", sourceDocumentSN: "A2", result: { decision: "同意" }, pipelineData: { humanResult: "同意" } }
|
||||
];
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: runs, total: 3 } }) })
|
||||
} as never;
|
||||
|
||||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-a", name: "A" }
|
||||
});
|
||||
|
||||
expect(data.reviews.size).toBe(3);
|
||||
expect(data.blocks).toHaveLength(3);
|
||||
// 每个 block 挂上裁决
|
||||
expect(data.blocks.map((b) => b.verdict)).toEqual(["human_correct", "ai_correct", "both_correct"]);
|
||||
// 裁决数 = 3,人工对 = human_correct(D1) + both_correct(A2) = 2 → 2/3 = 66.67%
|
||||
expect(data.notes.reviewedCount).toBe(3);
|
||||
expect(data.notes.humanAccuracyAvailable).toBe(true);
|
||||
expect(data.humanAccuracy).toBeCloseTo(66.67, 1);
|
||||
// D1 是分歧单(AI 同意 / 人工驳回)
|
||||
expect(data.notes.divergedCount).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("no reviews → human accuracy unavailable (honest gap, not fabricated)", async () => {
|
||||
const fakeClient = {
|
||||
get: async () => ({ json: async () => ({ data: { records: [{ id: "r1", sourceDocumentSN: "X1" }], total: 1 } }) })
|
||||
} as never;
|
||||
const data = await collectReportData(fakeClient, new Set(["blocks"]), {
|
||||
month: "2026-08",
|
||||
corp: { id: "corp-no-reviews", name: "B" }
|
||||
});
|
||||
expect(data.reviews.size).toBe(0);
|
||||
expect(data.notes.humanAccuracyAvailable).toBe(false);
|
||||
expect(data.humanAccuracy).toBeUndefined();
|
||||
});
|
||||
|
||||
test("render uses human accuracy when available and shows review coverage note", () => {
|
||||
const template = readFileSync(TEMPLATE, "utf8");
|
||||
const plans = describeTemplate(template);
|
||||
const reviews = new Map();
|
||||
reviews.set("FP260001", { sn: "FP260001", month: "2026-08", verdict: "human_correct", recordedAt: "" });
|
||||
const data = sampleData({
|
||||
reviews,
|
||||
humanAccuracy: 75,
|
||||
notes: { humanAccuracyAvailable: true, failureRateAvailable: true, mismatchCategoriesAvailable: false, reviewedCount: 4, divergedCount: 2 }
|
||||
});
|
||||
const out = renderMonthlyReport(template, data, plans);
|
||||
|
||||
// §1.2 人工审核行用真实 75%,且不再弹"口径待业务提供"
|
||||
expect(out).toContain("**75.00%**");
|
||||
expect(out).toContain("已裁决 4 笔");
|
||||
expect(out).not.toContain("口径待业务提供");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { validationError } from "../../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 人工裁决的本地持久化(JSONL,按 租户 × 月份 分片)。
|
||||
*
|
||||
* 为什么是 JSONL:跨周 review 天然是**追加**场景——每审一批写一批,不整文件重写,
|
||||
* 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。
|
||||
* 为什么按租户+月份分片:租户隔离、月度报告天然对应一个文件、文件不会无限膨胀。
|
||||
*
|
||||
* 一条记录 = 一个 SN 在某个月被人工裁决一次的结果。同一 SN 重复裁决时,
|
||||
* 以**最后一条**为准(loadReviews 归并时后写覆盖先写)。
|
||||
*/
|
||||
|
||||
/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */
|
||||
export type ReviewVerdict =
|
||||
| "ai_correct" // AI 对,人工错
|
||||
| "human_correct" // 人工对,AI 错
|
||||
| "both_correct" // 双方都对(意见不同但结论都成立,或一致且复核通过)
|
||||
| "both_wrong" // 双方都错
|
||||
| "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判)
|
||||
|
||||
export type ReviewRecord = {
|
||||
/** 合思/源单据 SN(裁决的自然键) */
|
||||
sn: string;
|
||||
/** 裁决所属统计月 YYYY-MM(与 report monthly 的 month 对齐) */
|
||||
month: string;
|
||||
verdict: ReviewVerdict;
|
||||
/** 裁决人(可选,留痕用) */
|
||||
reviewedBy?: string;
|
||||
/** 裁决备注(可选):为什么这么判 */
|
||||
note?: string;
|
||||
/** 写入时间(北京时间 ISO 秒) */
|
||||
recordedAt: string;
|
||||
};
|
||||
|
||||
const VERDICTS: ReadonlySet<string> = new Set([
|
||||
"ai_correct",
|
||||
"human_correct",
|
||||
"both_correct",
|
||||
"both_wrong",
|
||||
"undecided"
|
||||
]);
|
||||
|
||||
const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR";
|
||||
|
||||
/** 裁决存储根目录:~/.config/seal-use/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
|
||||
export function reviewsDir(): string {
|
||||
const configured = process.env[REVIEWS_DIR_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
return join(homedir(), ".config", "seal-use", "reviews");
|
||||
}
|
||||
|
||||
/** 分片路径:<reviewsDir>/<corpId>-<YYYY-MM>.jsonl */
|
||||
export function reviewFilePath(corpId: string, month: string): string {
|
||||
return join(reviewsDir(), `${sanitizeCorpId(corpId)}-${month}.jsonl`);
|
||||
}
|
||||
|
||||
function sanitizeCorpId(corpId: string): string {
|
||||
// corpId 可能含路径分隔符等非法字符,压成安全片段
|
||||
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
}
|
||||
|
||||
function assertMonth(month: string): void {
|
||||
if (!/^\d{4}-\d{2}$/.test(month)) {
|
||||
throw validationError(`Invalid month "${month}", expected YYYY-MM`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
|
||||
if (!VERDICTS.has(verdict)) {
|
||||
throw validationError(
|
||||
`Invalid verdict "${verdict}". Expected one of: ${[...VERDICTS].join(", ")}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取某租户某月的全部裁决,按 SN 归并(同一 SN 后写覆盖先写)。文件不存在返回空 Map。
|
||||
*/
|
||||
export function loadReviews(corpId: string, month: string): Map<string, ReviewRecord> {
|
||||
assertMonth(month);
|
||||
const filePath = reviewFilePath(corpId, month);
|
||||
const reviews = new Map<string, ReviewRecord>();
|
||||
if (!existsSync(filePath)) return reviews;
|
||||
|
||||
const lines = readFileSync(filePath, "utf8").split("\n");
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as ReviewRecord;
|
||||
if (parsed && typeof parsed.sn === "string" && VERDICTS.has(parsed.verdict)) {
|
||||
reviews.set(parsed.sn, parsed); // 后写覆盖先写
|
||||
}
|
||||
} catch {
|
||||
// 跳过损坏行:单行坏数据不应让整个裁决集不可读
|
||||
}
|
||||
}
|
||||
return reviews;
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加写一条裁决到磁盘(真正的落盘入口)。corpId 由调用方显式传入(sn 与租户无关,文件按租户分片)。
|
||||
*/
|
||||
export function writeReview(
|
||||
corpId: string,
|
||||
input: {
|
||||
sn: string;
|
||||
month: string;
|
||||
verdict: string;
|
||||
reviewedBy?: string;
|
||||
note?: string;
|
||||
recordedAt?: string;
|
||||
}
|
||||
): ReviewRecord {
|
||||
const sn = input.sn?.trim();
|
||||
if (!sn) throw validationError("sn is required for a review record");
|
||||
assertMonth(input.month);
|
||||
assertVerdict(input.verdict);
|
||||
|
||||
const record: ReviewRecord = {
|
||||
sn,
|
||||
month: input.month,
|
||||
verdict: input.verdict,
|
||||
...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}),
|
||||
...(input.note?.trim() ? { note: input.note.trim() } : {}),
|
||||
recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ")
|
||||
};
|
||||
|
||||
const filePath = reviewFilePath(corpId, input.month);
|
||||
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
|
||||
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
|
||||
return record;
|
||||
}
|
||||
Reference in new issue
Block a user