Compare commits

..
81 Commits
Author SHA1 Message Date
yunyingk c0af76f692 Merge pull request #232 from yunyingk/codex/release-v0.11.6
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.6: Automated release bump
2026-10-13 12:18:41 +08:00
gitea b2f72959ee Release v0.11.6: Automated release bump 2026-10-13 12:10:34 +08:00
yunyingk dd0ca78e5b Merge pull request #230 from yunyingk/mac15/rule-import-renumber
Organize Seal modules and add two-phase rule recoding
2026-10-13 11:51:02 +08:00
gitea 586ad521dc Harden post-write error codes, rules push recovery ledger, and capability param normalization 2026-10-13 11:48:37 +08:00
gitea 75017ab49c Merge remote-tracking branch 'origin/main' into mac15/rule-import-renumber 2026-10-13 11:30:28 +08:00
yunyingk 50414e100a Merge pull request #231 from yunyingk/mac15/venn-chart-4x
Upgrade report charts, organize reports domain, and export companion XLSX/CSV ledgers
2026-10-13 11:24:54 +08:00
gitea 4f3fb82856 Add companion XLSX/CSV report ledgers and unify reviewed accuracy metrics 2026-10-13 11:16:02 +08:00
gitea 8c7cb219a0 Organize Seal modules and add guarded rule recoding 2026-10-13 02:24:41 +00:00
gitea d71be55ec8 Refine report asset naming and include review notes in section 6 2026-10-13 10:16:49 +08:00
gitea 140d7bb33a Fix Venn chart dynamic rendering and eliminate EEKA mock data across report sections 2026-10-13 00:35:19 +08:00
gitea 9ef38cda0f Refine report pipeline data collection and rendering consistency 2026-10-12 23:18:28 +08:00
gitea 87b691bd4e Organize reports domain into cohesive submodules 2026-10-12 22:14:25 +08:00
gitea b3c8e93f0b Add native duration histogram chart and report export package 2026-10-12 22:02:52 +08:00
gitea c4a1148cbf Add 4x Venn chart renderer and report package export 2026-10-12 17:57:32 +08:00
yunyingk f788f9c6db Merge pull request #229 from yunyingk/mac15/generate-accuracy-venn-diagram
Add vector Venn diagram generator and upgrade accuracy chart
2026-10-12 17:25:19 +08:00
gitea 66673f3878 Add vector Venn diagram generator and upgrade accuracy chart 2026-10-12 17:23:38 +08:00
yunyingk d3659c076c Merge pull request #228 from yunyingk/mac15/sink-report-templates-to-domain
Consolidate report templates into reports domain and ignore reports
2026-10-12 16:49:19 +08:00
gitea 2e13b53351 Consolidate report templates into reports domain and ignore reports 2026-10-12 16:47:43 +08:00
yunyingk 59ef8c45db Merge pull request #227 from yunyingk/mac15/sync-docs-with-new-directory-layout
Update documentation and skills for new directory layout
2026-10-12 16:20:34 +08:00
gitea 7e8b9e6220 Update docs and skills for new directory layout 2026-10-12 16:19:26 +08:00
yunyingk 6a50512c4a Merge pull request #226 from yunyingk/mac15/streamline-directory-layout
Streamline directory layout and consolidate state and cache paths
2026-10-12 15:59:56 +08:00
gitea d3642b93d8 Streamline directory layout and consolidate state and cache paths 2026-10-12 15:58:28 +08:00
yunyingk 9cf3e8ce56 Merge pull request #225 from yunyingk/mac15/remove-legacy-report-python-scripts
Remove legacy report Python scripts and update documentation
2026-10-12 15:13:58 +08:00
gitea 90c366ebb2 Remove legacy report Python scripts and update documentation 2026-10-12 15:12:25 +08:00
yunyingk 736728496f Merge pull request #224 from yunyingk/mac15/ignore-tmp-sync-zcodeignore
Ignore tmp/ directory and sync .zcodeignore with .gitignore
2026-10-12 14:40:32 +08:00
gitea 904c9d4b8b Ignore tmp/ directory and sync .zcodeignore with .gitignore 2026-10-12 14:39:16 +08:00
yunyingk 0efd87a874 Merge pull request #223 from yunyingk/mac15/remove-report-python
Remove Python from report validation and rendering
2026-10-12 14:06:19 +08:00
gitea fb7948307c Remove Python from report validation and rendering 2026-10-12 14:02:44 +08:00
yunyingk c1a5cc20e9 Merge pull request #222 from yunyingk/mac15/remove-homebrew
Remove Homebrew integration and tap promotion
2026-10-12 13:18:49 +08:00
gitea 4bee160086 Remove Homebrew integration and tap promotion 2026-10-12 13:16:51 +08:00
yunyingk fc9e148764 Merge pull request #221 from yunyingk/mac15/fix-global-cli-resources
Fix global CLI resource paths and installation consistency
2026-10-12 12:32:44 +08:00
gitea fa304ca4dc Keep copied source packages out of parent Git repositories 2026-10-12 12:27:46 +08:00
gitea 2654e1b870 Fix global CLI resource paths and installation consistency 2026-10-12 12:17:38 +08:00
yunyingk 64af86ba9b Merge pull request #220 from yunyingk/mac15/bundle-report-workflow
Bundle report templates and integrate validation and rendering
2026-10-12 11:42:01 +08:00
gitea f726c22445 Bundle report templates and integrate validation and rendering 2026-10-12 11:38:19 +08:00
yunyingk c4df5ad325 Merge pull request #219 from yunyingk/mac15/fix-replay-matching-and-deploy-guards
Bound replay matching and confirm Hose deployment writes
2026-10-12 10:36:49 +08:00
gitea 22f4c87ecc Require confirmation and previews for Hose deployment 2026-10-12 10:33:45 +08:00
gitea fa2be3a4e9 Bound Hose replay log matching to explicit selectors 2026-10-12 10:33:45 +08:00
yunyingk 5a25cd5225 Merge pull request #218 from yunyingk/mac15/fix-outbound-review-findings
Fix outbound confirmation and consumption verification
2026-10-12 10:08:04 +08:00
gitea 67a461452c Fix outbound confirmation and verification safety 2026-10-12 00:13:22 +08:00
yunyingk b17bd09194 Merge pull request #217 from yunyingk/mac15/refactor-replay-dedup 2026-10-11 19:53:09 +08:00
gitea 0de2db14ae Close the re-export bypass in the helpers freeze ratchet
The declaration counter does not see `export { x } from "./y.js"` or
`export *`, so a re-export would re-publish helpers from this file's
namespace without touching either ceiling. Assert against that syntax.
2026-10-11 19:51:32 +08:00
gitea 19c8dd3146 Restore strict --expire units in the shared duration tokenizer
The shared tokenizer accepts `ms` for the simulation windows, and without a
per-caller unit set that grammar leaked into --expire: `--expire 500ms` was
a usage error before the parsers were unified and became silently rounded to
a 1h / 1s link after.

