Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
480f833580 | ||
|
|
b21beba419 | ||
|
|
97d1c47a6c | ||
|
|
f6fe0de286 | ||
|
|
f9f72fa918 | ||
|
|
a52b6ac117 | ||
|
|
f8ac839840 | ||
|
|
7df5feb7b7 | ||
|
|
16f3f252c0 | ||
|
|
25d1036eed | ||
|
|
0210051ab7 | ||
|
|
5573dfb60e | ||
|
|
1fb61f794e | ||
|
|
7d15f3834d | ||
|
|
aad591569a | ||
|
|
7304578bc7 | ||
|
|
16a673c910 | ||
|
|
ce1f1f3ca1 | ||
|
|
2177a06f39 | ||
|
|
c0af76f692 | ||
|
|
b2f72959ee | ||
|
|
dd0ca78e5b | ||
|
|
586ad521dc | ||
|
|
75017ab49c | ||
|
|
50414e100a | ||
|
|
4f3fb82856 | ||
|
|
8c7cb219a0 | ||
|
|
d71be55ec8 | ||
|
|
140d7bb33a | ||
|
|
9ef38cda0f | ||
|
|
87b691bd4e | ||
|
|
b3c8e93f0b | ||
|
|
c4a1148cbf | ||
|
|
f788f9c6db | ||
|
|
66673f3878 | ||
|
|
d3659c076c | ||
|
|
2e13b53351 | ||
|
|
59ef8c45db | ||
|
|
7e8b9e6220 | ||
|
|
6a50512c4a | ||
|
|
d3642b93d8 | ||
|
|
9cf3e8ce56 | ||
|
|
90c366ebb2 | ||
|
|
736728496f | ||
|
|
904c9d4b8b | ||
|
|
0efd87a874 | ||
|
|
fb7948307c | ||
|
|
c1a5cc20e9 | ||
|
|
4bee160086 | ||
|
|
fc9e148764 | ||
|
|
fa304ca4dc | ||
|
|
2654e1b870 | ||
|
|
64af86ba9b | ||
|
|
f726c22445 | ||
|
|
c4df5ad325 | ||
|
|
22f4c87ecc | ||
|
|
fa2be3a4e9 | ||
|
|
5a25cd5225 | ||
|
|
67a461452c | ||
|
|
b17bd09194 | ||
|
|
0de2db14ae | ||
|
|
19c8dd3146 | ||
|
|
8c3d98fd98 | ||
|
|
9ece30255e | ||
|
|
8d7f930596 | ||
|
|
6e3d4634f1 | ||
|
|
df44791779 | ||
|
|
f4147cec58 | ||
|
|
aed3a10958 | ||
|
|
7af7be4925 | ||
|
|
152f96ec78 | ||
|
|
2fc88e208c | ||
|
|
042d223704 | ||
|
|
0296c2bff2 | ||
|
|
c094980ae5 | ||
|
|
932957ea08 | ||
|
|
f6cd2c68b0 | ||
|
|
38e1a45fc2 | ||
|
|
fa4113e828 | ||
|
|
793fcff5d5 | ||
|
|
11780f7fe4 | ||
|
|
4583dcc090 | ||
|
|
d069e7232e | ||
|
|
45011c8333 | ||
|
|
e2410e6923 | ||
|
|
fb8a48ea3c | ||
|
|
0a71674c64 | ||
|
|
3918e3de43 | ||
|
|
d4fb3828b7 | ||
|
|
2724ea5490 | ||
|
|
e542c0a5f2 | ||
|
|
8329b294e5 | ||
|
|
e72803ba3c | ||
|
|
e4b1eea5a9 | ||
|
|
482ebf57b5 |
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`。
|
||||
@@ -25,3 +25,20 @@ When modifying or adding TypeScript files in `src/`:
|
||||
|
||||
4. **Architecture**:
|
||||
- Prefer small, cohesive domain functions over large generic utility files.
|
||||
- Place Seal business implementations and their colocated tests in the matching
|
||||
feature directory under `src/domains/seal/`, for example `rules/recode.ts`
|
||||
and `rules/recode.test.ts`. The domain root is reserved for `api.ts`,
|
||||
`api.test.ts`, `types.ts`, and `capabilities.ts`; do not add business files
|
||||
or old-path forwarding stubs there. See `AGENTS.md` for the feature layout.
|
||||
|
||||
5. **Frozen Utility Modules**:
|
||||
- `src/domains/seal/capabilities/helpers.ts` is FROZEN: no new exports. It is
|
||||
the historical catch-all (~85 exports, re-exported into every capability's
|
||||
namespace via `export *`), and `helpers.freeze.test.ts` fails CI when it
|
||||
grows past its line/export ceiling.
|
||||
- Put new logic in a focused module beside the domain that owns it. Moving an
|
||||
existing export OUT of `helpers.ts` is encouraged — then lower the ceiling
|
||||
constants in the ratchet test.
|
||||
- Apply the same instinct to any other module you are tempted to treat as a
|
||||
scrap drawer: if the file's name is `helpers`/`utils`/`common`, it is
|
||||
already a sign the logic belongs somewhere more specific.
|
||||
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
|
||||
@@ -110,5 +118,5 @@ jobs:
|
||||
path: dist/bin/
|
||||
retention-days: 1
|
||||
|
||||
# Gitea asset promotion and Homebrew tap updates are owned by the WSL
|
||||
# Gitea asset promotion is owned by the WSL
|
||||
# seal-use-release-sync.timer after this GitHub Release is published.
|
||||
@@ -3,14 +3,23 @@ node_modules/
|
||||
|
||||
# Build outputs
|
||||
dist/bin/
|
||||
build/
|
||||
|
||||
# Local runtime caches and system noise (regenerate at any time)
|
||||
.cache/
|
||||
.mimosa/
|
||||
.apifox/
|
||||
tmp/
|
||||
|
||||
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
||||
.local/
|
||||
/reports/
|
||||
|
||||
# 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.1",
|
||||
"version": "0.11.8",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
+18
-17
@@ -1,26 +1,27 @@
|
||||
node_modules/
|
||||
.DS_Store
|
||||
*.log
|
||||
.cache/
|
||||
tmp/*
|
||||
!tmp/.gitkeep
|
||||
|
||||
# Build outputs
|
||||
dist/bin/
|
||||
|
||||
# Local runtime caches and system noise (regenerate at any time)
|
||||
.cache/
|
||||
.mimosa/
|
||||
|
||||
# Local enterprise configs can contain credentials.
|
||||
enterprises/*.json
|
||||
!enterprises/example.*.json
|
||||
|
||||
# Local generated reports and exported deliverables.
|
||||
.local/
|
||||
.apifox/
|
||||
exports/
|
||||
scripts/export-*.ts
|
||||
tmp/
|
||||
|
||||
# Local custom linters. Loaded and executed from <cwd>/linters at runtime, so a fresh
|
||||
# clone has none — README.md is tracked to explain the convention, the linters stay private.
|
||||
linters/*
|
||||
!linters/README.md
|
||||
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
||||
.local/
|
||||
/reports/
|
||||
|
||||
# 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
|
||||
|
||||
# ===== ↑ 以上同步自 .gitignore(「从 .gitignore 同步」只重写以上部分)=====
|
||||
.git/
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
## 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`.
|
||||
|
||||
Within `src/domains/seal/`, the root contains only shared protocol boundaries (`api.ts`, `api.test.ts`, `types.ts`) and the public capability export (`capabilities.ts`). Business implementations belong in their feature directories: `rules/`, `approval-runs/`, `insight/`, `replay/`, `outbound/`, `enterprise/`, `search/`, and `testing/`; existing `reports/`, `linter/`, `material-pack/`, `doctor/`, and `regression/` retain their own boundaries. Put new Seal implementations and their tests in the matching feature directory (for example `rules/recode.ts` and `rules/recode.test.ts`), rather than adding business files or legacy forwarding stubs to the domain root. The registry-wide tests live in `capabilities/capabilities.test.ts`.
|
||||
|
||||
Tests are colocated as `*.test.ts` files in `src/`.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
@@ -19,7 +21,7 @@ Tests are colocated as `*.test.ts` files in `src/`.
|
||||
- `bun run lint`: lint with `oxlint src` (zero-warning gate; CI fails on warnings).
|
||||
- `bun test`: run all colocated Bun tests.
|
||||
- `bun run bump <version | patch | minor>`: bump version across all manifest and skill files.
|
||||
- `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the Mac global command (`/opt/homebrew/bin/seal-use`), and sync the local Agent Skill.
|
||||
- `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the existing global command found on PATH (falling back to a standalone bin directory), and sync the local Agent Skill.
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
|
||||
@@ -51,7 +53,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`
|
||||
@@ -101,13 +104,15 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
||||
git push origin refs/tags/vX.Y.Z
|
||||
```
|
||||
- GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release.
|
||||
- **Gitea & Homebrew Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea, and updates the Homebrew tap (`wsl-infra/systemd/`).
|
||||
- **Gitea Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea (`wsl-infra/systemd/`).
|
||||
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
|
||||
|
||||
## Security & Configuration Tips
|
||||
|
||||
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,79 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.8] - 2026-10-15
|
||||
|
||||
### Added
|
||||
- Merge pull request #235 from yunyingk/mac15/streamline-general-report-template
|
||||
- Add pkg/report standalone external validation suite and example report
|
||||
- Decouple chapter numbers from validation and pipeline rendering to allow arbitrary chapter order
|
||||
- Standardize report tables on clean 2-column format with clickable SN
|
||||
- Document user-centric dynamic adaptability principle in agent skill
|
||||
- Add automated audit link column and reconcile divergence metrics
|
||||
- Align Hose document URL with backlogDetail hash routing
|
||||
- Refine approval run URL resolution with Hose fallback and SSO
|
||||
|
||||
|
||||
## [0.11.7] - 2026-10-13
|
||||
|
||||
### Added
|
||||
- Merge pull request #233 from yunyingk/mac15/monthly-report-reference
|
||||
- Add lightweight report data capability and authoring reference
|
||||
|
||||
|
||||
## [0.11.6] - 2026-10-13
|
||||
|
||||
### Added
|
||||
- Merge pull request #230 from yunyingk/mac15/rule-import-renumber
|
||||
- Harden post-write error codes, rules push recovery ledger, and capability param normalization
|
||||
- Merge remote-tracking branch 'origin/main' into mac15/rule-import-renumber
|
||||
- Merge pull request #231 from yunyingk/mac15/venn-chart-4x
|
||||
- Add companion XLSX/CSV report ledgers and unify reviewed accuracy metrics
|
||||
- Organize Seal modules and add guarded rule recoding
|
||||
- Refine report asset naming and include review notes in section 6
|
||||
- Fix Venn chart dynamic rendering and eliminate EEKA mock data across report sections
|
||||
|
||||
|
||||
## [0.11.5] - 2026-10-10
|
||||
|
||||
### Added
|
||||
- Merge pull request #215 from yunyingk/mac15/hosecloud-test-outbound
|
||||
- Update agent skill docs for Hose outbound replay and test-outbound
|
||||
- Add Hose outbound replay with CloseAPI log matching and safety guards
|
||||
- Merge pull request #214 from yunyingk/mac15/unify-expire-duration-parsing
|
||||
- Unify assistance link duration parsing with hour floor and stderr hints
|
||||
- Merge pull request #213 from yunyingk/mac15/support-delegation-expire-config
|
||||
- Add configurable expiration for Seal and Hose assistance links
|
||||
|
||||
|
||||
## [0.11.4] - 2026-10-10
|
||||
|
||||
### Added
|
||||
- Merge pull request #211 from yunyingk/mac15/diagnose-simulation-dx-improvements
|
||||
- Refine simulation DX, diagnose fields extraction, and rule mapping
|
||||
|
||||
|
||||
## [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
|
||||
|
||||
@@ -39,7 +39,7 @@ After installation:
|
||||
seal-use version # Check version
|
||||
seal-use skill install # Install Agent skill to ~/.agents/skills/seal-use
|
||||
seal-use mcp-config # Print an MCP server snippet (for Cursor / Claude Desktop / Codex)
|
||||
seal-use update # Self-update (GitHub Releases binary, Homebrew, or source)
|
||||
seal-use update # Self-update (release binary or source checkout)
|
||||
```
|
||||
|
||||
## Source Setup & Development
|
||||
@@ -62,7 +62,7 @@ npm link
|
||||
seal-use version
|
||||
```
|
||||
|
||||
`npm link` creates a symlink from `/opt/homebrew/lib/node_modules/seal-use` → your local checkout. The `seal-use` binary on PATH then runs source files directly via bun — **no reinstall needed after editing source code**.
|
||||
`npm link` creates a symlink from the global npm package directory (`npm root -g`) to your local checkout. The `seal-use` binary on PATH then runs source files directly via bun — **no reinstall needed after editing source code**.
|
||||
|
||||
> ⚠️ **Do NOT use `npm install -g .`** for development. That copies files into the global node_modules directory and the copy becomes stale as soon as you edit the source. Always use `npm link` so edits take effect immediately.
|
||||
|
||||
@@ -129,13 +129,13 @@ Update an existing checkout:
|
||||
seal-use update
|
||||
```
|
||||
|
||||
`seal-use update` adapts to how it was installed: from a source checkout it runs `git pull --ff-only` and refreshes dependencies with `bun install`; a standalone binary downloads the matching GitHub Release asset and replaces itself; a Homebrew install upgrades through `brew upgrade seal-use`.
|
||||
`seal-use update` adapts to how it was installed: from a source checkout it runs `git pull --ff-only` and refreshes dependencies with `bun install`; a standalone binary downloads the matching GitHub Release asset and replaces itself.
|
||||
|
||||
Because `npm link` makes the global command a symlink into your checkout, **updating the checkout is sufficient** — no reinstall step required. The symlink continues to point to the updated source.
|
||||
|
||||
Enterprise configs live only in the global directory `~/.config/seal-use/enterprises` (legacy fallback `~/.config/seal-home/enterprises`); the project tree carries none.
|
||||
|
||||
The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.agents/skills/seal-use` symlink; run `seal-use skill install` (or copy that folder yourself) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`.
|
||||
The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.agents/skills/seal-use` symlink; run `seal-use skill install` (or `seal-use skill install --dir <target>`) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`. The installer includes the full embedded manifest, including report references sourced outside that folder; manually copying only the skill folder omits those references.
|
||||
|
||||
## ZCode Plugin
|
||||
|
||||
@@ -214,7 +214,7 @@ Most users do not need MCP. The public/shared path is the global `seal-use` CLI.
|
||||
|
||||
### One registry, two doors
|
||||
|
||||
All approval/logic lives once in the capability registry under `src/domains/seal/capabilities/` (`src/domains/seal/capabilities.ts` re-exports it). Two surfaces enter the same handlers, each with its own naming:
|
||||
Shared approval behavior lives in the business modules under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` dispatches it (`src/domains/seal/capabilities.ts` re-exports the registry). Two surfaces enter the same handlers, each with its own naming:
|
||||
|
||||
| Surface | Entry | Naming |
|
||||
| --- | --- | --- |
|
||||
@@ -240,6 +240,8 @@ Both run the same CLI dispatcher as the global binary, so `config` and `update`
|
||||
|
||||
## CLI-First Architecture
|
||||
|
||||
Seal implementations and their tests are grouped by feature: `src/domains/seal/rules/` owns local rule files, diffs, mappings, version snapshots, recoding and confirmation tickets; `approval-runs/` owns record export and attachments; `insight/` owns insight export; `replay/` owns Webhook/Hose replay and environment guards; `outbound/` owns downstream pushes; `enterprise/` owns Seal onboarding and identity resolution; `search/` owns cross-resource search; and `testing/` owns test-enterprise synchronization. Existing `reports/`, `linter/`, `material-pack/`, `doctor/` and `regression/` stay separate. Only shared API/types and the capability export remain at the domain root.
|
||||
|
||||
All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the `seal_use` / `seal_use_write` MCP tools passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`.
|
||||
|
||||
Key CLI command groups:
|
||||
@@ -256,6 +258,8 @@ For rule list commands, prefer `seal-use rules count --corp <corpId>` or `seal-u
|
||||
|
||||
For test tenants that need a clean slate before importing another rule set, use `seal-use rules clear --corp <corpId> --dry-run` first, then `seal-use rules clear --corp <corpId> --yes` to delete the current draft rules and verify the remaining count.
|
||||
|
||||
To compact draft rule numbers from `0000`, run `seal-use rules recode --corp <corpId>`. The first call returns an impact preview and an enterprise/environment/draft-bound one-use credential (exit 10), without executing the recode. Inspect the preview, then run the returned `nextCommand` separately; the credential expires after five minutes, and `--yes` cannot bypass it. `--dry-run` only previews. The server determines ordering, and every rule can change number; the verified per-rule mapping is returned after execution. Recode does not publish a version; old rule numbers must be interpreted with their published version. Clearing and test synchronization reset numbering only after verifying an empty draft.
|
||||
|
||||
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
|
||||
|
||||
## Approval Run To Langfuse Bridge
|
||||
@@ -330,4 +334,4 @@ bun run bump 0.8.5
|
||||
**CI & Promotion Pipeline:**
|
||||
- GitHub Actions triggers automatically upon pushing a `v*` tag to `origin`;
|
||||
- Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) and publishes them to **[GitHub Releases](https://github.com/yunyingk/seal-use/releases)**;
|
||||
- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** and the Homebrew tap (`ops/README.md`).
|
||||
- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** (`wsl-infra/README.md`).
|
||||
+15
-2
@@ -17,20 +17,33 @@ initial response within a few business days — this is a small project, not a s
|
||||
|
||||
| Path | Contents | Mode |
|
||||
| --- | --- | --- |
|
||||
| `~/.config/seal-use/seal_tokens.json` | Session tokens and derived keys | `0600` |
|
||||
| `~/.config/seal-use/tokens.json` | Session tokens and derived keys | `0600` |
|
||||
| `~/.config/seal-use/enterprises/*.json` | Per-enterprise Hose app key/password or Seal bearer token | `0600` |
|
||||
| `enterprises/*.json` (working tree) | Same, for enterprises added from a checkout | `0600` |
|
||||
| `~/.config/seal-use/usage.json` | Per-enterprise command counts | `0600` |
|
||||
| `~/.cache/seal-use/usage.json` | Per-enterprise command counts | `0600` |
|
||||
|
||||
The tool writes these `0600`; a config placed by hand can keep the `0o644` default, so
|
||||
`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/seal-use/langfuse/` (plus legacy `.cache/langfuse/` entries) 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
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
"exceljs": "^4.4.0",
|
||||
"iconv-lite": "^0.7.3",
|
||||
"ky": "^2.0.2",
|
||||
"marked": "15.0.12",
|
||||
"pinyin-pro": "^3.29.3",
|
||||
"pngjs": "7.0.0",
|
||||
"yauzl": "^3.4.0",
|
||||
"zod": "^4.4.3",
|
||||
},
|
||||
@@ -17,6 +19,7 @@
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/archiver": "^8.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/pngjs": "6.0.5",
|
||||
"@types/yauzl": "^3.4.0",
|
||||
"bun-types": "^1.3.14",
|
||||
"oxlint": "1.86.0",
|
||||
@@ -80,6 +83,8 @@
|
||||
|
||||
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
|
||||
|
||||
"@types/pngjs": ["@types/pngjs@6.0.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ=="],
|
||||
|
||||
"@types/readdir-glob": ["@types/readdir-glob@1.1.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg=="],
|
||||
|
||||
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
|
||||
@@ -228,6 +233,8 @@
|
||||
|
||||
"lodash.uniq": ["lodash.uniq@4.5.0", "", {}, "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ=="],
|
||||
|
||||
"marked": ["marked@15.0.12", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="],
|
||||
|
||||
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
|
||||
|
||||
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
|
||||
@@ -250,6 +257,8 @@
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"pngjs": ["pngjs@7.0.0", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
|
||||
|
||||
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
|
||||
|
||||
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.1",
|
||||
"version": "0.11.8",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
@@ -43,7 +43,9 @@
|
||||
"exceljs": "^4.4.0",
|
||||
"iconv-lite": "^0.7.3",
|
||||
"ky": "^2.0.2",
|
||||
"marked": "15.0.12",
|
||||
"pinyin-pro": "^3.29.3",
|
||||
"pngjs": "7.0.0",
|
||||
"yauzl": "^3.4.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -51,6 +53,7 @@
|
||||
"@modelcontextprotocol/client": "^2.0.0",
|
||||
"@types/archiver": "^8.0.0",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/pngjs": "6.0.5",
|
||||
"@types/yauzl": "^3.4.0",
|
||||
"bun-types": "^1.3.14",
|
||||
"oxlint": "1.86.0",
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。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 与人工审核准确率对比*
|
||||
|
||||
---
|
||||
|
||||
## 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 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||
---
|
||||
|
||||
## 5. 审核分歧与复核归因
|
||||
|
||||
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
|
||||
|
||||
| 原因分类 | 占比 | 单数 | 核心说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
|
||||
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
|
||||
| 合计 | 100% | 3 张 | — |
|
||||
|
||||
**分歧分析与后续建议**:
|
||||
|
||||
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
|
||||
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
|
||||
|
||||
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
|
||||
|
||||
---
|
||||
|
||||
## 6. 支撑数据与交付材料
|
||||
|
||||
### 6.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 类)*
|
||||
|
||||
### 6.2 跑批原始数据与交付台账
|
||||
|
||||
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
|
||||
@@ -0,0 +1,120 @@
|
||||
# AI 审核报告(Markdown)独立编制与校验套件
|
||||
|
||||
本套件是面向**外部交付、客户协作与第三方审核团队**的独立版 AI 审核报告验证工具包。
|
||||
|
||||
---
|
||||
|
||||
## 一、核心定位与特点
|
||||
|
||||
1. **零环境依赖**:基于纯 Python 标准库编写(Python 3.8+),无需安装 `seal-use`,无需 Node.js / Bun,跨平台(macOS / Linux / Windows)开箱即用。
|
||||
2. **纯粹面向 Markdown**:专注于 Markdown 报告文档本身的格式纯净度、结构严密性与数学总账守恒;**不强求本地 Excel 伴生台账**,**无需手动填写任何技术跳转链接**。
|
||||
3. **核心章节硬匹配,自定义章节完全放行**:核心论证章节按大标题名称硬匹配认领;中间任意插入的部门专项分析、整改排期等章节,校验器一律视为纯叙述业务章节,不施加任何教条规则,直接绿色放行!
|
||||
|
||||
---
|
||||
|
||||
## 二、目录结构
|
||||
|
||||
```text
|
||||
pkg/report/
|
||||
├── README.md # 本使用指南与规范手册
|
||||
├── validate.py # 独立离线校验脚本(纯标准库)
|
||||
├── example-report.md # 100% 格式合规的标准示例月报
|
||||
└── assets/ # 示例配图资产
|
||||
└── 图1-准确率对比.svg
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、快速上手
|
||||
|
||||
### 1. 快速校验一份 Markdown 报告
|
||||
|
||||
```bash
|
||||
# 进入本目录
|
||||
cd pkg/report
|
||||
|
||||
# 执行校验
|
||||
python3 validate.py example-report.md
|
||||
```
|
||||
|
||||
**校验通过输出示例**:
|
||||
```text
|
||||
✅ 报告文件: /path/to/example-report.md
|
||||
📊 识别表格: 14 个 | 配图资产: 1 个
|
||||
🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。
|
||||
```
|
||||
|
||||
### 2. 输出机器可读的 JSON 结构(方便接入 CI/CD 或自动化流水线)
|
||||
|
||||
```bash
|
||||
python3 validate.py example-report.md --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、报告大纲与编写原则
|
||||
|
||||
一份合格的 AI 审核商业月度报告,遵循**“骨架刚性、血肉自适应”**的设计理念:
|
||||
|
||||
### 1. 核心必选骨架(通过大标题名称硬匹配)
|
||||
|
||||
无论章节编号是第几章,系统只要匹配到大标题名称,就会认领对应的业务校验:
|
||||
|
||||
| 核心大标题名称 | 核心作用与定位 | 必须遵守的业务守恒 |
|
||||
| :--- | :--- | :--- |
|
||||
| **开篇「报告信息」表** | 抬头身份证明 | 必含 5 字段:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
|
||||
| **`审核测试结果`** | 核心业绩表态 | 包含样本总量、AI/人工准确率结论、LaTeX 准确率公式(`\frac{A}{B} = C\%`)及对比图。 |
|
||||
| **`AI 失准分析`** | 坦白 AI 误判与偏差 | 包含失准构成总览表、TOP 1~N 典型案例表格与针对性调优解决方案。 |
|
||||
| **`AI 发现的潜在风险`** | 力证风控拦截价值 | 包含潜在风险总览表、TOP 1~N 凭证缺失、比价缺失、超期等真实拦截案例。 |
|
||||
| **`综合效益`** | 总结人效与风控收益 | 时效、准确度、风险拦截笔数宏观总结表(纯内部对账时可按需裁剪)。 |
|
||||
| **`审核分歧与复核归因`** | 人机分歧深度定性 | 分类统计表(线上规则未覆盖 vs 模型偏差)与口头管控标准线上化管理建议。 |
|
||||
| **`支撑数据与交付材料`** | 分模板细分数据 | 分模板准确率与自动化率汇总表,说明底层流水交付物。 |
|
||||
|
||||
### 2. 中间随意插入的自定义章节(完全自由放行)
|
||||
|
||||
如果针对具体企业的特定管理需要,想在报告中间插入业务专属章节(例如在第 1 章后插入 `## 2. 营销大区差旅合规专项穿透`):
|
||||
* **系统处理方式**:大标题名称不在核心名单里的章节,校验器一律视为**纯叙述业务章节**;
|
||||
* **自由度**:不限制表格列数、不限制行数、不强制要求数学守恒,写什么内容都直接放行!
|
||||
* **唯一要求**:大章节使用 `##`,章节编号从 1 开始自然连续递增(1, 2, 3, 4, 5...),子小节使用 `###` 且不跳级。
|
||||
|
||||
### 3. 表格案例与链接约定
|
||||
|
||||
* 案例表格推荐使用纯净紧凑的 **2 列规范**(`| 单号 | 问题描述 |`);
|
||||
* 编写 Markdown 时**无需手动查询或粘贴长串后台技术 URL**,专注于业务事实描述即可。
|
||||
|
||||
---
|
||||
|
||||
## 五、校验规则与错误代码速查表
|
||||
|
||||
`validate.py` 内部内置了以下质量红线校验门禁。如果报告校验未通过,终端会指出具体问题行号与代码:
|
||||
|
||||
| 错误代码 | 校验类别 | 规则说明与修复指南 |
|
||||
| :--- | :--- | :--- |
|
||||
| **`FM001`** | 格式纯净 | 严禁以 YAML Frontmatter(`---`)开头;元数据请写在正文开头的「报告信息」表中。 |
|
||||
| **`MK001`** | 格式纯净 | 严禁残留模板草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等)。 |
|
||||
| **`MD001`** | 格式规范 | 代码围栏(反引号 ```)必须成对闭合,不可出现单数个。 |
|
||||
| **`TB001`** | 表格对齐 | 每行数据单元格按 `\|` 拆分后的列数,必须严格等于表头列数。 |
|
||||
| **`TB002`** | 表格规范 | 表头文字必须保持纯文本,禁止包含 `**` 加粗符号。 |
|
||||
| **`HD001`** | 标题层级 | 禁止跳级(如 `#` 一级标题直接跳到 `###` 三级标题)。 |
|
||||
| **`HD002`** | 标题序号 | 二级大章节编号(`## \d+\.`)必须从 1 开始连续递增,不得跳号。 |
|
||||
| **`INFO001`** | 头部元数据 | 开篇「报告信息」表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。 |
|
||||
| **`INFO002`** | 头部元数据 | 开篇「报告信息」表的 5 项元数据值均不能为空白。 |
|
||||
| **`IMG001`** | 资产存活 | 文档中引用的本地相对路径图片(如 `.svg` / `.png`)在磁盘必须真实存在。 |
|
||||
| **`NM001`** | 数学守恒 | 【失准分析】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
|
||||
| **`NM002`** | 数学守恒 | 【潜在风险】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
|
||||
| **`NM003`** | 数学守恒 | 分类总览表中声明的占比百分比与 `单数 / 合计` 计算误差不得超过 0.15%。 |
|
||||
| **`NM004`** | 数学守恒 | 【分歧归因】分类表各原因单数相加必须等于分歧总数,且与正文叙述一致。 |
|
||||
| **`NM005`** | 数学守恒 | LaTeX 公式 `\frac{A}{B} = C\%` 算术必须成立,且公式中的数字在正文中有数据来源。 |
|
||||
|
||||
---
|
||||
|
||||
## 六、常见问题解答 (FAQ)
|
||||
|
||||
**Q:编写报告时,出现失准或风险分类不是 3 种怎么办?**
|
||||
A:完全自由!如果有 2 种就列 TOP 1~2,有 4 种就列 TOP 1~4,只要总览表中这几项的单数加起来等于合计行、百分比加起来等于 100% 即可通过校验。
|
||||
|
||||
**Q:案例表格必须放 3 行吗?**
|
||||
A:不需要。可放 1 行典型单据,也可放 5 行全量单据,表格行数完全由业务深度决定。
|
||||
|
||||
**Q:为什么提示公式算术不成立(`NM005`)?**
|
||||
A:请检查 LaTeX 公式中的分子除以分母计算出的百分比,与等号右边的数值是否一致(如 $221 / 240 = 92.0833\% \approx 92.08\%$,如果写成 95% 则会被拦截)。
|
||||
@@ -0,0 +1,51 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="400" viewBox="0 0 960 400" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif">
|
||||
<defs>
|
||||
<!-- 精确交集透镜裁剪路径 -->
|
||||
<clipPath id="left-circle-clip">
|
||||
<circle cx="410" cy="160" r="135"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect width="960" height="400" fill="#ffffff"/>
|
||||
|
||||
<!-- Left Circle: Pastel Blue -->
|
||||
<circle cx="410" cy="160" r="135" fill="#b9deff"/>
|
||||
|
||||
<!-- Right Circle: Pastel Mint -->
|
||||
<circle cx="550" cy="160" r="135" fill="#d2ede8"/>
|
||||
|
||||
<!-- Distinct Intersection Lens: Perfect blend tone (#9ed4eb) -->
|
||||
<circle cx="550" cy="160" r="135" clip-path="url(#left-circle-clip)" fill="#9ed4eb"/>
|
||||
|
||||
<!-- Left Text Block (Horizontally centered lines) -->
|
||||
<g text-anchor="middle" fill="#111111">
|
||||
<text x="140" y="146" font-size="18"><tspan letter-spacing="1.5px">AI</tspan><tspan letter-spacing="0px">审核准确</tspan></text>
|
||||
<text x="140" y="176" font-size="18">(总准确率92.08%)</text>
|
||||
</g>
|
||||
<!-- Left dashed line: comfortable gap from text, extends into circle -->
|
||||
<line x1="245" y1="160" x2="310" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Left percentage -->
|
||||
<text x="348" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">16.66%</text>
|
||||
|
||||
<!-- Overlap percentage (in intersection lens) -->
|
||||
<text x="480" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">75.42%</text>
|
||||
|
||||
<!-- Right percentage -->
|
||||
<text x="612" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">7.91%</text>
|
||||
|
||||
<!-- Right dashed line -->
|
||||
<line x1="650" y1="160" x2="715" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Right Text Block (Horizontally centered lines) -->
|
||||
<g text-anchor="middle" fill="#111111">
|
||||
<text x="820" y="146" font-size="18">人工审核准确</text>
|
||||
<text x="820" y="176" font-size="18">(总准确率83.33%)</text>
|
||||
</g>
|
||||
|
||||
<!-- Bottom vertical dashed pointer -->
|
||||
<line x1="480" y1="215" x2="480" y2="305" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Bottom label: refined kerning on AI and comfortable character spacing -->
|
||||
<text x="480" y="338" font-size="18" fill="#111111" text-anchor="middle" dominant-baseline="central"><tspan letter-spacing="2px">AI</tspan><tspan letter-spacing="1px">与人工都准确</tspan></text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,190 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。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 与人工审核准确率对比*
|
||||
|
||||
---
|
||||
|
||||
## 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 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||
---
|
||||
|
||||
## 5. 审核分歧与复核归因
|
||||
|
||||
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
|
||||
|
||||
| 原因分类 | 占比 | 单数 | 核心说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
|
||||
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
|
||||
| 合计 | 100% | 3 张 | — |
|
||||
|
||||
**分歧分析与后续建议**:
|
||||
|
||||
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
|
||||
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
|
||||
|
||||
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
|
||||
|
||||
---
|
||||
|
||||
## 6. 支撑数据与交付材料
|
||||
|
||||
### 6.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 类)*
|
||||
|
||||
### 6.2 跑批原始数据与交付台账
|
||||
|
||||
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
|
||||
Executable
+375
@@ -0,0 +1,375 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI 审核报告(Markdown)独立校验器
|
||||
Independent Markdown Validator for AI Audit Reports
|
||||
|
||||
特点:
|
||||
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台(macOS / Linux / Windows)
|
||||
- 专为外部协同与客户交付设计:不依赖 seal-use、不强求本地 Excel 伴生台账
|
||||
- 核心章节硬匹配大标题名称:中间任意插入的自定义章节完全自由放行
|
||||
- 严格守护格式合规与数学总账守恒
|
||||
|
||||
用法:
|
||||
python3 validate.py <report.md>
|
||||
python3 validate.py <report.md> --json
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
|
||||
REQUIRED_INFO_ROWS = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
|
||||
FORBIDDEN_MARKS = [
|
||||
(re.compile(r"<!--slot:"), "slot 标记"),
|
||||
(re.compile(r"<!--/slot"), "slot 闭合"),
|
||||
(re.compile(r"<!--@"), "@table/@block 区域标记"),
|
||||
(re.compile(r"<!-- render:stop"), "render:stop 标记"),
|
||||
(re.compile(r"\{\{"), "{{槽位}}"),
|
||||
]
|
||||
|
||||
class ReportIssue:
|
||||
def __init__(self, level: str, code: str, message: str, line: Optional[int] = None):
|
||||
self.level = level # "ERROR" | "WARN"
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.line = line
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
d: Dict[str, Any] = {"level": self.level, "code": self.code, "message": self.message}
|
||||
if self.line is not None:
|
||||
d["line"] = self.line
|
||||
return d
|
||||
|
||||
|
||||
class TableRow:
|
||||
def __init__(self, line_num: int, cells: List[str]):
|
||||
self.line_num = line_num
|
||||
self.cells = cells
|
||||
|
||||
|
||||
class ParsedTable:
|
||||
def __init__(self, line_num: int, header: List[str], rows: List[TableRow]):
|
||||
self.line_num = line_num
|
||||
self.header = header
|
||||
self.rows = rows
|
||||
|
||||
|
||||
def split_cells(line: str) -> List[str]:
|
||||
text = line.strip()
|
||||
if text.startswith("|"):
|
||||
text = text[1:]
|
||||
if text.endswith("|") and not text.endswith(r"\|"):
|
||||
text = text[:-1]
|
||||
# Split on unescaped pipe
|
||||
raw_cells = re.split(r"(?<!\\)\|", text)
|
||||
return [c.replace(r"\|", "|").strip() for c in raw_cells]
|
||||
|
||||
|
||||
def parse_tables(lines: List[str]) -> List[ParsedTable]:
|
||||
result: List[ParsedTable] = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
line = lines[i].strip()
|
||||
if i + 1 < len(lines):
|
||||
separator = lines[i + 1].strip()
|
||||
if line.startswith("|") and "-" in separator and re.match(r"^[|\-: ]+$", separator):
|
||||
header = split_cells(line)
|
||||
table = ParsedTable(line_num=i + 1, header=header, rows=[])
|
||||
i += 2
|
||||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||||
table.rows.append(TableRow(line_num=i + 1, cells=split_cells(lines[i])))
|
||||
i += 1
|
||||
result.append(table)
|
||||
continue
|
||||
i += 1
|
||||
return result
|
||||
|
||||
|
||||
def extract_numeric(text: str, is_percent: bool = False) -> Optional[float]:
|
||||
pattern = r"(\d+(?:\.\d+)?)\s*%" if is_percent else r"(\d+(?:\.\d+)?)"
|
||||
m = re.search(pattern, text)
|
||||
if m:
|
||||
try:
|
||||
return float(m.group(1))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def validate_report(filepath: str) -> Dict[str, Any]:
|
||||
path = Path(filepath).resolve()
|
||||
if not path.is_file():
|
||||
return {
|
||||
"file": str(path),
|
||||
"valid": False,
|
||||
"tables": 0,
|
||||
"figures": 0,
|
||||
"issues": [{"level": "ERROR", "code": "FS001", "message": f"文件不存在: {filepath}"}],
|
||||
}
|
||||
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
text = f.read().replace("\r\n", "\n").replace("\r", "\n")
|
||||
|
||||
lines = text.split("\n")
|
||||
issues: List[ReportIssue] = []
|
||||
|
||||
def add_error(code: str, message: str, line: Optional[int] = None):
|
||||
issues.append(ReportIssue(level="ERROR", code=code, message=message, line=line))
|
||||
|
||||
# 1. 纯净性:严禁 Frontmatter 和 模板草稿占位标记
|
||||
if text.startswith("---\n"):
|
||||
add_error("FM001", "文件以 YAML frontmatter 开头;元数据请放正文开头的「报告信息」表格中", line=1)
|
||||
for pattern, name in FORBIDDEN_MARKS:
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
if pattern.search(l):
|
||||
add_error("MK001", f"出现模板未渲染痕迹({name}),交付文件应为纯 Markdown 文档", line=idx)
|
||||
|
||||
# 2. 代码围栏成对闭合
|
||||
fences = [idx for idx, l in enumerate(lines, start=1) if l.strip().startswith("```")]
|
||||
if len(fences) % 2 != 0:
|
||||
add_error("MD001", f"代码围栏为奇数(共 {len(fences)} 个),存在未闭合代码块", line=fences[-1] if fences else None)
|
||||
|
||||
# 3. 表格结构规范(列对齐、表头无加粗)
|
||||
parsed_tables = parse_tables(lines)
|
||||
for table in parsed_tables:
|
||||
header_len = len(table.header)
|
||||
for row in table.rows:
|
||||
if len(row.cells) != header_len:
|
||||
add_error("TB001", f"第 {row.line_num} 行表格列数 {len(row.cells)} ≠ 表头 {header_len} 列", line=row.line_num)
|
||||
for cell in table.header:
|
||||
if "**" in cell:
|
||||
add_error("TB002", f"第 {table.line_num} 行表头含有加粗标记 **(表头应保持纯文本)", line=table.line_num)
|
||||
|
||||
# 4. 标题层级与章节序号连续性
|
||||
previous_level = 0
|
||||
numbered_h2s: List[Tuple[int, str, int]] = [] # (chapter_num, full_heading, line_num)
|
||||
chapters: List[Dict[str, Any]] = []
|
||||
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
m = re.match(r"^(#{1,6})\s+(.*)$", l)
|
||||
if not m:
|
||||
continue
|
||||
level = len(m.group(1))
|
||||
heading_text = m.group(2).strip()
|
||||
if previous_level > 0 and level > previous_level + 1:
|
||||
add_error("HD001", f"标题层级跳级(从 H{previous_level} 直接跳到 H{level}):{heading_text[:40]}", line=idx)
|
||||
previous_level = level
|
||||
|
||||
if level == 2:
|
||||
num_match = re.match(r"^(\d+)\.", heading_text)
|
||||
if num_match:
|
||||
numbered_h2s.append((int(num_match.group(1)), heading_text, idx))
|
||||
chapters.append({"heading": heading_text, "start_line": idx, "line_num": idx})
|
||||
|
||||
# 检查大标题数字是否严格连续递增:1, 2, 3...
|
||||
if numbered_h2s:
|
||||
seen_nums = [item[0] for item in numbered_h2s]
|
||||
expected_nums = list(range(1, len(seen_nums) + 1))
|
||||
if seen_nums != expected_nums:
|
||||
add_error("HD002", f"## 大章节编号应自 1 开始连续递增,期望 {expected_nums},实际 {seen_nums}", line=numbered_h2s[0][2])
|
||||
|
||||
# 为每个大章节划分文本切片(从当前 ## 到下一个 ##)
|
||||
for i, chap in enumerate(chapters):
|
||||
start_idx = chap["start_line"] - 1
|
||||
end_idx = chapters[i + 1]["start_line"] - 1 if i + 1 < len(chapters) else len(lines)
|
||||
chap["text"] = "\n".join(lines[start_idx:end_idx])
|
||||
|
||||
def find_chapter_by_keyword(kw: str) -> Optional[Dict[str, Any]]:
|
||||
for c in chapters:
|
||||
if kw in c["heading"]:
|
||||
return c
|
||||
return None
|
||||
|
||||
def by_header_in_scope(keyword: str, scope_lines: Optional[List[str]] = None) -> Optional[ParsedTable]:
|
||||
target_tables = parse_tables(scope_lines) if scope_lines is not None else parsed_tables
|
||||
for t in target_tables:
|
||||
header_str = "".join(t.header).replace(" ", "")
|
||||
if keyword in header_str:
|
||||
return t
|
||||
return None
|
||||
|
||||
# 5. 开篇「报告信息」表完备性
|
||||
info_table = by_header_in_scope("报告信息")
|
||||
if not info_table:
|
||||
add_error("INFO001", "缺少开篇「报告信息」表(必须包含客户名称、期间、报告编号等元数据)")
|
||||
else:
|
||||
existing_keys = {r.cells[0] for r in info_table.rows if r.cells}
|
||||
missing_keys = [k for k in REQUIRED_INFO_ROWS if k not in existing_keys]
|
||||
if missing_keys:
|
||||
add_error("INFO001", f"「报告信息」表缺少必要字段:{', '.join(missing_keys)}", line=info_table.line_num)
|
||||
empty_keys = [r.cells[0] for r in info_table.rows if len(r.cells) > 1 and not r.cells[1].strip()]
|
||||
if empty_keys:
|
||||
add_error("INFO002", f"「报告信息」表以下字段值为空:{', '.join(empty_keys)}", line=info_table.line_num)
|
||||
|
||||
# 6. 本地图片资产存活性
|
||||
figure_count = 0
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
for img_match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", l):
|
||||
figure_count += 1
|
||||
src = img_match.group(1).strip()
|
||||
if src.startswith("http://") or src.startswith("https://") or src.startswith("data:"):
|
||||
continue
|
||||
# 解码 URL 编码的中文路径
|
||||
try:
|
||||
import urllib.parse
|
||||
decoded_src = urllib.parse.unquote(src)
|
||||
except Exception:
|
||||
decoded_src = src
|
||||
target_path = (path.parent / decoded_src).resolve()
|
||||
if not target_path.exists():
|
||||
add_error("IMG001", f"本地引用的图片文件不存在:{src}", line=idx)
|
||||
|
||||
# 7. 核心业务章节硬匹配校验与数学总账守恒
|
||||
|
||||
# 7.1 【AI 失准分析】核心章节
|
||||
mismatch_chapter = find_chapter_by_keyword("失准")
|
||||
if mismatch_chapter:
|
||||
c_lines = mismatch_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("失准类型", c_lines)
|
||||
if table:
|
||||
tops = []
|
||||
totals = []
|
||||
for r in table.rows:
|
||||
if len(r.cells) > 3:
|
||||
if r.cells[0].startswith("TOP"):
|
||||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||||
totals.append(extract_numeric(r.cells[3]))
|
||||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||||
if s != totals[0]:
|
||||
add_error("NM001", f"失准类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||||
base = totals[0]
|
||||
for r in table.rows:
|
||||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||||
share = extract_numeric(r.cells[2], is_percent=True)
|
||||
count = extract_numeric(r.cells[3])
|
||||
if share is not None and count is not None and base > 0:
|
||||
calc_share = (count / base) * 100
|
||||
if abs(calc_share - share) > 0.15:
|
||||
add_error("NM003", f"失准类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||||
# 校验小节标题张数与总览表严格一致
|
||||
for top in tops:
|
||||
esc = re.escape(top["name"])
|
||||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", mismatch_chapter["text"])
|
||||
if m and top["count"] is not None:
|
||||
c_in_h = int(m.group(1))
|
||||
if c_in_h != int(top["count"]):
|
||||
add_error("NM001", f"失准分析 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||||
|
||||
# 7.2 【AI 发现的潜在风险】核心章节
|
||||
risk_chapter = find_chapter_by_keyword("风险")
|
||||
if risk_chapter:
|
||||
c_lines = risk_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("风险类型", c_lines)
|
||||
if table:
|
||||
tops = []
|
||||
totals = []
|
||||
for r in table.rows:
|
||||
if len(r.cells) > 3:
|
||||
if r.cells[0].startswith("TOP"):
|
||||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||||
totals.append(extract_numeric(r.cells[3]))
|
||||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||||
if s != totals[0]:
|
||||
add_error("NM002", f"风险类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||||
base = totals[0]
|
||||
for r in table.rows:
|
||||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||||
share = extract_numeric(r.cells[2], is_percent=True)
|
||||
count = extract_numeric(r.cells[3])
|
||||
if share is not None and count is not None and base > 0:
|
||||
calc_share = (count / base) * 100
|
||||
if abs(calc_share - share) > 0.15:
|
||||
add_error("NM003", f"风险类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||||
for top in tops:
|
||||
esc = re.escape(top["name"])
|
||||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", risk_chapter["text"])
|
||||
if m and top["count"] is not None:
|
||||
c_in_h = int(m.group(1))
|
||||
if c_in_h != int(top["count"]):
|
||||
add_error("NM002", f"潜在风险 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||||
|
||||
# 7.3 【审核分歧与复核归因】核心章节
|
||||
diverged_chapter = find_chapter_by_keyword("分歧") or find_chapter_by_keyword("复核归因")
|
||||
if diverged_chapter:
|
||||
c_lines = diverged_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("原因分类", c_lines)
|
||||
if table:
|
||||
count_idx = -1
|
||||
for ci, col in enumerate(table.header):
|
||||
if "单数" in col:
|
||||
count_idx = ci
|
||||
break
|
||||
if count_idx >= 0:
|
||||
rows = [r.cells for r in table.rows]
|
||||
non_totals = [r for r in rows if r and r[0] not in ["合计", "总计", "—"]]
|
||||
total_row = next((r for r in rows if r and r[0] in ["合计", "总计", "—"]), None)
|
||||
s = sum(extract_numeric(r[count_idx]) or 0 for r in non_totals if len(r) > count_idx)
|
||||
if total_row and len(total_row) > count_idx:
|
||||
tv = extract_numeric(total_row[count_idx])
|
||||
if tv is not None and s != tv:
|
||||
add_error("NM004", f"原因分类各维度单数之和 {s} ≠ 合计 {tv}", line=table.line_num)
|
||||
|
||||
# 7.4 LaTeX 公式算术自洽
|
||||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
||||
outside_text = "\n".join([l for l in lines if not l.strip().startswith("$$")])
|
||||
for fl in formula_lines:
|
||||
for frac_match in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", fl):
|
||||
a = int(frac_match.group(1))
|
||||
b = int(frac_match.group(2))
|
||||
pct_val = float(frac_match.group(3))
|
||||
if b > 0:
|
||||
real_pct = (a / b) * 100
|
||||
if abs(real_pct - pct_val) > 0.05:
|
||||
add_error("NM005", f"公式 \\frac{{{a}}}{{{b}}} = {pct_val}% 算术不成立(实为 {real_pct:.2f}%)")
|
||||
for num_token in re.findall(r"\d+(?:\.\d+)?", fl):
|
||||
if num_token not in outside_text:
|
||||
add_error("NM005", f"公式中的数值 {num_token} 在正文别处找不到,可能与实际数据脱节")
|
||||
|
||||
return {
|
||||
"file": str(path),
|
||||
"valid": len(issues) == 0,
|
||||
"tables": len(parsed_tables),
|
||||
"figures": figure_count,
|
||||
"issues": [i.to_dict() for i in issues],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2 or sys.argv[1] in ["-h", "--help"]:
|
||||
print("用法: python3 validate.py <report.md> [--json]")
|
||||
print("说明: 离线静态校验 AI 审核报告 Markdown 文档的结构纯净度与数学总账守恒。")
|
||||
sys.exit(0)
|
||||
|
||||
target_file = sys.argv[1]
|
||||
is_json = "--json" in sys.argv
|
||||
|
||||
result = validate_report(target_file)
|
||||
|
||||
if is_json:
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
status_symbol = "✅" if result["valid"] else "❌"
|
||||
print(f"\n{status_symbol} 报告文件: {result['file']}")
|
||||
print(f"📊 识别表格: {result['tables']} 个 | 配图资产: {result['figures']} 个")
|
||||
|
||||
if result["valid"]:
|
||||
print("🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。\n")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print(f"⚠️ 发现 {len(result['issues'])} 项格式或勾稽问题,必须修正后方可交付:\n")
|
||||
for i, issue in enumerate(result["issues"], 1):
|
||||
loc = f" [第 {issue['line']} 行]" if "line" in issue else ""
|
||||
print(f" {i}. [{issue['code']}]{loc} {issue['message']}")
|
||||
print("\n💡 提示:请根据上述提示调整对应行的数字或表格结构,直至校验通过。\n")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,12 +0,0 @@
|
||||
# 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 注释、表格只换数据行。
|
||||
@@ -1,27 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 1.2 KiB |
@@ -1,5 +0,0 @@
|
||||
<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>
|
||||
|
Before Width: | Height: | Size: 605 B |
@@ -1,270 +0,0 @@
|
||||
#!/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())
|
||||
@@ -1,233 +0,0 @@
|
||||
#!/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
|
||||
} : {})
|
||||
};
|
||||
|
||||
+11
-10
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { execSync } from "node:child_process";
|
||||
import { execSync, spawnSync } from "node:child_process";
|
||||
|
||||
const ROOT = join(import.meta.dirname, "..");
|
||||
const pkgPath = join(ROOT, "package.json");
|
||||
@@ -87,14 +88,14 @@ console.log("✓ Updated skills/seal-use/SKILL.md");
|
||||
|
||||
|
||||
// 5. Sync to global ~/.agents/skills/seal-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "seal-use");
|
||||
const legacyGlobalSkillDir = join(process.env.HOME || "", ".agents", "skills", "seal-home");
|
||||
const { existsSync, cpSync, rmSync } = await import("node:fs");
|
||||
if (existsSync(legacyGlobalSkillDir)) {
|
||||
rmSync(legacyGlobalSkillDir, { recursive: true, force: true });
|
||||
}
|
||||
if (existsSync(globalSkillDir)) {
|
||||
cpSync(join(ROOT, "skills", "seal-use"), globalSkillDir, { recursive: true });
|
||||
const globalSkillDir = join(homedir(), ".agents", "skills", "seal-use");
|
||||
const legacyGlobalSkillDir = join(homedir(), ".agents", "skills", "seal-home");
|
||||
if (existsSync(globalSkillDir) || existsSync(legacyGlobalSkillDir)) {
|
||||
// A fresh source process reads the bumped skill, including the full embedded resource manifest.
|
||||
const sync = spawnSync(process.execPath, [join(ROOT, "src", "cli.ts"), "skill", "install", "--dir", globalSkillDir], {
|
||||
cwd: ROOT, stdio: "inherit", env: { ...process.env, SEAL_DISABLE_BG_UPDATE: "1" }
|
||||
});
|
||||
if (sync.status !== 0) throw new Error(`Failed to sync bumped Agent Skill: ${sync.error || sync.status}`);
|
||||
console.log("✓ Synchronized ~/.agents/skills/seal-use/");
|
||||
}
|
||||
|
||||
|
||||
+27
-32
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bun
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, rmSync } from "node:fs";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, realpathSync, renameSync, rmSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
@@ -7,14 +7,16 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
function resolveTargetBinaryPath(): string {
|
||||
export function resolveTargetBinaryPath(): string {
|
||||
// 1. Check which seal-use
|
||||
try {
|
||||
const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8" });
|
||||
const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8", env: { ...process.env } });
|
||||
if (whichRes.status === 0 && whichRes.stdout) {
|
||||
const p = whichRes.stdout.trim();
|
||||
if (p && existsSync(p)) {
|
||||
return p;
|
||||
// Preserve native binary symlinks, but never overwrite an npm-linked source entry.
|
||||
const target = realpathSync(p);
|
||||
return /\.(?:[cm]?[jt]sx?|sh)$/i.test(target) ? p : target;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -23,7 +25,6 @@ function resolveTargetBinaryPath(): string {
|
||||
|
||||
// 2. Fallback candidate paths in order of preference
|
||||
const candidates = [
|
||||
"/opt/homebrew/bin/seal-use",
|
||||
"/usr/local/bin/seal-use",
|
||||
join(homedir(), ".local", "bin", "seal-use"),
|
||||
join(homedir(), "bin", "seal-use")
|
||||
@@ -97,8 +98,7 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
copyFileSync(tmpTarget, targetPath);
|
||||
chmodSync(targetPath, 0o755);
|
||||
renameSync(tmpTarget, targetPath);
|
||||
try {
|
||||
rmSync(tmpTarget, { force: true });
|
||||
} catch {
|
||||
@@ -106,24 +106,14 @@ async function main() {
|
||||
}
|
||||
|
||||
// 4. Sync Agent Skill to ~/.agents/skills/seal-use
|
||||
const skillSource = join(root, "skills", "seal-use");
|
||||
const skillTarget = join(homedir(), ".agents", "skills", "seal-use");
|
||||
const legacySkill = join(homedir(), ".agents", "skills", "seal-home");
|
||||
if (existsSync(legacySkill)) {
|
||||
try {
|
||||
rmSync(legacySkill, { recursive: true, force: true });
|
||||
} catch {}
|
||||
}
|
||||
if (existsSync(skillSource)) {
|
||||
try {
|
||||
const { cpSync } = await import("node:fs");
|
||||
mkdirSync(dirname(skillTarget), { recursive: true });
|
||||
cpSync(skillSource, skillTarget, { recursive: true });
|
||||
console.error(`✓ [dev:override] Synced agent skill to ${skillTarget}`);
|
||||
} catch (err) {
|
||||
console.error(`⚠️ [dev:override] Failed to sync agent skill: ${err}`);
|
||||
}
|
||||
// Install the binary's manifest, including references sourced outside skills/seal-use.
|
||||
// A custom destination avoids changing unrelated agent host settings during development.
|
||||
const skillRes = spawnSync(targetPath, ["skill", "install", "--dir", skillTarget], { encoding: "utf8" });
|
||||
if (skillRes.status !== 0) {
|
||||
throw new Error(`[dev:override] Failed to sync agent skill: ${skillRes.stderr || skillRes.error || "unknown error"}`);
|
||||
}
|
||||
console.error(`✓ [dev:override] Synced agent skill to ${skillTarget}`);
|
||||
|
||||
// 5. Restart service daemon if it was previously running
|
||||
if (serviceWasRunning) {
|
||||
@@ -132,16 +122,21 @@ async function main() {
|
||||
}
|
||||
|
||||
// 6. Verify and output
|
||||
console.error("✨ [dev:override] Success! Active global seal-use binary is now updated:");
|
||||
const testRes = spawnSync(targetPath, ["v"], { encoding: "utf8" });
|
||||
if (testRes.status === 0 && testRes.stdout) {
|
||||
process.stdout.write(testRes.stdout);
|
||||
} else {
|
||||
console.error(testRes.stderr || "Failed to verify updated binary");
|
||||
if (testRes.status !== 0 || !testRes.stdout) {
|
||||
throw new Error(testRes.stderr || "Failed to verify updated binary");
|
||||
}
|
||||
const installed = JSON.parse(testRes.stdout);
|
||||
if (installed.name !== "seal-use" || typeof installed.version !== "string") {
|
||||
throw new Error("Updated binary returned an invalid version payload");
|
||||
}
|
||||
console.error("✨ [dev:override] Success! Active global seal-use binary is now updated:");
|
||||
process.stdout.write(testRes.stdout);
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
if (import.meta.main) {
|
||||
main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -27,6 +27,7 @@ const files = walk(skillRoot).map((fullPath) => ({
|
||||
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
|
||||
}));
|
||||
|
||||
|
||||
const lines = [
|
||||
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
|
||||
""
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bun
|
||||
// 生成 src/domains/seal/linter/plaintext.generated.ts:
|
||||
// 把 manifest 中 plaintext: true 的官方校验器源码嵌入为字符串,
|
||||
// 供 syncOfficialLinters 写入 ~/.config/seal-use/linters/official/。
|
||||
// 供 syncOfficialLinters 写入 ~/.cache/seal-use/linters/official/。
|
||||
// 修改 checkers/ 下任一源码后运行 `bun run generate:linter-plaintext` 刷新。
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
+12
-6
@@ -44,12 +44,18 @@ TARGET_DIR="${SEAL_USE_INSTALL_DIR:-${SEAL_HOME_INSTALL_DIR:-}}"
|
||||
if [ -n "$TARGET_DIR" ]; then
|
||||
mkdir -p "$TARGET_DIR"
|
||||
else
|
||||
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
|
||||
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
TARGET_DIR="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
# Reuse an existing command's directory so a second installation does not get shadowed on PATH.
|
||||
EXISTING_COMMAND="$(command -v seal-use || true)"
|
||||
if [ -n "$EXISTING_COMMAND" ] && [ -f "$EXISTING_COMMAND" ] && [ -w "$(dirname "$EXISTING_COMMAND")" ]; then
|
||||
TARGET_DIR="$(dirname "$EXISTING_COMMAND")"
|
||||
else
|
||||
for candidate in "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
|
||||
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||
TARGET_DIR="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$TARGET_DIR" ]; then
|
||||
|
||||
+2
-2
@@ -131,7 +131,7 @@ if (isDryRun) {
|
||||
console.log(` 4. git commit -m "Release ${tag}: ..."`);
|
||||
console.log(` 5. git push origin HEAD:refs/heads/${releaseBranch}`);
|
||||
console.log(` 6. gh pr create && gh pr checks --watch && gh pr merge --merge`);
|
||||
console.log(` 7. 同步 main,打标 ${tag} 并推送到 origin(Gitea 与 Homebrew 由 WSL seal-use-release-sync 主动拉取)`);
|
||||
console.log(` 7. 同步 main,打标 ${tag} 并推送到 origin(Gitea 由 WSL seal-use-release-sync 主动拉取)`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
@@ -229,6 +229,6 @@ if (success) {
|
||||
console.log(`🎉 恭喜!Seal Use ${tag} 已成功发布并触发多平台自动化编译!`);
|
||||
console.log(" • GitHub Actions 构建中心: https://github.com/yunyingk/seal-use/actions");
|
||||
console.log(` • GitHub Release 页面: https://github.com/yunyingk/seal-use/releases/tag/${tag}`);
|
||||
console.log(" • Gitea 与 Homebrew Tap 将由 WSL seal-use-release-sync.timer 自动拉取晋升");
|
||||
console.log(" • Gitea 将由 WSL seal-use-release-sync.timer 自动拉取晋升");
|
||||
console.log("========================================================\n");
|
||||
}
|
||||
+53
-14
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.1: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.8: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.1
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.1)
|
||||
version: 0.11.8
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.8)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -63,6 +63,14 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
|
||||
生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
|
||||
|
||||
## 规则编号重排:两次调用
|
||||
|
||||
`seal-use rules recode --corp <corpId>` 将当前草稿编号从 `0000` 连续编排。具体顺序由服务端决定,新建草稿可能排在已有规则之前;所有规则均可能变号,不能把预览中的编号范围当作逐条映射。第一次只返回影响预览、6 位一次性凭证、到期时间和 `nextCommand`,`executed: false`,退出码为 10;尚未执行重排。核对目标企业和完整影响范围后,另一次调用返回的完整命令才执行;成功返回的 `changes` 是按稳定身份回读验证的真实编号映射。
|
||||
|
||||
凭证绑定企业、环境及草稿状态,5 分钟有效且只能使用一次;`--yes` / `--confirm` 不能替代凭证。`--dry-run` 只预览,不签发凭证。确认码尚未生效时停止连调,不把两阶段写成自动执行脚本;草稿变化或凭证失效时重新预览。执行失败或超时后先回读当前草稿,再决定是否重新申请,不能重用旧码或盲目重跑。
|
||||
|
||||
重排不发布版本。旧编号可能对应不同规则,查看历史记录需指定发布版本。具体预览与返回字段见 `references/rule-lightweight.md`。
|
||||
|
||||
## 业务术语契约
|
||||
|
||||
对外统一使用以下术语:
|
||||
@@ -93,12 +101,13 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
||||
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
|
||||
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
|
||||
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
|
||||
| 规则数量、摘要列表、历史规则、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
||||
| 规则数量、摘要列表、历史规则、编号重排、制度文档(`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` |
|
||||
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `references/report-templates.md` |
|
||||
|
||||
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
||||
|
||||
@@ -112,20 +121,49 @@ seal-use approval-runs diagnose --sn <单号> --corp <corpId>
|
||||
|
||||
一次返回单据摘要、AI 判定结果、引用规则、判定当时的规则版本快照(含被引规则的快照内容)与 Langfuse trace 指针;需要完整 result 原文加 `--full`,需要按 recordId 定位则直接传 `<recordId>`。只有诊断结果不够、需要更细颗粒时,再拆用 `pick` / `get --summary` / `cited-rules` / `rules version`。
|
||||
|
||||
## 月度审核准确率报告
|
||||
## Langfuse trace 内置只读检索
|
||||
|
||||
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
|
||||
Langfuse 后台信息内建在 CLI 里(`seal-use langfuse`,凭据编译期注入、零配置、只读、无需 `--corp` 和 `langfuse-home`):
|
||||
|
||||
```bash
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId>
|
||||
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
|
||||
```
|
||||
|
||||
按模板结构(`report-templates/monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
||||
`approval-runs diagnose` / `bridge` 返回的 `bridge[].next` 就是下一步可执行命令。`seal-use langfuse check` 可自检内置密钥是否失效(失效 → exit 11/1 的结构化报错,绝不崩溃;已缓存 trace 仍可离线读取)。session、attachment-flow、rule-flow、缓存语义与失效兜底见 `references/langfuse-trace.md`。
|
||||
|
||||
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
|
||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||
- 结果里的 `next` 给出下游 `validate` / `render` 指引(校验与 HTML/PNG/PDF 渲染用 `report-templates/validate.py`、`render.py`,不进包)。
|
||||
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
||||
## 月度审核准确率报告
|
||||
|
||||
推荐通过轻量数据包 + Agent 协同填写的模式,彻底解耦数据与模板(亦兼容一键脚手架模式):
|
||||
|
||||
```bash
|
||||
# 模式 A (推荐轻量数据驱动): 提取当月纯结构化数据 (指标、分模板统计、待复核分歧单及具体触发条件)
|
||||
seal-use report data --month <YYYY-MM> --corp <corpId>
|
||||
# 保存纯净模板骨架
|
||||
seal-use report template --out reports/报告.md
|
||||
# 独立生成动态维恩图 SVG
|
||||
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/报告.assets/图1-准确率对比.svg
|
||||
|
||||
# 模式 B (传统模板脚手架): 一键生成初步替换的 Markdown 与配图包
|
||||
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
|
||||
|
||||
# 离线校验与全格式编译导出
|
||||
seal-use report validate reports/报告.md
|
||||
seal-use report render reports/报告.md --out build/报告
|
||||
```
|
||||
|
||||
按模板结构(内置 `monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
||||
|
||||
- **报告并非一键黑盒交付(人机协同研讨契约)**:数据接口无法自动获得“谁对谁错”的仲裁定性,也无法自动撰写管理归因与整改建议。生成初版 Markdown 后,Agent **严禁直接向客户交付带有 `> ⚠️ 数据说明` 警告框、模板假单号或 `(截图)` 占位符的半成品**,必须进入人机协同研讨模式(Tangent),向用户呈现分歧单据并共创定性分析文本。完整研讨流程、各章节动静边界与校验错误码见 `references/report-templates.md`。
|
||||
- **推荐轻量 Agent 执笔**:调用 `seal-use report data` 获取干净的 JSON 数据包(含触发的单个判断条件 `triggeredConditions`),由 Agent 亲自将真实数据与复核分析填入 Markdown,避免代码层正则换数的死板与脆弱。
|
||||
- **模板是可变的皮,以用户态度为最高准则**:大章节(§1~§6)是必选论证骨架,但具体问题分类(TOP 1~N,至少保留 1 个)、案例行数、表格列数均由当期数据与用户意图动态决定,严禁 Agent 固执教条(如机械死板凑满 3 类或 3 行);案例详情链接由管线全自动注入,Markdown 源码只聚焦业务内容。详见 `references/report-templates.md`。
|
||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,初稿保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
|
||||
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
|
||||
- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
|
||||
- 只读能力 `sealReportDataGet` / `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
||||
|
||||
### 人工裁决回填(算出人工审核准确率)
|
||||
|
||||
@@ -139,7 +177,8 @@ seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|hum
|
||||
seal-use report review list --month <YYYY-MM> --corp <corpId>
|
||||
```
|
||||
|
||||
- **存储**:`~/.config/seal-use/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
|
||||
- **存储**:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
|
||||
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
|
||||
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
|
||||
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
|
||||
- **协同研讨指南**:呈报分歧单据供用户裁决时,必须附带 Seal AI 审核页与合思原单据的双端直达链接(`approval-runs url --auto-login` / `hose-use bill link`);分歧单据挑选格式、失准归因撰写(§2)、分歧概览(§5)与严格离线校验(NM001~NM005)排查手册,完整参见 `references/report-templates.md`。
|
||||
@@ -38,25 +38,25 @@ 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>" \
|
||||
.cache/langfuse/traces/default/<traceId>.json
|
||||
~/.cache/seal-use/langfuse/traces/default/<traceId>.json
|
||||
```
|
||||
|
||||
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
|
||||
@@ -103,7 +103,7 @@ jq -r '
|
||||
or contains("附件中存在定额发票")
|
||||
or contains("检查该附件(定额发票)"))
|
||||
| [.id,.name,.type,.startTime,((.output|tostring)|gsub("\n";" ")|.[0:500])] | @tsv
|
||||
' .cache/langfuse/traces/default/<traceId>.json
|
||||
' ~/.cache/seal-use/langfuse/traces/default/<traceId>.json
|
||||
```
|
||||
|
||||
Then inspect the earliest matching observation. Typical interpretation:
|
||||
@@ -125,7 +125,7 @@ jq -r '
|
||||
.trace.observations[] | walkobs(.; 0)
|
||||
| select(.name? | test("pre_analysis"))
|
||||
| [.startTime,.id,.name,.type,.parentObservationId,((.input|tostring|length)//0),((.output|tostring|length)//0)] | @tsv
|
||||
' .cache/langfuse/traces/default/<traceId>.json
|
||||
' ~/.cache/seal-use/langfuse/traces/default/<traceId>.json
|
||||
```
|
||||
|
||||
Then inspect its output for the disputed file and rule:
|
||||
@@ -136,7 +136,7 @@ jq -r '
|
||||
.trace.observations[] | walkobs(.)
|
||||
| select(.name? == "pre_analysis:ai.streamText")
|
||||
| .output
|
||||
' .cache/langfuse/traces/default/<traceId>.json | rg -n "fileId|fileName|<file-name>|付款截图金额|收款金额|金额合计"
|
||||
' ~/.cache/seal-use/langfuse/traces/default/<traceId>.json | rg -n "fileId|fileName|<file-name>|付款截图金额|收款金额|金额合计"
|
||||
```
|
||||
|
||||
Look for these failure patterns:
|
||||
|
||||
@@ -124,10 +124,10 @@ When diagnosing a bad case or verifying rule fixes, replay the historic run's st
|
||||
seal-use webhook replay <recordId> --dry-run --corp <corpId>
|
||||
|
||||
# 执行重放,生成全新审批实例(支持自动附加单号后缀防重)
|
||||
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId>
|
||||
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId> --yes
|
||||
|
||||
# 跨企业提取:从生产企业提取单据并推送至测试企业 Webhook 进行回归验证
|
||||
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId>
|
||||
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId> --yes
|
||||
```
|
||||
|
||||
## Output Discipline
|
||||
|
||||
@@ -57,7 +57,9 @@ seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|la
|
||||
seal-use rules linters [--corp <corpId>]
|
||||
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
|
||||
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
|
||||
seal-use rules push status [--file <path>] [--corp <corpId>]
|
||||
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
|
||||
seal-use rules recode [--dry-run] --corp <corpId>
|
||||
seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]
|
||||
seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
|
||||
seal-use documents get <documentId> [--corp <corpId>]
|
||||
@@ -65,6 +67,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>]
|
||||
@@ -135,13 +147,15 @@ seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
|
||||
seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]
|
||||
seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--corp <corpId>]
|
||||
seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
|
||||
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]
|
||||
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--channel webhook|hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--dry-run] [--yes|--confirm] [--force] [--corp <corpId>]
|
||||
seal-use approval-runs replay --sn <sn> [--channel hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use deploy hosecloud requirements [--corp <corpId>]
|
||||
seal-use deploy hosecloud list [--corp <corpId>]
|
||||
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
||||
seal-use deploy hosecloud status [--corp <corpId>]
|
||||
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
|
||||
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
|
||||
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--rejection-num <n>] [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||
seal-use preference get [--corp <corpId>]
|
||||
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp <corpId>]
|
||||
seal-use preference thinking-depth set --default <medium|high> [--dry-run] [--corp <corpId>]
|
||||
@@ -253,7 +267,7 @@ Test Enterprise Binding, Staging Synchronization & Automated Regression Testing:
|
||||
- In the **Production Enterprise**: Rules remain strictly in **draft state** without publishing any live version.
|
||||
- In the **Test Enterprise**: Style preferences (`decisionPreferences`, `thinkingDepthPreference`) are updated to match production, test draft rules are cleared and populated with production draft rules, recoded, and immediately **published as a new official version** in the test tenant (`--version-name <name>`).
|
||||
- **Semantic Version Naming**: Defaults to `Sync from <ProdCorp> [Prod v<N> · #<Iteration>]` tracking production baseline version and test draft iteration without redundant date strings.
|
||||
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
|
||||
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/state/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
|
||||
- `--dry-run` previews the full preference diff, version mapping plan, and rule sync plan without sending mutations. Execution requires `--yes`.
|
||||
- **Approval Run Replay to Test Enterprise (`corps replay-test`)**:
|
||||
- Automatically identifies the bound test enterprise for `<prodCorpId>` (or current corp).
|
||||
@@ -287,10 +301,12 @@ Approval rule maintenance:
|
||||
- `seal-use rules version <versionNumber|latest> [--corp <corpId>]`
|
||||
- `seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
|
||||
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
|
||||
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: `~/.config/seal-use/linters` and `official/`)
|
||||
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: custom in `~/.config/seal-use/linters` and official in `~/.cache/seal-use/linters/official`)
|
||||
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
|
||||
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
|
||||
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Live execution persists a per-step recovery ledger (`status`: `not_started`, `partial`, `completed`, `uncertain`) and hydrates newly created IDs so an interrupted run can be inspected and resumed without duplicating rules.
|
||||
- `seal-use rules push status [--file <path>] [--corp <corpId>]` (or `--check`) inspects the last push recovery ledger and reconciles remaining diff against the live draft without mutating state.
|
||||
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
|
||||
- `seal-use rules recode [--dry-run] --corp <corpId>`: first returns an unexecuted numbering preview and a one-use credential (exit 10). Inspect the preview, then invoke the returned `nextCommand` separately. The credential is enterprise/environment/draft-bound, valid for five minutes, and cannot be replaced by `--yes`/`--confirm`. `--dry-run` only previews (exit 0). Recode does not publish; failed/uncertain executions require a draft read before another request. Do not script both phases into automatic consecutive execution.
|
||||
- `seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]` (reads local sync rule mapping snapshot)
|
||||
|
||||
Rule identity and versioning (Draft by default vs. `--version latest`):
|
||||
@@ -334,7 +350,7 @@ Webhook integrations:
|
||||
- `seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>` (将线上审核记录打包导出为标准 Webhook 资源包,支持按条数、状态或指定单据 ID 筛选)
|
||||
- `seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
|
||||
- `seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>` (别名 `pack`,旧名 `material-pack` 兼容支持)
|
||||
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持)
|
||||
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。实际重放要求 `--yes` 或 `--confirm`;默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持)
|
||||
|
||||
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
|
||||
|
||||
@@ -358,6 +374,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 `~/.cache/seal-use/langfuse/traces/default/<traceId>.json` (shared format with langfuse-home); other cache-first verbs answer from it across working directories and point here (exit 13) when it is missing, unless `--refresh-if-missing`. `SEAL_USE_LANGFUSE_CACHE_DIR` overrides the cache root. Matching legacy cwd caches are copied on first read, preserving their original files and timestamps.
|
||||
- `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:
|
||||
|
||||
@@ -50,7 +50,7 @@ seal-use deploy hosecloud list --corp <corpId>
|
||||
seal-use deploy hosecloud requirements --corp <corpId>
|
||||
|
||||
# 3. 添加新配置(自动探测平台)
|
||||
seal-use deploy hosecloud configure --corp <corpId> --json '{
|
||||
seal-use deploy hosecloud configure --corp <corpId> --yes --json '{
|
||||
"apiKey": "your-app-key",
|
||||
"apiSecret": "your-app-secret",
|
||||
"outboundName": "SealAI 财务审批",
|
||||
@@ -58,7 +58,7 @@ seal-use deploy hosecloud configure --corp <corpId> --json '{
|
||||
}'
|
||||
|
||||
# 4. 编辑已有配置(传入原 signKey)
|
||||
seal-use deploy hosecloud configure --corp <corpId> --json '{
|
||||
seal-use deploy hosecloud configure --corp <corpId> --yes --json '{
|
||||
"signKey": "<原 signKey>",
|
||||
"apiKey": "your-app-key",
|
||||
"apiSecret": "your-app-secret",
|
||||
@@ -67,19 +67,30 @@ seal-use deploy hosecloud configure --corp <corpId> --json '{
|
||||
}'
|
||||
|
||||
# 5. 一键同步发布到合思审批流
|
||||
seal-use deploy hosecloud sync <signKey> --corp <corpId>
|
||||
seal-use deploy hosecloud sync <signKey> --dry-run --corp <corpId>
|
||||
seal-use deploy hosecloud sync <signKey> --yes --corp <corpId>
|
||||
|
||||
# 5.1 单配置企业一键自动同步 (--auto)
|
||||
# 若企业内仅存在 1 个合思配置卡片,可直接传入 --auto 自动锁定执行,免去查询复制 signKey:
|
||||
seal-use deploy hosecloud sync --auto --corp <corpId>
|
||||
# 若企业内仅存在 1 个合思配置卡片,可传入 --auto 自动选择,免去查询复制 signKey;实际同步仍需确认:
|
||||
seal-use deploy hosecloud sync --auto --dry-run --corp <corpId>
|
||||
seal-use deploy hosecloud sync --auto --yes --corp <corpId>
|
||||
|
||||
# 6. 查看单项配置详情(未传 signKey 时自动列出当前企业候选列表与查看命令)
|
||||
seal-use deploy hosecloud get [<signKey>] --corp <corpId>
|
||||
|
||||
# 7. 检查发布与多平台集成状态
|
||||
seal-use deploy hosecloud status --corp <corpId>
|
||||
|
||||
# 8. 测试/重放出站请求 (要求 assisted 模式,默认使用中文 nodeId 阻断标记)
|
||||
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--dry-run] [--yes|--confirm] --corp <corpId>
|
||||
```
|
||||
|
||||
`configure` 保存 Seal 端集成配置,`sync` 在合思创建或更新出站消息及回调地址;两者实际写入都要求 `--yes` 或 `--confirm`。保存配置前可将示例中的 `--yes` 换成 `--dry-run` 查看脱敏后的前后差异。
|
||||
`sync --dry-run` 只列出待提交的名称、回调地址和模式;`remoteStateKnown: false` 表示未读取合思远端当前配置,不能把预览视为远端现状验证。
|
||||
|
||||
实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。
|
||||
出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。
|
||||
|
||||
---
|
||||
|
||||
## 4. 关键配置参数定义
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Langfuse Trace 内置只读检索
|
||||
|
||||
`seal-use langfuse` 是内建的只读 Langfuse trace 检索域:凭据在编译期注入,最终用户**零配置**,无需 `langfuse-home` 或任何本地 `.env`。命令不需要 `--corp`,MCP `seal_use` 网关全部可达。
|
||||
|
||||
只读边界:client 只发 `GET`,本地只写用户目录 `~/.cache/seal-use/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>
|
||||
```
|
||||
|
||||
缓存写入 `~/.cache/seal-use/langfuse/traces/default/<traceId>.json`,换目录后仍可读;可用 `SEAL_USE_LANGFUSE_CACHE_DIR` 显式指定缓存根目录。与 langfuse-home 的 JSON 格式保持兼容:从旧工作目录读取时,会将匹配当前项目的 `<cwd>/.cache/langfuse/traces/default/<traceId>.json` 复制到用户缓存,保留原文件和原缓存时间。后续命令缺缓存时报 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/seal-use/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`。
|
||||
@@ -0,0 +1,178 @@
|
||||
# 月度 AI 审核报告编制与人机协同作业指南 (Monthly Report Authoring & Tangent Workflow)
|
||||
|
||||
本文档面向 **AI Agent 与操作用户**,规范从**月度数据拉取**、**分歧单据人机复核研讨(Tangent)**、**Agent 自主理解与填报**,到**严格离线门禁校验、全格式渲染与多轮修改**的端到端人机协同闭环。
|
||||
|
||||
---
|
||||
|
||||
## 核心认知与人机分工 (Core Division of Labor)
|
||||
|
||||
1. **确定性工具管线 + Agent 智能执笔**:
|
||||
- **工具层 (`seal-use`)**:提供确定性提数(`report data`)、裁决记录(`review set`)、矢量图表(`report chart venn`)、离线格式与勾稽门禁(`report validate`)、全格式渲染(`report render`)及全量明细台账(`《明细台账.xlsx》`)。
|
||||
- **Agent 层(智能分析与自主撰写)**:Agent 最擅长理解数据、归纳归因并与用户对话。Agent 调取结构化数据包与模板骨架,结合用户裁决意见,亲自将真实数据、原因分类与业务建议填入 Markdown,彻底摆脱死板的模板脚本限制。
|
||||
2. **人机对齐与裁决研讨 (Review Tangent)**:
|
||||
- 当 AI 与人工判定结论不一致时,Agent 绝不凭空主观臆断,而是从数据包中提取关键分歧单(含单号、AI摘要、触发的具体规则卡口 `triggeredConditions`),主动在聊天窗口向用户征询对错裁决定性。
|
||||
3. **必须通过格式门禁校验 (Zero-Error Gate)**:
|
||||
- 严禁交付未经校验的 Markdown。Agent 在调用 `render` 渲染前,**必须执行 `seal-use report validate`**。若有报错,Agent 需读取报错 issue 自纠自查,修正格式与数字勾稽,直到 100% 通过。
|
||||
4. **即时渲染与多轮反馈修改**:
|
||||
- 渲染出的 HTML、A4 PDF 和高清长图交由用户审查。用户提出调整意见后,Agent 微调 Markdown,再次过门禁校验并重新渲染,完成多轮敏捷迭代。
|
||||
|
||||
---
|
||||
|
||||
## 端到端人机协同五步闭环 (The 5-Stage Lifecycle)
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
S1["第一步:拉取结构化数据与模板骨架<br/>(report data & report template)"] --> S2["第二步:分歧单据人机裁决研讨<br/>(Agent 汇报分歧,用户给出定性)"]
|
||||
S2 --> S3["第三步:Agent 结合理解自主撰写报告<br/>(撰写结构化 Markdown 报告草稿)"]
|
||||
S3 --> S4["第四步:离线格式与数学勾稽门禁<br/>(report validate 质检拦截与自纠)"]
|
||||
S4 --> S5["第五步:全格式渲染与多轮修改迭代<br/>(report render 产出交付,根据用户意见微调)"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 第一步:获取结构化数据包与模板骨架
|
||||
|
||||
1. **拉取当月纯结构化业务数据包 (JSON)**:
|
||||
```bash
|
||||
seal-use report data --month <YYYY-MM> --corp <corpId>
|
||||
```
|
||||
*输出说明:返回纯 JSON,包含全月样本量、AI 准确率、采纳率、平均耗时、公式代入值、分模板统计、TOP 风险标签,以及全量分歧单据池(`divergedRuns`)。*
|
||||
|
||||
2. **导出纯净标准模板骨架**:
|
||||
```bash
|
||||
seal-use report template --out reports/<企业名>-<YYYYMM>.md
|
||||
```
|
||||
|
||||
3. **动态生成准确率维恩图**:
|
||||
```bash
|
||||
mkdir -p reports/<企业名>-<YYYYMM>.assets
|
||||
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 第二步:分歧单据人机复核研讨 (Diverged Runs Review)
|
||||
|
||||
当 `reviews.divergedUnreviewedCount > 0` 时,存在 AI 放行但人工驳回、或 AI 驳回但人工放行的分歧单据。Agent 需主动在聊天中向用户汇总呈报并征询裁决。
|
||||
|
||||
**双链穿透规范 (Dual-Link Fast Traversal)**:
|
||||
呈报给用户裁决的每笔典型案例,Agent **必须同时生成并附带双端直达链接**,严禁让用户盲猜或手动去系统里翻查单据:
|
||||
- **🔗 Seal AI 审核页直达**:调用 `seal-use approval-runs url --sn <SN> --auto-login` 生成带临时免密凭证的直达链接,一键跳转到 Seal AI 查看完整判定快照、引用规则、卡口明细与 LLM 推理过程;
|
||||
- **📑 合思/易快报原单据直达**:调用 `hose-use bill link <SN>` 或从运行记录 `sourceExtendData.hosecloudViewUrl` 提取原单据 Web 链接,一键直达合思原单据查看发票原件影像、业务附件与人工审批操作历史。
|
||||
|
||||
1. **结构化向用户呈现典型案例**:
|
||||
```markdown
|
||||
【分歧单据复核确认】单号:FP2608010
|
||||
- 单据模板:发票-个人报销
|
||||
- 快速核验:[🔗 Seal AI 审核详情](https://<corp>.sealai.cc/approval-result/<recordId>) | [📑 合思原单据](https://wx2.ekuaibao.com/...)
|
||||
- AI 审核结论:同意(单据附件与发票齐全合规,满足既定规则)
|
||||
- 人工实际操作:驳回/终止(批注:口头超标)
|
||||
- 触发条件:现行线上规则库无该超标阻断规则
|
||||
|
||||
👉 请教您对本单的裁决:
|
||||
1. AI 依规正确(ai_correct):按线上规则库合规放行,人工属于口头加码标准;
|
||||
2. 人工正确 / AI 失准(human_correct):业务实际存在超标限制,属于 AI 误判或规则未覆盖;
|
||||
3. 双方都对(both_correct):规则执行正确,但有线下特殊处理。
|
||||
```
|
||||
|
||||
2. **将用户意见持久化录入复核账本**:
|
||||
```bash
|
||||
seal-use report review set \
|
||||
--month <YYYY-MM> \
|
||||
--sn <单号> \
|
||||
--verdict <ai_correct|human_correct|both_correct> \
|
||||
--note "口头加码标准,现行线上规则库未配置" \
|
||||
--corp <corpId>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 第三步:Agent 结合数据与裁决自主撰写
|
||||
|
||||
Agent 调取模板,结合数据包与用户裁决定性,自主撰写全新的 6 章节 Markdown:
|
||||
|
||||
* **§1 审核测试结果**:填入企业名称、账期、样本总量、AI 准确率、人工准确率公式及维恩图。
|
||||
* **§2 AI 失准分析**:将真实的错判单据填入 TOP 1~3 小节,写出针对性整改方案。
|
||||
* **§3 AI 发现的潜在风险**:列出 AI 在人工通过单据中额外识别出的票据、预付与凭证风险。
|
||||
* **§4 综合效益**:填入时效、准确度、拦截笔数等宏观关键数据。
|
||||
* **§5 审核分歧与复核归因**:
|
||||
- 填入分类统计表(如“未在线配置规则 66.7% / AI 识别偏差 33.3%”);
|
||||
- 总结管理建议(推动口头标准线上化规则沉淀);
|
||||
- 明确引导用户查看随包附带交付的《明细台账.xlsx》核对逐单流水。
|
||||
* **§6 支撑数据与交付材料**:
|
||||
- 6.1 分模板准确率与自动审批率表格;
|
||||
- 6.2 配套交付的《明细台账.xlsx》说明。
|
||||
|
||||
---
|
||||
|
||||
### 第四步:离线门禁格式与勾稽校验 (Validate)
|
||||
|
||||
在执行最终渲染前,Agent **必须**执行门禁校验命令:
|
||||
```bash
|
||||
seal-use report validate reports/<企业名>-<YYYYMM>.md
|
||||
```
|
||||
|
||||
#### 门禁校验重点关注项:
|
||||
- **`HD001` / `HD002`**:二级章节编号必须自 1 开始连续递增(`## 1.`, `## 2.`, ..., `## 6.`),不得跳级。
|
||||
- **`TB001` / `TB002`**:表格列数前后严格一致,表头行严禁带加粗 `**` 标记。
|
||||
- **`NM001` / `NM002`**:失准与风险总览表中的各分项张数之和必须严格等于合计行。
|
||||
- **`NM004`**:分歧原因分类表中的各单数与正文叙述中的笔数必须完全勾稽。
|
||||
- **`NM005`**:准确率公式(如 `\frac{221}{240} = 92.08\%`)算术必须成立,且数值在正文中必须能找到对应数据来源。
|
||||
- **`INFO001` / `INFO002`**:开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。
|
||||
|
||||
> ⚠️ 若返回 `valid: false`,Agent 必须读取报错列表中的 `code` 和 `message`,**自主编辑修正 Markdown**,直到再次校验返回 `valid: true`。
|
||||
|
||||
---
|
||||
|
||||
### 第五步:全格式渲染与多轮修改迭代 (Render & Iterate)
|
||||
|
||||
1. **一键编译渲染全套交付产物**:
|
||||
```bash
|
||||
seal-use report render reports/<企业名>-<YYYYMM>.md --out build/<企业名>-<YYYYMM> --format all
|
||||
```
|
||||
*产物包含:单文件自包含 HTML、A4 打印排版 PDF、4x 超高清拼接长图 PNG。*
|
||||
|
||||
2. **呈现给用户并接收修改意见**:
|
||||
- Agent 将渲染后的成果与核心数据摘要反馈给用户;
|
||||
- 用户审查后提出调整(如“某段原因描述请改一下”、“风险小节增加具体发票案例”);
|
||||
- Agent 直接在 Markdown 文件中微调,再次运行 `report validate` 确保无勾稽错误,然后重新 `report render` 刷新交付。
|
||||
|
||||
---
|
||||
|
||||
## 模板 6 大标准章节剖析 (Section Anatomy)
|
||||
|
||||
| 章节编号与名称 | 数据来源与机制 | 说明与核心关注点 |
|
||||
| :--- | :--- | :--- |
|
||||
| **标题与报告信息表** | 数据填充 | 包含企业名称、账期、生成日期、草稿状态与唯一报告编号。 |
|
||||
| **摘要** | 动态提炼 | 提炼全月单量、核心准确率与额外发现的合规风险笔数。 |
|
||||
| **§1 审核测试结果** | 核心数据 | 1.1 数据来源与样本总量;1.2 准确率结论、计算公式与图 1 维恩图。 |
|
||||
| **§2 AI 失准分析** | 深度归因 | 2.1 失准构成总览;2.2~2.4 TOP 失准真实案例与调优解决方案。 |
|
||||
| **§3 AI 发现的潜在风险** | 价值体现 | 3.1 风险构成总览;3.2~3.4 缺失凭证、大额预付、专票违规等真实拦截。 |
|
||||
| **§4 综合效益** | 数据汇总 | 准确度、时效(平均秒数)、风险拦截量与人力释放宏观汇总表。 |
|
||||
| **§5 审核分歧与复核归因** | 概览归因 | 人机分歧分类统计(线上规则未覆盖 vs 识别偏差),引导查验《明细台账.xlsx》。 |
|
||||
| **§6 支撑数据与交付材料** | 支撑底账 | 6.1 各模板准确率与自动化率;6.2 交付文件说明(明细台账 Excel/CSV)。 |
|
||||
|
||||
---
|
||||
|
||||
## 动态自适应与用户至上原则 (Dynamic Adaptability & User-Centric Principles)
|
||||
|
||||
为避免后续使用的 AI Agent 产生死板教条(“非要凑满 3 类问题”、“非要放满 3 行”、“强行增加冗余列”等固执偏见),特此确立以下人机协同规范:
|
||||
|
||||
### 1. 必选骨架 vs 动态子部分的边界
|
||||
* **大章节是不可缺少的骨架**:§1~§6 大章节承载了完整严谨的商业论证闭环(业绩证明、失准坦白、额外价值、分歧归因、支撑台账),必须存在。
|
||||
* **章节内部的子部分完全动态**:
|
||||
* 例如 §2(失准分析)与 §3(潜在风险)下的具体问题分类,**数量完全由实际跑批结果与用户业务关注度决定**。
|
||||
* **唯一硬性底线**:动态章节下**至少保留 1 个子分类**(不能是无正文的空标题),可以是 TOP 1~2、TOP 1~3 或扩展至 TOP 1~5。
|
||||
* **数学自洽守恒**:无论列出几种分类,分类表中的单数之和必须严格等于「合计」行单数,且百分比之和严格等于 100%(`NM001`~`NM003`)。
|
||||
|
||||
### 2. 用户态度为最高准则 (User Preference First)
|
||||
* **严禁 Agent 固执己见**:Agent 必须以用户的业务判断与汇报习惯为首要输入。如果用户要求“重点只突出 2 个主要风险”、“案例只放 1 个最具代表性的单据”,Agent 必须立即响应调整,不得机械搬用模板默认的 3 分类或 3 行案例。
|
||||
* **文字叙述灵活定性**:针对失准单据的“解决方案”与分歧归因的“管理建议”,Agent 需结合具体企业的管理要求与规则实际情况有针对性地撰写,杜绝空话套话。
|
||||
|
||||
### 3. 表格案例与跳转超链接免维护契约
|
||||
* **Markdown 源码专注业务语义**:用户与 Agent 在编写或编辑 Markdown 报告草稿时,无需在源码中手动维护长串技术 URL,保持干净易读(如常规的 `| 单号 | 问题描述 |`)。
|
||||
* **自动化链接注入机制**:
|
||||
* **2 列模式**:若表格只有两列,管线在填充真实数据时会自动将第一列单号升级为跳转链接 `[SN](https://<corp>.sealai.cc/approval-result/<recordId>)`。
|
||||
* **3 列模式**:若表头显式声明了 `审核详情` 或 `链接` 列,管线会自动在第 3 列生成 `[👉 查看详情](https://...)`。
|
||||
* **跨端交付表现**:单文件自包含 HTML 与 A4 排版 PDF 均天然支持在浏览器或 PDF 阅读器中一键点击穿透直达系统后台;长图 PNG 为纯像素光栅位图,主要用于 IM 聊天窗口内快速滑动预览。
|
||||
|
||||
@@ -92,6 +92,19 @@ Expected shape:
|
||||
}
|
||||
```
|
||||
|
||||
## Recode Draft Rule Numbers
|
||||
|
||||
```bash
|
||||
seal-use rules recode --corp <corpId>
|
||||
seal-use rules recode --dry-run --corp <corpId>
|
||||
```
|
||||
|
||||
The first command returns a preview, a six-character one-use confirmation code, `expiresAt`, and `nextCommand`, with `executed: false` and exit code 10. Inspect the enterprise and full impact scope, then invoke the returned command separately. Preview `changesDiff` shows the existing and resulting number ranges, not a per-rule mapping (`mappingAvailable: false`); every rule can change number. The code is bound to the enterprise, environment and exact draft state, expires in five minutes, and is consumed before the POST. Ordinary `--yes`/`--confirm` cannot bypass this flow. Do not combine both phases into an automatic script.
|
||||
|
||||
`--dry-run` returns only the preview (exit 0) without issuing a code. A successful second call returns `executed: true`, the verified per-rule `changes` (`mappingAvailable: true`), and `nextCode`. Recode starts at `0000`, and the server determines ordering: new drafts may move before existing active rules. It does not publish. A not-yet-active code should not trigger immediate repeated calls. On expiry or draft changes request a fresh preview; on POST failure/timeout, read the current draft before requesting another code. A spent code is never reusable.
|
||||
|
||||
Clearing rules and test synchronization reset the allocation counter only after verifying the draft is empty. If clear leaves any rules behind, it skips automatic recoding and reports a warning.
|
||||
|
||||
## Output Discipline
|
||||
|
||||
If a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports.
|
||||
@@ -58,8 +58,8 @@ seal-use config lint disable
|
||||
| 层 | 位置 | 说明 |
|
||||
| :--- | :--- | :--- |
|
||||
| 内置引擎 | 编译进二进制 | 永远可用,`builtin` 即此层 |
|
||||
| 官方明文版 | `~/.config/seal-use/linters/official/` | `syncOfficialLinters` 自动同步,改动会被覆盖;agent 可直接阅读源码理解校验逻辑 |
|
||||
| 用户自定义 | `~/.config/seal-use/linters/<name>.ts`(全局唯一位置) | 私有脚本,跨项目共用;不再从项目 cwd 读取 |
|
||||
| 官方明文版 | `~/.cache/seal-use/linters/official/` | `syncOfficialLinters` 自动同步,改动会被覆盖;agent 可直接阅读源码理解校验逻辑 |
|
||||
| 用户自定义 | `~/.config/seal-use/linters/<name>.ts`(全局唯一位置) | 私有脚本,跨项目共用;保留在 ~/.config 防止随缓存清理误删 |
|
||||
|
||||
哪些官方校验器明文下发由 `src/domains/seal/linter/manifest.ts` 的 `plaintext` 标记决定:`true` 的条目源码会被写入 `official/`(源码嵌入物 `plaintext.generated.ts` 由 `bun run generate:linter-plaintext` 从 `linter/checkers/` 生成,改动校验器后必须重跑并提交,CI 的 `verify:linter-plaintext` 会拦截漂移);`false` 的条目只以进程内函数存在、不下发明文。
|
||||
|
||||
@@ -103,7 +103,7 @@ seal-use rules lint --linter hlab --file ./rules.local.json
|
||||
|
||||
## Custom TS Linters (Plugin-as-Code)
|
||||
|
||||
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts` or `./linters/<name>.ts`:
|
||||
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts`:
|
||||
|
||||
```typescript
|
||||
// ~/.config/seal-use/linters/finance-strict.ts
|
||||
|
||||
@@ -185,13 +185,34 @@ flowchart TD
|
||||
seal-use corps replay-test <prodCorpId> --sn '<单据号>' --confirm
|
||||
|
||||
# 跨企业通用重放
|
||||
seal-use webhook replay --limit 5 --status failed --prod-corp <prodCorpId> --test-corp <testCorpId>
|
||||
seal-use webhook replay --limit 5 --status failed --prod-corp <prodCorpId> --test-corp <testCorpId> --yes
|
||||
|
||||
# 未绑定测试企业 / 明确需要重放到生产企业(必须显式指定 --force 覆盖生产保护拦截)
|
||||
seal-use webhook replay <recordId> --force
|
||||
seal-use webhook replay <recordId> --force --yes
|
||||
```
|
||||
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
|
||||
|
||||
- **方式 D:合思出站通道高仿重放 (Hose Outbound Replay,单据/附件仿真专属)**:
|
||||
基于合思出站(EBot Outbound Webhook)官方通道的仿真重放。通过合思管理后台 CloseAPI 自动抓取历史出站日志中真实有效的 `messageId`、`flowId` 与 `rejectionNum`,并向测试环境出站网关推送;Seal 会依据真实 `messageId` 从合思开放平台拉取完整单据字段与全量二进制附件(发票、合同等),仿真度极高:
|
||||
```bash
|
||||
# 预览重放(自动从合思 CloseAPI 检索日志、提取真实 messageId 并做安全检查,不实际推送)
|
||||
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --dry-run
|
||||
|
||||
# 正式执行(自动推送到绑定的测试企业,并在测试企业异步生成 AI 审核记录)
|
||||
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --yes
|
||||
|
||||
# 精准匹配指定驳回重提轮次
|
||||
seal-use approval-runs replay --sn <SN> --channel hose-outbound --rejection-num 1 --corp <prodCorpId> --yes
|
||||
|
||||
# 底层直接推送出站调试消息(仅限 assisted 模式)
|
||||
seal-use deploy hosecloud test-outbound --flow-id <flowId> --message-id <msgId> --corp <testCorpId> --yes
|
||||
```
|
||||
指定 `--rejection-num N` 时只接受第 N 轮出站日志,找不到则报错;按审核记录创建时间推测出站事件时,只接受相差小于 60 秒的记录,不会退回更旧的轮次或日志。
|
||||
> **专属安全红线契约**:
|
||||
> 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。
|
||||
> 2. **锁死 assisted 模式**:目标测试环境的合思配置必须为 `assisted` 辅助模式,否则直接触发 Exit 14 安全阻断。
|
||||
> 3. **中文 nodeId 物理阻断**:出站报文中注入中文标记 `nodeId: "FLOW:测试模拟节点_禁止流转"`。因为合思辅助审核也会调用审批回调,篡改后合思在回调时必定返回 `HTTP 200 { code: 412, message: "当前的审批节点不为:..." }` 物理级阻断,双重保障生产单据绝不会被意外流转或修改。
|
||||
|
||||
3. **轮询并检查判定结果**:
|
||||
```bash
|
||||
# 查看状态与进度
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ describe("CLI version & help handling", () => {
|
||||
expect(result.stdout).toContain("seal-use webhook get|find <idOrName>");
|
||||
expect(result.stdout).toContain("seal-use webhook add --name <name> --result-url <url>");
|
||||
expect(result.stdout).toContain("seal-use corps add-link <url>");
|
||||
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--corp <corpId>]");
|
||||
expect(result.stdout).toContain("seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]");
|
||||
expect(result.stdout).toContain("[--secret <secret>|--rotate-secret]");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { exportInsightReportToExcel } from "../../domains/seal/insight-export.js";
|
||||
import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs-export.js";
|
||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs/export.js";
|
||||
import {
|
||||
downloadApprovalRunAttachments,
|
||||
extractApprovalRunAttachments
|
||||
} from "../../domains/seal/attachments.js";
|
||||
} from "../../domains/seal/approval-runs/attachments.js";
|
||||
import { runCapability, runCapabilityResult } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
|
||||
@@ -93,6 +93,83 @@ describe("auth links", () => {
|
||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||
});
|
||||
|
||||
test("supports --expire 7d for native Seal link and passes expiresInHours: 168", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-link-expire-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
tempDirs.push(root);
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
|
||||
|
||||
writeFileSync(
|
||||
join(enterprises, "native-seal.json"),
|
||||
JSON.stringify({
|
||||
id: "native-seal",
|
||||
name: "原生 Seal 企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://native.seal.test",
|
||||
expiresIn: 3600,
|
||||
corpId: "native-corp",
|
||||
staffId: "native-staff"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
|
||||
let recordedPayload: any = null;
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl = typeof input === "string"
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.toString()
|
||||
: input.url;
|
||||
const url = new URL(requestUrl);
|
||||
if (url.pathname === "/api/v1/delegation/create") {
|
||||
if (input instanceof Request) {
|
||||
recordedPayload = await input.clone().json();
|
||||
} else if (init?.body) {
|
||||
recordedPayload = JSON.parse(String(init.body));
|
||||
}
|
||||
return new Response(JSON.stringify({
|
||||
data: {
|
||||
id: "delegation-7d",
|
||||
token: "delegation-token-7d",
|
||||
link: "https://native.seal.test/delegation?token=delegation-token-7d"
|
||||
}
|
||||
}), { status: 200, headers: { "content-type": "application/json" } });
|
||||
}
|
||||
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||
status: 404,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
const result = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "7d"]);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(recordedPayload).toMatchObject({
|
||||
expiresInHours: 168
|
||||
});
|
||||
|
||||
// Test fractional duration: floors to 1h and prints stderr guidance
|
||||
const floorResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "90m"]);
|
||||
expect(floorResult.isError).toBe(false);
|
||||
expect(recordedPayload).toMatchObject({
|
||||
expiresInHours: 1
|
||||
});
|
||||
expect(floorResult.stderr).toContain("已自动向下取整为 1 小时 (1h)");
|
||||
|
||||
// Test reject exceeding 7 days (168 hours)
|
||||
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
|
||||
expect(invalidResult.isError).toBe(true);
|
||||
expect(invalidResult.exitCode).toBe(2);
|
||||
});
|
||||
|
||||
test("formats hose-link with corp metadata, link, and Beijing ISO expiry without url field", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
@@ -164,6 +241,82 @@ describe("auth links", () => {
|
||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||
});
|
||||
|
||||
test("supports --expire 7d for hose-link and converts to 604800 seconds", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-hose-link-7d-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
tempDirs.push(root);
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
|
||||
|
||||
writeFileSync(
|
||||
join(enterprises, "hose-corp.json"),
|
||||
JSON.stringify({
|
||||
id: "hose-corp",
|
||||
name: "合思测试企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://hose-corp.sealai.cc" },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key-1",
|
||||
appSecurity: "sec-1",
|
||||
corpId: "HOSE-CORP",
|
||||
staffId: "HOSE-CORP:STAFF-1"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
|
||||
let recordedHoseBody: any = null;
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
const url = new URL(requestUrl);
|
||||
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: { accessToken: "test-openapi-token", expireTime: 7200 }
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
|
||||
if (input instanceof Request) {
|
||||
recordedHoseBody = await input.clone().json();
|
||||
} else if (init?.body) {
|
||||
recordedHoseBody = JSON.parse(String(init.body));
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
message: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-7d"
|
||||
}
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||
status: 404,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
const result = await runCli(["auth", "hose-link", "--corp", "hose-corp", "--expire", "7d"]);
|
||||
expect(result.isError).toBe(false);
|
||||
expect(recordedHoseBody).toMatchObject({
|
||||
expireDate: 604800
|
||||
});
|
||||
|
||||
const result2 = await runCli(["auth", "hose-link", "--corp", "hose-corp", "--expire", "2"]);
|
||||
expect(result2.isError).toBe(false);
|
||||
expect(recordedHoseBody).toMatchObject({
|
||||
expireDate: 7200
|
||||
});
|
||||
expect(result2.stderr).toContain("已按 2 小时 (7200s) 自动换算");
|
||||
});
|
||||
|
||||
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-auth-check-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
|
||||
+17
-10
@@ -5,7 +5,12 @@ import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||
import { createDelegation, getMe } from "../../domains/seal/api.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import {
|
||||
booleanOption,
|
||||
parseDelegationExpireHours,
|
||||
parseHoseExpireSeconds,
|
||||
stringOption
|
||||
} from "../parser.js";
|
||||
import { outputOptions, printJson, redactSensitiveText } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { runCapability, runCapabilityResult } from "../helpers.js";
|
||||
@@ -40,11 +45,13 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
|
||||
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
|
||||
const note = stringOption(args.options.note);
|
||||
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
||||
const session = await exchangeHoseAssistLink(fromLink);
|
||||
const client = createSealClientForUrl(session.sealUrl, session.token);
|
||||
const me = await getMe(client);
|
||||
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
|
||||
const delegation = await createDelegation(client, { note });
|
||||
const delegation = await createDelegation(client, { note, expiresInHours });
|
||||
|
||||
printJson({
|
||||
tenant: {
|
||||
@@ -60,7 +67,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
isAdmin: me.user.isAdmin
|
||||
},
|
||||
delegation,
|
||||
expiresIn: session.expiresIn
|
||||
expiresIn: session.expiresIn,
|
||||
expiresAt: formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000)
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -90,18 +98,20 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
}
|
||||
|
||||
const note = stringOption(args.options.note) ?? "CLI generated provisional access link";
|
||||
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
||||
const delegation = await runCapabilityResult(
|
||||
"sealDelegationCreate",
|
||||
client,
|
||||
corp,
|
||||
{ note }
|
||||
{ note, expiresInHours }
|
||||
);
|
||||
if (action === "hose-link") {
|
||||
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
||||
}
|
||||
const delegationRecord = delegation as Record<string, unknown>;
|
||||
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
|
||||
const expiresAt = formatBeijingIso(Date.now() + 86400 * 1000);
|
||||
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
|
||||
printJson({
|
||||
id: delegationRecord.id,
|
||||
corpId: corp.source.corpId ?? corp.id,
|
||||
@@ -116,11 +126,8 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
}
|
||||
|
||||
if (action === "hose-link") {
|
||||
const rawExpire = args.options.expire;
|
||||
const expiresIn = rawExpire !== undefined ? numberOption(rawExpire) : 7200;
|
||||
if (expiresIn === undefined || expiresIn <= 0) {
|
||||
throw new Error(`Invalid --expire: ${String(rawExpire)}. Must be a positive number of seconds (e.g. --expire 7200 or --expire 86400).`);
|
||||
}
|
||||
const rawExpire = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||
const expiresIn = parseHoseExpireSeconds(rawExpire, 7200);
|
||||
const force =
|
||||
booleanOption(args.options.force) === true ||
|
||||
booleanOption(args.options.refresh) === true ||
|
||||
|
||||
@@ -355,6 +355,10 @@ describe("corps sync-test", () => {
|
||||
expect(createdRules.length).toBe(2);
|
||||
expect((createdRules[0]!.body as any).description).toBe("Production Rule A");
|
||||
expect((createdRules[1]!.body as any).description).toBe("Production Rule B");
|
||||
const resetIndex = requests.findIndex(r => r.path === "/api/v1/rules/batch-recode");
|
||||
const firstCreateIndex = requests.findIndex(r => r.method === "POST" && r.path === "/api/v1/rules");
|
||||
expect(resetIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(resetIndex).toBeLessThan(firstCreateIndex);
|
||||
|
||||
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
|
||||
expect(publishVersion).toBeDefined();
|
||||
@@ -909,6 +913,9 @@ describe("corps replay-test", () => {
|
||||
function mockSealSyncRequests(options: {
|
||||
onMutation?: (method: string, path: string, body?: unknown) => void;
|
||||
} = {}) {
|
||||
let remainingTestRules = [
|
||||
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
|
||||
];
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl = typeof input === "string"
|
||||
? input
|
||||
@@ -1071,9 +1078,7 @@ function mockSealSyncRequests(options: {
|
||||
} else {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
rules: [
|
||||
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
|
||||
],
|
||||
rules: remainingTestRules,
|
||||
hasPendingDeletes: false
|
||||
}
|
||||
});
|
||||
@@ -1082,6 +1087,7 @@ function mockSealSyncRequests(options: {
|
||||
|
||||
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
|
||||
options.onMutation?.("DELETE", url.pathname);
|
||||
remainingTestRules = remainingTestRules.filter(rule => rule.id !== url.pathname.split("/").pop());
|
||||
return jsonResponse({ data: { success: true } });
|
||||
}
|
||||
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -78,11 +78,17 @@ export async function handleCorpBindings(
|
||||
}
|
||||
|
||||
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
|
||||
console.error(
|
||||
`⚠️ [bind-test] 检测到冲突:已强制解除生产企业「${prodCorp.name}」(${prodCorp.id}) 与原测试企业「${prodCorp.testCorpId}」的绑定关联。`
|
||||
);
|
||||
try {
|
||||
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
|
||||
} catch {}
|
||||
}
|
||||
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
|
||||
console.error(
|
||||
`⚠️ [bind-test] 检测到冲突:已强制解除测试企业「${testCorp.name}」(${testCorp.id}) 与原生产企业「${testCorp.prodCorpId}」的绑定关联。`
|
||||
);
|
||||
try {
|
||||
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
|
||||
} catch {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { maskHoseSecurity } from "../../../core/auth/hose.js";
|
||||
import { scoreAssistLink } from "../../../core/auth/delegate.js";
|
||||
import { onboardSealBearer } from "../../../domains/seal/onboarding.js";
|
||||
import { onboardSealBearer } from "../../../domains/seal/enterprise/onboarding.js";
|
||||
import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js";
|
||||
import {
|
||||
listHoseStaffs,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { createSealClient } from "../../../core/http/factory.js";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import { syncTestEnterprise } from "../../../domains/seal/test-sync.js";
|
||||
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/webhook-replay.js";
|
||||
import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js";
|
||||
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js";
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { outputOptions, printJson } from "../../printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
|
||||
export { buildTestHosecloudOutboundName } from "../../../domains/seal/testing/sync.js";
|
||||
|
||||
export async function handleCorpSync(
|
||||
action: string | undefined,
|
||||
@@ -50,7 +50,16 @@ export async function handleCorpSync(
|
||||
`seal-use corps sync-test ${prodCorp.id} --yes`
|
||||
);
|
||||
}
|
||||
printJson(await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true }));
|
||||
const result = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true });
|
||||
const targetVersion = (result as { target?: { publishedVersion?: { versionNumber?: number; versionName?: string; rulesCount?: number } } })?.target?.publishedVersion;
|
||||
const rulesList = (result as { ruleMapping?: unknown[] })?.ruleMapping ?? [];
|
||||
console.error(
|
||||
`✅ 测试企业同步完成: 生产「${prodCorp.name}」(${prodCorp.id}) -> 测试「${testCorp.name}」(${testCorp.id})\n` +
|
||||
`📦 已发布测试版本: v${targetVersion?.versionNumber ?? "?"} (${targetVersion?.versionName ?? "最新"}) | 规则总数: ${targetVersion?.rulesCount ?? rulesList.length} 条\n` +
|
||||
`🔄 规则映射已归档: 共 ${rulesList.length} 条规则已与测试环境对齐\n` +
|
||||
`👉 下一步模拟测试建议: seal-use simulation create --document-sn <单号> --corp ${testCorp.id} --extract-expenses`
|
||||
);
|
||||
printJson(result, outputOptions(args.options));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -117,7 +126,8 @@ export async function handleCorpSync(
|
||||
snSuffix: stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]),
|
||||
docIdPrefix: stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]),
|
||||
docIdSuffix: stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]),
|
||||
dryRun
|
||||
dryRun,
|
||||
confirm: confirmed
|
||||
});
|
||||
if (dryRun) {
|
||||
console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`);
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import type { KyInstance } from "ky";
|
||||
import { CorpConfigSchema } from "../../core/config/types.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { runCapabilityResult } from "../helpers.js";
|
||||
import { handleDeployCommand } from "./deploy.js";
|
||||
|
||||
const originalLog = console.log;
|
||||
const originalError = console.error;
|
||||
afterEach(() => {
|
||||
console.log = originalLog;
|
||||
console.error = originalError;
|
||||
});
|
||||
|
||||
const corp = CorpConfigSchema.parse({
|
||||
id: "deploy-test", name: "Deployment test", environment: "test",
|
||||
seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } },
|
||||
source: { type: "seal", sealUrl: "https://seal.test", token: "mock-token" }
|
||||
});
|
||||
|
||||
const input = {
|
||||
apiKey: "mock-key", apiSecret: "mock-secret", signKey: "sign-key",
|
||||
apiOrigin: "custom", customApiUrl: "https://hose.test", mode: "assisted"
|
||||
};
|
||||
|
||||
function fakeClient(signKeys = ["sign-key"]) {
|
||||
const requests: Array<{ method: string; path: string; json?: unknown }> = [];
|
||||
let config: Record<string, unknown> = {
|
||||
integrations: signKeys.map((signKey) => ({
|
||||
type: "hosecloud", signKey, outboundName: "AI review", mode: "assisted",
|
||||
apiKey: "existing-key", apiSecret: "existing-secret"
|
||||
}))
|
||||
};
|
||||
const client = {
|
||||
get: (path: string) => {
|
||||
requests.push({ method: "GET", path });
|
||||
return { json: async () => ({ data: config }) };
|
||||
},
|
||||
post: (path: string, options: { json: Record<string, unknown> }) => {
|
||||
requests.push({ method: "POST", path, json: options.json });
|
||||
if (path === "api/hosecloud/corporation") {
|
||||
return { json: async () => ({ data: { corporationId: "hose-corp" } }) };
|
||||
}
|
||||
if (path === corp.seal.endpoints.approvalStylePreferences) {
|
||||
config = options.json;
|
||||
return { json: async () => ({ data: config }) };
|
||||
}
|
||||
if (path === "api/hosecloud/outbound-config/sync") {
|
||||
return { json: async () => ({ data: { outboundMessageId: "message" } }) };
|
||||
}
|
||||
throw new Error(`Unexpected POST ${path}`);
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
return { client, requests };
|
||||
}
|
||||
|
||||
async function callDeploy(client: KyInstance, argv: string[]) {
|
||||
const lines: string[] = [];
|
||||
console.log = (line: string) => lines.push(line);
|
||||
console.error = () => {};
|
||||
const args = parseArgs(argv);
|
||||
await handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args);
|
||||
return JSON.parse(lines.join("\n")) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
describe("Hose configure and sync confirmation", () => {
|
||||
test("both execution handlers refuse unconfirmed writes before any network call", async () => {
|
||||
for (const name of ["sealDeployHosecloudConfigure", "sealDeployHosecloudSync"]) {
|
||||
for (const confirm of [undefined, false]) {
|
||||
const fixture = fakeClient();
|
||||
await expect(runCapabilityResult(name, fixture.client, corp, {
|
||||
...(name.endsWith("Configure") ? input : { signKey: "sign-key" }), confirm
|
||||
})).rejects.toMatchObject({ exitCode: 10 });
|
||||
expect(fixture.requests).toHaveLength(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("configure previews a masked diff without persisting credentials or control flags", async () => {
|
||||
const fixture = fakeClient();
|
||||
const preview = await callDeploy(fixture.client, [
|
||||
"deploy", "hosecloud", "configure", "--json", JSON.stringify(input), "--dry-run", "--yes"
|
||||
]);
|
||||
expect(preview.preview).toBe(true);
|
||||
expect(preview.targetUrl).toBe("https://seal.test/api/custom/preferences");
|
||||
expect(JSON.stringify(preview)).not.toContain("mock-secret");
|
||||
expect(JSON.stringify(preview)).not.toContain("existing-secret");
|
||||
expect(fixture.requests.filter((request) => request.method === "POST").map((request) => request.path))
|
||||
.toEqual(["api/hosecloud/corporation"]);
|
||||
const after = (preview.changesDiff as { after: { integrations: Record<string, unknown>[] } }).after;
|
||||
expect(after.integrations[0]?.confirm).toBeUndefined();
|
||||
expect(after.integrations[0]?.dryRun).toBeUndefined();
|
||||
});
|
||||
|
||||
test("configure honors either CLI confirmation flag and keeps control flags out of saved configuration", async () => {
|
||||
for (const flag of ["--yes", "--confirm"]) {
|
||||
const fixture = fakeClient();
|
||||
await callDeploy(fixture.client, ["deploy", "hosecloud", "configure", "--json", JSON.stringify(input), flag]);
|
||||
const saved = fixture.requests.find((request) => request.path === corp.seal.endpoints.approvalStylePreferences && request.method === "POST");
|
||||
expect(saved).toBeDefined();
|
||||
const integration = (saved!.json as { integrations: Record<string, unknown>[] }).integrations[0]!;
|
||||
expect(integration.apiSecret).toBe("mock-secret");
|
||||
expect(integration.confirm).toBeUndefined();
|
||||
expect(integration.dryRun).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
test("a JSON confirm field cannot replace an explicit CLI flag", async () => {
|
||||
const fixture = fakeClient();
|
||||
await expect(callDeploy(fixture.client, [
|
||||
"deploy", "hosecloud", "configure", "--json", JSON.stringify({ ...input, confirm: true })
|
||||
])).rejects.toMatchObject({ exitCode: 10 });
|
||||
expect(fixture.requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("legacy credential spellings are normalized and masked in previews", async () => {
|
||||
const fixture = fakeClient();
|
||||
const { apiKey, apiSecret, ...settings } = input;
|
||||
const preview = await callDeploy(fixture.client, [
|
||||
"deploy", "hosecloud", "configure", "--json",
|
||||
JSON.stringify({ ...settings, appKey: apiKey, appSecurity: apiSecret }), "--dry-run"
|
||||
]);
|
||||
expect(JSON.stringify(preview)).not.toContain("mock-secret");
|
||||
const after = (preview.changesDiff as { after: { integrations: Record<string, unknown>[] } }).after;
|
||||
expect(after.integrations[0]?.apiSecret).toBe("***");
|
||||
expect(after.integrations[0]?.appSecurity).toBeUndefined();
|
||||
});
|
||||
|
||||
test("sync preview matches the live request without calling the synchronization endpoint", async () => {
|
||||
const fixture = fakeClient();
|
||||
const preview = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "sign-key", "--dry-run"]);
|
||||
expect(preview.preview).toBe(true);
|
||||
expect(preview.remoteStateKnown).toBe(false);
|
||||
expect(preview.targetUrl).toBe("https://seal.test/api/hosecloud/outbound-config/sync");
|
||||
expect((preview.changesDiff as { before: unknown }).before).toBeNull();
|
||||
expect(fixture.requests.every((request) => request.method === "GET")).toBe(true);
|
||||
expect(fixture.requests[0]?.path).toBe(corp.seal.endpoints.approvalStylePreferences);
|
||||
|
||||
for (const flag of ["--yes", "--confirm"]) {
|
||||
const live = fakeClient();
|
||||
const result = await callDeploy(live.client, ["deploy", "hosecloud", "sync", "sign-key", flag]);
|
||||
expect(result.synced).toBe(true);
|
||||
expect(live.requests.find((request) => request.path === "api/hosecloud/outbound-config/sync")?.json)
|
||||
.toEqual((preview.changesDiff as { after: unknown }).after);
|
||||
}
|
||||
});
|
||||
|
||||
test("auto only selects a singleton and never replaces confirmation", async () => {
|
||||
const fixture = fakeClient();
|
||||
await expect(callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "--auto"]))
|
||||
.rejects.toMatchObject({ exitCode: 10 });
|
||||
expect(fixture.requests.every((request) => request.method === "GET")).toBe(true);
|
||||
const preview = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "--auto", "--dry-run"]);
|
||||
expect(preview.preview).toBe(true);
|
||||
const multiple = fakeClient(["first", "second"]);
|
||||
await expect(callDeploy(multiple.client, ["deploy", "hosecloud", "sync", "--auto", "--yes"]))
|
||||
.rejects.toMatchObject({ exitCode: 2 });
|
||||
expect(multiple.requests.every((request) => request.method === "GET")).toBe(true);
|
||||
});
|
||||
|
||||
test("either confirmation flag supports singleton selection without a positional signKey", async () => {
|
||||
for (const flag of ["--yes", "--confirm"]) {
|
||||
const fixture = fakeClient();
|
||||
const result = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", flag]);
|
||||
expect(result.synced).toBe(true);
|
||||
expect(fixture.requests[0]?.path).toBe(corp.seal.endpoints.approvalStylePreferences);
|
||||
expect(fixture.requests.filter((request) => request.path === "api/hosecloud/outbound-config/sync")).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
+52
-17
@@ -2,10 +2,11 @@ import { readFileSync } from "node:fs";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, jsonObject, stringOption } from "../parser.js";
|
||||
import { booleanOption, jsonObject, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
import { listHoseIntegrations } from "../../domains/seal/outbound/push.js";
|
||||
import { CliError } from "../errors.js";
|
||||
|
||||
export async function handleDeployCommand(
|
||||
@@ -68,7 +69,7 @@ export async function handleDeployCommand(
|
||||
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
||||
if (!signKey) {
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||
const hoseConfigs = listHoseIntegrations(config);
|
||||
if (hoseConfigs.length === 0) {
|
||||
throw new Error(
|
||||
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
|
||||
@@ -78,9 +79,9 @@ export async function handleDeployCommand(
|
||||
console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${corp.id}]\n`);
|
||||
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
|
||||
for (const item of hoseConfigs) {
|
||||
const name = (item as any).outboundName ?? "SealAI 审批";
|
||||
const name = item.outboundName ?? "SealAI 审批";
|
||||
const key = item.signKey;
|
||||
const origin = (item as any).apiOrigin ?? "production";
|
||||
const origin = item.apiOrigin ?? "production";
|
||||
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
|
||||
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
|
||||
}
|
||||
@@ -111,18 +112,21 @@ export async function handleDeployCommand(
|
||||
}
|
||||
await runCapability("sealDeployHosecloudConfigure", client, corp, {
|
||||
...payload,
|
||||
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
|
||||
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
|
||||
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
|
||||
}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "sync") {
|
||||
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
||||
const autoOpt = booleanOption(args.options.auto) ?? booleanOption(args.options.yes);
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
const confirm = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
||||
const autoOpt = booleanOption(args.options.auto) ?? confirm;
|
||||
|
||||
if (!signKey) {
|
||||
const config = await api.getApprovalStylePreferences(client);
|
||||
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
||||
const config = await api.getApprovalStylePreferences(client, corp.seal.endpoints.approvalStylePreferences);
|
||||
const hoseConfigs = listHoseIntegrations(config);
|
||||
|
||||
if (hoseConfigs.length === 0) {
|
||||
throw new Error(
|
||||
@@ -135,36 +139,67 @@ export async function handleDeployCommand(
|
||||
if (firstHose && hoseConfigs.length === 1 && autoOpt) {
|
||||
const singleKey = firstHose.signKey;
|
||||
console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${singleKey})`);
|
||||
await runCapability("sealDeployHosecloudSync", client, corp, { signKey: singleKey }, outputOptions(args.options));
|
||||
await runCapability("sealDeployHosecloudSync", client, corp, { signKey: singleKey, dryRun, confirm }, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${corp.id}]\n`);
|
||||
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--dry-run] [--yes|--confirm] [--corp ${corp.id}]\n`);
|
||||
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
|
||||
for (const item of hoseConfigs) {
|
||||
const name = (item as any).outboundName ?? "SealAI 审批";
|
||||
const name = item.outboundName ?? "SealAI 审批";
|
||||
const key = item.signKey;
|
||||
const origin = (item as any).apiOrigin ?? "production";
|
||||
const origin = item.apiOrigin ?? "production";
|
||||
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
|
||||
console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`);
|
||||
console.error(` 👉 同步预览: seal-use deploy hosecloud sync ${key} --dry-run --corp ${corp.id}\n`);
|
||||
}
|
||||
|
||||
if (hoseConfigs.length === 1) {
|
||||
console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`);
|
||||
console.error(`💡 提示:若希望自动选择单配置,可使用:seal-use deploy hosecloud sync --auto --dry-run --corp ${corp.id}\n`);
|
||||
}
|
||||
|
||||
throw new CliError(
|
||||
"缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",
|
||||
2,
|
||||
hoseConfigs.length === 1
|
||||
? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --corp ${corp.id}`
|
||||
? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --dry-run --corp ${corp.id}`
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
|
||||
await runCapability("sealDeployHosecloudSync", client, corp, { signKey }, outputOptions(args.options));
|
||||
await runCapability("sealDeployHosecloudSync", client, corp, { signKey, dryRun, confirm }, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync.`);
|
||||
if (action === "test-outbound" || action === "outbound-test") {
|
||||
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
||||
const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]);
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN);
|
||||
const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]);
|
||||
const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]);
|
||||
const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]);
|
||||
const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]);
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
|
||||
await runCapability(
|
||||
"sealDeployHosecloudTestOutbound",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
signKey,
|
||||
flowId,
|
||||
sn,
|
||||
messageId,
|
||||
nodeId,
|
||||
rejectionNum,
|
||||
corporationId,
|
||||
dryRun,
|
||||
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
|
||||
}
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
+115
-9
@@ -1,24 +1,114 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
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 { runCapabilityResult } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js";
|
||||
import { CliError, usageError } from "../../core/errors.js";
|
||||
import {
|
||||
BUILTIN_MONTHLY_TEMPLATE,
|
||||
exportReportPackage,
|
||||
renderReportFile,
|
||||
renderVennAccuracySvg,
|
||||
saveReportMarkdown,
|
||||
validateReportFile,
|
||||
loadReviews,
|
||||
reviewFilePath,
|
||||
writeReview,
|
||||
type MonthlyReportResult
|
||||
} from "../../domains/seal/reports/index.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
|
||||
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
|
||||
export async function handleLocalReportCommand(action: "validate" | "render" | "export" | "template" | "chart", args: ParsedArgs) {
|
||||
if (action === "template") {
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (out) {
|
||||
writeFileSync(resolve(out), BUILTIN_MONTHLY_TEMPLATE, "utf8");
|
||||
printJson({ file: resolve(out), size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
|
||||
} else {
|
||||
printJson({ content: BUILTIN_MONTHLY_TEMPLATE, size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "chart") {
|
||||
const sub = args.command[2];
|
||||
if (sub !== "venn") throw usageError("Usage: seal-use report chart venn --ai <accuracy> --human <accuracy> [--both <accuracy>] [--out <file.svg>]");
|
||||
const ai = numberOption(args.options.ai) ?? numberOption(args.options["ai-accuracy"]) ?? 92.08;
|
||||
const human = numberOption(args.options.human) ?? numberOption(args.options["human-accuracy"]) ?? 83.33;
|
||||
const both = numberOption(args.options.both) ?? numberOption(args.options["both-accurate"]) ?? 75.42;
|
||||
const svg = renderVennAccuracySvg({ aiAccuracy: ai, humanAccuracy: human, bothAccurate: both });
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (out) {
|
||||
writeFileSync(resolve(out), svg, "utf8");
|
||||
printJson({ file: resolve(out), format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, size: Buffer.byteLength(svg) }, outputOptions(args.options));
|
||||
} else {
|
||||
printJson({ format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, svg }, outputOptions(args.options));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const file = args.command[2] ?? stringOption(args.options.file);
|
||||
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : action === "export" ? " --out <目标文件夹>" : ""}`);
|
||||
if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。");
|
||||
if (action === "validate") {
|
||||
const result = await validateReportFile(file);
|
||||
printJson(result, outputOptions(args.options));
|
||||
if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1);
|
||||
return;
|
||||
}
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`);
|
||||
if (action === "export") {
|
||||
const result = await exportReportPackage(file, {
|
||||
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
||||
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
|
||||
});
|
||||
printJson(result, outputOptions(args.options));
|
||||
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1);
|
||||
return;
|
||||
}
|
||||
const result = await renderReportFile(file, {
|
||||
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
||||
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
|
||||
});
|
||||
printJson(result, outputOptions(args.options));
|
||||
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
|
||||
}
|
||||
|
||||
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
|
||||
export async function handleReportCommand(
|
||||
action: string | undefined,
|
||||
client: Awaited<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "data") {
|
||||
const month = stringOption(args.options.month);
|
||||
if (!month) {
|
||||
throw new Error("Usage: seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]");
|
||||
}
|
||||
const result = await runCapabilityResult(
|
||||
"sealReportDataGet",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
month,
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||
}
|
||||
);
|
||||
printJson(result, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
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(
|
||||
const result = await runCapabilityResult(
|
||||
"sealReportMonthlyGet",
|
||||
client,
|
||||
corp,
|
||||
@@ -26,10 +116,26 @@ export async function handleReportCommand(
|
||||
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)
|
||||
);
|
||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns),
|
||||
allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force)
|
||||
}
|
||||
) as MonthlyReportResult;
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||
if (out) {
|
||||
const saved = saveReportMarkdown(
|
||||
result.content,
|
||||
result.templatePath,
|
||||
out,
|
||||
booleanOption(args.options.overwrite),
|
||||
result.dynamicAssets,
|
||||
result.companionFiles
|
||||
);
|
||||
const quotedFile = `'${saved.file.replace(/'/g, "'\\''")}'`;
|
||||
printJson({ ...result, content: undefined, dynamicAssets: undefined, companionFiles: undefined, ...saved, next: {
|
||||
validate: `seal-use report validate ${quotedFile}`,
|
||||
render: `seal-use report render ${quotedFile} --out build/report`
|
||||
} }, outputOptions(args.options));
|
||||
} else printJson({ ...result, dynamicAssets: undefined, companionFiles: undefined }, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { createServer, SEAL_USE_MCP_TOOL_NAME, SEAL_USE_MCP_WRITE_TOOL_NAME } from "../../server.js"
|
||||
|
||||
test("separate CLI processes share one-use tickets and MCP retains the first-phase JSON preview", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-recode-cli-"))
|
||||
const corpId = `recode-${randomBytes(4).toString("hex")}`
|
||||
let posts = 0
|
||||
const rules = [
|
||||
{ id: "a", tenantId: "tenant", code: 0, description: "First", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" },
|
||||
{ id: "b", tenantId: "tenant", code: 2, description: "Second", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" }
|
||||
]
|
||||
const upstream = Bun.serve({
|
||||
hostname: "127.0.0.1", port: 0,
|
||||
fetch(request) {
|
||||
const path = new URL(request.url).pathname
|
||||
if (path === "/api/v1/rules" && request.method === "GET") {
|
||||
return Response.json({ data: { rules, hasPendingDeletes: false } })
|
||||
}
|
||||
if (path === "/api/v1/auth/me") {
|
||||
return Response.json({ data: { user: { id: "operator", tenantId: "tenant", name: "Operator" }, tenant: { id: "tenant", name: "Test" } } })
|
||||
}
|
||||
if (path === "/api/v1/rules/batch-recode" && request.method === "POST") {
|
||||
posts++
|
||||
rules.forEach((rule, index) => { rule.code = index })
|
||||
return Response.json({ data: { activeRules: 2, pendingDeleteRules: 0, nextCode: 2 } })
|
||||
}
|
||||
return Response.json({ error: "Unexpected request" }, { status: 404 })
|
||||
}
|
||||
})
|
||||
const enterprises = join(dir, "enterprises")
|
||||
const store = join(dir, "tickets.sqlite")
|
||||
mkdirSync(enterprises)
|
||||
const url = `http://127.0.0.1:${upstream.port}`
|
||||
writeFileSync(join(enterprises, "corp.json"), JSON.stringify({
|
||||
id: corpId, name: "CLI Test", environment: "test",
|
||||
seal: { url }, source: { type: "seal", token: "test-token", sealUrl: url }
|
||||
}))
|
||||
writeFileSync(join(dir, "config.json"), JSON.stringify({ stateful: false }))
|
||||
const env = {
|
||||
SEAL_USE_ENTERPRISES_DIR: enterprises,
|
||||
SEAL_USE_CONFIG_FILE: join(dir, "config.json"),
|
||||
SEAL_USE_TOKEN_STORE: join(dir, "tokens.json"),
|
||||
SEAL_USE_USAGE_FILE: join(dir, "usage.json"),
|
||||
SEAL_USE_RECODE_STORE: store,
|
||||
SEAL_DISABLE_BG_UPDATE: "1"
|
||||
}
|
||||
const previous = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]]))
|
||||
const server = createServer({ enableCli: true })
|
||||
const client = new Client({ name: "recode-preview-test", version: "1.0.0" })
|
||||
const run = async (args: string[]) => {
|
||||
const child = Bun.spawn([process.execPath, join(import.meta.dirname, "../../cli.ts"), "rules", "recode", "--corp", corpId, ...args], {
|
||||
env: { ...process.env, ...env }, stdout: "pipe", stderr: "pipe"
|
||||
})
|
||||
const [stdout, stderr, exitCode] = await Promise.all([
|
||||
new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited
|
||||
])
|
||||
return { stdout, stderr, exitCode }
|
||||
}
|
||||
try {
|
||||
const dry = await run(["--dry-run"])
|
||||
expect(dry.exitCode).toBe(0)
|
||||
expect(JSON.parse(dry.stdout).executed).toBe(false)
|
||||
expect(existsSync(store)).toBe(false)
|
||||
const first = await run(["--yes"])
|
||||
expect(first.exitCode).toBe(10)
|
||||
const preview = JSON.parse(first.stdout)
|
||||
expect(preview).toMatchObject({ phase: "confirmation_required", executed: false, impactCount: 2, mappingAvailable: false })
|
||||
expect(first.stderr).toContain(preview.nextCommand)
|
||||
expect(posts).toBe(0)
|
||||
await Bun.sleep(510)
|
||||
const competed = await Promise.all([run(["--confirm-code", preview.confirmCode]), run(["--confirmCode", preview.confirmCode])])
|
||||
expect(competed.map(result => result.exitCode).sort()).toEqual([0, 10])
|
||||
const executed = JSON.parse(competed.find(result => result.exitCode === 0)!.stdout)
|
||||
expect(executed).toMatchObject({ executed: true, nextCode: 2 })
|
||||
expect(executed.changes).toEqual([{ beforeCode: "0000", afterCode: "0000" }, { beforeCode: "0002", afterCode: "0001" }])
|
||||
expect(posts).toBe(1)
|
||||
|
||||
for (const [key, value] of Object.entries(env)) process.env[key] = value
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
|
||||
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)])
|
||||
const denied = await client.callTool({ name: SEAL_USE_MCP_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } })
|
||||
expect(denied.isError).toBe(true)
|
||||
const result = await client.callTool({ name: SEAL_USE_MCP_WRITE_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } })
|
||||
expect(result.isError).toBe(true)
|
||||
const content = result.content as Array<{ type: "text"; text: string }>
|
||||
expect(JSON.parse(content[0]!.text)).toMatchObject({ executed: false, phase: "confirmation_required" })
|
||||
expect(content[1]!.text).toContain("nextCommand")
|
||||
expect(posts).toBe(1)
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()])
|
||||
upstream.stop(true)
|
||||
for (const [key, value] of Object.entries(previous)) {
|
||||
if (value === undefined) delete process.env[key]
|
||||
else process.env[key] = value
|
||||
}
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
+53
-13
@@ -1,7 +1,8 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js";
|
||||
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rules/mapping.js";
|
||||
import { RulePushExecutionError } from "../../domains/seal/rules/push.js";
|
||||
import {
|
||||
listAvailableLinters,
|
||||
PRIMARY_LINTERS_DIR,
|
||||
@@ -66,6 +67,18 @@ export async function handleRulesCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "recode") {
|
||||
const result = await runCapabilityResult("sealApprovalRulesRecode", client!, corp, {
|
||||
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
|
||||
confirmCode: stringOption(args.options.confirmCode) ?? stringOption(args.options["confirm-code"])
|
||||
}) as { phase: string; nextCommand?: string };
|
||||
printJson(result, outputOptions(args.options));
|
||||
if (result.phase === "confirmation_required") {
|
||||
throw confirmationRequired("尚未执行规则重排。请核对预览后运行返回的 nextCommand。", result.nextCommand!);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "list") {
|
||||
const version = resolveVersionOption(args);
|
||||
if (booleanOption(args.options.count)) {
|
||||
@@ -326,7 +339,26 @@ export async function handleRulesCommand(
|
||||
}
|
||||
|
||||
if (action === "push") {
|
||||
const file = stringOption(args.options.file) ?? stringOption(args.options.f) ?? maybeName;
|
||||
const statusOnly =
|
||||
maybeName === "status" ||
|
||||
booleanOption(args.options.check) === true ||
|
||||
args.options.status === "true" ||
|
||||
args.options.status === true;
|
||||
const file =
|
||||
stringOption(args.options.file) ??
|
||||
stringOption(args.options.f) ??
|
||||
(maybeName && maybeName !== "status" && !maybeName.startsWith("-") ? maybeName : undefined);
|
||||
if (statusOnly) {
|
||||
await runCapability(
|
||||
"sealApprovalRulesPush",
|
||||
client!,
|
||||
corp,
|
||||
{ file, statusOnly: true },
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmed = booleanOption(args.options.yes) === true;
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
|
||||
const publish = booleanOption(args.options.publish);
|
||||
@@ -339,18 +371,26 @@ export async function handleRulesCommand(
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealApprovalRulesPush",
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
file,
|
||||
dryRun,
|
||||
confirm: confirmed,
|
||||
publish,
|
||||
versionName
|
||||
let result: unknown;
|
||||
try {
|
||||
result = await runCapabilityResult(
|
||||
"sealApprovalRulesPush",
|
||||
client!,
|
||||
corp,
|
||||
{
|
||||
file,
|
||||
dryRun,
|
||||
confirm: confirmed,
|
||||
publish,
|
||||
versionName
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof RulePushExecutionError) {
|
||||
printJson(error.recoveryPayload, outputOptions(args.options));
|
||||
}
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!confirmed && dryRun && result && typeof result === "object") {
|
||||
printJson(
|
||||
|
||||
@@ -66,6 +66,26 @@ export async function handleSimulationCommand(
|
||||
const wait = booleanOption(args.options.wait) === true;
|
||||
const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]) ?? (wait ? false : true);
|
||||
|
||||
const extractExpenses =
|
||||
booleanOption(args.options.extract) ??
|
||||
booleanOption(args.options["extract-expenses"]) ??
|
||||
booleanOption(args.options.extractExpenses) ??
|
||||
booleanOption(args.options["with-expense-extraction"]) ??
|
||||
booleanOption(args.options.withExpenseExtraction);
|
||||
const skipExpenseOption =
|
||||
booleanOption(args.options["skip-extract"]) ??
|
||||
booleanOption(args.options.skipExtract) ??
|
||||
booleanOption(args.options.skipExpenseExtraction) ??
|
||||
booleanOption(args.options["skip-expense-extraction"]);
|
||||
const skipExpenseExtraction =
|
||||
extractExpenses !== undefined ? !extractExpenses : skipExpenseOption;
|
||||
|
||||
if (extractExpenses === true) {
|
||||
console.error(
|
||||
"💡 [simulation] 已开启后台费用明细提取入库 (--extract)。此批次明细将写入费用库,供后续跨单防重报检索。"
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealSimulationBatchCreate",
|
||||
client,
|
||||
@@ -78,7 +98,7 @@ export async function handleSimulationCommand(
|
||||
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
|
||||
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
|
||||
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
|
||||
skipExpenseExtraction: booleanOption(args.options.skipExpenseExtraction) ?? booleanOption(args.options["skip-expense-extraction"]),
|
||||
skipExpenseExtraction,
|
||||
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
|
||||
signKey,
|
||||
packageIds,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js";
|
||||
import { printJson } from "../printer.js";
|
||||
|
||||
export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { compareSemVer, getMirrorMode, isHomebrewInstall, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js";
|
||||
import { compareSemVer, getMirrorMode, handleUpdateCommand, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js";
|
||||
|
||||
type Asset = { name: string; downloadUrl: string; size: number };
|
||||
|
||||
@@ -241,33 +241,58 @@ describe("update command bgSave and cache integration", () => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("isHomebrewInstall", () => {
|
||||
test("requires the executable to resolve inside Homebrew's registered formula prefix", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-homebrew-detect-"));
|
||||
try {
|
||||
const formulaPrefix = join(root, "opt", "seal-use");
|
||||
const cellarBin = join(root, "Cellar", "seal-use", "0.10.33", "bin");
|
||||
const nativeBin = join(root, "bin");
|
||||
const formulaExecutable = join(cellarBin, "seal-use");
|
||||
const nativeExecutable = join(nativeBin, "seal-use");
|
||||
describe("update installation modes", () => {
|
||||
test("a copied source package cannot update its parent application's Git repository", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-source-update-test-"));
|
||||
try {
|
||||
await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }))
|
||||
.rejects.toMatchObject({ exitCode: 13 });
|
||||
expect(existsSync(join(dir, "bun.lock"))).toBe(false);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
mkdirSync(cellarBin, { recursive: true });
|
||||
mkdirSync(nativeBin, { recursive: true });
|
||||
mkdirSync(join(root, "opt"), { recursive: true });
|
||||
writeFileSync(formulaExecutable, "homebrew binary");
|
||||
writeFileSync(nativeExecutable, "native binary");
|
||||
symlinkSync(join(root, "Cellar", "seal-use", "0.10.33"), formulaPrefix);
|
||||
|
||||
expect(isHomebrewInstall(formulaExecutable, formulaPrefix)).toBe(true);
|
||||
expect(isHomebrewInstall(nativeExecutable, formulaPrefix)).toBe(false);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("does not infer Homebrew from a matching directory name alone", () => {
|
||||
expect(isHomebrewInstall("/opt/homebrew/bin/seal-use", "/tmp/not-installed-seal-use")).toBe(false);
|
||||
});
|
||||
test("native updates ignore package managers and allow selecting a release", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-native-update-test-"));
|
||||
const originalExecPath = process.execPath;
|
||||
const originalEnv = { ...process.env };
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalLog = console.log;
|
||||
try {
|
||||
// Every executable, cache and response is a temp fixture; never update the running test engine.
|
||||
const binary = join(dir, "seal-use");
|
||||
const invoked = join(dir, "package-manager-invoked");
|
||||
writeFileSync(binary, "native fixture");
|
||||
writeFileSync(join(dir, "brew"), `#!/bin/sh\ntouch '${invoked}'\nprintf '%s\\n' '${dir}'\n`, { mode: 0o755 });
|
||||
process.execPath = binary;
|
||||
process.env.PATH = `${dir}:${originalEnv.PATH ?? ""}`;
|
||||
process.env.SEAL_USE_UPDATE_CACHE_FILE = join(dir, "update-cache.json");
|
||||
process.env.SEAL_USE_MIRROR = "github";
|
||||
globalThis.fetch = Object.assign(async () => new Response(JSON.stringify([
|
||||
{ tag_name: "v100.0.0", assets: [] },
|
||||
{ tag_name: "v99.0.0", assets: [] }
|
||||
]), { headers: { "Content-Type": "application/json" } }), { preconnect: originalFetch.preconnect });
|
||||
let stdout = "";
|
||||
console.log = (message: string) => { stdout += message; };
|
||||
const runtime = { appRoot: dir, entryFile: join(dir, "src", "cli.ts") };
|
||||
await handleUpdateCommand(runtime, { checkOnly: true, targetVersion: "99.0.0" });
|
||||
expect(JSON.parse(stdout)).toMatchObject({ mode: "binary", latestVersion: "99.0.0", updateAvailable: true });
|
||||
stdout = "";
|
||||
// Reaching asset selection proves explicit versions are not blocked by a removed installation mode.
|
||||
await expect(handleUpdateCommand(runtime, { targetVersion: "v99.0.0" }))
|
||||
.rejects.toThrow("in release v99.0.0");
|
||||
expect(stdout).toBe("");
|
||||
expect(existsSync(invoked)).toBe(false);
|
||||
expect(readFileSync(binary, "utf8")).toBe("native fixture");
|
||||
} finally {
|
||||
process.execPath = originalExecPath;
|
||||
process.env = originalEnv;
|
||||
globalThis.fetch = originalFetch;
|
||||
console.log = originalLog;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+9
-276
@@ -1,12 +1,13 @@
|
||||
import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { basename, dirname, isAbsolute, join, relative } from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary } from "../../core/runtime.js";
|
||||
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
|
||||
import { readInstalledSkillVersion } from "../../core/embedded-skill.js";
|
||||
import { saveUpdateCache } from "../../core/update-cache.js";
|
||||
import { VERSION, IS_RELEASE } from "../../version.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import { validationError } from "../../core/errors.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
const DEFAULT_GITHUB_REPO = "yunyingk/seal-use";
|
||||
@@ -130,6 +131,10 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
return;
|
||||
}
|
||||
|
||||
// Source updates must operate on this package's checkout, never a parent app's repository.
|
||||
if (!existsSync(join(runtime.appRoot, ".git"))) {
|
||||
throw validationError("当前源码安装目录不是 seal-use 的 Git 工作区。请使用发行版二进制,或从 seal-use 仓库通过 npm link 安装。");
|
||||
}
|
||||
try {
|
||||
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
|
||||
} catch (err) {
|
||||
@@ -145,19 +150,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Homebrew managed mode
|
||||
if (isHomebrewInstall()) {
|
||||
try {
|
||||
await handleHomebrewUpdate(options, repo, targetVersion);
|
||||
return;
|
||||
} catch (err) {
|
||||
console.error(
|
||||
`⚠️ Homebrew 自动更新失败,回退至原生二进制更新: ${err instanceof Error ? err.message : String(err)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Standalone binary mode: check GitHub Releases
|
||||
// 3. Standalone binary mode: check GitHub Releases
|
||||
const platform = detectPlatform();
|
||||
const arch = detectArch();
|
||||
|
||||
@@ -201,18 +194,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
return;
|
||||
}
|
||||
|
||||
if (targetVersion && !options.checkOnly) {
|
||||
printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
targetVersion,
|
||||
latestVersion,
|
||||
mode: "homebrew",
|
||||
message: "Homebrew-managed installations follow the formula version and do not support selecting a historical release. Use Homebrew directly for version pinning."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.checkOnly) {
|
||||
printJson({
|
||||
updated: false,
|
||||
@@ -440,254 +421,6 @@ function detectArch(): "arm64" | "x64" {
|
||||
return process.arch === "arm64" ? "arm64" : "x64";
|
||||
}
|
||||
|
||||
function homebrewFormulaPrefix(): string | undefined {
|
||||
try {
|
||||
const result = spawnSync("brew", ["--prefix", "seal-use"], {
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
encoding: "utf-8"
|
||||
});
|
||||
if (result.status !== 0 || typeof result.stdout !== "string") return undefined;
|
||||
const prefix = result.stdout.trim();
|
||||
return prefix || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function homebrewInstalledVersion(): string | undefined {
|
||||
try {
|
||||
const result = spawnSync("brew", ["list", "--versions", "seal-use"], {
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
encoding: "utf-8"
|
||||
});
|
||||
if (result.status !== 0 || typeof result.stdout !== "string") return undefined;
|
||||
const parts = result.stdout.trim().split(/\s+/);
|
||||
return parts.length >= 2 ? parts[parts.length - 1] : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function isHomebrewInstall(
|
||||
execPath = process.execPath,
|
||||
formulaPrefix = homebrewFormulaPrefix()
|
||||
): boolean {
|
||||
if (!formulaPrefix) return false;
|
||||
|
||||
try {
|
||||
const resolvedExec = realpathSync(execPath);
|
||||
const resolvedPrefix = realpathSync(formulaPrefix);
|
||||
const fromFormula = relative(resolvedPrefix, resolvedExec);
|
||||
const parentPrefix = `..${process.platform === "win32" ? "\\" : "/"}`;
|
||||
return Boolean(fromFormula && fromFormula !== ".." && !fromFormula.startsWith(parentPrefix) && !isAbsolute(fromFormula));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleHomebrewUpdate(
|
||||
options: UpdateOptions,
|
||||
repo: string,
|
||||
targetVersion?: string
|
||||
): Promise<void> {
|
||||
const releases = await fetchGitHubReleases(repo, 30);
|
||||
const release = targetVersion
|
||||
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
|
||||
await fetchGitHubRelease(repo, targetVersion))
|
||||
: (releases[0] ?? await fetchGitHubRelease(repo));
|
||||
|
||||
const latestVersion = release?.version ?? VERSION;
|
||||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
||||
const shouldUpdate = isUpgrade || Boolean(options.force);
|
||||
|
||||
if (release?.version) {
|
||||
saveUpdateCache({
|
||||
latestVersion: release.version,
|
||||
publishedAt: release.publishedAt,
|
||||
releaseUrl: release.htmlUrl
|
||||
});
|
||||
}
|
||||
|
||||
if (options.bgSave) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.checkOnly) {
|
||||
const currentRelease = releases.find((r) => r.version === VERSION);
|
||||
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
|
||||
printJson({
|
||||
updated: false,
|
||||
updateAvailable: isUpgrade,
|
||||
currentVersion: VERSION,
|
||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: release?.publishedAt,
|
||||
behindCount: pendingReleases.length,
|
||||
pendingReleases: pendingReleases.map((r) => ({
|
||||
version: r.version,
|
||||
tagName: r.tagName,
|
||||
publishedAt: r.publishedAt,
|
||||
author: r.author,
|
||||
releaseNotes: r.notes,
|
||||
releaseUrl: r.htmlUrl
|
||||
})),
|
||||
releaseNotes: release?.notes ?? "",
|
||||
releaseUrl: release?.htmlUrl ?? "",
|
||||
mode: "homebrew"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!shouldUpdate) {
|
||||
printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
latestVersion,
|
||||
mode: "homebrew",
|
||||
message: `seal-use is already up to date (v${VERSION})`
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.error("ℹ️ 检测到当前 seal-use 由 Homebrew 管理。");
|
||||
console.error("📦 正在通过 Homebrew 极速更新: brew update && brew upgrade seal-use ...");
|
||||
|
||||
const installedBefore = homebrewInstalledVersion();
|
||||
const alreadyLatestBeforeUpdate = installedBefore
|
||||
? !isNewerVersion(latestVersion, installedBefore)
|
||||
: false;
|
||||
let alreadyLatest = alreadyLatestBeforeUpdate;
|
||||
// `brew update` refreshes all configured taps. Passing a tap name here is
|
||||
// parsed as a formula upgrade by newer Homebrew versions (and fails with
|
||||
// "No available formula ... tap").
|
||||
const tapUpdate = await runHomebrewCommand(
|
||||
["update"],
|
||||
"🔄 [1/2] 正在刷新 Homebrew 软件源(可能需要几分钟)..."
|
||||
);
|
||||
|
||||
if (tapUpdate.status !== 0) {
|
||||
const msg = tapUpdate.stderr?.trim() || tapUpdate.stdout?.trim();
|
||||
throw new Error(`brew update failed (exit ${tapUpdate.status}): ${msg || "unknown error"}`);
|
||||
}
|
||||
|
||||
// 2. Upgrade the formula
|
||||
const upgradeRes = await runHomebrewCommand(
|
||||
["upgrade", "seal-use"],
|
||||
"⬆️ [2/2] 正在升级 seal-use..."
|
||||
);
|
||||
|
||||
const outCombined = `${upgradeRes.stdout || ""} ${upgradeRes.stderr || ""}`;
|
||||
const brewReportsAlreadyLatest =
|
||||
outCombined.includes("already installed") || outCombined.includes("latest version already installed");
|
||||
|
||||
if (upgradeRes.status !== 0 && !brewReportsAlreadyLatest) {
|
||||
throw new Error(
|
||||
`brew upgrade seal-use failed (exit ${upgradeRes.status}): ${upgradeRes.stderr.trim() || upgradeRes.stdout.trim()}`
|
||||
);
|
||||
}
|
||||
|
||||
const installedVersion = homebrewInstalledVersion();
|
||||
if (installedVersion && isNewerVersion(latestVersion, installedVersion)) {
|
||||
throw new Error(
|
||||
`Homebrew still has seal-use v${installedVersion}; expected v${latestVersion}. ` +
|
||||
"Refresh the tap and run `brew upgrade seal-use` again."
|
||||
);
|
||||
}
|
||||
alreadyLatest = alreadyLatestBeforeUpdate;
|
||||
|
||||
// Refresh installed skill through new binary
|
||||
try {
|
||||
spawnSync("seal-use", ["skill", "install"], { stdio: "ignore" });
|
||||
} catch {
|
||||
// best-effort
|
||||
}
|
||||
|
||||
console.error(
|
||||
alreadyLatest
|
||||
? "ℹ️ seal-use 已是 Homebrew 中的最新版本。"
|
||||
: "✅ seal-use 已通过 Homebrew 成功更新!"
|
||||
);
|
||||
|
||||
printJson({
|
||||
updated: !alreadyLatest,
|
||||
previousVersion: VERSION,
|
||||
latestVersion,
|
||||
mode: "homebrew",
|
||||
message: alreadyLatest
|
||||
? `seal-use is already at the latest version v${latestVersion} in Homebrew`
|
||||
: `Successfully upgraded seal-use to v${latestVersion} via Homebrew`
|
||||
});
|
||||
}
|
||||
|
||||
type HomebrewCommandResult = {
|
||||
status: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs Homebrew without buffering its output until completion. Homebrew can spend several minutes
|
||||
* refreshing taps or downloading a formula, so its output belongs on stderr as live diagnostics;
|
||||
* stdout must remain reserved for the command's final machine-readable JSON payload.
|
||||
*/
|
||||
function runHomebrewCommand(args: string[], startMessage: string): Promise<HomebrewCommandResult> {
|
||||
console.error(startMessage);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn("brew", args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, NONINTERACTIVE: "1" }
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let lastOutputAt = Date.now();
|
||||
let settled = false;
|
||||
|
||||
const forward = (chunk: Buffer, stream: "stdout" | "stderr") => {
|
||||
const text = chunk.toString();
|
||||
if (stream === "stdout") stdout += text;
|
||||
else stderr += text;
|
||||
lastOutputAt = Date.now();
|
||||
try {
|
||||
process.stderr.write(text);
|
||||
} catch {
|
||||
// Ignore a closed diagnostic stream; the child process still needs to complete normally.
|
||||
}
|
||||
};
|
||||
|
||||
child.stdout?.on("data", (chunk: Buffer) => forward(chunk, "stdout"));
|
||||
child.stderr?.on("data", (chunk: Buffer) => forward(chunk, "stderr"));
|
||||
|
||||
const heartbeat = setInterval(() => {
|
||||
if (Date.now() - lastOutputAt >= 15000) {
|
||||
console.error("⏳ Homebrew 仍在运行,当前没有新的输出,请稍候...");
|
||||
lastOutputAt = Date.now();
|
||||
}
|
||||
}, 15000);
|
||||
heartbeat.unref?.();
|
||||
|
||||
const finish = (callback: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearInterval(heartbeat);
|
||||
callback();
|
||||
};
|
||||
|
||||
child.once("error", (error) => finish(() => reject(error)));
|
||||
child.once("close", (status, signal) =>
|
||||
finish(() => resolve({ status, signal, stdout, stderr }))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
type GitHubAsset = {
|
||||
name: string;
|
||||
downloadUrl: string;
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { confirmationRequired } from "../errors.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
@@ -73,9 +73,17 @@ export async function handleUsersCommand(
|
||||
|
||||
if (action === "delegation" || action === "impersonate") {
|
||||
const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone);
|
||||
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");
|
||||
if (!userIdOrPhone) throw new Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
|
||||
const note = stringOption(args.options.note);
|
||||
await runCapability("sealUserDelegationCreate", client, corp, { userIdOrPhone, note }, outputOptions(args.options));
|
||||
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
|
||||
await runCapability(
|
||||
"sealUserDelegationCreate",
|
||||
client,
|
||||
corp,
|
||||
{ userIdOrPhone, note, expiresInHours },
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -288,7 +288,7 @@ describe("seal-use webhook replay CLI", () => {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli(["webhook", "replay", "run-001"]);
|
||||
const result = await runCli(["webhook", "replay", "run-001", "--yes"]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
@@ -513,4 +513,122 @@ describe("seal-use webhook replay CLI", () => {
|
||||
const parsed = JSON.parse(forceResult.stdout);
|
||||
expect(parsed.targetCorp.id).toBe("prod-corp-target");
|
||||
});
|
||||
|
||||
test("approval-runs replay --channel hose-outbound executes dry-run preview with safety guards", async () => {
|
||||
setupMockEnv();
|
||||
|
||||
const mockHoseIntegrations = [
|
||||
{
|
||||
type: "hosecloud",
|
||||
signKey: "sign-key-xyz",
|
||||
outboundName: "测试出站通道",
|
||||
mode: "assisted",
|
||||
corporationId: "corp-id-123"
|
||||
}
|
||||
];
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl =
|
||||
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
|
||||
if (
|
||||
requestUrl.includes("api/v1/system/preferences/approval-style") ||
|
||||
requestUrl.includes("api/v1/agent/ai-approval/config")
|
||||
) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
data: { integrations: mockHoseIntegrations }
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
}) as any;
|
||||
|
||||
const result = await runCli([
|
||||
"approval-runs",
|
||||
"replay",
|
||||
"--sn",
|
||||
"S26002992",
|
||||
"--channel",
|
||||
"hose-outbound",
|
||||
"--message-id",
|
||||
"ID01Wh05v0In3F",
|
||||
"--flow-id",
|
||||
"ID01Wah1FQ9faf",
|
||||
"--dry-run"
|
||||
]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.preview).toBe(true);
|
||||
expect(parsed.channel).toBe("hose-outbound");
|
||||
expect(parsed.payload.messageId).toBe("ID01Wh05v0In3F");
|
||||
expect(parsed.payload.nodeId).toBe("FLOW:测试模拟节点_禁止流转");
|
||||
expect(parsed.safetyGuards.targetModeAssisted).toBe(true);
|
||||
expect(parsed.safetyGuards.nodeId412Blocked).toBe(true);
|
||||
});
|
||||
|
||||
test("webhook replay requires confirmation before provisioning or pushing", async () => {
|
||||
setupMockEnv();
|
||||
let mutations = 0;
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
|
||||
if (method !== "GET") mutations++;
|
||||
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||
status: 200, headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}) as typeof fetch;
|
||||
const result = await runCli(["approval-runs", "replay", "run-001"]);
|
||||
expect(result.exitCode).toBe(10);
|
||||
expect(result.stderr).toContain("--yes or --confirm");
|
||||
expect(mutations).toBe(0);
|
||||
});
|
||||
|
||||
test("outbound CLI gates both entry points and passes either confirmation flag", async () => {
|
||||
setupMockEnv();
|
||||
let pushes = 0;
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const requestUrl = input instanceof Request ? input.url : input.toString();
|
||||
if (requestUrl.includes("/api/hosecloud/outbound")) {
|
||||
pushes++;
|
||||
return new Response(JSON.stringify({ data: { success: true } }), {
|
||||
status: 200, headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ data: { integrations: [{
|
||||
type: "hosecloud", signKey: "key", mode: "assisted", corporationId: "corp"
|
||||
}] } }), { status: 200, headers: { "Content-Type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
for (const command of [
|
||||
["approval-runs", "replay", "--sn", "SN", "--channel", "hose-outbound"],
|
||||
["deploy", "hosecloud", "test-outbound"]
|
||||
]) {
|
||||
const args = [...command, "--flow-id", "flow", "--message-id", "message"];
|
||||
for (const flags of [[], ["--yes=false"], ["--force"]]) {
|
||||
const before = pushes;
|
||||
const result = await runCli([...args, ...flags]);
|
||||
expect(result.exitCode).toBe(10);
|
||||
expect(pushes).toBe(before);
|
||||
}
|
||||
for (const flag of ["--yes", "--confirm"]) {
|
||||
const before = pushes;
|
||||
const result = await runCli([...args, flag]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(pushes).toBe(before + 1);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.consumptionVerified).toBe(false);
|
||||
expect(parsed.recordId).toBeUndefined();
|
||||
}
|
||||
|
||||
const before = pushes;
|
||||
const preview = await runCli([...args, "--node-id", "FLOW:real-node", "--dry-run"]);
|
||||
expect(preview.exitCode).toBe(0);
|
||||
expect(pushes).toBe(before);
|
||||
const parsed = JSON.parse(preview.stdout);
|
||||
expect((parsed.safetyGuards ?? parsed.safetyCheck).nodeId412Blocked).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,8 @@ import {
|
||||
executeApprovalRunsReplay,
|
||||
resolveReplayCorpPair,
|
||||
type ReplayRecordsQuery
|
||||
} from "../../domains/seal/webhook-replay.js";
|
||||
} from "../../domains/seal/replay/webhook.js";
|
||||
import { executeHoseOutboundReplay } from "../../domains/seal/replay/hose-outbound.js";
|
||||
import {
|
||||
checkWebhookReadiness,
|
||||
exportApprovalRunsToResourcePack,
|
||||
@@ -147,6 +148,44 @@ export async function handleWebhookCommand(
|
||||
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
||||
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||
const confirm = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
||||
|
||||
const channel =
|
||||
stringOption(args.options.channel) ??
|
||||
(booleanOption(args.options["hose-outbound"]) || booleanOption(args.options.outbound) ? "hose-outbound" : undefined);
|
||||
|
||||
if (channel === "hose-outbound" || channel === "outbound") {
|
||||
const flowId = stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]);
|
||||
const messageId = stringOption(args.options.messageId) ?? stringOption(args.options["message-id"]);
|
||||
const nodeId = stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]);
|
||||
const corporationId = stringOption(args.options.corporationId) ?? stringOption(args.options["corporation-id"]);
|
||||
const rejectionNum = numberOption(args.options.rejectionNum) ?? numberOption(args.options["rejection-num"]);
|
||||
const targetSignKey =
|
||||
stringOption(args.options.signKey) ??
|
||||
stringOption(args.options["sign-key"]) ??
|
||||
stringOption(args.options.webhook);
|
||||
|
||||
const result = await executeHoseOutboundReplay({
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
sourceClient,
|
||||
targetClient,
|
||||
sn,
|
||||
recordId,
|
||||
flowId,
|
||||
messageId,
|
||||
nodeId,
|
||||
corporationId,
|
||||
rejectionNum,
|
||||
targetSignKey,
|
||||
dryRun,
|
||||
confirm,
|
||||
force
|
||||
});
|
||||
|
||||
printJson(result, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
const query: ReplayRecordsQuery = {
|
||||
recordId,
|
||||
@@ -170,7 +209,8 @@ export async function handleWebhookCommand(
|
||||
snSuffix,
|
||||
docIdPrefix,
|
||||
docIdSuffix,
|
||||
dryRun
|
||||
dryRun,
|
||||
confirm
|
||||
});
|
||||
|
||||
if (dryRun) {
|
||||
|
||||
@@ -91,12 +91,16 @@ describe("CLI semantic errors", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps domain failures and quality gates at exit 1", () => {
|
||||
test("keeps domain failures, post-mutation recovery errors, and quality gates at exit 1", () => {
|
||||
expect(classifyCliError(new Error("未找到指定的规则版本: 99"))).toEqual({ exitCode: 1 });
|
||||
expect(classifyCliError(new Error("[Linter 质量门禁未通过] 综合评分 80 低于要求的最低分 85 分"))).toEqual({
|
||||
exitCode: 1
|
||||
});
|
||||
expect(classifyCliError(new Error("Webhook 单据推送失败 (500): internal"))).toEqual({ exitCode: 1 });
|
||||
expect(classifyCliError(new Error("测试企业「T」AI 审批额度不足:当前剩余 200 点"))).toEqual({ exitCode: 1 });
|
||||
expect(
|
||||
classifyCliError(new Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。"))
|
||||
).toEqual({ exitCode: 1 });
|
||||
expect(classifyCliError(new Error("上游网关响应超时,请重试或检查网络连接。"))).toEqual({ exitCode: 1 });
|
||||
});
|
||||
});
|
||||
@@ -61,6 +61,14 @@ describe("extractHelpRequest", () => {
|
||||
});
|
||||
|
||||
describe("renderHelp", () => {
|
||||
test("explains both recode phases without exposing internal activation timing", () => {
|
||||
const help = renderHelp(["rules", "recode"]);
|
||||
expect(help).toContain("一次性凭证");
|
||||
expect(help).toContain("另一次调用");
|
||||
expect(help).toContain("不执行重排");
|
||||
expect(help).not.toContain("500");
|
||||
expect(help).not.toContain("--confirm-code");
|
||||
});
|
||||
test("renders global help when target is empty", () => {
|
||||
const help = renderHelp([]);
|
||||
expect(help).toContain("seal-use CLI");
|
||||
|
||||
+240
-25
@@ -343,14 +343,23 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "push",
|
||||
summary: "Push rules from local JSON file to enterprise draft space",
|
||||
usage: ["seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]"]
|
||||
summary: "Push rules from local JSON file to enterprise draft space (with step recovery & status check)",
|
||||
usage: [
|
||||
"seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]",
|
||||
"seal-use rules push status [--file <path>] [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "clear",
|
||||
summary: "Clear all draft rules from enterprise",
|
||||
usage: ["seal-use rules clear [--dry-run|--yes] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "recode",
|
||||
summary: "Preview consecutive rule numbering, then execute with a one-use confirmation code",
|
||||
usage: ["seal-use rules recode [--dry-run] --corp <corpId>"],
|
||||
description: "首次运行只返回影响预览、一次性凭证和 nextCommand,不执行重排;核对后另一次调用返回的命令才会生效。凭证绑定企业、环境和草稿,5 分钟有效且只能使用一次。--yes/--confirm 不能跳过该流程。--dry-run 只预览,不签发凭证。服务端决定编号顺序,所有规则均可能变号;逐条映射在执行后回读。重排不发布版本;查看旧编号需结合发布版本。"
|
||||
},
|
||||
{
|
||||
name: "map",
|
||||
summary: "Inspect locally synced production/test rule code mappings",
|
||||
@@ -435,9 +444,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
name: "replay",
|
||||
usage: [
|
||||
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
||||
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
|
||||
"seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
|
||||
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--corp <corpId>]",
|
||||
"seal-use webhook replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]",
|
||||
"seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Approval run record ID to replay" },
|
||||
@@ -450,6 +459,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN and documentId" },
|
||||
{ flag: "--sn-prefix <str>", description: "Optional prefix prepended to documentSN and documentId" },
|
||||
{ flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" },
|
||||
{ flag: "--yes, --confirm", description: "Required for live replay; --force only overrides the environment guard" },
|
||||
{ flag: "--force", description: "Allow replaying to a production enterprise" }
|
||||
],
|
||||
description: "Extracts structured form fields from historical approval records (Webhook or Hose source), sanitizes field types, and pushes documents to the target Webhook channel. Automatically infers 1-to-1 bound test/production enterprise pairs."
|
||||
@@ -582,20 +592,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
name: "replay",
|
||||
summary: "Replay approval run record into a Webhook integration",
|
||||
usage: [
|
||||
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
|
||||
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
|
||||
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
|
||||
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--corp <corpId>]",
|
||||
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]",
|
||||
"seal-use approval-runs replay --sn <documentSN> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]",
|
||||
"seal-use approval-runs replay <recordId> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]",
|
||||
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "<recordId>", description: "Approval run record ID" },
|
||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
||||
{ flag: "--channel <webhook|hose-outbound>", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" },
|
||||
{ flag: "--sign-key <key>", description: "Target Hose integration signKey for hose-outbound; required when the target has several integrations" },
|
||||
{ flag: "--message-id <msgId>", description: "Explicit Hose outbound messageId override" },
|
||||
{ flag: "--rejection-num <n>", description: "Target specific rejection iteration (0, 1, 2, ...)" },
|
||||
{ flag: "--limit <n>", description: "Batch replay latest N records" },
|
||||
{ flag: "--status <status>", description: "Filter records by status" },
|
||||
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
|
||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside" },
|
||||
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed" },
|
||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
|
||||
{ flag: "--dry-run", description: "Preview payload without sending" }
|
||||
{ flag: "--dry-run", description: "Preview payload without sending" },
|
||||
{ flag: "--yes, --confirm", description: "Required for live replay; --force only overrides environment and pairing guards" }
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -603,21 +620,88 @@ 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.",
|
||||
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
|
||||
commands: [
|
||||
{
|
||||
name: "data",
|
||||
summary: "Extract pure structured report data, metrics, diverged runs, and triggers without templates",
|
||||
usage: ["seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
],
|
||||
description: "Template-free data pack for Agent authoring: returns performance metrics, formula fractions, template groups, top risk tags, diverged runs with exact triggered conditions, and reviews."
|
||||
},
|
||||
{
|
||||
name: "template",
|
||||
summary: "Dump or save the built-in monthly report Markdown template",
|
||||
usage: ["seal-use report template [--out <file.md>]"],
|
||||
options: [
|
||||
{ flag: "--out <file>", description: "Save built-in Markdown template directly to a file" }
|
||||
],
|
||||
description: "Tenant-free local command: returns or saves the built-in monthly.md template so an Agent or user can co-author."
|
||||
},
|
||||
{
|
||||
name: "chart venn",
|
||||
summary: "Generate dynamic Venn accuracy comparison SVG chart independently",
|
||||
usage: ["seal-use report chart venn --ai <acc> --human <acc> [--both <both>] [--out <file.svg>]"],
|
||||
options: [
|
||||
{ flag: "--ai <acc>", description: "AI accuracy percentage (e.g. 92.08)" },
|
||||
{ flag: "--human <acc>", description: "Human accuracy percentage (e.g. 83.33)" },
|
||||
{ flag: "--both <both>", description: "Both accurate percentage (e.g. 75.42)" },
|
||||
{ flag: "--out <file>", description: "Save SVG directly to file" }
|
||||
],
|
||||
description: "Tenant-free local command: calculates proportions and outputs high-fidelity SVG chart."
|
||||
},
|
||||
{
|
||||
name: "monthly",
|
||||
aliases: ["month"],
|
||||
summary: "Fill the monthly report template with performance, risk, and approval-run data",
|
||||
usage: ["seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
|
||||
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--allow-unreviewed] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to report-templates/monthly.md" },
|
||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" },
|
||||
{ flag: "--out <file>", description: "Save Markdown plus local images beside the report; stdout stays JSON (without the content field)" },
|
||||
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" },
|
||||
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" },
|
||||
{ flag: "--allow-unreviewed", description: "Bypass pre-flight adjudication gate to generate draft when unreviewed diverged runs exist" }
|
||||
],
|
||||
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
|
||||
},
|
||||
{
|
||||
name: "validate",
|
||||
summary: "Check a local report's structure, images, totals, and formulas",
|
||||
usage: ["seal-use report validate <报告.md>"],
|
||||
options: [],
|
||||
description: "Local only: no --corp, credentials, or Seal requests. Returns JSON issues; exit 1 if validation fails."
|
||||
},
|
||||
{
|
||||
name: "render",
|
||||
summary: "Validate and export HTML, full-length PNG, and A4 PDF from local Markdown",
|
||||
usage: ["seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]"],
|
||||
options: [
|
||||
{ flag: "--out <stem>", description: "Output filename stem; extensions are appended" },
|
||||
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
|
||||
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
|
||||
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
|
||||
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
|
||||
],
|
||||
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
|
||||
},
|
||||
{
|
||||
name: "export",
|
||||
summary: "Package Markdown, local 4x assets, self-contained HTML, and PDF into a dedicated directory",
|
||||
usage: ["seal-use report export <报告.md> --out <输出目录> [--format <all|html|pdf>]"],
|
||||
options: [
|
||||
{ flag: "--out <dir>", description: "Dedicated output directory for the report bundle" },
|
||||
{ flag: "--format <format>", description: "all (default), html, or pdf" },
|
||||
{ flag: "--width <px>", description: "PNG viewport width, default 1200" },
|
||||
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
|
||||
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" }
|
||||
],
|
||||
description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF."
|
||||
},
|
||||
{
|
||||
name: "review set",
|
||||
summary: "Record one human adjudication (who was right: AI or human) for a document",
|
||||
@@ -629,7 +713,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{ 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."
|
||||
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
|
||||
},
|
||||
{
|
||||
name: "review list",
|
||||
@@ -654,9 +738,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "create",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window)",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction)",
|
||||
usage: [
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]",
|
||||
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
|
||||
]
|
||||
@@ -740,13 +824,34 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "hosecloud configure",
|
||||
summary: "Configure HoseCloud deployment settings",
|
||||
usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]"]
|
||||
summary: "Save Hose integration settings in Seal",
|
||||
usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--dry-run", description: "Preview the configuration diff without saving" },
|
||||
{ flag: "--yes, --confirm", description: "Required to save the integration configuration" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "hosecloud sync",
|
||||
summary: "Synchronize HoseCloud rules and definitions",
|
||||
usage: ["seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]"]
|
||||
summary: "Create or update Hose outbound messages and callback URLs",
|
||||
usage: ["seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--auto", description: "Select the sole Hose integration; does not confirm synchronization" },
|
||||
{ flag: "--dry-run", description: "Preview the sync request without creating or updating messages" },
|
||||
{ flag: "--yes, --confirm", description: "Required for live synchronization" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "hosecloud test-outbound",
|
||||
summary: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发(要求 assisted 模式)",
|
||||
usage: [
|
||||
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <id> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]",
|
||||
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --sn <SN> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "--dry-run", description: "Preview the outbound payload without sending" },
|
||||
{ flag: "--yes, --confirm", description: "Required for live outbound push" }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -835,11 +940,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
name: "link",
|
||||
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
|
||||
usage: [
|
||||
"seal-use auth link [--note <note>] [--corp <corpId>]",
|
||||
"seal-use auth link --from-link <url> [--note <note>]"
|
||||
"seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]",
|
||||
"seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]"
|
||||
],
|
||||
options: [
|
||||
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" },
|
||||
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" },
|
||||
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
|
||||
],
|
||||
description:
|
||||
@@ -859,9 +965,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
name: "hose-link",
|
||||
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
|
||||
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200] [--force]"],
|
||||
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]"],
|
||||
options: [
|
||||
{ flag: "--expire <seconds>", description: "链接有效时间(秒),默认 7200,支持如 86400(1天)" },
|
||||
{ flag: "--expire, --expires-in <duration>", description: "链接有效时间,推荐 '7d' 或 '2h'(默认 2h,兼容秒数如 7200)" },
|
||||
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
|
||||
],
|
||||
description:
|
||||
@@ -912,7 +1018,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
{
|
||||
name: "delegation",
|
||||
summary: "Create delegation token for a specific user",
|
||||
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]"]
|
||||
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--note <note>", description: "委托授权备注说明" },
|
||||
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" }
|
||||
]
|
||||
},
|
||||
{
|
||||
name: "reset-password",
|
||||
@@ -1170,6 +1280,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",
|
||||
|
||||
+47
-3
@@ -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";
|
||||
@@ -62,8 +65,49 @@ export async function runCapabilityResult(
|
||||
);
|
||||
// Schema gate: a missing required field or an out-of-range value fails here
|
||||
// with exit 13 instead of reaching the handler as `undefined` and surfacing
|
||||
// as an opaque upstream error. Valid params pass through untouched.
|
||||
parseCapabilityParams(tool, compactParams);
|
||||
// as an opaque upstream error. Valid params are normalized so the handler
|
||||
// executes with the exact coerced/defaulted values that passed validation.
|
||||
const normalizedParams = parseCapabilityParams(tool, compactParams);
|
||||
const handler = tool.handler as SealCapability["handler"];
|
||||
return handler(client, compactParams as never, { corp });
|
||||
return handler(client, normalizedParams 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 normalizedParams =
|
||||
parsed.data && typeof parsed.data === "object"
|
||||
? {
|
||||
...compactParams,
|
||||
...Object.fromEntries(
|
||||
Object.entries(parsed.data as Record<string, unknown>).filter(([, value]) => value !== undefined)
|
||||
)
|
||||
}
|
||||
: compactParams;
|
||||
const handler = tool.handler as (params: never, service: LangfuseService) => Promise<unknown>;
|
||||
printJson(await handler(normalizedParams as never, createLangfuseService()), options);
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
KNOWN_FLAGS,
|
||||
numberOption,
|
||||
parseArgs,
|
||||
parseDelegationExpireHours,
|
||||
parseHoseExpireSeconds,
|
||||
splitOption,
|
||||
stringOption,
|
||||
VALUE_FLAGS
|
||||
@@ -116,6 +118,87 @@ describe("option helpers", () => {
|
||||
expect(splitOption("")).toBeUndefined();
|
||||
expect(splitOption(true)).toBeUndefined();
|
||||
});
|
||||
|
||||
test("parseDelegationExpireHours parses days, hours, rounds down with stderr notice, and clamps to 1..168", () => {
|
||||
expect(parseDelegationExpireHours(undefined)).toBe(24);
|
||||
expect(parseDelegationExpireHours("7d")).toBe(168);
|
||||
expect(parseDelegationExpireHours("1d")).toBe(24);
|
||||
expect(parseDelegationExpireHours("24h")).toBe(24);
|
||||
expect(parseDelegationExpireHours("2h")).toBe(2);
|
||||
expect(parseDelegationExpireHours("168")).toBe(168);
|
||||
expect(parseDelegationExpireHours(168)).toBe(168);
|
||||
expect(parseDelegationExpireHours("86400")).toBe(24);
|
||||
expect(parseDelegationExpireHours("7200s")).toBe(2);
|
||||
|
||||
// Floor fractional hours and clamp minimum to 1h
|
||||
expect(parseDelegationExpireHours("90m")).toBe(1);
|
||||
expect(parseDelegationExpireHours("1.5h")).toBe(1);
|
||||
expect(parseDelegationExpireHours("30m")).toBe(1);
|
||||
expect(parseDelegationExpireHours("1800s")).toBe(1);
|
||||
|
||||
expect(() => parseDelegationExpireHours("8d")).toThrow("最多为 7 天 (168h)");
|
||||
expect(() => parseDelegationExpireHours("0h")).toThrow("必须为大于 0 的有效时长");
|
||||
expect(() => parseDelegationExpireHours("invalid")).toThrow("必须为有效时长格式");
|
||||
});
|
||||
|
||||
test("parseHoseExpireSeconds parses days, hours, minutes, raw seconds, and converts unitless small numbers to hours", () => {
|
||||
expect(parseHoseExpireSeconds(undefined)).toBe(7200);
|
||||
expect(parseHoseExpireSeconds("7200")).toBe(7200);
|
||||
expect(parseHoseExpireSeconds(7200)).toBe(7200);
|
||||
expect(parseHoseExpireSeconds("2h")).toBe(7200);
|
||||
expect(parseHoseExpireSeconds("7d")).toBe(604800);
|
||||
expect(parseHoseExpireSeconds("30m")).toBe(1800);
|
||||
|
||||
// Unitless small numbers (<= 168) convert to hours automatically
|
||||
expect(parseHoseExpireSeconds(2)).toBe(7200);
|
||||
expect(parseHoseExpireSeconds("2")).toBe(7200);
|
||||
expect(parseHoseExpireSeconds("24")).toBe(86400);
|
||||
|
||||
expect(() => parseHoseExpireSeconds("0s")).toThrow("必须为大于 0 的有效时长");
|
||||
expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长");
|
||||
});
|
||||
|
||||
test("overflowing --expire literals are usage errors before reaching auth", () => {
|
||||
for (const parse of [parseDelegationExpireHours, parseHoseExpireSeconds]) {
|
||||
for (const literal of ["9".repeat(309), "9".repeat(309) + "s", "9".repeat(308) + "d"]) {
|
||||
expect(() => parse(literal)).toThrow();
|
||||
try {
|
||||
parse(literal);
|
||||
} catch (error) {
|
||||
expect((error as { exitCode: number }).exitCode).toBe(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("both --expire flags read a unitless literal the same way", () => {
|
||||
// Regression: the two parsers used to each carry their own copy of the
|
||||
// unitless heuristic, so `--expire 300` meant 5 minutes on one path and
|
||||
// clamped to 1 hour on the other purely by implementation accident.
|
||||
for (const literal of [300, "300", 86400, "86400", 7200, "7200"]) {
|
||||
const hours = parseDelegationExpireHours(literal);
|
||||
const seconds = parseHoseExpireSeconds(literal);
|
||||
const unitlessSeconds = typeof literal === "number" ? literal : Number(literal);
|
||||
expect(seconds).toBe(unitlessSeconds);
|
||||
// Delegation floors to whole hours and never drops below 1h.
|
||||
expect(hours).toBe(Math.max(Math.floor(seconds / 3600), 1));
|
||||
}
|
||||
|
||||
// A small unitless value is hours on both paths.
|
||||
expect(parseDelegationExpireHours("24")).toBe(24);
|
||||
expect(parseHoseExpireSeconds("24")).toBe(86_400);
|
||||
expect(parseDelegationExpireHours(2)).toBe(2);
|
||||
expect(parseHoseExpireSeconds(2)).toBe(7200);
|
||||
});
|
||||
|
||||
test("sub-second input stays a usage error on both --expire flags", () => {
|
||||
// Regression: the shared tokenizer understands `ms` for the simulation
|
||||
// windows, and without a per-caller unit set that grammar leaked into
|
||||
// --expire, silently rounding 500ms up to a 1h / 1s link.
|
||||
expect(() => parseDelegationExpireHours("500ms")).toThrow("必须为有效时长格式");
|
||||
expect(() => parseHoseExpireSeconds("500ms")).toThrow("必须为有效时长");
|
||||
expect(() => parseHoseExpireSeconds("200ms")).toThrow("必须为有效时长");
|
||||
});
|
||||
});
|
||||
|
||||
describe("flag registry cross-check", () => {
|
||||
|
||||
+146
-43
@@ -1,6 +1,7 @@
|
||||
import type { WebhookMode } from "../domains/seal/types.js";
|
||||
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
|
||||
import type { ParsedArgs } from "./types.js";
|
||||
import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../core/duration.js";
|
||||
import { usageError } from "./errors.js";
|
||||
|
||||
/**
|
||||
@@ -22,52 +23,52 @@ import { usageError } from "./errors.js";
|
||||
|
||||
// Read with booleanOption(...) / Boolean(...) / presence check.
|
||||
export const BOOLEAN_FLAGS = new Set([
|
||||
"V", "add", "all", "as-hose", "attachments", "auto",
|
||||
"V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto",
|
||||
"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", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
|
||||
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
|
||||
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "recode", "refresh", "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",
|
||||
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
// Read with stringOption/numberOption/splitOption(...).
|
||||
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",
|
||||
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
|
||||
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
|
||||
"channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
|
||||
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
|
||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||
"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",
|
||||
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
|
||||
"from-link", "host", "humanResult", "id", "input", "integration",
|
||||
"json", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
|
||||
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
|
||||
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration",
|
||||
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
|
||||
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
|
||||
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "note", "o", "offset", "out",
|
||||
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
|
||||
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
|
||||
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
|
||||
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
|
||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
|
||||
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
|
||||
"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",
|
||||
@@ -77,54 +78,54 @@ export const VALUE_FLAGS = new Set([
|
||||
"template",
|
||||
"taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth",
|
||||
"timeout", "timezone", "title", "to", "token", "tokenId",
|
||||
"template",
|
||||
"trace-id", "trace-limit",
|
||||
"type", "until", "url", "userId", "version-name", "versionName",
|
||||
"verdict",
|
||||
"webhook", "workflow-type-id", "workflowTypeId"
|
||||
"webhook", "width", "workflow-type-id", "workflowTypeId"
|
||||
]);
|
||||
|
||||
// Registered flags. Unknown flags are rejected.
|
||||
export const KNOWN_FLAGS = new Set([
|
||||
"V", "access-token", "accessToken", "add", "all", "app-key",
|
||||
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
|
||||
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
||||
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
||||
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
|
||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
||||
"content-file", "content-type", "contentFile", "contentType", "contextLines", "corp",
|
||||
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
|
||||
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
|
||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
|
||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
|
||||
"default", "departmentId", "dept", "desc", "description", "description-file",
|
||||
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
|
||||
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
|
||||
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
|
||||
"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",
|
||||
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
||||
"full", "h", "help", "hose", "hose-sso", "hoseSso",
|
||||
"host", "humanResult", "id", "include-deleted", "include-simulation", "include-unchanged",
|
||||
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
|
||||
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
|
||||
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
||||
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
|
||||
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
|
||||
"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",
|
||||
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
|
||||
"max-runs",
|
||||
"month",
|
||||
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
|
||||
"note", "o", "offset", "out", "out-dir", "outDir",
|
||||
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId",
|
||||
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
|
||||
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
|
||||
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
|
||||
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
|
||||
"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", "rejection-num", "rejectionNum", "repo",
|
||||
"report-id",
|
||||
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
|
||||
"reviewed-by", "reviewedBy",
|
||||
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId",
|
||||
"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",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
|
||||
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration",
|
||||
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
||||
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
|
||||
@@ -134,10 +135,10 @@ export const KNOWN_FLAGS = new Set([
|
||||
"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",
|
||||
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
@@ -168,6 +169,7 @@ export function parseArgs(argv: string[]): ParsedArgs {
|
||||
const eqIdx = raw.indexOf("=");
|
||||
const key = raw.slice(0, eqIdx);
|
||||
const val = raw.slice(eqIdx + 1);
|
||||
if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。");
|
||||
options[key] = val;
|
||||
continue;
|
||||
}
|
||||
@@ -436,3 +438,104 @@ export function materialPackFilePolicyOptions(
|
||||
allowedExtensions
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an `--expire` literal through the shared tokenizer, raising the two
|
||||
* usage errors both link flags share. The format hint differs per flag only in
|
||||
* which example it recommends.
|
||||
*/
|
||||
function readExpireToken(
|
||||
value: string | boolean | number,
|
||||
options: { formatHint: string; unitlessHint?: string }
|
||||
): DurationToken {
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw usageError(
|
||||
`Invalid --expire: ${value}。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。`
|
||||
);
|
||||
}
|
||||
const token = tokenizeDuration(value, { units: EXPIRE_UNITS });
|
||||
if (!token) throw usageError(`Invalid --expire: ${value}。`);
|
||||
return token;
|
||||
}
|
||||
|
||||
if (typeof value !== "string") {
|
||||
throw usageError(`Invalid --expire: ${String(value)}。`);
|
||||
}
|
||||
|
||||
const token = tokenizeDuration(value, { units: EXPIRE_UNITS });
|
||||
if (!token) {
|
||||
throw usageError(`Invalid --expire: '${value}'。必须为有效时长格式${options.formatHint}`);
|
||||
}
|
||||
if (token.value <= 0) {
|
||||
throw usageError(
|
||||
`Invalid --expire: '${value}'。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。`
|
||||
);
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
export function parseDelegationExpireHours(
|
||||
value: string | boolean | number | undefined,
|
||||
defaultHours = 24
|
||||
): number {
|
||||
if (value === undefined || value === null || value === "") {
|
||||
return defaultHours;
|
||||
}
|
||||
|
||||
const token = readExpireToken(value, {
|
||||
formatHint: ",推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)",
|
||||
unitlessHint: ",推荐使用 '7d' 或 '24h'"
|
||||
});
|
||||
|
||||
// Seal delegation links are hourly and capped at 7 days.
|
||||
const rawHours = expireSeconds(token) / 3600;
|
||||
if (rawHours > 168) {
|
||||
throw usageError(
|
||||
`Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。`
|
||||
);
|
||||
}
|
||||
|
||||
const finalHours = Math.floor(rawHours);
|
||||
|
||||
if (finalHours < 1) {
|
||||
console.error(
|
||||
`👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!Number.isInteger(rawHours)) {
|
||||
console.error(
|
||||
`👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。`
|
||||
);
|
||||
}
|
||||
|
||||
return finalHours;
|
||||
}
|
||||
|
||||
export function parseHoseExpireSeconds(
|
||||
value: string | boolean | number | undefined,
|
||||
defaultSeconds = 7200
|
||||
): number {
|
||||
if (value === undefined || value === null || value === "") {
|
||||
return defaultSeconds;
|
||||
}
|
||||
|
||||
const token = readExpireToken(value, {
|
||||
formatHint: ",推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)"
|
||||
});
|
||||
|
||||
// A bare number is ambiguous: <=168 is read as hours, larger as seconds.
|
||||
if (token.unit === undefined && token.value <= 168) {
|
||||
console.error(
|
||||
`👉 提示: 检测到未加单位的数值 ${token.value},已按 ${token.value} 小时 (${Math.round(token.value * 3600)}s) 自动换算。建议明确使用 --expire ${token.value}h。`
|
||||
);
|
||||
}
|
||||
|
||||
const seconds = Math.round(expireSeconds(token));
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) {
|
||||
throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`);
|
||||
}
|
||||
return seconds;
|
||||
}
|
||||
@@ -26,6 +26,7 @@ describe("CLI read-only classification", () => {
|
||||
"auth status",
|
||||
"auth test",
|
||||
"auth doctor",
|
||||
"auth seal-link list",
|
||||
"doctor auth"
|
||||
]);
|
||||
|
||||
@@ -61,6 +62,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 +102,7 @@ describe("CLI read-only classification", () => {
|
||||
["auth", "keys"],
|
||||
["analytics", "analyze", "record-1"],
|
||||
["tool", "sealApprovalRuleCreate", "--json", "{}"],
|
||||
["langfuse", "unknown-verb"],
|
||||
["totally-unknown", "list"],
|
||||
[]
|
||||
]) {
|
||||
@@ -129,21 +135,34 @@ describe("CLI read-only classification", () => {
|
||||
expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false);
|
||||
});
|
||||
|
||||
test("allows rules push status / --check as read-only while refusing mutating rules push forms", () => {
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "status", "--corp", "corp-a"])).toBe(true);
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "--check", "--corp", "corp-a"])).toBe(true);
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "--corp", "corp-a"])).toBe(false);
|
||||
expect(isReadOnlyCliCommand(["rules", "push", "status", "--yes", "--corp", "corp-a"])).toBe(false);
|
||||
});
|
||||
|
||||
test("refuses command lines that cannot be parsed", () => {
|
||||
expect(isReadOnlyCliCommand(["--json"])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// The two classifications are maintained by hand, in different files: the CLI allow-list here and
|
||||
// The two classifications are maintained in different files: the CLI allow-list here and
|
||||
// SEAL_READ_ONLY_CAPABILITIES in the tool registry. Nothing stopped them from disagreeing, and they did —
|
||||
// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs
|
||||
// were simply missing. This derives one from the other and fails on any new disagreement.
|
||||
// were simply missing. This scans both `runCapability` and `runCapabilityResult` and fails on any disagreement.
|
||||
describe("CLI allow-list agrees with the tool registry", () => {
|
||||
// `deploy` only accepts `deploy hosecloud <action>`; the short `deploy <action>` form throws
|
||||
// "未知的发布目标系统" at runtime, so these pairs are unreachable rather than refused.
|
||||
const UNREACHABLE_CLI_FORMS = new Set(["deploy requirements", "deploy list", "deploy status"]);
|
||||
// "未知的发布目标系统" at runtime. `auth seal-link` only calls `sealDelegationList` when the
|
||||
// third token `list` is present (`auth seal-link list`); bare `auth seal-link` mints a token.
|
||||
const UNREACHABLE_CLI_FORMS = new Set([
|
||||
"deploy requirements",
|
||||
"deploy list",
|
||||
"deploy status",
|
||||
"auth seal-link"
|
||||
]);
|
||||
|
||||
test("every CLI verb dispatching to a read-only tool is itself read-only", () => {
|
||||
test("every CLI verb dispatching to a read-only tool is itself read-only, and mutating tools are not read-only", () => {
|
||||
const files = readdirSync(join(import.meta.dir, "commands")).filter(
|
||||
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
|
||||
);
|
||||
@@ -152,7 +171,8 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
||||
for (const file of files) {
|
||||
const area = file.replace(/\.ts$/, "");
|
||||
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
|
||||
const pattern = /action === "([a-z0-9-]+)"[\s\S]{0,600}?runCapability\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
|
||||
const pattern =
|
||||
/if\s*\(\s*action === "([a-z0-9-]+)"(?:(?!\bif\s*\(\s*action\b)[\s\S]){0,600}?runCapability(?:Result)?\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
|
||||
let match;
|
||||
while ((match = pattern.exec(source))) {
|
||||
pairs.push({ area, action: match[1]!, tool: match[2]! });
|
||||
@@ -160,7 +180,7 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
||||
}
|
||||
|
||||
// If the dispatch shape changes this silently finds nothing, which would make the test vacuous.
|
||||
expect(pairs.length).toBeGreaterThan(50);
|
||||
expect(pairs.length).toBeGreaterThan(55);
|
||||
|
||||
const disagreements = pairs
|
||||
.filter((pair) => SEAL_READ_ONLY_CAPABILITIES.has(pair.tool))
|
||||
@@ -169,5 +189,12 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
||||
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
|
||||
|
||||
expect(disagreements).toEqual([]);
|
||||
|
||||
const unsafeMutating = pairs
|
||||
.filter((pair) => SEAL_MUTATING_CAPABILITIES.has(pair.tool))
|
||||
.filter((pair) => isReadOnlyCliCommand([pair.area, pair.action]))
|
||||
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
|
||||
|
||||
expect(unsafeMutating).toEqual([]);
|
||||
});
|
||||
});
|
||||
+31
-3
@@ -37,6 +37,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"count",
|
||||
"export",
|
||||
"flow",
|
||||
"hose-flow",
|
||||
"list",
|
||||
// `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry.
|
||||
"search",
|
||||
@@ -68,8 +69,8 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
// read forms cannot be separated from the value-taking write forms. `config get` returns
|
||||
// the same summary (mode + lint included), so read access loses nothing.
|
||||
config: ["paths", "get"],
|
||||
auth: ["check", "diagnose", "status", "test", "doctor", "link list"],
|
||||
users: ["search", "get", "delegation"],
|
||||
auth: ["check", "diagnose", "status", "test", "doctor", "link list", "seal-link list"],
|
||||
users: ["search", "get"],
|
||||
contacts: ["departments", "children", "users", "sync-time"],
|
||||
data: ["expenses", "invoices"],
|
||||
llm: ["config", "providers"],
|
||||
@@ -78,10 +79,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"],
|
||||
report: ["monthly", "data", "template", "chart venn", "validate", "render", "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: [""]
|
||||
@@ -113,7 +127,10 @@ export function describeCliCommand(argv: string[]): { area: string; actionTokens
|
||||
export function isReadOnlyCliCommand(argv: string[]): boolean {
|
||||
let area: string;
|
||||
let actionTokens: string[];
|
||||
let options: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = parseArgs(argv);
|
||||
options = parsed.options;
|
||||
({ area, actionTokens } = describeCliCommand(argv));
|
||||
} catch {
|
||||
// Unparsable command lines are refused rather than guessed at.
|
||||
@@ -123,6 +140,17 @@ export function isReadOnlyCliCommand(argv: string[]): boolean {
|
||||
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
|
||||
// The `<corpId>` selector form; the bare form falls through to the `""` entry.
|
||||
if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true;
|
||||
// `rules push status` / `rules push --check` inspects the recovery journal and
|
||||
// reconciles against the remote draft without mutating anything.
|
||||
if (
|
||||
area === "rules" &&
|
||||
actionTokens[0] === "push" &&
|
||||
(actionTokens[1] === "status" || options.check === true || options.status === "true") &&
|
||||
!options.yes &&
|
||||
!options.confirm
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const allowed = READ_ONLY_COMMANDS[area];
|
||||
if (!allowed) return false;
|
||||
|
||||
@@ -64,6 +64,7 @@ export const KNOWN_AREAS = new Set([
|
||||
"skill",
|
||||
"probe",
|
||||
"doctor",
|
||||
"langfuse",
|
||||
"changelog",
|
||||
"test"
|
||||
]);
|
||||
@@ -223,6 +224,19 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
|
||||
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
|
||||
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;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { SEAL_CONFIG_DIR } from "../paths.js";
|
||||
import {
|
||||
CorpTokenCache,
|
||||
HoseAuthCache,
|
||||
@@ -9,14 +9,14 @@ import {
|
||||
TokenStoreSchema
|
||||
} from "./types.js";
|
||||
|
||||
const PRIMARY_TOKEN_STORE = join(homedir(), ".config", "seal-use", "sealTokens.json");
|
||||
const LEGACY_TOKEN_STORE = join(homedir(), ".config", "seal-home", "sealTokens.json");
|
||||
const PRIMARY_TOKEN_STORE = join(SEAL_CONFIG_DIR, "tokens.json");
|
||||
const MIGRATION_TOKEN_STORE = join(SEAL_CONFIG_DIR, "sealTokens.json");
|
||||
|
||||
function resolveReadStorePath(): string {
|
||||
const configured = (process.env.SEAL_USE_TOKEN_STORE ?? process.env.SEAL_HOME_TOKEN_STORE)?.trim();
|
||||
if (configured) return configured;
|
||||
if (existsSync(PRIMARY_TOKEN_STORE)) return PRIMARY_TOKEN_STORE;
|
||||
if (existsSync(LEGACY_TOKEN_STORE)) return LEGACY_TOKEN_STORE;
|
||||
if (existsSync(MIGRATION_TOKEN_STORE)) return MIGRATION_TOKEN_STORE;
|
||||
return PRIMARY_TOKEN_STORE;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { resolveTargetBinaryPath } from "../../scripts/dev-override.js";
|
||||
|
||||
describe("development CLI install target", () => {
|
||||
test("npm-linked source is never selected as the binary replacement target", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-dev-target-test-"));
|
||||
const originalPath = process.env.PATH;
|
||||
try {
|
||||
const command = join(dir, "seal-use");
|
||||
const source = join(dir, "cli.ts");
|
||||
writeFileSync(source, "#!/usr/bin/env bun\nconsole.log('source fixture')\n");
|
||||
chmodSync(source, 0o755);
|
||||
symlinkSync(source, command);
|
||||
process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${originalPath ?? ""}`;
|
||||
expect(resolveTargetBinaryPath()).toBe(command);
|
||||
expect(readFileSync(source, "utf8")).toContain("source fixture");
|
||||
} finally {
|
||||
if (originalPath === undefined) delete process.env.PATH; else process.env.PATH = originalPath;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("native command symlinks continue to replace the installed target", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-dev-target-test-"));
|
||||
const originalPath = process.env.PATH;
|
||||
try {
|
||||
const command = join(dir, "seal-use");
|
||||
mkdirSync(join(dir, "formula"));
|
||||
const target = join(dir, "formula", "seal-use");
|
||||
writeFileSync(target, "native binary fixture");
|
||||
chmodSync(target, 0o755);
|
||||
symlinkSync(target, command);
|
||||
process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${originalPath ?? ""}`;
|
||||
expect(resolveTargetBinaryPath()).toBe(realpathSync(target));
|
||||
} finally {
|
||||
if (originalPath === undefined) delete process.env.PATH; else process.env.PATH = originalPath;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -112,20 +112,24 @@ function findGroupOrWorldReadable(paths: string[]): string[] {
|
||||
export function diagnoseSystem(): DoctorDiagnosis {
|
||||
const home = homedir();
|
||||
const configDir = join(home, ".config", "seal-use");
|
||||
const stateDir = join(configDir, "state");
|
||||
const enterprisesDir = join(configDir, "enterprises");
|
||||
const globalConfigFile = join(configDir, "config.json");
|
||||
const tokenStore = join(configDir, "sealTokens.json");
|
||||
const mappingsDir = join(configDir, "mappings");
|
||||
const tokenStore = existsSync(join(configDir, "tokens.json"))
|
||||
? join(configDir, "tokens.json")
|
||||
: existsSync(join(configDir, "sealTokens.json"))
|
||||
? join(configDir, "sealTokens.json")
|
||||
: join(configDir, "tokens.json");
|
||||
const mappingsDir = existsSync(join(stateDir, "mappings")) ? join(stateDir, "mappings") : join(configDir, "mappings");
|
||||
const agentSkillDir = getDefaultGlobalSkillDir();
|
||||
const exportDir = join(home, "Downloads");
|
||||
|
||||
const globalBinaryCandidates = [
|
||||
"/opt/homebrew/bin/seal-use",
|
||||
"/usr/local/bin/seal-use",
|
||||
join(home, ".local", "bin", "seal-use"),
|
||||
join(home, "bin", "seal-use")
|
||||
];
|
||||
const detectedBinary = globalBinaryCandidates.find((p) => existsSync(p)) ?? process.execPath;
|
||||
const detectedBinary = Bun.which("seal-use") ?? globalBinaryCandidates.find((p) => existsSync(p)) ?? process.execPath;
|
||||
|
||||
const directories: Record<string, DirectoryHealth> = {
|
||||
configDir: {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
export interface DirectorySpec {
|
||||
name: string;
|
||||
category: "config" | "binary" | "skill" | "export" | "temp";
|
||||
category: "config" | "binary" | "skill" | "export" | "temp" | "cache";
|
||||
standardPath: string;
|
||||
purpose: string;
|
||||
accessMode: "read-write" | "executable" | "transient";
|
||||
@@ -55,23 +55,31 @@ export const EMBEDDED_DIRECTORY_SPECS: DirectorySpec[] = [
|
||||
{
|
||||
name: "会话凭据安全缓存",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use/sealTokens.json",
|
||||
standardPath: "~/.config/seal-use/tokens.json",
|
||||
purpose: "缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",
|
||||
accessMode: "read-write",
|
||||
retention: "cache"
|
||||
},
|
||||
{
|
||||
name: "规则版本映射快照",
|
||||
name: "业务持久状态目录",
|
||||
category: "config",
|
||||
standardPath: "~/.config/seal-use/mappings",
|
||||
purpose: "存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",
|
||||
standardPath: "~/.config/seal-use/state",
|
||||
purpose: "业务持久状态统一子目录,存放规则映射对照(mappings)、发布快照(snapshots)与人工复核账本(reviews)。",
|
||||
accessMode: "read-write",
|
||||
retention: "persistent"
|
||||
},
|
||||
{
|
||||
name: "运行时缓存根目录",
|
||||
category: "cache",
|
||||
standardPath: "~/.cache/seal-use",
|
||||
purpose: "用户本地运行时缓存目录,存放版本检测缓存、打点度量、官方只读校验器及报告离线资源,可随时安全清理。",
|
||||
accessMode: "read-write",
|
||||
retention: "cache"
|
||||
},
|
||||
{
|
||||
name: "全局命令行程序",
|
||||
category: "binary",
|
||||
standardPath: "/opt/homebrew/bin/seal-use",
|
||||
standardPath: "/usr/local/bin/seal-use",
|
||||
purpose: "macOS / Linux 全局独立单文件二进制程序;旧版 seal-home 命令仅保留解析兼容,不再新建全局别名。",
|
||||
accessMode: "executable",
|
||||
retention: "persistent"
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
durationSeconds,
|
||||
expireSeconds,
|
||||
parseDurationMs,
|
||||
tokenizeDuration
|
||||
} from "./duration.js";
|
||||
|
||||
describe("tokenizeDuration", () => {
|
||||
test("splits magnitude from unit and accepts every alias", () => {
|
||||
expect(tokenizeDuration("7d")).toEqual({ value: 7, unit: "d" });
|
||||
expect(tokenizeDuration("24h")).toEqual({ value: 24, unit: "h" });
|
||||
expect(tokenizeDuration("90m")).toEqual({ value: 90, unit: "m" });
|
||||
expect(tokenizeDuration("7200s")).toEqual({ value: 7200, unit: "s" });
|
||||
expect(tokenizeDuration("1.5h")).toEqual({ value: 1.5, unit: "h" });
|
||||
expect(tokenizeDuration("2 hours")).toEqual({ value: 2, unit: "h" });
|
||||
expect(tokenizeDuration("500ms")).toEqual({ value: 500, unit: "ms" });
|
||||
expect(tokenizeDuration(" 300 ")).toEqual({ value: 300, unit: undefined });
|
||||
expect(tokenizeDuration(168)).toEqual({ value: 168, unit: undefined });
|
||||
});
|
||||
|
||||
test("rejects unparseable input instead of guessing", () => {
|
||||
expect(tokenizeDuration("invalid")).toBeUndefined();
|
||||
expect(tokenizeDuration("")).toBeUndefined();
|
||||
expect(tokenizeDuration("-5m")).toBeUndefined();
|
||||
expect(tokenizeDuration("5parsecs")).toBeUndefined();
|
||||
expect(tokenizeDuration(Number.NaN)).toBeUndefined();
|
||||
expect(tokenizeDuration(true as unknown as string)).toBeUndefined();
|
||||
expect(tokenizeDuration("9".repeat(309))).toBeUndefined();
|
||||
expect(tokenizeDuration("9".repeat(309) + "s")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("expireSeconds", () => {
|
||||
test("reads a unitless number at most 168 as hours and a larger one as seconds", () => {
|
||||
// Both --expire paths used to reimplement this rule separately, and they
|
||||
// disagreed at the boundary; 300 now means 5 minutes everywhere.
|
||||
expect(expireSeconds({ value: 168, unit: undefined })).toBe(168 * 3600);
|
||||
expect(expireSeconds({ value: 169, unit: undefined })).toBe(169);
|
||||
expect(expireSeconds({ value: 300, unit: undefined })).toBe(300);
|
||||
expect(expireSeconds({ value: 86400, unit: undefined })).toBe(86_400);
|
||||
});
|
||||
|
||||
test("converts explicit units regardless of magnitude", () => {
|
||||
expect(expireSeconds({ value: 7, unit: "d" })).toBe(604_800);
|
||||
expect(expireSeconds({ value: 7200, unit: "s" })).toBe(7200);
|
||||
expect(expireSeconds({ value: 30, unit: "m" })).toBe(1800);
|
||||
});
|
||||
});
|
||||
|
||||
describe("durationSeconds", () => {
|
||||
test("uses the caller's unitless policy when none is written", () => {
|
||||
expect(durationSeconds({ value: 5, unit: undefined }, "s")).toBe(5);
|
||||
expect(durationSeconds({ value: 5, unit: undefined }, "h")).toBe(18_000);
|
||||
expect(durationSeconds({ value: 5, unit: "ms" }, "h")).toBe(0.005);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseDurationMs", () => {
|
||||
test("converts simulation windows to milliseconds", () => {
|
||||
expect(parseDurationMs("2s")).toBe(2000);
|
||||
expect(parseDurationMs("10m")).toBe(600_000);
|
||||
expect(parseDurationMs("5m")).toBe(300_000);
|
||||
expect(parseDurationMs("500ms")).toBe(500);
|
||||
expect(parseDurationMs("1h")).toBe(3_600_000);
|
||||
expect(parseDurationMs("1d")).toBe(86_400_000);
|
||||
});
|
||||
|
||||
test("reads unitless input as seconds, matching the flag's defaults", () => {
|
||||
expect(parseDurationMs("30")).toBe(30_000);
|
||||
});
|
||||
|
||||
test("falls back rather than failing a batch over a bad poll interval", () => {
|
||||
expect(parseDurationMs("soon")).toBe(600_000);
|
||||
expect(parseDurationMs("soon", 1000)).toBe(1000);
|
||||
expect(parseDurationMs("9".repeat(309) + "s", 1000)).toBe(1000);
|
||||
expect(parseDurationMs("9".repeat(308) + "d", 1000)).toBe(1000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Duration tokenizing shared by every flag that accepts `7d` / `1.5h` / `300`.
|
||||
*
|
||||
* The tokenizer owns exactly one job: turning the written form into a magnitude
|
||||
* plus a canonical unit. Interpretation stays with each caller, because the
|
||||
* three consumers genuinely disagree — Seal delegation links take whole hours
|
||||
* in 1..168, Hose assistance links take seconds, simulation windows take
|
||||
* milliseconds. Sharing the grammar (and the unitless heuristic) is what stops
|
||||
* `--expire 300` from parsing two different ways in two files.
|
||||
*/
|
||||
|
||||
export type DurationUnit = "ms" | "s" | "m" | "h" | "d";
|
||||
|
||||
export interface DurationToken {
|
||||
/** The magnitude exactly as written, before any unit conversion. */
|
||||
value: number;
|
||||
/** `undefined` when the input carried no unit, e.g. `300`. */
|
||||
unit: DurationUnit | undefined;
|
||||
}
|
||||
|
||||
const UNIT_ALIASES: Record<string, DurationUnit> = {
|
||||
ms: "ms",
|
||||
s: "s",
|
||||
sec: "s",
|
||||
secs: "s",
|
||||
second: "s",
|
||||
seconds: "s",
|
||||
m: "m",
|
||||
min: "m",
|
||||
mins: "m",
|
||||
minute: "m",
|
||||
minutes: "m",
|
||||
h: "h",
|
||||
hr: "h",
|
||||
hrs: "h",
|
||||
hour: "h",
|
||||
hours: "h",
|
||||
d: "d",
|
||||
day: "d",
|
||||
days: "d"
|
||||
};
|
||||
|
||||
const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i;
|
||||
|
||||
export interface TokenizeDurationOptions {
|
||||
/**
|
||||
* Units this caller accepts. Restricting the set keeps a shared tokenizer
|
||||
* from quietly widening a flag's grammar: sub-second input was a usage error
|
||||
* for `--expire` before the parsers were unified, and must stay one.
|
||||
*/
|
||||
units?: readonly DurationUnit[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a duration literal. Returns `undefined` when the input cannot be read
|
||||
* at all — callers decide whether that is a usage error or a default.
|
||||
*
|
||||
* A unitless number keeps whatever magnitude it had; pair it with
|
||||
* {@link expireSeconds} or an explicit `unitless` argument to resolve it.
|
||||
*/
|
||||
export function tokenizeDuration(
|
||||
value: string | number,
|
||||
options: TokenizeDurationOptions = {}
|
||||
): DurationToken | undefined {
|
||||
if (typeof value === "number") {
|
||||
return Number.isFinite(value) ? { value, unit: undefined } : undefined;
|
||||
}
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const match = value.trim().match(DURATION_PATTERN);
|
||||
if (!match || !match[1]) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const magnitude = parseFloat(match[1]);
|
||||
if (!Number.isFinite(magnitude)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const rawUnit = match[2]?.toLowerCase();
|
||||
if (!rawUnit) {
|
||||
return { value: magnitude, unit: undefined };
|
||||
}
|
||||
|
||||
const unit = UNIT_ALIASES[rawUnit];
|
||||
if (!unit) {
|
||||
return undefined;
|
||||
}
|
||||
if (options.units && !options.units.includes(unit)) {
|
||||
return undefined;
|
||||
}
|
||||
return { value: magnitude, unit };
|
||||
}
|
||||
|
||||
/**
|
||||
* Units the `--expire` flags accept. Sub-second precision is meaningless for
|
||||
* an assistance link and was rejected before the parsers were shared.
|
||||
*/
|
||||
export const EXPIRE_UNITS: readonly DurationUnit[] = ["d", "h", "m", "s"];
|
||||
|
||||
/** Convert a token to seconds, resolving a unitless value as `unitless`. */
|
||||
export function durationSeconds(token: DurationToken, unitless: DurationUnit): number {
|
||||
switch (token.unit ?? unitless) {
|
||||
case "ms":
|
||||
return token.value / 1000;
|
||||
case "m":
|
||||
return token.value * 60;
|
||||
case "h":
|
||||
return token.value * 3600;
|
||||
case "d":
|
||||
return token.value * 86400;
|
||||
case "s":
|
||||
default:
|
||||
return token.value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unitless `--expire` heuristic shared by the Seal and Hose link flags:
|
||||
* a bare number at most 168 reads as hours (7 days of them), a larger one
|
||||
* reads as seconds. Without this, `--expire 300` would mean 300 hours on one
|
||||
* path and 5 minutes on another.
|
||||
*/
|
||||
export function expireSeconds(token: DurationToken): number {
|
||||
return durationSeconds(token, token.value <= 168 ? "h" : "s");
|
||||
}
|
||||
|
||||
/** Default used by {@link parseDurationMs} when the literal is unreadable. */
|
||||
export const DEFAULT_DURATION_MS = 600_000;
|
||||
|
||||
/**
|
||||
* Simulation windows and poll intervals: milliseconds, unitless input read as
|
||||
* seconds, and an unreadable literal falls back to the default instead of
|
||||
* failing the call — a poll interval is not worth aborting a batch over.
|
||||
*/
|
||||
export function parseDurationMs(duration: string, fallbackMs = DEFAULT_DURATION_MS): number {
|
||||
const token = tokenizeDuration(duration);
|
||||
if (!token || token.value < 0) {
|
||||
return fallbackMs;
|
||||
}
|
||||
const milliseconds = Math.round(durationSeconds(token, "s") * 1000);
|
||||
return Number.isFinite(milliseconds) ? milliseconds : fallbackMs;
|
||||
}
|
||||
@@ -18,10 +18,12 @@ 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/report-templates.md" with { type: "text" };
|
||||
import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
|
||||
import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||
import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||
import file23 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 +38,12 @@ 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/report-templates.md": file19,
|
||||
"references/rule-lightweight.md": file20,
|
||||
"references/rule-lint.md": file21,
|
||||
"references/staging-simulation-workflow.md": file22,
|
||||
"references/webhook-resource-pack.md": file23,
|
||||
};
|
||||
|
||||
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
|
||||
@@ -70,6 +74,8 @@ 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/report-templates.md",
|
||||
"references/rule-lightweight.md",
|
||||
"references/rule-lint.md",
|
||||
"references/staging-simulation-workflow.md",
|
||||
|
||||
+3
-1
@@ -56,8 +56,10 @@ const USAGE_PREFIX =
|
||||
|
||||
// Wording a Chinese-language usage error uses when it names a flag/parameter
|
||||
// the caller must supply, or rejects a value the caller chose. Exit `13`.
|
||||
// Deliberately excludes generic recovery verbs like "请先"/"请重试" so post-write
|
||||
// or upstream failures that offer recovery advice stay at exit `1`.
|
||||
const CN_USAGE =
|
||||
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用|请提供|请重试|请先)/;
|
||||
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用 --|请提供)/;
|
||||
|
||||
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
|
||||
const CORP_SELECTION =
|
||||
|
||||
+9
-2
@@ -2,5 +2,12 @@ import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const SEAL_CONFIG_DIR = join(homedir(), ".config", "seal-use");
|
||||
export const PRIMARY_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters");
|
||||
export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, "official");
|
||||
export const SEAL_STATE_DIR = join(SEAL_CONFIG_DIR, "state");
|
||||
export const SEAL_CACHE_DIR = join(homedir(), ".cache", "seal-use");
|
||||
|
||||
/** 用户全局自定义校验器存放目录(属于用户资产,保留在 ~/.config/,防止随缓存被误删) */
|
||||
export const USER_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters");
|
||||
export const PRIMARY_LINTERS_DIR = USER_LINTERS_DIR;
|
||||
|
||||
/** 官方明文下发校验器目录(由 CLI 自动同步与重写,属于只读缓存,归位于 ~/.cache/) */
|
||||
export const OFFICIAL_LINTERS_DIR = join(SEAL_CACHE_DIR, "linters", "official");
|
||||
@@ -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);
|
||||
}
|
||||
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user