Compare commits

..
76 Commits
Author SHA1 Message Date
yunyingk 480f833580 Merge pull request #236 from yunyingk/codex/release-v0.11.8
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.8: Automated release bump
2026-10-15 16:52:22 +08:00
gitea b21beba419 Release v0.11.8: Automated release bump 2026-10-15 16:51:01 +08:00
yunyingk 97d1c47a6c Merge pull request #235 from yunyingk/mac15/streamline-general-report-template
Streamline monthly report template and enhance validator
2026-10-15 16:50:12 +08:00
gitea f6fe0de286 Add pkg/report standalone external validation suite and example report 2026-10-15 16:47:26 +08:00
gitea f9f72fa918 Decouple chapter numbers from validation and pipeline rendering to allow arbitrary chapter order 2026-10-15 16:39:33 +08:00
gitea a52b6ac117 Standardize report tables on clean 2-column format with clickable SN 2026-10-15 16:29:28 +08:00
gitea f8ac839840 Document user-centric dynamic adaptability principle in agent skill 2026-10-15 16:20:01 +08:00
gitea 7df5feb7b7 Add automated audit link column and reconcile divergence metrics 2026-10-15 16:06:29 +08:00
gitea 16f3f252c0 Align Hose document URL with backlogDetail hash routing 2026-10-15 15:36:26 +08:00
gitea 25d1036eed Refine approval run URL resolution with Hose fallback and SSO 2026-10-15 15:27:14 +08:00
gitea 0210051ab7 Implement pre-flight adjudication gate and companion ledger cross-validation 2026-10-15 15:17:44 +08:00
gitea 5573dfb60e Codify dual-link fast traversal standard into report authoring skill 2026-10-15 15:08:24 +08:00
gitea 1fb61f794e Fix report sample count and decision distribution for scoped runs 2026-10-15 14:53:25 +08:00
gitea 7d15f3834d Update report skill reference for streamlined 6-section workflow 2026-10-15 14:46:37 +08:00
gitea aad591569a Streamline monthly report template and enhance validator 2026-10-15 14:30:59 +08:00
yunyingk 7304578bc7 Merge pull request #234 from yunyingk/codex/release-v0.11.7
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.7: Automated release bump
2026-10-13 17:34:14 +08:00
gitea 16a673c910 Release v0.11.7: Automated release bump 2026-10-13 17:32:50 +08:00
yunyingk ce1f1f3ca1 Merge pull request #233 from yunyingk/mac15/monthly-report-reference
Add lightweight report data capability and authoring reference
2026-10-13 17:28:28 +08:00
gitea 2177a06f39 Add lightweight report data capability and authoring reference 2026-10-13 17:22:02 +08:00
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
189 changed files with 11631 additions and 2786 deletions

No files matched your search