tokenizeDuration now takes an allowed-unit set; the expire flags pass
EXPIRE_UNITS (d/h/m/s) while parseDurationMs keeps the full set. Adds a
regression test asserting sub-second input stays exit 2 on both flags.
2026-10-11 19:51:29 +08:00
gitea 8c3d98fd98 Fix absent-SN record match and document --sign-key on replay
Two findings from reviewing the outbound-push extraction:

The verify poll compared `record.sourceDocumentSN === sn` with `sn` optional,
so a caller that only knows the flowId compared against `undefined` and
matched any record lacking an SN — reporting an unrelated run as the one this
push created, with its id and taskMode in the response. Guard the needle:
an absent SN matches nothing. This class did not exist on the deploy path
before (it compared against flowId only), so it was introduced by the merge.

The replay help text also never listed --sign-key even though the channel
resolves the target integration through it, and selectHoseIntegration now
errors on an ambiguous list with "请通过 --sign-key 指定" — pointing at a
flag the user could not discover from `help approval-runs`.

Adds direct tests for replay-safety.ts (the exit-14 wording, the next action,
and that --force is the only override), which previously had none.
2026-10-11 19:51:29 +08:00
gitea 9ece30255e Freeze capabilities/helpers.ts with a size ratchet
The file is the registry's catch-all (~85 exports over unrelated domains),
and index.ts re-exports all of it into every capability's namespace — which
is why helpers get re-derived rather than reused, and why unrelated work
keeps landing here.

A comment alone would not stop the next addition, so the ceiling is enforced
by test: helpers.freeze.test.ts fails when the file grows past its line or
export count, and the failure message names where the logic should go
instead. Both ceilings only ever drop — moving an export out to a focused
module is the intended change, followed by lowering the constant. Verified
by temporarily adding an export: both assertions fire.

Records the policy in .agents/rules/typescript-style.md as well, since the
ratchet explains what to do and the rule explains why.
2026-10-11 19:33:35 +08:00
gitea 8d7f930596 Split Langfuse flow heuristics out of the trace service
service.ts interleaved orchestration (cache-first trace access) with ~200
lines of flow heuristics — stage word tables, evidence collection, source
classification — and carried near-isomorphic copies of the collector for the
attachment and rule flows. None of it had tests.

flows.ts now owns the heuristics: one collectEvidence shared by both flows,
stage vocabulary as data tables so tuning a word list cannot alter a code
path, and an explicit attachment/rule difference (only the rule flow falls
back to scanning every observation when a stage has no named candidates).
summary.ts holds the trace/observation projections both the service and the
flows need, which also keeps service <-> flows acyclic.

Adds 15 tests over the previously untested branches, including the two
behaviors the extraction surfaced: the "unknown" classification arm is
unreachable as written, and a filename-only needle set can never reach the
OCR/inference grading.
2026-10-11 19:33:29 +08:00
gitea 6e3d4634f1 Unify duration parsing behind a core/duration tokenizer
The two --expire flags each carried a byte-identical copy of the same regex
and unit-conversion switch, and a third parser (parseDurationMs) lived in
capabilities/helpers.ts with yet another regex. Because the copies were
independent, --expire 300 could be read differently on each path without
anyone noticing.

core/duration.ts now owns the grammar (tokenizeDuration) and the unitless
heuristic (expireSeconds: a bare number <= 168 reads as hours, larger as
seconds). Each flag keeps only what genuinely differs: Seal delegation links
floor to whole hours and cap at 168h, Hose links round to seconds, simulation
windows are milliseconds and fall back instead of failing the batch.

Adds a cross-flag regression test asserting both --expire parsers read the
same literal the same way.
2026-10-11 19:33:25 +08:00
gitea df44791779 Add shared outbound-push module for Hose deploy and replay
The deploy capability and the cross-tenant replay each carried their own
copy of the same outbound pipeline: integration selection, the assisted-only
gate, payload/URL construction, and push-then-verify. A change to the wire
contract could drift into one path and not the other.

Move the shared parts into domains/seal/outbound-push.ts and return the raw
CloseAPI messageLog query to the hose domain (domains/hose/close/outbound.ts),
leaving only the replay-specific log matching on the seal side. The
production-target guard is now one implementation (replay-safety.ts) shared
by the corp-pair resolver and the channel validator; both call sites are
kept deliberately as defense in depth.

Behavior note: replay used to silently pick the first integration when the
target had several and no --sign-key was given. It now errors and lists the
available signKeys, matching what deploy already did — pushing a message to
the wrong outbound channel should not depend on array order.
2026-10-11 19:33:19 +08:00
yunyingk f4147cec58 Merge pull request #216 from yunyingk/codex/release-v0.11.5
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.5: Automated release bump
2026-10-10 16:04:38 +08:00
gitea aed3a10958 Release v0.11.5: Automated release bump 2026-10-10 16:03:41 +08:00
yunyingk 7af7be4925 Merge pull request #215 from yunyingk/mac15/hosecloud-test-outbound
Add Hose outbound replay with CloseAPI log matching and safety guards
2026-10-10 16:02:52 +08:00
gitea 152f96ec78 Update agent skill docs for Hose outbound replay and test-outbound 2026-10-10 16:01:27 +08:00
gitea 2fc88e208c Add Hose outbound replay with CloseAPI log matching and safety guards 2026-10-10 15:58:06 +08:00
yunyingk 042d223704 Merge pull request #214 from yunyingk/mac15/unify-expire-duration-parsing
Unify assistance link duration parsing with hour floor and stderr hints
2026-10-10 15:10:24 +08:00
gitea 0296c2bff2 Unify assistance link duration parsing with hour floor and stderr hints 2026-10-10 15:09:11 +08:00
yunyingk c094980ae5 Merge pull request #213 from yunyingk/mac15/support-delegation-expire-config
Add configurable expiration for Seal and Hose assistance links
2026-10-10 14:59:43 +08:00
gitea 932957ea08 Add configurable expiration for Seal and Hose assistance links 2026-10-10 14:58:30 +08:00
yunyingk f6cd2c68b0 Merge pull request #212 from yunyingk/codex/release-v0.11.4
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.4: Automated release bump
2026-10-10 11:58:40 +08:00
gitea 38e1a45fc2 Release v0.11.4: Automated release bump 2026-10-10 11:57:51 +08:00
yunyingk fa4113e828 Merge pull request #211 from yunyingk/mac15/diagnose-simulation-dx-improvements
Refine simulation DX, diagnose fields extraction, and test rule mapping
2026-10-10 11:55:53 +08:00
gitea 793fcff5d5 Refine simulation DX, diagnose fields extraction, and rule mapping 2026-10-10 11:54:44 +08:00
yunyingk 11780f7fe4 Merge pull request #210 from yunyingk/codex/release-v0.11.3
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.3: Automated release bump
2026-10-10 10:00:35 +08:00
gitea 4583dcc090 Release v0.11.3: Automated release bump 2026-10-10 09:59:44 +08:00
yunyingk d069e7232e Merge pull request #209 from yunyingk/mac15/langfuse-readonly-domain
Add built-in read-only Langfuse trace domain
2026-10-10 09:59:04 +08:00
gitea 45011c8333 Add built-in read-only Langfuse trace domain 2026-10-10 09:57:20 +08:00
yunyingk e2410e6923 Merge pull request #208 from yunyingk/mac15/corp-search-optimization
Split corp-search module and tune match ranking
2026-10-02 19:09:22 +08:00
gitea fb8a48ea3c Break search relevance ties by recent usage 2026-10-02 19:08:09 +08:00
gitea 0a71674c64 Split corp-search module and tune match scoring 2026-10-02 19:08:09 +08:00
yunyingk 3918e3de43 Merge pull request #207 from yunyingk/mac15/rename-corp-search-dir
Rename core search module to corp-search
2026-10-02 16:40:55 +08:00
gitea d4fb3828b7 Rename core search module to corp-search 2026-10-02 16:39:34 +08:00
yunyingk 2724ea5490 Merge pull request #206 from yunyingk/codex/release-v0.11.2
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.2: Automated release bump
2026-10-02 16:35:18 +08:00
gitea e542c0a5f2 Release v0.11.2: Automated release bump 2026-10-02 16:34:18 +08:00
yunyingk 8329b294e5 Merge pull request #205 from yunyingk/mac15/improve-corp-search
Improve corp search engine and add branch naming guard
2026-10-02 16:33:55 +08:00
gitea e72803ba3c Add device branch-prefix rule with hook enforcement 2026-10-02 16:32:39 +08:00
gitea e4b1eea5a9 Refactor fuzzy search engine into strategy functions 2026-10-02 16:32:39 +08:00
gitea 482ebf57b5 Improve Chinese enterprise search segmentation and ranking 2026-10-02 13:02:54 +08:00
yunyingk ada91c6c76 Merge pull request #204 from yunyingk/codex/release-v0.11.1
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.1: Automated release bump
2026-09-30 19:41:25 +08:00
gitea 686b397846 Release v0.11.1: Automated release bump 2026-09-30 19:40:22 +08:00
yunyingk e5644db726 Merge pull request #203 from yunyingk/codex/report-monthly-and-reviews
Add monthly audit report command and local human adjudication store
2026-09-30 19:39:52 +08:00
gitea d3c44e02d7 Add local human adjudication store that computes human review accuracy
The report previously could not compute human accuracy because upstream only
says whether AI and human agree, never who was right. This adds an append-only
local store so a reviewer judges each (typically diverged) document across
weekly passes, and report monthly folds those judgments back in.

- review-store.ts: JSONL per tenant+month (~/.config/seal-use/reviews/
  <corpId>-<YYYY-MM>.jsonl), append-only (weekly passes never rewrite), one
  record per SN; last write wins on re-adjudication. Verdicts: ai_correct,
  human_correct, both_correct, both_wrong, undecided. Env-overridable root
  (SEAL_USE_REVIEWS_DIR) for tests; corrupt lines skipped.
- collect.ts: load the store, join verdicts onto fetched blocks, compute
  humanAccuracy = (human_right / reviewed) * 100 over adjudicated samples,
  expose reviewedCount/divergedCount, and flip humanAccuracyAvailable. No
  reviews -> honest gap (still unavailable), never fabricated.
- render.ts: when available, fill the §1.2 human row with real accuracy and
  replace the gap warning with a coverage note; when not, keep the warning.
- CLI: `report review set/list --month ... [--sn --verdict --note
  --reviewed-by]` (set writes local store, list reads it). Help registers
  both as separate commands; read-only list vs mutating set classified
  accordingly. Prefix help (`report review --help`) now lists subcommands
  instead of erroring.