+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.
+1 -1
View File
@@ -118,5 +118,5 @@ jobs:
path: dist/bin/
retention-days: 1
# Gitea asset promotion and Homebrew tap updates are owned by the WSL
# Gitea asset promotion is owned by the WSL
# seal-use-release-sync.timer after this GitHub Release is published.
+3
View File
@@ -3,14 +3,17 @@ node_modules/
# Build outputs
dist/bin/
build/
# Local runtime caches and system noise (regenerate at any time)
.cache/
.mimosa/
.apifox/
tmp/
# Local runtime state (rule snapshots, bridge, reports) — never committed
.local/
/reports/
# Developer-only build-time credentials for compile-time injection — never committed
.env.langfuse
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.4",
"version": "0.11.8",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+18 -17
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/
+4 -2
View File
@@ -6,6 +6,8 @@ This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP
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
@@ -102,7 +104,7 @@ 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
+45
View File
@@ -7,6 +7,51 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.8] - 2026-10-15
### Added
- Merge pull request #235 from yunyingk/mac15/streamline-general-report-template
- Add pkg/report standalone external validation suite and example report
- Decouple chapter numbers from validation and pipeline rendering to allow arbitrary chapter order
- Standardize report tables on clean 2-column format with clickable SN
- Document user-centric dynamic adaptability principle in agent skill
- Add automated audit link column and reconcile divergence metrics
- Align Hose document URL with backlogDetail hash routing
- Refine approval run URL resolution with Hose fallback and SSO
## [0.11.7] - 2026-10-13
### Added
- Merge pull request #233 from yunyingk/mac15/monthly-report-reference
- Add lightweight report data capability and authoring reference
## [0.11.6] - 2026-10-13
### Added
- Merge pull request #230 from yunyingk/mac15/rule-import-renumber
- Harden post-write error codes, rules push recovery ledger, and capability param normalization
- Merge remote-tracking branch 'origin/main' into mac15/rule-import-renumber
- Merge pull request #231 from yunyingk/mac15/venn-chart-4x
- Add companion XLSX/CSV report ledgers and unify reviewed accuracy metrics
- Organize Seal modules and add guarded rule recoding
- Refine report asset naming and include review notes in section 6
- Fix Venn chart dynamic rendering and eliminate EEKA mock data across report sections
## [0.11.5] - 2026-10-10
### Added
- Merge pull request #215 from yunyingk/mac15/hosecloud-test-outbound
- Update agent skill docs for Hose outbound replay and test-outbound
- Add Hose outbound replay with CloseAPI log matching and safety guards
- Merge pull request #214 from yunyingk/mac15/unify-expire-duration-parsing
- Unify assistance link duration parsing with hour floor and stderr hints
- Merge pull request #213 from yunyingk/mac15/support-delegation-expire-config
- Add configurable expiration for Seal and Hose assistance links
## [0.11.4] - 2026-10-10
### Added
+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`).
+4 -3
View File
@@ -17,10 +17,10 @@ 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
@@ -41,7 +41,8 @@ than described here.
full API access, so "read-only" is guaranteed only by this client (it exposes `GET` only — see
`src/domains/langfuse/client.ts`), and anyone with the binary can extract the key pair. The
repository and its Releases are private, which is what bounds distribution. Treat Langfuse traces
and `.cache/langfuse/` as sensitive (they can contain enterprise approval data); rotate the key
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
+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.4",
"version": "0.11.8",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
@@ -43,7 +43,9 @@
"exceljs": "^4.4.0",
"iconv-lite": "^0.7.3",
"ky": "^2.0.2",
"marked": "15.0.12",
"pinyin-pro": "^3.29.3",
"pngjs": "7.0.0",
"yauzl": "^3.4.0",
"zod": "^4.4.3"
},
@@ -51,6 +53,7 @@
"@modelcontextprotocol/client": "^2.0.0",
"@types/archiver": "^8.0.0",
"@types/bun": "^1.3.14",
"@types/pngjs": "6.0.5",
"@types/yauzl": "^3.4.0",
"bun-types": "^1.3.14",
"oxlint": "1.86.0",
+190
View File
@@ -0,0 +1,190 @@
# 【模板企业】8月AI审核准确率报告
| 报告信息 | 内容 |
| --- | --- |
| 报告编号 | RPT-202608-A3F8C2 |
| 客户名称 | 模板企业 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
| 报告状态 | 草稿 |
| 生成日期 | 2026-09-23 |
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
---
## 1. 审核测试结果
### 1.1 数据来源与范围
| 项目 | 内容 |
| --- | --- |
| 数据来源 | 客户授权的已完成历史审批单据 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
### 1.2 核心准确率结论
基于已经给定的规则库:
| 审核方式 | 准确率 |
| --- | --- |
| AI 审核 | **92.08%** |
| 人工审核 | **83.33%** |
AI 审核准确率的计算方式:
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
![AI 与人工审核准确率对比](assets/图1-准确率对比.svg)
*图 1 · AI 与人工审核准确率对比*
---
## 2. AI 失准分析(学习优化空间)
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
### 2.1 失准构成总览
| 维度 | 失准类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
| 合计 | — | 100% | 19 张 |
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
**解决方案**:严格校准规则触发后动作,按规则执行。
| 单号 | 问题描述 |
| --- | --- |
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
*(节选 3 例,全量 9 张)*
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
| 单号 | 问题描述 |
| --- | --- |
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
*(节选 3 例,全量 5 张)*
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
| 单号 | 问题描述 |
| --- | --- |
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
*(节选 3 例,全量 5 张)*
---
## 3. AI 发现的潜在风险
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
### 3.1 风险构成总览
| 维度 | 风险类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
| 合计 | — | 100% | 40 张 |
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
| 单号 | 问题描述 |
| --- | --- |
| FP260011 | 改衣费未附改衣明细表 |
| FP260012 | 咨询费报销资料不全 |
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
*(节选 3 例,全量 23 张)*
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
| 单号 | 问题描述 |
| --- | --- |
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
*(节选 3 例,全量 9 张)*
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
| 单号 | 问题描述 |
| --- | --- |
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
*(节选 3 条,全量 8 张)*
---
## 4. 综合效益
| 维度 | 结论 | 关键数据 |
| --- | --- | --- |
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
---
## 5. 审核分歧与复核归因
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
| 原因分类 | 占比 | 单数 | 核心说明 |
| --- | --- | --- | --- |
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
| 合计 | 100% | 3 张 | — |
**分歧分析与后续建议**:
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
---
## 6. 支撑数据与交付材料
### 6.1 分模板准确率与自动审批率
全量 N = 240:
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
| --- | --- | --- | --- | --- | --- |
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
*(其余 10 类模板从略,实际报告列出全量 16 类)*
### 6.2 跑批原始数据与交付台账
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
+120
View File
@@ -0,0 +1,120 @@
# AI 审核报告(Markdown)独立编制与校验套件
本套件是面向**外部交付、客户协作与第三方审核团队**的独立版 AI 审核报告验证工具包。
---
## 一、核心定位与特点
1. **零环境依赖**:基于纯 Python 标准库编写(Python 3.8+),无需安装 `seal-use`,无需 Node.js / Bun,跨平台(macOS / Linux / Windows)开箱即用。
2. **纯粹面向 Markdown**:专注于 Markdown 报告文档本身的格式纯净度、结构严密性与数学总账守恒;**不强求本地 Excel 伴生台账**,**无需手动填写任何技术跳转链接**。
3. **核心章节硬匹配,自定义章节完全放行**:核心论证章节按大标题名称硬匹配认领;中间任意插入的部门专项分析、整改排期等章节,校验器一律视为纯叙述业务章节,不施加任何教条规则,直接绿色放行!
---
## 二、目录结构
```text
pkg/report/
├── README.md # 本使用指南与规范手册
├── validate.py # 独立离线校验脚本(纯标准库)
├── example-report.md # 100% 格式合规的标准示例月报
└── assets/ # 示例配图资产
└── 图1-准确率对比.svg
```
---
## 三、快速上手
### 1. 快速校验一份 Markdown 报告
```bash
# 进入本目录
cd pkg/report
# 执行校验
python3 validate.py example-report.md
```
**校验通过输出示例**:
```text
✅ 报告文件: /path/to/example-report.md
📊 识别表格: 14 个 | 配图资产: 1 个
🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。
```
### 2. 输出机器可读的 JSON 结构(方便接入 CI/CD 或自动化流水线)
```bash
python3 validate.py example-report.md --json
```
---
## 四、报告大纲与编写原则
一份合格的 AI 审核商业月度报告,遵循**“骨架刚性、血肉自适应”**的设计理念:
### 1. 核心必选骨架(通过大标题名称硬匹配)
无论章节编号是第几章,系统只要匹配到大标题名称,就会认领对应的业务校验:
| 核心大标题名称 | 核心作用与定位 | 必须遵守的业务守恒 |
| :--- | :--- | :--- |
| **开篇「报告信息」表** | 抬头身份证明 | 必含 5 字段:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
| **`审核测试结果`** | 核心业绩表态 | 包含样本总量、AI/人工准确率结论、LaTeX 准确率公式(`\frac{A}{B} = C\%`)及对比图。 |
| **`AI 失准分析`** | 坦白 AI 误判与偏差 | 包含失准构成总览表、TOP 1~N 典型案例表格与针对性调优解决方案。 |
| **`AI 发现的潜在风险`** | 力证风控拦截价值 | 包含潜在风险总览表、TOP 1~N 凭证缺失、比价缺失、超期等真实拦截案例。 |
| **`综合效益`** | 总结人效与风控收益 | 时效、准确度、风险拦截笔数宏观总结表(纯内部对账时可按需裁剪)。 |
| **`审核分歧与复核归因`** | 人机分歧深度定性 | 分类统计表(线上规则未覆盖 vs 模型偏差)与口头管控标准线上化管理建议。 |
| **`支撑数据与交付材料`** | 分模板细分数据 | 分模板准确率与自动化率汇总表,说明底层流水交付物。 |
### 2. 中间随意插入的自定义章节(完全自由放行)
如果针对具体企业的特定管理需要,想在报告中间插入业务专属章节(例如在第 1 章后插入 `## 2. 营销大区差旅合规专项穿透`):
* **系统处理方式**:大标题名称不在核心名单里的章节,校验器一律视为**纯叙述业务章节**;
* **自由度**:不限制表格列数、不限制行数、不强制要求数学守恒,写什么内容都直接放行!
* **唯一要求**:大章节使用 `##`,章节编号从 1 开始自然连续递增(1, 2, 3, 4, 5...),子小节使用 `###` 且不跳级。
### 3. 表格案例与链接约定
* 案例表格推荐使用纯净紧凑的 **2 列规范**(`| 单号 | 问题描述 |`);
* 编写 Markdown 时**无需手动查询或粘贴长串后台技术 URL**,专注于业务事实描述即可。
---
## 五、校验规则与错误代码速查表
`validate.py` 内部内置了以下质量红线校验门禁。如果报告校验未通过,终端会指出具体问题行号与代码:
| 错误代码 | 校验类别 | 规则说明与修复指南 |
| :--- | :--- | :--- |
| **`FM001`** | 格式纯净 | 严禁以 YAML Frontmatter(`---`)开头;元数据请写在正文开头的「报告信息」表中。 |
| **`MK001`** | 格式纯净 | 严禁残留模板草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等)。 |
| **`MD001`** | 格式规范 | 代码围栏(反引号 ```)必须成对闭合,不可出现单数个。 |
| **`TB001`** | 表格对齐 | 每行数据单元格按 `\|` 拆分后的列数,必须严格等于表头列数。 |
| **`TB002`** | 表格规范 | 表头文字必须保持纯文本,禁止包含 `**` 加粗符号。 |
| **`HD001`** | 标题层级 | 禁止跳级(如 `#` 一级标题直接跳到 `###` 三级标题)。 |
| **`HD002`** | 标题序号 | 二级大章节编号(`## \d+\.`)必须从 1 开始连续递增,不得跳号。 |
| **`INFO001`** | 头部元数据 | 开篇「报告信息」表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。 |
| **`INFO002`** | 头部元数据 | 开篇「报告信息」表的 5 项元数据值均不能为空白。 |
| **`IMG001`** | 资产存活 | 文档中引用的本地相对路径图片(如 `.svg` / `.png`)在磁盘必须真实存在。 |
| **`NM001`** | 数学守恒 | 【失准分析】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
| **`NM002`** | 数学守恒 | 【潜在风险】总览表中 TOP 1~N 单数之和必须等于合计行;且各小节标题单数必须与总览表一致。 |
| **`NM003`** | 数学守恒 | 分类总览表中声明的占比百分比与 `单数 / 合计` 计算误差不得超过 0.15%。 |
| **`NM004`** | 数学守恒 | 【分歧归因】分类表各原因单数相加必须等于分歧总数,且与正文叙述一致。 |
| **`NM005`** | 数学守恒 | LaTeX 公式 `\frac{A}{B} = C\%` 算术必须成立,且公式中的数字在正文中有数据来源。 |
---
## 六、常见问题解答 (FAQ)
**Q:编写报告时,出现失准或风险分类不是 3 种怎么办?**
A:完全自由!如果有 2 种就列 TOP 1~2,有 4 种就列 TOP 1~4,只要总览表中这几项的单数加起来等于合计行、百分比加起来等于 100% 即可通过校验。
**Q:案例表格必须放 3 行吗?**
A:不需要。可放 1 行典型单据,也可放 5 行全量单据,表格行数完全由业务深度决定。
**Q:为什么提示公式算术不成立(`NM005`)?**
A:请检查 LaTeX 公式中的分子除以分母计算出的百分比,与等号右边的数值是否一致(如 $221 / 240 = 92.0833\% \approx 92.08\%$,如果写成 95% 则会被拦截)。
@@ -0,0 +1,51 @@
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="400" viewBox="0 0 960 400" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif">
<defs>
<!-- 精确交集透镜裁剪路径 -->
<clipPath id="left-circle-clip">
<circle cx="410" cy="160" r="135"/>
</clipPath>
</defs>
<rect width="960" height="400" fill="#ffffff"/>
<!-- Left Circle: Pastel Blue -->
<circle cx="410" cy="160" r="135" fill="#b9deff"/>
<!-- Right Circle: Pastel Mint -->
<circle cx="550" cy="160" r="135" fill="#d2ede8"/>
<!-- Distinct Intersection Lens: Perfect blend tone (#9ed4eb) -->
<circle cx="550" cy="160" r="135" clip-path="url(#left-circle-clip)" fill="#9ed4eb"/>
<!-- Left Text Block (Horizontally centered lines) -->
<g text-anchor="middle" fill="#111111">
<text x="140" y="146" font-size="18"><tspan letter-spacing="1.5px">AI</tspan><tspan letter-spacing="0px">审核准确</tspan></text>
<text x="140" y="176" font-size="18">(总准确率92.08%)</text>
</g>
<!-- Left dashed line: comfortable gap from text, extends into circle -->
<line x1="245" y1="160" x2="310" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
<!-- Left percentage -->
<text x="348" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">16.66%</text>
<!-- Overlap percentage (in intersection lens) -->
<text x="480" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">75.42%</text>
<!-- Right percentage -->
<text x="612" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">7.91%</text>
<!-- Right dashed line -->
<line x1="650" y1="160" x2="715" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
<!-- Right Text Block (Horizontally centered lines) -->
<g text-anchor="middle" fill="#111111">
<text x="820" y="146" font-size="18">人工审核准确</text>
<text x="820" y="176" font-size="18">(总准确率83.33%)</text>
</g>
<!-- Bottom vertical dashed pointer -->
<line x1="480" y1="215" x2="480" y2="305" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
<!-- Bottom label: refined kerning on AI and comfortable character spacing -->
<text x="480" y="338" font-size="18" fill="#111111" text-anchor="middle" dominant-baseline="central"><tspan letter-spacing="2px">AI</tspan><tspan letter-spacing="1px">与人工都准确</tspan></text>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+190
View File
@@ -0,0 +1,190 @@
# 【模板企业】8月AI审核准确率报告
| 报告信息 | 内容 |
| --- | --- |
| 报告编号 | RPT-202608-A3F8C2 |
| 客户名称 | 模板企业 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
| 报告状态 | 草稿 |
| 生成日期 | 2026-09-23 |
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
---
## 1. 审核测试结果
### 1.1 数据来源与范围
| 项目 | 内容 |
| --- | --- |
| 数据来源 | 客户授权的已完成历史审批单据 |
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
### 1.2 核心准确率结论
基于已经给定的规则库:
| 审核方式 | 准确率 |
| --- | --- |
| AI 审核 | **92.08%** |
| 人工审核 | **83.33%** |
AI 审核准确率的计算方式:
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
![AI 与人工审核准确率对比](assets/图1-准确率对比.svg)
*图 1 · AI 与人工审核准确率对比*
---
## 2. AI 失准分析(学习优化空间)
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
### 2.1 失准构成总览
| 维度 | 失准类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
| 合计 | — | 100% | 19 张 |
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
**解决方案**:严格校准规则触发后动作,按规则执行。
| 单号 | 问题描述 |
| --- | --- |
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
*(节选 3 例,全量 9 张)*
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
| 单号 | 问题描述 |
| --- | --- |
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
*(节选 3 例,全量 5 张)*
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
| 单号 | 问题描述 |
| --- | --- |
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
*(节选 3 例,全量 5 张)*
---
## 3. AI 发现的潜在风险
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
### 3.1 风险构成总览
| 维度 | 风险类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
| 合计 | — | 100% | 40 张 |
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
| 单号 | 问题描述 |
| --- | --- |
| FP260011 | 改衣费未附改衣明细表 |
| FP260012 | 咨询费报销资料不全 |
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
*(节选 3 例,全量 23 张)*
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
| 单号 | 问题描述 |
| --- | --- |
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
*(节选 3 例,全量 9 张)*
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
| 单号 | 问题描述 |
| --- | --- |
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
*(节选 3 条,全量 8 张)*
---
## 4. 综合效益
| 维度 | 结论 | 关键数据 |
| --- | --- | --- |
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
---
## 5. 审核分歧与复核归因
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
| 原因分类 | 占比 | 单数 | 核心说明 |
| --- | --- | --- | --- |
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
| 合计 | 100% | 3 张 | — |
**分歧分析与后续建议**:
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
---
## 6. 支撑数据与交付材料
### 6.1 分模板准确率与自动审批率
全量 N = 240:
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
| --- | --- | --- | --- | --- | --- |
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
*(其余 10 类模板从略,实际报告列出全量 16 类)*
### 6.2 跑批原始数据与交付台账
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
+375
View File
@@ -0,0 +1,375 @@
#!/usr/bin/env python3
"""
AI 审核报告(Markdown)独立校验器
Independent Markdown Validator for AI Audit Reports
特点:
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台(macOS / Linux / Windows)
- 专为外部协同与客户交付设计:不依赖 seal-use、不强求本地 Excel 伴生台账
- 核心章节硬匹配大标题名称:中间任意插入的自定义章节完全自由放行
- 严格守护格式合规与数学总账守恒
用法:
python3 validate.py <report.md>
python3 validate.py <report.md> --json
"""
import os
import sys
import re
import json
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
REQUIRED_INFO_ROWS = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
FORBIDDEN_MARKS = [
(re.compile(r"<!--slot:"), "slot 标记"),
(re.compile(r"<!--/slot"), "slot 闭合"),
(re.compile(r"<!--@"), "@table/@block 区域标记"),
(re.compile(r"<!-- render:stop"), "render:stop 标记"),
(re.compile(r"\{\{"), "{{槽位}}"),
]
class ReportIssue:
def __init__(self, level: str, code: str, message: str, line: Optional[int] = None):
self.level = level # "ERROR" | "WARN"
self.code = code
self.message = message
self.line = line
def to_dict(self) -> Dict[str, Any]:
d: Dict[str, Any] = {"level": self.level, "code": self.code, "message": self.message}
if self.line is not None:
d["line"] = self.line
return d
class TableRow:
def __init__(self, line_num: int, cells: List[str]):
self.line_num = line_num
self.cells = cells
class ParsedTable:
def __init__(self, line_num: int, header: List[str], rows: List[TableRow]):
self.line_num = line_num
self.header = header
self.rows = rows
def split_cells(line: str) -> List[str]:
text = line.strip()
if text.startswith("|"):
text = text[1:]
if text.endswith("|") and not text.endswith(r"\|"):
text = text[:-1]
# Split on unescaped pipe
raw_cells = re.split(r"(?<!\\)\|", text)
return [c.replace(r"\|", "|").strip() for c in raw_cells]
def parse_tables(lines: List[str]) -> List[ParsedTable]:
result: List[ParsedTable] = []
i = 0
while i < len(lines):
line = lines[i].strip()
if i + 1 < len(lines):
separator = lines[i + 1].strip()
if line.startswith("|") and "-" in separator and re.match(r"^[|\-: ]+$", separator):
header = split_cells(line)
table = ParsedTable(line_num=i + 1, header=header, rows=[])
i += 2
while i < len(lines) and lines[i].strip().startswith("|"):
table.rows.append(TableRow(line_num=i + 1, cells=split_cells(lines[i])))
i += 1
result.append(table)
continue
i += 1
return result
def extract_numeric(text: str, is_percent: bool = False) -> Optional[float]:
pattern = r"(\d+(?:\.\d+)?)\s*%" if is_percent else r"(\d+(?:\.\d+)?)"
m = re.search(pattern, text)
if m:
try:
return float(m.group(1))
except ValueError:
return None
return None
def validate_report(filepath: str) -> Dict[str, Any]:
path = Path(filepath).resolve()
if not path.is_file():
return {
"file": str(path),
"valid": False,
"tables": 0,
"figures": 0,
"issues": [{"level": "ERROR", "code": "FS001", "message": f"文件不存在: {filepath}"}],
}
with open(path, "r", encoding="utf-8") as f:
text = f.read().replace("\r\n", "\n").replace("\r", "\n")
lines = text.split("\n")
issues: List[ReportIssue] = []
def add_error(code: str, message: str, line: Optional[int] = None):
issues.append(ReportIssue(level="ERROR", code=code, message=message, line=line))
# 1. 纯净性:严禁 Frontmatter 和 模板草稿占位标记
if text.startswith("---\n"):
add_error("FM001", "文件以 YAML frontmatter 开头;元数据请放正文开头的「报告信息」表格中", line=1)
for pattern, name in FORBIDDEN_MARKS:
for idx, l in enumerate(lines, start=1):
if pattern.search(l):
add_error("MK001", f"出现模板未渲染痕迹({name}),交付文件应为纯 Markdown 文档", line=idx)
# 2. 代码围栏成对闭合
fences = [idx for idx, l in enumerate(lines, start=1) if l.strip().startswith("```")]
if len(fences) % 2 != 0:
add_error("MD001", f"代码围栏为奇数(共 {len(fences)} 个),存在未闭合代码块", line=fences[-1] if fences else None)
# 3. 表格结构规范(列对齐、表头无加粗)
parsed_tables = parse_tables(lines)
for table in parsed_tables:
header_len = len(table.header)
for row in table.rows:
if len(row.cells) != header_len:
add_error("TB001", f"第 {row.line_num} 行表格列数 {len(row.cells)} ≠ 表头 {header_len} 列", line=row.line_num)
for cell in table.header:
if "**" in cell:
add_error("TB002", f"第 {table.line_num} 行表头含有加粗标记 **(表头应保持纯文本)", line=table.line_num)
# 4. 标题层级与章节序号连续性
previous_level = 0
numbered_h2s: List[Tuple[int, str, int]] = [] # (chapter_num, full_heading, line_num)
chapters: List[Dict[str, Any]] = []
for idx, l in enumerate(lines, start=1):
m = re.match(r"^(#{1,6})\s+(.*)$", l)
if not m:
continue
level = len(m.group(1))
heading_text = m.group(2).strip()
if previous_level > 0 and level > previous_level + 1:
add_error("HD001", f"标题层级跳级(从 H{previous_level} 直接跳到 H{level}):{heading_text[:40]}", line=idx)
previous_level = level
if level == 2:
num_match = re.match(r"^(\d+)\.", heading_text)
if num_match:
numbered_h2s.append((int(num_match.group(1)), heading_text, idx))
chapters.append({"heading": heading_text, "start_line": idx, "line_num": idx})
# 检查大标题数字是否严格连续递增:1, 2, 3...
if numbered_h2s:
seen_nums = [item[0] for item in numbered_h2s]
expected_nums = list(range(1, len(seen_nums) + 1))
if seen_nums != expected_nums:
add_error("HD002", f"## 大章节编号应自 1 开始连续递增,期望 {expected_nums},实际 {seen_nums}", line=numbered_h2s[0][2])
# 为每个大章节划分文本切片(从当前 ## 到下一个 ##)
for i, chap in enumerate(chapters):
start_idx = chap["start_line"] - 1
end_idx = chapters[i + 1]["start_line"] - 1 if i + 1 < len(chapters) else len(lines)
chap["text"] = "\n".join(lines[start_idx:end_idx])
def find_chapter_by_keyword(kw: str) -> Optional[Dict[str, Any]]:
for c in chapters:
if kw in c["heading"]:
return c
return None
def by_header_in_scope(keyword: str, scope_lines: Optional[List[str]] = None) -> Optional[ParsedTable]:
target_tables = parse_tables(scope_lines) if scope_lines is not None else parsed_tables
for t in target_tables:
header_str = "".join(t.header).replace(" ", "")
if keyword in header_str:
return t
return None
# 5. 开篇「报告信息」表完备性
info_table = by_header_in_scope("报告信息")
if not info_table:
add_error("INFO001", "缺少开篇「报告信息」表(必须包含客户名称、期间、报告编号等元数据)")
else:
existing_keys = {r.cells[0] for r in info_table.rows if r.cells}
missing_keys = [k for k in REQUIRED_INFO_ROWS if k not in existing_keys]
if missing_keys:
add_error("INFO001", f"「报告信息」表缺少必要字段:{', '.join(missing_keys)}", line=info_table.line_num)
empty_keys = [r.cells[0] for r in info_table.rows if len(r.cells) > 1 and not r.cells[1].strip()]
if empty_keys:
add_error("INFO002", f"「报告信息」表以下字段值为空:{', '.join(empty_keys)}", line=info_table.line_num)
# 6. 本地图片资产存活性
figure_count = 0
for idx, l in enumerate(lines, start=1):
for img_match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", l):
figure_count += 1
src = img_match.group(1).strip()
if src.startswith("http://") or src.startswith("https://") or src.startswith("data:"):
continue
# 解码 URL 编码的中文路径
try:
import urllib.parse
decoded_src = urllib.parse.unquote(src)
except Exception:
decoded_src = src
target_path = (path.parent / decoded_src).resolve()
if not target_path.exists():
add_error("IMG001", f"本地引用的图片文件不存在:{src}", line=idx)
# 7. 核心业务章节硬匹配校验与数学总账守恒
# 7.1 【AI 失准分析】核心章节
mismatch_chapter = find_chapter_by_keyword("失准")
if mismatch_chapter:
c_lines = mismatch_chapter["text"].split("\n")
table = by_header_in_scope("失准类型", c_lines)
if table:
tops = []
totals = []
for r in table.rows:
if len(r.cells) > 3:
if r.cells[0].startswith("TOP"):
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
elif r.cells[0] in ["合计", "总计", "—"]:
totals.append(extract_numeric(r.cells[3]))
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
s = sum(t["count"] for t in tops if t["count"] is not None)
if s != totals[0]:
add_error("NM001", f"失准类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
base = totals[0]
for r in table.rows:
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
share = extract_numeric(r.cells[2], is_percent=True)
count = extract_numeric(r.cells[3])
if share is not None and count is not None and base > 0:
calc_share = (count / base) * 100
if abs(calc_share - share) > 0.15:
add_error("NM003", f"失准类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
# 校验小节标题张数与总览表严格一致
for top in tops:
esc = re.escape(top["name"])
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", mismatch_chapter["text"])
if m and top["count"] is not None:
c_in_h = int(m.group(1))
if c_in_h != int(top["count"]):
add_error("NM001", f"失准分析 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
# 7.2 【AI 发现的潜在风险】核心章节
risk_chapter = find_chapter_by_keyword("风险")
if risk_chapter:
c_lines = risk_chapter["text"].split("\n")
table = by_header_in_scope("风险类型", c_lines)
if table:
tops = []
totals = []
for r in table.rows:
if len(r.cells) > 3:
if r.cells[0].startswith("TOP"):
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
elif r.cells[0] in ["合计", "总计", "—"]:
totals.append(extract_numeric(r.cells[3]))
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
s = sum(t["count"] for t in tops if t["count"] is not None)
if s != totals[0]:
add_error("NM002", f"风险类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
base = totals[0]
for r in table.rows:
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
share = extract_numeric(r.cells[2], is_percent=True)
count = extract_numeric(r.cells[3])
if share is not None and count is not None and base > 0:
calc_share = (count / base) * 100
if abs(calc_share - share) > 0.15:
add_error("NM003", f"风险类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
for top in tops:
esc = re.escape(top["name"])
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", risk_chapter["text"])
if m and top["count"] is not None:
c_in_h = int(m.group(1))
if c_in_h != int(top["count"]):
add_error("NM002", f"潜在风险 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
# 7.3 【审核分歧与复核归因】核心章节
diverged_chapter = find_chapter_by_keyword("分歧") or find_chapter_by_keyword("复核归因")
if diverged_chapter:
c_lines = diverged_chapter["text"].split("\n")
table = by_header_in_scope("原因分类", c_lines)
if table:
count_idx = -1
for ci, col in enumerate(table.header):
if "单数" in col:
count_idx = ci
break
if count_idx >= 0:
rows = [r.cells for r in table.rows]
non_totals = [r for r in rows if r and r[0] not in ["合计", "总计", "—"]]
total_row = next((r for r in rows if r and r[0] in ["合计", "总计", "—"]), None)
s = sum(extract_numeric(r[count_idx]) or 0 for r in non_totals if len(r) > count_idx)
if total_row and len(total_row) > count_idx:
tv = extract_numeric(total_row[count_idx])
if tv is not None and s != tv:
add_error("NM004", f"原因分类各维度单数之和 {s} ≠ 合计 {tv}", line=table.line_num)
# 7.4 LaTeX 公式算术自洽
formula_lines = [l for l in lines if l.strip().startswith("$$")]
outside_text = "\n".join([l for l in lines if not l.strip().startswith("$$")])
for fl in formula_lines:
for frac_match in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", fl):
a = int(frac_match.group(1))
b = int(frac_match.group(2))
pct_val = float(frac_match.group(3))
if b > 0:
real_pct = (a / b) * 100
if abs(real_pct - pct_val) > 0.05:
add_error("NM005", f"公式 \\frac{{{a}}}{{{b}}} = {pct_val}% 算术不成立(实为 {real_pct:.2f}%)")
for num_token in re.findall(r"\d+(?:\.\d+)?", fl):
if num_token not in outside_text:
add_error("NM005", f"公式中的数值 {num_token} 在正文别处找不到,可能与实际数据脱节")
return {
"file": str(path),
"valid": len(issues) == 0,
"tables": len(parsed_tables),
"figures": figure_count,
"issues": [i.to_dict() for i in issues],
}
def main():
if len(sys.argv) < 2 or sys.argv[1] in ["-h", "--help"]:
print("用法: python3 validate.py <report.md> [--json]")
print("说明: 离线静态校验 AI 审核报告 Markdown 文档的结构纯净度与数学总账守恒。")
sys.exit(0)
target_file = sys.argv[1]
is_json = "--json" in sys.argv
result = validate_report(target_file)
if is_json:
print(json.dumps(result, ensure_ascii=False, indent=2))
else:
status_symbol = "✅" if result["valid"] else "❌"
print(f"\n{status_symbol} 报告文件: {result['file']}")
print(f"📊 识别表格: {result['tables']} 个 | 配图资产: {result['figures']} 个")
if result["valid"]:
print("🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。\n")
sys.exit(0)
else:
print(f"⚠️ 发现 {len(result['issues'])} 项格式或勾稽问题,必须修正后方可交付:\n")
for i, issue in enumerate(result["issues"], 1):
loc = f" [第 {issue['line']} 行]" if "line" in issue else ""
print(f" {i}. [{issue['code']}]{loc} {issue['message']}")
print("\n💡 提示:请根据上述提示调整对应行的数字或表格结构,直至校验通过。\n")
sys.exit(1)
if __name__ == "__main__":
main()
-12
View File
@@ -1,12 +0,0 @@
# Report templates
月度 AI 审核准确率报告的模板与配套资产(供 `seal-use report monthly` 消费)。
| 文件 | 用途 |
| --- | --- |
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
| `validate.py` / `render.py` | 下游工具:结构校验 + HTML/PNG/PDF 渲染。**不进包**,需要时用 `python3 report-templates/validate.py` 执行 |
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
@@ -1,27 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="400" viewBox="0 0 880 400" font-family="PingFang SC, Hiragino Sans GB, Microsoft YaHei, sans-serif">
<rect x="0" y="0" width="880" height="400" fill="#ffffff"/>
<g stroke="#eceff3" stroke-width="1">
<line x1="110" y1="265" x2="800" y2="265"/>
<line x1="110" y1="190" x2="800" y2="190"/>
<line x1="110" y1="115" x2="800" y2="115"/>
<line x1="110" y1="40" x2="800" y2="40"/>
</g>
<line x1="110" y1="340" x2="800" y2="340" stroke="#d1d9e0" stroke-width="1.5"/>
<g font-size="13" fill="#8b949e" text-anchor="end">
<text x="98" y="345">0%</text>
<text x="98" y="270">25%</text>
<text x="98" y="195">50%</text>
<text x="98" y="120">75%</text>
<text x="98" y="45">100%</text>
</g>
<rect x="270" y="63.76" width="150" height="276.24" rx="4" fill="#4c8bf5"/>
<rect x="510" y="90.01" width="150" height="249.99" rx="4" fill="#6fbf9a"/>
<g font-size="22" font-weight="600" fill="#1f2328" text-anchor="middle">
<text x="345" y="54">92.08%</text>
<text x="585" y="80">83.33%</text>
</g>
<g font-size="15" fill="#59636e" text-anchor="middle">
<text x="345" y="372">AI 审核</text>
<text x="585" y="372">人工审核</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

@@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="360" viewBox="0 0 880 360">
<rect x="4" y="4" width="872" height="352" rx="10" fill="#f6f8fa" stroke="#c9d1d9" stroke-width="2" stroke-dasharray="8 6"/>
<text x="440" y="168" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="22" fill="#8b949e">配图占位:效率、准确度、风险拦截、工作量综合对比</text>
<text x="440" y="202" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="14" fill="#adb5bd">实际报告替换为正式图表</text>
</svg>

Before

Width:  |  Height:  |  Size: 605 B

-270
View File
@@ -1,270 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""md → 渲染产物三件套:HTML + 全长度 PNG + A4 PDF。
用法:
python3 tools/render.py 模板.md -o build/模板
# 产出 build/模板.html、build/模板.png(完整长图,非第一页)、build/模板.pdf(A4 分页)
PNG 先量出文档真实高度再整页截取;超过单次截取上限时自动分带截取并用 Pillow 拼接。
PDF 走 Chrome 打印管线,A4 分页,表头跨页重复、行不跨页截断。
"""
from __future__ import annotations
import argparse
import re
import subprocess
import tempfile
from pathlib import Path
from urllib.parse import unquote
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
PNG_WIDTH = 1200 # PNG 视口宽度(CSS 像素)
PNG_BAND = 14000 # 单次截取的最大高度,超出则分带拼接
# KaTeX 公式渲染(CDN 引入一次并缓存到本地,此后渲染不依赖网络)
KATEX_CSS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css"
KATEX_JS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"
KATEX_AUTO = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
CSS = """
:root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; }
* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg);
font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
-webkit-font-smoothing:antialiased; }
h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); }
h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); }
h3 { font-size:18px; margin:28px 0 12px; }
h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); }
p, li { margin:10px 0; }
blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head);
color:#33404d; border-radius:0 6px 6px 0; }
blockquote p { margin:6px 0; }
code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px;
font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; }
pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; }
pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; }
table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; }
th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; }
th { background:var(--head); font-weight:600; }
tr:nth-child(even) td { background:#fbfcfd; }
img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; }
em { color:var(--muted); font-size:14px; }
hr { border:0; border-top:1px solid var(--line); margin:32px 0; }
a { color:#0969da; }
.katex-display { margin:18px 0; }
@page { size: A4; margin: 14mm 12mm; }
@media print {
body { max-width:none; padding:0; font-size:12pt; }
h2, h3 { page-break-after:avoid; break-after:avoid; }
tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; }
thead { display:table-header-group; }
}
"""
def chrome(args: list[str], timeout: int = 300) -> subprocess.CompletedProcess:
return subprocess.run(
[CHROME, "--headless", "--disable-gpu", "--hide-scrollbars",
"--run-all-compositor-stages-before-draw", *args],
capture_output=True, text=True, timeout=timeout,
)
def doc_title(md: str, fallback: str) -> str:
"""标题取自正文 H1;顺带剥掉可能夹在里面的 HTML 注释。"""
m = re.search(r"(?m)^#\s+(.+?)\s*$", md)
if not m:
return fallback
return re.sub(r"<!--.*?-->", "", m.group(1), flags=re.S).strip() or fallback
def md_to_html(md: str) -> str:
with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as f:
f.write(md)
tmp = f.name
try:
res = subprocess.run(["npx", "--yes", "marked@15", "-i", tmp],
capture_output=True, text=True, check=True)
finally:
Path(tmp).unlink(missing_ok=True)
return res.stdout
def build_html(src: Path) -> tuple[str, str]:
"""渲染出完整 HTML 文本,返回 (html, 标题)。"""
text = src.read_text(encoding="utf-8")
body = md_to_html(text)
base = src.resolve().parent
# 相对图片路径改为绝对 file:// URI;marked 输出已做一次百分号编码,先 unquote 再转
def absolutize(m: re.Match) -> str:
s = m.group(1)
if s.startswith(("http://", "https://", "file://", "data:")):
return m.group(0)
return m.group(0).replace(s, (base / unquote(s)).as_uri(), 1)
body = re.sub(r'<img src="([^"]+)"', absolutize, body)
title = doc_title(text, src.stem)
# $…$ / $$…$$ → KaTeX 显示式;原文中的反斜杠需先转义回渲染器写法
has_math = False
if "$$" in text or re.search(r"(?<!\\)\$(?!\$)[^$]+?\$(?!\$)", text):
has_math = True
body = body.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")
def _display(m: re.Match) -> str:
# KaTeX 把裸 % 当注释符,须转义
return "\\(\\displaystyle " + m.group(1).replace("%", "\\%") + " \\)"
def _inline(m: re.Match) -> str:
return "\\(" + m.group(1).replace("%", "\\%") + " \\)"
body = re.sub(r"\$\$(.+?)\$\$", _display, body, flags=re.S)
body = re.sub(r"(?<!\\)\$(?!\$)([^$]+?)\$(?!\$)", _inline, body)
href_css, _ = local_assets("katex.min.css", KATEX_CSS)
js_local = [local_assets(n, u) for n, u in (
("katex.min.js", KATEX_JS), ("auto-render.min.js", KATEX_AUTO))]
head = (
'<!doctype html>\n<html lang="zh-CN">\n<head>\n<meta charset="utf-8">\n'
f"<title>{title}</title>\n"
f'<link rel="stylesheet" href="{href_css}">\n'
f"<style>{CSS}</style>\n</head>\n"
)
if has_math:
init = (
"<script>document.addEventListener('DOMContentLoaded',function(){"
"renderMathInElement(document.body,{"
"delimiters:[{left:'\\\\(',right:'\\\\)',display:false}],"
"throwOnError:false});});</script>"
)
body += "\n" + init
scripts = "\n".join(f'<script src="{u}"></script>' for _, u in js_local)
body = scripts + "\n" + body
html = head + f"<body>\n{body}\n</body>\n</html>\n"
return html, title
def local_assets(name: str, url: str) -> tuple[str, str]:
"""CDN 资源下载到 .cache/assets 后用本地路径,渲染离线可用;缓存命中不联网。"""
d = Path(__file__).resolve().parent.parent / ".cache" / "assets"
d.mkdir(parents=True, exist_ok=True)
f = d / name
if not f.exists() or f.stat().st_size == 0:
r = subprocess.run(["curl", "-sSL", "-o", str(f), url], capture_output=True)
if not f.exists() or f.stat().st_size == 0:
if f.exists():
f.unlink()
return "", url # 回退 CDN
return f.as_uri(), f.as_uri()
def measure_height(html_path: Path) -> int:
"""注入测量脚本,用 dump-dom 取文档真实高度(等待全部图片加载完)。"""
probe = html_path.with_name("_measure.html")
script = ("<script>window.addEventListener('load',function(){"
"document.title='PAGEH:'+Math.ceil(document.documentElement.scrollHeight)});"
"setTimeout(function(){document.title='PAGEH:'+Math.ceil("
"document.documentElement.scrollHeight)},3000)</script>")
probe.write_text(html_path.read_text(encoding="utf-8").replace("</body>", script + "</body>"),
encoding="utf-8")
try:
res = chrome(["--virtual-time-budget=30000", "--dump-dom", probe.as_uri()])
finally:
probe.unlink(missing_ok=True)
hits = re.findall(r"PAGEH:(\d+)", res.stdout)
if not hits:
raise RuntimeError("量取页面高度失败:" + res.stderr[-300:])
return int(hits[-1])
def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None:
h = measure_height(html_path)
uri = html_path.as_uri()
if h <= PNG_BAND:
chrome([f"--screenshot={png_path}", f"--window-size={width},{h}",
"--virtual-time-budget=30000", uri])
else:
bands: list[Path] = []
offset, i = 0, 0
while offset < h:
bh = min(PNG_BAND, h - offset)
band_html = html_path.with_name(f"_band{i}.html")
band_html.write_text(
html_path.read_text(encoding="utf-8").replace(
"</style>", f"body{{margin-top:-{offset}px}}</style>", 1),
encoding="utf-8")
out = html_path.parent / f"_band{i}.png"
chrome([f"--screenshot={out}", f"--window-size={width},{bh}",
"--virtual-time-budget=30000", band_html.as_uri()])
bands.append(out)
band_html.unlink(missing_ok=True)
offset += bh
i += 1
from PIL import Image
imgs = [Image.open(b) for b in bands]
total = sum(im.height for im in imgs)
canvas = Image.new("RGB", (imgs[0].width, total), "white")
y = 0
for im in imgs:
canvas.paste(im, (0, y))
y += im.height
canvas.save(png_path)
for b, im in zip(bands, imgs):
b.unlink(missing_ok=True)
im.close()
def render_pdf(html_path: Path, pdf_path: Path) -> None:
chrome([f"--print-to-pdf={pdf_path}", "--no-pdf-header-footer",
"--virtual-time-budget=30000", html_path.as_uri()])
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("src")
ap.add_argument("-o", "--out", required=True, help="产物路径词干,如 build/模板")
ap.add_argument("--width", type=int, default=PNG_WIDTH, help="PNG 视口宽度")
a = ap.parse_args()
src = Path(a.src)
stem = Path(a.out).resolve()
stem.parent.mkdir(parents=True, exist_ok=True)
html_path = stem.with_suffix(".html")
html, _ = build_html(src)
html_path.write_text(html, encoding="utf-8")
png_path = stem.with_suffix(".png")
render_png(html_path, png_path, a.width)
pdf_path = stem.with_suffix(".pdf")
render_pdf(html_path, pdf_path)
for p in (html_path, png_path, pdf_path):
size = p.stat().st_size
extra = ""
if p.suffix == ".png":
try:
from PIL import Image
with Image.open(p) as im:
extra = f",{im.width}×{im.height}px"
except ImportError:
pass
if p.suffix == ".pdf":
try:
import subprocess as sp
r = sp.run(["mdls", "-name", "kMDItemNumberOfPages", "-raw", str(p)],
capture_output=True, text=True)
if r.stdout.strip().isdigit():
extra = f",{r.stdout.strip()} 页"
except Exception:
pass
print(f" {p} ({size / 1024:.0f} KB{extra})")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-233
View File
@@ -1,233 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AI 审核报告结构校验器。
文档是纯 Markdown(无 frontmatter、无模板标记),校验器只看文档本身:
- 结构:标题层级、章节编号、表格列数、代码围栏、必填报告信息、图片可解析
- 纯净:不得出现任何模板机制痕迹(slot/@table/{{}}/render:stop/frontmatter)
- 数值:总览表求和与占比、小节标题张数、§6 明细与正文、公式算术——全部从正文推导
用法:
python3 tools/validate.py # 校验根目录全部 .md(README 除外)
python3 tools/validate.py 某文件.md
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
SECTION_NUMBERS = ["1", "2", "3", "4", "5", "6", "7"]
REQUIRED_INFO_ROWS = {"报告编号", "客户名称", "统计期间", "报告状态", "生成日期"}
FORBIDDEN_MARKS = [
(r"<!--slot:", "slot 标记"),
(r"<!--/slot", "slot 闭合"),
(r"<!--@", "@table/@block 区域标记"),
(r"<!-- render:stop", "render:stop 标记"),
(r"\{\{", "{{槽位}}"),
]
class Report:
def __init__(self, path: Path):
self.path = path
self.issues: list[tuple[str, str, str]] = []
self.n_tables = 0
self.n_figs = 0
def err(self, code: str, msg: str) -> None:
self.issues.append(("ERROR", code, msg))
def warn(self, code: str, msg: str) -> None:
self.issues.append(("WARN", code, msg))
def ok(self) -> bool:
return not any(lv == "ERROR" for lv, _, _ in self.issues)
def cells(line: str) -> list[str]:
"""按未转义的 | 拆单元格;\\| 视为字面竖线。"""
s = line.strip()
if s.startswith("|"):
s = s[1:]
if s.endswith("|") and not s.endswith("\\|"):
s = s[:-1]
return [p.replace("\\|", "|").strip() for p in re.split(r"(?<!\\)\|", s)]
def is_sep(line: str) -> bool:
return line.strip() != "" and "-" in line and set(line.strip()) <= set("|-: ")
def iter_tables(lines: list[str]):
i = 0
while i < len(lines):
if lines[i].startswith("|") and i + 1 < len(lines) and is_sep(lines[i + 1]):
header = cells(lines[i])
body, j = [], i + 2
while j < len(lines) and lines[j].startswith("|"):
body.append((j + 1, cells(lines[j])))
j += 1
yield i + 1, header, body
i = j
else:
i += 1
def table_by_header(lines: list[str], keyword: str) -> dict | None:
"""按表头关键词找表,返回 {rows, start, end}(行号 1-based,含表头与分隔行)。"""
for lineno, header, rows in iter_tables(lines):
if keyword in "".join(header).replace(" ", ""):
end = rows[-1][0] if rows else lineno + 1
return {"rows": [r for _, r in rows], "start": lineno, "end": end}
return None
def pct(x: str) -> float | None:
m = re.search(r"(\d+(?:\.\d+)?)\s*%", x)
return float(m.group(1)) if m else None
def count(x: str) -> float | None:
m = re.search(r"(\d+(?:\.\d+)?)", x)
return float(m.group(1)) if m else None
def check(path: Path) -> Report:
r = Report(path)
text = path.read_text(encoding="utf-8")
lines = text.split("\n")
# 1. 纯净性:单层纯 Markdown
if text.startswith("---\n"):
r.err("FM001", "文件以 YAML frontmatter 开头;元数据请放正文「报告信息」表")
for pat, name in FORBIDDEN_MARKS:
if re.search(pat, text):
r.err("MK001", f"出现模板机制痕迹({name}),模板应是纯 Markdown 文档")
# 2. 代码围栏
fences = [i for i, ln in enumerate(lines, 1) if ln.startswith("```")]
if len(fences) % 2:
r.err("MD001", f"代码围栏为奇数({len(fences)}),存在未闭合代码块")
# 3. 表格列数与表头
for lineno, header, rows in iter_tables(lines):
r.n_tables += 1
n = len(header)
for rl, row in rows:
if len(row) != n:
r.err("TB001", f"第 {rl} 行表格列数 {len(row)} ≠ 表头 {n} 列")
if any("**" in c for c in header):
r.err("TB002", f"第 {lineno} 行表头含加粗标记 **")
# 4. 标题层级与章节编号
prev, seen = 0, []
for ln in lines:
m = re.match(r"^(#{1,6})\s+(.*)$", ln)
if not m:
continue
lvl = len(m.group(1))
if prev and lvl > prev + 1:
r.err("HD001", f"标题层级跳级({prev} → {lvl}):{m.group(2)[:40]}")
prev = lvl
m2 = re.match(r"^(\d+)\.", m.group(2))
if lvl == 2 and m2:
seen.append(m2.group(1))
if seen and seen != SECTION_NUMBERS:
r.err("HD002", f"## 章节编号应为 {SECTION_NUMBERS},实际 {seen}")
# 5. 报告信息表
info = table_by_header(lines, "报告信息")
if not info:
r.err("INFO001", "缺少「报告信息」表")
else:
keys = {row[0] for row in info["rows"] if row}
missing = REQUIRED_INFO_ROWS - keys
if missing:
r.err("INFO001", f"报告信息表缺少:{', '.join(sorted(missing))}")
empty = [row[0] for row in info["rows"] if row and len(row) > 1 and not row[1].strip()]
if empty:
r.err("INFO002", f"报告信息表以下项为空:{', '.join(empty)}")
# 6. 图片可解析:http(s) 或存在的本地文件
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
src = m.group(1).strip()
r.n_figs += 1
if src.startswith(("http://", "https://")):
continue
if not (path.parent / src).exists():
r.err("IMG001", f"图片不存在:{src}")
# 7. 数值自洽(全部从正文推导)
for tag, kw in (("NM001", "失准类型"), ("NM002", "风险类型")):
tb = table_by_header(lines, kw)
if not tb:
continue
rows = tb["rows"]
tops = [(c[0], count(c[3])) for c in rows if len(c) > 3 and c[0].startswith("TOP")]
totals = [count(c[3]) for c in rows if len(c) > 3 and c[0] in ("合计", "总计", "—")]
if tops and totals and all(c is not None for _, c in tops):
if sum(c for _, c in tops) != totals[0]:
r.err(tag, f"{kw}各维度之和 {sum(c for _, c in tops)} ≠ 合计 {totals[0]}")
base = totals[0] if totals else None
for c in rows:
if len(c) < 4:
continue
share, cnt = pct(c[2]), count(c[3])
if share and cnt and base and c[0].startswith("TOP") and abs(cnt / base * 100 - share) > 0.15:
r.err("NM003", f"{kw}「{c[1]}」占比 {share}% ≠ {cnt:.0f}/{base:.0f} = {cnt / base * 100:.1f}%")
# 小节标题里的张数与总览表一致
for no, cnt in tops:
sec = "2" if kw == "失准类型" else "3"
m = re.search(r"###\s*%s\.\d+\s*%s[^(]*((\d+)\s*张" % (sec, re.escape(no)), text)
if m and cnt is not None and int(m.group(1)) != cnt:
r.err(tag, f"{no} 小节标题写 {m.group(1)} 张,总览表写 {cnt:.0f} 张")
# NM004:§6 明细表的结论分类计数 = 正文数字
pr = table_by_header(lines, "原因分类")
if pr:
d4 = sum(1 for c in pr["rows"] if len(c) > 4 and "依规正确" in c[4])
miss = sum(1 for c in pr["rows"] if len(c) > 4 and "失准" in c[4])
m = re.search(r"((\d+)\s*/\s*(\d+)\s*笔)", text)
m2 = re.search(r"仅有\s*\*{0,2}(\d+)\s*笔", text)
if m and int(m.group(1)) != d4:
r.err("NM004", f"正文称依规正确 {m.group(1)} 笔,明细表实际 {d4} 行")
if m and int(m.group(2)) != len(pr["rows"]):
r.err("NM004", f"正文称合计 {m.group(2)} 笔,明细表实际 {len(pr['rows'])} 行")
if m2 and int(m2.group(1)) != miss:
r.err("NM004", f"正文称 AI 失准 {m2.group(1)} 笔,明细表实际 {miss} 行")
# NM005:公式算术自洽,且代入值能在正文别处找到
formula_lines = [l for l in lines if l.strip().startswith("$$")]
outside = "\n".join(l for l in lines if not l.strip().startswith("$$"))
for ln in formula_lines:
for frac in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", ln):
a, b, p = int(frac.group(1)), int(frac.group(2)), float(frac.group(3))
if b and abs(a / b * 100 - p) > 0.05:
r.err("NM005", f"公式 {a}/{b} = {p}% 算术不成立(实为 {a / b * 100:.2f}%)")
for tok in re.findall(r"\d+(?:\.\d+)?", ln):
if tok not in outside:
r.err("NM005", f"公式中的数值 {tok} 在正文别处找不到,可能与数据脱节")
return r
def default_paths() -> list[Path]:
"""默认校验根目录全部 .md(README.md 除外)。"""
return sorted(p for p in Path(".").glob("*.md") if p.name != "README.md")
def main() -> int:
paths = [Path(a) for a in sys.argv[1:]] or default_paths()
failed = False
for p in paths:
rep = check(p)
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
for lv, code, msg in rep.issues:
print(f" {lv} {code}: {msg}")
failed |= not rep.ok()
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+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);
});
}
+1
View File
@@ -27,6 +27,7 @@ const files = walk(skillRoot).map((fullPath) => ({
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
}));
const lines = [
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
""
+1 -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");
}
+38 -13
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.4: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.8: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.4
short-description: Seal tenant and Hose approval automation (v0.11.4)
version: 0.11.8
short-description: Seal tenant and Hose approval automation (v0.11.8)
---
# Seal Use
@@ -63,6 +63,14 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
## 规则编号重排:两次调用
`seal-use rules recode --corp <corpId>` 将当前草稿编号从 `0000` 连续编排。具体顺序由服务端决定,新建草稿可能排在已有规则之前;所有规则均可能变号,不能把预览中的编号范围当作逐条映射。第一次只返回影响预览、6 位一次性凭证、到期时间和 `nextCommand`,`executed: false`,退出码为 10;尚未执行重排。核对目标企业和完整影响范围后,另一次调用返回的完整命令才执行;成功返回的 `changes` 是按稳定身份回读验证的真实编号映射。
凭证绑定企业、环境及草稿状态,5 分钟有效且只能使用一次;`--yes` / `--confirm` 不能替代凭证。`--dry-run` 只预览,不签发凭证。确认码尚未生效时停止连调,不把两阶段写成自动执行脚本;草稿变化或凭证失效时重新预览。执行失败或超时后先回读当前草稿,再决定是否重新申请,不能重用旧码或盲目重跑。
重排不发布版本。旧编号可能对应不同规则,查看历史记录需指定发布版本。具体预览与返回字段见 `references/rule-lightweight.md`。
## 业务术语契约
对外统一使用以下术语:
@@ -93,13 +101,13 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
| 规则数量、摘要列表、历史规则、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 需要结构校验或 PDF 渲染时,再读 `report-templates/README.md` |
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `references/report-templates.md` |
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
@@ -128,18 +136,34 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
## 月度审核准确率报告
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
推荐通过轻量数据包 + Agent 协同填写的模式,彻底解耦数据与模板(亦兼容一键脚手架模式):
```bash
seal-use report monthly --month <YYYY-MM> --corp <corpId>
# 模式 A (推荐轻量数据驱动): 提取当月纯结构化数据 (指标、分模板统计、待复核分歧单及具体触发条件)
seal-use report data --month <YYYY-MM> --corp <corpId>
# 保存纯净模板骨架
seal-use report template --out reports/报告.md
# 独立生成动态维恩图 SVG
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/报告.assets/图1-准确率对比.svg
# 模式 B (传统模板脚手架): 一键生成初步替换的 Markdown 与配图包
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
# 离线校验与全格式编译导出
seal-use report validate reports/报告.md
seal-use report render reports/报告.md --out build/报告
```
按模板结构(`report-templates/monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
按模板结构(内置 `monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- 结果里的 `next` 给出下游 `validate` / `render` 指引(校验与 HTML/PNG/PDF 渲染用 `report-templates/validate.py`、`render.py`,不进包)。
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
- **报告并非一键黑盒交付(人机协同研讨契约)**:数据接口无法自动获得“谁对谁错”的仲裁定性,也无法自动撰写管理归因与整改建议。生成初版 Markdown 后,Agent **严禁直接向客户交付带有 `> ⚠️ 数据说明` 警告框、模板假单号或 `(截图)` 占位符的半成品**,必须进入人机协同研讨模式(Tangent),向用户呈现分歧单据并共创定性分析文本。完整研讨流程、各章节动静边界与校验错误码见 `references/report-templates.md`。
- **推荐轻量 Agent 执笔**:调用 `seal-use report data` 获取干净的 JSON 数据包(含触发的单个判断条件 `triggeredConditions`),由 Agent 亲自将真实数据与复核分析填入 Markdown,避免代码层正则换数的死板与脆弱。
- **模板是可变的皮,以用户态度为最高准则**:大章节(§1~§6)是必选论证骨架,但具体问题分类(TOP 1~N,至少保留 1 个)、案例行数、表格列数均由当期数据与用户意图动态决定,严禁 Agent 固执教条(如机械死板凑满 3 类或 3 行);案例详情链接由管线全自动注入,Markdown 源码只聚焦业务内容。详见 `references/report-templates.md`。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,初稿保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
- 只读能力 `sealReportDataGet` / `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
### 人工裁决回填(算出人工审核准确率)
@@ -153,7 +177,8 @@ seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|hum
seal-use report review list --month <YYYY-MM> --corp <corpId>
```
- **存储**:`~/.config/seal-use/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
- **存储**:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
- **协同研讨指南**:呈报分歧单据供用户裁决时,必须附带 Seal AI 审核页与合思原单据的双端直达链接(`approval-runs url --auto-login` / `hose-use bill link`);分歧单据挑选格式、失准归因撰写(§2)、分歧概览(§5)与严格离线校验(NM001~NM005)排查手册,完整参见 `references/report-templates.md`。
@@ -50,7 +50,7 @@ If `seal-use langfuse search` does not find Chinese terms reliably, grep the cac
```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.
@@ -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
+14 -8
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>]
@@ -145,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>]
@@ -263,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).
@@ -297,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`):
@@ -344,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.
@@ -371,7 +377,7 @@ Approval runs, simulations, and Langfuse bridge:
Langfuse trace inspection (built-in, read-only, credentials injected at compile time; no `--corp` and no user config required; all verbs are `seal_use` MCP-read-only):
- `seal-use langfuse check` verifies connectivity of the embedded read-only credentials (missing credentials → exit 11).
- `seal-use langfuse cache-refresh <traceId>` fetches one full trace into `<cwd>/.cache/langfuse/traces/default/<traceId>.json` (shared format with langfuse-home); other cache-first verbs answer from it and point here (exit 13) when it is missing, unless `--refresh-if-missing`.
- `seal-use langfuse 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`).
@@ -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. 关键配置参数定义
+3 -3
View File
@@ -2,7 +2,7 @@
`seal-use langfuse` 是内建的只读 Langfuse trace 检索域:凭据在编译期注入,最终用户**零配置**,无需 `langfuse-home` 或任何本地 `.env`。命令不需要 `--corp`,MCP `seal_use` 网关全部可达。
只读边界:client 只发 `GET`,本地只写 `.cache/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。
只读边界:client 只发 `GET`,本地只写用户目录 `~/.cache/seal-use/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。
## IO-last 工作流
@@ -14,7 +14,7 @@
seal-use langfuse cache-refresh <traceId>
```
缓存写入 `<cwd>/.cache/langfuse/traces/default/<traceId>.json`(与 langfuse-home 同格式,可共享)。后续命令缺缓存时报 exit 13 并提示补缓存,或加 `--refresh-if-missing` 现场拉取。
缓存写入 `~/.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)
@@ -33,7 +33,7 @@ seal-use langfuse search <traceId> --query "关键词" --fields input,output --o
seal-use langfuse search <traceId> --query "关键词" --metadata '{"stage":"review"}'
```
返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" .cache/langfuse/traces/default/<traceId>.json`。
返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" ~/.cache/seal-use/langfuse/traces/default/<traceId>.json`。
### 4. 焦点 observation IO
@@ -0,0 +1,178 @@
# 月度 AI 审核报告编制与人机协同作业指南 (Monthly Report Authoring & Tangent Workflow)
本文档面向 **AI Agent 与操作用户**,规范从**月度数据拉取**、**分歧单据人机复核研讨(Tangent)**、**Agent 自主理解与填报**,到**严格离线门禁校验、全格式渲染与多轮修改**的端到端人机协同闭环。
---
## 核心认知与人机分工 (Core Division of Labor)
1. **确定性工具管线 + Agent 智能执笔**:
- **工具层 (`seal-use`)**:提供确定性提数(`report data`)、裁决记录(`review set`)、矢量图表(`report chart venn`)、离线格式与勾稽门禁(`report validate`)、全格式渲染(`report render`)及全量明细台账(`《明细台账.xlsx》`)。
- **Agent 层(智能分析与自主撰写)**:Agent 最擅长理解数据、归纳归因并与用户对话。Agent 调取结构化数据包与模板骨架,结合用户裁决意见,亲自将真实数据、原因分类与业务建议填入 Markdown,彻底摆脱死板的模板脚本限制。
2. **人机对齐与裁决研讨 (Review Tangent)**:
- 当 AI 与人工判定结论不一致时,Agent 绝不凭空主观臆断,而是从数据包中提取关键分歧单(含单号、AI摘要、触发的具体规则卡口 `triggeredConditions`),主动在聊天窗口向用户征询对错裁决定性。
3. **必须通过格式门禁校验 (Zero-Error Gate)**:
- 严禁交付未经校验的 Markdown。Agent 在调用 `render` 渲染前,**必须执行 `seal-use report validate`**。若有报错,Agent 需读取报错 issue 自纠自查,修正格式与数字勾稽,直到 100% 通过。
4. **即时渲染与多轮反馈修改**:
- 渲染出的 HTML、A4 PDF 和高清长图交由用户审查。用户提出调整意见后,Agent 微调 Markdown,再次过门禁校验并重新渲染,完成多轮敏捷迭代。
---
## 端到端人机协同五步闭环 (The 5-Stage Lifecycle)
```mermaid
flowchart TD
S1["第一步:拉取结构化数据与模板骨架<br/>(report data & report template)"] --> S2["第二步:分歧单据人机裁决研讨<br/>(Agent 汇报分歧,用户给出定性)"]
S2 --> S3["第三步:Agent 结合理解自主撰写报告<br/>(撰写结构化 Markdown 报告草稿)"]
S3 --> S4["第四步:离线格式与数学勾稽门禁<br/>(report validate 质检拦截与自纠)"]
S4 --> S5["第五步:全格式渲染与多轮修改迭代<br/>(report render 产出交付,根据用户意见微调)"]
```
---
### 第一步:获取结构化数据包与模板骨架
1. **拉取当月纯结构化业务数据包 (JSON)**:
```bash
seal-use report data --month <YYYY-MM> --corp <corpId>
```
*输出说明:返回纯 JSON,包含全月样本量、AI 准确率、采纳率、平均耗时、公式代入值、分模板统计、TOP 风险标签,以及全量分歧单据池(`divergedRuns`)。*
2. **导出纯净标准模板骨架**:
```bash
seal-use report template --out reports/<企业名>-<YYYYMM>.md
```
3. **动态生成准确率维恩图**:
```bash
mkdir -p reports/<企业名>-<YYYYMM>.assets
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
```
---
### 第二步:分歧单据人机复核研讨 (Diverged Runs Review)
当 `reviews.divergedUnreviewedCount > 0` 时,存在 AI 放行但人工驳回、或 AI 驳回但人工放行的分歧单据。Agent 需主动在聊天中向用户汇总呈报并征询裁决。
**双链穿透规范 (Dual-Link Fast Traversal)**:
呈报给用户裁决的每笔典型案例,Agent **必须同时生成并附带双端直达链接**,严禁让用户盲猜或手动去系统里翻查单据:
- **🔗 Seal AI 审核页直达**:调用 `seal-use approval-runs url --sn <SN> --auto-login` 生成带临时免密凭证的直达链接,一键跳转到 Seal AI 查看完整判定快照、引用规则、卡口明细与 LLM 推理过程;
- **📑 合思/易快报原单据直达**:调用 `hose-use bill link <SN>` 或从运行记录 `sourceExtendData.hosecloudViewUrl` 提取原单据 Web 链接,一键直达合思原单据查看发票原件影像、业务附件与人工审批操作历史。
1. **结构化向用户呈现典型案例**:
```markdown
【分歧单据复核确认】单号:FP2608010
- 单据模板:发票-个人报销
- 快速核验:[🔗 Seal AI 审核详情](https://<corp>.sealai.cc/approval-result/<recordId>) | [📑 合思原单据](https://wx2.ekuaibao.com/...)
- AI 审核结论:同意(单据附件与发票齐全合规,满足既定规则)
- 人工实际操作:驳回/终止(批注:口头超标)
- 触发条件:现行线上规则库无该超标阻断规则
👉 请教您对本单的裁决:
1. AI 依规正确(ai_correct):按线上规则库合规放行,人工属于口头加码标准;
2. 人工正确 / AI 失准(human_correct):业务实际存在超标限制,属于 AI 误判或规则未覆盖;
3. 双方都对(both_correct):规则执行正确,但有线下特殊处理。
```
2. **将用户意见持久化录入复核账本**:
```bash
seal-use report review set \
--month <YYYY-MM> \
--sn <单号> \
--verdict <ai_correct|human_correct|both_correct> \
--note "口头加码标准,现行线上规则库未配置" \
--corp <corpId>
```
---
### 第三步:Agent 结合数据与裁决自主撰写
Agent 调取模板,结合数据包与用户裁决定性,自主撰写全新的 6 章节 Markdown:
* **§1 审核测试结果**:填入企业名称、账期、样本总量、AI 准确率、人工准确率公式及维恩图。
* **§2 AI 失准分析**:将真实的错判单据填入 TOP 1~3 小节,写出针对性整改方案。
* **§3 AI 发现的潜在风险**:列出 AI 在人工通过单据中额外识别出的票据、预付与凭证风险。
* **§4 综合效益**:填入时效、准确度、拦截笔数等宏观关键数据。
* **§5 审核分歧与复核归因**:
- 填入分类统计表(如“未在线配置规则 66.7% / AI 识别偏差 33.3%”);
- 总结管理建议(推动口头标准线上化规则沉淀);
- 明确引导用户查看随包附带交付的《明细台账.xlsx》核对逐单流水。
* **§6 支撑数据与交付材料**:
- 6.1 分模板准确率与自动审批率表格;
- 6.2 配套交付的《明细台账.xlsx》说明。
---
### 第四步:离线门禁格式与勾稽校验 (Validate)
在执行最终渲染前,Agent **必须**执行门禁校验命令:
```bash
seal-use report validate reports/<企业名>-<YYYYMM>.md
```
#### 门禁校验重点关注项:
- **`HD001` / `HD002`**:二级章节编号必须自 1 开始连续递增(`## 1.`, `## 2.`, ..., `## 6.`),不得跳级。
- **`TB001` / `TB002`**:表格列数前后严格一致,表头行严禁带加粗 `**` 标记。
- **`NM001` / `NM002`**:失准与风险总览表中的各分项张数之和必须严格等于合计行。
- **`NM004`**:分歧原因分类表中的各单数与正文叙述中的笔数必须完全勾稽。
- **`NM005`**:准确率公式(如 `\frac{221}{240} = 92.08\%`)算术必须成立,且数值在正文中必须能找到对应数据来源。
- **`INFO001` / `INFO002`**:开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。
> ⚠️ 若返回 `valid: false`,Agent 必须读取报错列表中的 `code` 和 `message`,**自主编辑修正 Markdown**,直到再次校验返回 `valid: true`。
---
### 第五步:全格式渲染与多轮修改迭代 (Render & Iterate)
1. **一键编译渲染全套交付产物**:
```bash
seal-use report render reports/<企业名>-<YYYYMM>.md --out build/<企业名>-<YYYYMM> --format all
```
*产物包含:单文件自包含 HTML、A4 打印排版 PDF、4x 超高清拼接长图 PNG。*
2. **呈现给用户并接收修改意见**:
- Agent 将渲染后的成果与核心数据摘要反馈给用户;
- 用户审查后提出调整(如“某段原因描述请改一下”、“风险小节增加具体发票案例”);
- Agent 直接在 Markdown 文件中微调,再次运行 `report validate` 确保无勾稽错误,然后重新 `report render` 刷新交付。
---
## 模板 6 大标准章节剖析 (Section Anatomy)
| 章节编号与名称 | 数据来源与机制 | 说明与核心关注点 |
| :--- | :--- | :--- |
| **标题与报告信息表** | 数据填充 | 包含企业名称、账期、生成日期、草稿状态与唯一报告编号。 |
| **摘要** | 动态提炼 | 提炼全月单量、核心准确率与额外发现的合规风险笔数。 |
| **§1 审核测试结果** | 核心数据 | 1.1 数据来源与样本总量;1.2 准确率结论、计算公式与图 1 维恩图。 |
| **§2 AI 失准分析** | 深度归因 | 2.1 失准构成总览;2.2~2.4 TOP 失准真实案例与调优解决方案。 |
| **§3 AI 发现的潜在风险** | 价值体现 | 3.1 风险构成总览;3.2~3.4 缺失凭证、大额预付、专票违规等真实拦截。 |
| **§4 综合效益** | 数据汇总 | 准确度、时效(平均秒数)、风险拦截量与人力释放宏观汇总表。 |
| **§5 审核分歧与复核归因** | 概览归因 | 人机分歧分类统计(线上规则未覆盖 vs 识别偏差),引导查验《明细台账.xlsx》。 |
| **§6 支撑数据与交付材料** | 支撑底账 | 6.1 各模板准确率与自动化率;6.2 交付文件说明(明细台账 Excel/CSV)。 |
---
## 动态自适应与用户至上原则 (Dynamic Adaptability & User-Centric Principles)
为避免后续使用的 AI Agent 产生死板教条(“非要凑满 3 类问题”、“非要放满 3 行”、“强行增加冗余列”等固执偏见),特此确立以下人机协同规范:
### 1. 必选骨架 vs 动态子部分的边界
* **大章节是不可缺少的骨架**:§1~§6 大章节承载了完整严谨的商业论证闭环(业绩证明、失准坦白、额外价值、分歧归因、支撑台账),必须存在。
* **章节内部的子部分完全动态**:
* 例如 §2(失准分析)与 §3(潜在风险)下的具体问题分类,**数量完全由实际跑批结果与用户业务关注度决定**。
* **唯一硬性底线**:动态章节下**至少保留 1 个子分类**(不能是无正文的空标题),可以是 TOP 1~2、TOP 1~3 或扩展至 TOP 1~5。
* **数学自洽守恒**:无论列出几种分类,分类表中的单数之和必须严格等于「合计」行单数,且百分比之和严格等于 100%(`NM001`~`NM003`)。
### 2. 用户态度为最高准则 (User Preference First)
* **严禁 Agent 固执己见**:Agent 必须以用户的业务判断与汇报习惯为首要输入。如果用户要求“重点只突出 2 个主要风险”、“案例只放 1 个最具代表性的单据”,Agent 必须立即响应调整,不得机械搬用模板默认的 3 分类或 3 行案例。
* **文字叙述灵活定性**:针对失准单据的“解决方案”与分歧归因的“管理建议”,Agent 需结合具体企业的管理要求与规则实际情况有针对性地撰写,杜绝空话套话。
### 3. 表格案例与跳转超链接免维护契约
* **Markdown 源码专注业务语义**:用户与 Agent 在编写或编辑 Markdown 报告草稿时,无需在源码中手动维护长串技术 URL,保持干净易读(如常规的 `| 单号 | 问题描述 |`)。
* **自动化链接注入机制**:
* **2 列模式**:若表格只有两列,管线在填充真实数据时会自动将第一列单号升级为跳转链接 `[SN](https://<corp>.sealai.cc/approval-result/<recordId>)`。
* **3 列模式**:若表头显式声明了 `审核详情` 或 `链接` 列,管线会自动在第 3 列生成 `[👉 查看详情](https://...)`。
* **跨端交付表现**:单文件自包含 HTML 与 A4 排版 PDF 均天然支持在浏览器或 PDF 阅读器中一键点击穿透直达系统后台;长图 PNG 为纯像素光栅位图,主要用于 IM 聊天窗口内快速滑动预览。
@@ -92,6 +92,19 @@ Expected shape:
}
```
## Recode Draft Rule Numbers
```bash
seal-use rules recode --corp <corpId>
seal-use rules recode --dry-run --corp <corpId>
```
The first command returns a preview, a six-character one-use confirmation code, `expiresAt`, and `nextCommand`, with `executed: false` and exit code 10. Inspect the enterprise and full impact scope, then invoke the returned command separately. Preview `changesDiff` shows the existing and resulting number ranges, not a per-rule mapping (`mappingAvailable: false`); every rule can change number. The code is bound to the enterprise, environment and exact draft state, expires in five minutes, and is consumed before the POST. Ordinary `--yes`/`--confirm` cannot bypass this flow. Do not combine both phases into an automatic script.
`--dry-run` returns only the preview (exit 0) without issuing a code. A successful second call returns `executed: true`, the verified per-rule `changes` (`mappingAvailable: true`), and `nextCode`. Recode starts at `0000`, and the server determines ordering: new drafts may move before existing active rules. It does not publish. A not-yet-active code should not trigger immediate repeated calls. On expiry or draft changes request a fresh preview; on POST failure/timeout, read the current draft before requesting another code. A spent code is never reusable.
Clearing rules and test synchronization reset the allocation counter only after verifying the draft is empty. If clear leaves any rules behind, it skips automatic recoding and reports a warning.
## Output Discipline
If a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports.
+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 } });
}
+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,
+5 -4
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 { 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,
@@ -126,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.`);
}
+115 -9
View File
@@ -1,24 +1,114 @@
import { writeFileSync } from "node:fs";
import { resolve } from "node:path";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { runCapabilityResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js";
import { CliError, usageError } from "../../core/errors.js";
import {
BUILTIN_MONTHLY_TEMPLATE,
exportReportPackage,
renderReportFile,
renderVennAccuracySvg,
saveReportMarkdown,
validateReportFile,
loadReviews,
reviewFilePath,
writeReview,
type MonthlyReportResult
} from "../../domains/seal/reports/index.js";
import type { ParsedArgs } from "../types.js";
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
export async function handleLocalReportCommand(action: "validate" | "render" | "export" | "template" | "chart", args: ParsedArgs) {
if (action === "template") {
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
writeFileSync(resolve(out), BUILTIN_MONTHLY_TEMPLATE, "utf8");
printJson({ file: resolve(out), size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
} else {
printJson({ content: BUILTIN_MONTHLY_TEMPLATE, size: Buffer.byteLength(BUILTIN_MONTHLY_TEMPLATE) }, outputOptions(args.options));
}
return;
}
if (action === "chart") {
const sub = args.command[2];
if (sub !== "venn") throw usageError("Usage: seal-use report chart venn --ai <accuracy> --human <accuracy> [--both <accuracy>] [--out <file.svg>]");
const ai = numberOption(args.options.ai) ?? numberOption(args.options["ai-accuracy"]) ?? 92.08;
const human = numberOption(args.options.human) ?? numberOption(args.options["human-accuracy"]) ?? 83.33;
const both = numberOption(args.options.both) ?? numberOption(args.options["both-accurate"]) ?? 75.42;
const svg = renderVennAccuracySvg({ aiAccuracy: ai, humanAccuracy: human, bothAccurate: both });
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
writeFileSync(resolve(out), svg, "utf8");
printJson({ file: resolve(out), format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, size: Buffer.byteLength(svg) }, outputOptions(args.options));
} else {
printJson({ format: "svg", aiAccuracy: ai, humanAccuracy: human, bothAccurate: both, svg }, outputOptions(args.options));
}
return;
}
const file = args.command[2] ?? stringOption(args.options.file);
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : action === "export" ? " --out <目标文件夹>" : ""}`);
if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。");
if (action === "validate") {
const result = await validateReportFile(file);
printJson(result, outputOptions(args.options));
if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1);
return;
}
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`);
if (action === "export") {
const result = await exportReportPackage(file, {
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1);
return;
}
const result = await renderReportFile(file, {
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
}
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
export async function handleReportCommand(
action: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "data") {
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]");
}
const result = await runCapabilityResult(
"sealReportDataGet",
client,
corp,
{
month,
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
}
);
printJson(result, outputOptions(args.options));
return;
}
if (action === "monthly" || action === "month") {
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
}
await runCapability(
const result = await runCapabilityResult(
"sealReportMonthlyGet",
client,
corp,
@@ -26,10 +116,26 @@ export async function handleReportCommand(
month,
templatePath: stringOption(args.options.template),
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
},
outputOptions(args.options)
);
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns),
allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force)
}
) as MonthlyReportResult;
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
const saved = saveReportMarkdown(
result.content,
result.templatePath,
out,
booleanOption(args.options.overwrite),
result.dynamicAssets,
result.companionFiles
);
const quotedFile = `'${saved.file.replace(/'/g, "'\\''")}'`;
printJson({ ...result, content: undefined, dynamicAssets: undefined, companionFiles: undefined, ...saved, next: {
validate: `seal-use report validate ${quotedFile}`,
render: `seal-use report render ${quotedFile} --out build/report`
} }, outputOptions(args.options));
} else printJson({ ...result, dynamicAssets: undefined, companionFiles: undefined }, outputOptions(args.options));
return;
}
+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(
+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");
+133 -23
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,20 +592,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "replay",
summary: "Replay approval run record into a Webhook integration",
usage: [
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--corp <corpId>]",
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>]",
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>]"
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--corp <corpId>]",
"seal-use approval-runs replay --sn <documentSN> [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]",
"seal-use approval-runs replay --sn <documentSN> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]",
"seal-use approval-runs replay <recordId> --channel hose-outbound [--sign-key <key>] [--target-corp <corpId>] [--dry-run] [--yes|--confirm]",
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]"
],
options: [
{ flag: "<recordId>", description: "Approval run record ID" },
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
{ flag: "--channel <webhook|hose-outbound>", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" },
{ flag: "--sign-key <key>", description: "Target Hose integration signKey for hose-outbound; required when the target has several integrations" },
{ flag: "--message-id <msgId>", description: "Explicit Hose outbound messageId override" },
{ flag: "--rejection-num <n>", description: "Target specific rejection iteration (0, 1, 2, ...)" },
{ flag: "--limit <n>", description: "Batch replay latest N records" },
{ flag: "--status <status>", description: "Filter records by status" },
{ flag: "--webhook <idOrName>", description: "Target Webhook integration" },
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside" },
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed" },
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
{ flag: "--dry-run", description: "Preview payload without sending" }
{ flag: "--dry-run", description: "Preview payload without sending" },
{ flag: "--yes, --confirm", description: "Required for live replay; --force only overrides environment and pairing guards" }
]
}
]
@@ -603,21 +620,88 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
area: "report",
title: "Monthly audit accuracy reports",
description: "Generate the monthly AI audit accuracy report (Markdown) from a mutable template plus live tenant data.",
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
commands: [
{
name: "data",
summary: "Extract pure structured report data, metrics, diverged runs, and triggers without templates",
usage: ["seal-use report data --month <YYYY-MM> [--max-runs <n>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
],
description: "Template-free data pack for Agent authoring: returns performance metrics, formula fractions, template groups, top risk tags, diverged runs with exact triggered conditions, and reviews."
},
{
name: "template",
summary: "Dump or save the built-in monthly report Markdown template",
usage: ["seal-use report template [--out <file.md>]"],
options: [
{ flag: "--out <file>", description: "Save built-in Markdown template directly to a file" }
],
description: "Tenant-free local command: returns or saves the built-in monthly.md template so an Agent or user can co-author."
},
{
name: "chart venn",
summary: "Generate dynamic Venn accuracy comparison SVG chart independently",
usage: ["seal-use report chart venn --ai <acc> --human <acc> [--both <both>] [--out <file.svg>]"],
options: [
{ flag: "--ai <acc>", description: "AI accuracy percentage (e.g. 92.08)" },
{ flag: "--human <acc>", description: "Human accuracy percentage (e.g. 83.33)" },
{ flag: "--both <both>", description: "Both accurate percentage (e.g. 75.42)" },
{ flag: "--out <file>", description: "Save SVG directly to file" }
],
description: "Tenant-free local command: calculates proportions and outputs high-fidelity SVG chart."
},
{
name: "monthly",
aliases: ["month"],
summary: "Fill the monthly report template with performance, risk, and approval-run data",
usage: ["seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--allow-unreviewed] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to report-templates/monthly.md" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" },
{ flag: "--out <file>", description: "Save Markdown plus local images beside the report; stdout stays JSON (without the content field)" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" },
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" },
{ flag: "--allow-unreviewed", description: "Bypass pre-flight adjudication gate to generate draft when unreviewed diverged runs exist" }
],
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
},
{
name: "validate",
summary: "Check a local report's structure, images, totals, and formulas",
usage: ["seal-use report validate <报告.md>"],
options: [],
description: "Local only: no --corp, credentials, or Seal requests. Returns JSON issues; exit 1 if validation fails."
},
{
name: "render",
summary: "Validate and export HTML, full-length PNG, and A4 PDF from local Markdown",
usage: ["seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]"],
options: [
{ flag: "--out <stem>", description: "Output filename stem; extensions are appended" },
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
],
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
},
{
name: "export",
summary: "Package Markdown, local 4x assets, self-contained HTML, and PDF into a dedicated directory",
usage: ["seal-use report export <报告.md> --out <输出目录> [--format <all|html|pdf>]"],
options: [
{ flag: "--out <dir>", description: "Dedicated output directory for the report bundle" },
{ flag: "--format <format>", description: "all (default), html, or pdf" },
{ flag: "--width <px>", description: "PNG viewport width, default 1200" },
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" }
],
description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF."
},
{
name: "review set",
summary: "Record one human adjudication (who was right: AI or human) for a document",
@@ -629,7 +713,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--note <text>", description: "Optional adjudication note" },
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
],
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
},
{
name: "review list",
@@ -740,13 +824,34 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "hosecloud configure",
summary: "Configure HoseCloud deployment settings",
usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]"]
summary: "Save Hose integration settings in Seal",
usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]"],
options: [
{ flag: "--dry-run", description: "Preview the configuration diff without saving" },
{ flag: "--yes, --confirm", description: "Required to save the integration configuration" }
]
},
{
name: "hosecloud sync",
summary: "Synchronize HoseCloud rules and definitions",
usage: ["seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]"]
summary: "Create or update Hose outbound messages and callback URLs",
usage: ["seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]"],
options: [
{ flag: "--auto", description: "Select the sole Hose integration; does not confirm synchronization" },
{ flag: "--dry-run", description: "Preview the sync request without creating or updating messages" },
{ flag: "--yes, --confirm", description: "Required for live synchronization" }
]
},
{
name: "hosecloud test-outbound",
summary: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发(要求 assisted 模式)",
usage: [
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <id> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]",
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --sn <SN> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]"
],
options: [
{ flag: "--dry-run", description: "Preview the outbound payload without sending" },
{ flag: "--yes, --confirm", description: "Required for live outbound push" }
]
}
]
},
@@ -835,11 +940,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "link",
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
usage: [
"seal-use auth link [--note <note>] [--corp <corpId>]",
"seal-use auth link --from-link <url> [--note <note>]"
"seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]",
"seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]"
],
options: [
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" },
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" },
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
],
description:
@@ -859,9 +965,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "hose-link",
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200] [--force]"],
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]"],
options: [
{ flag: "--expire <seconds>", description: "链接有效时间(秒),默认 7200,支持如 86400(1天)" },
{ flag: "--expire, --expires-in <duration>", description: "链接有效时间,推荐 '7d' 或 '2h'(默认 2h,兼容秒数如 7200)" },
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
],
description:
@@ -912,7 +1018,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "delegation",
summary: "Create delegation token for a specific user",
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]"]
usage: ["seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]"],
options: [
{ flag: "--note <note>", description: "委托授权备注说明" },
{ flag: "--expire, --expires-in <duration>", description: "委托授权有效期,推荐 '7d' 或 '24h'(最大 7 天,兼容秒数并自动向下取整)" }
]
},
{
name: "reset-password",
+14 -4
View File
@@ -65,10 +65,11 @@ 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 });
}
/**
@@ -98,6 +99,15 @@ export async function runLangfuseCapability(
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(compactParams as never, createLangfuseService()), options);
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", () => {
+131 -28
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";
/**
@@ -22,14 +23,14 @@ import { usageError } from "./errors.js";
// Read with booleanOption(...) / Boolean(...) / presence check.
export const BOOLEAN_FLAGS = new Set([
"V", "add", "all", "as-hose", "attachments", "auto",
"V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
"hose", "hose-sso", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"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",
"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",
@@ -39,29 +40,29 @@ export const BOOLEAN_FLAGS = new Set([
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
"code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "date",
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
"channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "expire", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "humanResult", "id", "input", "integration",
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "note", "observation-id", "observation-types", "o", "offset", "out",
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
"reviewed-by", "reviewedBy",
"report-id",
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
@@ -80,43 +81,43 @@ export const VALUE_FLAGS = new Set([
"trace-id", "trace-limit",
"type", "until", "url", "userId", "version-name", "versionName",
"verdict",
"webhook", "workflow-type-id", "workflowTypeId"
"webhook", "width", "workflow-type-id", "workflowTypeId"
]);
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "add", "all", "app-key",
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "allow-unreviewed", "allowUnreviewed", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
"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", "extract", "extract-expenses", "extractExpenses", "expire", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso",
"host", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"json-path", "key-id", "keyId", "keyword", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "repo",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
"report-id",
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reviewed-by", "reviewedBy",
@@ -137,7 +138,7 @@ export const KNOWN_FLAGS = new Set([
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
"until", "url", "userId", "v", "version", "version-name",
"verdict",
"versionName", "wait", "webhook", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
"workspace", "yes"
]);
@@ -168,6 +169,7 @@ export function parseArgs(argv: string[]): ParsedArgs {
const eqIdx = raw.indexOf("=");
const key = raw.slice(0, eqIdx);
const val = raw.slice(eqIdx + 1);
if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。");
options[key] = val;
continue;
}
@@ -436,3 +438,104 @@ export function materialPackFilePolicyOptions(
allowedExtensions
};
}
/**
* Read an `--expire` literal through the shared tokenizer, raising the two
* usage errors both link flags share. The format hint differs per flag only in
* which example it recommends.
*/
function readExpireToken(
value: string | boolean | number,
options: { formatHint: string; unitlessHint?: string }
): DurationToken {
if (typeof value === "number") {
if (!Number.isFinite(value) || value <= 0) {
throw usageError(
`Invalid --expire: ${value}。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。`
);
}
const token = tokenizeDuration(value, { units: EXPIRE_UNITS });
if (!token) throw usageError(`Invalid --expire: ${value}。`);
return token;
}
if (typeof value !== "string") {
throw usageError(`Invalid --expire: ${String(value)}。`);
}
const token = tokenizeDuration(value, { units: EXPIRE_UNITS });
if (!token) {
throw usageError(`Invalid --expire: '${value}'。必须为有效时长格式${options.formatHint}`);
}
if (token.value <= 0) {
throw usageError(
`Invalid --expire: '${value}'。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。`
);
}
return token;
}
export function parseDelegationExpireHours(
value: string | boolean | number | undefined,
defaultHours = 24
): number {
if (value === undefined || value === null || value === "") {
return defaultHours;
}
const token = readExpireToken(value, {
formatHint: ",推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)",
unitlessHint: ",推荐使用 '7d' 或 '24h'"
});
// Seal delegation links are hourly and capped at 7 days.
const rawHours = expireSeconds(token) / 3600;
if (rawHours > 168) {
throw usageError(
`Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。`
);
}
const finalHours = Math.floor(rawHours);
if (finalHours < 1) {
console.error(
`👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。`
);
return 1;
}
if (!Number.isInteger(rawHours)) {
console.error(
`👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。`
);
}
return finalHours;
}
export function parseHoseExpireSeconds(
value: string | boolean | number | undefined,
defaultSeconds = 7200
): number {
if (value === undefined || value === null || value === "") {
return defaultSeconds;
}
const token = readExpireToken(value, {
formatHint: ",推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)"
});
// A bare number is ambiguous: <=168 is read as hours, larger as seconds.
if (token.unit === undefined && token.value <= 168) {
console.error(
`👉 提示: 检测到未加单位的数值 ${token.value},已按 ${token.value} 小时 (${Math.round(token.value * 3600)}s) 自动换算。建议明确使用 --expire ${token.value}h。`
);
}
const seconds = Math.round(expireSeconds(token));
if (!Number.isFinite(seconds) || seconds <= 0) {
throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`);
}
return seconds;
}
+29 -7
View File
@@ -26,6 +26,7 @@ describe("CLI read-only classification", () => {
"auth status",
"auth test",
"auth doctor",
"auth seal-link list",
"doctor auth"
]);
@@ -134,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")
);
@@ -157,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]! });
@@ -165,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))
@@ -174,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([]);
});
});
+18 -3
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,7 +79,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
analytics: ["insight", "risks", "performance", "export"],
report: ["monthly", "review list"],
report: ["monthly", "data", "template", "chart venn", "validate", "render", "review list"],
source: ["config"],
skill: ["dump", "status"],
doctor: ["", "guide", "paths", "tenant", "auth"],
@@ -126,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.
@@ -136,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;
+5
View File
@@ -224,6 +224,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
return;
}
// Langfuse trace inspection needs no tenant: it authenticates with the
// compile-time injected read-only key pair, so it dispatches before corp
// selection (like probe/doctor) and never touches a Seal client.
+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;
}
+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;
}
+11 -8
View File
@@ -19,10 +19,11 @@ import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" wi
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/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 file19 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -38,10 +39,11 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/hose-enterprise-deploy.md": file16,
"references/hose-enterprise-init.md": file17,
"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": file19,
"references/rule-lightweight.md": file20,
"references/rule-lint.md": file21,
"references/staging-simulation-workflow.md": file22,
"references/webhook-resource-pack.md": file23,
};
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
@@ -73,6 +75,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/hose-enterprise-deploy.md",
"references/hose-enterprise-init.md",
"references/langfuse-trace.md",
"references/report-templates.md",
"references/rule-lightweight.md",
"references/rule-lint.md",
"references/staging-simulation-workflow.md",
+3 -1
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");
+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;
+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();
}
});
});
+43 -15
View File
@@ -1,12 +1,16 @@
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
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 CACHE_ROOT = ".cache/langfuse/traces";
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` (same cwd-relative layout), so the
// two tools share cached traces instead of re-fetching them.
// 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 = {
@@ -15,18 +19,21 @@ export type TraceCacheProject = {
};
/**
* Single-trace JSON cache keyed by traceId, written under `<cwd>/.cache`
* (gitignored). Holds the FULL raw trace (including observation IO) so outline,
* 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 {
constructor(private readonly project: TraceCacheProject) {}
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(
process.cwd(),
CACHE_ROOT,
this.root,
PROJECT_SEGMENT,
`${sanitizeSegment(traceId)}.json`
);
@@ -42,10 +49,25 @@ export class TraceCache {
}
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(this.path(traceId), "utf8");
const content = await readFile(path, "utf8");
const parsed = JSON.parse(content) as CachedTrace;
return parsed.cacheVersion === CACHE_VERSION ? parsed : undefined;
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;
}
@@ -63,11 +85,17 @@ export class TraceCache {
trace
};
const path = this.path(traceId);
await mkdir(dirname(path), { recursive: true });
await writeFile(path, `${JSON.stringify(cached, null, 2)}\n`, "utf8");
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 {
+246
View File
@@ -0,0 +1,246 @@
import { describe, expect, test } from "bun:test";
import {
ATTACHMENT_STAGES,
buildAttachmentFlow,
buildRuleFlow,
candidatesForStage,
classifyAttachmentEvidence,
collectEvidence,
RULE_FLOW_STAGES,
stageTerms,
summarizeEvidenceFields
} from "./flows.js";
import type { LangfuseObservationSummary } from "./types.js";
function observation(overrides: Partial<LangfuseObservationSummary> & { id: string }): LangfuseObservationSummary {
return {
traceId: "trace-1",
type: "SPAN",
...overrides
} as LangfuseObservationSummary;
}
describe("stage vocabulary", () => {
test("every stage resolves bilingual search terms", () => {
for (const stage of ATTACHMENT_STAGES) {
expect(stageTerms(stage, "attachment").length).toBeGreaterThan(0);
}
for (const stage of RULE_FLOW_STAGES) {
expect(stageTerms(stage, "rule").length).toBeGreaterThan(0);
}
});
test("matches observation names case-insensitively in either language", () => {
const observations = [
observation({ id: "a", name: "Attachment_Parsing" }),
observation({ id: "b", name: "文档解析 worker" }),
observation({ id: "c", name: "unrelated" })
];
const matched = candidatesForStage(observations, stageTerms("document_parsing", "attachment"));
expect(matched.map((item) => item.id)).toEqual(["b"]);
// The rule vocabulary is broader, so it also picks up the English name.
const ruleParsed = candidatesForStage(observations, stageTerms("document parsing", "rule"));
expect(ruleParsed.map((item) => item.id)).toEqual(["a", "b"]);
});
});
describe("collectEvidence", () => {
const obs = observation({
id: "obs-1",
name: "attachment parsing",
input: "folder/invoice.pdf",
output: "解析完成 invoice.pdf",
metadata: { file: "invoice.pdf" }
});
test("scans input, output and metadata and pads the snippet with context", () => {
const hits = collectEvidence(obs, ["invoice.pdf"], 5, 10);
expect(hits.map((hit) => hit.field)).toEqual(["input", "output", "metadata"]);
expect(hits[0]?.matched).toBe("invoice.pdf");
// contextChars=5 → 5 chars of lead-in before the needle (index 7 - 5 = 2).
expect(hits[0]?.snippet).toBe("lder/invoice.pdf");
// Needle sits at index 5 (4 CJK chars + space), so 5 chars of lead-in
// reaches the start of the string.
expect(hits[1]?.snippet).toBe("解析完成 invoice.pdf");
});
test("caps the number of hits so a pathological trace cannot balloon", () => {
const noisy = observation({
id: "obs-2",
input: "x".repeat(500),
output: "x".repeat(500),
metadata: { a: "x".repeat(500) }
});
expect(collectEvidence(noisy, ["x"], 10, 3)).toHaveLength(3);
expect(collectEvidence(noisy, ["nope"], 10, 3)).toHaveLength(0);
});
test("matching is case-insensitive on both sides", () => {
const hits = collectEvidence(obs, ["INVOICE.PDF"], 5, 10);
expect(hits.length).toBeGreaterThan(0);
// `matched` preserves the original casing from the trace text.
expect(hits[0]?.matched).toBe("invoice.pdf");
});
});
describe("classifyAttachmentEvidence", () => {
test("returns absent when nothing matched", () => {
expect(classifyAttachmentEvidence([], "file-1", "a.pdf")).toBe("absent");
});
test("filename-only and file-id-only when those are the sole hits", () => {
expect(
classifyAttachmentEvidence([{ matched: "a.pdf", snippet: "a.pdf" }], "file-1", "a.pdf")
).toBe("filename-only");
expect(
classifyAttachmentEvidence([{ matched: "file-1", snippet: "file-1" }], "file-1", "a.pdf")
).toBe("file-id-only");
});
test("some other hint wins over filename/id and is graded by the snippet", () => {
const other = [{ matched: "some extra token", snippet: "..." }];
expect(classifyAttachmentEvidence(other, "file-1", "a.pdf")).toBe("parsed-text");
expect(
classifyAttachmentEvidence(
[...other, { matched: "ocr", snippet: "run OCR on the scan" }],
"file-1",
"a.pdf"
)
).toBe("image-ocr");
expect(
classifyAttachmentEvidence(
[...other, { matched: "推断", snippet: "模型认为金额为 120" }],
"file-1",
"a.pdf"
)
).toBe("model-inferred");
});
test("with no identifiers every hit is an 'other hint' graded from the snippet", () => {
// fileName/fileId undefined → `matched !== undefined` is always true, so
// hasOtherHint fires and the snippet decides. Note: the union's "unknown"
// arm is unreachable — with both identifiers defined, hasOtherHint false
// already implies one of them matched. Kept as a defensive fallback only.
expect(
classifyAttachmentEvidence([{ matched: "x", snippet: "raw parsed text" }], undefined, undefined)
).toBe("parsed-text");
expect(
classifyAttachmentEvidence([{ matched: "x", snippet: "OCR pipeline output" }], undefined, undefined)
).toBe("image-ocr");
});
});
describe("summarizeEvidenceFields", () => {
test("counts hits per field and de-duplicates repeated matches", () => {
const summary = summarizeEvidenceFields([
{ field: "input", matched: "rule-a" } as never,
{ field: "input", matched: "rule-a" } as never,
{ field: "input", matched: "rule-b" } as never,
{ field: "output", matched: "rule-a" } as never
]);
expect(summary.input).toEqual({ count: 3, matched: ["rule-a", "rule-b"] });
expect(summary.output).toEqual({ count: 1, matched: ["rule-a"] });
expect(summary.metadata).toBeUndefined();
});
});
describe("buildAttachmentFlow", () => {
const observations = [
observation({ id: "p1", name: "attachment parsing", input: "读取 a.pdf" }),
observation({ id: "p2", name: "document_parsing", output: "解析 a.pdf 得到 120 元" }),
observation({ id: "p3", name: "approval_review", output: "OCR 结果 a.pdf 金额 120" }),
observation({ id: "other", name: "unrelated", input: "nothing here" })
];
test("labels a stage seen and classifies the evidence source", () => {
const stages = buildAttachmentFlow({
observations,
fileName: "a.pdf",
// A second, non-identifier needle is what makes hasOtherHint fire — a
// filename-only query can never reach the OCR/inference grading.
needles: ["a.pdf", "金额"],
contextChars: 20
});
expect(stages).toHaveLength(ATTACHMENT_STAGES.length);
expect(stages.map((stage) => stage.stage)).toEqual([...ATTACHMENT_STAGES]);
const parsing = stages.find((stage) => stage.stage === "document_parsing");
expect(parsing?.status).toBe("seen");
expect(parsing?.source).toBe("filename-only");
expect(parsing?.observations.map((item) => item.id)).toEqual(["p2"]);
expect(parsing?.evidence[0]?.observationId).toBe("p2");
const review = stages.find((stage) => stage.stage === "approval_review");
expect(review?.evidence.length).toBeGreaterThan(0);
// 金额 is a non-identifier hit, so hasOtherHint fires and "OCR" in the
// snippet grades this stage as image-ocr.
expect(review?.source).toBe("image-ocr");
});
test("stages with no matching observation report absent", () => {
const stages = buildAttachmentFlow({
observations,
fileId: "file-xyz",
needles: ["file-xyz"],
contextChars: 20
});
const understanding = stages.find(
(stage) => stage.stage === "image/document understanding"
);
expect(understanding?.status).toBe("absent");
expect(understanding?.source).toBe("absent");
expect(understanding?.observations).toEqual([]);
});
});
describe("buildRuleFlow", () => {
const observations = [
observation({ id: "r1", name: "rule matching", input: "规则:禁止差旅超标" }),
observation({ id: "g1", name: "generic span", output: "命中规则 禁止差旅超标" }),
observation({ id: "f1", name: "final review", output: "审核结论:驳回" })
];
test("falls back to every observation when no stage name matches", () => {
const flow = buildRuleFlow({
observations,
needles: ["禁止差旅超标"],
contextChars: 30
});
expect(flow.stages.ruleMatching?.matched).toBe(true);
expect(flow.stages.ruleMatching?.matchedObservationIds).toContain("r1");
// g1 sits in a generically-named span, reachable only via the fallback pool.
expect(flow.relatedObservationIds).toContain("g1");
expect(flow.evidenceCount).toBeGreaterThan(0);
// No observation is named for "document parsing", so the stage has zero
// *named* candidates but still scans the whole trace via the fallback —
// that is what keeps a rule applied inside a generically-named span visible.
const documentParsing = flow.stages.documentParsing;
expect(documentParsing?.observations).toEqual([]);
expect(documentParsing?.matched).toBe(true);
expect(documentParsing?.matchedObservationIds).toContain("r1");
});
test("reports extracted fields grouped by source field", () => {
const flow = buildRuleFlow({
observations,
needles: ["禁止差旅超标", "驳回"],
contextChars: 30
});
expect(flow.stages.ruleMatching?.extractedFields.input?.matched).toEqual(["禁止差旅超标"]);
expect(flow.stages.finalReview?.extractedFields.output?.matched).toEqual(["驳回"]);
expect(flow.stages.finalReview?.matched).toBe(true);
});
test("returns the documented stage keys in order", () => {
const flow = buildRuleFlow({ observations, needles: ["nothing-matches"], contextChars: 30 });
expect(Object.keys(flow.stages)).toEqual(["ruleMatching", "documentParsing", "finalReview"]);
expect(flow.evidenceCount).toBe(0);
expect(flow.relatedObservationIds).toEqual([]);
});
});
+242
View File
@@ -0,0 +1,242 @@
import { stringifyValue } from "./search.js";
import { summarizeObservation, uniqueStrings } from "./summary.js";
import type { LangfuseObservationSummary } from "./types.js";
/**
* Deterministic flow reconstruction from cached Langfuse fields.
*
* Everything here is plain text matching over observation name/input/output/
* metadata — no network, no model calls. Both flows answer "where does this
* file or rule show up across the stages", so they share one evidence
* collector and differ only in their stage vocabulary and in what they report.
*
* The stage word lists are bilingual heuristics tuned against real traces;
* they are deliberately data, not logic, so tuning them cannot change a code
* path.
*/
export const ATTACHMENT_STAGES = [
"attachment parsing",
"image/document understanding",
"pre_analysis",
"document_parsing",
"approval_review"
] as const;
export const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const;
export type AttachmentStage = (typeof ATTACHMENT_STAGES)[number];
export type RuleFlowStage = (typeof RULE_FLOW_STAGES)[number];
export type EvidenceField = "input" | "output" | "metadata";
export interface EvidenceHit {
observationId: string;
name?: string;
type?: string;
field: EvidenceField;
matched: string;
snippet: string;
}
export type AttachmentSource =
| "filename-only"
| "file-id-only"
| "parsed-text"
| "image-ocr"
| "model-inferred"
| "absent"
| "unknown";
const ATTACHMENT_STAGE_TERMS: Record<AttachmentStage, string[]> = {
"attachment parsing": ["attachment", "附件", "parse_attachment", "attachment_parsing"],
"image/document understanding": [
"understanding",
"vision",
"image",
"document_understanding",
"文档理解",
"图片理解"
],
pre_analysis: ["pre_analysis", "pre-analysis", "预分析"],
document_parsing: ["document_parsing", "document parsing", "文档解析"],
approval_review: ["approval_review", "approval review", "审核"]
};
const RULE_STAGE_TERMS: Record<RuleFlowStage, string[]> = {
"rule matching": ["rule", "规则", "policy", "match", "matching", "命中"],
"document parsing": ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"],
"final review": ["approval_review", "approval review", "review", "审核", "结论", "final"]
};
export function stageTerms(
stage: AttachmentStage | RuleFlowStage,
vocabulary: "attachment" | "rule"
): string[] {
return vocabulary === "attachment"
? ATTACHMENT_STAGE_TERMS[stage as AttachmentStage]
: RULE_STAGE_TERMS[stage as RuleFlowStage];
}
/** Observations whose name mentions any of the stage's terms. */
export function candidatesForStage(
observations: LangfuseObservationSummary[],
terms: string[]
): LangfuseObservationSummary[] {
const lowered = terms.map((term) => term.toLowerCase());
return observations.filter((observation) => {
const name = observation.name?.toLowerCase() ?? "";
return lowered.some((term) => name.includes(term));
});
}
/**
* Scan every field of an observation for each needle and return bounded,
* context-padded hits. The cap keeps a pathological trace from ballooning the
* response.
*/
export function collectEvidence(
observation: LangfuseObservationSummary,
needles: string[],
contextChars: number,
limit: number
): EvidenceHit[] {
const fields = [
["input", stringifyValue(observation.input)],
["output", stringifyValue(observation.output)],
["metadata", stringifyValue(observation.metadata)]
] as const;
const evidence: EvidenceHit[] = [];
for (const [field, text] of fields) {
const normalized = text.toLowerCase();
for (const needle of needles) {
const index = normalized.indexOf(needle.toLowerCase());
if (index < 0) continue;
evidence.push({
observationId: observation.id,
name: observation.name,
type: observation.type,
field,
matched: text.slice(index, index + needle.length),
snippet: text.slice(
Math.max(0, index - contextChars),
Math.min(text.length, index + needle.length + contextChars)
)
});
}
}
return evidence.slice(0, limit);
}
/**
* Decide where an attachment's presence appears to come from. Labels describe
* the text that was found — they never assert that a model understood the file.
*/
export function classifyAttachmentEvidence(
evidence: Array<{ matched: string; snippet: string }>,
fileId: string | undefined,
fileName: string | undefined
): AttachmentSource {
if (evidence.length === 0) return "absent";
const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false;
const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false;
const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName);
if (hasOtherHint) {
const joined = evidence
.map((item) => item.snippet)
.join("\n")
.toLowerCase();
if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr";
if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred";
return "parsed-text";
}
if (hasFileName) return "filename-only";
if (hasFileId) return "file-id-only";
return "unknown";
}
/** Count hits per field, de-duplicating the matched substrings. */
export function summarizeEvidenceFields(
evidence: EvidenceHit[]
): Record<string, { count: number; matched: string[] }> {
const summary: Record<string, { count: number; matched: string[] }> = {};
for (const item of evidence) {
const entry = summary[item.field];
if (entry) {
entry.count += 1;
if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched);
} else {
summary[item.field] = { count: 1, matched: [item.matched] };
}
}
return summary;
}
export function buildAttachmentFlow(options: {
observations: LangfuseObservationSummary[];
fileId?: string;
fileName?: string;
needles: string[];
contextChars: number;
}) {
const { observations, fileId, fileName, needles, contextChars } = options;
return ATTACHMENT_STAGES.map((stage) => {
const candidates = candidatesForStage(observations, stageTerms(stage, "attachment"));
const evidence = candidates.flatMap((observation) =>
collectEvidence(observation, needles, contextChars, 10)
);
const source = classifyAttachmentEvidence(evidence, fileId, fileName);
return {
stage,
source,
status: source === "absent" ? ("absent" as const) : ("seen" as const),
observations: candidates.map(summarizeObservation),
evidence
};
});
}
export function buildRuleFlow(options: {
observations: LangfuseObservationSummary[];
needles: string[];
contextChars: number;
}) {
const { observations, needles, contextChars } = options;
const stages = RULE_FLOW_STAGES.map((stage) => {
const candidates = candidatesForStage(observations, stageTerms(stage, "rule"));
// Unlike attachment flow, a rule query falls back to every observation:
// a rule can be applied inside a generically-named span.
const pool = candidates.length ? candidates : observations;
const evidence = pool
.flatMap((observation) => collectEvidence(observation, needles, contextChars, 20))
.slice(0, 20);
return {
stage,
matched: evidence.length > 0,
matchedObservationIds: uniqueStrings(evidence.map((item) => item.observationId)),
observations: candidates.map(summarizeObservation),
extractedFields: summarizeEvidenceFields(evidence),
evidence
};
});
const allEvidence = stages.flatMap((stage) => stage.evidence);
return {
stages: {
ruleMatching: stages[0],
documentParsing: stages[1],
finalReview: stages[2]
},
relatedObservationIds: uniqueStrings(allEvidence.map((item) => item.observationId)),
evidenceCount: allEvidence.length
};
}
+9 -6
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, realpathSync, rmSync } from "node:fs";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CliError } from "../../core/errors.js";
@@ -52,16 +52,21 @@ function sampleTrace(): LangfuseTraceSummary {
}
let originalCwd: string;
let originalCacheDir: string | undefined;
let workdir: string;
beforeEach(() => {
originalCwd = process.cwd();
originalCacheDir = process.env.SEAL_USE_LANGFUSE_CACHE_DIR;
workdir = mkdtempSync(join(tmpdir(), "seal-langfuse-test-"));
process.env.SEAL_USE_LANGFUSE_CACHE_DIR = join(workdir, "cache");
process.chdir(workdir);
});
afterEach(() => {
process.chdir(originalCwd);
if (originalCacheDir === undefined) delete process.env.SEAL_USE_LANGFUSE_CACHE_DIR;
else process.env.SEAL_USE_LANGFUSE_CACHE_DIR = originalCacheDir;
rmSync(workdir, { recursive: true, force: true });
});
@@ -72,13 +77,11 @@ async function seedCache(trace: LangfuseTraceSummary = sampleTrace()) {
}
describe("trace cache", () => {
test("writes the langfuse-home compatible path and round-trips", async () => {
test("writes the langfuse-home compatible format in the configured cache directory and round-trips", async () => {
const cache = await seedCache();
// process.cwd() resolves symlinks, so compare against the physical tmpdir
// (macOS /var -> /private/var).
const physicalWorkdir = realpathSync(workdir);
// The cache root is explicit and independent of cwd, including macOS /var symlinks.
expect(cache.path("trace-1")).toBe(
join(physicalWorkdir, ".cache", "langfuse", "traces", "default", "trace-1.json")
join(workdir, "cache", "default", "trace-1.json")
);
const read = await new TraceCache({ baseUrl: CONFIG.baseUrl }).read("trace-1");
+17 -278
View File
@@ -3,7 +3,9 @@ import { LangfuseApi } from "./api.js";
import { TraceCache } from "./cache.js";
import type { LangfuseConfig } from "./config.js";
import { LangfuseClient } from "./client.js";
import { buildAttachmentFlow, buildRuleFlow } from "./flows.js";
import { searchTrace, stringifyValue } from "./search.js";
import { byteLength, objectKeys, summarizeObservation, summarizeTrace, uniqueStrings } from "./summary.js";
import type {
AttachmentFlowInput,
CachedTrace,
@@ -28,14 +30,6 @@ const DEFAULT_IO_CHARS = 8_000;
const DEFAULT_PREVIEW_CHARS = 160;
const FULL_OUTPUT_WARNING_THRESHOLD = 30_000;
const OUTLINE_FULL_FIELD_THRESHOLD = 20_000;
const ATTACHMENT_STAGES = [
"attachment parsing",
"image/document understanding",
"pre_analysis",
"document_parsing",
"approval_review"
] as const;
const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const;
/**
* Read-only Langfuse trace service, ported from langfuse-home.
@@ -278,15 +272,17 @@ export class LangfuseService {
}
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
const trace = cached.trace;
const contextChars = clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500);
const needles = [input.fileId, input.fileName, ...(input.contentHints ?? [])].filter(
(value): value is string => Boolean(value?.trim())
);
const observations = trace.observations ?? [];
const stages = ATTACHMENT_STAGES.map((stage) =>
inspectAttachmentStage(stage, observations, needles, input.fileId, input.fileName, contextChars)
);
const stages = buildAttachmentFlow({
observations: cached.trace.observations ?? [],
fileId: input.fileId,
fileName: input.fileName,
needles,
contextChars
});
return {
traceId: input.traceId,
@@ -304,27 +300,20 @@ export class LangfuseService {
async getTraceRuleFlow(input: TraceRuleFlowInput) {
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
const trace = cached.trace;
const contextChars = clamp(input.contextChars ?? 300, 20, 500);
const needles = uniqueStrings([input.rule, ...(input.ruleHints ?? [])]);
const observations = trace.observations ?? [];
const stageResults = RULE_FLOW_STAGES.map((stage) =>
inspectRuleStage(stage, observations, needles, contextChars)
);
const allEvidence = stageResults.flatMap((stage) => stage.evidence);
const relatedObservationIds = uniqueStrings(allEvidence.map((item) => item.observationId));
const flow = buildRuleFlow({
observations: cached.trace.observations ?? [],
needles: uniqueStrings([input.rule, ...(input.ruleHints ?? [])]),
contextChars
});
return {
traceId: input.traceId,
rule: input.rule,
ruleHints: input.ruleHints,
stages: {
ruleMatching: stageResults[0],
documentParsing: stageResults[1],
finalReview: stageResults[2]
},
relatedObservationIds,
evidenceCount: allEvidence.length,
stages: flow.stages,
relatedObservationIds: flow.relatedObservationIds,
evidenceCount: flow.evidenceCount,
note:
"Rule flow is deterministic text evidence extraction from cached Langfuse fields. It reports where the rule or hints appear; it does not infer hidden model reasoning or prove causality beyond the recorded trace text.",
cache: {
@@ -436,45 +425,6 @@ function buildOutlineWarnings(
return warnings.slice(0, 20);
}
function summarizeTrace(trace: LangfuseTraceSummary) {
return {
id: trace.id,
name: trace.name,
projectId: trace.projectId,
sessionId: trace.sessionId,
userId: trace.userId,
timestamp: trace.timestamp,
environment: trace.environment,
tags: trace.tags,
inputLength: stringifyValue(trace.input).length,
outputLength: stringifyValue(trace.output).length,
metadata: trace.metadata,
latency: trace.latency,
totalCost: trace.totalCost
};
}
function summarizeObservation(observation: LangfuseObservationSummary) {
return {
id: observation.id,
traceId: observation.traceId,
parentObservationId: observation.parentObservationId,
type: observation.type,
name: observation.name,
startTime: observation.startTime,
endTime: observation.endTime,
model: observation.providedModelName ?? observation.model,
inputLength: stringifyValue(observation.input).length,
outputLength: stringifyValue(observation.output).length,
inputBytes: byteLength(stringifyValue(observation.input)),
outputBytes: byteLength(stringifyValue(observation.output)),
metadataKeys: objectKeys(observation.metadata),
usageDetails: observation.usageDetails,
costDetails: observation.costDetails,
totalCost: observation.totalCost
};
}
function buildTraceUrl(baseUrl: string, projectId: string, traceId: string): string {
const url = new URL(
`/project/${encodeURIComponent(projectId)}/traces/${encodeURIComponent(traceId)}`,
@@ -545,209 +495,6 @@ function parsePath(path: string): Array<string | number> {
return segments;
}
function inspectAttachmentStage(
stage: (typeof ATTACHMENT_STAGES)[number],
observations: LangfuseObservationSummary[],
needles: string[],
fileId: string | undefined,
fileName: string | undefined,
contextChars: number
) {
const stageTerms = stageSearchTerms(stage);
const candidates = observations.filter((observation) => {
const name = observation.name?.toLowerCase() ?? "";
return stageTerms.some((term) => name.includes(term));
});
const evidence = candidates.flatMap((observation) =>
collectAttachmentEvidence(observation, needles, contextChars)
);
const source = classifyAttachmentEvidence(evidence, fileId, fileName);
return {
stage,
source,
status: source === "absent" ? "absent" : "seen",
observations: candidates.map(summarizeObservation),
evidence
};
}
function stageSearchTerms(stage: (typeof ATTACHMENT_STAGES)[number]): string[] {
switch (stage) {
case "attachment parsing":
return ["attachment", "附件", "parse_attachment", "attachment_parsing"];
case "image/document understanding":
return ["understanding", "vision", "image", "document_understanding", "文档理解", "图片理解"];
case "pre_analysis":
return ["pre_analysis", "pre-analysis", "预分析"];
case "document_parsing":
return ["document_parsing", "document parsing", "文档解析"];
case "approval_review":
return ["approval_review", "approval review", "审核"];
}
}
function collectAttachmentEvidence(
observation: LangfuseObservationSummary,
needles: string[],
contextChars: number
): Array<{
observationId: string;
name?: string;
field: "input" | "output" | "metadata";
matched: string;
snippet: string;
}> {
const fields = [
["input", stringifyValue(observation.input)],
["output", stringifyValue(observation.output)],
["metadata", stringifyValue(observation.metadata)]
] as const;
const evidence: ReturnType<typeof collectAttachmentEvidence> = [];
for (const [field, text] of fields) {
const normalized = text.toLowerCase();
for (const needle of needles) {
const index = normalized.indexOf(needle.toLowerCase());
if (index < 0) continue;
evidence.push({
observationId: observation.id,
name: observation.name,
field,
matched: text.slice(index, index + needle.length),
snippet: text.slice(
Math.max(0, index - contextChars),
Math.min(text.length, index + needle.length + contextChars)
)
});
}
}
return evidence.slice(0, 10);
}
function classifyAttachmentEvidence(
evidence: Array<{ matched: string; snippet: string; field?: string }>,
fileId: string | undefined,
fileName: string | undefined
): "filename-only" | "file-id-only" | "parsed-text" | "image-ocr" | "model-inferred" | "absent" | "unknown" {
if (evidence.length === 0) return "absent";
const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false;
const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false;
const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName);
if (hasOtherHint) {
const joined = evidence
.map((item) => item.snippet)
.join("\n")
.toLowerCase();
if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr";
if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred";
return "parsed-text";
}
if (hasFileName && !hasOtherHint) return "filename-only";
if (hasFileId && !hasOtherHint) return "file-id-only";
return "unknown";
}
function inspectRuleStage(
stage: (typeof RULE_FLOW_STAGES)[number],
observations: LangfuseObservationSummary[],
needles: string[],
contextChars: number
) {
const stageTerms = ruleStageSearchTerms(stage);
const candidates = observations.filter((observation) => {
const name = observation.name?.toLowerCase() ?? "";
return stageTerms.some((term) => name.includes(term));
});
const candidatePool = candidates.length ? candidates : observations;
const evidence = candidatePool
.flatMap((observation) => collectRuleEvidence(observation, needles, contextChars))
.slice(0, 20);
const matchedObservationIds = uniqueStrings(evidence.map((item) => item.observationId));
return {
stage,
matched: evidence.length > 0,
matchedObservationIds,
observations: candidates.map(summarizeObservation),
extractedFields: summarizeEvidenceFields(evidence),
evidence
};
}
function ruleStageSearchTerms(stage: (typeof RULE_FLOW_STAGES)[number]): string[] {
switch (stage) {
case "rule matching":
return ["rule", "规则", "policy", "match", "matching", "命中"];
case "document parsing":
return ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"];
case "final review":
return ["approval_review", "approval review", "review", "审核", "结论", "final"];
}
}
function collectRuleEvidence(
observation: LangfuseObservationSummary,
needles: string[],
contextChars: number
): Array<{
observationId: string;
name?: string;
type?: string;
field: "input" | "output" | "metadata";
matched: string;
snippet: string;
}> {
const fields = [
["input", stringifyValue(observation.input)],
["output", stringifyValue(observation.output)],
["metadata", stringifyValue(observation.metadata)]
] as const;
const evidence: ReturnType<typeof collectRuleEvidence> = [];
for (const [field, text] of fields) {
const normalized = text.toLowerCase();
for (const needle of needles) {
const index = normalized.indexOf(needle.toLowerCase());
if (index < 0) continue;
evidence.push({
observationId: observation.id,
name: observation.name,
type: observation.type,
field,
matched: text.slice(index, index + needle.length),
snippet: text.slice(
Math.max(0, index - contextChars),
Math.min(text.length, index + needle.length + contextChars)
)
});
}
}
return evidence;
}
function summarizeEvidenceFields(
evidence: Array<{ field: "input" | "output" | "metadata"; matched: string }>
): Record<string, { count: number; matched: string[] }> {
const summary: Record<string, { count: number; matched: string[] }> = {};
for (const item of evidence) {
const entry = summary[item.field];
if (entry) {
entry.count += 1;
if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched);
} else {
summary[item.field] = { count: 1, matched: [item.matched] };
}
}
return summary;
}
function uniqueStrings(values: Array<string | undefined>): string[] {
return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))];
}
function hasValue(value: unknown): boolean {
return stringifyValue(value).length > 0;
}
@@ -759,14 +506,6 @@ function truncateMiddle(text: string, maxChars: number): string {
return `${text.slice(0, head)}\n...<truncated>...\n${text.slice(text.length - tail)}`;
}
function objectKeys(value: unknown): string[] {
return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
}
function byteLength(value: string): number {
return Buffer.byteLength(value, "utf8");
}
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
+62
View File
@@ -0,0 +1,62 @@
import { stringifyValue } from "./search.js";
import type { LangfuseObservationSummary, LangfuseTraceSummary } from "./types.js";
/**
* Size-before-content projections of a cached trace.
*
* Both the outline/search responses and the flow evidence builders need these
* (a stage reports its candidate observations in summary form), so they live
* here rather than in `service.ts` — otherwise `flows.ts` would have to import
* the service that imports it back.
*/
export function summarizeTrace(trace: LangfuseTraceSummary) {
return {
id: trace.id,
name: trace.name,
projectId: trace.projectId,
sessionId: trace.sessionId,
userId: trace.userId,
timestamp: trace.timestamp,
environment: trace.environment,
tags: trace.tags,
inputLength: stringifyValue(trace.input).length,
outputLength: stringifyValue(trace.output).length,
metadata: trace.metadata,
latency: trace.latency,
totalCost: trace.totalCost
};
}
export function summarizeObservation(observation: LangfuseObservationSummary) {
return {
id: observation.id,
traceId: observation.traceId,
parentObservationId: observation.parentObservationId,
type: observation.type,
name: observation.name,
startTime: observation.startTime,
endTime: observation.endTime,
model: observation.providedModelName ?? observation.model,
inputLength: stringifyValue(observation.input).length,
outputLength: stringifyValue(observation.output).length,
inputBytes: byteLength(stringifyValue(observation.input)),
outputBytes: byteLength(stringifyValue(observation.output)),
metadataKeys: objectKeys(observation.metadata),
usageDetails: observation.usageDetails,
costDetails: observation.costDetails,
totalCost: observation.totalCost
};
}
export function objectKeys(value: unknown): string[] {
return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
}
export function byteLength(value: string): number {
return Buffer.byteLength(value, "utf8");
}
export function uniqueStrings(values: Array<string | undefined>): string[] {
return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))];
}
+45 -5
View File
@@ -10,6 +10,7 @@ import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { redactSensitiveText } from "../../core/redact.js";
import { safetyBlocked } from "../../core/errors.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
ApprovalDocumentListData,
@@ -140,7 +141,13 @@ export async function deleteApprovalRule(client: KyInstance, ruleId: string): Pr
}
export async function recodeApprovalRules(client: KyInstance): Promise<unknown> {
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false });
// Legacy clear/sync callers may reset an EMPTY draft's allocation counter.
// Renumbering existing rules must go through the ticketed recode capability.
const draft = await listApprovalRules(client);
if (draft.rules.length > 0) {
throw safetyBlocked("禁止隐式重排非空草稿,请使用 rules recode 的两阶段确认流程。");
}
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false, retry: 0 });
const body = await response.json().catch(() => ({}));
return z.object({
ok: z.boolean(),
@@ -153,6 +160,19 @@ export async function recodeApprovalRules(client: KyInstance): Promise<unknown>
});
}
/** Called only after the shared recode capability consumes its confirmation ticket. */
export async function executeApprovalRulesRecode(client: KyInstance) {
const response = await client.post("api/v1/rules/batch-recode", { retry: 0 });
const body = await response.json() as { data?: unknown };
const result = z.object({
activeRules: z.number().int().nonnegative(),
pendingDeleteRules: z.number().int().nonnegative(),
nextCode: z.number().int().nonnegative()
}).safeParse(body.data ?? body);
if (!result.success) throw new Error("规则重排接口返回了无效结果,请回读当前草稿确认状态。");
return result.data;
}
export async function listApprovalRuleVersions(client: KyInstance): Promise<RuleSetVersion[]> {
return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema));
}
@@ -842,6 +862,24 @@ export async function syncHosecloudOutbound(
return json.data ?? json;
}
export async function postHosecloudOutbound(
client: KyInstance,
signKey: string,
payload: {
flowId: string;
nodeId: string;
messageId: string;
rejectionNum: number;
corporationId: string;
}
): Promise<{ success?: boolean; message?: string; [key: string]: unknown }> {
const response = await client.post(`api/hosecloud/outbound?config_id=${encodeURIComponent(signKey)}`, {
json: payload
});
const json = (await response.json().catch(() => ({}))) as { data?: unknown };
return (json.data ?? json) as { success?: boolean; message?: string; [key: string]: unknown };
}
export async function uploadMaterialPackage(
client: KyInstance,
params: { fileName: string; fileBuffer: Uint8Array }
@@ -882,7 +920,7 @@ export async function listDelegations(client: KyInstance): Promise<SealDelegatio
export async function createDelegation(
client: KyInstance,
params?: { note?: string }
params?: { note?: string; expiresInHours?: number }
): Promise<SealDelegationCreateResult> {
return unwrap(
await client.post("api/v1/delegation/create", { json: params ?? {} }),
@@ -1162,7 +1200,7 @@ export async function loginWithPhonePassword(
export async function createDelegationForUser(
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
createClientForToken: (token: string) => Promise<KyInstance>,
corp?: CorpConfig
): Promise<{
@@ -1249,7 +1287,8 @@ export async function createDelegationForUser(
if (targetUserSealToken) {
const userClient = await createClientForToken(targetUserSealToken);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
note: params.note ?? `Delegation generated by admin for ${user.name}`,
expiresInHours: params.expiresInHours
});
return {
@@ -1287,7 +1326,8 @@ export async function createDelegationForUser(
const userClient = await createClientForToken(token);
const delegation = await createDelegation(userClient, {
note: params.note ?? `Delegation generated by admin for ${user.name}`
note: params.note ?? `Delegation generated by admin for ${user.name}`,
expiresInHours: params.expiresInHours
});
return {
@@ -9,7 +9,7 @@ import {
sanitizeFileName,
type FetchLike
} from "./attachments.js";
import type { ApprovalRun } from "./types.js";
import type { ApprovalRun } from "../types.js";
describe("attachments domain", () => {
let tmpDir: string;
@@ -1,6 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import type { ApprovalRun } from "./types.js";
import type { ApprovalRun } from "../types.js";
export interface ApprovalRunAttachment {
path: string;
@@ -14,8 +14,8 @@ import {
resolveExportDateRange,
resolveOutputFilePath,
exportApprovalRunsToExcel
} from "./approval-runs-export.js";
import type { CorpConfig } from "../../core/config/types.js";
} from "./export.js";
import type { CorpConfig } from "../../../core/config/types.js";
describe("approval-runs-export helpers", () => {
test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => {
@@ -3,17 +3,17 @@ import { homedir } from "node:os";
import { dirname, extname, resolve } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow,
type HoseOpenStaffItem,
type HoseRunAlignment
} from "../hose/index.js";
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
} from "../../hose/index.js";
import type { ApprovalRun, ApprovalRunListData } from "../types.js";
export interface ApprovalRunsExportOptions {
limit?: number;
+38 -13
View File
@@ -3,8 +3,8 @@ import type { KyInstance } from "ky";
import * as api from "../api.js";
import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
@@ -465,7 +465,18 @@ export const approvalRunsCapabilities = [
}
const record = await resolveApprovalRunForUrl(client, params);
const source = context.corp.source;
const hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
let hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
const flowId = record?.sourceDocumentId;
if (hoseDocumentUrl) {
if (flowId && hoseDocumentUrl.includes("backlogId=") && !hoseDocumentUrl.includes("#/")) {
hoseDocumentUrl = `${hoseDocumentUrl}#/backlogDetail/false/${encodeURIComponent(flowId)}`;
}
} else if (source.type === "hose" && flowId) {
const hoseDomain = normalizeUrl(source.domain);
const encodedFlowId = encodeURIComponent(flowId);
const corpId = encodeURIComponent(source.corpId);
hoseDocumentUrl = `${hoseDomain}/web/thirdparty.html?ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${encodedFlowId}&backlogId=#/backlogDetail/false/${encodedFlowId}`;
}
const sealBaseUrl = resolveSealBaseUrl(context.corp);
const sealResultUrl = `${sealBaseUrl}/approval-result/${record.id}`;
@@ -478,13 +489,12 @@ export const approvalRunsCapabilities = [
const expiresIn = params.expiresIn ?? 7200;
let ssoUrl: string | undefined;
let sealSsoUrl: string | undefined;
let hoseSsoUrl: string | undefined;
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
let warning: string | undefined;
if (useAutoLogin) {
if (isHoseDoc) {
throw new Error("Auto-login (--auto-login) is only supported for Seal AI audit links (type: seal-result). To generate an auto-login link for Hose document page, please use: seal-use auth hose-link");
}
if (source.type !== "hose") {
throw new Error(
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
@@ -498,7 +508,17 @@ export const approvalRunsCapabilities = [
}
const targetPath = `/approval-result/${record.id}`;
ssoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
sealSsoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
if (record?.sourceDocumentId) {
const hoseDomain = normalizeUrl(source.domain);
const flowId = encodeURIComponent(record.sourceDocumentId);
const corpId = encodeURIComponent(source.corpId);
const token = encodeURIComponent(provisionalToken);
hoseSsoUrl = `${hoseDomain}/web/thirdparty.html?accessToken=${token}&ekbCorpId=${corpId}&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=${flowId}&backlogId=#/backlogDetail/false/${flowId}`;
}
ssoUrl = isHoseDoc ? (hoseSsoUrl ?? sealSsoUrl) : sealSsoUrl;
try {
const me = await api.getMe(client);
@@ -516,18 +536,21 @@ export const approvalRunsCapabilities = [
const userName = identity.name ?? "企业成员";
const roleLabel = identity.isAdmin ? " (管理员)" : "";
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
const targetSystem = isHoseDoc ? "合思 (Hose)" : "Seal AI";
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 ${targetSystem} 拥有对应操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
console.error(
`⚠️ 安全警示 (免密直达链接):\n` +
`• 身份主体:${userName}${roleLabel}\n` +
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
`• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!`
`• 目标系统:${targetSystem}\n` +
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留会话\n` +
`• 安全边界:仅限内部排查,严禁在外部公开分享!`
);
}
const activeUrl = isHoseDoc ? hoseDocumentUrl : (useAutoLogin ? ssoUrl : sealResultUrl);
const activeUrl = isHoseDoc
? (useAutoLogin ? (hoseSsoUrl ?? hoseDocumentUrl) : hoseDocumentUrl)
: (useAutoLogin ? sealSsoUrl : sealResultUrl);
const activeMode = useAutoLogin ? "auto_login" : "direct";
return {
@@ -536,6 +559,8 @@ export const approvalRunsCapabilities = [
mode: activeMode,
sealResultUrl,
hoseDocumentUrl,
sealSsoUrl,
hoseSsoUrl,
// Legacy compatibility fields
documentUrl: hoseDocumentUrl,
ssoUrl,
@@ -549,7 +574,7 @@ export const approvalRunsCapabilities = [
sourceSystem: record.sourceSystem,
missing: {
hoseDocumentUrl: !hoseDocumentUrl
? `该审批运行未回写 hosecloudViewUrl,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
? `该审批运行未回写 hosecloudViewUrl 且缺少 sourceDocumentId,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。`
: undefined
}
};
@@ -4,10 +4,10 @@ import { z } from "zod";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CorpConfig } from "../../core/config/types.js";
import { CliError } from "../../core/errors.js";
import { saveRuleMappingSnapshot } from "./rule-mapping.js";
import { buildRulePushPlan, findSealCapability, sealCapabilities } from "./capabilities.js";
import { CorpConfig } from "../../../core/config/types.js";
import { CliError } from "../../../core/errors.js";
import { saveRuleMappingSnapshot } from "../rules/mapping.js";
import { buildRulePushPlan, findSealCapability, sealCapabilities } from "../capabilities.js";
type CapabilityHandler = (
client: KyInstance,
@@ -892,6 +892,52 @@ describe("sealCapabilities", () => {
expect(result.sealResultUrl).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
});
test("approval run url synthesizes hoseDocumentUrl from source.domain and sourceDocumentId when hosecloudViewUrl is missing", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
expect(tool).toBeDefined();
const handler = tool!.handler as CapabilityHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ recordId: "run-2" },
fakeHoseContext()
) as {
hoseDocumentUrl?: string;
documentUrl?: string;
sealResultUrl?: string;
missing?: Record<string, string>;
};
const expectedHoseUrl = "https://app.ekuaibao.com/web/thirdparty.html?ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
expect(result.hoseDocumentUrl).toBe(expectedHoseUrl);
expect(result.documentUrl).toBe(expectedHoseUrl);
expect(result.missing?.hoseDocumentUrl).toBeUndefined();
});
test("approval run url supports auto-login for hose-document", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
expect(tool).toBeDefined();
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
const handler = tool!.handler as CapabilityHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ recordId: "run-2", type: "hose-document", autoLogin: true },
fakeHoseContext()
) as {
url?: string;
hoseSsoUrl?: string;
type?: string;
mode?: string;
};
const expectedSsoUrl = "https://app.ekuaibao.com/web/thirdparty.html?accessToken=close-token&ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
expect(result.type).toBe("hose_document");
expect(result.mode).toBe("auto_login");
expect(result.url).toBe(expectedSsoUrl);
expect(result.hoseSsoUrl).toBe(expectedSsoUrl);
});
test("approval run url throws error without a document lookup", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
expect(tool).toBeDefined();
@@ -1170,6 +1216,55 @@ describe("sealCapabilities", () => {
});
});
test("sealReportDataGet returns lightweight structured report data payload", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealReportDataGet");
expect(tool).toBeDefined();
const handler = tool!.handler as CapabilityHandler;
const mockClient = {
get: async () => ({
json: async () => ({
data: {
records: [
{
id: "run-rep-1",
sourceDocumentSN: "SN-001",
result: { decision: "REJECT", summary: "缺失发票", riskPoints: ["缺失发票"] },
pipelineData: { humanResult: "APPROVE" },
document: { fields: [{ key: "specificationId", value: "差旅报销" }] }
}
],
total: 1
}
})
}),
post: async () => ({
json: async () => ({
data: {
approvalCount: 1,
accuracy: 0,
automationRate: 0,
riskCount: 1,
avgDuration: 15
}
})
})
} as unknown as KyInstance;
const res = await handler(mockClient, { month: "2026-08" }, fakeContext()) as {
period: { month: string };
metrics: { approvalCount: number; aiAccuracy: number };
divergedRuns: Array<{ sn: string; triggeredConditions: string[] }>;
charts: { vennSvg: string };
};
expect(res.period.month).toBe("2026-08");
expect(res.metrics.approvalCount).toBe(1);
expect(res.divergedRuns).toHaveLength(1);
expect(res.divergedRuns[0]?.sn).toBe("SN-001");
expect(res.divergedRuns[0]?.triggeredConditions).toContain("缺失发票");
expect(res.charts.vennSvg).toContain("<svg");
});
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealDeployHosecloudConfigure");
expect(tool).toBeDefined();
@@ -1198,7 +1293,8 @@ describe("sealCapabilities", () => {
apiSecret: "test-sk",
apiOrigin: "custom",
customApiUrl: "https://dd2.hosecloud.com",
outboundName: "DingTalk AI Audit"
outboundName: "DingTalk AI Audit",
confirm: true
},
fakeContext()
) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } };
@@ -1364,6 +1460,15 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
},
createdAt: 1780898164536
}
: url === "api/v1/approvals/run-2"
? {
id: "run-2",
status: "completed",
taskMode: "assisted",
sourceDocumentSN: "B26001808",
sourceDocumentId: "doc-source-2",
createdAt: 1780887698055
}
: {
total: 3,
records: [
+203 -26
View File
@@ -3,9 +3,19 @@ import type { KyInstance } from "ky";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { probeHoseDomain } from "../../../core/auth/hose.js";
import { confirmationRequired, validationError } from "../../../core/errors.js";
import { type HosecloudConfigInput } from "../types.js";
import {
type HosecloudConfigInput
} from "../types.js";
assertAssistedIntegration,
BLOCKING_NODE_ID,
buildOutboundPayload,
buildOutboundWebhookUrl,
flowIdFromDocumentSn,
listHoseIntegrations,
pushOutboundAndVerify,
resolveCorporationId,
selectHoseIntegration
} from "../outbound/push.js";
import type {
CapabilityContext
} from "./helpers.js";
@@ -44,7 +54,7 @@ export const deployCapabilities = [
parameters: z.object({}),
handler: async (client: KyInstance) => {
const config = await api.getApprovalStylePreferences(client);
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
const integrations = listHoseIntegrations(config);
return {
count: integrations.length,
integrations: integrations.map(redactIntegrationSecrets)
@@ -59,8 +69,8 @@ export const deployCapabilities = [
}),
handler: async (client: KyInstance, params: { signKey: string }) => {
const config = await api.getApprovalStylePreferences(client);
const integration = (config.integrations ?? []).find(
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
const integration = listHoseIntegrations(config).find(
(item) => item.signKey === params.signKey
);
if (!integration) {
throw new Error(`未找到合思配置:${params.signKey}`);
@@ -75,7 +85,7 @@ export const deployCapabilities = [
handler: async (client: KyInstance) => {
const status = await api.getSimulationIntegrationStatus(client);
const config = await api.getApprovalStylePreferences(client);
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
const integrations = listHoseIntegrations(config);
return {
status,
integrations: integrations.map(redactIntegrationSecrets)
@@ -105,12 +115,13 @@ export const deployCapabilities = [
autoApproveNodeNames: z.array(z.string()).optional(),
apiOrigin: z.string().default("production"),
customApiUrl: z.string().optional(),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入"),
confirm: z.boolean().optional().describe("明确确认保存配置;CLI 使用 --yes 或 --confirm")
}),
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: CapabilityContext) => {
const { dryRun, ...inputParams } = rawParams;
const apiKey = inputParams.apiKey ?? (inputParams as any).appKey;
const apiSecret = inputParams.apiSecret ?? (inputParams as any).appSecurity;
const { dryRun, confirm, appKey, appSecurity, ...inputParams } = rawParams;
const apiKey = inputParams.apiKey ?? (typeof appKey === "string" ? appKey : undefined);
const apiSecret = inputParams.apiSecret ?? (typeof appSecurity === "string" ? appSecurity : undefined);
if (!apiKey || !apiSecret) {
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
}
@@ -118,6 +129,16 @@ export const deployCapabilities = [
let effectiveApiOrigin = params.apiOrigin ?? "production";
let effectiveCustomApiUrl = params.customApiUrl;
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
throw new Error("自定义合思环境必须提供 customApiUrl");
}
if (!dryRun && confirm !== true) {
throw confirmationRequired(
"Refusing to save Hose integration configuration without --yes or --confirm. Use --dry-run to preview first.",
"seal-use help deploy hosecloud configure"
);
}
// 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名
if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") {
try {
@@ -136,17 +157,13 @@ export const deployCapabilities = [
}
}
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
throw new Error("自定义合思环境必须提供 customApiUrl");
}
const corpResult = await api.getHosecloudCorporation(client, {
apiKey: params.apiKey,
apiSecret: params.apiSecret,
apiOrigin: effectiveApiOrigin,
customApiUrl: effectiveCustomApiUrl
});
const config = await api.getApprovalStylePreferences(client);
const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences);
const signKey = params.signKey ?? randomBytes(6).toString("hex");
const nextIntegration = {
type: "hosecloud",
@@ -177,7 +194,7 @@ export const deployCapabilities = [
await api.updateApprovalStylePreferences(client, nextConfig, context.corp.seal.endpoints.approvalStylePreferences);
console.error(`✓ 配置已保存 (signKey: ${signKey})`);
console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}`);
console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --dry-run --corp ${context.corp.id}`);
return {
integration: redactIntegrationSecrets(nextIntegration)
@@ -188,25 +205,42 @@ export const deployCapabilities = [
name: "sealDeployHosecloudSync",
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
parameters: z.object({
signKey: z.string().describe("合思集成 sign-key")
signKey: z.string().describe("合思集成 sign-key"),
dryRun: z.boolean().optional().describe("只预览待同步的消息名称、回调地址和模式,不执行同步"),
confirm: z.boolean().optional().describe("明确确认同步到合思;CLI 使用 --yes 或 --confirm")
}),
handler: async (client: KyInstance, params: { signKey: string }, context: CapabilityContext) => {
const config = await api.getApprovalStylePreferences(client);
const integration = (config.integrations ?? []).find(
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
handler: async (client: KyInstance, params: { signKey: string; dryRun?: boolean; confirm?: boolean }, context: CapabilityContext) => {
if (!params.dryRun && params.confirm !== true) {
throw confirmationRequired(
"Refusing to synchronize Hose outbound messages without --yes or --confirm. Use --dry-run to preview first.",
`seal-use deploy hosecloud sync ${params.signKey} --dry-run --corp ${context.corp.id}`
);
}
const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences);
const integration = listHoseIntegrations(config).find(
(item) => item.signKey === params.signKey
);
if (!integration) {
throw new Error(`未找到合思配置:${params.signKey}`);
}
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const messageName = (integration as any).outboundName ?? "SealAI 审批";
const result = await api.syncHosecloudOutbound(client, {
const messageName = integration.outboundName ?? "SealAI 审批";
const payload = {
signKey: params.signKey,
webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`,
webhookUrl: buildOutboundWebhookUrl(context.corp, params.signKey),
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
messageName,
mode: (integration as any).mode ?? "assisted"
});
mode: integration.mode ?? "assisted"
};
if (params.dryRun) {
return {
...mutationPreview(context, "api/hosecloud/outbound-config/sync", null, payload, 1),
signKey: params.signKey,
remoteStateKnown: false,
note: "仅预览将同步的消息名称、回调地址和模式;合思远端当前配置尚未读取。"
};
}
const result = await api.syncHosecloudOutbound(client, payload);
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
@@ -217,5 +251,148 @@ export const deployCapabilities = [
result
};
}
},
{
name: "sealDeployHosecloudTestOutbound",
description: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发,强制要求目标集成必须为 assisted 模式",
parameters: z.object({
signKey: z.string().optional().describe("合思集成 sign-key(若企业仅有一个合思配置可自动识别)"),
flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"),
sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"),
messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"),
nodeId: z.string().optional().default(BLOCKING_NODE_ID).describe("合思流程节点 ID(默认填入中文阻断标识)"),
rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"),
corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"),
dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送"),
confirm: z.boolean().optional().describe("明确确认实际推送;CLI 使用 --yes 或 --confirm")
}),
handler: async (
client: KyInstance,
params: {
signKey?: string;
flowId?: string;
sn?: string;
messageId: string;
nodeId?: string;
rejectionNum?: number;
corporationId?: string;
dryRun?: boolean;
confirm?: boolean;
},
context: CapabilityContext
) => {
const config = await api.getApprovalStylePreferences(client);
const integration = selectHoseIntegration({
integrations: listHoseIntegrations(config),
signKey: params.signKey,
corpName: context.corp.name,
corpId: context.corp.id
});
// 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式
assertAssistedIntegration(integration, {
corpName: context.corp.name,
corpId: context.corp.id
});
// 2. 消息凭证校验
const messageId = params.messageId?.trim();
if (!messageId) {
throw validationError(
"缺少必需参数 --message-id。合思开放平台出站协议要求使用真实有效的 messageId 换取单据上下文,请从合思出站请求日志中提取提供。"
);
}
// 3. 解析 flowId
let flowId = params.flowId?.trim();
const sn = params.sn?.trim();
if (!flowId && sn) {
try {
const existing = await api.listApprovalRuns(client, {
search: sn,
sourceDocumentSN: sn,
limit: 5
});
const match = (existing.records || []).find(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn
);
if (match?.sourceDocumentId) {
flowId = match.sourceDocumentId;
}
} catch {
// 忽略
}
if (!flowId) {
flowId = flowIdFromDocumentSn(sn);
}
}
if (!flowId) {
throw validationError(
"缺少必需参数 --flow-id(合思单据/流程 ID)。若已存在该单的历史运行记录,也可通过 --sn <单号> 自动解析。"
);
}
// 4. 解析 corporationId
const corporationId = resolveCorporationId([params.corporationId, integration.corporationId]);
const payload = buildOutboundPayload({
flowId,
messageId,
nodeId: params.nodeId,
rejectionNum: params.rejectionNum,
corporationId
});
const webhookUrl = buildOutboundWebhookUrl(context.corp, integration.signKey!);
if (params.dryRun) {
return {
preview: true,
url: webhookUrl,
targetCorp: context.corp.id,
targetIntegration: {
signKey: integration.signKey,
outboundName: integration.outboundName,
mode: integration.mode
},
safetyCheck: {
mode: "assisted",
passed: true,
nodeId412Blocked: payload.nodeId === BLOCKING_NODE_ID,
note: payload.nodeId === BLOCKING_NODE_ID
? "目标企业出站模式为 assisted;使用默认中文 nodeId 阻断标记。"
: "目标企业出站模式为 assisted;自定义 nodeId 未验证具备 HTTP 412 阻断保障。"
},
payload
};
}
const { response, createdRecord } = await pushOutboundAndVerify({
client,
signKey: integration.signKey!,
payload,
flowId,
sn,
confirm: params.confirm,
corpName: context.corp.name,
corpId: context.corp.id,
pushedMessages: [
`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`
]
});
return {
success: true,
targetCorp: context.corp.id,
signKey: integration.signKey,
mode: integration.mode,
payload,
response,
consumptionVerified: createdRecord !== undefined,
recordId: createdRecord?.id,
recordStatus: createdRecord?.status,
taskMode: createdRecord?.taskMode
};
}
}
];
@@ -0,0 +1,72 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
/**
* Size ratchet for `helpers.ts` (see the FROZEN header at the top of that file).
*
* The module is the historical dumping ground for anything a capability needed,
* and `export *` from index.ts leaks all of it into every capability's
* namespace. A comment alone does not stop the next addition, so the ceiling is
* enforced here: adding an export (or growing the file) fails CI with a message
* that says where the logic should go instead.
*
* Both ceilings may go DOWN — moving an export out to a focused module is the
* intended fix. Only `helpers.ts` is measured; sibling modules are unrestricted.
*/
const HELPERS_PATH = join(import.meta.dirname, "helpers.ts");
// Lower these only when logic actually leaves the file.
const MAX_LINES = 1694;
const MAX_EXPORTS = 85;
function measure(source: string) {
const lines = source.split("\n").length;
// Top-level `export` declarations only; re-exports and `export { x } from`
// lists would be counted by a looser pattern.
const exports = source.match(/^export (?:async )?(?:function|const|class|type|interface|enum) /gm);
return { lines, exports: exports?.length ?? 0 };
}
describe("capabilities/helpers.ts freeze", () => {
const source = readFileSync(HELPERS_PATH, "utf8");
const { lines, exports } = measure(source);
test("stays under the line ceiling", () => {
expect(
lines,
`helpers.ts is ${lines} lines (ceiling ${MAX_LINES}). It is frozen: add new ` +
`logic to a focused module next to its domain instead of growing this grab-bag, ` +
`or move an existing export out to lower the ceiling.`
).toBeLessThanOrEqual(MAX_LINES);
});
test("stays under the export ceiling", () => {
expect(
exports,
`helpers.ts exports ${exports} symbols (ceiling ${MAX_EXPORTS}). New exports are ` +
`not accepted here — index.ts re-exports the whole file into every capability's ` +
`namespace. Give the function a home beside the domain that owns it.`
).toBeLessThanOrEqual(MAX_EXPORTS);
});
test("the FROZEN header stays in place", () => {
expect(source.startsWith("// FROZEN")).toBe(true);
expect(source).toContain("helpers.freeze.test.ts");
});
test("no re-export syntax sneaks new symbols into the namespace", () => {
// The declaration counter above does not see `export { x } from "..."` or
// `export *`, which would re-publish helpers from this file's namespace
// without touching either ceiling.
expect(source).not.toMatch(/^export\s*(\{|\*)/m);
});
test("measures what it claims to measure", () => {
// Guard the ratchet itself: a pattern that matches nothing would silently
// pin the export ceiling at 0 and pass forever.
expect(exports).toBeGreaterThan(0);
expect(lines).toBeGreaterThan(MAX_LINES - 200);
});
});
+20 -25
View File
@@ -1,3 +1,16 @@
// FROZEN — see helpers.freeze.test.ts, which fails the build if this file grows.
//
// This module started as shared plumbing for the capability registry and has
// been the default place to drop anything for years. It now holds ~85 exports
// spanning unrelated concerns (base URLs, rule versions, Beijing timestamps,
// generic object paths), and `export *` in index.ts pushes every one of them
// into every capability's namespace — which is why the same helper gets
// re-derived instead of reused.
//
// Rules while frozen:
// - No new exports. Put new logic in a focused module next to its domain.
// - Existing exports may move out (update importers) — the budget only drops.
// - Fixes to existing exports are fine; the line/export ceiling is the guard.
import { z } from "zod";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
@@ -10,10 +23,11 @@ import type {
SimulationBatch,
WebhookIntegration
} from "../types.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import type { LocalRuleItem } from "../rules-local.js";
import { loadRuleMappingSnapshot } from "../rule-mapping.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import type { LocalRuleItem } from "../rules/local.js";
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
import { validationError } from "../../../core/errors.js";
export type CapabilityContext = {
corp: CorpConfig;
@@ -156,21 +170,17 @@ export function buildRulePushPlan(
if (localRule.id) {
remoteRule = remoteById.get(localRule.id);
if (!remoteRule) {
throw new Error(
`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`
);
throw validationError(`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`);
}
if (usedRemoteIds.has(localRule.id)) {
throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`);
throw validationError(`本地规则文件包含重复的规则 ID:${localRule.id}`);
}
} else {
const matches = remoteRules.filter(
(candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule)
);
if (matches.length > 1) {
throw new Error(
`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`
);
throw validationError(`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`);
}
remoteRule = matches[0];
}
@@ -254,21 +264,6 @@ export type SimulationBatchCreateInput = {
rawParams?: Record<string, unknown>;
};
export function parseDurationMs(duration: string): number {
const match = duration.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i);
if (!match || !match[1]) return 600000;
const val = parseFloat(match[1]);
const unit = (match[2] ?? "s").toLowerCase();
switch (unit) {
case "ms": return val;
case "s": return val * 1000;
case "m": return val * 60 * 1000;
case "h": return val * 3600 * 1000;
case "d": return val * 86400 * 1000;
default: return val * 1000;
}
}
export function redactIntegrationSecrets(integration: Record<string, unknown>) {
return Object.fromEntries(
Object.entries(integration).map(([key, value]) => [
+21 -5
View File
@@ -29,10 +29,19 @@ export const identityCapabilities = [
name: "sealDelegationCreate",
description: "创建新的 Seal 授权链接 (Delegation)",
parameters: z.object({
note: z.string().optional().describe("授权链接的备注或说明信息")
note: z.string().optional().describe("授权链接的备注或说明信息"),
expiresInHours: z
.number()
.int()
.min(1)
.max(168)
.optional()
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
}),
handler: async (client: KyInstance, params: { note?: string }) =>
api.createDelegation(client, params)
handler: async (
client: KyInstance,
params: { note?: string; expiresInHours?: number }
) => api.createDelegation(client, params)
},
{
name: "sealDelegationRevoke",
@@ -107,11 +116,18 @@ export const identityCapabilities = [
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
parameters: z.object({
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
note: z.string().optional().describe("授权链接备注信息")
note: z.string().optional().describe("授权链接备注信息"),
expiresInHours: z
.number()
.int()
.min(1)
.max(168)
.optional()
.describe("授权链接有效期小时数(1~168 小时,即最大 7 天,默认 24 小时)")
}),
handler: async (
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
params: { userIdOrPhone: string; note?: string; expiresInHours?: number },
context: CapabilityContext
) =>
api.createDelegationForUser(
+3
View File
@@ -101,6 +101,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealPermissionsConfigsList",
"sealPreferenceGet",
"sealPreferenceThinkingDepthPoliciesList",
"sealReportDataGet",
"sealReportMonthlyGet",
"sealSessionGet",
"sealSimulationBatchGet",
@@ -129,12 +130,14 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
"sealApprovalRuleUpdate",
"sealApprovalRuleVersionPublish",
"sealApprovalRulesClear",
"sealApprovalRulesRecode",
"sealApprovalRulesPush",
"sealApprovalStylePreferencesUpdate",
"sealDelegationCreate",
"sealDelegationRevoke",
"sealDeployHosecloudConfigure",
"sealDeployHosecloudSync",
"sealDeployHosecloudTestOutbound",
"sealInsightRecordAnalyze",
"sealPreferenceDecisionUpdate",
"sealPreferenceThinkingDepthPoliciesRemove",
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff. Show more