- parser: register --template/--report-id/--max-runs/--verdict/--reviewed-by
  (the first three were previously rejected as unknown, breaking report
  monthly's own flags); reviewed-by moves to VALUE_FLAGS so it consumes its
  argument.
- SKILL.md: document the adjudication workflow and storage semantics.

Verified: 639 tests (6 new review tests incl. tenant/month isolation, corrupt
line skip, join + accuracy math, honest no-review gap, render coverage note),
tsc clean, oxlint 0 warnings.
2026-09-30 18:59:26 +08:00
gitea 2ee15bb0d6 Add one-shot monthly audit report command (report monthly)
Eats in the ai-audit-report-template as a module. The template is the mutable
skin: describeTemplate() infers per-section data demands from ##/### headings
(keyword rules), so editing/renaming/reordering sections does not require
touching collect or render code.

- src/domains/seal/reports/: describe (heading to demand), collect (performance/
  risk blocks/template groups, fetched only for declared demands), render (fills
  tables by section+column signature, rewrites narrative by structure not line
  number), monthly (orchestrator returning content + per-section completeness +
  notes).
- report-templates/: the template body, assets, example, and downstream
  validate.py/render.py (not bundled; next.validate/render in the result point
  at them).
- Capability sealReportMonthlyGet (read-only, allow-listed) + CLI
  "seal-use report monthly --month <YYYY-MM>" + help + KNOWN_FLAGS month +
  read-only report:monthly.
- SKILL.md: routing row + a section stating the two hard rules: the template is
  swappable, and metrics with no upstream source keep template sample values
  with a warning note instead of fabricated numbers.

Template-path resolution branches on isCompiledBinary() (dev: module-relative to
repo root; compiled: cwd), matching how rules lint --file resolves paths, since
templates are not embedded.

Verified: bun test 633 pass (6 new reports tests), tsc clean, oxlint 0 warnings.
Live smoke: 2026-08 report for a real corp fills real accuracy/counts/distribution
and marks human-accuracy + mismatch-classification + section-6 sample rows with
gap notes.
2026-09-30 17:55:37 +08:00
209 changed files with 14682 additions and 1617 deletions

No files matched your search

+32
View File
@@ -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`。
+17
View File
@@ -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.
+38
View File
@@ -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
}
+6
View File
@@ -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)"
+12
View File
@@ -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)
+9 -1
View File
@@ -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.
+8
View File
@@ -8,9 +8,17 @@ dist/bin/
.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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.0",
"version": "0.11.6",
"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
View File
@@ -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/
+9 -4
View File
@@ -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
+61
View File
@@ -7,6 +7,67 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [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
- Merge pull request #203 from yunyingk/codex/report-monthly-and-reviews
- Add local human adjudication store that computes human review accuracy
- Add one-shot monthly audit report command (report monthly)
## [0.11.0] - 2026-09-30
### Added
+10 -6
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.0",
"version": "0.11.6",
"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",
+51 -2
View File
@@ -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
View File
@@ -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
View File
@@ -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);
});
}
+9
View File
@@ -27,6 +27,15 @@ const files = walk(skillRoot).map((fullPath) => ({
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
}));
// The skill's report reference is owned by the repository too; install it without maintaining a second copy.
const reportReadme = resolve(root, "src", "domains", "seal", "reports", "templates", "README.md");
files.push({
fullPath: reportReadme,
relativePath: "references/report-templates.md",
importPath: relative(resolve(root, "src", "core"), reportReadme).split("\\").join("/"),
kind: "text"
});
const lines = [
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
""
+1 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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");
}
+63 -4
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.0: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.6: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.0
short-description: Seal tenant and Hose approval automation (v0.11.0)
version: 0.11.6
short-description: Seal tenant and Hose approval automation (v0.11.6)
---
# 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,11 +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 | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `references/report-templates.md` |
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
@@ -110,3 +120,52 @@ seal-use approval-runs diagnose --sn <单号> --corp <corpId>
```
一次返回单据摘要、AI 判定结果、引用规则、判定当时的规则版本快照(含被引规则的快照内容)与 Langfuse trace 指针;需要完整 result 原文加 `--full`,需要按 recordId 定位则直接传 `<recordId>`。只有诊断结果不够、需要更细颗粒时,再拆用 `pick` / `get --summary` / `cited-rules` / `rules version`。
## Langfuse trace 内置只读检索
Langfuse 后台信息内建在 CLI 里(`seal-use langfuse`,凭据编译期注入、零配置、只读、无需 `--corp` 和 `langfuse-home`):
```bash
seal-use langfuse cache-refresh <traceId> # 先缓存(一次拉全)
seal-use langfuse outline <traceId> --include-io-preview # 大纲:观测树/体量/用量/成本
seal-use langfuse search <traceId> --query "关键词1,关键词2" # 单 trace 关键词检索(qrep)
seal-use langfuse observation <traceId> <observationId> # 最后才取焦点 IO
```
`approval-runs diagnose` / `bridge` 返回的 `bridge[].next` 就是下一步可执行命令。`seal-use langfuse check` 可自检内置密钥是否失效(失效 → exit 11/1 的结构化报错,绝不崩溃;已缓存 trace 仍可离线读取)。session、attachment-flow、rule-flow、缓存语义与失效兜底见 `references/langfuse-trace.md`。
## 月度审核准确率报告
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
```bash
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
seal-use report validate reports/报告.md
seal-use report render reports/报告.md --out build/报告
```
按模板结构(内置 `monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- 默认模板、配图和校验/渲染引擎由仓库 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` 并替换配图。
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
### 人工裁决回填(算出人工审核准确率)
上游只给 AI 与人工结论是否同向(`agreement`),**谁对必须人来判**。判断结果按 SN 本地持久化,跨周累积到月底,`report monthly` 据此回填 §1.2 人工审核准确率与覆盖度说明:
```bash
# 录入一条裁决(本地 JSONL,无需网络;通常裁决 AI≠人工 的分歧单)
seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <说明>] [--reviewed-by <裁决人>] --corp <corpId>
# 查看已录入的裁决
seal-use report review list --month <YYYY-MM> --corp <corpId>
```
- **存储**:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
@@ -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
+33 -7
View File
@@ -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`。
@@ -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.
+3 -3
View File
@@ -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
View File
@@ -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 -1
View File
@@ -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";
+2 -2
View File
@@ -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";
+153
View File
@@ -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
View File
@@ -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 ||
+9 -3
View File
@@ -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 } });
}
+26
View File
@@ -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 });
+6
View File
@@ -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 -1
View File
@@ -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,
+9 -3
View File
@@ -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) {
+16 -6
View File
@@ -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(未实际推送)。`);
+170
View File
@@ -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
View File
@@ -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.`);
}
+171
View File
@@ -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>;
}
+133
View File
@@ -0,0 +1,133 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapabilityResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import { CliError, usageError } from "../../core/errors.js";
import {
exportReportPackage,
renderReportFile,
saveReportMarkdown,
validateReportFile,
loadReviews,
reviewFilePath,
writeReview,
type MonthlyReportResult
} from "../../domains/seal/reports/index.js";
import type { ParsedArgs } from "../types.js";
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
export async function handleLocalReportCommand(action: "validate" | "render" | "export", args: ParsedArgs) {
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` — 月度 AI 审核准确率报告(Markdown 填充)。 */
export async function handleReportCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "monthly" || action === "month") {
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
}
const result = await runCapabilityResult(
"sealReportMonthlyGet",
client,
corp,
{
month,
templatePath: stringOption(args.options.template),
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
}
) 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;
}
if (action === "review") {
const sub = args.command[2]; // set | list
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report review <set|list> --month <YYYY-MM> [--sn <SN> --verdict <v>] [--corp <corpId>]");
}
if (sub === "list") {
const reviews = loadReviews(corp.id, month);
printJson({
corpId: corp.id,
month,
file: reviewFilePath(corp.id, month),
count: reviews.size,
reviews: [...reviews.values()]
});
return;
}
if (sub === "set") {
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
const verdict = stringOption(args.options.verdict);
if (!sn || !verdict) {
throw new Error(
"Usage: seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
);
}
const record = writeReview(corp.id, {
sn,
month,
verdict,
note: stringOption(args.options.note),
reviewedBy: stringOption(args.options["reviewed-by"]) ?? stringOption(args.options.reviewedBy)
});
printJson({ corpId: corp.id, file: reviewFilePath(corp.id, month), record });
return;
}
throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
}
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
}
+103
View File
@@ -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
View File
@@ -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(
+21 -1
View File
@@ -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 -1
View File
@@ -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) {
+53 -28
View File
@@ -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
View File
@@ -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;
+11 -3
View File
@@ -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;
}
+119 -1
View File
@@ -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);
}
});
});
+42 -2
View File
@@ -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) {
+5 -1
View File
@@ -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 });
});
});
+8
View File
@@ -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");
+251 -20
View File
@@ -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,24 +592,108 @@ 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" }
]
}
]
},
{
area: "report",
title: "Monthly audit accuracy reports",
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
commands: [
{
name: "monthly",
aliases: ["month"],
summary: "Fill the monthly report template with performance, risk, and approval-run data",
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to 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)" }
],
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",
usage: ["seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" },
{ flag: "--sn <SN>", description: "Document SN to adjudicate (required)" },
{ flag: "--verdict <v>", description: "ai_correct | human_correct | both_correct | both_wrong | undecided (required)" },
{ flag: "--note <text>", description: "Optional adjudication note" },
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
],
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/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",
summary: "List human adjudications recorded for a tenant+month",
usage: ["seal-use report review list --month <YYYY-MM> [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" }
],
description: "Reads the local JSONL store and returns all adjudications keyed by SN."
}
]
},
{
area: "simulation",
title: "Simulation testing engine",
@@ -612,9 +706,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>]"
]
@@ -698,13 +792,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" }
]
}
]
},
@@ -793,11 +908,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:
@@ -817,9 +933,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:
@@ -870,7 +986,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",
@@ -1128,6 +1248,111 @@ export const HELP_REGISTRY: AreaHelp[] = [
}
]
},
{
area: "langfuse",
title: "Langfuse trace inspection (read-only)",
description:
"Inspect Langfuse traces/sessions with the built-in read-only credentials: cache once, then outline → search → observation IO. No tenant or user config required.",
commands: [
{
name: "check",
summary: "Check connectivity of the built-in Langfuse read-only credentials",
usage: ["seal-use langfuse check"]
},
{
name: "cache-refresh",
summary: "Fetch one full trace into the local cache for offline inspection",
usage: ["seal-use langfuse cache-refresh <traceId> [--trace-id <traceId>]"],
options: [{ flag: "--trace-id <id>", description: "Trace id when not given as a positional" }]
},
{
name: "outline",
summary: "Read a compact observation tree with sizes, usage, cost, and optional IO previews",
usage: ["seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]"],
options: [
{ flag: "--include-io-preview", description: "Include short input/output previews on the trace and observations" },
{ flag: "--max-preview-chars <n>", description: "Preview length per field, 20-5000 (default 160)" },
{ flag: "--full", description: "Return full IO instead of previews (large output)" },
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
]
},
{
name: "search",
summary: "Ranked keyword search inside one cached trace (qrep)",
usage: ["seal-use langfuse search <traceId> --query <term1,term2> [--fields input,output] [--max-results <n>]"],
options: [
{ flag: "--query <terms>", description: "Comma-separated terms; earliest best match wins per field" },
{ flag: "--fields <fields>", description: "Comma-separated fields: name,input,output,metadata,userId,sessionId" },
{ flag: "--observation-types <types>", description: "Comma-separated observation type filter (e.g. GENERATION,SPAN)" },
{ flag: "--metadata <json>", description: "Exact metadata filter as a JSON object" },
{ flag: "--max-results <n>", description: "Maximum ranked results, 1-30 (default 10)" },
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 120)" },
{ flag: "--session-id <id>", description: "Only match when the trace belongs to this session" },
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
]
},
{
name: "observation",
summary: "Read focused input/output/metadata of one observation",
usage: ["seal-use langfuse observation <traceId> <observationId> [--fields input,output] [--max-chars <n>]"],
options: [
{ flag: "--fields <fields>", description: "Comma-separated fields to read: input,output,metadata (default input,output)" },
{ flag: "--max-chars <n>", description: "Per-field character cap, 100-30000 (default 8000)" },
{ flag: "--json-path <path>", description: "Read one nested value, e.g. items[0].name" },
{ flag: "--full", description: "Raise the cap to 500000 chars (large output)" },
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
]
},
{
name: "session",
summary: "Read a compact session outline with trace summaries",
usage: ["seal-use langfuse session <sessionId> [--trace-limit <n>]"],
options: [{ flag: "--trace-limit <n>", description: "Maximum traces to summarize, 1-200 (default 50)" }]
},
{
name: "observations",
summary: "Filter cached observations by name/type/metadata without loading IO",
usage: ["seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>]"],
options: [
{ flag: "--name-contains <text>", description: "Substring match on observation name" },
{ flag: "--type <type>", description: "Exact observation type filter" },
{ flag: "--metadata-key <key>", description: "Only observations whose metadata has this key" },
{ flag: "--has-input", description: "Only observations with non-empty input" },
{ flag: "--has-output", description: "Only observations with non-empty output" },
{ flag: "--max-results <n>", description: "Maximum summaries, 1-200 (default 50)" },
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
]
},
{
name: "url",
summary: "Build the Langfuse UI deep link for one trace",
usage: ["seal-use langfuse url <traceId>"]
},
{
name: "attachment-flow",
summary: "Trace text evidence of a file id/name through attachment and review stages",
usage: ["seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>]"],
options: [
{ flag: "--file-id <id>", description: "File id to look for (at least one hint required)" },
{ flag: "--file-name <name>", description: "File name to look for (at least one hint required)" },
{ flag: "--content-hints <hints>", description: "Comma-separated extra content hints" },
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 120)" },
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
]
},
{
name: "rule-flow",
summary: "Trace text evidence of one rule through matching, parsing, and review stages",
usage: ["seal-use langfuse rule-flow <traceId> --rule <规则内容>"],
options: [
{ flag: "--rule <text>", description: "Rule text to trace (required)" },
{ flag: "--rule-hints <hints>", description: "Comma-separated extra rule hints" },
{ flag: "--context-chars <n>", description: "Context around each match, 20-500 (default 300)" },
{ flag: "--refresh-if-missing", description: "Fetch the trace when it is not cached yet" }
]
}
]
},
{
area: "mcp",
title: "Model Context Protocol (MCP) server",
@@ -1276,6 +1501,12 @@ export function renderHelp(target: string[] = []): string {
const matchedCommand = findCommandInArea(areaEntry, actionPath, rest);
if (!matchedCommand) {
// 前缀命令(如 `report review` 覆盖 `review set`/`review list`):列出该组子命令而非报错
const groupPrefix = `${actionPath} `;
const subcommands = areaEntry.commands.filter((cmd) => cmd.name?.startsWith(groupPrefix));
if (subcommands.length > 0) {
return renderAreaHelp({ ...areaEntry, commands: subcommands });
}
throw usageError(`Unknown ${areaEntry.area} command: ${rest.join(" ")}. Run 'seal-use ${areaEntry.area} --help' for available commands.`);
}
+47 -3
View File
@@ -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);
}
+83
View File
@@ -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", () => {
+153 -37
View File
@@ -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";
/**
@@ -26,14 +27,14 @@ export const BOOLEAN_FLAGS = new Set([
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "help",
"hose", "hose-sso", "hoseSso", "include-deleted", "include-simulation", "include-unchanged",
"exclude-deleted", "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"
]);
@@ -41,39 +42,46 @@ export const BOOLEAN_FLAGS = new Set([
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
"code", "concurrency", "content", "content-file", "content-type", "contentFile",
"contentType", "contextLines", "corp", "corp-id", "corpId", "date",
"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",
"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", "humanResult", "id", "input", "integration",
"json", "key-id", "keyId", "keyword", "level", "limit",
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
"n", "name", "note", "o", "offset", "out",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"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",
"staffName", "staffPhone", "start", "start-date", "start-time", "startDate",
"startTime", "state", "status", "strictness", "tag", "tag-id",
"tagId", "tags", "target", "target-corp", "targetCorp", "task-mode",
"template",
"taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth",
"timeout", "timezone", "title", "to", "token", "tokenId",
"trace-id", "trace-limit",
"type", "until", "url", "userId", "version-name", "versionName",
"webhook", "workflow-type-id", "workflowTypeId"
"verdict",
"webhook", "width", "workflow-type-id", "workflowTypeId"
]);
// Registered flags. Unknown flags are rejected.
@@ -81,50 +89,56 @@ export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "add", "all", "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", "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", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"key-id", "keyId", "keyword", "level", "limit", "lines",
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
"note", "o", "offset", "out", "out-dir", "outDir",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"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",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId",
"reviewed-by", "reviewedBy",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
"selector", "sign-key", "signKey", "silent", "silent-save", "simulation",
"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",
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
"startDate", "startTime", "state", "status", "strict", "strictness",
"summary", "tag", "tag-id", "tagId", "tags", "target",
"template",
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
"to", "to-downloads", "toDownloads", "token", "tokenId", "type",
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
"until", "url", "userId", "v", "version", "version-name",
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
"verdict",
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
"workspace", "yes"
]);
@@ -155,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;
}
@@ -423,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;
}
+34 -7
View File
@@ -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 -2
View File
@@ -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,9 +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", "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: [""]
@@ -112,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.
@@ -122,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;
+20
View File
@@ -53,6 +53,7 @@ export const KNOWN_AREAS = new Set([
"rules",
"approval-runs",
"analytics",
"report",
"simulation",
"deploy",
"preference",
@@ -63,6 +64,7 @@ export const KNOWN_AREAS = new Set([
"skill",
"probe",
"doctor",
"langfuse",
"changelog",
"test"
]);
@@ -222,6 +224,19 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "report" && (action === "validate" || action === "render" || action === "export")) {
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;
@@ -386,6 +401,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "report") {
await (await import("./commands/report.js")).handleReportCommand(action, client, corp, args);
return;
}
if (area === "simulation") {
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
return;
+4 -4
View File
@@ -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;
}
+112
View File
@@ -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
};
}
+30
View File
@@ -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);
});
});
});
+72
View File
@@ -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;
}
+90
View File
@@ -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);
});
});
+178
View File
@@ -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()
);
}
+140
View File
@@ -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);
}
});
}
});
+24
View File
@@ -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("谢子豪"));
});
});
+41
View File
@@ -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;
}
+156
View File
@@ -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"]);
});
});
+54
View File
@@ -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);
}
+61
View File
@@ -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;
});
}
+54
View File
@@ -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();
}
+34
View File
@@ -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;
}
+43
View File
@@ -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 });
}
});
});
+8 -4
View File
@@ -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: {
+14 -6
View File
@@ -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"
+79
View File
@@ -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);
});
});
+145
View File
@@ -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;
}
+14 -8
View File
@@ -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/rule-lightweight.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file23 from "../domains/seal/reports/templates/README.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/rule-lightweight.md": file19,
"references/rule-lint.md": file20,
"references/staging-simulation-workflow.md": file21,
"references/webhook-resource-pack.md": file22,
"references/report-templates.md": file23,
};
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
@@ -70,8 +74,10 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/hose-enterprise-auth.md",
"references/hose-enterprise-deploy.md",
"references/hose-enterprise-init.md",
"references/langfuse-trace.md",
"references/rule-lightweight.md",
"references/rule-lint.md",
"references/staging-simulation-workflow.md",
"references/webhook-resource-pack.md",
"references/report-templates.md",
];
+3 -1
View File
@@ -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
View File
@@ -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");
+1
View File
@@ -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"
-242
View File
@@ -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([]);
});
});
});
-400
View File
@@ -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);
}
+4 -3
View File
@@ -1,9 +1,10 @@
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { SEAL_CACHE_DIR } from "../paths.js";
export const USAGE_FILE_ENV = "SEAL_USE_USAGE_FILE";
const DEFAULT_USAGE_FILE = join(homedir(), ".config", "seal-use", "usage.json");
const DEFAULT_USAGE_FILE = join(SEAL_CACHE_DIR, "usage.json");
const DEFAULT_WINDOW_DAYS = 7;
export type CorpUsageDailyStats = Record<string, number>;
@@ -66,7 +67,7 @@ function saveUsageStatsAtomic(stats: CorpUsageStats, targetPath: string = resolv
}
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`;
try {
// 0o600 like `sealTokens.json`: usage rows name the enterprises this machine has been
// 0o600 like `tokens.json`: usage rows name the enterprises this machine has been
// operating, so keep them owner-only instead of inheriting the 0o644 default.
writeFileSync(tempPath, JSON.stringify(stats, null, 2), { encoding: "utf-8", mode: 0o600 });
renameSync(tempPath, targetPath);
+3 -2
View File
@@ -1,14 +1,15 @@
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { spawn } from "node:child_process";
import type { LauncherConfig } from "./runtime.js";
import { formatBeijingIso, normalizeBeijingIso } from "./config/timestamps.js";
import { SEAL_CACHE_DIR } from "./paths.js";
export const UPDATE_CACHE_FILE_ENV = "SEAL_USE_UPDATE_CACHE_FILE";
export const DEFAULT_UPDATE_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
const DEFAULT_UPDATE_CACHE_FILE = join(homedir(), ".config", "seal-use", "update-cache.json");
const DEFAULT_UPDATE_CACHE_FILE = join(SEAL_CACHE_DIR, "update-cache.json");
export interface UpdateCacheData {
checkedAt: string;
+10
View File
@@ -12,3 +12,13 @@ declare module "*.yml" {
const content: string;
export default content;
}
declare module "*.css" {
const content: string;
export default content;
}
declare module "*.svg" {
const content: string;
export default content;
}
+1 -1
View File
@@ -6,7 +6,7 @@ import {
} from "../../core/auth/delegate.js";
import { parseHoseAssistLink } from "../../core/auth/hose.js";
import { onboardHoseWebSession } from "../hose/onboarding.js";
import { persistSealDelegateSession } from "../seal/onboarding.js";
import { persistSealDelegateSession } from "../seal/enterprise/onboarding.js";
export type AssistanceLinkOnboardingInput = {
name?: string;
+1
View File
@@ -1,3 +1,4 @@
export * from "./types.js";
export * from "./client.js";
export * from "./api.js";
export * from "./outbound.js";
+80
View File
@@ -0,0 +1,80 @@
import type { KyInstance } from "ky";
import { validationError } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { createHoseCloseClient } from "./client.js";
/**
* A single row of the CloseAPI outbound message log. The `request` payload is
* the EBot push body, so its fields mirror Seal's `/api/hosecloud/outbound`
* contract (flowId / nodeId / messageId / rejectionNum / corporationId).
*/
export interface HoseOutboundLogItem {
id: string;
name: string;
type: "INVOKING" | "CALLBACK" | string;
state: string;
flowId?: {
id: string;
form?: {
code?: string;
};
};
nodeName?: string;
createTime: number;
messageType?: string;
request?: {
flowId?: string;
nodeId?: string;
messageId?: string;
rejectionNum?: number;
corporationId?: string;
action?: string;
comment?: string;
signKey?: string;
[key: string]: unknown;
};
response?: unknown;
}
/**
* Query CloseAPI's outbound message log for one document SN (flowId.form.code).
*/
export async function searchOutboundMessageLogs(
client: KyInstance,
corpId: string,
sn: string
): Promise<HoseOutboundLogItem[]> {
const response = (await client
.post("api/outbound/v1/message/messageLog", {
searchParams: {
messageType: "flow",
corpId
},
json: {
limit: { start: 0, count: 20 },
orderBy: [{ value: "createTime", order: "DESC" }],
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType",
filterBy: `(flowId.form.code==("${sn}"))`
}
})
.json()) as { items?: HoseOutboundLogItem[] };
return response.items ?? [];
}
/**
* Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN.
*/
export async function fetchHoseOutboundLogs(
sourceCorp: CorpConfig,
sn: string
): Promise<HoseOutboundLogItem[]> {
if (sourceCorp.source.type !== "hose") {
throw validationError(
`源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。`
);
}
const client = await createHoseCloseClient(sourceCorp);
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn);
}
+1 -1
View File
@@ -13,7 +13,7 @@ import { saveCorpConfig, type SavedCorpConfig } from "../../core/config/reposito
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { getMe } from "../seal/api.js";
import { resolveLiveSealEnterpriseConfig } from "../seal/source.js";
import { resolveLiveSealEnterpriseConfig } from "../seal/enterprise/source.js";
export type HosePersistentInput = {
id?: string;
+30
View File
@@ -0,0 +1,30 @@
import type { LangfuseClient } from "./client.js";
import type { LangfuseProject, LangfuseSession, LangfuseTraceSummary } from "./types.js";
/**
* Langfuse Public API surface used by this domain. Deliberately tiny: every
* method maps to a single `GET`, mirroring the read-only client contract.
*/
export class LangfuseApi {
constructor(private readonly client: LangfuseClient) {}
async getProject(): Promise<LangfuseProject[]> {
const response = await this.client.getJson<{ data?: LangfuseProject[] }>(
"/api/public/projects"
);
return response.data ?? [];
}
async getTrace(traceId: string, params: { fields?: string } = {}): Promise<LangfuseTraceSummary> {
return await this.client.getJson<LangfuseTraceSummary>(
`/api/public/traces/${encodeURIComponent(traceId)}`,
{ fields: params.fields }
);
}
async getSession(sessionId: string): Promise<LangfuseSession> {
return await this.client.getJson<LangfuseSession>(
`/api/public/sessions/${encodeURIComponent(sessionId)}`
);
}
}
+80
View File
@@ -0,0 +1,80 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DEFAULT_LANGFUSE_CACHE_DIR, LANGFUSE_CACHE_DIR_ENV, TraceCache } from "./cache.js";
import type { CachedTrace } from "./types.js";
const project = { baseUrl: "https://langfuse.test", projectId: "test-project" };
const originalCwd = process.cwd();
const originalCacheDir = process.env[LANGFUSE_CACHE_DIR_ENV];
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-trace-cache-test-"));
process.env[LANGFUSE_CACHE_DIR_ENV] = join(dir, "user-cache");
});
afterEach(() => {
process.chdir(originalCwd);
if (originalCacheDir === undefined) delete process.env[LANGFUSE_CACHE_DIR_ENV];
else process.env[LANGFUSE_CACHE_DIR_ENV] = originalCacheDir;
rmSync(dir, { recursive: true, force: true });
});
function legacyEntry(overrides: Record<string, unknown> = {}): string {
const cached: CachedTrace = {
cacheVersion: 1, cachedAt: "2026-10-01T00:00:00Z",
project: { key: "default", ...project }, trace: { id: "trace", projectId: project.projectId, observations: [] }
};
const file = join(dir, ".cache", "langfuse", "traces", "default", "trace.json");
mkdirSync(join(dir, ".cache", "langfuse", "traces", "default"), { recursive: true });
writeFileSync(file, JSON.stringify({ ...cached, ...overrides }));
process.chdir(dir);
return file;
}
describe("portable Langfuse cache", () => {
test("the default path is independent of cwd without writing to the real user's cache", () => {
delete process.env[LANGFUSE_CACHE_DIR_ENV];
const first = new TraceCache(project).path("trace");
process.chdir(dir);
const second = new TraceCache(project).path("trace");
expect(first).toBe(join(DEFAULT_LANGFUSE_CACHE_DIR, "default", "trace.json"));
expect(second).toBe(first);
});
test("a newly created service can read a trace after changing directories", async () => {
const first = new TraceCache(project);
await first.write("trace", { id: "trace", projectId: project.projectId, observations: [] });
const elsewhere = join(dir, "elsewhere");
mkdirSync(elsewhere);
process.chdir(elsewhere);
const second = new TraceCache(project);
expect(second.path("trace")).toBe(first.path("trace"));
expect((await second.read("trace"))?.trace.id).toBe("trace");
expect(statSync(first.path("trace")).mode & 0o777).toBe(0o600);
});
test("legacy cache is copied once with its timestamp and original file retained", async () => {
const legacy = legacyEntry();
const original = readFileSync(legacy, "utf8");
const imported = await new TraceCache(project).read("trace");
expect(imported?.cachedAt).toBe("2026-10-01T00:00:00Z");
expect(readFileSync(legacy, "utf8")).toBe(original);
process.chdir(originalCwd);
expect(await new TraceCache(project).read("trace")).toEqual(imported);
});
test("a different project's legacy trace is not imported", async () => {
legacyEntry({ project: { key: "default", baseUrl: project.baseUrl, projectId: "other-project" } });
const cache = new TraceCache(project);
expect(await cache.read("trace")).toBeUndefined();
expect(existsSync(cache.path("trace"))).toBe(false);
});
test("wrong trace IDs and unsupported cache versions are not accepted", async () => {
for (const entry of [{ cacheVersion: 2 }, { trace: { id: "another-trace", projectId: project.projectId } }]) {
legacyEntry(entry);
expect(await new TraceCache(project).read("trace")).toBeUndefined();
}
});
});
+103
View File
@@ -0,0 +1,103 @@
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import type { CachedTrace, LangfuseTraceSummary } from "./types.js";
const CACHE_VERSION = 1;
const LEGACY_CACHE_ROOT = ".cache/langfuse/traces";
export const LANGFUSE_CACHE_DIR_ENV = "SEAL_USE_LANGFUSE_CACHE_DIR";
export const DEFAULT_LANGFUSE_CACHE_DIR = join(homedir(), ".cache", "seal-use", "langfuse", "traces");
// Single-project domain: the cache segment stays "default", which keeps this
// cache byte-compatible with `langfuse-home`, so old cwd-relative entries can
// be imported without re-fetching or removing their original files.
const PROJECT_SEGMENT = "default";
export type TraceCacheProject = {
baseUrl: string;
projectId?: string;
};
/**
* Single-trace JSON cache keyed by traceId, written under the user's cache
* directory. Holds the FULL raw trace (including observation IO) so outline,
* search, observation and flow tools can answer without touching the network.
* No TTL: `cache-refresh` overwrites explicitly.
*/
export class TraceCache {
private readonly root: string;
constructor(private readonly project: TraceCacheProject) {
this.root = resolve(process.env[LANGFUSE_CACHE_DIR_ENV]?.trim() || DEFAULT_LANGFUSE_CACHE_DIR);
}
path(traceId: string): string {
return resolve(
this.root,
PROJECT_SEGMENT,
`${sanitizeSegment(traceId)}.json`
);
}
async exists(traceId: string): Promise<boolean> {
try {
await stat(this.path(traceId));
return true;
} catch {
return false;
}
}
async read(traceId: string): Promise<CachedTrace | undefined> {
const cached = await this.readEntry(this.path(traceId), traceId);
if (cached) return cached;
const legacyPath = resolve(process.cwd(), LEGACY_CACHE_ROOT, PROJECT_SEGMENT, `${sanitizeSegment(traceId)}.json`);
if (legacyPath === this.path(traceId)) return undefined;
const legacy = await this.readEntry(legacyPath, traceId);
if (!legacy) return undefined;
// Preserve cachedAt and the original legacy entry; only copy a matching project's trace.
await this.persist(traceId, legacy);
return legacy;
}
private async readEntry(path: string, traceId: string): Promise<CachedTrace | undefined> {
try {
const content = await readFile(path, "utf8");
const parsed = JSON.parse(content) as CachedTrace;
if (parsed.cacheVersion !== CACHE_VERSION || parsed.trace?.id !== traceId) return undefined;
if (parsed.project?.baseUrl?.replace(/\/+$/, "") !== this.project.baseUrl.replace(/\/+$/, "")) return undefined;
if (this.project.projectId && parsed.project.projectId !== this.project.projectId) return undefined;
return parsed;
} catch {
return undefined;
}
}
async write(traceId: string, trace: LangfuseTraceSummary): Promise<CachedTrace> {
const cached: CachedTrace = {
cacheVersion: CACHE_VERSION,
cachedAt: new Date().toISOString(),
project: {
key: PROJECT_SEGMENT,
projectId: trace.projectId ?? this.project.projectId ?? "",
baseUrl: this.project.baseUrl
},
trace
};
await this.persist(traceId, cached);
return cached;
}
private async persist(traceId: string, cached: CachedTrace): Promise<void> {
const path = this.path(traceId);
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
const temp = `${path}.${randomUUID()}.tmp`;
await writeFile(temp, `${JSON.stringify(cached, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
await rename(temp, path);
}
}
function sanitizeSegment(value: string): string {
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
}
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, test } from "bun:test";
import {
LANGFUSE_READ_ONLY_CAPABILITIES,
findLangfuseCapability,
langfuseCapabilities
} from "./capabilities.js";
describe("langfuse capability registry", () => {
test("every capability is classified read-only, exhaustively and without overlap", () => {
const names = langfuseCapabilities.map((capability) => capability.name);
expect(new Set(names).size).toBe(names.length);
expect([...LANGFUSE_READ_ONLY_CAPABILITIES].sort()).toEqual(names.slice().sort());
});
test("every capability carries a description and a parameter schema", () => {
for (const capability of langfuseCapabilities) {
expect({ name: capability.name, described: capability.description.length > 0 }).toEqual({
name: capability.name,
described: true
});
expect(typeof capability.handler).toBe("function");
expect(capability.parameters.safeParse({}).success).toBeTypeOf("boolean");
}
});
test("unknown capability names resolve to undefined", () => {
expect(findLangfuseCapability("sealLangfuseDoesNotExist")).toBeUndefined();
});
test("required params gate before any handler runs", () => {
expect(findLangfuseCapability("sealLangfuseTraceCacheRefresh")!.parameters.safeParse({}).success).toBe(false);
expect(
findLangfuseCapability("sealLangfuseTraceCacheRefresh")!.parameters.safeParse({ traceId: "t-1" }).success
).toBe(true);
expect(findLangfuseCapability("sealLangfuseTraceRuleFlowGet")!.parameters.safeParse({ traceId: "t-1" }).success).toBe(
false
);
});
test("ranges and refinements reject out-of-contract values", () => {
const outline = findLangfuseCapability("sealLangfuseTraceOutlineGet")!.parameters;
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 10 }).success).toBe(false);
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 100 }).success).toBe(true);
expect(outline.safeParse({ traceId: "t-1", maxPreviewChars: 9_999 }).success).toBe(false);
const search = findLangfuseCapability("sealLangfuseTraceQrepSearch")!.parameters;
expect(search.safeParse({ traceId: "t-1", query: "发票" }).success).toBe(true);
expect(search.safeParse({ traceId: "t-1", maxResults: 0 }).success).toBe(false);
expect(search.safeParse({ traceId: "t-1", query: ["a"], fields: ["bogus"] }).success).toBe(false);
const attachment = findLangfuseCapability("sealLangfuseAttachmentFlowGet")!.parameters;
expect(attachment.safeParse({ traceId: "t-1" }).success).toBe(false);
expect(attachment.safeParse({ traceId: "t-1", fileName: "a.pdf" }).success).toBe(true);
});
});
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more