Compare commits

..
71 Commits
Author SHA1 Message Date
yunyingk d00fa1b960 Merge pull request #262 from yunyingk/codex/release-v0.11.15
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Release v0.11.15: Automated release bump
2026-10-23 16:46:13 +08:00
gitea 4541f9c4fb Release v0.11.15: Automated release bump 2026-10-23 16:44:25 +08:00
yunyingk fed0a8464c Merge pull request #261 from yunyingk/mac15/simulation-local-search
Add local search for simulation batches
2026-10-23 16:43:50 +08:00
gitea ed57c0cd42 Add local search for simulation batches 2026-10-23 16:42:20 +08:00
yunyingk 4c4a80b10c Merge pull request #260 from yunyingk/mac15/approval-raw-json
Add native JSON fallback for approval record details
2026-10-22 16:26:11 +08:00
gitea 3ae39bcc08 Add native JSON fallback for approval record details 2026-10-22 16:19:52 +08:00
yunyingk b49f25a2bc Merge pull request #259 from yunyingk/codex/release-v0.11.14
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.14: extra risk filters and link identities
2026-10-22 12:41:32 +08:00
gitea b1769d8a25 Release v0.11.14: extra risk filters and link identities 2026-10-22 12:39:02 +08:00
yunyingk 0582bc7898 Merge pull request #258 from yunyingk/mac15/assist-link-person-names
Report verified personnel names for assistance links
2026-10-22 12:38:07 +08:00
yunyingk 6d310ba945 Merge pull request #257 from yunyingk/mac15/approval-extra-risk
Add approval record extra risk filtering
2026-10-22 12:36:35 +08:00
gitea 41e0bfba71 Report verified personnel names for assistance links 2026-10-22 12:35:28 +08:00
gitea b5dd3560b6 Add approval record extra risk filtering 2026-10-22 12:34:54 +08:00
yunyingk ec513adf38 Merge pull request #256 from yunyingk/codex/release-v0.11.13
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.13: Automated release bump
2026-10-20 23:12:07 +08:00
gitea 9e591cc146 Release v0.11.13: Automated release bump 2026-10-20 23:10:46 +08:00
yunyingk 05dbdb17af Merge pull request #254 from yunyingk/mac15/safe-document-file-editing
Add safe knowledge document file editing
2026-10-20 17:45:32 +08:00
gitea a2963c736c Preserve auth exit codes when document readback fails 2026-10-20 17:40:06 +08:00
gitea b017e1fc48 Add safe knowledge document file editing 2026-10-20 17:30:38 +08:00
yunyingk cbef6d0ef6 Merge pull request #255 from yunyingk/mac15/expense-document-lookup
Add expense store lookup by document number
2026-10-20 17:29:50 +08:00
gitea 10852eb198 Fix platform-dependent config selection test 2026-10-20 10:23:36 +08:00
gitea b21d92efae Add expense store lookup by document number 2026-10-20 10:15:08 +08:00
yunyingk 4b3a899e5a Merge pull request #242 from yunyingk/mac15/clean-report-templates-and-assets
Clean report templates, drop legacy charts, and refine guidelines
2026-10-18 22:54:55 +08:00
yunyingk a83f78b140 Merge pull request #243 from yunyingk/mac15/invoices-flatten-and-conflict-trace
Add normalized invoice fields, first-class invoices CLI, and CLI-attributed conflict diagnosis
2026-10-18 22:54:14 +08:00
gitea 05dfd0f5bb Clean report templates, drop legacy charts, and refine guidelines 2026-10-18 22:53:25 +08:00
gitea d40ab9648d Add normalized invoice fields, first-class invoices CLI, and CLI-attributed conflict diagnosis 2026-10-18 22:52:36 +08:00
yunyingk b17f7ad722 Merge pull request #253 from yunyingk/mac15/add-protocol-test-closure
Add protocol test closures for secure writes, aliases, help and cli docs
2026-10-18 13:45:51 +08:00
gitea 9e7275f09b Add protocol test closures for secure writes, aliases, help and cli docs 2026-10-18 11:16:07 +08:00
yunyingk 97c59fae14 Merge pull request #252 from yunyingk/codex/release-v0.11.12
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.12: credential and CLI consistency fixes
2026-10-17 20:24:38 +08:00
gitea b44800c108 Release v0.11.12: Automated release bump 2026-10-17 20:23:23 +08:00
yunyingk baa47753d3 Merge pull request #251 from yunyingk/mac15/fix-architecture-review
Fix architecture review findings and align CLI metadata
2026-10-17 20:22:04 +08:00
gitea 50e4e492b4 Fix architecture review findings and align CLI metadata 2026-10-17 20:17:06 +08:00
yunyingk 780a4ba9c0 Merge pull request #250 from yunyingk/mac15/refine-report-glossary-and-math-layout
Refine report glossary to plain business language and improve math layout
2026-10-16 18:28:58 +08:00
gitea 818f33a8e1 Refine report glossary to plain business language and improve math layout 2026-10-16 18:27:18 +08:00
yunyingk a760ea9572 Merge pull request #249 from yunyingk/mac15/add-report-glossary-page
Add trailing terms definition appendix to report renderers
2026-10-16 18:07:44 +08:00
gitea 69d5b4f130 Add trailing terms definition appendix to report renderers 2026-10-16 18:06:02 +08:00
yunyingk cbc3b333ba Merge pull request #248 from yunyingk/codex/release-v0.11.11
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.11: Automated release bump
2026-10-16 17:48:45 +08:00
gitea 059616ba22 Release v0.11.11: Automated release bump 2026-10-16 17:47:30 +08:00
yunyingk 11434f75f0 Merge pull request #247 from yunyingk/mac15/remove-500-runs-limit
Refine report data collection to support unlimited runs without 500 cap
2026-10-16 17:46:34 +08:00
gitea 91feec7b0b Refine risk intercept fallback calculation and sync ledger documentation 2026-10-16 17:44:58 +08:00
gitea 04915c6ad6 Refine report data collection to support unlimited runs without 500 cap 2026-10-16 17:36:36 +08:00
yunyingk bea6a9cf4e Merge pull request #246 from yunyingk/codex/release-v0.11.10
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Release v0.11.10: Automated release bump
2026-10-16 15:54:32 +08:00
gitea 1209164cc8 Release v0.11.10: Automated release bump 2026-10-16 15:53:06 +08:00
yunyingk b18f1d772b Merge pull request #245 from yunyingk/mac15/report-date-range-and-record-id-review
Add report ledger workflow, refine terminology and codify skill discipline
2026-10-16 15:37:07 +08:00
gitea c6bd113fff Add report ledger workflow, refine terminology and codify skill discipline 2026-10-16 15:35:25 +08:00
gitea 077ecb050c Refine report pipeline to support date ranges and recordId reviews 2026-10-16 14:56:11 +08:00
yunyingk 64680cd4a0 Merge pull request #244 from yunyingk/mac15/refine-hose-auth-doc
Refine hose auth guidelines and remove hardcoded personnel names
2026-10-16 14:22:56 +08:00
gitea 135cd84e69 Refine hose auth guidelines and remove hardcoded personnel names 2026-10-16 13:22:23 +08:00
yunyingk d26c4358c5 Merge pull request #241 from yunyingk/codex/release-v0.11.9
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.9: Automated release bump
2026-10-16 11:43:54 +08:00
gitea d127e80c1b Release v0.11.9: Automated release bump 2026-10-16 11:42:28 +08:00
yunyingk e52654fec7 Merge pull request #240 from yunyingk/mac15/hose-ebot-outbound
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add hose-ebot command for Hose outbound discovery and approval callback
2026-10-16 11:22:48 +08:00
gitea bbff9338a0 Add hose-ebot command for Hose outbound discovery and approval callback 2026-10-16 11:19:50 +08:00
yunyingk 21e1a9d27a Merge pull request #239 from yunyingk/mac15/skill-install-and-wsl-gitea-sync
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add tool installation to skill and Git mirror sync to WSL worker
2026-10-16 09:54:15 +08:00
gitea e9eb8095fc Add tool installation to skill and Git mirror sync to WSL worker 2026-10-16 09:52:24 +08:00
yunyingk 2749d765b3 Merge pull request #238 from yunyingk/mac15/auth-hose-openapi-token
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
Add auth hose-openapi-token command for Hose enterprises
2026-10-15 17:07:52 +08:00
gitea 6e4a8cb088 Add auth hose-openapi-token command for Hose enterprises 2026-10-15 17:05:55 +08:00
yunyingk 55ead68a06 Merge pull request #237 from yunyingk/mac15/refine-external-report-readme
Refine pkg/report README and clean external docstrings
2026-10-15 17:01:00 +08:00
gitea 41d5b175a6 Refine pkg/report README and clean external docstrings 2026-10-15 16:58:49 +08:00
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
178 changed files with 9932 additions and 2455 deletions

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ When developing or refactoring CLI commands under `src/cli/`:
## 2. Performance Contract & SWR Architecture
- **Sub-50ms Local Execution**:
- Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return in under 50ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~40ms for the module graph).
- **Sub-70ms Local Execution**:
- Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return in under 70ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~60ms for the module graph).
- Achieved by keeping `src/cli/runner.ts` free of static command-module imports: dispatch branches load their handler with `await import("./commands/<area>.js")` on demand, so `seal-use version` never loads the Excel/zip tool chain.
- Never trigger synchronous external HTTP requests during routine discovery or inspection invocations. Measured on the maintainer's machine (2026-09): version 45ms, help 41ms, corps list 41ms, bare `bun -e` 7ms.
- **Stale-While-Revalidate (SWR) Pattern**:
+72
View File
@@ -0,0 +1,72 @@
---
description: "Agent Skill architecture, documentation layering discipline, and tool-agent boundary principles"
globs: "skills/**/*.md"
trigger: "manual"
---
# Agent Skill Architecture & Documentation Discipline
When authoring, refactoring, or maintaining Agent Skills under `skills/`:
## 1. Document Layering & Single Source of Truth
Agent Skill documentation follows a strict two-tier architecture:
```
skills/<skill>/
├── SKILL.md # Tier 1: Lightweight Traffic Routing Hub (导流中枢)
└── references/ # Tier 2: Deep Domain Guides & Manuals (业务纵深手册)
├── enterprise-onboarding.md
├── report-templates.md
└── ...
```
### Tier 1: Main `SKILL.md` (Traffic Routing Hub)
- **Role**: Lightweight, high-signal, rapid routing hub.
- **Allowed Contents**:
1. Frontmatter metadata (name, description, version);
2. Bootstrap & installation guide;
3. Universal system invariants (timestamp format `+08:00`, data masking, stdout/stderr boundaries);
4. Core domain navigation (`corps`, `rules`);
5. Cross-domain terminology contracts;
6. **Reference Routing Table (`## 参考文档路由`)**: The primary mechanism to guide AI agents to specific deep-dive guides based on user intent and intent triggers;
7. A strictly limited number of high-frequency single-step aggregate shortcut commands (e.g. `approval-runs diagnose`).
- **Strict Anti-Patterns**:
- ❌ **No "Feature Billboard" bloat**: NEVER dump multi-step workflows, full section breakdowns, complete schemas, or qualitative debate procedures into `SKILL.md`.
- ❌ **Overcoming "Locality Bias" (就近修改惯性)**: When adding a new capability (e.g. `--ledger`), DO NOT casually expand the main `SKILL.md` just because it's in front of you. Always route to or expand the corresponding `references/*.md`.
- ❌ **No Duplicate Maintenance**: If a topic is covered in `references/<name>.md`, do not duplicate its prose or guidelines in `SKILL.md`. The routing table row is sufficient.
### Tier 2: `references/*.md` (Deep Domain Manuals)
- **Role**: The authoritative, exhaustive source of truth for deep workflows, business context, and operational troubleshooting.
- **Contents**:
1. Business background, objectives, and audience;
2. Multi-step collaborative lifecycles (e.g. human-in-the-loop Tangent reviews);
3. Complete column-by-column schema specifications;
4. Decision matrices and terminology rules;
5. Troubleshooting guides, validation error catalogs (e.g. `HD001`~`INFO002`), and mitigation examples;
6. Concrete Markdown/JSON payload examples.
---
## 2. Tool vs. Agent Boundary Contract (Wrench vs. Discretion)
When designing CLI features and their Skill documentation:
- **CLI is a Deterministic Wrench (确定性扳手)**:
- The CLI provides deterministic, repeatable, pure operations: data extraction, file export/import, offline schema/math validation, and self-contained rendering.
- The CLI **MUST NOT** overstep into business discretion: it does not guess subjective fault attribution ("who is right/wrong"), nor does it fabricate explanations.
- **Agent Exercises Business Discretion (自由裁量权)**:
- The Agent (together with the user) exercises full discretion: pruning templates, filtering dirty data, conducting review debates (Tangent), and authoring qualitative takeaways.
- **Strict Offline Boundary (本地事实源绝不越界)**:
- When driven by a local artifact (e.g. `--ledger 台账.xlsx`), the CLI treats the local file as the **absolute and exclusive boundary**.
- The CLI **MUST NEVER** reach out to remote cloud APIs to investigate records that were intentionally pruned/deleted from the local ledger.
- The offline validation gatekeeper evaluates only the internal consistency and mathematical harmony of the remaining records in the ledger.
---
## 3. Terminology Precision & Anti-Ambiguity Contract
- **Avoid Ambiguous Catch-All Words**: Never use vague terms that conflate document status with system performance (e.g. completely retire the ambiguous word "失准").
- **Strict Two-Level Separation**:
- **Level 1: Document Validity / Approval Decision (审批决策)**: Focuses on the business document itself. Use `通过 (Pass)` / `驳回 (Reject)` / `违规拦截 (Interception)`. Rejection represents rule enforcement, NOT a system defect.
- **Level 2: Review Verdict / Correctness Judgment (复核裁决)**: Focuses on whether the AI or human decision was correct upon subsequent review. Use explicit verdicts: `ai_correct`, `human_correct`, `both_correct`, `both_wrong`, `undecided`.
+6
View File
@@ -41,6 +41,12 @@ jobs:
- name: Linter Plaintext Sync
run: bun run verify:linter-plaintext
- name: CLI Documentation Sync
run: bun run verify:cli-md
- name: Embedded Skill Sync
run: bun run verify:embedded-skill
- name: Colocated Unit Tests
run: bun test
+1
View File
@@ -3,6 +3,7 @@ node_modules/
# Build outputs
dist/bin/
build/
# Local runtime caches and system noise (regenerate at any time)
.cache/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.7",
"version": "0.11.15",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+14 -3
View File
@@ -34,7 +34,7 @@ Prefer small domain functions over broad utility modules.
- **Machine Channel (`stdout`)**: Data commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
- **Documented exception — document-output commands**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract.
- **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync <signKey>`).
- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute in under 50ms wall clock (Bun startup alone is ~7ms; runner dispatch uses lazy `await import()` per command area, so the version path never loads the Excel/zip tool chain). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`).
- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute in under 70ms wall clock (Bun startup alone is ~7ms; runner dispatch uses lazy `await import()` per command area, so the version path never loads the Excel/zip tool chain). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`).
- **Safety Guardrail & Mutation Preview (`--dry-run`)**: All potentially destructive or state-mutating commands (e.g. `rules push/clear`, `corps sync-test`, `preference update`, `webhook add/update`) MUST support `--dry-run` returning structured JSON previews with `preview: true` and a clean diff, without executing mutations. Live execution requires explicit `--yes` or `--confirm`.
- **Exit Code Contract**:
- `0`: Successful execution.
@@ -63,6 +63,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
- Webhook material pack & attachment policy: `.agents/rules/material-pack-policy.md`
- Security trade-offs (usability-first accepted risks): `.agents/rules/security-posture.md`
- Workspace hygiene (branch/worktree cleanup & release delta review): `.agents/rules/workspace-hygiene.md`
- Skill documentation layering & tool-agent boundaries: `.agents/rules/skill-documentation.md`
## Release & Publishing Guidelines
@@ -76,7 +77,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
4. Release branch creation (`codex/release-vX.Y.Z`), commit, and push to `origin`.
5. GitHub PR creation, CI monitoring, and merge.
6. Main branch fast-forward (`git pull --ff-only origin main`).
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`).
7. Annotated tag creation (`vX.Y.Z`) and push to `origin` (`git push origin refs/tags/vX.Y.Z`), with synchronous best-effort mirror to `home` (Gitea).
8. Clean removal of temporary release branch.
2. **Manual Protected-Branch Release & Workspace Isolation (Reference)**:
@@ -104,7 +105,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 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/`).
- **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets 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
@@ -118,3 +119,13 @@ Credential files are written `0600`; a config placed by hand keeps the `0o644` d
## Agent-Specific Instructions
Do not create `.codex/skills`; Codex is compatible with `.agents/skills`, and this project treats `.agents/` as authoritative. At project scope, prefer `AGENTS.md` instructions when present.
### Skill Documentation Layering & Traffic Routing Discipline
- **Main `skills/<skill>/SKILL.md` is a Lightweight Traffic Routing Hub (精准路由中枢)**: Keep `SKILL.md` lean, structured, and focused on discovery, installation, universal conventions, and the Reference Routing Table (`## 参考文档路由`).
- **NEVER bloat `SKILL.md` into a feature billboard**: Do NOT write lengthy multi-step workflows, full section breakdowns, extensive table schemas, or qualitative debate procedures into `SKILL.md`.
- **Overcome Locality Bias (杜绝“就近修改”惯性)**: When developing or extending a feature, do not casually append detailed guides to `SKILL.md` just because it is open or visible. Always place the detailed manual in `skills/<skill>/references/<topic>.md`, and keep `SKILL.md` strictly to a one-line routing table entry.
- **`references/*.md` is the Single Source of Truth**: All operational guides, schema specifications, business debate workflows (Tangent), and troubleshooting catalogs belong in `references/`.
- **Deterministic Wrench vs. Agent Discretion (CLI 是扳手,Agent 自由裁量)**:
- The CLI provides deterministic, repeatable tooling: data fetching, ledger export/import, offline schema/math gates, and self-contained rendering.
- The Agent and user exercise business discretion: pruning templates, filtering dirty rows in local ledgers, debating edge cases, and authoring qualitative takeaways.
- **Strict Offline Boundary**: When driven by a local file (`--ledger 台账.xlsx`), the CLI treats the local file as the absolute boundary and NEVER queries cloud APIs for rows deleted or pruned from the file. The validation gate checks only internal consistency. See `.agents/rules/skill-documentation.md`.
+85
View File
@@ -7,6 +7,91 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.15] - 2026-10-23
### Added
- Merge pull request #261 from yunyingk/mac15/simulation-local-search
- Add local search for simulation batches
- Merge pull request #260 from yunyingk/mac15/approval-raw-json
- Add native JSON fallback for approval record details
## [0.11.14] - 2026-10-22
### Added
- 审核记录 `list/search` 新增 `--has-extra-risk`,按系统检测的 `warning/error` 筛选额外风险,返回风险明细、数量与无法判断的记录数;沿用现有查询条件和分页,100 条为共享单页上限,没有独立的总量限制(#257)。
### Fixed
- 合思与 Seal 协助链接自动返回实际人员姓名及已核实的角色或权限;身份查询失败明确标记未核实,Skill 要求汇报人员姓名、目标系统、权限和有效期(#258)。
## [0.11.13] - 2026-10-20
### Added
- Merge pull request #254 from yunyingk/mac15/safe-document-file-editing
- Preserve auth exit codes when document readback fails
- Add safe knowledge document file editing
- Merge pull request #255 from yunyingk/mac15/expense-document-lookup
- Fix platform-dependent config selection test
- Add expense store lookup by document number
- Merge pull request #242 from yunyingk/mac15/clean-report-templates-and-assets
- Merge pull request #243 from yunyingk/mac15/invoices-flatten-and-conflict-trace
## [0.11.12] - 2026-10-17
### Added
- Merge pull request #251 from yunyingk/mac15/fix-architecture-review
- Fix architecture review findings and align CLI metadata
- Merge pull request #250 from yunyingk/mac15/refine-report-glossary-and-math-layout
- Refine report glossary to plain business language and improve math layout
- Merge pull request #249 from yunyingk/mac15/add-report-glossary-page
- Add trailing terms definition appendix to report renderers
## [0.11.11] - 2026-10-16
### Added
- Merge pull request #247 from yunyingk/mac15/remove-500-runs-limit
- Refine risk intercept fallback calculation and sync ledger documentation
- Refine report data collection to support unlimited runs without 500 cap
## [0.11.10] - 2026-10-16
### Added
- Merge pull request #245 from yunyingk/mac15/report-date-range-and-record-id-review
- Add report ledger workflow, refine terminology and codify skill discipline
- Refine report pipeline to support date ranges and recordId reviews
- Merge pull request #244 from yunyingk/mac15/refine-hose-auth-doc
- Refine hose auth guidelines and remove hardcoded personnel names
## [0.11.9] - 2026-10-16
### Added
- Merge pull request #240 from yunyingk/mac15/hose-ebot-outbound
- Add hose-ebot command for Hose outbound discovery and approval callback
- Merge pull request #239 from yunyingk/mac15/skill-install-and-wsl-gitea-sync
- Add tool installation to skill and Git mirror sync to WSL worker
- Merge pull request #238 from yunyingk/mac15/auth-hose-openapi-token
- Add auth hose-openapi-token command for Hose enterprises
- Merge pull request #237 from yunyingk/mac15/refine-external-report-readme
- Refine pkg/report README and clean external docstrings
## [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
+1 -1
View File
@@ -260,7 +260,7 @@ For test tenants that need a clean slate before importing another rule set, use
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.
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. For a raw Hose OpenAPI access token from persisted `appKey/appSecurity`, run `seal-use auth hose-openapi-token --corp <corpId>`; stdout returns `token`, `expiresAt`, and `cached`, and `--force` skips the local cache to mint a new token.
## Approval Run To Langfuse Bridge
+1 -1
View File
@@ -22,7 +22,7 @@ initial response within a few business days — this is a small project, not a s
| `enterprises/*.json` (working tree) | Same, for enterprises added from a checkout | `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
Credential writes tighten existing files to `0600` before storing new content, including updates, overwrites, and legacy migration. A hand-placed file can retain `0o644` until the next write, so
`seal-use doctor` reports any credential file whose mode is wider than `0600`. Real enterprise
configs are gitignored — never commit them.
+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.7",
"version": "0.11.15",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
@@ -35,7 +35,11 @@
"generate:linter-plaintext": "bun run scripts/generate-linter-plaintext.mjs",
"verify:linter-plaintext": "bun run scripts/check-linter-plaintext.mjs",
"test": "bun test",
"prepare": "git config core.hooksPath .githooks"
"prepare": "git config core.hooksPath .githooks",
"generate:embedded-skill": "bun run scripts/generate-embedded-skill.mjs",
"verify:embedded-skill": "bun run scripts/check-embedded-skill.mjs",
"generate:cli-md": "bun run scripts/generate-cli-md.mjs",
"verify:cli-md": "bun run scripts/check-cli-md.mjs"
},
"dependencies": {
"@modelcontextprotocol/server": "^2.0.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 审核意见、人工审批结论及逐笔复核定性台账)。
+64
View File
@@ -0,0 +1,64 @@
# AI 审核报告编制与校验规范
本目录提供标准的 AI 审核报告 Markdown 模板与配套的离线校验脚本。
---
## 一、标准模板与章节规范
报告应以 Markdown 格式编写(可参考同目录下的 [`example-report.md`](example-report.md))。
### 1. 核心必填章节(按大标题名称识别)
核心章节通过 `##` 大标题名称自动识别与归属,包含以下板块:
| 核心大标题名称 | 说明与要求 |
| :--- | :--- |
| **开篇「报告信息」表** | 文档顶部表格,必填 5 项:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
| **`审核测试结果`** | 汇总效能指标、AI 与人工准确率结论、LaTeX 计算公式(`$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$`)与对比图表。 |
| **`AI 失准分析`** | 包含失准构成总览表、TOP 1~N 典型错判案例表格与调优方案。 |
| **`AI 发现的潜在风险`** | 包含潜在风险总览表、TOP 1~N 真实拦截案例表格(如凭证缺失、比价缺失、超期等)。 |
| **`综合效益`** | 时效、准确度、风险拦截笔数宏观总结表(纯内部核对时可按需裁剪)。 |
| **`审核分歧与复核归因`** | 人机分歧分类统计表(如“未在线配置规则”与“识别偏差”)与管理建议。 |
| **`支撑数据与交付材料`** | 分模板统计表与说明。 |
### 2. 中间自定义插入章节
* 如需针对特定部门、专项费用做深入穿透,允许在任意位置插入自定义章节(例如 `## 2. 营销业务线专项分析`)。
* **规则**:大标题序号从 1 开始自然连续递增(1, 2, 3, 4, 5...);自定义插入的章节内容不受业务规则限制,写什么格式都直接放行。
---
## 二、核心格式规范
为保证文档严谨自洽,报告编写需满足以下格式守则:
1. **纯净 Markdown 语法**:
* 严禁在开头使用 YAML Frontmatter(`---`),元数据请统一写在开篇「报告信息」表中;
* 严禁残留草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等);
* 代码块(```)必须成对闭合。
2. **表格结构**:
* 表格每行单元格数量必须严格与表头对齐;
* 表头文字保持纯文本,禁止包含加粗符号(`**`);
* 案例表格推荐使用纯净紧凑的 2 列格式(`| 单号 | 问题描述 |`),无需手工填写长链接。
3. **数学总账守恒**:
* 失准总览表与潜在风险总览表中,各 TOP 行的单数相加必须严格等于「合计」行单数,百分比相加必须等于 100%(误差 $\le 0.15\%$);
* 各子小节标题中声明的张数(如 `### 2.2 TOP 1 · xxx(9 张 / 47.4%)`)必须与总览表该行单数完全一致;
* LaTeX 公式中的算术计算必须成立(如 $\frac{221}{240} = 92.08\%$),且公式中的数字在正文中有对应出处。
---
## 三、校验脚本使用说明
同目录下已提供独立的 Python 校验脚本 [`validate.py`](validate.py)(纯 Python 标准库编写,无需安装任何第三方库)。
### 运行校验
```bash
python3 validate.py example-report.md
```
* **校验通过**:终端输出绿色通过提示,退出码为 `0`;
* **校验未通过**:终端会明确打印出具体报错的行号、错误代码及修复指南,退出码为 `1`。
支持输出 JSON 格式供程序化调用:
```bash
python3 validate.py example-report.md --json
```
@@ -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 审核意见、人工审批结论及逐笔复核定性台账)。
+374
View File
@@ -0,0 +1,374 @@
#!/usr/bin/env python3
"""
AI 审核报告(Markdown)独立校验器
Independent Markdown Validator for AI Audit Reports
特点:
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台开箱即用
- 核心章节按大标题名称硬匹配,中间插入的自定义章节直接放行
- 严格守护格式合规与数学总账守恒
用法:
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()
+5
View File
@@ -128,6 +128,11 @@ function getBuildInfo(releaseMode) {
async function main() {
const startTime = Date.now();
const generatedCliDoc = spawnSync(bun, [resolve(root, "scripts/generate-cli-md.mjs")], {
cwd: root,
stdio: "inherit"
});
if (generatedCliDoc.status !== 0) throw new Error("Failed to generate CLI documentation");
const generatedSkill = spawnSync(bun, [resolve(root, "scripts/generate-embedded-skill.mjs")], {
cwd: root,
stdio: "inherit"
+4
View File
@@ -87,6 +87,10 @@ writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/seal-use/SKILL.md");
// Keep command documentation and the embedded file manifest synchronized before installation.
execSync("bun run generate:cli-md", { cwd: ROOT, stdio: "inherit" });
execSync("bun run generate:embedded-skill", { cwd: ROOT, stdio: "inherit" });
// 5. Sync to global ~/.agents/skills/seal-use/ if present
const globalSkillDir = join(homedir(), ".agents", "skills", "seal-use");
const legacyGlobalSkillDir = join(homedir(), ".agents", "skills", "seal-home");
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bun
import { readFileSync } from "node:fs";
import { cliDocPath, updateCliDoc } from "./generate-cli-md.mjs";
const content = readFileSync(cliDocPath, "utf8");
if (content !== updateCliDoc(content)) {
console.error("CLI command documentation is stale. Run bun run generate:cli-md and commit the result.");
process.exitCode = 1;
} else {
console.log("CLI command documentation is synchronized.");
}
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bun
import { existsSync, readFileSync } from "node:fs";
import { embeddedSkillOutput, renderEmbeddedSkill } from "./generate-embedded-skill.mjs";
if (!existsSync(embeddedSkillOutput) || readFileSync(embeddedSkillOutput, "utf8") !== renderEmbeddedSkill()) {
console.error("Embedded Skill manifest is stale. Run bun run generate:embedded-skill and commit the result.");
process.exitCode = 1;
} else {
console.log("Embedded Skill manifest is synchronized.");
}
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { HELP_REGISTRY } from "../src/cli/help.ts";
export const cliDocPath = resolve(import.meta.dirname, "../skills/seal-use/references/cli.md");
const begin = "<!-- BEGIN GENERATED CLI COMMANDS -->";
const end = "<!-- END GENERATED CLI COMMANDS -->";
export function renderCliCommandBlock() {
const usages = ["seal-use version", ...HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) => command.usage))];
return [begin, "", "```bash", ...usages, "```", "", end].join("\n");
}
export function updateCliDoc(markdown) {
if (markdown.split(begin).length !== 2 || markdown.split(end).length !== 2 || markdown.indexOf(end) < markdown.indexOf(begin)) {
throw new Error("CLI documentation must contain exactly one ordered generated command block.");
}
const start = markdown.indexOf(begin);
const finish = markdown.indexOf(end) + end.length;
return markdown.slice(0, start) + renderCliCommandBlock() + markdown.slice(finish);
}
if (import.meta.main) {
const before = readFileSync(cliDocPath, "utf8");
const after = updateCliDoc(before);
if (before !== after) writeFileSync(cliDocPath, after, "utf8");
}
+31 -32
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const skillRoot = resolve(root, "skills", "seal-use");
const output = resolve(root, "src", "core", "embedded-skill.generated.ts");
export const embeddedSkillOutput = resolve(root, "src", "core", "embedded-skill.generated.ts");
const textExtensions = new Set([".md", ".yaml", ".yml", ".json", ".txt"]);
function walk(dir) {
@@ -20,40 +20,39 @@ function walk(dir) {
return files;
}
const files = walk(skillRoot).map((fullPath) => ({
fullPath,
relativePath: relative(skillRoot, fullPath).split("\\").join("/"),
importPath: relative(resolve(root, "src", "core"), fullPath).split("\\").join("/"),
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
}));
export function renderEmbeddedSkill(sourceDir = skillRoot, coreDir = resolve(root, "src", "core")) {
const files = walk(sourceDir).map((fullPath) => ({
relativePath: relative(sourceDir, fullPath).split("\\").join("/"),
importPath: relative(coreDir, fullPath).split("\\").join("/"),
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
}));
const lines = [
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
""
];
const lines = [
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
""
];
for (const [index, file] of files.entries()) {
if (file.kind === "text") {
lines.push(`import file${index} from ${JSON.stringify(file.importPath)} with { type: "text" };`);
} else {
const base64 = readFileSync(file.fullPath).toString("base64");
lines.push(`const file${index} = ${JSON.stringify(base64)};`);
for (const [index, file] of files.entries()) {
const loader = file.kind === "text" ? "text" : "file";
lines.push(`import file${index} from ${JSON.stringify(file.importPath)} with { type: "${loader}" };`);
}
lines.push("", "export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "text") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
}
lines.push("};", "", "export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "asset") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
}
lines.push("};", "", "export const EMBEDDED_SKILL_ALL_PATHS = [");
for (const file of files) lines.push(` ${JSON.stringify(file.relativePath)},`);
lines.push("];", "");
return lines.join("\n");
}
lines.push("", "export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "text") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
if (import.meta.main) {
const content = renderEmbeddedSkill();
const previous = existsSync(embeddedSkillOutput) ? readFileSync(embeddedSkillOutput, "utf8") : "";
if (previous !== content) writeFileSync(embeddedSkillOutput, content, "utf8");
}
lines.push("};", "", "export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {");
for (const [index, file] of files.entries()) {
if (file.kind === "asset") lines.push(` ${JSON.stringify(file.relativePath)}: file${index},`);
}
lines.push("};", "", "export const EMBEDDED_SKILL_ALL_PATHS = [");
for (const file of files) lines.push(` ${JSON.stringify(file.relativePath)},`);
lines.push("];", "");
const content = lines.join("\n");
const previous = existsSync(output) ? readFileSync(output, "utf8").replace(/\r\n/g, "\n") : "";
if (previous !== content) writeFileSync(output, content, "utf8");
+77
View File
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, test } from "bun:test"
import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { embeddedSkillOutput, renderEmbeddedSkill } from "./generate-embedded-skill.mjs"
import { cliDocPath, renderCliCommandBlock, updateCliDoc } from "./generate-cli-md.mjs"
const tempDirs: string[] = []
afterEach(() => {
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
describe("generated documentation contracts", () => {
test("both committed generated artifacts match their source", () => {
const markdown = readFileSync(cliDocPath, "utf8")
expect(updateCliDoc(markdown)).toBe(markdown)
expect(readFileSync(embeddedSkillOutput, "utf8")).toBe(renderEmbeddedSkill())
})
test("CLI regeneration repairs drift while preserving surrounding handwritten content", () => {
const block = renderCliCommandBlock()
const drifted = `before\n${block.replace("seal-use version", "seal-use stale-command")}\nafter`
expect(updateCliDoc(drifted)).toBe(`before\n${block}\nafter`)
expect(() => updateCliDoc("missing markers")).toThrow("exactly one ordered")
expect(() => updateCliDoc(`${block}\n${block}`)).toThrow("exactly one ordered")
})
test("embedded manifests follow added and removed paths without inlining asset bytes", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-generator-"))
tempDirs.push(dir)
const skill = join(dir, "skill")
mkdirSync(skill)
writeFileSync(join(skill, "SKILL.md"), "first")
const before = renderEmbeddedSkill(skill, dir)
writeFileSync(join(skill, "SKILL.md"), "second")
expect(renderEmbeddedSkill(skill, dir)).toBe(before)
writeFileSync(join(skill, "fixture.png"), new Uint8Array([1, 2, 3]))
const after = renderEmbeddedSkill(skill, dir)
expect(after).not.toBe(before)
expect(after).toContain('with { type: "file" }')
expect(after).not.toContain("AQID")
// Rendering and checking never write the generated output or alter sources.
expect(readFileSync(join(skill, "SKILL.md"), "utf8")).toBe("second")
rmSync(join(skill, "fixture.png"))
expect(renderEmbeddedSkill(skill, dir)).toBe(before)
})
test("check commands reject stale artifacts without rewriting them", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-generator-check-"))
tempDirs.push(dir)
const scripts = join(dir, "scripts")
const core = join(dir, "src/core")
const cli = join(dir, "src/cli")
const skill = join(dir, "skills/seal-use")
for (const path of [scripts, core, cli, join(skill, "references")]) mkdirSync(path, { recursive: true })
for (const name of ["generate-embedded-skill.mjs", "check-embedded-skill.mjs", "generate-cli-md.mjs", "check-cli-md.mjs"]) {
copyFileSync(join(import.meta.dir, name), join(scripts, name))
}
writeFileSync(join(cli, "help.ts"), 'export const HELP_REGISTRY = [{ commands: [{ usage: ["seal-use fixture list"] }] }];')
writeFileSync(join(skill, "SKILL.md"), "fixture skill")
const embeddedPath = join(core, "embedded-skill.generated.ts")
const markdownPath = join(skill, "references/cli.md")
writeFileSync(embeddedPath, "stale embedded fixture")
const markdown = renderCliCommandBlock().replace("seal-use version", "seal-use stale-command")
writeFileSync(markdownPath, markdown)
for (const script of ["check-embedded-skill.mjs", "check-cli-md.mjs"]) {
const result = Bun.spawnSync([process.execPath, join(scripts, script)], { cwd: dir })
expect(result.exitCode).toBe(1)
}
expect(readFileSync(embeddedPath, "utf8")).toBe("stale embedded fixture")
expect(readFileSync(markdownPath, "utf8")).toBe(markdown)
for (const script of ["generate-cli-md.mjs", "generate-embedded-skill.mjs", "check-embedded-skill.mjs", "check-cli-md.mjs"]) {
const result = Bun.spawnSync([process.execPath, join(scripts, script)], { cwd: dir })
expect(result.exitCode).toBe(0)
}
})
})
+57 -13
View File
@@ -48,19 +48,49 @@ console.log(`🚀 Seal Use 自动化发布向导: v${currentVersion} -> v${nextV
if (isDryRun) console.log("🔍 [DRY RUN 预检演练模式 - 不会执行真实推送或合并]");
console.log("========================================================\n");
function run(cmd: string, options: { cwd?: string; stdio?: "inherit" | "pipe" | "ignore" } = {}) {
function run(cmd: string, options: { cwd?: string; stdio?: "inherit" | "pipe" | "ignore"; env?: NodeJS.ProcessEnv; retries?: number } = {}) {
const stdio = options.stdio ?? "inherit";
try {
const out = execSync(cmd, { cwd: options.cwd ?? ROOT, encoding: "utf-8", stdio });
return out ? out.toString().trim() : "";
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
throw new Error(`执行命令失败: ${cmd}\n${errorMsg}`);
const maxRetries = options.retries ?? (cmd.includes("push") || cmd.includes("gh ") || cmd.includes("fetch") ? 3 : 0);
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const out = execSync(cmd, { cwd: options.cwd ?? ROOT, encoding: "utf-8", stdio, env: options.env });
return out ? out.toString().trim() : "";
} catch (err) {
if (attempt < maxRetries) {
console.warn(`⚠️ 网络命令遭遇瞬时抖动,2 秒后重试 (${attempt + 1}/${maxRetries}): ${cmd}`);
spawnSync("sleep", ["2"], { stdio: "ignore" });
continue;
}
const errorMsg = err instanceof Error ? err.message : String(err);
throw new Error(`执行命令失败: ${cmd}\n${errorMsg}`);
}
}
return "";
}
function runCapture(cmd: string) {
return execSync(cmd, { cwd: ROOT, encoding: "utf-8" }).trim();
const CLEAN_TEST_ENV: NodeJS.ProcessEnv = {
...process.env,
http_proxy: "",
https_proxy: "",
all_proxy: "",
HTTP_PROXY: "",
HTTPS_PROXY: "",
ALL_PROXY: ""
};
function runCapture(cmd: string, retries = (cmd.includes("gh ") || cmd.includes("git ") ? 3 : 0)) {
for (let attempt = 0; attempt <= retries; attempt++) {
try {
return execSync(cmd, { cwd: ROOT, encoding: "utf-8" }).trim();
} catch (err) {
if (attempt < retries) {
spawnSync("sleep", ["2"], { stdio: "ignore" });
continue;
}
throw err;
}
}
return "";
}
/**
@@ -90,7 +120,11 @@ console.log("🔍 步骤 1/8: 执行发布前置条件核验...");
// Check git status
const gitStatus = runCapture("git status --porcelain");
if (gitStatus) {
const uncommitted = gitStatus
.split("\n")
.map((l) => l.trim())
.filter((l) => l && !l.endsWith("scripts/release.ts"));
if (uncommitted.length > 0) {
console.error("❌ 工作区存在未提交的修改,请先提交或暂存后再发布:\n");
console.error(gitStatus);
process.exit(1);
@@ -112,7 +146,7 @@ if (!remotes.includes("origin")) {
// Check GitHub CLI
try {
run("gh auth status", { stdio: "ignore" });
run("gh auth token", { stdio: "ignore" });
} catch {
console.error("❌ GitHub CLI (gh) 未登录或不可用。请先运行 'gh auth login'。");
process.exit(1);
@@ -123,7 +157,7 @@ console.log("✓ 前置检查通过!\n");
if (isDryRun) {
console.log("🧪 正在模拟运行测试与编译检查...");
run("bun run check");
run("bun test");
run("bun test", { env: CLEAN_TEST_ENV });
console.log("\n✅ [DRY RUN] 预检演练全部通过!真实发布将执行:");
console.log(` 1. git switch -c ${releaseBranch}`);
console.log(` 2. bun run bump ${nextVersion}`);
@@ -137,6 +171,7 @@ if (isDryRun) {
// 3. Create release branch
console.log(`🌿 步骤 2/8: 创建并切换至发布分支: ${releaseBranch}...`);
try { execSync(`git branch -D ${releaseBranch}`, { cwd: ROOT, stdio: "ignore" }); } catch {}
run(`git switch -c ${releaseBranch}`);
let success = false;
@@ -166,7 +201,7 @@ try {
// 5. Test and build validation
console.log("\n🧪 步骤 4/8: 执行全量测试与类型安全校验...");
run("bun run check");
run("bun test");
run("bun test", { env: CLEAN_TEST_ENV });
console.log("✓ 本地测试与类型验证通过!\n");
// 6. Commit and Push
@@ -203,6 +238,15 @@ try {
console.log(`📤 推送 Tag ${tag} 到 origin (GitHub,触发 Release 构建)...`);
run(`git push origin refs/tags/${tag}`);
try {
console.log(`📤 同步推送主干分支与 Tag ${tag} 到 home (Gitea)...`);
run("git push home main");
run(`git push home refs/tags/${tag}`);
console.log("✓ Gitea 镜像主干与 Tag 已同步!");
} catch (err) {
console.warn("⚠️ 同步 Gitea 镜像失败(非致命,将由 WSL 定时服务兜底):", err);
}
// 9. Cleanup
console.log("\n🧹 步骤 8/8: 清理临时发布分支...");
run(`git branch -d ${releaseBranch}`);
+43 -61
View File
@@ -1,14 +1,47 @@
---
name: seal-use
description: "v0.11.7: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.15: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.7
short-description: Seal tenant and Hose approval automation (v0.11.7)
version: 0.11.15
short-description: Seal tenant and Hose approval automation (v0.11.15)
---
# Seal Use
CLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。插件不带 MCP;本地 MCP 需显式 `seal-use mcp` 启动。
CLI 是主执行通道。运行 `seal-use help` 获取完整命令清单,使用 `seal-use help <area> [command]` 按需查询参数。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。插件不带 MCP;本地 MCP 需显式 `seal-use mcp` 启动。
## 工具就绪检测与安装 (Bootstrap & Installation)
在执行具体业务前,先通过 `command -v seal-use` 检查 CLI 是否已就绪。若命令未安装或需要升级:
### 1. 一键免环境安装(推荐)
独立预编译原生二进制分发,无需 Node.js 或 Bun 运行环境,自动识别系统架构(macOS Apple Silicon/Intel、Linux x64/arm64):
```bash
# 国内高速镜像(免代理推荐,秒级完成)
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
# GitHub 直连
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
```
### 2. 下载预编译原生二进制
亦可从 Releases 页面直接下载对应平台可执行文件并放入 PATH:
- **Gitea Releases(国内高速)**:`https://git.ying-qing.cn/gitea/seal-use/releases`
- **GitHub Releases**:`https://github.com/yunyingk/seal-use/releases/latest`
### 3. 安装后初始化与激活
```bash
seal-use version # 校验安装版本与架构
seal-use skill install # 同步/安装 Agent Skill 到 ~/.agents/skills/seal-use(支持 Codex / Cursor / Antigravity)
seal-use mcp-config # 输出 MCP 配置 JSON 片段(供 Cursor / Claude Desktop 使用)
seal-use update # 在线自升级至最新版本
seal-use doctor # 运行环境与已接入租户健康诊断
```
### 4. 开发者源码覆盖(本地开发环境)
```bash
bun run dev:override # 编译本机二进制、打版本号并原子覆盖全局命令与本地 Skill
```
## 时间与输出
@@ -53,11 +86,7 @@ CLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志
## `corps` 主线
- 接入:`add-link`、`add-seal-bearer`、`add-hose-persistent`、`add-hose-web-session`
- 发现:`list`、`search`/`find`、`get`/`show`、`current`、`switch`
- 维护:`mark`、`rename`
- 测试闭环:`bind-test`、`unbind-test`、`sync-test`、`replay-test`
- Hose 专属:`probe-hose`、`hose-staffs`、`hose-extract-keys`、`hose-keys`
企业接入、发现、维护与测试配对的具体语法见 `seal-use help corps`;材料选择与操作流程按下方 reference 路由。
Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`approval-runs hose-flow`、`deploy hosecloud`、`simulation --mode hosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--type hose-document` 时才启用对应 Hose 能力。
@@ -94,20 +123,22 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
| --- | --- | --- |
| 第一次接入、不会找凭据、需要截图 | `references/first-time-user.md` | 用户交付材料后,再读 `enterprise-onboarding.md` 做来源决策 |
| 判断材料来源、Token 边界、cURL、Hose 提权 | `references/enterprise-onboarding.md` | 需要具体域名/员工探测时,再读 `hose-enterprise-init.md` |
| Hose 登录检查、认证失败、生成授权链接 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
| Hose 登录检查、认证失败、合思/Seal 协助链接及登录人员身份 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
| Hose 域名探测、角色/员工发现、管理员选择 | `references/hose-enterprise-init.md` | 不要先加载部署或规则文档 |
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` |
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` |
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `references/report-templates.md` |
| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 |
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
@@ -133,52 +164,3 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
```
`approval-runs diagnose` / `bridge` 返回的 `bridge[].next` 就是下一步可执行命令。`seal-use langfuse check` 可自检内置密钥是否失效(失效 → exit 11/1 的结构化报错,绝不崩溃;已缓存 trace 仍可离线读取)。session、attachment-flow、rule-flow、缓存语义与失效兜底见 `references/langfuse-trace.md`。
## 月度审核准确率报告
推荐通过轻量数据包 + Agent 协同填写的模式,彻底解耦数据与模板(亦兼容一键脚手架模式):
```bash
# 模式 A (推荐轻量数据驱动): 提取当月纯结构化数据 (指标、分模板统计、待复核分歧单及具体触发条件)
seal-use report data --month <YYYY-MM> --corp <corpId>
# 保存纯净模板骨架
seal-use report template --out reports/报告.md
# 独立生成动态维恩图 SVG
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/报告.assets/图1-准确率对比.svg
# 模式 B (传统模板脚手架): 一键生成初步替换的 Markdown 与配图包
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
# 离线校验与全格式编译导出
seal-use report validate reports/报告.md
seal-use report render reports/报告.md --out build/报告
```
按模板结构(内置 `monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
- **报告并非一键黑盒交付(人机协同研讨契约)**:数据接口无法自动获得“谁对谁错”的仲裁定性,也无法自动撰写管理归因与整改建议。生成初版 Markdown 后,Agent **严禁直接向客户交付带有 `> ⚠️ 数据说明` 警告框、模板假单号或 `(截图)` 占位符的半成品**,必须进入人机协同研讨模式(Tangent),向用户呈现分歧单据并共创定性分析文本。完整研讨流程、各章节动静边界与校验错误码见 `references/report-templates.md`。
- **推荐轻量 Agent 执笔**:调用 `seal-use report data` 获取干净的 JSON 数据包(含触发的单个判断条件 `triggeredConditions`),由 Agent 亲自将真实数据与复核分析填入 Markdown,避免代码层正则换数的死板与脆弱。
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,初稿保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
- 只读能力 `sealReportDataGet` / `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
### 人工裁决回填(算出人工审核准确率)
上游只给 AI 与人工结论是否同向(`agreement`),**谁对必须人来判**。判断结果按 SN 本地持久化,跨周累积到月底,`report monthly` 据此回填 §1.2 人工审核准确率与覆盖度说明:
```bash
# 录入一条裁决(本地 JSONL,无需网络;通常裁决 AI≠人工 的分歧单)
seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <说明>] [--reviewed-by <裁决人>] --corp <corpId>
# 查看已录入的裁决
seal-use report review list --month <YYYY-MM> --corp <corpId>
```
- **存储**:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
- **协同研讨指南**:分歧单据挑选呈现格式、失准深度归因撰写(§2)、系统迭代历程(§1.3)与严格离线校验(NM001~NM005)排查手册,完整参见 `references/report-templates.md`。
@@ -16,6 +16,31 @@ Default output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDo
If there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.
## Find Runs With Extra Risks
审核结果区分 `result.rulesResult[].findings`(绑定规则的检查发现)与 `result.otherFindings[]`(额外发现)。额外发现中的 `warning` / `error` 计为额外风险,`info` 仅为提示;不根据最终审批结论或摘要文本推断额外风险。
前端将规则内发现映射为 `source: "rule"`,额外发现映射为 `source: "system"` 并标注“系统检测”。这是展示层根据字段来源派生的分类,不是当前审核列表接口已接入的筛选参数。“系统检测”也可能是 `info`,因此不能将全部系统检测项都计为风险。原始等级枚举为 `info / warning / error`;页面的“需复核”还可能由规则的 `UNCERTAIN` 结论派生。
```bash
# 从最近一页 100 条记录中筛出含额外风险的记录
seal-use approval-runs list --has-extra-risk --limit 100 --corp <corpId>
# 在时间、运行状态、人工结果等条件下筛选
seal-use approval-runs search --has-extra-risk --status completed --startDate 2026-10-01 --endDate 2026-10-22 --limit 100 --corp <corpId>
# 继续检查下一页;offset 按上游记录数推进,不按 matched 推进
seal-use approval-runs list --has-extra-risk --limit 100 --offset 100 --corp <corpId>
```
- `limit` 是筛选前读取的页大小(默认 50,最多 100),不会为凑满命中数自动翻页。`offset` 同样作用于上游结果集。
- `scanned` 是本页上游返回的条数,`matched` 是所有本地筛选后的返回条数。`total` 保留上游筛选条件下的记录总数,**不是额外风险单据总数**。
- 启用筛选时,`unknown` 是通过其他本地条件后,因结果缺失或格式异常而无法判断额外风险的条数。这些记录不混入命中列表;无筛选读取时,可通过 `extraFindingsStatus: "unknown"` 定位。
- 记录摘要包含 `otherFindingCount`(含 info 的额外发现总数)、`extraRiskCount`、`hasExtraRisk`、`extraFindingsStatus`。空数组表示已知无额外发现;缺失/异常数据的数量和布尔值为 `null`。
- 本筛选读取结构化的 `otherFindings`。前端还会转换旧版结果中的 `otherRisks` 等字段,但本筛选不推断旧版关联关系;未提供 `otherFindings` 的历史记录计为 `unknown`。
- 启用筛选时,每条命中记录附带 `extraRisks`,含风险标题、等级和描述。一次审核可能有多个风险,`matched` 按审核记录计数;同一单据多次审核也可能返回多条记录。
- `approval-runs result <recordId> --summary` 和 `get <recordId> --summary` 的 AI 结果也返回上述计数字段。查看全部额外发现可用 `get <recordId> --fields result.otherFindings`。
## Read Compact Run Detail
Use `--summary` for most diagnosis and support questions.
@@ -35,6 +60,25 @@ seal-use approval-runs get <recordId> --corp <corpId> --fields document.keyField
Avoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.
## Native JSON Compatibility Fallback
日常读取优先使用 `--summary`、`--fields` 及专用查询命令。只有后台字段结构变化导致常规解析失败,或确需原生响应供本地脚本处理时,使用以下兜底入口:
```bash
# 原生响应写入文件,适合大数据和脚本处理
seal-use approval-runs get <recordId> --raw-json --output-file ./approval-raw.json --corp <corpId>
# 明确需要完整终端输出时
seal-use approval-runs get <recordId> --raw-json --full --corp <corpId>
```
- 常规 `get` 未指定 `--summary/--fields` 时已经返回完整记录,但会解开上游 `data` 包装、校验已知字段类型,并添加 `aliases`、`humanResult` 等派生字段;这不等于原生响应。
- `--raw-json` 保留上游响应的 JSON 结构(包括 `data` 包装、嵌套内容、新字段及上游同名字段),绕过审核记录的业务 schema 校验,不额外添加或覆盖字段。它仍只调用同一条只读审核详情接口,沿用企业认证和 HTTP 错误处理。
- 该模式解析并重新序列化 JSON,缩进等文本格式可能变化,不是 HTTP 响应的字节级副本。上游未返回的内容不会补查;无效 JSON、网络错误或 HTTP 失败仍按原协议报错。
- 输出不会静默截断。共享的 stdout 大小保护超过 200,000 字节时返回退出码 12;`--full` 或 `--output-file` 可输出完整内容。`--full` 只控制大小保护,不会绕过字段校验,也不会撤销 `--summary/--fields`。
- `--raw-json` 不能与 `--summary`、`--fields` 或 `--flow` 同用;这些参数会改写结构或切换接口,CLI 会以退出码 2 明确拒绝。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- 不把兜底入口作为默认查询,也不将大段原生 JSON 直接贴给用户;Agent 可按需读取文件中的特定字段。
## Understand The Case First
Before pulling the full document, use:
+180 -121
View File
@@ -35,13 +35,30 @@ override that path. The legacy `current-corp` file is not read.
## Top-Level Commands
<!-- BEGIN GENERATED CLI COMMANDS -->
```bash
seal-use version
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]
seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]
seal-use corps search <query> [--env <production|test>] [--strict]
seal-use corps get <corpId>
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps rename <corpId> --name <newName>
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--confirm|--yes] [--force]
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal-bearer --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-hose-web-session --json '{"baseUrl":"https://wx2.ekuaibao.com","corpId":"...","staffId":"...","accessToken":"..."}'
seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--app-key <key>] [--key-id <id>] [--overwrite] [--dry-run]
seal-use corps probe-hose --json '{"appKey":"...","appSecurity":"...","domain":"https://..."}'
seal-use corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}'
seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]
seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save] [--app-key <key>]
seal-use rules count [--version <number|latest>] [--corp <corpId>]
seal-use rules list [--version <number|latest>] [--summary] [--limit 20] [--offset 0] [--output-file <path>] [--corp <corpId>]
seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]
@@ -61,67 +78,106 @@ 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>]
seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]
seal-use documents delete <documentId> --yes [--corp <corpId>]
seal-use langfuse check
seal-use langfuse cache-refresh <traceId>
seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full] [--refresh-if-missing]
seal-use langfuse search <traceId> --query <term1,term2> [--fields <fields>] [--max-results <n>] [--context-chars <n>] [--observation-types <types>] [--metadata <json>] [--session-id <id>] [--refresh-if-missing]
seal-use langfuse observation <traceId> <observationId> [--fields <fields>] [--max-chars <n>] [--json-path <path>] [--full] [--refresh-if-missing]
seal-use langfuse session <sessionId> [--trace-limit <n>]
seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>] [--metadata-key <key>] [--has-input] [--has-output] [--max-results <n>] [--refresh-if-missing]
seal-use langfuse url <traceId>
seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>] [--content-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
seal-use langfuse rule-flow <traceId> --rule <text> [--rule-hints <hints>] [--context-chars <n>] [--refresh-if-missing]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
seal-use changelog [--limit <n>]
seal-use mcp
seal-use mcp config
seal-use mcp-config
seal-use skill dump
seal-use skill install [--dir <path>|--local]
seal-use skill status
seal-use doctor [--quiet]
seal-use doctor tenant [--corp <corpId>] [--quiet]
seal-use doctor guide
seal-use doctor paths
seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]
seal-use probe [<corpId>]
seal-use corps list [query] [--env <production|test>] [--limit <n>] [--all] [--strict] [--corp <corpId>]
seal-use corps search <query> [--env <production|test>] [--strict]
seal-use corps get <corpId>
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps replay-test [<prodCorpId>] [--record-id <id>] [--sn <sn>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--confirm|--yes] [--force]
seal-use corps add-hose-persistent --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal-bearer --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--app-key <key>] [--key-id <id>] [--overwrite] [--dry-run]
seal-use corps probe-hose --json '{"appKey":"...","appSecurity":"...","domain":"https://..."}'
seal-use corps hose-staffs --json '{"appKey":"...","appSecurity":"...","role":"admin"}'
seal-use corps hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--app-key <key>] [--key-id <id>] [--overwrite]
seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save] [--app-key <key>] [--key-id <id>]
seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--app-key <key>] [--key-id <id>] [--overwrite]
seal-use auth hose-keys [--corp <corpId>] [--reveal]
seal-use webhook ready [<材料包.zip>] [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size 500] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
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 export <recordId> [--output <file.zip>] [--corp <corpId>]
seal-use webhook resource-pack export --record-ids <id1,id2> [--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> [--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]
seal-use approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
seal-use approval-runs count [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--corp <corpId>]
seal-use approval-runs export [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow] [--out <file>] [--corp <corpId>]
seal-use approval-runs hose-flow <recordId|SN> [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]
seal-use approval-runs document-summary <recordId> [--corp <corpId>]
seal-use approval-runs attachments <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] [--corp <corpId>]
seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs link <recordId> [--corp <corpId>]
seal-use approval-runs link <recordId> --auto-login [--expire 7200] [--corp <corpId>]
seal-use approval-runs link <recordId> --type hose-document [--corp <corpId>]
seal-use approval-runs link --sn <documentSN> [--auto-login] [--corp <corpId>]
seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--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]
seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx>] [--corp <corpId>]
seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--corp <corpId>]
seal-use report template [--out <file.md>]
seal-use report chart venn --ai <acc> --human <acc> [--both <both>] [--out <file.svg>]
seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--limit <n>] [--allow-unreviewed] [--corp <corpId>]
seal-use report validate <报告.md>
seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]
seal-use report export <报告.md> --out <输出目录> [--format <all|html|pdf>]
seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]
seal-use report review list [--corp <corpId>]
seal-use report review import <台账.xlsx|csv> --corp <corpId>
seal-use simulation batch-records <batchId> [--corp <corpId>]
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
seal-use simulation status <batchId> [--corp <corpId>]
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use simulation clean <batchId> --yes [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation approval-definitions [--corp <corpId>]
seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]
seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
seal-use simulation search "任务 fe1993e4" --since 2026-10-01 [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
seal-use simulation package-upload <材料包.zip> [--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] [--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 <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>]
seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]
seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]
seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--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>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
seal-use auth check [--corp <corpId>]
seal-use auth link [--corp <corpId>] [--note <note>]
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>]
seal-use auth link list [--corp <corpId>]
seal-use auth link revoke <tokenId> [--corp <corpId>]
seal-use auth hose-link [--corp <corpId>] [--expire <seconds>] [--force]
seal-use auth hose-link [--corp <corpId>] [--expire <duration>] [--force]
seal-use auth hose-openapi-token [--corp <corpId>] [--force]
seal-use auth hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]
seal-use auth hose-keys [--corp <corpId>] [--reveal]
seal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]
seal-use users search <keyword> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--corp <corpId>]
seal-use users activate <userId> [--corp <corpId>]
seal-use users delegation <userIdOrPhone|name> [--note <note>] [--expire <duration>] [--corp <corpId>]
seal-use users reset-password <userId> --yes [--corp <corpId>]
seal-use users get <userId> [--corp <corpId>]
seal-use users delete <userId> --yes [--corp <corpId>]
@@ -129,8 +185,12 @@ seal-use contacts departments [<departmentId>] [--corp <corpId>]
seal-use contacts children <departmentId> [--corp <corpId>]
seal-use contacts users <departmentId> [--corp <corpId>]
seal-use contacts sync-time [--corp <corpId>]
seal-use data expenses --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use data invoices --corp <corpId> [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>]
seal-use data expenses [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]
seal-use invoices trace <invoiceNumber> [--corp <corpId>]
seal-use invoices <invoiceNumber> [--corp <corpId>]
seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
seal-use llm config [--corp <corpId>]
seal-use llm providers [--corp <corpId>]
seal-use permissions available [--corp <corpId>]
@@ -138,69 +198,56 @@ seal-use permissions configs [--corp <corpId>]
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<资源包.zip>] [--webhook <idOrName>] [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--dry-run] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--dry-run] [--corp <corpId>]
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>] [--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] [--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>]
seal-use preference thinking-depth policies list [--corp <corpId>]
seal-use preference thinking-depth policies upsert --json '{...}' [--dry-run] [--corp <corpId>]
seal-use preference thinking-depth policies remove <policyId> [--dry-run] [--corp <corpId>]
seal-use analytics insight [--start-date <ISO>] [--end-date <ISO>] [--limit <n>] [--corp <corpId>]
seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]
seal-use analytics performance [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--corp <corpId>]
seal-use analytics analyze <recordId> [--corp <corpId>]
seal-use analytics export [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force] [--limit <n>] [--corp <corpId>]
seal-use context [--ruleVersion <versionId|versionNumber|latest>] [--documentLimit 50] [--corp <corpId>]
seal-use source config [--corp <corpId>]
seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]
seal-use analytics insight --corp <corpId> [--start-date <ISO>] [--end-date <ISO>] [--limit <n>]
seal-use analytics risks <tagId> --corp <corpId> [--start-date <ISO>] [--end-date <ISO>]
seal-use analytics performance --corp <corpId> [--start-date <ISO|ms>] [--end-date <ISO|ms>]
seal-use analytics analyze <recordId> --corp <corpId>
seal-use analytics export --corp <corpId> [--downloads] [--out <file>] [--start-date <ISO>] [--end-date <ISO>] [--force]
seal-use approval-runs count --corp <corpId> [--status APPROVED] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>]
seal-use approval-runs export --corp <corpId> [--sn <SN1,SN2>] [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--out <file>] [--with-flow]
seal-use documents list [--summary] [--fields <id,title,purpose,updatedAt>] [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
seal-use documents get <documentId> [--out <path>] [--content-format raw] [--overwrite] [--corp <corpId>]
seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]
seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]
seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]
seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
seal-use changelog [--limit <n>]
seal-use probe [<corpId>]
seal-use langfuse check
seal-use langfuse cache-refresh <traceId> [--trace-id <traceId>]
seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]
seal-use langfuse search <traceId> --query <term1,term2> [--fields input,output] [--max-results <n>]
seal-use langfuse observation <traceId> <observationId> [--fields input,output] [--max-chars <n>]
seal-use langfuse session <sessionId> [--trace-limit <n>]
seal-use langfuse observations <traceId> [--name-contains <text>] [--type <type>]
seal-use langfuse url <traceId>
seal-use langfuse attachment-flow <traceId> [--file-id <id>] [--file-name <name>]
seal-use langfuse rule-flow <traceId> --rule <规则内容>
seal-use mcp
seal-use mcp config
seal-use mcp-config
seal-use skill dump
seal-use skill install [--dir <path>|--local]
seal-use skill status
seal-use doctor [--quiet]
seal-use doctor guide
seal-use doctor paths
seal-use doctor tenant [--corp <corpId>] [--quiet]
seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-on-flips]
```
<!-- END GENERATED CLI COMMANDS -->
以下补充说明独立维护:
```bash
# --sn / --sns: 定向筛选单据编号(支持逗号/分号/空格分隔,跳过全量分页,秒级定向导出特定单据)
# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,默认关闭以节省合思 API 调用)
# 导出文件名自动追加精确到分钟的 _YYYYMMDD_HHmm 时间戳后缀防止文件覆盖,格式:${企业名称}_审核记录_${时间区间}_${条数}_${导出时间戳}.xlsx
seal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
seal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
seal-use approval-runs attachments <recordId> --corp <corpId>
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] --corp <corpId>
seal-use approval-runs result <recordId> --corp <corpId> [--summary]
seal-use approval-runs link <recordId> --corp <corpId>
seal-use approval-runs link <recordId> --auto-login [--expire 7200] --corp <corpId>
seal-use approval-runs link <recordId> --type hose-document --corp <corpId>
seal-use approval-runs link --sn <documentSN> [--auto-login] --corp <corpId>
# 生成审批详情链接:seal-use approval-runs link <recordId>
seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sourceDocumentSN>]
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--force] [--reuse-window 5m] --corp <corpId>
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp <corpId>
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" --corp <corpId>
seal-use simulation status <batchId> --corp <corpId>
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] --corp <corpId>
seal-use simulation clean <batchId> --yes --corp <corpId>
seal-use simulation specifications [--integration <sign-key>] --corp <corpId>
seal-use simulation approval-definitions --corp <corpId>
seal-use simulation list [--limit 50] --corp <corpId>
seal-use simulation get <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
seal-use simulation integrations --corp <corpId>
seal-use simulation package-upload <材料包.zip> --corp <corpId>
```
## CLI Command Overview
@@ -246,6 +293,13 @@ Durable Hose configs are identified by `source.type: "hose"` plus `appKey/appSec
- `seal-use corps hose-extract-keys <url> [--reveal] [--save] [--name <name>] [--app-key <key>] [--key-id <id>] [--overwrite]` extracts OpenAPI keys (`appKey` and `appSecurity`) from a Hose assistance link (`thirdparty.html`). The old `extract-keys`/`extract-key`/`extract-hose-keys` forms remain aliases. **Hose Subdomain Privilege Elevation**: elevates a short-lived session token to permanent Hose OpenAPI developer credentials. If `--save` is specified, registers the enterprise as a durable Hose tenant. If the enterprise has multiple keys, execution halts and candidates are listed unless `--app-key` or `--key-id` is passed.
- `seal-use corps hose-keys [<url> | <corpId>] [--reveal] [--save]` reads/displays OpenAPI keys for a Hose assistance link or configured Hose enterprise (masked by default, `--reveal` displays plaintext). The old `keys` form remains an alias. Rejects non-Hose/native-Seal tenants with exit code 2.
- `seal-use auth hose-extract-keys <url>` and `seal-use auth hose-keys [--corp <corpId>]` are the explicit Hose auth-domain commands. The old `extract-keys`/`extract-key`/`extract-hose-keys` and `keys` forms remain aliases.
- `seal-use auth hose-openapi-token [--corp <corpId>] [--force]` exchanges the persisted Hose `appKey/appSecurity` for an OpenAPI `accessToken` and prints it as machine JSON (`token`, `expiresAt`, `cached`; aliases `openapi-token`, `hose-token`). A still-fresh cached token is reused by default (`cached: true`, with a stderr notice); `--force` mints a new one. Unlike `auth check`, the token is intentionally unredacted. Rejects non-Hose tenants with exit code 2; missing credentials exit 13.
Hose outbound discovery & EBot callback (first-level `hose-ebot` command; Hose-only):
- `seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal]` is the default entry: it searches the Hose outbound message log by document SN and returns records that each carry a unique `id` (`INVOKING`=出站触发, `CALLBACK`=回调), plus the `flowId`/`nodeId`/`messageId`/`rejectionNum` a callback needs. Read-only; any `signKey` inside records is masked unless `--reveal`.
- `seal-use hose-ebot messages [--type flow|message] [--reveal]` lists every outbound message config on the Hose side (`messageName`, `signKey`, `callbackUrl`, `enable`, …). `signKey` is the `config_id` embedded in the callback URL; masked unless `--reveal`. Read-only.
- `seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> …` runs the EBot approval callback (`POST /api/openapi/v1/approval`) and writes the result into the approval flow; success is `value.code=204`. Requires `--dry-run` (masked preview) or `--yes/--confirm` (otherwise exit 10). `--sign-key` is optional when the enterprise has exactly one Seal Hose integration. Upstream business codes map to exit codes: 401→11, 400→13, 412/500→1. Only EBot-node approvals are supported upstream.
Read-only discovery:
@@ -368,7 +422,8 @@ Approval runs, simulations, and Langfuse bridge:
- `seal-use simulation approval-definitions --corp <corpId>` lists available Feishu approval definitions so an `approvalCode` can be selected before creating a batch.
- `seal-use simulation wait <batchId> --corp <corpId>`
- `seal-use simulation clean <batchId> --yes --corp <corpId>`
- `seal-use simulation list --corp <corpId>`
- `seal-use simulation list [--query <text>] [--since <time>] [--until <time>] [--all] --corp <corpId>` (过滤在本地完成,见下方“本地聚合”说明)
- `seal-use simulation search "<关键词>" [--since 7d] [--all] --corp <corpId>` (**本地聚合检索,非云端原生**;先按 limit/offset 拉取批次再过滤,响应 `retrieval.serverSideSearch: false`)
- `seal-use simulation get <batchId> --corp <corpId>`
- `seal-use simulation batch-records <batchId> --corp <corpId>`
- `seal-use simulation templates --corp <corpId>`
@@ -469,8 +524,12 @@ seal-use simulation get <batchId> --corp <corpId>
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
seal-use simulation integrations --corp <corpId>
# 本地检索批次(服务端无原生 search): 界面「任务 fe1993e4」可直接粘贴
seal-use simulation search "任务 fe1993e4" --since 7d --all --corp <corpId>
```
> **本地聚合,不是云端原生检索**:`/api/v1/simulation/batches` 只有 `limit`/`offset`,没有名称或关键词检索,批次对象也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。`list --query/--since/--until` 与 `search` 都是 CLI 先把批次拉到本地再过滤,返回体固定带 `retrieval: { mode: "local_scan", serverSideSearch: false, scanned }`;命中范围以 `scanned` 为准,不覆盖未扫描的批次(`truncated: true` 时用 `--all` 或调大 `--max-scan`)。不要把它当作服务端能力向用户描述。
## Failure Handling
- If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`.
@@ -211,8 +211,8 @@ Do not automatically rerun or resubmit the customer's production document. Run a
- 优先输出自带内联样式的**自包含单文件 HTML**(以及原始 Markdown)。用户可以在任何 Chrome / Edge 浏览器中直接打开、查看,或使用浏览器的「打印 -> 另存为 PDF」无损导出,字体内嵌、格式绝对保真。
- 当本地宿主环境已具备极简无头工具(如系统级 `typst` 或系统自带无头 Chrome/Edge)时,可静默协同编译出 PDF 文件一同交付。
2. **操作身份声明原则(避免张冠李戴)**:
- 严禁将底层 API 绑定的系统凭证名称(如“周晚容”)直接写为“发布操作人”;
- 必须显式注明:**“发布操作身份:周晚容(系统调用凭证账号,由智能助手代执行)”**,明确告知这只是调用系统所使用的鉴权身份,不代表是该自然人亲自操作。
- 严禁将底层 API 绑定的系统凭证名称直接写为“发布操作人”;
- 必须显式注明:**“发布操作身份:<系统凭证绑定账号/员工名>(系统调用凭证账号,由智能助手代执行)”**,明确告知这只是调用系统所使用的鉴权身份,不代表是该自然人亲自操作。
3. **免尾戳原则 (No Vendor Footers)**:
- 报告文末与页脚**严禁携带工具自夸尾戳**(例如:❌ `生成工具:Seal Use Automated Engineering Suite`),保持纯粹中立、属于客户企业与业务事实本身的技术报告风格。
4. **双重呈现原则 (Diff + 完整前文/完整后文)**:
@@ -261,6 +261,6 @@ Do not automatically rerun or resubmit the customer's production document. Run a
- **线上版本序号**:发布的版本序号(如 `版本 34`)
- **线上版本名称**:发布时录入的具体版本名称
- **正式生效时间**:精确到秒的北京时间
- **系统调用凭证账号**:显式说明“周晚容(系统调用凭证账号,由智能助手代执行)”
- **系统调用凭证账号**:显式说明“<系统凭证绑定账号/员工名>(系统调用凭证账号,由智能助手代执行)”
- **全量规则总数**:核对总数是否变化
- **规则一致性校验**:确认目标规则文本与确认内容 100% 逐字吻合
+65
View File
@@ -0,0 +1,65 @@
# 知识文档:文件编辑与安全更新
## 列表与读取
```bash
seal-use documents list --summary --corp <corpId>
seal-use documents list --fields id,title,purpose,updatedAt --corp <corpId>
seal-use documents get <documentId> --corp <corpId>
```
`list` 默认保留既有完整 JSON;`--summary` 返回 id、title、purpose、contentType、status、enabled、scenarios、tags、updatedAt,不返回 content。显式 `--fields` 覆盖摘要字段,非法字段报 exit 2。分页、过滤、total 不变;投影在客户端完成,不能据此声称减少了上游网络流量,也不会逐篇请求详情。
`get` 默认输出完整文档 JSON,正文位于 `content`。`--output-file <path>` 保存整份 JSON;`--out <path>` 单独导出正文,两者互斥。
## 导出 → 编辑 → 预览 → 更新
```bash
seal-use documents get <documentId> --out ./document.txt --corp <corpId>
# 编辑 document.txt;保留相邻的 document.txt.seal-use.json
seal-use documents update <documentId> --content-file ./document.txt --dry-run --corp <corpId>
seal-use documents update <documentId> --content-file ./document.txt --yes --corp <corpId>
```
导出产生三个本地文件:指定路径的 UTF-8 正文、相邻的 `.seal-use.json` 来源清单、配置目录 `document-history/` 下的原文快照。stdout 仍是 JSON 回执,包含路径、字节数、内容哈希和 snapshotId;文件权限为 0600,历史目录为 0700。正文不插入标题或 frontmatter,不 trim、不补末尾换行。扩展名可以是 `.md`,但不会改变编码行为。目标父目录须已存在;覆盖既有导出必须显式 `--overwrite`,目录和符号链接不可覆盖。
本期只支持 raw;`--content-format raw` 可显式指定。正文中的反斜杠、转义竖线、硬换行、代码与路径全部保持。Markdown 自动互转尚未开放,`--content-format markdown` 报 exit 2。不要批量替换 `\\` 或 `\|`:平台编码尚需真实脱敏样本证明可逆,JSON 显示转义也不能当作存储协议。
更新自动读取相邻来源清单,核对企业、Seal 服务地址与文档身份,并比较本次拟修改字段的导出基线哈希。远端变化返回 exit 1、`DOCUMENT_CONFLICT`,不会写入;`--yes` 不能绕过。重新导出并合并编辑后再预览。存在但损坏的清单报 exit 13,不会退化成无基线更新。
没有清单的旧 `--content-file` / `--content` 输入仍支持,但 preview、stderr 和回执明确 `baselineAvailable:false`,无法发现编辑期间发生的他人修改。不要为了绕过冲突删除清单。一次成功更新后,如需继续编辑,应重新导出新基线;保留本地修改前先自行留存,`--overwrite` 会覆盖正文。
仅传 `--content-file` 时,PATCH 只提交 content;title、purpose、status、enabled、scenarios、tags 保持。多个正文来源同时给出报 exit 2;非法 UTF-8、文件不可读或清单不可用报 exit 13。空或纯空白正文默认拒绝;明确要清空时加 `--allow-empty`。未变化的内容返回 `changed:false`,不写远端、不产生更新快照。
## 写入安全与兼容变化
所有 documents 创建、更新、删除正式执行均要求 `--yes` 或 `--confirm`,否则 exit 10。旧创建和更新脚本必须补确认标志。`--dry-run` 始终只读,即使同时提供确认标志也不写远端;预览不写历史快照。预览返回 `preview:true` 和结构化 `changesDiff`;内容过大时使用 `--output-file` 或有意选择 `--full`,仍遵守 exit 12 输出保护。
```bash
seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --dry-run --corp <corpId>
seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --yes --corp <corpId>
seal-use documents delete <documentId> --dry-run --corp <corpId>
seal-use documents delete <documentId> --yes --corp <corpId>
```
创建/更新成功回执改为紧凑执行结果,不再输出整篇文档;需要全文时重新 `get`。正式更新和删除前先保存实际将被覆盖的完整文档快照,备份失败则不写远端。创建和更新后回读,只有正文及预期保留字段核对通过才返回 `verified:true`。写请求禁用自动重试。
更新错误同时返回 JSON 状态和非零退出码:
- `DOCUMENT_CONFLICT`:未执行写入,重新导出并审阅。
- `DOCUMENT_WRITE_UNCERTAIN`:写入结果不确定,`executed:null`;先用返回的只读 next action 回读,不能盲目重跑。
- `DOCUMENT_READBACK_FAILED`:已完成写请求,回读失败,`executed:true, verified:false`。
- `DOCUMENT_VERIFICATION_FAILED`:回读和预期不符,保留 snapshotId / snapshotFile,核对当前状态后处理。
- `DOCUMENT_AUTH_FAILED`:认证失败,exit 11;其他上述失败一般 exit 1。
创建请求失败时可能无法取得新文档 ID,应先查看列表,避免重复创建。删除成功表示服务端已接受删除;快照保留原对象,但重建不承诺保留原文档 ID。错误结果不会自动再次覆盖,也不会自动回滚。快照记录采集阶段,不能仅凭快照存在判断后续写入是否成功。
## 本地恢复、草稿和平台版本边界
历史默认位于当前配置文件所在目录的 `document-history/<来源哈希>/<snapshotId>.json`。包含正文和元数据,视为敏感业务数据,勿加入项目 Git。首期不自动清理快照,也没有快照浏览/一键恢复命令。
需要恢复时先回读当前文档,读取快照的 `document.content` 写成独立正文文件,再预览并确认更新;标题/状态等仅在明确需要时逐项传入。不要把整个快照当 PATCH 上传,不要覆盖作者、时间戳等系统字段。恢复本身是一次新更新,仍需备份与回读。
当前 CLI 有 `--status draft` 输入,但未验证其是否允许“旧发布版继续生效,同时编辑新草稿”。不要为了获得本地编辑稿而修改线上 status。文档更新可能立即影响生产;已发布版本与草稿并存、跨设备完整版本历史、原生回滚和原子条件写入属于待验证的平台能力。
客户端 GET→PATCH 之间仍有竞态窗口;哈希检查不能替代服务端 If-Match/修订号条件更新。本地快照只覆盖本机 CLI 留存过的内容,不能称为平台原生版本历史。
@@ -0,0 +1,60 @@
# 费用明细:按单号核验入库
## 首选入口
用户问“某单据的费用明细是否进入 SealAI 数据管理 → 费用明细”时,先确定目标企业,再运行:
```bash
seal-use expenses --sn <documentSN> --corp <corpId>
```
这是只读查询,使用同一个 `sealExpensesList` 内部能力和既有 MCP 网关,不触发同步、审批或费用写入。`data expenses --sn` 与该入口等价。不要把查询扩大为自动补录或重新审核。
## 已验证的关联路径
2026-10-20 对测试站点公开前端契约和测试企业进行只读往返验证:费用列表支持 `filter.recordId`,返回 `id`、`documentId`、`recordId` 等字段;普通文本搜索用于费用类型、描述、金额。同一已存在费用对应的原单号作为普通搜索词时未命中,按关联审批记录 ID 筛选则命中。因此不能用 `--search <单号>` 的空结果判断未入库,也不能仅因审批记录存在就说费用已入库。
CLI 先分页查询单号候选审批记录,对 `sourceDocumentSN` 做精确相等匹配,再对每个匹配记录调用费用列表的 `filter[recordId]`。返回的费用必须与请求记录 ID 一致;若双方都有 documentId,还必须一致。重审/重放产生的多个记录均纳入查询,不默认只查最新一次;费用按稳定费用 ID 去重,不按单号去重。
单号对应多个不同来源单据时返回 `ambiguous_source_documents`,不混合归因。费用列表本身没有已验证的单号直接过滤;找不到关联审批记录时返回 `approval_link_not_found` 和“无法确定”,无法凭该路径排除孤立费用记录。必要时取得明确关联记录 ID,用下面的原始列表入口补查。
## 结论判定
- `status:found, found:true`:至少一条费用已从费用库读取并通过关联校验。`matchedCount` 是已观察到的去重条数,`complete:false` 时仅为下限。
- `status:not_found, found:false, complete:true`:单号匹配到的可见审批记录及其费用分页均已查完,指定费用日期范围内未找到关联费用。对外表述“关联范围内未找到”,不要断言该单据从未入库或推断入库失败根因。
- `status:unknown, found:null, complete:false`:没有足够证据确认存在或不存在。常见原因包括没有审批关联、同号多原单据、扫描上限、分页重复/变化、关联字段不符或接口失败。
所有结果都有 `source:seal_expense_store`、`verification:existence_only`、查询时间、queryScope、scanned、关联记录及费用摘要;摘要不输出员工手机号和邮箱。不得把存在性查询解释成“所有原始费用明细均完整入库”;逐项完整性对账需另有原单明细和稳定行标识。
## 日期、分页和上限
单号查询不自动添加本月或最近一年范围;显式日期只过滤费用列表,不过滤用于定位的审批记录创建日期:
```bash
seal-use expenses --sn <documentSN> --start-date 2025-01-01 --end-date 2025-12-31T23:59:59+08:00 --corp <corpId>
seal-use expenses --sn <documentSN> --limit 100 --max-scan 10000 --corp <corpId>
```
queryScope.startDate/endDate 是规范化毫秒时间戳,null 表示未显式传入;不代表服务端所有历史数据都永久可见。费用记录时间戳和 checkedAt 使用北京时间 ISO 秒级格式。
单号查询中 `--limit` 为每页大小(1–100,默认 100),不是最多返回匹配条数。审批候选扫描和费用扫描各最多 `--max-scan` 条(默认 5000,最高 10000);整个流程最多发起 100 次业务分页调用。命中上限保留已发现证据,标记 `complete:false`,不会以不完整查询得出否定结论。HTTP 层安全 GET 重试不包含在业务分页调用计数中。
总数缺失或变化、重复页、过早空页、记录变化、响应超出页大小都不能认为查询完整。分页不是数据库快照,`complete:true` 只表示当前观察到的相关分页已遍历,不是对并发写入的事务保证。
`--sn` 与 `--search`、`--record-id`、`--offset` 互斥;`--max-scan` 仅用于 `--sn`。非法组合报 exit 2,扫描范围参数未通过 schema 校验报 exit 13。
## 普通费用列表
```bash
seal-use expenses list --search <text> --offset 0 --limit 50 --corp <corpId>
seal-use expenses list --record-id <recordId> --corp <corpId>
seal-use data expenses --record-id <recordId> --corp <corpId>
```
不传 `--sn` 时继续返回原始 `{expenses,total}`,不进行入库判定;`--record-id` 透传精确关联过滤,普通列表由调用者控制分页。列表请求始终包含平台要求的 filter 对象,未指定筛选时发送空搜索值。日期支持 ISO 或时间戳,并转换为接口所需毫秒值。未知子命令和裸位置单号会报用法错误,不会被忽略后返回无关列表。
## 失败和大结果
单号查询接口失败时 stdout 保留结构化查询状态,stderr 说明不完整,进程返回非零:认证失败 exit 11,其他上游/响应格式失败 exit 1。已有确切匹配仍保留 `found:true`,但 `complete:false`;没有匹配证据时保持 unknown。不能把失败当作未入库。
大结果可使用 `--output-file <path>` 保存 JSON,或有意选择 `--full` 放开现有输出保护;默认超过输出限制返回 exit 12。原始费用列表和结构化单号查询均遵守 stdout 纯 JSON。
@@ -34,6 +34,10 @@ Read the JSON `stages` in order:
Do not expect tokens in the output; the command intentionally redacts or omits them.
Seal requests made with a renewable Hose session recover from HTTP 401 once for GET/HEAD/OPTIONS: the CLI exchanges a fresh Seal session and retries that read. Concurrent reads share the refresh, and another 401 stops with exit 11. Fixed Seal Bearer credentials are not refreshed automatically. Mutation requests are never replayed by this recovery path; inspect their result before deciding whether to retry.
When the caller needs the actual OpenAPI `accessToken` itself (for example to call Hose OpenAPI from their own script), use `seal-use auth hose-openapi-token --corp <corpId> [--force]`. It prints the unredacted token as JSON together with `expiresAt` and `cached` (`cached: true` means a still-fresh local token was reused; pass `--force` to mint a new one). Non-Hose enterprises are rejected with exit 2, and a Hose enterprise without persisted `appKey/appSecurity` exits 13.
## Get a Hose authorization link
When the user asks for a 合思/易快报授权链接、登录链接、入口链接, or says "来一个授权链接" for a Hose sourced enterprise, return the Hose provisional/CloseAPI URL from `getProvisionalAuth`'s `value.message`.
@@ -61,9 +65,23 @@ Important:
- Do not return the Seal tenant URL such as `https://<tenant>.sealai.cc`; that is not the Hose authorization link.
- Do not manually assemble `thirdparty.html` with a global/OpenAPI token.
- `seal-use auth check` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **Formatting Requirement**: When returning an authorization link (`auth link` or `auth hose-link`) to the user, ALWAYS provide:
1. The operator identity used (e.g. `周晚容` / `staffId`),
2. The exact expiration time in Beijing time (`expiresAt`, e.g. `2026-09-22T11:20:02+08:00`),
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <duration>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default `2h`, e.g. `7d` or `7200`).
- **Formatting Requirement**: When returning a Hose authorization link (`auth hose-link`) to the user, directly use the CLI JSON output:
1. The operator identity: **always report the person's name from `staffName`**. The CLI automatically looks up the exact Hose employee for `auth hose-link`, and the actual Seal session user for `auth link`. Do not use `staffId` as a person's name, infer a name from an ID, or assume both systems use the same person. If `identityStatus` is `unresolved` (`staffName: null`), explicitly report that the identity name could not be verified; do not silently omit it or guess,
2. The exact expiration time in Beijing time (`expiresAt`),
3. BOTH a code block (` ```text ... ``` `) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- **Dedicated CLI Command**: Use `seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports `--expire` (default 7200, e.g. 86400 for 1 day).
- **Seal AI Platform Direct Link**: Use `seal-use auth link --corp <corpId> [--note <note>]`. This generates a 24-hour provisional delegation link for the Seal AI audit platform (`https://*.sealai.cc`).
- **Seal AI Platform Direct Link**: If the user needs a delegation link for the Seal AI audit platform (`https://*.sealai.cc`) instead of Hose/易快报, use `seal-use auth link --corp <corpId> [--note <note>]`.
## Assistance link identity and reporting contract
This contract applies to both `auth hose-link` and `auth link`, including `auth link --from-link`.
- `staffName` is the verified person's name, or `null`; `identityStatus` is `resolved` / `unresolved`. Identity lookups do not switch the configured employee, modify enterprise configuration, reset a password, or request additional privileges.
- Hose links return `roleNames` from that exact employee's role assignments. `null` means role names could not be verified; an empty array means the employee response explicitly contained no roles. Never infer “主管理员” merely because the CLI can generate a link.
- Seal links return the actual session user's `isAdmin` and `permissions`. Report administrative access only when confirmed by those fields; `null` means the lookup failed. Seal permissions describe Seal access and must not be presented as Hose permissions.
- If an identity lookup fails, the generated link remains usable, the command returns `staffName: null` / `identityStatus: "unresolved"`, and a diagnostic is written to `stderr`. Additional role-lookup failure preserves a verified name but returns `roleNames: null`. Never claim that an unresolved identity is an administrator.
- A user-facing link report must include **enterprise name, person's name, verified role/permissions (or explicitly unknown), target system, and exact Beijing expiration time**. Include both a code block and a clickable link. If returning Hose and Seal links together, report identity and permissions separately for each.
- Do not show raw tokens, full phone numbers, or internal IDs as explanatory prose. Do not fetch or list unrelated administrator candidates just to describe the identity of an existing link.
Example presentation: “企业:示例公司;合思登录身份:张三(主管理员);有效期至北京时间 …”;“Seal 登录身份:李四(依据 CLI 返回的管理员标记及权限说明);有效期至北京时间 …”。The names may differ; use each command's actual output.
@@ -91,6 +91,31 @@ seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --
实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。
出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。
### 出站发现与 EBot 回调(一级命令 `hose-ebot`)
`sync` 之后,出站消息的发现与回调审批走独立的一级命令 `seal-use hose-ebot`(Hose 专属,非合思租户拒绝,退出码 13):
```text
# 9. 按单号搜索出站/回调记录(默认入口;每条记录带唯一 id)
seal-use hose-ebot search <sn> --corp <corpId>
seal-use hose-ebot search <sn> --type invoking --corp <corpId> # 只看 出站触发
seal-use hose-ebot search <sn> --type callback --corp <corpId> # 只看 回调
# 10. 列出全部出站消息配置,发现 signKey(即回调地址中的 config_id)
seal-use hose-ebot messages --corp <corpId>
seal-use hose-ebot messages --reveal --type flow --corp <corpId> # 明文 signKey
# 11. 回调审批(写入审批流;先 --dry-run 预览,正式执行必须 --yes)
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --dry-run
seal-use hose-ebot callback --corp <corpId> --sign-key <signKey> \
--flow-id <flowId> --node-id <nodeId> --action accept --comment "同意" --yes
```
- `hose-ebot search` 返回记录的唯一 `id`,回调所需的 `flowId`/`nodeId` 直接来自记录的 `request` 字段;`--type invoking|callback` 区分出站触发与回调,`--limit` 控制条数(默认 20)。
- `hose-ebot messages --reveal` 输出的 `signKey` 就是 `hose-ebot callback --sign-key` 的入参;企业仅有一个 Seal 合思集成时可省略 `--sign-key` 自动解析。
- 回调成功返回 `value.code=204`;上游业务码映射退出码:401(signKey 错误)→11、400(参数错误)→13、412/500 →1。缺少 `--yes`/`--confirm` 且无 `--dry-run` 时退出码 10。accessToken 在回调前实时换取,不复用缓存;仅支持 EBot 节点的审批回调。
---
## 4. 关键配置参数定义
+324 -163
View File
@@ -1,218 +1,379 @@
# 月度 AI 审核准确率报告编制与人机协同研讨指南 (Monthly Report Authoring & Tangent Workflow)
# AI 审核报告编制与人机协同作业指南 (AI Audit Report Authoring & Tangent Workflow)
本文档面向 AI Agent 与实施运维人员,规范从**月度数据拉取与底稿装配**、**分歧单据人机复核研讨(Tangent)**、**纯文本质性分析与整改建议共创**,到**严格离线校验与多格式商业交付**的端到端标准工作流。
本文档面向 **AI Agent 与操作用户**,是 Seal Enterprise AI 审核报告的**唯一权威业务与实施参考手册**。详细规范从**周期数据拉取与自由裁量台账导出**、**分歧单据人机复核研讨(Tangent)**、**Agent 自主执笔与排版**,到**严格离线门禁校验、全格式渲染与多轮修改**的端到端人机协同闭环。
---
## 核心认知与架构分工 (Core Architecture & Division of Labor)
1. **轻量数据接口 + Agent 亲自执笔 (The Lightweight Authoring Model)**:
- **工具层(确定性计算与缓存)**:负责拉取审批运行数据、统计分模板数据、计算准确率公式、记录用户逐单裁决(`review set`)、生成独立矢量图表(`report chart venn`)以及提供离线格式/数值勾稽校验(`report validate`)与全格式编译(`report render`)。
- **Agent 层(智能分析与文档创作)**:Agent 最擅长理解数据、归纳总结、与用户对话,并撰写自然流畅的业务报告。因此,**推荐让 Agent 直接获取轻量数据包(`seal-use report data`),亲自将真实数据、分歧案例与整改建议手工填入 Markdown 模板**,彻底摆脱代码中死板的正则替换与假数据。
2. **严禁交付半成品 (Zero-Mock Delivery Red Line)**:
- 严禁向客户交付带有 `> ⚠️ **数据说明**:...需人工归类后替换` 警告框的半成品。
- 严禁保留模板中写死的假数据(如 `B26002583` 等固定占位单号)或字面 `(截图)` 占位符。
- 严禁跳过 `seal-use report validate` 直接交付未经勾稽校验的文档。
3. **单个判断条件与人机复核契约 (Triggered Conditions & Tangent Contract)**:
- 分歧单据中包含 AI 拦截触发的**单个具体判断条件**(`triggeredConditions`,如“发票日期早于行程日”、“未附改衣明细表”)。
- Agent 获取初版数据后,**必须主动进入“研讨模式”(Tangent)**,向用户呈现这些具体的触发条件,征询真实业务对错裁决,并引导用户共创定性分析文本。
## 目录 (Table of Contents)
1. [报告定位与三大业务类型](#一报告定位与三大业务类型)
2. [核心边界与人机分工契约](#二核心边界与人机分工契约)
3. [术语规范契约(彻底弃用“失准”)](#三术语规范契约彻底弃用失准)
4. [自由裁量台账 16 列规格说明](#四自由裁量台账-16-列规格说明)
5. [端到端人机协同作业流程](#五端到端人机协同作业流程)
6. [标准 6 大章节深度剖析](#六标准-6-大章节深度剖析)
7. [动态自适应与用户至上原则](#七动态自适应与用户至上原则)
8. [离线门禁校验规则手册 (Zero-Error Gate)](#八离线门禁校验规则手册-zero-error-gate)
9. [全格式编译渲染与跨端交付](#九全格式编译渲染与跨端交付)
---
## 端到端标准研讨流 (The 4-Stage Lifecycle)
## 一、报告定位与三大业务类型
Seal AI 审核报告是向企业财务总监、风控负责人及 CIO 交付的专业级商业论证报告。它并非局限于传统的“月报”,而是普遍涵盖以下三类业务场景:
| 报告类型 | 业务场景与目标 | 取数周期与事实源建议 | 核心关注论证点 |
| :--- | :--- | :--- | :--- |
| **验收审核报告** | 客户试点验证、POC 结项交付、商业签约对赌。证明 AI 审核精度达到既定合同标准。 | 自定义时间周期(`--start-date` / `--end-date`),支持按模板过滤(`--templates`),结合 Excel 裁剪。 | 规则通过率、AI 依规审核准确率、与人工对比的漏审与误拦截率、可量化提效收益。 |
| **上线审核报告** | 新版规则上线前评审、规则组重大重构、系统切割试运行。评估新规则组的稳定性与风控阻断效果。 | 指定跑批周期,或通过 staging 环境同步与模拟跑批结果对照。 | 新旧规则差异、对存量单据的重判影响、高风险违规拦截有效性。 |
| **周期审核报告** | 持续运营中的月度、季度、半年度常规复盘。跟踪规则运行健康度、持续调优风控卡口。 | 按月度或季度周期提取,结合跨周累积的复核裁决记录。 | 准确率演进趋势、人机分歧根因演进、未在线配置规则的制度沉淀进度。 |
> [!NOTE]
> **统一论证骨架**:这三类报告共享完全相同的 6 大章节骨架、数学勾稽定义、双端穿透跳转与离线门禁规则。
---
## 二、核心边界与人机分工契约
为了确保报告的客观性、专业性与极高的交付质量,系统严格划分了**确定性工具**与**智能裁量权**的边界:
```
┌────────────────────────────────────────────────────────────────────────┐
│ 确定性工具层(CLI 扳手) │
│ │
│ - 纯粹提数:从云端无损拉取审批运行数据,绝不主观推断对错 │
│ - 双向台账:导出含双端完整依据的 Excel,导入裁决结果 │
│ - 严格边界:一旦传入 --ledger,完全以本地文件为唯一事实源,绝不越界回查 │
│ - 机械门禁:严格执行格式自洽与数学勾稽检查(退出码 1 拦截) │
│ - 无赖渲染:跨平台原生编译 HTML / PNG / PDF,免 Python / Node │
└───────────────────────────────────┬────────────────────────────────────┘
│ 赋能支撑
▼
┌────────────────────────────────────────────────────────────────────────┐
│ 智能执笔层(AI Agent) │
│ │
│ - 自由裁量权:在 Excel 台账中随意删减模板(如 8 删 4)、清洗脏数据、定性裁决 │
│ - 人机研讨(Tangent):向用户汇报分歧案例,征询权威定性,拒绝臆断 │
│ - 深度归因执笔:将数字转化为深刻的业务管理建议与制度沉淀路径 │
│ - 交付质量底线:严禁向用户交付带警告框、模板假单号或占位符的半成品 │
│ - 门禁自纠自查:遇门禁报错主动阅读 issue 并精准自愈修正 │
└────────────────────────────────────────────────────────────────────────┘
```
### 1. CLI 只是扳手,绝不越界
- CLI 的职责是提供精确、高速、可复现的确定性底层操作。
- **边界约束**:当用户或 Agent 指定 `--ledger 台账.xlsx` 时,CLI 将**完全把该 Excel 视为封闭的全局事实边界**。在 Excel 中被 Agent 删除的单据行或模板,CLI 绝不会再去远程接口探查其历史存在。CLI 的离线门禁校验也仅针对当前 Excel 内部剩余的数据做逻辑与数学校验。
### 2. Agent 自由裁量与研讨契约
- **台账是自由裁量的操作台**:Agent 导出台账后,可以根据业务实际诉求对数据进行清洗,例如:剔除尚在调试中的非核心模板单据、剔除测试人员提交的脏数据等。
- **严禁交付半成品**:数据接口无法自动获知分歧单到底“谁对谁错”,无法凭空撰写针对性的管理对策。生成 Markdown 草稿后,Agent 严禁直接把带有 `> ⚠️ 数据说明` 警告框、模板占位符或示例假数据的初稿交付给客户,必须进入人机协同研讨,共创定性。
---
## 三、术语规范契约(彻底弃用“失准”)
在过往沟通中,由于词汇模糊,常常将“AI 驳回而人工放行”粗暴地称为“AI 失准”或“失准单据”。这导致客户管理层极易产生巨大误解:**“到底是单据本身有问题违规了,还是你们 AI 做错了?”**
为了彻底杜绝此类误解,在所有的代码、台账、Markdown 报告、命令行输出以及与用户的对话中,**必须严格区分以下两个相互独立的评价层级**:
### 1. 层级一:单据合规性判断(审批决策 / Approval Decision)
- **定义**:AI 或人工审批人在业务流水线中,针对送审单据本身是否合规给出的处理操作。
- **规范措辞**:
- `通过 (Pass)`:单据材料完备、发票合规、符合当前既定规则,予以放行。
- `驳回 (Reject)`:单据存在不合规事项、附件缺失或超标,予以阻断退回。
- `违规拦截`:在论述风控价值时,将驳回操作正确定性为识别并阻断了合规风险。
- **禁忌**:❌ 严禁使用“单据错误”、“AI 错误”来指名单据被驳回。单据驳回是规则库正常发挥风控作用的正面体现。
### 2. 层级二:审核行为复核评判(裁决判定 / Review Verdict)
- **定义**:在后续审计复核或人机研讨中,对“AI 或人工在审批时的决策行为是否正确”所下的仲裁定性。
- **规范枚举与标准术语**:
| 枚举代码 | 标准对外术语 | 业务判定基准 | 准确率归因影响 |
| :--- | :--- | :--- | :--- |
| `ai_correct` | **AI 判断正确 / 人工判断错误** | AI 依线上既定规则放行或拦截完全正确;人工属于漏审放行,或依据线下口头标准无理驳回。 | 计入 AI 依规正确(分子 +1);扣减人工准确率。 |
| `human_correct` | **人工判断正确 / AI 判定误判** | 人工判定符合真实业务合规标准;AI 出现误报(误拦合规单)或漏报(放行违规单)。 | 计入 AI 判定误判(不计入分子);计入人工正确。 |
| `both_correct` | **双方判断均正确** | AI 依线上规则合规,人工依线下审批特例亦合情合理,双方均符合各自依据。 | 计入双方正确。 |
| `both_wrong` | **双方判定均误判** | AI 与人工均产生认知失误或操作偏差。 | 双方均扣减准确率。 |
| `undecided` | **存疑待定** | 关键发票或凭证附件信息不全,当前暂无法定性。 | 暂不计入已裁决样本。 |
### 3. 一致单覆盖支持(Consistent Override)
- 默认情况下,通常只需裁决 AI 与人工结论相反(`diverged`)的分歧单。
- 但若用户指名道姓要求对人机原本同向的单据进行覆盖,系统完全支持:
- **典型场景**:一笔单据 AI 给出了驳回,人工也给出了驳回。但用户复核后指出:“AI 是依据发票跨期规则精准拦截,而人工审批人只是随便填了个理由跟风驳回,甚至根本没看发票”。
- **处理方式**:用户或 Agent 将该单录入 `ai_correct`,系统将明确认定 AI 正确、人工失误,如实扣减人工准确率。
### 4. 双键定位机制(`recordId` vs `sn`)
- 在企业实际运行中,同一张单据(相同 `sn`)可能由于被驳回修改而经历多轮审核,或者在测试环境中被多次跑批,产生多条运行记录。
- **机制**:复核账本与 Excel 台账全面支持双键定位。系统优先以精准单次审核运行的 `recordId` 为主键进行裁决绑定;若未提供 `recordId`,则向下兼容以单据业务单号 `sn` 匹配。
---
## 四、自由裁量台账 16 列规格说明
通过 `seal-use report ledger` 导出的 Excel / CSV 台账是人机自由裁量的核心载体。它包含了双端最完整的判定凭据:
```markdown
| 列号 | 列名 | 字段含义与说明 | 数据来源 |
| :--- | :--- | :--- | :--- |
| **A** | `审核ID(recordId)` | 单次 AI 审核运行的唯一主键,用于版本精确锁定 | 审批运行记录主键 |
| **B** | `单据编号(SN)` | 单据业务自然键(如 `CL2608001`) | 业务单据主键 |
| **C** | `单据模板` | 单据所属表单类型(如 `差旅报销单`) | 业务单据模板 |
| **D** | `单据标题/事由` | 单据报销或申请标题、事由摘要 | 业务单据属性 |
| **E** | `提交人` | 单据发起员工姓名或工号 | 业务单据属性 |
| **F** | `费用承担部门` | 单据所属费用发生或承担部门 | 业务单据属性 |
| **G** | `跑批时间` | AI 审核执行的北京时间 | 审批运行属性 |
| **H** | `AI审批决策` | AI 给出的审批决策:`同意` / `驳回` | 审批运行结果 |
| **I** | `AI审核完整意见与违规详情` | **核心证据列**:包含 AI 综合评语、触发的具体规则编号及违规条款细则 | 聚合 summary + conditions |
| **J** | `人工审批结论` | 人工审批人实际操作:`同意` / `驳回` / `终止` | 人工操作记录 |
| **K** | `人工审批批注/驳回说明` | **核心证据列**:人工审批人在系统后台填写的真实审批意见与驳回理由 | 提取 manualComment / rejectComment |
| **L** | `人机一致性` | `一致`、`分歧` 或 `未完结/流转中` | 比较 H 与 J 决策极性 |
| **M** | `复核定性裁决` | **自由裁量填报列**:Agent/用户填写的定性结论(支持中英文口语化识别) | 人工/Agent 填报 |
| **N** | `复核人` | 执行该单裁决核查的业务人员或 Agent 署名 | 人工/Agent 填报 |
| **O** | `复核批注说明` | 针对复核裁决填写的定性分析、归因说明与管理整改建议 | 人工/Agent 填报 |
| **P** | `审批耗时(秒)` | AI 模型单据全生命周期审核耗时(秒) | 审批运行属性 |
```
> [!TIP]
> **中文口语化智能解析**:在「复核定性裁决」列中,用户不仅可以填写规范枚举(`ai_correct`),也可以自由填写中文口语:“`AI判断正确 / 人工判断错误`”、“`AI正确`”、“`人工正确`”、“`AI误判`”、“`双方正确`”等,CLI 在加载时均能百分之百精准识别映射。
>
> 若需核查单据更细维度的明细金额、发票结构化票面或附件凭证,Agent 可通过 `seal-use approval-runs get <recordId>` 或 `seal-use hose-ebot` 按需补充调阅。
---
## 五、端到端人机协同作业流程
### 模式 A:Excel 台账自由裁量驱动(首推推荐)
```mermaid
flowchart TD
S1["Stage 1: 获取轻量报告数据包与模板 (report data & template)"] --> S2["Stage 2: 分歧单据人机复核研讨 (Diverged Runs Review Tangent)"]
S2 --> S3["Stage 3: 纯文本深度叙述与质性洞察共创 (Agent 执笔填入 Markdown)"]
S3 --> S4["Stage 4: 离线门禁校验与全格式商业渲染 (report validate & render)"]
sequenceDiagram
autonumber
actor User as 用户 / 客户管理层
participant Agent as AI Agent (智能执笔)
participant CLI as seal-use CLI (确定性扳手)
participant Cloud as Seal 云端 / 本地缓存
Agent->>CLI: 1. seal-use report ledger --start-date ... --end-date ... --out 台账.xlsx
CLI->>Cloud: 提取全量明细与双端完整意见
CLI-->>Agent: 产出《台账.xlsx》(16列完整数据)
Note over Agent: 2. 自由裁量清洗:<br/>- 删去暂未验收的 4 种模板<br/>- 剔除异常测试单<br/>- 在复核定性列填写裁决
Agent->>User: 汇报分歧案例并对齐裁决
User-->>Agent: 确认裁决定性
Agent->>CLI: 3. seal-use report generate --ledger 台账.xlsx --out 报告.md
Note over CLI: 严格以本地 Excel 为边界,<br/>绝不回查云端已删除数据
CLI-->>Agent: 生成干净完整的结构化 Markdown
Agent->>CLI: 4. seal-use report validate 报告.md
CLI-->>Agent: 门禁通过 (valid: true)
Agent->>CLI: 5. seal-use report render 报告.md --out <输出目录>/报告/
CLI-->>User: 交付单文件 HTML、A4 PDF 与长图 PNG
```
---
### 第一阶段:获取轻量报告数据包与模板 (Data Pack & Template Scaffold)
#### 推荐方式:轻量数据驱动 (Mode A: Lightweight Data Pack)
1. **拉取纯结构化报告数据包 (JSON)**:
```bash
seal-use report data --month <YYYY-MM> --corp <corpId>
```
*说明:返回纯 JSON 数据,包含当期效能指标(样本量、AI 准确率、采纳率、平均耗时)、公式代入值、分模板统计、TOP 风险标签,以及**全量分歧单据及其触发的具体判断条件(`triggeredConditions`)**,完全不依赖任何 Markdown 模板。*
2. **获取纯净内置模板与生成矢量图表**:
```bash
# 保存纯净的内置月报模板 Markdown
seal-use report template --out reports/<企业名>-<YYYYMM>.md
# 准备配图目录并独立生成动态维恩图 SVG
mkdir -p reports/<企业名>-<YYYYMM>.assets
seal-use report chart venn --ai <AI准确率> --human <人工准确率> --out reports/<企业名>-<YYYYMM>.assets/图1-准确率对比.svg
```
#### 传统方式:模板脚手架一键填充 (Mode B: Template Scaffold)
亦可使用经典命令一键拉取并由代码初步组装 Markdown 脚手架与伴随台账:
#### 具体操作指令:
```bash
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/<企业名>-<YYYYMM>.md
# 步骤 1:一键拉取指定周期的全量明细台账(含 AI 完整意见与人工批注)
seal-use report ledger --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId> --out <输出目录>/明细台账.xlsx
# 步骤 2:Agent 或用户在 Excel 中自由裁量,增删模板行并填入裁决;
# 步骤 3:严格以修改后的台账为唯一事实源,出具报告草稿
seal-use report generate --ledger <输出目录>/明细台账.xlsx --corp <corpId> --out <输出目录>/审核报告.md
# 步骤 4:严格门禁校验(必须通过)
seal-use report validate <输出目录>/审核报告.md
# 步骤 5:本地全格式编译渲染
seal-use report render <输出目录>/审核报告.md --out <输出目录>/审核报告/
```
*诊断返回 JSON 中的 `notes.humanAccuracyAvailable`,若为 `false` 则说明尚未复核,需进入第二阶段。*
> [!TIP]
> **全量取数与分页控制**:`seal-use report ledger`、`report data` 与 `report generate` 默认自动分页拉取所选时间区间内的**全部审批单据**(内置 100,000 笔安全防死循环上限),无任何 500 条的人工截断限制。如需做小样本分析或限定抓取笔数,可传入 `--limit <n>`(别名 `--max-runs <n>` / `-n <n>`,例如 `--limit 2000`)。
> [!IMPORTANT]
> **落盘位置红线(代码仓零污染)**:`seal-use` 是全局 CLI,输出目录与执行目录解耦。最终交付物以客户/用户要求为最高准则,放用户指定目录或系统下载目录(如 `~/Downloads/<企业名>-<YYYYMM>/`),**严禁在代码仓库根目录(如 `Code/seal-use/reports/`)生成或留存业务报告文件**。会话内供 Agent 快速读取的只读快照落在全局缓存 `~/.cache/seal-use/reports/<corpId>/<YYYY-MM>/`,缓存天然可丢弃、可随时清理,且不占用 `~/.config/`。
---
### 第二阶段:分歧单据人机复核研讨 (Diverged Runs Review Tangent)
### 模式 B:CLI 命令行实时研讨驱动
在 AI 审核与人工审批结论相悖的单据中(AI 同意但人工驳回,或 AI 驳回但人工同意),必须由熟悉业务的实施/财务人员裁决真实对错。
适合小批量单据核查或纯命令行快速批处理:
1. **提取高价值分歧单据**:
Agent 可直接分析伴随生成的《明细台账.csv》或调用查询命令检索分歧单据:
1. **提取结构化数据包**:
```bash
# 查看或导出当前月份分歧单据
seal-use report review list --month <YYYY-MM> --corp <corpId>
seal-use report data --start-date 2026-08-12 --end-date 2026-09-18 --corp <corpId>
```
返回纯 JSON 数据,包含全周期样本量、AI 准确率、采纳率、平均耗时、分模板统计及全量分歧单池(`divergedRuns`)。
2. **结构化向用户呈现案例并征询裁决 (Interactive Tangent Prompting)**:
挑选 3~5 笔最具代表性的分歧单据,以结构化卡片形式向用户呈现关键上下文:
2. **双链穿透研讨呈现**:
在聊天窗口中结构化呈报案例给用户:
```markdown
【分歧单据复核研讨】单号:FP2026090123
- 单据模板:一般费用报销单【发票】- 个人报销
- 提交人 / 部门:张三 / 市场运营部
- AI 审核结论:建议驳回(发票开票日期早于出差行程起始日)
- 人工实际操作:直接审批同意(已支付)
【分歧单据复核确认】单号:CL2608019
- 单据模板:差旅报销单
- 快速核验:[🔗 Seal AI 审核详情](https://<corp>.sealai.cc/approval-result/<recordId>) | [📑 合思原单据](https://wx2.ekuaibao.com/...)
- AI 审核结论:驳回(检测到机票发票开票日期早于出差申请单行程日期 15 天,违反制度条款 3.2)
- 人工实际操作:同意放行(批注:线下特殊批准提前出发)
- 触发条件:规则 0012「行程与票据日期逻辑核验」
👉 请教您对本单的裁决看法:
1. AI 正确(ai_correct):按财务规范确实属于跨期违规,人工属于特批放行,AI 依规放行正确;
2. 人工正确(human_correct):业务实际存在合理提前购票场景,规则未配置豁免,属于 AI 误判;
3. 双方都对(both_correct):规则执行无误,但存在线下特殊批复;
4. 其它/暂无法定性(undecided)。
👉 请教您对本单的裁决:
1. AI 判断正确 / 人工判断错误 (ai_correct):AI 依规拦截正确,人工属于线下特批未补充审批单;
2. 人工判断正确 / AI 判定误判 (human_correct):业务允许特定场景提前订票,属于规则库未覆盖例外;
3. 双方判断均正确 (both_correct):双方各自依规,属于已知特例。
```
3. **实时录入裁决定性**:
收到用户的确认后,执行 CLI 命令持久化到本地裁决账本:
3. **裁决录入持久化账本**:
```bash
seal-use report review set \
--month <YYYY-MM> \
--sn <SN> \
--verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> \
--note "跨期发票已获总监线下邮件特批,规则库缺少该豁免卡口" \
--reviewed-by "实施顾问/财务张老师" \
--corp <corpId>
--corp <corpId> \
--record-id <ID> \
--sn CL2608019 \
--verdict ai_correct \
--note "线下特批未附审批单,AI依规拦截正确"
```
4. **离线台账批量导入**:
若线下已在 Excel 台账中集中批量评审完毕,可一键导入持久化存储:
```bash
seal-use report review import <输出目录>/明细台账.xlsx --corp <corpId>
```
*本地存储路径:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`。*
---
### 第三阶段:纯文本深度叙述与质性洞察共创 (Qualitative Narrative Co-Authoring)
## 六、标准 6 大章节深度剖析
模板中的许多章节属于管理咨询范畴,必须通过与用户沟通讨论,将模板占位符改写为客户真实的业务洞察:
标准报告结构是严谨的商业论证闭环,每一章节均承载特定的论证目的:
```mermaid
flowchart LR
Review["复核定性成果"] --> Sec2["§2 失准归因与整改方案"]
Context["企业本月动态"] --> Sec1["§1.3 稳定性与迭代历程"]
RiskData["AI 风险统计"] --> Sec3["§3 潜在风险与拦截案例"]
HumanValue["财务反馈"] --> Sec4["§4 综合效益与人力释放"]
```
§1. 审核测试结果 ───► 数据底座:样本总量、AI 准确率、人工准确率公式及维恩图
│
§2. AI 判定误判分析 ─► 坦诚归因:剖析模型不足与漏报误报,输出规则库调优方案
│
§3. 潜在风险拦截 ───► 商业价值:展示 AI 额外识别并拦截的违规单(专票、大额、假凭证)
│
§4. 综合效益 ─────► 宏观收益:审核秒级时效提升、准确度收益与财务人力释放
│
§5. 分歧与复核归因 ─► 管理对策:分析人机差异根本原因,引导推动线上规则库制度沉淀
│
§6. 支撑数据与交付 ─► 交付落地:分模板准确率细分表,配套交付《明细台账.xlsx》
```
#### 1. §1.3 系统稳定性与迭代历程
- **模板问题**:内置模板写着死板的“自 8 月 8 日迭代后稳定在 96.07%”。
- **研讨引导**:
> “请问本月企业是否有上线新规则版本、更新豁免白名单,或者合思系统有单据模板调整?我们可以把具体的迭代时间节点与优化成效如实写进‘系统稳定性’一节。”
- **改写产出**:将通用的占位文字改写为真实事件,例如:“9 月 12 日优化‘发票查重与专票强制校验规则’后,全月系统审核成功率稳定在 97.4%”。
### 1. 标题与信息表
- 包含报告编号(`HD001`)、企业名称、统计期间、生成日期与报告状态(`草稿` 或 `正式交付`)。
#### 2. §2 AI 失准深度归因与整改方案(报告核心技术价值)
- **模板问题**:代码存在硬编码假单号(如 `B26002583`)或默认示例分类。
- **研讨引导**:
> “基于我们在第二阶段复核出的 X 笔 AI 真实失准(`verdict === human_correct`),主要集中在以下两个现象:
> 1. 多附件中部分手写收据金额识别偏差(3 笔);
> 2. 差旅补贴跨自然月计算未自动扣除周末(2 笔)。
> 我们来总结针对这几类问题的整改建议与下月规则库优化计划。”
- **改写产出**:
- 彻底替换 `§2.2 ~ §2.4` 中的单号与问题描述为真实 SN 和真实原因;
- 撰写具体的“整改建议”,如“下期将差旅补贴计算调整为按工作日日历核算”、“针对手写收据调优大模型 OCR 提示词”。
### 2. §1 审核测试结果
- **1.1 数据来源与样本量**:明确审计周期的起止时间、纳管模板清单及样本总量($S$)。
- **1.2 准确率结论与维恩图**:
- 展示核心指标:AI 依规准确率(如 $93.75\%$)、人工实际准确率(如 $87.50\%$)。
- **准确率严密计算公式**(必须在正文中由 LaTeX 公式呈现):
$$\text{AI 准确率} = \frac{D_1 + D_4}{S} = \frac{\text{双方同向一致通过数} + \text{AI 依规正确拦截数}}{\text{样本总量}}$$
- 动态内嵌维恩图(`图 1:AI 与人工审核准确率对比.svg`),直观呈现两者的交集与重合度。
- **图表纯粹性**:标准模板只保留这一张数据驱动维恩图;旧版图二(综合效益耗时直方图)与图三(截图占位)已全面废弃并清理,严禁再引入冗余图表或相关死代码。
#### 3. §3 潜在风险与拦截价值业务解读
- **业务价值**:AI 拦截了人工放行的风险单据,是向企业管理层证明“AI 审计提升内控质量”的最有力武器。
- **研讨引导**:
> “在人工审核通过的单据中,AI 额外拦截了 28 笔风险,其中 TOP 1 为‘无正规发票直接支付’(16 笔)。这些单据主要发生在哪些部门?我们可以结合公司的差旅/采购内控制度进行强调。”
### 3. §2 AI 判定误判分析
- **2.1 误判构成总览**:总结在分歧复核中判定为“人工正确 / AI 判定误判”的单据总量及在全样本中的占比。
- **2.2~2.4 TOP 误判典型案例剖析**:
- 提炼真实典型案例,详细分析 AI 判定失误的机理(如复杂多税率混合计算偏差、手写收据文字模糊混淆等)。
- **针对性调优方案**:明确给出技术调优与规则优化对策(例如:升级发票 OCR 专有切片模型、增设多税率拆行核对规则)。
#### 4. §4 综合效益与人力释放量化
- **质性文案润色**:与客户确认 AI 审核耗时(通常在 10~30 秒)对比财务人工审核周期(通常为 1~3 个工作日),突出“即提即审”的时效提升,以及协助财务防堵税务合规风险(如进项税虚开、专票未取等)的价值。
### 4. §3 AI 发现的潜在风险
- **3.1 潜在风险总览**:总结 AI 依规成功拦截的真实违规单据总量及金额。
- **3.2~3.4 典型风险单据拦截剖析**:
- 列举人工审批人漏审放行、但被 AI 坚决拦截的重大合规隐患(例如:专票未开具销货清单、跨期发票混报、同一发票重复报销、连号大额发票等)。
- 证明 AI 审核在“防范税务稽查风险”与“资金合规安全”上的不可替代价值。
#### 5. 截图凭证指引 (Screenshots Placement)
- 提醒用户在正式提交前,将关键凭证(如发票实物照片、审批流驳回截图)替换到报告中:
- 将 `assets/图3-示例截图.svg` 替换为真实的代表性单据截图;
- 将 `§6` 明细表格中的 `(截图)` 占位字样替换为具体的图片引用或在附件中打包交付。
### 5. §4 综合效益
- 表格化汇总四大效益维度:
- **审核时效**:人工平均审批耗时(例如 18.5 小时)vs AI 平均秒级处理时效(例如 4.2 秒),提效超 99%;
- **风控拦截**:全周期拦截违规单据笔数与违规金额;
- **人力释放**:测算自动化放行单据释放的财务初审工作量。
### 6. §5 审核分歧与复核归因
- **5.1 分歧原因分类表**:将全部人机分歧单归结为三大主因:
1. *未在线配置规则(人工依据口头制度驳回)*:占比通常最高;
2. *规则库逻辑配置缺陷(边界条件未覆盖)*;
3. *AI 模型识别偏差*。
- **5.2 管理优化建议**:引导企业将线下口头标准转化为线上明确规则,消除人为认知分歧。
- **5.3 引导查验台账**:明确指引领导与操作人员查阅随包附带的《明细台账.xlsx》进行逐单核对。
### 7. §6 支撑数据与交付材料
- **6.1 分模板统计表**:列出每个模板的单据量、通过率、AI 准确率与自动化放行率。
- **6.2 交付清单**:列出报告交付套件(Markdown 源码、矢量图包、单文件 HTML、A4 PDF、明细台账 Excel)。
---
### 第四阶段:报告重新装配、严格离线校验与全格式导出 (Regenerate, Validate & Render)
## 七、动态自适应与用户至上原则
1. **重新装配底稿(应用人工裁决)**:
```bash
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/<企业名>-<YYYYMM>.md --overwrite
```
*此时,由于本地已存在 `review-store` 裁决记录,底稿将自动完成指标闭环:人工准确率真实回填、维恩图准确渲染、分模板同意/驳回比与全量范围自动更新。*
为了杜绝后续使用的 AI Agent 产生死板教条(如“机械凑满 3 类问题”、“非要放满 3 行表格”),特此确立以下人机协同规范:
2. **更新共创文本**:
使用文件编辑工具将第三阶段共创出的 §1.3、§2、§3、§4 文本精准写入 `reports/<企业名>-<YYYYMM>.md`,替换掉模板占位内容。
### 1. 必选骨架 vs 动态子分类
- **大章节是不可缺少的骨架**:§1~§6 大章节承载了严密的商业论证闭环,必须完整保留。
- **动态子分类完全由真实数据驱动**:
- §2(误判分析)与 §3(潜在风险)下的具体问题分类,**数量完全由实际跑批数据与用户业务关注度决定**。
- **唯一硬性底线**:动态章节下**至少保留 1 个子分类**(不能是无正文的空标题),可以是 TOP 1~2、TOP 1~3 或拓展至 TOP 1~5。
- **数学守恒定律**:分类表中的单数之和必须严格等于「合计」行单数,且百分比之和严格等于 100%(触发 `NM001`~`NM003` 校验)。
3. **执行严格离线门禁校验 (Zero-Error Gate)**:
```bash
seal-use report validate reports/<企业名>-<YYYYMM>.md
```
必须确保**校验通过(`valid: true`,0 ERROR)**。若遇到报错,参考下文排查手册逐一修复。
### 2. 用户态度为最高准则
- Agent 必须以用户的业务判断与汇报习惯为首要输入。若用户要求“重点只突出 2 个主要风险”、“案例只放 1 个最具代表性的单据”,Agent 必须立即响应调整,绝不生搬硬套模板默认布局。
4. **全格式编译与打包交付 (Multi-Format Rendering)**:
```bash
# 一键导出自包含 HTML、超高精度长图 PNG 与 A4 PDF
seal-use report render reports/<企业名>-<YYYYMM>.md --out build/<企业名>-<YYYYMM>
```
最终交付物清单:
- `build/<企业名>-<YYYYMM>.html`:内嵌图片与 KaTeX 公式样式的单文件自包含 HTML(适合邮件与在线流转);
- `build/<企业名>-<YYYYMM>.png`:高清晰度长图(适合飞书、微信、钉钉大图浏览);
- `build/<企业名>-<YYYYMM>.pdf`:标准 A4 分页打印级 PDF(适合正式汇报与归档);
- `reports/明细台账.xlsx` 与 `明细台账.csv`:审计复核完整底账。
### 3. 表格超链接免维护契约
- **Markdown 源码专注业务语义**:用户与 Agent 在编写或编辑 Markdown 报告草稿时,无需在表格中手写超长技术 URL。
- **自动化升级**:管线渲染引擎会自动识别表格结构。若表格只有两列,会自动将第一列单号升级为跳转链接;若表头显式声明了 `审核详情` 列,会自动在第 3 列生成直达链接。
---
## 模板各章节深度剖析与动静边界 (Section Anatomy)
## 八、离线门禁校验规则手册 (Zero-Error Gate)
| 章节编号与名称 | 数据来源与机制 | 是否需要人工协同改写 / 研讨 | 说明与关注要点 |
| :--- | :--- | :--- | :--- |
| **标题与报告信息表** | 动态填充 | 否(自动替换) | 自动写入企业名称、统计期间、生成日期与报告编号。 |
| **摘要** | 动态换数 | 建议微调 | 正则自动替换总样本数、AI 准确率与风险拦截数;可根据企业汇报偏好润色开篇。 |
| **§1.1 数据来源与范围** | 动态生成 | 否(自动替换) | 自动汇总样本总量、业务单据模板种类数与决策分布。 |
| **§1.2 核心准确率 & 图 1** | 动态联动 | 否(自动联动) | AI 与人工准确率、公式代入值以及图 1 维恩图由底账与 review-store 动态计算联动。 |
| **§1.3 系统稳定性** | 静态占位 | **必须研讨改写** | 采纳率自动填充,但“迭代影响”必须替换为本月真实的上线与优化历程。 |
| **§2.1 失准构成总览** | 动态 / 模板 | **必须研讨确认** | 需确保维度单数、占比与合计严密勾稽(满足 NM001/NM003)。 |
| **§2.2~2.4 TOP 失准案例** | 模板假数据 | **必须完全替换** | **绝对不能保留假单号**!必须填入第二阶段复核出的真实 Bad Case 与针对性整改建议。 |
| **§3 潜在风险与拦截案例** | 动态标签 + 切片 | 建议研讨润色 | TOP 3 风险标签自动更新,明细案例可结合客户核心财务卡口进行价值解读。 |
| **§4 综合效益 & 图 2** | 半动态 + 静态图 | 建议微调 | 时效与风险笔数自动填充;工作量价值可结合企业实际审批流转特点润色。 |
| **§5 一致性示例 & 图 3** | 动态切片 + 占位图 | 需替换配图 | 表格可自动抽取人机一致单据,图 3 需替换为真实系统截图。 |
| **§6 AI通过/人工驳回明细** | 动态生成 | 需补充截图 | 自动取前 10 笔分歧单及复核结论;最后一列 `(截图)` 需在交付前处理。 |
| **§7 支撑数据与台账** | 动态生成 | 否(自动生成) | §7.1 分模板表、§7.2 配套 Excel 台账、§7.3 全量覆盖声明均由引擎全自动产出。 |
在执行最终渲染交付前,Agent **必须**执行门禁校验命令:
```bash
seal-use report validate <输出目录>/审核报告.md
```
若存在任何格式或数学勾稽问题,命令将以 **退出码 1** 阻断导出,并输出带有错误代码的 JSON。Agent 必须根据报错信息自主编辑修正。
### 门禁重点校验代码全集:
| 错误代码 | 校验类别 | 校验规则与触发条件 | 常见违规示例 | 正确自纠方式 |
| :--- | :--- | :--- | :--- | :--- |
| **`HD001`** | 标题规范 | 二级章节必须从 1 开始严格连续递增(`## 1.`, `## 2.`, ..., `## 6.`),不得跳级。 | 出现 `## 1.` 后面直接跟 `## 3.` | 修正章节编号,确保 1~6 完整递增。 |
| **`HD002`** | 标题规范 | 三级子章节编号必须隶属于所属二级章节(如 `### 2.1`, `### 2.2`)。 | 在 `## 2.` 章节下出现 `### 3.1` | 修正三级标题序号,保持父子关系一致。 |
| **`TB001`** | 表格格式 | 表格所有行的列数必须前后完全一致。 | 表头有 4 列,某数据行只有 3 列 | 补齐缺失的竖线 `\|` 与单元格占位。 |
| **`TB002`** | 表格格式 | 表头行(Header)严禁带有加粗 `**` 标记。 | `\| **单号** \| **问题描述** \|` | 移除表头文字中的 `**`,改为 `\| 单号 \| 问题描述 \|`。 |
| **`NM001`** | 数学勾稽 | 分类统计表中的各分项单张数之和,必须严格等于合计行。 | 分项分别为 3、5、2,但合计行写了 11 | 修正分项数值或合计行数值,确保加法恒等。 |
| **`NM002`** | 数学勾稽 | 分类统计表中的百分比之和,必须严格等于 100.0%(允许 0.1% 舍入误差)。 | 各分项占比之和为 98.5% | 重新核算各分项百分比,确保相加为 100%。 |
| **`NM003`** | 数学勾稽 | 分项百分比计算值必须与单数占比精确勾稽。 | 10 单中占 3 单,但百分比写了 40% | 修正为 `\frac{3}{10} = 30.0\%`。 |
| **`NM004`** | 文本勾稽 | 正文中提及的误判/分歧笔数,必须与表格及公式中的笔数完全一致。 | 正文写“共发现 3 笔误判”,但表格列了 4 笔 | 统一正文措辞与表格中的单据笔数。 |
| **`NM005`** | 公式算术 | 准确率 LaTeX 公式算术必须成立,且分子分母在正文中可溯源。 | `\frac{221}{240} = 95.00\%` (实际应为 92.08%) | 重新计算并填入真实算术结果。 |
| **`INFO001`** | 信息完备 | 开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。 | 缺失了“报告编号”行 | 在开篇信息表中补齐所缺行。 |
| **`INFO002`** | 信息完备 | 开篇信息表中的关键字段值不得为空或保留 `待填充` 占位符。 | 统计期间写着 `YYYY-MM` | 替换为真实的业务统计区间(如 `2026-08-12 ~ 2026-09-18`)。 |
---
## 离线校验错误码排查手册 (Validator Error Code Playbook)
## 九、全格式编译渲染与跨端交付
当 `seal-use report validate` 报错时,请根据以下代码快速定位:
门禁校验通过后,使用 `report render` 即可产出全套工业级交付产物:
- **`NM001` / `NM002`(分类总数与小节单数勾稽不符)**:
- 检查总览表各行单数之和是否等于“合计”行;
- 检查总览表中的单数是否与后续 `### 2.x` 或 `### 3.x` 小节标题中的 `(N 张 / X%)` 严格一致。
- **`NM003`(百分比算术不符)**:
- 检查各行单数除以合计总数得出的百分比,与表格中写的百分比差距是否超过 `0.15%`。
- **`NM004`(明细表行数与正文叙述不符)**:
- 检查 `§6` 叙述中的 `在上述 **N 笔**单据中` 与 `依规正确(计入 D4)`、`AI 真实失准` 数量是否与下表明细行完全相等。
- **`NM005`(公式算术错误或数值孤岛)**:
- 检查 `$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$` 中 $A / B$ 是否算术等于 $C\%$;
- 检查公式里的分子、分母数值是否在正文其他段落中有据可查。
- **`TB001`(表格列数不齐)**:某一行的竖线 `|` 数量与表头不一致,或未对单元格中的 `|` 字符进行 `\|` 转义。
- **`TB002`(表头含加粗)**:Markdown 表头行中严禁使用 `**加粗**`。
- **`HD001` / `HD002`(标题跳级或章节编号不规范)**:
- 二级标题必须严格按 `## 1.`, `## 2.`, ..., `## 7.` 编号;
- 不能出现从 `#` 直接跳到 `###` 的层级跳跃。
- **`INFO001` / `INFO002`(报告信息表缺失或字段为空)**:开篇信息表必须完整包含:报告编号、客户名称、统计期间、报告状态、生成日期。
- **`IMG001`(图片不存在)**:引用的本地图片路径未找到,检查相对路径是否有效或文件名是否有中文编码问题。
- **`FM001` / `MK001`(模板痕迹或 Frontmatter 残留)**:严禁出现 YAML frontmatter 或 `<!--slot:` 等模板痕迹,必须是纯净 Markdown。
```bash
# 一键编译全套产物(单文件 HTML、A4 PDF、超清拼接长图 PNG)
seal-use report render <输出目录>/审核报告.md --out <输出目录>/审核报告/ --format all
# 整包打包归档(产出 ZIP / 完整文件夹,自动收拢 Markdown、配图与明细台账)
seal-use report export <输出目录>/审核报告.md --out <输出目录>/交付整包/
```
### 交付产物技术特性与适用场景:
1. **单文件自包含 HTML (`.html`)**:
- 所有 CSS 样式、矢量图表与字体资源全部通过 Data URI 内嵌;
- 零网络依赖,双击即可在任何现代浏览器中完美打开浏览;
- 内部超链接天然支持跨端点击穿透直达系统后台。
2. **A4 打印级分页 PDF (`.pdf`)**:
- 严格遵循 A4 物理纸张比例与分页控制(CSS `@page` 与 `break-inside: avoid`);
- 页眉页脚清晰标注企业名称与唯一报告编号;
- 支持高精度矢量文字缩放,适用于正式纸质打印与签字归档。
3. **超高清拼接长图 (`.png`)**:
- 由原生无头浏览器以 4x 视口倍率切片截取,并通过高性能图形算法在内存中无损拼接;
- 专为钉钉、微信、飞书等移动端 IM 聊天窗口设计,方便管理层在手机上顺滑滑动审阅。
4. **末尾术语与指标定义规范附录页 (Glossary Page)**:
- 渲染流水线在生成 HTML、PDF、PNG 产物时,自动在末尾追加独立术语解释与指标定义附录页(涵盖审批决策与五类裁决、人机一致性与极性、KaTeX 量化公式、`recordId` 与 `SN` 双主键规范);
- 原始报告 Markdown 保持干净不被侵入修改;PDF 在打印时拥有独立的物理分页隔离(`page-break-before: always`);
- 若特定简报场景不需要附录页,可在 `report render` 或 `report export` 中指定 `--no-glossary` 参数跳过追加。
@@ -170,6 +170,8 @@ flowchart TD
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>" --wait
```
> **打断/重发防重复扣费**:批次创建默认幂等——复用窗口(默认 5 分钟,`--reuse-window` 可调)内对同一组 `--flow-ids`/`--package-ids` 再次执行 `simulation create` 会直接返回既有批次(`reused: true`),不会重复扣费。若 `--wait` 挂起期间命令被用户消息打断或后台 task 被 kill,**先执行 `seal-use simulation list --limit 3` 查最近批次**(同单批次可能已在服务端跑完),拿到批次 ID 后用 `status`/`batch-records` 取结果;确认无在途同单批次再决定重发。确需立刻重跑同组单号时显式加 `--force`。
>
> **按界面名称找历史批次**:模拟测试服务端没有名称/关键词检索,批次也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。用 `seal-use simulation search "任务 fe1993e4" --since 7d` 或 `seal-use simulation list --query <关键词> --since <时间>`;这是 **CLI 本地聚合检索**(先按 `limit`/`offset` 拉取再过滤,响应带 `retrieval.serverSideSearch: false`),命中范围以 `scanned` 为准,需要覆盖更早批次时加 `--all`(可用 `--max-scan` 控上限)。
- **方式 C:Webhook 原始报文重放 (Webhook Replay,仅限事件通知调测)**:
直接将正式企业的特定单据/不良案例表单抽取并推送到测试企业 Webhook 通道:
+3 -2
View File
@@ -107,12 +107,13 @@ describe("CLI version & help handling", () => {
expect(result.stderr).toContain("Usage: seal-use documents get <documentId>");
});
test("requires --yes confirmation on documents delete", () => {
test("requires explicit confirmation on documents delete", () => {
const env = makeConfigEnv();
const result = runCli(["documents", "delete", "doc-123", "--corp", "corp-a"], env);
expect(result.status).toBe(10);
expect(result.stderr).toContain("Refusing to delete document 'doc-123' without --yes.");
expect(result.stderr).toContain("documents delete requires --yes or --confirm");
expect(result.stderr).toContain("--dry-run");
});
test("does not hijack --version option when passed to subcommands like rules", () => {
+1 -1
View File
@@ -11,7 +11,7 @@ process.stderr.on("error", (err: any) => {
if (err?.code === "EPIPE") process.exit(0);
});
performRuntimeSelfHealing();
await performRuntimeSelfHealing();
const entryFile = fileURLToPath(import.meta.url);
const isCompiled = isCompiledBinary();
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, test } from "bun:test";
import { AREA_ALIASES, UPDATE_ALIASES, normalizeCliArea } from "./area-aliases.js";
import { KNOWN_AREAS } from "./runner.js";
/**
* Drift guard for the shared alias table.
*
* `read-only.ts` once hand-copied the alias pairs from `runner.ts` and the two
* silently diverged — the exact class of bug the 2026-10-17 architecture
* review called "two sources of truth". The tables now live in one module and
* are imported by dispatch, help, and the read-only gateway; these tests make
* the remaining cross-module contract explicit: an alias may only point at an
* area the dispatcher actually handles, may not chain into another alias, and
* must not shadow a real area name.
*/
describe("area alias integrity", () => {
test("every alias resolves to a dispatchable area", () => {
const dangling = Object.entries(AREA_ALIASES)
.filter(([, target]) => !KNOWN_AREAS.has(target))
.map(([alias, target]) => `${alias} -> ${target}`);
expect(dangling).toEqual([]);
});
test("no alias chains into another alias", () => {
// normalizeCliArea applies one lookup; a chained alias would dispatch the
// raw alias spelling as a command area and fail with "Unknown command".
const chained = Object.values(AREA_ALIASES).filter((target) => target in AREA_ALIASES);
expect(chained).toEqual([]);
});
test("alias spellings never shadow a real area name", () => {
// KNOWN_AREAS is the handler tables plus the alias keys; subtracting the
// alias keys recovers the real dispatch areas. An alias colliding with
// one of them would be dead weight at best and ambiguous at worst.
const realAreas = new Set([...KNOWN_AREAS].filter((area) => !(area in AREA_ALIASES)));
const shadowing = Object.keys(AREA_ALIASES).filter((alias) => realAreas.has(alias));
expect(shadowing).toEqual([]);
});
test("every update spelling normalizes onto the real update area", () => {
for (const spelling of UPDATE_ALIASES) {
expect(normalizeCliArea(spelling)).toBe("update");
}
expect(KNOWN_AREAS.has("update")).toBe(true);
});
test("normalization is idempotent and case-insensitive", () => {
expect(normalizeCliArea(normalizeCliArea("corp"))).toBe("corps");
expect(normalizeCliArea("CORP")).toBe("corps");
expect(normalizeCliArea("Self-Update")).toBe("update");
});
test("every alias and update spelling resolves through KNOWN_AREAS", () => {
// Alias keys must be members outright: help lookup and the read-only
// gateway resolve the raw spelling before any normalization. Update
// spellings are normalized first, so their canonical target is the
// dispatchable name.
for (const alias of Object.keys(AREA_ALIASES)) {
expect(KNOWN_AREAS.has(alias)).toBe(true);
}
for (const spelling of UPDATE_ALIASES) {
expect(KNOWN_AREAS.has(normalizeCliArea(spelling))).toBe(true);
}
});
});
+18
View File
@@ -0,0 +1,18 @@
/** Execution aliases shared by dispatch, help, and the read-only gateway. */
export const AREA_ALIASES: Readonly<Record<string, string>> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference",
server: "mcp",
invoice: "invoices",
expense: "expenses"
}
export const UPDATE_ALIASES = new Set([
"update", "upgrade", "up", "self-update", "selfupdate"
])
export function normalizeCliArea(area: string): string {
const lower = area.toLowerCase()
return UPDATE_ALIASES.has(lower) ? "update" : AREA_ALIASES[lower] ?? lower
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js";
@@ -31,7 +32,7 @@ export async function handleAnalyticsCommand(
if (action === "risks" || action === "risks-by-tag" || action === "tag-risks") {
const tagId = maybeName ?? stringOption(args.options.tagId) ?? stringOption(args.options["tag-id"]);
if (!tagId) {
throw new Error("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
throw usageError("Usage: seal-use analytics risks <tagId> [--start-date <ISO>] [--end-date <ISO>] [--corp <corpId>]");
}
await runCapability(
"sealInsightRisksByTagGet",
@@ -64,7 +65,7 @@ export async function handleAnalyticsCommand(
if (action === "analyze" || action === "reanalyze") {
const recordId = maybeName ?? stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]);
if (!recordId) {
throw new Error("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
throw usageError("Usage: seal-use analytics analyze <recordId> [--corp <corpId>]");
}
await runCapability(
"sealInsightRecordAnalyze",
@@ -91,5 +92,5 @@ export async function handleAnalyticsCommand(
return;
}
throw new Error(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown analytics command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+209
View File
@@ -0,0 +1,209 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_DISABLE_BG_UPDATE"] as const
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let requests: Request[]
let rawResponse: unknown
let rawStatus: number
const fixtures = [
{ id: "warning", result: { decision: "APPROVE", otherFindings: [
{ title: "说明", description: "仅说明", level: "info" },
{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }
] } },
{ id: "error", result: { decision: "REJECT", otherFindings: [{ title: "金额差异", description: "金额不一致", level: "error" }] } },
{ id: "info", result: { otherFindings: [{ title: "说明", description: "无需处理", level: "info" }] } },
{ id: "rule-only", result: { rulesResult: [{ id: "rule-1", findings: [{ level: "error" }] }], otherFindings: [] } },
{ id: "missing", result: {} },
{ id: "malformed", result: { otherFindings: "bad" } }
].map((record, index) => ({
...record, sourceDocumentSN: `SN-${index}`, status: "completed", createdAt: 1792639007830 - index,
pipelineData: { humanResult: index === 0 ? "驳回" : "通过" },
sourceExtendData: { _langfuseTraceId: `trace-${index}` }
}))
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-extra-risk-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
process.env.SEAL_DISABLE_BG_UPDATE = "1"
writeFileSync(join(enterprises, "extra-risk-test.json"), JSON.stringify({
id: "extra-risk-test", name: "Extra Risk Test", environment: "test",
seal: { url: "https://extra-risk.example.test" },
source: { type: "seal", token: "test-token", sealUrl: "https://extra-risk.example.test", staffId: "fixture" }
}))
requests = []
rawResponse = { data: { id: 123, status: { future: true }, document: { fields: "changed-shape" }, addedByBackend: [1, { nested: null }] }, responseMetadata: { future: true } }
rawStatus = 200
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
requests.push(request)
const url = new URL(request.url)
if (request.method !== "GET") return Response.json({ error: "unexpected mutation" }, { status: 405 })
if (url.pathname === "/api/v1/approvals/raw-fixture") return Response.json(rawResponse, { status: rawStatus })
if (url.pathname === "/api/v1/approvals") {
const offset = Number(url.searchParams.get("offset") ?? 0)
const limit = Number(url.searchParams.get("limit") ?? 50)
return Response.json({ data: { records: fixtures.slice(offset, offset + limit), total: 1000 } })
}
const record = fixtures.find(item => url.pathname === `/api/v1/approvals/${item.id}`)
return record ? Response.json({ data: record }) : Response.json({ error: "unexpected read" }, { status: 404 })
}) as typeof fetch
})
describe("approval run native JSON fallback", () => {
test("preserves upstream envelopes and schema changes that normal get cannot parse", async () => {
const normal = await cli("get", "raw-fixture", "--full")
expect(normal.exitCode).toBe(13)
const raw = await cli("get", "raw-fixture", "--raw-json")
expect(raw.exitCode).toBe(0)
expect(JSON.parse(raw.stdout)).toEqual(rawResponse)
expect(requests.map(request => new URL(request.url).pathname)).toEqual([
"/api/v1/approvals/raw-fixture", "/api/v1/approvals/raw-fixture"
])
expect(requests.every(request => request.method === "GET")).toBe(true)
})
test("preserves bare responses and upstream fields that would otherwise be CLI-derived", async () => {
rawResponse = { id: "raw-fixture", aliases: { fromServer: true }, humanResult: { original: true }, result: { future: { nested: [false, 0, ""] } } }
const result = await cli("get", "raw-fixture", "--raw-json")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toEqual(rawResponse)
})
test("returns complete large payloads with full/file and uses the shared size error otherwise", async () => {
rawResponse = { data: { id: "raw-fixture", result: { text: "x".repeat(210_000) + "END-OF-UPSTREAM-JSON" } } }
const guarded = await cli("get", "raw-fixture", "--raw-json")
expect(guarded.exitCode).toBe(12)
expect(guarded.stdout).toBe("")
const full = await cli("get", "raw-fixture", "--raw-json", "--full")
expect(full.exitCode).toBe(0)
expect(JSON.parse(full.stdout)).toEqual(rawResponse)
const path = join(dir, "raw.json")
const file = await cli("get", "raw-fixture", "--raw-json", "--output-file", path)
expect(file.exitCode).toBe(0)
expect(JSON.parse(file.stdout)).toEqual({ outputFile: path, bytes: Buffer.byteLength(readFileSync(path)) })
expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(rawResponse)
})
test("rejects transformations and flow routing before sending any request", async () => {
for (const flags of [["--summary"], ["--fields", "result"], ["--flow"]]) {
const result = await cli("get", "raw-fixture", "--raw-json", ...flags)
expect(result.exitCode).toBe(2)
expect(result.stdout).toBe("")
expect(result.stderr).toContain("--raw-json cannot be combined")
}
expect(requests).toHaveLength(0)
})
test("keeps HTTP authentication and upstream failures as errors", async () => {
for (const [status, exitCode] of [[401, 11], [400, 1]] as const) {
rawStatus = status
rawResponse = { error: "Upstream rejected request" }
const result = await cli("get", "raw-fixture", "--raw-json")
expect(result.exitCode).toBe(exitCode)
expect(result.stdout).toBe("")
}
})
test("accepts the camelCase alias and explicit false retains normal behavior", async () => {
const raw = await cli("get", "raw-fixture", "--rawJson")
expect(raw.exitCode).toBe(0)
expect(JSON.parse(raw.stdout)).toEqual(rawResponse)
const normal = await cli("get", "warning", "--raw-json=false")
expect(normal.exitCode).toBe(0)
expect(JSON.parse(normal.stdout)).toHaveProperty("aliases")
})
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
else process.env[key] = oldEnv[key]
}
globalThis.fetch = oldFetch
rmSync(dir, { recursive: true, force: true })
})
function cli(...argv: string[]) { return runCli(["approval-runs", ...argv, "--corp", "extra-risk-test"]) }
describe("approval run extra risk CLI", () => {
test("filters the fetched page, preserves upstream totals and aligns bridge to matches", async () => {
const response = await cli("list", "--has-extra-risk", "--limit", "100", "--includeBridge")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 2, unknown: 2, total: 1000 })
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning", "error"])
expect(data.records[0]).toMatchObject({
otherFindingCount: 2, extraRiskCount: 1, hasExtraRisk: true, extraFindingsStatus: "known",
extraRisks: [{ title: "主体差异", description: "付款主体与销方不同", level: "warning" }]
})
expect(data.bridge).toHaveLength(2)
expect(requests).toHaveLength(1)
const url = new URL(requests[0]!.url)
expect(url.searchParams.get("limit")).toBe("100")
expect(url.searchParams.has("hasExtraRisk")).toBe(false)
expect(requests.every(request => request.method === "GET")).toBe(true)
})
test("limit and offset apply before filtering without fetching more pages", async () => {
const response = await cli("search", "--has-extra-risk", "--limit", "2", "--offset", "2")
expect(response.exitCode).toBe(0)
expect(JSON.parse(response.stdout)).toMatchObject({ scanned: 2, matched: 0, unknown: 0, total: 1000, records: [] })
expect(requests).toHaveLength(1)
expect(new URL(requests[0]!.url).searchParams.get("offset")).toBe("2")
})
test("combines with human-result filtering and forwards time and status conditions", async () => {
const response = await cli("search", "--has-extra-risk", "--humanResult", "驳回", "--status", "completed", "--startDate", "2026-10-01", "--endDate", "2026-10-22")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 1, unknown: 0 })
expect(data.records.map((record: { id: string }) => record.id)).toEqual(["warning"])
const params = new URL(requests[0]!.url).searchParams
expect(params.get("status[0]")).toBe("completed")
expect(params.get("manualApprovalStatus[0]")).toBe("TERMINATED")
expect(params.get("startDate")).toBe(String(Date.parse("2026-10-01T00:00:00+08:00")))
expect(params.get("endDate")).toBe(String(Date.parse("2026-10-22T23:59:59.999+08:00")))
})
test("unfiltered lists preserve unknown and negative records with compact counts", async () => {
const response = await cli("list")
expect(response.exitCode).toBe(0)
const data = JSON.parse(response.stdout)
expect(data).toMatchObject({ scanned: 6, matched: 6, total: 1000 })
expect(data).not.toHaveProperty("unknown")
expect(data.records[2]).toMatchObject({ otherFindingCount: 1, extraRiskCount: 0, hasExtraRisk: false })
expect(data.records[3]).toMatchObject({ otherFindingCount: 0, extraRiskCount: 0, hasExtraRisk: false })
expect(data.records[4]).toMatchObject({ extraFindingsStatus: "unknown", otherFindingCount: null, extraRiskCount: null, hasExtraRisk: null })
expect(data.records[0]).not.toHaveProperty("extraRisks")
})
test("result and detail summaries expose extra risk counts without replacing existing counts", async () => {
const result = await cli("result", "warning", "--summary")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ decision: "APPROVE", extraRiskCount: 1, otherFindingCount: 2, hasExtraRisk: true })
const detail = await cli("get", "warning", "--summary")
expect(detail.exitCode).toBe(0)
expect(JSON.parse(detail.stdout).aiResult).toMatchObject({ extraRiskCount: 1, hasExtraRisk: true })
})
test("supports the camelCase alias and explicit false without filtering", async () => {
const filtered = await cli("list", "--hasExtraRisk")
expect(filtered.exitCode).toBe(0)
expect(JSON.parse(filtered.stdout).matched).toBe(2)
const unfiltered = await cli("list", "--has-extra-risk=false")
expect(unfiltered.exitCode).toBe(0)
expect(JSON.parse(unfiltered.stdout).matched).toBe(6)
})
})
+19 -16
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import * as api from "../../domains/seal/api.js";
@@ -124,6 +125,7 @@ export async function handleApprovalRunsCommand(
sourceDocumentSN: stringOption(args.options.sourceDocumentSN),
sourceDocumentId: stringOption(args.options.sourceDocumentId),
humanResult: stringOption(args.options.humanResult),
hasExtraRisk: booleanOption(args.options["has-extra-risk"]) ?? booleanOption(args.options.hasExtraRisk),
query: stringOption(args.options.query),
includeBridge: booleanOption(args.options.includeBridge)
},
@@ -151,7 +153,7 @@ export async function handleApprovalRunsCommand(
if (action === "pick") {
const query = maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.sn);
if (!query) throw new Error("Usage: seal-use approval-runs pick --sn <documentSN>");
if (!query) throw usageError("Usage: seal-use approval-runs pick --sn <documentSN>");
await runCapability(
"sealApprovalRunPick",
client,
@@ -173,6 +175,10 @@ export async function handleApprovalRunsCommand(
if (action === "get") {
const recordId = args.command[2];
if (!recordId) throw new Error("Missing approval run recordId");
const rawJson = booleanOption(args.options["raw-json"]) ?? booleanOption(args.options.rawJson);
if (rawJson && (booleanOption(args.options.flow) || booleanOption(args.options.summary) || stringOption(args.options.fields) !== undefined)) {
throw usageError("--raw-json cannot be combined with --flow, --summary or --fields");
}
if (booleanOption(args.options.flow)) {
await runCapability(
"sealApprovalRunFlowGet",
@@ -190,7 +196,8 @@ export async function handleApprovalRunsCommand(
{
recordId,
fields: stringOption(args.options.fields),
summary: booleanOption(args.options.summary)
summary: booleanOption(args.options.summary),
rawJson
},
outputOptions(args.options)
);
@@ -199,14 +206,14 @@ export async function handleApprovalRunsCommand(
if (action === "cited-rules") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs cited-rules <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs cited-rules <recordId>");
await runCapability("sealApprovalRunCitedRulesGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "document-summary") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs document-summary <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs document-summary <recordId>");
await runCapability("sealApprovalRunDocumentSummaryGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
@@ -215,7 +222,7 @@ export async function handleApprovalRunsCommand(
const recordId = args.command[2];
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
if (!recordId && !sn) {
throw new Error("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
throw usageError("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRunDiagnose",
@@ -236,9 +243,7 @@ export async function handleApprovalRunsCommand(
if (subAction === "download") {
const recordId = args.command[3];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
throw usageError("Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]");
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
@@ -259,7 +264,7 @@ export async function handleApprovalRunsCommand(
}
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (!recordId) throw usageError("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (booleanOption(args.options.download)) {
const record = await api.getApprovalRun(client, recordId);
@@ -291,9 +296,7 @@ export async function handleApprovalRunsCommand(
if (action === "download") {
const recordId = args.command[2];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
throw usageError("Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]");
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
@@ -315,7 +318,7 @@ export async function handleApprovalRunsCommand(
if (action === "result") {
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs result <recordId> [--summary]");
if (!recordId) throw usageError("Usage: seal-use approval-runs result <recordId> [--summary]");
await runCapability(
"sealApprovalRunResultGet",
client,
@@ -344,7 +347,7 @@ export async function handleApprovalRunsCommand(
const sourceDocumentId = stringOption(args.options.sourceDocumentId);
if (!recordId && !sn && !sourceDocumentId) {
throw new Error("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
throw usageError("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
}
await runCapability(
@@ -373,7 +376,7 @@ export async function handleApprovalRunsCommand(
stringOption(args.options.id) ??
stringOption(args.options.recordId);
if (!target) {
throw new Error("Usage: seal-use approval-runs hose-flow <recordId|SN>");
throw usageError("Usage: seal-use approval-runs hose-flow <recordId|SN>");
}
await runCapability(
@@ -451,5 +454,5 @@ export async function handleApprovalRunsCommand(
return;
}
throw new Error(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+180
View File
@@ -62,6 +62,12 @@ describe("auth links", () => {
? input.toString()
: input.url;
const url = new URL(requestUrl);
if (url.pathname === "/api/v1/auth/me") {
return Response.json({ data: {
user: { id: "session-user", tenantId: "tenant", name: "当前Seal人员", isAdmin: true, permissions: ["*"] },
tenant: { id: "tenant", name: "原生 Seal 企业" }
} });
}
if (url.pathname === "/api/v1/delegation/create") {
return new Response(JSON.stringify({
data: {
@@ -86,10 +92,15 @@ describe("auth links", () => {
corpId: "native-corp",
corpName: "原生 Seal 企业",
staffId: "native-staff",
staffName: "当前Seal人员",
identityStatus: "resolved",
isAdmin: true,
permissions: ["*"],
link: "https://native.seal.test/delegation?token=delegation-token",
token: "delegation-token"
});
expect(parsed.url).toBeUndefined();
expect(result.stderr).not.toContain("未能核实");
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
@@ -163,6 +174,8 @@ describe("auth links", () => {
expiresInHours: 1
});
expect(floorResult.stderr).toContain("已自动向下取整为 1 小时 (1h)");
expect(JSON.parse(floorResult.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", isAdmin: null, permissions: null });
expect(floorResult.stderr).toContain("未能核实实际登录人员姓名");
// Test reject exceeding 7 days (168 hours)
const invalidResult = await runCli(["auth", "link", "--corp", "native-seal", "--expire", "8d"]);
@@ -220,6 +233,12 @@ describe("auth links", () => {
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.pathname === "/api/openapi/v1/staffs/getStaffIds") {
return Response.json({ items: [{ id: "HOSE-CORP:STAFF-1", name: "当前合思人员", active: true, roles: [{ roleDefId: "HOSE-CORP:admin" }] }] });
}
if (url.pathname === "/api/openapi/v1/roleDefGroups") {
return Response.json({ items: [{ id: "system", name: "系统", roleDefs: [{ id: "HOSE-CORP:admin", name: "主管理员" }] }] });
}
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
status: 404,
headers: { "content-type": "application/json" }
@@ -234,6 +253,9 @@ describe("auth links", () => {
corpId: "HOSE-CORP",
corpName: "合思测试企业",
staffId: "HOSE-CORP:STAFF-1",
staffName: "当前合思人员",
identityStatus: "resolved",
roleNames: ["主管理员"],
link: "https://app.ekuaibao.com/web/thirdparty.html?accessToken=provisional-token-xyz",
token: "provisional-token-xyz"
});
@@ -315,6 +337,8 @@ describe("auth links", () => {
expireDate: 7200
});
expect(result2.stderr).toContain("已按 2 小时 (7200s) 自动换算");
expect(JSON.parse(result2.stdout)).toMatchObject({ staffName: null, identityStatus: "unresolved", roleNames: null });
expect(result2.stderr).toContain("未能核实实际登录人员姓名");
});
test("runs auth check and hidden aliases (status, diagnose, test)", async () => {
@@ -385,6 +409,162 @@ describe("auth links", () => {
});
});
describe("auth hose-openapi-token", () => {
function setupRoot(name: string) {
const root = mkdtempSync(join(tmpdir(), name));
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");
return { root, enterprises };
}
function writeHoseCorp(enterprises: string, sourceOverride: Record<string, unknown> = {}) {
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",
...sourceOverride
},
auth: { refreshTtl: 300 }
})
);
}
function mockGetAccessToken(counter: { count: number }, token = "fresh-openapi-token") {
globalThis.fetch = (async (input: RequestInfo | URL) => {
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") {
counter.count += 1;
return new Response(JSON.stringify({ value: { accessToken: token, expireTime: 7200 } }), {
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;
}
test("mints a fresh OpenAPI token from persisted keys and prints it as machine JSON", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-");
writeHoseCorp(enterprises);
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(result.isError).toBe(false);
expect(counter.count).toBe(1);
const parsed = JSON.parse(result.stdout);
expect(parsed).toMatchObject({
corpId: "HOSE-CORP",
corpName: "合思测试企业",
domain: "https://app.ekuaibao.com",
token: "fresh-openapi-token",
cached: false
});
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
});
test("reuses a fresh cached token by default and mints a new one with --force", async () => {
const { root, enterprises } = setupRoot("seal-use-auth-openapi-token-force-");
writeHoseCorp(enterprises);
writeFileSync(
join(root, "tokens.json"),
JSON.stringify({
"hose-corp": {
hose: {
openapi: { token: "cached-openapi-token", expiresAt: Date.now() + 3600_000 }
}
}
})
);
const counter = { count: 0 };
mockGetAccessToken(counter);
const cachedResult = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(cachedResult.isError).toBe(false);
expect(counter.count).toBe(0);
const cachedParsed = JSON.parse(cachedResult.stdout);
expect(cachedParsed).toMatchObject({ token: "cached-openapi-token", cached: true });
expect(cachedResult.stderr).toContain("复用本地仍有效的 accessToken");
const forcedResult = await runCli(["auth", "openapi-token", "--corp", "hose-corp", "--force"]);
expect(forcedResult.isError).toBe(false);
expect(counter.count).toBe(1);
const forcedParsed = JSON.parse(forcedResult.stdout);
expect(forcedParsed).toMatchObject({ token: "fresh-openapi-token", cached: false });
});
test("rejects a native Seal enterprise with exit code 2", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-native-");
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 }
})
);
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "native-seal"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("非合思");
expect(counter.count).toBe(0);
});
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
const { enterprises } = setupRoot("seal-use-auth-openapi-token-nocreds-");
writeHoseCorp(enterprises, {
appKey: undefined,
appSecurity: undefined,
closeToken: "web-session-token",
expiresAt: "2099-01-01T00:00:00+08:00"
});
const counter = { count: 0 };
mockGetAccessToken(counter);
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(13);
expect(result.stderr).toContain("缺少合思凭证");
expect(counter.count).toBe(0);
});
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
+58 -11
View File
@@ -1,10 +1,18 @@
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink, getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
import {
assertHoseAssistTenantMatches,
exchangeHoseAssistLink,
getHoseOpenapiToken,
getHoseProvisionalAuthLink,
normalizeBaseUrl
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { CliError, validationError, usageError } from "../../core/errors.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { createDelegation, getMe } from "../../domains/seal/api.js";
import { resolveHoseLinkIdentity, resolveSealLinkIdentity, summarizeSealLinkIdentity } from "../../domains/seal/enterprise/assist-identity.js";
import {
booleanOption,
parseDelegationExpireHours,
@@ -19,9 +27,7 @@ import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js";
export async function handleAuthExtractKeysCommand(maybeName: string | undefined, args: ParsedArgs) {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error(
"Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]"
);
throw usageError("Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");
}
const reveal =
booleanOption(args.options.reveal) === true ||
@@ -54,6 +60,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
const delegation = await createDelegation(client, { note, expiresInHours });
printJson({
...summarizeSealLinkIdentity(me.user),
tenant: {
id: me.tenant.id,
name: me.tenant.name,
@@ -74,7 +81,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
}
if (!corp) {
throw new Error(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
throw validationError(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
}
if (action === "check" || action === "diagnose" || action === "status" || action === "test" || action === "doctor") {
@@ -92,7 +99,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
if (subAction === "revoke") {
const tokenId = args.command[3] ?? stringOption(args.options.tokenId) ?? stringOption(args.options.id);
if (!tokenId) throw new Error("Usage: seal-use auth link revoke <tokenId>");
if (!tokenId) throw usageError("Usage: seal-use auth link revoke <tokenId>");
await runCapability("sealDelegationRevoke", client, corp, { tokenId }, outputOptions(args.options));
return;
}
@@ -110,14 +117,15 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
}
const delegationRecord = delegation as Record<string, unknown>;
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
const expiresAt = formatBeijingIso(Date.now() + expiresInHours * 3600 * 1000);
const identity = await resolveSealLinkIdentity(client);
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
printJson({
id: delegationRecord.id,
corpId: corp.source.corpId ?? corp.id,
corpName: corp.name,
staffId: corp.source.staffId,
...(staffName ? { staffName } : {}),
...identity,
link: delegationRecord.link,
expiresAt,
token: delegationRecord.token
@@ -133,13 +141,14 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
booleanOption(args.options.refresh) === true ||
booleanOption(args.options.f) === true;
const provisional = await getHoseProvisionalAuthLink(corp, expiresIn, { force });
const staffName = "staffName" in corp.source && typeof corp.source.staffName === "string" ? corp.source.staffName : undefined;
const expiresAt = formatBeijingIso(Date.now() + expiresIn * 1000);
const identity = await resolveHoseLinkIdentity(corp);
if (identity.identityStatus === "unresolved") console.error("提示:链接已生成,但未能核实实际登录人员姓名;请勿将 staffId 当作姓名或推断管理员身份。");
printJson({
corpId: corp.source.corpId ?? corp.id,
corpName: corp.name,
staffId: corp.source.staffId,
...(staffName ? { staffName } : {}),
...identity,
link: provisional.url,
expiresAt,
token: provisional.token
@@ -147,6 +156,44 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
return;
}
if (
action === "hose-openapi-token" ||
action === "openapi-token" ||
action === "hose-token"
) {
if (corp.source.type !== "hose") {
throw new CliError(
`【合思专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
"OpenAPI accessToken 签发能力专属于合思生态租户(使用持久化的 appKey/appSecurity 向合思 OpenAPI 换取 token),非合思渠道企业不支持此命令。",
2
);
}
const appKey = corp.source.appKey ?? corp.source.key;
const appSecurity = corp.source.appSecurity ?? corp.source.password;
if (!appKey || !appSecurity) {
throw validationError(
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法向合思 OpenAPI 签发 accessToken。`
);
}
const force =
booleanOption(args.options.force) === true ||
booleanOption(args.options.refresh) === true ||
booleanOption(args.options.f) === true;
const entry = await getHoseOpenapiToken(corp, { force });
if (entry.cached) {
console.error("ℹ️ [合思 OpenAPI] 复用本地仍有效的 accessToken 缓存,追加 --force 可强制签发全新 token。");
}
printJson({
corpId: corp.source.corpId ?? corp.id,
corpName: corp.name,
domain: normalizeBaseUrl(corp.source.domain),
token: entry.token,
expiresAt: formatBeijingIso(entry.expiresAt),
cached: entry.cached
});
return;
}
if (action === "keys" || action === "hose-keys") {
const reveal =
booleanOption(args.options.reveal) === true ||
@@ -156,7 +203,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
return;
}
throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
async function diagnoseAuth(corp: CorpConfig) {
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -25,5 +26,5 @@ export async function handleBillingCommand(
return;
}
throw new Error(`Unknown billing command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown billing command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import {
getEnterprisesDirCandidates,
loadCorpConfigs,
@@ -123,5 +124,5 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -27,16 +28,16 @@ export async function handleContactsCommand(
}
if (action === "children" || action === "department-children") {
if (!maybeName) throw new Error("Usage: seal-use contacts children <departmentId>");
if (!maybeName) throw usageError("Usage: seal-use contacts children <departmentId>");
await runCapability("sealContactsDepartmentChildrenList", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
if (action === "users" || action === "department-users") {
if (!maybeName) throw new Error("Usage: seal-use contacts users <departmentId>");
if (!maybeName) throw usageError("Usage: seal-use contacts users <departmentId>");
await runCapability("sealContactsDepartmentUsersList", client, corp, { departmentId: maybeName }, outputOptions(args.options));
return;
}
throw new Error(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown contacts command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2
View File
@@ -80,6 +80,8 @@ describe("corps link onboarding", () => {
expect(result.isError).toBe(false);
expect(JSON.parse(result.stdout)).toMatchObject({
staffName: "Support User",
identityStatus: "resolved",
tenant: {
corpId: "acme-01",
tenantSlug: "acme-01"
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { handleCorpBindings } from "./corps/bindings.js";
import { handleCorpOnboarding, extractKeysFromLinkAction, showCorpKeysAction } from "./corps/onboarding.js";
import { handleCorpOverview } from "./corps/overview.js";
@@ -17,5 +18,5 @@ export async function handleCorpsCommand(
if (await handleCorpSync(action, maybeName, args)) return;
if (await handleCorpOnboarding(action, maybeName, args)) return;
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { updateCorpConfig } from "../../../core/config/loader.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
+4 -4
View File
@@ -14,7 +14,7 @@ import {
formatHoseKeyForOutput,
HoseKeySelectionError
} from "../../../domains/hose/keys.js";
import { CliError } from "../../errors.js";
import { CliError, usageError } from "../../../core/errors.js";
import { selectCorp } from "../../helpers.js";
import {
booleanOption,
@@ -181,7 +181,7 @@ export async function handleCorpOnboarding(
if (action === "add-link") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--overwrite]");
throw usageError("Usage: seal-use corps add-link <url> [--name <customName>] [--elevate-hose] [--overwrite]");
}
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
const legacyAsHose = booleanOption(args.options["as-hose"]) === true || booleanOption(args.options.hose) === true;
@@ -211,7 +211,7 @@ export async function handleCorpOnboarding(
if (action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys") {
const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url);
if (!link) {
throw new Error("Usage: seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");
throw usageError("Usage: seal-use corps hose-extract-keys <url> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--name <customName>] [--overwrite]");
}
await extractKeysFromLinkAction(link, {
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true || booleanOption(args.options.plain) === true,
@@ -250,7 +250,7 @@ export async function handleCorpOnboarding(
async function addSealCorp(input: Record<string, unknown>) {
const token = requiredString(input, "token");
const sealUrl = (optionalString(input, "sealUrl") ?? optionalString(input, "url") ?? "").replace(/\/+$/, "");
if (!sealUrl) throw new Error("Missing required JSON field: sealUrl");
if (!sealUrl) throw usageError("Missing required JSON field: sealUrl");
const result = await onboardSealBearer({
...input,
token,
+3 -3
View File
@@ -12,7 +12,7 @@ import {
} from "../../../core/stats/usage-tracker.js";
import type { CorpEnvironment } from "../../../core/config/types.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../errors.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
@@ -192,7 +192,7 @@ export async function handleCorpOverview(
(args.command[3] && !args.command[3].startsWith("-") ? args.command[3] : undefined);
if (!targetCorpId || !newName) {
throw new Error("Usage: seal-use corps rename <corpId> --name <newName>");
throw usageError("Usage: seal-use corps rename <corpId> --name <newName>");
}
const corp = selectCorp(targetCorpId);
@@ -208,7 +208,7 @@ export async function handleCorpOverview(
if (action === "switch") {
const corpId = maybeName;
if (!corpId) throw new Error("Usage: seal-use corps switch <corpId>");
if (!corpId) throw usageError("Usage: seal-use corps switch <corpId>");
const globalConfig = loadGlobalConfig();
if (!globalConfig.stateful) {
throw new Error(
+1 -1
View File
@@ -3,7 +3,7 @@ import type { CorpConfig } from "../../../core/config/types.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 { CliError, confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { outputOptions, printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
+8 -14
View File
@@ -1,8 +1,6 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
import { numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleDataCommand(
@@ -11,23 +9,19 @@ export async function handleDataCommand(
corp: CorpConfig,
args: ParsedArgs
) {
const params = {
offset: numberOption(args.options.offset),
limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
search: stringOption(args.options.search) ?? stringOption(args.options.query)
};
if (action === "expenses" || action === "expense") {
await runCapability("sealExpensesList", client, corp, params, outputOptions(args.options));
const { handleExpensesCommand } = await import("./expenses.js");
await handleExpensesCommand(args.command[2], client, corp, args);
return;
}
if (action === "invoices" || action === "invoice") {
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
const subAction = args.command[2];
const maybeTarget = args.command[3];
const { handleInvoicesCommand } = await import("./invoices.js");
await handleInvoicesCommand(subAction, maybeTarget, client, corp, args);
return;
}
throw new Error(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown data command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+6 -8
View File
@@ -7,7 +7,7 @@ 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";
import { CliError, usageError, validationError } from "../../core/errors.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -18,16 +18,14 @@ export async function handleDeployCommand(
args: ParsedArgs
) {
if (!systemOrAction || systemOrAction === "help") {
throw new Error(
"Usage: seal-use deploy <system> <action> [options]\n\n" +
throw usageError("Usage: seal-use deploy <system> <action> [options]\n\n" +
"支持的审批系统与发布目标:\n" +
" • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>\n" +
" • webhook (通用审批流回调): seal-use webhook <list|get|add|update|delete> --corp <corpId>\n" +
" • feishu (飞书审批): 建议使用 Webhook 模式对接\n" +
" • weaver (泛微 OA): 建议使用 Webhook 模式对接\n" +
" • helios (汇联易): 建议使用 Webhook 模式对接\n" +
" • maycur (每刻报销): 建议使用 Webhook 模式对接"
);
" • maycur (每刻报销): 建议使用 Webhook 模式对接");
}
if (systemOrAction === "webhook" || systemOrAction === "webhooks") {
@@ -52,7 +50,7 @@ export async function handleDeployCommand(
const target = systemOrAction === "hosecloud" ? maybeTarget : actionOrTarget;
if (!isHosecloud) {
throw new Error(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
throw validationError(`未知的发布目标系统: ${systemOrAction}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);
}
if (action === "requirements") {
@@ -108,7 +106,7 @@ export async function handleDeployCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
throw usageError("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");
}
await runCapability("sealDeployHosecloudConfigure", client, corp, {
...payload,
@@ -200,6 +198,6 @@ export async function handleDeployCommand(
return;
}
throw new Error(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
throw usageError(`Unknown deploy hosecloud action: ${action ?? ""}. Available: requirements, list, get, status, configure, sync, test-outbound.`);
}
+1 -1
View File
@@ -44,7 +44,7 @@ export async function handleDoctorCommand(
const { selectCorp } = await import("../helpers.js");
const { createSealClient } = await import("../../core/http/factory.js");
const { stringOption } = await import("../parser.js");
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../core/doctor/tenant-diagnose.js");
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../domains/seal/doctor/tenant-diagnose.js");
const corpSelector =
stringOption(args.options.corp) ??
+180
View File
@@ -0,0 +1,180 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let document = { id: "doc-1", title: "Fixture policy", purpose: "Testing", content: "Line one\\\r\n| a \\| b |", status: "published", enabled: true, scenarios: ["audit"], tags: ["test"] }
let requests: Array<{ method: string; path: string; query: string; body?: Record<string, unknown> }>
let failReadback: boolean
let failReadbackStatus: number
const original = structuredClone(document)
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-documents-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
writeFileSync(join(enterprises, "document-cli-test.json"), JSON.stringify({
id: "document-cli-test", name: "Document Test", environment: "test",
seal: { url: "https://documents.example.test" },
source: { type: "seal", token: "test-token", sealUrl: "https://documents.example.test", staffId: "fixture" }
}))
document = structuredClone(original)
requests = []
failReadback = false
failReadbackStatus = 400
let writeCount = 0
let readbackWrites = 0
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
const url = new URL(request.url)
const method = request.method
const body = ["PATCH", "POST"].includes(method) ? JSON.parse(await request.text()) as Record<string, unknown> : undefined
requests.push({ method, path: url.pathname, query: url.searchParams.toString(), body })
if (failReadback && method === "GET" && writeCount > readbackWrites) {
readbackWrites = writeCount
return Response.json({ error: "offline" }, { status: failReadbackStatus })
}
if (method === "PATCH") {
writeCount++
document = { ...document, ...(body?.attributes as object) }
}
if (method === "POST") document = { ...document, ...body }
return Response.json({ data: url.pathname.endsWith("/articles") && method === "GET" ? { articles: [document], total: 115 } : document })
}) as typeof fetch
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
else process.env[key] = oldEnv[key]
}
globalThis.fetch = oldFetch
rmSync(dir, { recursive: true, force: true })
})
function cli(...argv: string[]) { return runCli(["documents", ...argv, "--corp", "document-cli-test"]) }
const writes = () => requests.filter(request => request.method !== "GET")
describe("documents CLI", () => {
test("exports body plus baseline, previews edits, and updates only body with JSON receipts", async () => {
const out = join(dir, "body.txt")
const exported = await cli("get", "doc-1", "--out", out)
expect(exported.exitCode).toBe(0)
expect(JSON.parse(exported.stdout)).toMatchObject({ contentFile: out, contentFormat: "raw" })
expect(readFileSync(out, "utf8")).toBe(original.content)
writeFileSync(out, "edited content")
const preview = await cli("update", "doc-1", "--content-file", out, "--dry-run", "--yes")
expect(preview.exitCode).toBe(0)
expect(JSON.parse(preview.stdout)).toMatchObject({ preview: true, executed: false, baselineAvailable: true, changedFields: ["content"] })
expect(writes()).toHaveLength(0)
const result = await cli("update", "doc-1", "--content-file", out, "--yes")
expect(result.exitCode).toBe(0)
const payload = JSON.parse(result.stdout)
expect(payload).toMatchObject({ verified: true, executed: true, baselineAvailable: true })
expect(JSON.parse(readFileSync(payload.snapshotFile, "utf8")).document.content).toBe(original.content)
expect(writes()).toHaveLength(1)
expect(writes()[0]?.body).toEqual({ attributes: { content: "edited content" } })
expect(document.title).toBe(original.title)
expect(document.status).toBe("published")
})
test("plain get and output-file still produce whole document JSON", async () => {
expect(JSON.parse((await cli("get", "doc-1")).stdout)).toMatchObject(original)
const path = join(dir, "document.json")
const result = await cli("get", "doc-1", "--output-file", path)
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject(original)
})
test("lightweight list and explicit fields do not request per-document details", async () => {
const summary = await cli("list", "--summary", "--limit", "2", "--offset", "1")
expect(summary.exitCode).toBe(0)
expect(JSON.parse(summary.stdout).articles[0]).not.toHaveProperty("content")
expect(new URLSearchParams(requests[0]?.query).get("limit")).toBe("2")
expect(new URLSearchParams(requests[0]?.query).get("offset")).toBe("1")
const fields = await cli("list", "--summary", "--fields", "id,title")
expect(JSON.parse(fields.stdout)).toEqual({ total: 115, articles: [{ id: "doc-1", title: original.title }] })
expect(requests.every(request => request.path === "/api/v1/knowledge/articles")).toBe(true)
expect((await cli("list", "--fields", "typo")).exitCode).toBe(2)
})
test("all write commands require confirmation and all previews remain read-only", async () => {
const variants = [
["create", "--title", "new", "--purpose", "test", "--content", "new"],
["update", "doc-1", "--content", "new"],
["delete", "doc-1"]
]
for (const argv of variants) {
expect((await cli(...argv)).exitCode).toBe(10)
for (const flag of ["--dry-run", "--dryRun"]) {
const result = await cli(...argv, flag, "--confirm")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ preview: true, executed: false })
}
}
expect(writes()).toHaveLength(0)
expect(existsSync(join(dir, "document-history"))).toBe(false)
})
test("conflicts and failed readback return JSON state with nonzero exit codes", async () => {
const path = join(dir, "body")
await cli("get", "doc-1", "--out", path)
writeFileSync(path, "my edit")
document.content = "remote edit"
const conflict = await cli("update", "doc-1", "--content-file", path, "--yes")
expect(conflict.exitCode).toBe(1)
expect(JSON.parse(conflict.stdout)).toMatchObject({ code: "DOCUMENT_CONFLICT", executed: false })
expect(writes()).toHaveLength(0)
failReadback = true
const uncertain = await cli("update", "doc-1", "--content", "new", "--yes")
expect(uncertain.exitCode).toBe(1)
expect(JSON.parse(uncertain.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
expect(uncertain.stderr).toContain("Next action:")
failReadbackStatus = 401
const authFailed = await cli("update", "doc-1", "--content", "newer", "--yes")
expect(authFailed.exitCode).toBe(11)
expect(JSON.parse(authFailed.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false })
})
test("unsupported format and path/input conflicts fail before requests or file changes", async () => {
const path = join(dir, "body")
writeFileSync(path, "keep")
for (const argv of [
["get", "doc-1", "--out", path, "--content-format", "markdown"],
["get", "doc-1", "--out", path, "--output-file", path],
["update", "doc-1", "--content-file", path, "--content", "other", "--yes"],
["update", "doc-1", "--content-file", path, "--output-file", path, "--yes"],
["update", "doc-1", "--content-file", path, "--output-file", `${path}.seal-use.json`, "--yes"]
]) expect((await cli(...argv)).exitCode).toBe(2)
expect(readFileSync(path, "utf8")).toBe("keep")
expect(requests).toHaveLength(0)
})
test("invalid UTF-8, missing file and damaged baseline fail with exit 13 and zero writes", async () => {
const path = join(dir, "body")
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
writeFileSync(path, Buffer.from([0xff]))
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
writeFileSync(path, "new")
writeFileSync(`${path}.seal-use.json`, "{}")
expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13)
expect(writes()).toHaveLength(0)
})
test("legacy raw input is supported and discloses absence of an editing baseline", async () => {
const result = await cli("update", "doc-1", "--content", "new", "--confirm")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ verified: true, baselineAvailable: false })
expect(result.stderr).toContain("baselineAvailable:false")
})
})
+72 -43
View File
@@ -1,8 +1,11 @@
import { readFileSync } 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 { confirmationRequired } from "../errors.js";
import { runCapability } from "../helpers.js";
import { usageError } from "../../core/errors.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import { exportDocument, readDocumentBaseline, readDocumentText } from "../../domains/seal/documents/files.js";
import { DocumentMutationError } from "../../domains/seal/documents/service.js";
import { ApprovalDocumentSchema } from "../../domains/seal/types.js";
import {
booleanOption,
jsonObject,
@@ -10,17 +13,25 @@ import {
splitOption,
stringOption
} from "../parser.js";
import { outputOptions } from "../printer.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
const filePath =
function contentFilePath(args: ParsedArgs): string | undefined {
return (
stringOption(args.options.contentFile) ??
stringOption(args.options["content-file"]) ??
stringOption(args.options.file) ??
stringOption(args.options.f);
stringOption(args.options.f)
);
}
function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
const filePath = contentFilePath(args);
const fileInputs = ["contentFile", "content-file", "file", "f"].filter(key => args.options[key] !== undefined).length;
const sources = fileInputs + Number(args.options.content !== undefined) + Number(payload.content !== undefined);
if (sources > 1) throw usageError("Specify exactly one document content source: --content-file, --content, or JSON content");
if (filePath) {
return readFileSync(filePath, "utf8");
return readDocumentText(filePath);
}
const direct = stringOption(args.options.content);
if (direct !== undefined) return direct;
@@ -34,6 +45,33 @@ export async function handleDocumentsCommand(
corp: CorpConfig,
args: ParsedArgs
) {
const out = stringOption(args.options.out);
const format = stringOption(args.options["content-format"]) ?? stringOption(args.options.contentFormat);
if (format !== undefined && format !== "raw") throw usageError("--content-format supports raw only; Markdown conversion requires a verified platform codec");
if (out && action !== "get") throw usageError("--out is supported only by documents get");
if (format !== undefined && !["get", "create", "update"].includes(action ?? "")) throw usageError("--content-format is supported only by documents get/create/update");
if (out && outputOptions(args.options).outputFile) throw usageError("--out (body) and --output-file (JSON) are mutually exclusive");
if (booleanOption(args.options.overwrite) && !out) throw usageError("--overwrite requires documents get --out");
const contentPath = contentFilePath(args);
const jsonOutput = outputOptions(args.options).outputFile;
if (contentPath && jsonOutput && [resolve(contentPath), `${resolve(contentPath)}.seal-use.json`].includes(resolve(jsonOutput))) {
throw usageError("--output-file must not overwrite the input body or its export baseline");
}
const safety = {
dryRun: booleanOption(args.options["dry-run"]) ?? booleanOption(args.options.dryRun),
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true,
allowEmpty: booleanOption(args.options["allow-empty"]) ?? booleanOption(args.options.allowEmpty)
};
const mutate = async (name: string, params: Record<string, unknown>) => {
try {
printJson(await runCapabilityResult(name, client, corp, params), outputOptions(args.options));
} catch (error) {
if (error instanceof DocumentMutationError) printJson(error.payload, outputOptions(args.options));
throw error;
}
};
if (!action || action === "list") {
const scenarios = splitOption(args.options.scenarios);
const limit = numberOption(args.options.limit);
@@ -42,7 +80,7 @@ export async function handleDocumentsCommand(
"sealApprovalDocumentsList",
client,
corp,
{ scenarios, limit, offset },
{ scenarios, limit, offset, summary: booleanOption(args.options.summary), fields: splitOption(args.options.fields) },
outputOptions(args.options)
);
return;
@@ -55,7 +93,12 @@ export async function handleDocumentsCommand(
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents get <documentId> [--corp <corpId>]");
throw usageError("Usage: seal-use documents get <documentId> [--corp <corpId>]");
}
if (out) {
const document = ApprovalDocumentSchema.parse(await runCapabilityResult("sealApprovalDocumentGet", client, corp, { documentId }));
printJson(exportDocument(corp, document, out, booleanOption(args.options.overwrite)));
return;
}
await runCapability(
"sealApprovalDocumentGet",
@@ -70,7 +113,7 @@ export async function handleDocumentsCommand(
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) {
throw new Error("Usage: seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]");
throw usageError("Usage: seal-use documents search <keyword> [--maxResults 20] [--corp <corpId>]");
}
await runCapability(
"sealApprovalSearch",
@@ -115,15 +158,11 @@ export async function handleDocumentsCommand(
(Array.isArray(payload.tags) ? (payload.tags as string[]) : undefined);
if (!title || !purpose || content === undefined) {
throw new Error(
"Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
throw usageError("Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
}
await runCapability(
await mutate(
"sealApprovalDocumentCreate",
client,
corp,
{
title,
purpose,
@@ -132,9 +171,9 @@ export async function handleDocumentsCommand(
status,
enabled,
scenarios,
tags
},
outputOptions(args.options)
tags,
...safety
}
);
return;
}
@@ -179,15 +218,14 @@ export async function handleDocumentsCommand(
tags !== undefined;
if (!documentId || !hasChanges) {
throw new Error(
"Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
);
throw usageError("Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]");
}
await runCapability(
const filePath = contentFilePath(args);
const baseline = filePath ? readDocumentBaseline(filePath) : undefined;
if (content !== undefined && !baseline) console.error("Document input has no export baseline; changes made by others during editing cannot be detected (baselineAvailable:false).");
await mutate(
"sealApprovalDocumentUpdate",
client,
corp,
{
documentId,
title,
@@ -197,9 +235,10 @@ export async function handleDocumentsCommand(
status,
enabled,
scenarios,
tags
},
outputOptions(args.options)
tags,
baseline,
...safety
}
);
return;
}
@@ -211,24 +250,14 @@ export async function handleDocumentsCommand(
stringOption(args.options["document-id"]) ??
stringOption(args.options.id);
if (!documentId) {
throw new Error("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
throw usageError("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to delete document '${documentId}' without --yes.`,
`seal-use documents delete ${documentId} --corp ${corp.id} --yes`
);
}
await runCapability(
await mutate(
"sealApprovalDeleteDocument",
client,
corp,
{ documentId },
outputOptions(args.options)
{ documentId, dryRun: safety.dryRun, confirm: safety.confirm }
);
return;
}
throw new Error(`Unknown documents command: ${action}. Available: list, get, search, create, update, delete.`);
throw usageError(`Unknown documents command: ${action}. Available: list, get, search, create, update, delete.`);
}
+127
View File
@@ -0,0 +1,127 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runCli } from "../runner.js"
const envKeys = ["SEAL_USE_CONFIG_FILE", "SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
const oldFetch = globalThis.fetch
let dir: string
let requests: Array<{ method: string; path: string; query: URLSearchParams }>
let approvalSN: string
let expenseCount: number
let failureStatus: number | undefined
let description: string
const sn = "SN-CLI-FIXTURE"
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-expense-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
writeFileSync(join(enterprises, "expense-cli-test.json"), JSON.stringify({
id: "expense-cli-test", name: "Expense Test", environment: "test", seal: { url: "https://expense.example.test" },
source: { type: "seal", token: "test-token", sealUrl: "https://expense.example.test", staffId: "fixture" }
}))
requests = []
approvalSN = sn
expenseCount = 2
failureStatus = undefined
description = "Fixture only"
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
const url = new URL(request.url)
requests.push({ method: request.method, path: url.pathname, query: url.searchParams })
if (request.method !== "GET") throw new Error("Unexpected mutation")
if (url.pathname === "/api/v1/approvals") return Response.json({ data: { records: [{ id: "record-1", sourceDocumentSN: approvalSN, sourceDocumentId: "source-1", documentId: "document-1" }], total: 1 } })
if (failureStatus) return Response.json({ error: { message: "fixture failure" } }, { status: failureStatus })
if (!url.searchParams.has("filter[search]") && !url.searchParams.has("filter[recordId]")) return Response.json({ error: "filter required" }, { status: 400 })
const offset = Number(url.searchParams.get("offset"))
const limit = Number(url.searchParams.get("limit"))
const expenses = Array.from({ length: expenseCount }, (_, i) => ({ id: `expense-${i}`, recordId: "record-1", documentId: "document-1", type: "fixture", amount: i + 1, currency: "CNY", description, user: { mobile: "private-fixture" } }))
return Response.json({ data: { expenses: expenses.slice(offset, offset + limit), total: expenses.length } })
}) as typeof fetch
})
afterEach(() => {
for (const key of envKeys) {
if (oldEnv[key] === undefined) delete process.env[key]
else process.env[key] = oldEnv[key]
}
globalThis.fetch = oldFetch
rmSync(dir, { recursive: true, force: true })
})
function cli(...argv: string[]) { return runCli([...argv, "--corp", "expense-cli-test"]) }
describe("expense document lookup CLI", () => {
test("canonical, singular, list and data entrances all execute the same read-only lookup", async () => {
for (const prefix of [["expenses"], ["expense"], ["expenses", "list"], ["data", "expenses"], ["data", "expense", "list"]]) {
const result = await cli(...prefix, "--sn", sn, "--limit", "1")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", found: true, complete: true, matchedCount: 2 })
expect(result.stdout).not.toContain("private-fixture")
}
expect(requests.every(request => request.method === "GET")).toBe(true)
expect(requests.filter(request => request.path.includes("expenses")).every(request => request.query.get("filter[recordId]") === "record-1")).toBe(true)
})
test("raw list behavior stays compatible while bare list and record filters get a required filter object", async () => {
const raw = await cli("expenses", "list")
expect(raw.exitCode).toBe(0)
expect(JSON.parse(raw.stdout)).toHaveProperty("expenses")
expect(requests[0]?.query.get("filter[search]")).toBe("")
expect(requests[0]?.query.has("filter[startDate]")).toBe(false)
const byRecord = await cli("data", "expenses", "--record-id", "record-1")
expect(byRecord.exitCode).toBe(0)
expect(requests[1]?.query.get("filter[recordId]")).toBe("record-1")
await cli("expenses", "--search", "交通", "--offset", "2")
expect(requests[2]?.query.get("filter[search]")).toBe("交通")
expect(requests[2]?.query.get("offset")).toBe("2")
})
test("absence and unresolved linking have different JSON conclusions", async () => {
expenseCount = 0
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "not_found", found: false, complete: true })
approvalSN = `${sn}-UNRELATED`
expect(JSON.parse((await cli("expenses", "--sn", sn)).stdout)).toMatchObject({ status: "unknown", found: null, complete: false, reason: "approval_link_not_found" })
})
test("limits are explicit and partial scans cannot return not_found", async () => {
const result = await cli("expenses", "--sn", sn, "--max-scan", "1")
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ status: "found", complete: false, reason: "scan_limit", matchedCount: 1 })
})
test("bad selector combinations, unknown verbs and invalid scan budgets fail before requests", async () => {
for (const argv of [
["expenses", "delete"], ["expenses", "SN-as-unsupported-positional"], ["expenses", "list", sn], ["data", "expenses", "list", sn],
["expenses", "--sn", sn, "--search", "text"], ["expenses", "--sn", sn, "--record-id", "record-1"],
["expenses", "--sn", sn, "--offset", "0"], ["expenses", "--max-scan", "1"]
]) expect((await cli(...argv)).exitCode).toBe(2)
expect((await cli("expenses", "--sn", sn, "--max-scan", "0")).exitCode).toBe(13)
expect(requests).toHaveLength(0)
})
test("expense lookup failures retain JSON uncertainty and correct exit codes", async () => {
for (const status of [400, 403]) {
failureStatus = status
const result = await cli("expenses", "--sn", sn)
expect(result.exitCode).toBe(status === 403 ? 11 : 1)
expect(JSON.parse(result.stdout)).toMatchObject({ status: "unknown", complete: false, found: null })
expect(result.stderr).toContain("incomplete")
}
})
test("oversized reports retain existing output protection and can be exported as JSON", async () => {
description = "x".repeat(210000)
expect((await cli("expenses", "--sn", sn)).exitCode).toBe(12)
const path = join(dir, "report.json")
const result = await cli("expenses", "--sn", sn, "--output-file", path)
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path })
expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject({ status: "found", complete: true, matchedCount: 2 })
})
})
+33
View File
@@ -0,0 +1,33 @@
import type { CorpConfig } from "../../core/config/types.js"
import type { createSealClient } from "../../core/http/factory.js"
import { usageError } from "../../core/errors.js"
import { ExpenseLookupError } from "../../domains/seal/expenses/lookup.js"
import { runCapabilityResult } from "../helpers.js"
import { numberOption, stringOption } from "../parser.js"
import { outputOptions, printJson } from "../printer.js"
import type { ParsedArgs } from "../types.js"
export async function handleExpensesCommand(action: string | undefined, client: Awaited<ReturnType<typeof createSealClient>>, corp: CorpConfig, args: ParsedArgs) {
const prefixLength = args.command[0]?.toLowerCase() === "data" ? 2 : 1
if ((action && action !== "list") || args.command.length > prefixLength + Number(Boolean(action))) {
throw usageError("Usage: seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>]")
}
const sn = stringOption(args.options.sn)
const recordId = stringOption(args.options["record-id"]) ?? stringOption(args.options.recordId)
const search = stringOption(args.options.search) ?? stringOption(args.options.query)
const offset = numberOption(args.options.offset)
const maxScan = numberOption(args.options["max-scan"]) ?? numberOption(args.options.maxScan)
if (sn !== undefined && (recordId !== undefined || search !== undefined || offset !== undefined)) throw usageError("--sn cannot be combined with --search, --record-id, or --offset")
if (maxScan !== undefined && sn === undefined) throw usageError("--max-scan requires --sn")
try {
const result = await runCapabilityResult("sealExpensesList", client, corp, {
sn, recordId, search, offset, maxScan, limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"])
})
printJson(result, outputOptions(args.options))
} catch (error) {
if (error instanceof ExpenseLookupError) printJson(error.report, outputOptions(args.options))
throw error
}
}
+580
View File
@@ -0,0 +1,580 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { KyInstance } from "ky";
import { CorpConfigSchema } from "../../core/config/types.js";
import { classifyCliError } from "../../core/errors.js";
import { parseArgs } from "../parser.js";
import { handleHoseEbotCommand } from "./hose-ebot.js";
const ORIGINAL_ENV = {
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
usageFile: process.env.SEAL_USE_USAGE_FILE
};
const ORIGINAL_FETCH = globalThis.fetch;
const ORIGINAL_LOG = console.log;
const ORIGINAL_ERROR = console.error;
let tempDir: string | undefined;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-use-hose-ebot-area-"));
process.env.SEAL_USE_TOKEN_STORE = join(tempDir, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(tempDir, "usage.json");
});
afterEach(() => {
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
globalThis.fetch = ORIGINAL_FETCH;
console.log = ORIGINAL_LOG;
console.error = ORIGINAL_ERROR;
if (tempDir) {
rmSync(tempDir, { recursive: true, force: true });
tempDir = undefined;
}
});
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
const hoseCorp = CorpConfigSchema.parse({
id: "hose-ebot",
name: "合思 EBot 测试企业",
environment: "test",
seal: { url: "https://hose-ebot.sealai.cc" },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key-1",
appSecurity: "sec-1",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const hoseCorpNoOpenApiCredentials = CorpConfigSchema.parse({
...hoseCorp,
id: "hose-ebot-nocreds",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
closeToken: "web-session-token",
corpId: "ID01LG7ksGroB1",
staffId: "ID01LG7ksGroB1:ID01KsDgHaH5nN"
}
});
const sealCorp = CorpConfigSchema.parse({
id: "seal-ebot",
name: "原生 Seal 企业",
environment: "test",
seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } },
source: {
type: "seal",
sealUrl: "https://seal.test",
token: "mock-token",
staffId: "seal-staff",
corpId: "seal-corp"
}
});
const messageFixture = {
items: [
{
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true,
signKey: "Q4H15lpixMyE7secretvalue",
callbackUrl: "https://sealai.cc/api/hosecloud/outbound?config_id=Q4H15lpixMyE7secretvalue",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["backlog.processed"],
formFields: ["action", "flowId", "nodeId"]
},
{
id: "ID01Vj4VDa8CGH",
messageName: "完成回调",
messageType: "message",
enable: false,
signKey: "Q4H15lpixOtherSecret",
callbackUrl: "https://sealai.cc/api/hosecloud/complete",
corporationId: "ID01LG7ksGroB1",
actionEvent: ["flow.completed"]
}
]
};
const logFixture = {
items: [
{
id: "log-1",
name: "出站调用",
type: "INVOKING",
state: "SUCCESS",
createTime: 1727764000000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
messageId: "MSG-1",
rejectionNum: 0
}
},
{
id: "log-2",
name: "审批回调",
type: "CALLBACK",
state: "SUCCESS",
createTime: 1727764010000,
flowId: { id: "FLOW-1", form: { code: "SN123" } },
nodeName: "AI 审核节点",
request: {
flowId: "FLOW-1",
nodeId: "NODE-1",
signKey: "Q4H15lpixMyE7secretvalue",
action: "accept",
comment: "AI 审核通过"
}
}
]
};
function mockFetch(responses: {
messages?: unknown;
logs?: unknown;
token?: unknown;
approval?: unknown;
}) {
const record: {
calls: number;
messageUrl?: string;
logUrl?: string;
logBody?: unknown;
tokenUrl?: string;
tokenBody?: unknown;
approvalUrl?: string;
approvalBody?: unknown;
} = { calls: 0 };
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
record.calls++;
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
let bodyText: string | undefined;
if (init?.body) {
bodyText = String(init.body);
} else if (input && typeof input === "object" && "clone" in input) {
bodyText = await (input as Request).clone().text().catch(() => undefined);
}
if (url.includes("/api/outbound/v1/message/messageLog")) {
record.logUrl = url;
record.logBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(JSON.stringify(responses.logs ?? logFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/outbound/v1/message")) {
record.messageUrl = url;
return new Response(JSON.stringify(responses.messages ?? messageFixture), {
status: 200,
headers: { "content-type": "application/json" }
});
}
if (url.includes("/api/openapi/v1/auth/getAccessToken") || url.includes("/api/openapi/v1/accessToken")) {
record.tokenUrl = url;
record.tokenBody = bodyText ? JSON.parse(bodyText) : undefined;
return new Response(
JSON.stringify(responses.token ?? { accessToken: "live-openapi-token" }),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url.includes("/api/openapi/v1/approval")) {
record.approvalUrl = url;
record.approvalBody = bodyText ? JSON.parse(bodyText) : undefined;
const resp = responses.approval ?? { value: { code: "204", message: "EBot执行完成" } };
return new Response(JSON.stringify(resp), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response(JSON.stringify({ error: "unexpected url", url }), { status: 500 });
}) as typeof fetch;
return record;
}
function fakeClient(integrations: Array<Record<string, unknown>> = []) {
return {
get: async () => ({
json: async () => ({ integrations })
})
} as unknown as KyInstance;
}
async function callHoseEbot(client: KyInstance, corp: typeof hoseCorp, argv: string[]) {
const lines: string[] = [];
console.log = (line: string) => lines.push(String(line));
console.error = () => {};
const args = parseArgs(argv);
await handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args);
return JSON.parse(lines.join("\n")) as Record<string, unknown>;
}
async function captureError(action: () => Promise<unknown>): Promise<unknown> {
try {
await action();
} catch (error) {
return error;
}
throw new Error("expected action to throw, but it succeeded");
}
describe("hose-ebot messages", () => {
test("lists configured outbound messages with a masked signKey by default", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "messages"]);
expect(output.count).toBe(2);
expect(record.messageUrl).toContain("corpId=ID01LG7ksGroB1");
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages[0]).toMatchObject({
id: "ID01Vj4Zq1Lytp",
messageName: "希尔顿Seal AI审核1",
messageType: "flow",
enable: true
});
// maskHoseSecurity keeps the first 8 and last 4 characters.
expect(messages[0]!.signKey).toBe("Q4H15lpi...alue");
expect(messages[0]!.signKey).not.toBe("Q4H15lpixMyE7secretvalue");
expect(messages[0]!.callbackUrl).toContain("config_id=Q4H15lpixMyE7secretvalue");
expect(output.revealed).toBe(false);
});
test("filters by type and reveals the signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "messages", "--type", "flow", "--reveal"
]);
expect(output.count).toBe(1);
expect(output.revealed).toBe(true);
const messages = output.messages as Array<Record<string, unknown>>;
expect(messages).toHaveLength(1);
expect(messages[0]!.signKey).toBe("Q4H15lpixMyE7secretvalue");
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, ["hose-ebot", "messages"])
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
});
describe("hose-ebot search", () => {
test("requires an SN and lists records with their unique ids", async () => {
const usageError = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "search"])
);
expect(classifyCliError(usageError).exitCode).toBe(2);
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--limit", "5"
]);
expect(output.count).toBe(2);
expect(output.sn).toBe("SN123");
expect(output.type).toBe("all");
expect(record.logBody).toMatchObject({
limit: { start: 0, count: 5 },
filterBy: '(flowId.form.code==("SN123"))'
});
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]).toMatchObject({ id: "log-1", type: "INVOKING" });
expect((records[0]!.request as Record<string, unknown>).nodeId).toBe("NODE-1");
// Callback records embed signKey; masked unless --reveal.
expect((records[1]!.request as Record<string, unknown>).signKey).not.toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("filters to invoking or callback records with --type", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "callback"
]);
expect(output.type).toBe("callback");
expect(output.count).toBe(1);
const records = output.records as Array<Record<string, unknown>>;
expect(records[0]!.type).toBe("CALLBACK");
// The client-side filter over-fetches first so the page stays full.
expect(record.logBody).toMatchObject({ limit: { start: 0, count: 80 } });
// Also accepts uppercase --type CALLBACK
const outputUpper = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--type", "CALLBACK"
]);
expect(outputUpper.count).toBe(1);
});
test("reveals the record signKey with --reveal", async () => {
mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "search", "SN123", "--reveal"
]);
const records = output.records as Array<Record<string, unknown>>;
expect((records[1]!.request as Record<string, unknown>).signKey).toBe(
"Q4H15lpixMyE7secretvalue"
);
});
test("rejects an unknown verb with exit code 2", async () => {
const error = await captureError(() => callHoseEbot(fakeClient(), hoseCorp, ["hose-ebot", "banana"]));
expect(classifyCliError(error).exitCode).toBe(2);
expect(String((error as Error).message)).toContain("Unknown hose-ebot command");
});
});
describe("hose-ebot callback", () => {
const callbackArgv = (extra: string[] = []) => [
"hose-ebot", "callback",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "accept",
"--comment", "同意",
...extra
];
test("refuses to run without --yes/--confirm before any network call", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1"]))
);
expect(classifyCliError(error).exitCode).toBe(10);
expect(record.calls).toBe(0);
expect(classifyCliError(error).nextAction).toContain("seal-use hose-ebot callback");
});
test("previews a masked payload with --dry-run without minting a token", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, [
...callbackArgv(["--sign-key", "sig-1", "--dry-run"])
]);
expect(output.preview).toBe(true);
expect(output.endpoint).toBe("https://app.ekuaibao.com/api/openapi/v1/approval");
const payload = output.payload as Record<string, unknown>;
expect(payload).toMatchObject({
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
expect(payload.signKey).not.toBe("sig-1");
expect(record.calls).toBe(0);
});
test("mints a fresh accessToken and posts the callback on a confirmed run", async () => {
const record = mockFetch({});
const output = await callHoseEbot(fakeClient(), hoseCorp, callbackArgv([
"--sign-key", "sig-1",
"--yes"
]));
expect(output).toMatchObject({
ok: true,
code: "204",
message: "EBot执行完成",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept"
});
expect(record.approvalUrl).toContain("/api/openapi/v1/approval");
expect(record.approvalUrl).toContain("accessToken=live-openapi-token");
expect(record.approvalBody).toMatchObject({
signKey: "sig-1",
flowId: "FLOW-1",
nodeId: "NODE-1",
action: "accept",
comment: "同意"
});
});
test("normalizes action aliases like agree/approve/reject", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "agree",
"--comment", "口语化同意",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "accept" });
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "reject",
"--comment", "口语化驳回",
"--yes"
]);
expect(record.approvalBody).toMatchObject({ action: "refuse" });
});
test("passes optional callback fields through to the wire payload with camelCase support", async () => {
const record = mockFetch({});
await callHoseEbot(fakeClient(), hoseCorp, [
"hose-ebot", "callback",
"--sign-key", "sig-1",
"--flow-id", "FLOW-1",
"--node-id", "NODE-1",
"--action", "refuse",
"--comment", "驳回",
"--policy", "ALL",
"--addApproverIds", "staff-1,staff-2",
"--rejectTo", "NODE-0",
"--resubmitMethod", "TO_REJECTOR",
"--yes"
]);
expect(record.approvalBody).toMatchObject({
action: "refuse",
policy: "ALL",
addApproverIds: ["staff-1", "staff-2"],
rejectTo: "NODE-0",
resubmitMethod: "TO_REJECTOR"
});
});
test("resolves signKey from the sole Seal integration when --sign-key is omitted", async () => {
const record = mockFetch({});
const client = fakeClient([
{ type: "hosecloud", signKey: "integrated-key", outboundName: "AI review", mode: "assisted" }
]);
await callHoseEbot(client, hoseCorp, callbackArgv(["--yes"]));
expect(record.approvalBody).toMatchObject({ signKey: "integrated-key" });
});
test("maps upstream business codes to exit codes and references hose-ebot messages", async () => {
mockFetch({ approval: { value: { code: "401", message: "签名秘钥错误" } } });
const error401 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error401).exitCode).toBe(11);
expect(String((error401 as Error).message)).toContain("seal-use hose-ebot messages --reveal");
mockFetch({ approval: { value: { code: "412", message: "当前的审批节点不为: xxx,请检查" } } });
const error412 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error412).exitCode).toBe(1);
expect(String((error412 as Error).message)).toContain("seal-use hose-ebot search");
mockFetch({ approval: { value: { code: "400", message: "请求参数错误" } } });
const error400 = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error400).exitCode).toBe(13);
});
test("validates preAdd and aftAdd approver and policy requirements before network call", async () => {
const record = mockFetch({});
const preAddError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv(["--action", "preAdd", "--sign-key", "sig-1", "--yes"])
)
);
expect(classifyCliError(preAddError).exitCode).toBe(13);
expect(String((preAddError as Error).message)).toContain("必须通过 --add-approver-ids 指定加签审批人");
expect(record.calls).toBe(0);
const aftAddPolicyError = await captureError(() =>
callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--sign-key",
"sig-1",
"--yes"
])
)
);
expect(classifyCliError(aftAddPolicyError).exitCode).toBe(13);
expect(String((aftAddPolicyError as Error).message)).toContain("必须指定会签方式 --policy ALL");
expect(record.calls).toBe(0);
});
test("normalizes lowercase policy and kebab-case resubmit-method", async () => {
const record = mockFetch({
approval: { value: { code: "204", message: "success" } }
});
await callHoseEbot(
fakeClient(),
hoseCorp,
callbackArgv([
"--action",
"aftAdd",
"--add-approver-ids",
"user1,user2",
"--policy",
"all",
"--resubmit-method",
"from-start",
"--sign-key",
"sig-1",
"--yes"
])
);
expect(record.approvalBody).toMatchObject({
action: "aftAdd",
addApproverIds: ["user1", "user2"],
policy: "ALL",
resubmitMethod: "FROM_START"
});
});
test("rejects a non-Hose enterprise with exit code 13", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), sealCorp, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(record.calls).toBe(0);
});
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
const record = mockFetch({});
const error = await captureError(() =>
callHoseEbot(fakeClient(), hoseCorpNoOpenApiCredentials, callbackArgv(["--sign-key", "sig-1", "--yes"]))
);
expect(classifyCliError(error).exitCode).toBe(13);
expect(String((error as Error).message)).toContain("缺少合思凭证");
expect(record.calls).toBe(0);
});
});
+125
View File
@@ -0,0 +1,125 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { CliError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
const USAGE =
"Usage:\n" +
" seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]\n" +
" seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--dry-run] [--yes|--confirm] [--corp <corpId>]";
function normalizeEbotAction(raw: string | undefined): string | undefined {
if (!raw) return undefined;
const lower = raw.trim().toLowerCase();
if (lower === "accept" || lower === "agree" || lower === "approve") return "accept";
if (lower === "refuse" || lower === "reject") return "refuse";
if (lower === "preadd" || lower === "pre-add") return "preAdd";
if (lower === "aftadd" || lower === "aft-add" || lower === "postadd" || lower === "post-add") return "aftAdd";
return raw;
}
function normalizeEbotPolicy(raw: string | undefined): "ALL" | "ANY" | undefined {
if (!raw) return undefined;
const upper = raw.trim().toUpperCase();
if (upper === "ALL" || upper === "ANY") return upper;
return raw as "ALL" | "ANY";
}
function normalizeResubmitMethod(raw: string | undefined): "FROM_START" | "TO_REJECTOR" | undefined {
if (!raw) return undefined;
const norm = raw.trim().toUpperCase().replace(/-/g, "_");
if (norm === "FROM_START" || norm === "TO_REJECTOR") return norm;
return raw as "FROM_START" | "TO_REJECTOR";
}
/**
* First-level `seal-use hose-ebot` surface for the Hose EBot outbound & callback loop:
* search is the default entry (discover records by document SN), `messages`
* discovers outbound message configs and their signKey, and `callback` runs
* the approval callback.
*/
export async function handleHoseEbotCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
if (!action) {
throw new CliError(USAGE, 2);
}
if (action === "search") {
const sn = maybeName ?? stringOption(args.options.sn);
if (!sn) {
throw new CliError(`Missing document SN.\n\n${USAGE}`, 2);
}
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundSearch",
client,
corp,
{
sn,
type: rawType,
limit: numberOption(args.options.limit),
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true
},
outputOptions(args.options)
);
return;
}
if (action === "messages") {
const rawType = stringOption(args.options.type)?.trim().toLowerCase();
await runCapability(
"sealHoseOutboundMessages",
client,
corp,
{
reveal: booleanOption(args.options.reveal) === true || booleanOption(args.options.r) === true,
type: rawType
},
outputOptions(args.options)
);
return;
}
if (action === "callback") {
const addApproverIdsRaw =
stringOption(args.options["add-approver-ids"]) ?? stringOption(args.options.addApproverIds);
await runCapability(
"sealHoseApprovalCallback",
client,
corp,
{
signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]),
flowId: stringOption(args.options.flowId) ?? stringOption(args.options["flow-id"]),
nodeId: stringOption(args.options.nodeId) ?? stringOption(args.options["node-id"]),
action: normalizeEbotAction(stringOption(args.options.action)),
comment: stringOption(args.options.comment),
policy: normalizeEbotPolicy(stringOption(args.options.policy)),
addApproverIds: addApproverIdsRaw
? addApproverIdsRaw.split(",").map((id) => id.trim()).filter(Boolean)
: undefined,
rejectTo: stringOption(args.options["reject-to"]) ?? stringOption(args.options.rejectTo),
resubmitMethod: normalizeResubmitMethod(
stringOption(args.options["resubmit-method"]) ?? stringOption(args.options.resubmitMethod)
),
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;
}
throw new CliError(
`Unknown hose-ebot command: ${action}. Available: search, messages, callback. Run 'seal-use hose-ebot --help' for usage.`,
2
);
}
+65
View File
@@ -0,0 +1,65 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { traceInvoice } from "../../domains/seal/approval-runs/invoices.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleInvoicesCommand(
action: string | undefined,
maybeTarget: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
corp: CorpConfig,
args: ParsedArgs
) {
// Check if subcommand is "trace" or a positional invoice number
const isTrace = action === "trace";
const invoiceNumberToTrace = isTrace
? (maybeTarget ?? stringOption(args.options.number) ?? stringOption(args.options.invoice))
: (action && /^\d{10,25}$/.test(action) ? action : undefined);
if (invoiceNumberToTrace) {
const report = await traceInvoice(client, invoiceNumberToTrace, corp.id);
if (!report) {
printJson(
{
found: false,
invoiceNumber: invoiceNumberToTrace,
message: `未在进项发票库中找到发票号码为 ${invoiceNumberToTrace} 的记录。`
},
outputOptions(args.options)
);
return;
}
if (report.conflictStatus === "MULTIPLE_DOCUMENTS_ATTACHED") {
console.error(
`\n💡 [CLI 辅助溯源指引](注:此指引由 seal-use CLI 基于进项发票库关联数据自动提炼,非后端大模型生成):\n` +
`• 发票 ${report.invoice.invoiceNumber}(${report.invoice.sellerName},¥${report.invoice.totalAmount})在 ${report.associatedDocuments.length} 笔单据中均有挂载记录:\n` +
report.associatedDocuments.map((d) => ` - 单号: ${d.sourceDocumentSN}(已占 ¥${d.usedAmount ?? 0})👉 诊断命令: ${d.nextDiagnose}`).join("\n") +
`\n`
);
}
printJson(report, outputOptions(args.options));
return;
}
// Otherwise, default to list / search
const searchQuery =
stringOption(args.options.search) ??
stringOption(args.options.query) ??
(action && action !== "list" ? action : undefined);
const params = {
offset: numberOption(args.options.offset),
limit: numberOption(args.options.limit),
startDate: stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]),
endDate: stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]),
search: searchQuery,
full: booleanOption(args.options.full) === true
};
await runCapability("sealInvoicesList", client, corp, params, outputOptions(args.options));
}
+2 -4
View File
@@ -1,4 +1,4 @@
import { validationError } from "../../core/errors.js";
import { validationError, usageError } from "../../core/errors.js";
import { booleanOption, numberOption, splitOption, stringOption } from "../parser.js";
import { runLangfuseCapability } from "../helpers.js";
import { outputOptions } from "../printer.js";
@@ -151,9 +151,7 @@ export async function handleLangfuseCommand(
return;
}
throw new Error(
`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`
);
throw usageError(`Unknown langfuse command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
function parseMetadataOption(raw: string | undefined): Record<string, string | number | boolean> | undefined {
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -20,5 +21,5 @@ export async function handleLlmCommand(
return;
}
throw new Error(`Unknown llm command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown llm command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runCapability } from "../helpers.js";
@@ -20,5 +21,5 @@ export async function handlePermissionsCommand(
return;
}
throw new Error(`Unknown permissions command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown permissions command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+6 -5
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
@@ -27,7 +28,7 @@ export async function handlePreferenceCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || Object.keys(payload).length === 0) {
throw new Error("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
throw usageError("Usage: seal-use preference decision update --json '{\"explicitApprove\":\"...\"}'");
}
await runCapability("sealPreferenceDecisionUpdate", client, corp, {
...payload,
@@ -44,7 +45,7 @@ export async function handlePreferenceCommand(
stringOption(args.options.level) ??
maybeTarget;
if (defaultLevel !== "medium" && defaultLevel !== "high") {
throw new Error("Usage: seal-use preference thinking-depth set --default <medium|high>");
throw usageError("Usage: seal-use preference thinking-depth set --default <medium|high>");
}
await runCapability("sealPreferenceThinkingDepthSet", client, corp, {
defaultLevel,
@@ -65,7 +66,7 @@ export async function handlePreferenceCommand(
? JSON.parse(readFileSync(rawInput, "utf8"))
: jsonObject(args.json);
if (!payload || !payload.id || !payload.name) {
throw new Error("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
throw usageError("Usage: seal-use preference thinking-depth policies upsert --json '{\"id\":\"...\",\"name\":\"...\",\"level\":\"high\"}'");
}
await runCapability("sealPreferenceThinkingDepthPoliciesUpsert", client, corp, {
...payload,
@@ -77,7 +78,7 @@ export async function handlePreferenceCommand(
if (thirdAction === "remove" || thirdAction === "delete") {
const policyId = maybeTarget ?? stringOption(args.options.id) ?? stringOption(args.options.policyId);
if (!policyId) {
throw new Error("Usage: seal-use preference thinking-depth policies remove <policyId>");
throw usageError("Usage: seal-use preference thinking-depth policies remove <policyId>");
}
await runCapability("sealPreferenceThinkingDepthPoliciesRemove", client, corp, {
policyId,
@@ -88,5 +89,5 @@ export async function handlePreferenceCommand(
}
}
throw new Error(`Unknown preference action: ${action ?? ""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`);
throw usageError(`Unknown preference action: ${action ?? ""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`);
}
+193 -28
View File
@@ -16,12 +16,29 @@ import {
loadReviews,
reviewFilePath,
writeReview,
type MonthlyReportResult
type MonthlyReportResult,
buildReportLedgerCsv,
buildReportLedgerXlsx,
loadReportDataFromLedger,
collectReportData,
type ReportData
} from "../../domains/seal/reports/index.js";
import type { ParsedArgs } from "../types.js";
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
export async function handleLocalReportCommand(action: "validate" | "render" | "export" | "template" | "chart", args: ParsedArgs) {
export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) {
if (Boolean(args.options.ledger) || action === "review") {
const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger";
const corp = {
corpId,
id: corpId,
name: corpId,
corpName: corpId,
source: { source: "seal", sealUrl: "" }
} as unknown as CorpConfig;
await handleReportCommand(action, {} as any, corp, args);
return;
}
if (action === "template") {
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (out) {
@@ -61,10 +78,12 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
}
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`);
const glossary = args.options["no-glossary"] ? false : booleanOption(args.options.glossary) ?? true;
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)
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
glossary
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1);
@@ -72,51 +91,173 @@ export async function handleLocalReportCommand(action: "validate" | "render" | "
}
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)
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
glossary
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
}
/** `seal-use report monthly` / `data` — 月度 AI 审核报告。 */
function resolveMaxRuns(args: ParsedArgs): number | undefined {
return (
numberOption(args.options.limit) ??
numberOption(args.options.n) ??
numberOption(args.options.count) ??
numberOption(args.options["max-runs"]) ??
numberOption(args.options.maxRuns)
);
}
/** `seal-use report generate` / `ledger` / `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>]");
if (action === "ledger") {
const ledgerPath = stringOption(args.options.ledger);
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
const format = (stringOption(args.options.format) ?? (out?.endsWith(".csv") ? "csv" : "xlsx")).toLowerCase();
let data: ReportData;
if (ledgerPath) {
data = await loadReportDataFromLedger(ledgerPath, { corp: { id: corp.id, name: corp.name } });
} else {
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if ((!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx|csv>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
data = await collectReportData(client, new Set(["blocks", "templateGroups", "performance"]), {
startDate,
endDate,
month,
corp: { id: corp.id, name: corp.name },
templates,
maxRuns: resolveMaxRuns(args)
});
}
const outFile = out ?? `台账-${corp.id}-${(data.period.label ?? data.period.start).replace(/[^0-9A-Za-z_-]/g, "_")}.${format === "csv" ? "csv" : "xlsx"}`;
const targetPath = resolve(outFile);
if (format === "csv") {
const csvContent = buildReportLedgerCsv(data);
writeFileSync(targetPath, csvContent, "utf8");
} else {
const xlsxBuffer = await buildReportLedgerXlsx(data);
writeFileSync(targetPath, xlsxBuffer);
}
const divergedCount = data.blocks.filter((b) => b.agreement === "diverged").length;
const unreviewedDiverged = data.blocks.filter((b) => b.agreement === "diverged" && !b.verdict).length;
printJson({
file: targetPath,
format: format === "csv" ? "csv" : "xlsx",
corpId: corp.id,
period: data.period,
totalBlocks: data.blocks.length,
templates: [...new Set(data.blocks.map((b) => b.template))],
divergedCount,
unreviewedDiverged,
next: {
reviewTip: "可在 Excel 中直接编辑'复核定性裁决'列(填写:AI判断正确 / 人工判断错误,或人工判断正确 / AI判定误判),也可直接剔除不需要的模板行",
generate: `seal-use report generate --ledger '${targetPath}' --corp ${corp.id} --out reports/报告.md`
}
}, outputOptions(args.options));
return;
}
if (action === "data") {
const ledgerPath = stringOption(args.options.ledger);
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
const month = stringOption(args.options.month);
if (!ledgerPath && (!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
const result = await runCapabilityResult(
"sealReportDataGet",
client,
corp,
{
startDate,
endDate,
month,
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
templates,
ledgerPath,
maxRuns: resolveMaxRuns(args)
}
);
printJson(result, outputOptions(args.options));
return;
}
if (action === "monthly" || action === "month") {
if (action === "monthly" || action === "month" || action === "generate") {
const ledgerPath = stringOption(args.options.ledger);
const startDate =
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since);
const endDate =
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until);
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>]");
if (!ledgerPath && (!startDate || !endDate) && !month) {
throw usageError(
"Usage: seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <n>] [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]"
);
}
const templates = stringOption(args.options.templates)?.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
const result = await runCapabilityResult(
"sealReportMonthlyGet",
client,
corp,
{
startDate,
endDate,
month,
templates,
ledgerPath,
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)
maxRuns: resolveMaxRuns(args),
allowUnreviewed: booleanOption(args.options["allow-unreviewed"]) ?? booleanOption(args.options.force)
}
) as MonthlyReportResult;
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
@@ -139,33 +280,57 @@ export async function handleReportCommand(
}
if (action === "review") {
const sub = args.command[2]; // set | list
const month = stringOption(args.options.month);
if (!month) {
throw new Error("Usage: seal-use report review <set|list> --month <YYYY-MM> [--sn <SN> --verdict <v>] [--corp <corpId>]");
}
const sub = args.command[2]; // set | list | import
if (sub === "list") {
const reviews = loadReviews(corp.id, month);
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
const reviews = loadReviews(corp.id, scope);
printJson({
corpId: corp.id,
month,
file: reviewFilePath(corp.id, month),
...(scope ? { month: scope } : {}),
file: reviewFilePath(corp.id, scope),
count: reviews.size,
reviews: [...reviews.values()]
});
return;
}
if (sub === "import") {
const file = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.ledger);
if (!file) throw usageError("Usage: seal-use report review import <台账.xlsx|csv> --corp <corpId>");
const ledgerData = await loadReportDataFromLedger(file, { corp: { id: corp.id, name: corp.name } });
let imported = 0;
for (const rev of ledgerData.reviews.values()) {
writeReview(corp.id, rev);
imported++;
}
printJson({
corpId: corp.id,
file: resolve(file),
importedCount: imported,
totalBlocks: ledgerData.blocks.length
}, outputOptions(args.options));
return;
}
if (sub === "set") {
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
const recordId =
stringOption(args.options["record-id"]) ??
stringOption(args.options.recordId) ??
stringOption(args.options.id);
const sn =
stringOption(args.options.sn) ??
stringOption(args.options["document-sn"]);
const verdict = stringOption(args.options.verdict);
if (!sn || !verdict) {
throw new Error(
"Usage: seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
const month = stringOption(args.options.month) ?? stringOption(args.options.scope);
if ((!recordId && !sn) || !verdict) {
throw usageError(
"Usage: seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <ai_correct|human_correct|both_correct|both_wrong|undecided> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"
);
}
const record = writeReview(corp.id, {
recordId,
sn,
month,
verdict,
@@ -176,8 +341,8 @@ export async function handleReportCommand(
return;
}
throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`);
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', or 'import'.`);
}
throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`);
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
}
+11 -11
View File
@@ -9,7 +9,7 @@ import {
OFFICIAL_LINTERS_DIR
} from "../../domains/seal/linter/index.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, validationError, usageError } from "../../core/errors.js";
import {
booleanOption,
jsonObject,
@@ -58,7 +58,7 @@ export async function handleRulesCommand(
// lint, linters, and map actions can run without a network client
const clientless = action === "lint" || action === "linters" || action === "linter-list" || action === "map";
if (!client && !clientless) {
throw new Error(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
throw validationError(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
}
if (action === "count") {
@@ -145,7 +145,7 @@ export async function handleRulesCommand(
if (action === "version") {
const version = resolveVersionOption(args, maybeName);
if (!version) throw new Error("Usage: seal-use rules version <versionNumber|latest>");
if (!version) throw usageError("Usage: seal-use rules version <versionNumber|latest>");
await runCapability(
"sealApprovalRuleVersionGet",
client!,
@@ -160,7 +160,7 @@ export async function handleRulesCommand(
const from = stringOption(args.options.from) ?? maybeName;
const to = stringOption(args.options.to) ?? args.command[3];
if (!from || !to) {
throw new Error("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
throw usageError("Usage: seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--full]");
}
const singleSelector = args.command[4];
await runCapability(
@@ -190,7 +190,7 @@ export async function handleRulesCommand(
stringOption(args.options.ruleId) ??
stringOption(args.options["rule-id"]);
if (!target) {
throw new Error("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules get <code> [--version <number|latest>] [--record-id <recordId>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleGet",
@@ -214,7 +214,7 @@ export async function handleRulesCommand(
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : "MUST_FOLLOW");
if (!description || !scope) {
throw new Error("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules create --description <text> --scope <scope> [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--description-file <path>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleCreate",
@@ -240,7 +240,7 @@ export async function handleRulesCommand(
stringOption(args.options.strictness) ??
(typeof payload.strictness === "string" ? payload.strictness : undefined);
if (!ruleId || (description === undefined && scope === undefined && strictness === undefined)) {
throw new Error("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
throw usageError("Usage: seal-use rules update <code> [--description <text>|--description-file <path>] [--scope <scope>] [--strictness <MUST_FOLLOW|SHOULD_FOLLOW|SUGGESTION>] [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleUpdate",
@@ -259,7 +259,7 @@ export async function handleRulesCommand(
stringOption(args.options["rule-id"]) ??
stringOption(args.options.code);
if (!ruleId) {
throw new Error("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
throw usageError("Usage: seal-use rules delete <code> --yes [--corp <corpId>]");
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
@@ -287,7 +287,7 @@ export async function handleRulesCommand(
stringOption(args.options.name) ??
(typeof payload.versionName === "string" ? payload.versionName : undefined);
if (!versionName) {
throw new Error("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
throw usageError("Usage: seal-use rules publish <versionName> [--corp <corpId>]");
}
await runCapability(
"sealApprovalRuleVersionPublish",
@@ -301,7 +301,7 @@ export async function handleRulesCommand(
if (action === "search") {
const keyword = maybeName ?? stringOption(args.options.query);
if (!keyword) throw new Error("Usage: seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]");
if (!keyword) throw usageError("Usage: seal-use rules search <keyword> [--version <number|latest>] [--maxResults 20] [--corp <corpId>]");
await runCapability(
"sealApprovalSearch",
client!,
@@ -465,5 +465,5 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown rules command: ${action ?? ""}. Available: count, list, get, search, create, update, delete, publish, versions, version, diff, lint, linters, pull, push, clear, map. Run 'seal-use help' for available commands.`);
}
+79
View File
@@ -76,6 +76,85 @@ function trackMutationRequests() {
return mutations;
}
function mockSimulationBatches() {
const requested: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
requested.push(url);
const body = url.includes("/api/v1/simulation/batches")
? {
data: [
{
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
createdAt: "2026-10-10T06:38:17.757Z"
},
{
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
createdAt: "2026-10-09T02:56:58.000Z"
}
]
}
: { data: {} };
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}) as typeof fetch;
return requested;
}
describe("simulation local search", () => {
test("search matches the console「任务 fe1993e4」label locally", async () => {
setupMockEnv();
const requested = mockSimulationBatches();
const result = await runCli(["simulation", "search", "任务 fe1993e4"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout) as {
count: number;
scanned: number;
retrieval: { mode: string; serverSideSearch: boolean };
batches: Array<{ id: string }>;
};
expect(payload.count).toBe(1);
expect(payload.retrieval).toMatchObject({ mode: "local_scan", serverSideSearch: false });
expect(payload.batches[0]?.id).toBe("01a12488-a69d-74c4-88b1-118bfe1993e4");
expect(result.stderr).toContain("本地聚合检索");
expect(requested.every((url) => url.includes("/api/v1/simulation/batches"))).toBe(true);
});
test("search respects a local time window", async () => {
setupMockEnv();
mockSimulationBatches();
const result = await runCli(["simulation", "search", "任务", "--since", "2026-10-09", "--until", "2026-10-09"]);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout) as { count: number; batches: Array<{ id: string }> };
expect(payload.count).toBe(1);
expect(payload.batches[0]?.id).toBe("01a123be-0742-743a-ac16-87f7c4e121c7");
});
test("search without a keyword is a usage error", async () => {
setupMockEnv();
const requested = mockSimulationBatches();
const result = await runCli(["simulation", "search"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(requested).toEqual([]);
});
});
describe("simulation command confirmation gates", () => {
test("simulation clean refuses without --yes and never reaches the API", async () => {
setupMockEnv();
+30 -11
View File
@@ -1,7 +1,7 @@
import { existsSync, readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, usageError, validationError } from "../../core/errors.js";
import { runCapability, runCapabilityResult } from "../helpers.js";
import {
booleanOption,
@@ -22,7 +22,7 @@ export async function handleSimulationCommand(
) {
if (action === "batch-records" || action === "records") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation batch-records <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation batch-records <batchId>");
await runCapability(
"sealSimulationBatchRecordsGet",
client,
@@ -142,7 +142,7 @@ export async function handleSimulationCommand(
if (action === "wait") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");
if (!batchId) throw usageError("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");
await runCapability(
"sealSimulationBatchWait",
client,
@@ -159,7 +159,7 @@ export async function handleSimulationCommand(
if (action === "status") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation status <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation status <batchId>");
await runCapability(
"sealSimulationBatchStatus",
client,
@@ -172,7 +172,7 @@ export async function handleSimulationCommand(
if (action === "clean" || action === "delete") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation clean <batchId> --yes");
if (!batchId) throw usageError("Usage: seal-use simulation clean <batchId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -205,13 +205,32 @@ export async function handleSimulationCommand(
return;
}
if (action === "list") {
if (action === "list" || action === "search") {
const query =
stringOption(args.options.query) ??
stringOption(args.options.q) ??
(action === "search" ? maybeName : undefined);
if (action === "search" && (!query || !query.trim())) {
throw usageError(
"Usage: seal-use simulation search <keyword> [--since 7d] [--until <time>] [--all]"
);
}
const limit = numberOption(args.options.limit);
// search 默认扫到底(受 --max-scan 保护), 避免只搜到最近 50 个;显式 --limit 时按用户范围
const all = booleanOption(args.options.all) ?? (action === "search" ? limit === undefined : false);
await runCapability(
"sealSimulationBatchesList",
client,
corp,
{
limit: numberOption(args.options.limit)
limit,
all,
maxScan: numberOption(args.options.maxScan) ?? numberOption(args.options["max-scan"]),
query,
since: stringOption(args.options.since) ?? stringOption(args.options["created-after"]),
until: stringOption(args.options.until) ?? stringOption(args.options["created-before"])
},
outputOptions(args.options)
);
@@ -220,7 +239,7 @@ export async function handleSimulationCommand(
if (action === "get") {
const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]);
if (!batchId) throw new Error("Usage: seal-use simulation get <batchId>");
if (!batchId) throw usageError("Usage: seal-use simulation get <batchId>");
await runCapability("sealSimulationBatchGet", client, corp, { batchId }, outputOptions(args.options));
return;
}
@@ -237,11 +256,11 @@ export async function handleSimulationCommand(
if (action === "package-upload") {
const filePath = maybeName ?? stringOption(args.options.file);
if (!filePath) throw new Error("Usage: seal-use simulation package-upload <材料包.zip>");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!filePath) throw usageError("Usage: seal-use simulation package-upload <材料包.zip>");
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
await runCapability("sealSimulationMaterialPackageUpload", client, corp, { filePath }, outputOptions(args.options));
return;
}
throw new Error(`Unknown simulation command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown simulation command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
@@ -66,5 +67,5 @@ export function handleSkillCommand(action: string | undefined, maybeName: string
return;
}
throw new Error(`Unknown skill command: ${action}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown skill command: ${action}. Run 'seal-use help' for available commands.`);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js";
import { printJson } from "../printer.js";
@@ -8,5 +9,5 @@ export async function handleSourceCommand(action: string | undefined, corp: Corp
return;
}
throw new Error(`Unknown source command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown source command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { CliError } from "../errors.js";
import { CliError } from "../../core/errors.js";
import { selectCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson } from "../printer.js";
+8 -8
View File
@@ -1,6 +1,6 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { confirmationRequired } from "../errors.js";
import { confirmationRequired, usageError } from "../../core/errors.js";
import { runCapability } from "../helpers.js";
import { booleanOption, parseDelegationExpireHours, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
@@ -16,7 +16,7 @@ export async function handleUsersCommand(
if (action === "create") {
const name = stringOption(args.options.name) ?? maybeName;
const phone = stringOption(args.options.phone);
if (!name || !phone) throw new Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");
if (!name || !phone) throw usageError("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");
const deptId = stringOption(args.options.dept) ?? stringOption(args.options.departmentId);
const departmentIds = deptId ? [deptId] : undefined;
await runCapability("sealUserCreate", client, corp, { name, phone, departmentIds }, outputOptions(args.options));
@@ -25,7 +25,7 @@ export async function handleUsersCommand(
if (action === "reset-password") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users reset-password <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users reset-password <userId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -45,14 +45,14 @@ export async function handleUsersCommand(
if (action === "get") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users get <userId>");
if (!userId) throw usageError("Usage: seal-use users get <userId>");
await runCapability("sealUserGet", client, corp, { userId }, outputOptions(args.options));
return;
}
if (action === "delete") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users delete <userId> --yes");
if (!userId) throw usageError("Usage: seal-use users delete <userId> --yes");
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
@@ -66,14 +66,14 @@ export async function handleUsersCommand(
if (action === "activate") {
const userId = maybeName ?? stringOption(args.options.userId);
if (!userId) throw new Error("Usage: seal-use users activate <userId>");
if (!userId) throw usageError("Usage: seal-use users activate <userId>");
await runCapability("sealUserActivate", client, corp, { userId }, outputOptions(args.options));
return;
}
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>] [--expire <duration>]");
if (!userIdOrPhone) throw usageError("Usage: seal-use users delegation <userIdOrPhone> [--note <note>] [--expire <duration>]");
const note = stringOption(args.options.note);
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
const expiresInHours = parseDelegationExpireHours(expireOption, 24);
@@ -87,5 +87,5 @@ export async function handleUsersCommand(
return;
}
throw new Error(`Unknown users command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown users command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+11 -13
View File
@@ -32,13 +32,13 @@ import {
import { outputOptions, printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
import { CliError, confirmationRequired, usageError, validationError } from "../errors.js";
import { CliError, confirmationRequired, usageError, validationError } from "../../core/errors.js";
export async function handleWebhookResourcePackPreview(
filePath: string,
filePolicy?: MaterialPackFilePolicyPatch
) {
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
printJson(await previewMaterialPack(input.fileBuffer, input.fileName, filePolicy));
}
@@ -110,9 +110,7 @@ export async function handleWebhookCommand(
const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]);
if (!recordId && !recordIds && !sn && !sns && limit === undefined) {
throw new Error(
"Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]"
);
throw usageError("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");
}
const sourceCorpId =
@@ -317,14 +315,14 @@ export async function handleWebhookCommand(
? stringOption(args.options.file) ?? stringOption(args.options.input)
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
if (!filePath) throw usageError("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (!existsSync(filePath)) throw validationError(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
if (operation === "preview") {
printJson(await previewMaterialPack(input.fileBuffer, input.fileName), outputOptions(args.options));
return;
}
if (operation !== "push") throw new Error("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
if (operation !== "push") throw usageError("Usage: seal-use webhook resource-pack <export|preview|push> [options]");
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
let integration: WebhookIntegration;
@@ -370,7 +368,7 @@ export async function handleWebhookCommand(
if (action === "get" || action === "find") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook get <idOrName> [--show-secret]");
if (!selector) throw usageError("Usage: seal-use webhook get <idOrName> [--show-secret]");
await runCapability(
"sealWebhookGet",
client,
@@ -392,7 +390,7 @@ export async function handleWebhookCommand(
stringOption(args.options.outgoingResultWebhook) ??
stringOption(args.options["outgoing-result-webhook"]);
if (!name || !outgoingResultWebhook) {
throw new Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
throw usageError("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");
}
const autoApprovalRate = webhookRateOption(args.options);
const materialPackFilePolicy = materialPackFilePolicyOptions(args.options);
@@ -417,7 +415,7 @@ export async function handleWebhookCommand(
if (action === "update") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
if (!selector) throw new Error("Usage: seal-use webhook update <idOrName> [options]");
if (!selector) throw usageError("Usage: seal-use webhook update <idOrName> [options]");
const secret = stringOption(args.options.secret);
const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]);
if (secret !== undefined && rotateSecret) {
@@ -468,7 +466,7 @@ export async function handleWebhookCommand(
if (action === "delete") {
const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id);
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
if (!selector) throw new Error("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (!selector) throw usageError("Usage: seal-use webhook delete <idOrName> [--yes|--dry-run]");
if (booleanOption(args.options.yes) !== true && !dryRun) {
throw confirmationRequired(
"Refusing to delete Webhook integration without --yes",
@@ -489,5 +487,5 @@ export async function handleWebhookCommand(
return;
}
throw new Error(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown webhook command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+77
View File
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { parseArgs } from "./parser.js";
import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js";
/**
@@ -67,3 +68,79 @@ describe("documentation references live commands", () => {
expect(stale).toEqual({});
});
});
/**
* Usage-level closure for the generated cli.md block.
*
* `verify:cli-md` proves the block byte-matches what HELP_REGISTRY renders,
* and parser.test.ts proves registry usage flags are registered — but nothing
* fed the rendered lines back through the real parser. That is exactly the
* hole the 2026-10-17 review found in the opposite direction: 22 parser tests
* green while nine documented flags were rejected at runtime. Rendering is
* code too, so the doc reader's copy-paste path gets its own parse.
*/
const CLI_DOC_PATH = join(REPO_ROOT, "skills/seal-use/references/cli.md");
function generatedUsageLines(markdown: string): string[] {
const block = markdown.match(
/<!-- BEGIN GENERATED CLI COMMANDS -->([\s\S]*?)<!-- END GENERATED CLI COMMANDS -->/
);
if (!block?.[1]) throw new Error(`generated command block missing in ${CLI_DOC_PATH}`);
return block[1].split("\n").filter((line) => line.startsWith("seal-use "));
}
/**
* Turn a documented usage line into argv the way a reader would type it:
* keep one alternative of each `a|b` group, unwrap `[...]` optionality, and
* replace `<value hints>` with a neutral placeholder token. Single quotes are
* respected so `--json '{...}'` payloads survive as one argument.
*/
function usageToArgv(line: string): string[] {
// `--json '{...}'` is a fill-in placeholder in the docs, not literal JSON;
// substitute a valid empty object so the parser sees a well-formed payload.
const hinted = line.slice("seal-use ".length)
.replace(/<[^<>]*>/g, " __HINT__ ")
.replace(/'\{\.\.\.\}'/g, "'{}'");
const unbracketed = hinted.replace(/[[\]]/g, " ");
const tokens: string[] = [];
let current = "";
let quoted = false;
for (const char of unbracketed) {
if (char === "'") {
quoted = !quoted;
continue;
}
if (!quoted && /\s/.test(char)) {
if (current) tokens.push(current);
current = "";
continue;
}
current += char;
}
if (current) tokens.push(current);
return tokens.map((token) => token.split("|")[0]!).filter((token) => token.length > 0);
}
describe("generated cli.md usage lines parse", () => {
test("every documented usage line is accepted by parseArgs", () => {
const lines = generatedUsageLines(readFileSync(CLI_DOC_PATH, "utf8"));
// Format guard: if the markers or the `seal-use ` line convention change,
// the extraction silently yields nothing and this suite would pass while
// checking zero lines.
expect(lines.length).toBeGreaterThan(100);
const rejected: Record<string, string> = {};
for (const line of lines) {
try {
parseArgs(usageToArgv(line));
} catch (error) {
rejected[line] = error instanceof Error ? error.message : String(error);
}
}
expect(rejected).toEqual({});
});
});
-12
View File
@@ -1,12 +0,0 @@
// Re-export from core — this file is the legacy entry point.
// Domain-layer code should import from "../core/errors.js" directly.
export {
type CliExitCode,
CliError,
PayloadTooLargeError,
usageError,
validationError,
safetyBlocked,
confirmationRequired,
classifyCliError
} from "../core/errors.js";
+12 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { extractHelpRequest, renderHelp } from "./help.js";
import { extractHelpRequest, HELP_REGISTRY, renderHelp } from "./help.js";
import { KNOWN_AREAS, runCli } from "./runner.js";
describe("extractHelpRequest", () => {
@@ -210,6 +210,17 @@ describe("help coverage", () => {
}
});
test("every help registry area is dispatchable", () => {
// The forward direction is checked above. The reverse catches a registry
// area that renders help but no longer reaches a handler table — the
// "documented for two releases after the dispatcher dropped it" failure
// mode this suite exists to prevent, applied to `seal-use help` itself.
const dead = HELP_REGISTRY.map((entry) => entry.area)
.filter((area) => !KNOWN_AREAS.has(area));
expect(dead).toEqual([]);
});
test("stop shortcut and server alias resolve to help", () => {
expect(renderHelp(["server"])).toContain("seal-use mcp");
});
+197 -52
View File
@@ -1,5 +1,6 @@
import { normalizeCliArea } from "./area-aliases.js";
import type { ParsedArgs } from "./types.js";
import { usageError } from "./errors.js";
import { usageError } from "../core/errors.js";
export interface CommandOptionHelp {
flag: string;
@@ -514,7 +515,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
name: "list",
aliases: ["search"],
summary: "Search approval records by keyword, dates, or decision status",
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]"]
usage: ["seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--has-extra-risk] [--limit 20] [--includeBridge true] [--corp <corpId>]"],
options: [
{ flag: "--has-extra-risk", description: "Filter the fetched page to records with warning/error in result.otherFindings; info is excluded. Includes extraRisks with titles, levels and descriptions." },
{ flag: "--limit <n>", description: "Records to scan before local filtering (default 50, maximum 100); no automatic pagination to fill matches" },
{ flag: "--offset <n>", description: "Offset in the upstream result set before local filtering" }
]
},
{
name: "pick",
@@ -524,7 +530,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
name: "get",
summary: "Get detailed approval record payload",
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]"]
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]"],
options: [
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary, --fields and --flow" },
{ flag: "--full", description: "Bypass the shared 200,000-byte stdout size guard; this does not change payload structure" },
{ flag: "--output-file <path>", description: "Write the complete JSON payload to a file, bypassing the stdout size guard" }
]
},
{
name: "cited-rules",
@@ -619,22 +630,40 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
area: "report",
title: "Monthly audit accuracy reports",
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
title: "AI audit accuracy reports (acceptance, go-live, periodic)",
description: "Generate AI audit and acceptance reports, export standalone Excel/CSV ledgers, validate local Markdown, and export HTML/PNG/PDF.",
commands: [
{
name: "ledger",
summary: "Export standalone audit run ledger (.xlsx / .csv) with full AI & human opinions",
usage: ["seal-use report ledger --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD> [--templates <t1,t2...>] [--limit <n>] [--out <file.xlsx>] [--corp <corpId>]"],
options: [
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
{ flag: "--ledger <file>", description: "Inspect or convert an existing ledger file" },
{ flag: "--out <file>", description: "Output path (.xlsx or .csv); defaults to 台账-<corpId>-<period>.xlsx" },
{ flag: "--format <xlsx|csv>", description: "Export format (default: xlsx, or inferred from --out)" },
{ flag: "--limit <n>", description: "Cap approval-run fetch (alias: --max-runs, default: all records in period, max 100000)" }
],
description: "Exports full audit ledger containing recordId, SN, template, AI decisions, full AI opinions & conditions, human results & comments, agreement, and review verdict columns. Agents can freely trim rows/templates and fill verdicts."
},
{
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>]"],
usage: ["seal-use report data (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--limit <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)" }
{ flag: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD" },
{ flag: "--ledger <file>", description: "Directly parse an edited Excel/CSV ledger file without remote requests" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist" },
{ flag: "--limit <n>", description: "Cap approval-run detail fetch (alias: --max-runs, default: all records in period, max 100000)" }
],
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",
summary: "Dump or save the built-in 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" }
@@ -654,19 +683,23 @@ export const HELP_REGISTRY: AreaHelp[] = [
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> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
name: "generate",
aliases: ["monthly", "month"],
summary: "Fill the audit report template with performance, risk, and approval-run data",
usage: ["seal-use report generate (--ledger <台账.xlsx> | --start-date <YYYY-MM-DD> --end-date <YYYY-MM-DD>) [--templates <t1,t2...>] [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--limit <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 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: "--start-date <YYYY-MM-DD>", description: "Statistics start date, YYYY-MM-DD (e.g. 2026-08-12)" },
{ flag: "--end-date <YYYY-MM-DD>", description: "Statistics end date, YYYY-MM-DD (e.g. 2026-09-18)" },
{ flag: "--ledger <file>", description: "Driven directly by an edited Excel/CSV ledger as the sole source of truth; ignores deleted templates/runs and respects in-place verdicts" },
{ flag: "--templates <names>", description: "Comma-separated template whitelist; filters blocks and ledger at source" },
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary" },
{ flag: "--out <file>", description: "Save Markdown plus local images and Excel/CSV ledgers beside the report; stdout stays JSON" },
{ 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: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<dateTag>-<random>" },
{ flag: "--limit <n>", description: "Cap approval-run detail fetch (alias: --max-runs, default: all records in period, max 100000)" },
{ 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."
description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings. Supports direct ledger-driven generation where user/Agent modifications to templates and rows are strictly respected."
},
{
name: "validate",
@@ -684,6 +717,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ 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: "--no-glossary", description: "Omit the trailing terms definition and calculation standards appendix" },
{ 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."
@@ -697,38 +731,48 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ 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: "--no-glossary", description: "Omit the trailing terms definition and calculation standards appendix" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" }
],
description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF."
},
{
name: "review set",
summary: "Record one human adjudication (who was right: AI or human) for a document",
usage: ["seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
summary: "Record one human adjudication (who was right: AI or human) for an approval run or document",
usage: ["seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" },
{ flag: "--sn <SN>", description: "Document SN to adjudicate (required)" },
{ flag: "--record-id <ID>", description: "Approval run recordId for exact single-run targeting" },
{ flag: "--sn <SN>", description: "Document SN to adjudicate" },
{ flag: "--verdict <v>", description: "ai_correct | human_correct | both_correct | both_wrong | undecided (required)" },
{ flag: "--note <text>", description: "Optional adjudication note" },
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
],
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
description: "Append-only local JSONL per tenant (~/.config/seal-use/state/reviews/). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
},
{
name: "review list",
summary: "List human adjudications recorded for a tenant+month",
usage: ["seal-use report review list --month <YYYY-MM> [--corp <corpId>]"],
summary: "List human adjudications recorded for a tenant",
usage: ["seal-use report review list [--corp <corpId>]"],
options: [
{ flag: "--month <YYYY-MM>", description: "Statistics month, YYYY-MM (required)" }
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Reads the local JSONL store and returns all adjudications keyed by SN."
description: "Reads the local JSONL store and returns all adjudications."
},
{
name: "review import",
summary: "Bulk import adjudications from an edited Excel/CSV ledger file",
usage: ["seal-use report review import <台账.xlsx|csv> --corp <corpId>"],
options: [
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Reads '复核定性裁决', '复核人', and '复核批注说明' columns from the ledger and bulk writes into the local review store."
}
]
},
{
area: "simulation",
title: "Simulation testing engine",
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules.",
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules. Note: batch search is a local scan over the list API — the server exposes no name/keyword search.",
commands: [
{
name: "batch-records",
@@ -771,8 +815,16 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "list",
summary: "List recent simulation batches",
usage: ["seal-use simulation list [--limit 50] [--corp <corpId>]"]
summary: "List recent simulation batches (filtering is LOCAL only: batches are pulled by limit/offset, the server has no query API)",
usage: ["seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]"]
},
{
name: "search",
summary: "Search simulation batches LOCALLY (not a server-side/native search): scans batches then filters by UI name fragment, document SN, package/template or time window",
usage: [
"seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]",
"seal-use simulation search \"任务 fe1993e4\" --since 2026-10-01 [--corp <corpId>]"
]
},
{
name: "get",
@@ -854,6 +906,56 @@ export const HELP_REGISTRY: AreaHelp[] = [
}
]
},
{
area: "hose-ebot",
title: "Hose EBot outbound discovery & callback (合思 EBot 出站发现与审批回调)",
description: "按单号搜索出站/回调记录、列出出站消息配置(signKey),并执行 EBot 审批回调。",
commands: [
{
name: "search",
summary: "【出站发现·默认入口】按单号搜索出站消息调用记录(只读)",
usage: ["seal-use hose-ebot search <sn> [--type invoking|callback] [--limit <n>] [--reveal] [--corp <corpId>]"],
options: [
{ flag: "--type <invoking|callback>", description: "筛选记录类型:invoking=出站触发,callback=回调;缺省全部" },
{ flag: "--limit <n>", description: "返回条数上限(默认 20,最大 100)" },
{ flag: "--reveal, -r", description: "明文展示记录中的 signKey(默认脱敏)" }
],
description:
"在合思 CloseAPI 出站消息日志中按单号 (SN) 搜索,返回带唯一 id 的记录列表(INVOKING 出站触发 / CALLBACK 回调),含 flowId/nodeId/messageId/rejectionNum 等回调上下文。"
},
{
name: "messages",
summary: "【出站配置】列出全部出站消息配置,发现 signKey 与回调地址(只读)",
usage: ["seal-use hose-ebot messages [--type flow|message] [--reveal] [--corp <corpId>]"],
options: [
{ flag: "--type <flow|message>", description: "按类型过滤:flow=审批流 EBot 出站,message=完成回调/通知" },
{ flag: "--reveal, -r", description: "明文展示 signKey(默认脱敏为 8...4 形式)" }
],
description:
"经合思 CloseAPI 只读查询本企业全部出站消息配置(messageName、signKey、callbackUrl、enable 等)。signKey 即出站回调地址中的 config_id,可直接用于 'hose-ebot callback'。"
},
{
name: "callback",
summary: "【回调审批】调用合思开放接口执行 EBot 审批回调(同意/驳回/加签)",
usage: [
"seal-use hose-ebot callback --flow-id <flowId> --node-id <nodeId> --action <accept|refuse|preAdd|aftAdd> --comment <审批意见> [--sign-key <key>] [--policy <ALL|ANY>] [--add-approver-ids <id,id>] [--reject-to <nodeId>] [--resubmit-method <FROM_START|TO_REJECTOR>] [--dry-run] [--yes|--confirm] [--corp <corpId>]"
],
options: [
{ flag: "--comment <text>", description: "审批意见(必填)" },
{ flag: "--sign-key <key>", description: "出站消息签名密钥;缺省时从本企业唯一 Seal 合思集成解析" },
{ flag: "--action <accept|refuse|preAdd|aftAdd>", description: "同意 / 驳回 / 前加签 / 后加签(兼容 agree/approve/reject)" },
{ flag: "--policy <ALL|ANY>", description: "会签方式:ALL 会签 / ANY 或签(加签超过一人时必填)" },
{ flag: "--add-approver-ids <id,id>", description: "前后加签审批人 ID 列表(加签时必填,逗号分隔)" },
{ flag: "--reject-to <nodeId>", description: "驳回目标节点 ID;缺省按 EBot 节点驳回配置" },
{ flag: "--resubmit-method <FROM_START|TO_REJECTOR>", description: "驳回后重提方式;缺省按 EBot 节点配置" },
{ flag: "--dry-run", description: "仅预览回调请求(signKey 脱敏),不执行" },
{ flag: "--yes, --confirm", description: "正式执行必需;届时实时换取 accessToken 后回调" }
],
description:
"调用合思开放接口 POST /api/openapi/v1/approval,向审批流回写 EBot 节点审批结果,成功返回 value.code=204。仅支持 EBot 节点的审批;signKey 可通过 'seal-use hose-ebot messages --reveal' 发现。"
}
]
},
{
area: "preference",
title: "Audit preferences and thinking depth",
@@ -948,7 +1050,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--from-link <url>", description: "直接由合思协助链接换取 Seal 委托直达链接" }
],
description:
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。主体作用于 Seal 审核后台。"
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。返回实际会话人员 staffName、identityStatus、isAdmin 和 permissions;姓名查询失败时明确标记为未核实。主体作用于 Seal 审核后台。"
},
{
name: "link list",
@@ -970,7 +1072,18 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
],
description:
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。自动查询绑定员工的 staffName、identityStatus 和 roleNames;未能核实的姓名或角色明确标记为未知。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
},
{
name: "hose-openapi-token",
aliases: ["openapi-token", "hose-token"],
summary: "【合思】用持久化密钥签发合思 OpenAPI accessToken",
usage: ["seal-use auth hose-openapi-token [--corp <corpId>] [--force]"],
options: [
{ flag: "--force, --refresh, -f", description: "跳过本地缓存,强制向合思 OpenAPI 签发全新 token" }
],
description:
"专用于合思 (Hose) 来源企业。使用已持久化的 appKey/appSecurity 调用 /api/openapi/v1/auth/getAccessToken 换取 OpenAPI accessToken(约 1 小时有效),stdout 输出含 token、expiresAt 与 cached 字段(cached=true 表示复用了本地仍有效的缓存)。"
},
{
name: "hose-extract-keys",
@@ -1074,13 +1187,49 @@ export const HELP_REGISTRY: AreaHelp[] = [
commands: [
{
name: "expenses",
summary: "Search raw expense items",
usage: ["seal-use data expenses [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
summary: "List expenses, or verify expense-store membership by exact document number with --sn",
usage: ["seal-use data expenses [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"]
},
{
name: "invoices",
summary: "Search raw invoice records",
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--corp <corpId>]"]
summary: "Search raw invoice records (also available as 'seal-use invoices')",
usage: ["seal-use data invoices [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"]
}
]
},
{
area: "invoices",
title: "进项发票查询与溯源",
description: "查看已审批单据中出现的进项发票,支持单据关联穿透、跨单据重复占用排查与扁平化业务视图。",
commands: [
{
name: "list",
summary: "分页查询进项发票(默认输出扁平化业务字段,对齐控制台表格)",
usage: [
"seal-use invoices [list] [--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--full] [--corp <corpId>]"
]
},
{
name: "trace",
summary: "穿透溯源指定发票,排查在哪些报销单据中被使用及是否存在跨单重复占用",
usage: [
"seal-use invoices trace <invoiceNumber> [--corp <corpId>]",
"seal-use invoices <invoiceNumber> [--corp <corpId>]"
]
}
]
},
{
area: "expenses",
title: "费用明细查询",
description: "查询历史费用明细;--sn 按单号关联审批记录并核验费用库存在性,区分找到、关联范围内未找到和无法确定。",
commands: [
{
name: "list",
summary: "普通查询分页返回原始记录;--sn 自动翻页核验,--limit 为页大小,--max-scan 默认为 5000",
usage: [
"seal-use expenses [list] [--sn <documentSN>|--record-id <recordId>|--search <text>] [--start-date <ISO|ms>] [--end-date <ISO|ms>] [--offset <n>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]"
]
}
]
},
@@ -1216,13 +1365,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
commands: [
{
name: "list",
summary: "List approval knowledge documents",
usage: ["seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"]
summary: "List knowledge documents; --summary omits body, --fields selects explicit fields",
usage: ["seal-use documents list [--summary] [--fields <id,title,purpose,updatedAt>] [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"]
},
{
name: "get",
summary: "Get approval knowledge document details by ID",
usage: ["seal-use documents get <documentId> [--corp <corpId>]"]
summary: "Get document JSON, or export exact UTF-8 body plus baseline with --out; --output-file saves JSON",
usage: ["seal-use documents get <documentId> [--out <path>] [--content-format raw] [--overwrite] [--corp <corpId>]"]
},
{
name: "search",
@@ -1231,22 +1380,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "create",
summary: "Create a new approval knowledge document",
summary: "Preview with --dry-run; --yes/--confirm creates and verifies a knowledge document",
usage: [
"seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
"seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]"
]
},
{
name: "update",
summary: "Update an approval knowledge document by ID",
summary: "Preview changes; confirmed updates check export baseline, snapshot and verify readback",
usage: [
"seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"
"seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]"
]
},
{
name: "delete",
summary: "Delete an approval knowledge document by ID",
usage: ["seal-use documents delete <documentId> --yes [--corp <corpId>]"]
summary: "Preview deletion; --yes/--confirm snapshots the document before deleting it",
usage: ["seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>]"]
}
]
},
@@ -1545,14 +1694,10 @@ export function renderHelp(target: string[] = []): string {
}
function normalizeArea(area: string): string {
const lower = area.toLowerCase();
if (lower === "corp") return "corps";
if (lower === "webhooks") return "webhook";
if (lower === "preferences") return "preference";
const lower = normalizeCliArea(area);
if (lower === "changelog") return "update";
if (lower === "serve") return "http";
if (lower === "mcp-config") return "mcp";
if (lower === "server") return "mcp";
return lower;
}
+22 -16
View File
@@ -1,6 +1,5 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { HELP_REGISTRY } from "./help.js";
import {
booleanOption,
BOOLEAN_FLAGS,
@@ -203,23 +202,30 @@ describe("option helpers", () => {
describe("flag registry cross-check", () => {
test("every flag documented in help.ts is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const documented = new Set(
[...help.matchAll(/flag: "--([a-z][a-z0-9-]*)"/g)].map((match) => match[1]!)
);
for (const flag of documented) {
expect(KNOWN_FLAGS.has(flag)).toBe(true);
}
const documented = new Set(HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) =>
(command.options ?? []).flatMap((option) => [...option.flag.matchAll(/--([a-zA-Z][a-zA-Z0-9-]*)/g)].map((match) => match[1]!))
)));
expect([...documented].filter((flag) => !KNOWN_FLAGS.has(flag))).toEqual([]);
expect(documented.size).toBeGreaterThanOrEqual(20);
});
test("every flag shown in a help usage line is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const usageFlags = new Set(
[...help.matchAll(/ --([a-z][a-z0-9-]*)/g)].map((match) => match[1]!)
);
const missing = [...usageFlags].filter((flag) => !KNOWN_FLAGS.has(flag));
expect(missing).toEqual([]);
test("every flag shown in a help usage line is registered, including bracket and pipe forms", () => {
const usageFlags = new Set(HELP_REGISTRY.flatMap((area) => area.commands.flatMap((command) =>
command.usage.flatMap((usage) => [...usage.matchAll(/--([a-zA-Z][a-zA-Z0-9-]*)/g)].map((match) => match[1]!))
)));
expect([...usageFlags].filter((flag) => !KNOWN_FLAGS.has(flag))).toEqual([]);
});
test("formerly rejected public flags retain their boolean and value arity", () => {
const parsed = parseArgs(["report", "data", "--templates", "one,two", "--latest", "record"]);
expect(parsed.options).toEqual({ templates: "one,two", latest: true });
expect(parsed.command).toEqual(["report", "data", "record"]);
expect(parseArgs(["config", "test-dir", "--clear"]).options.clear).toBe(true);
expect(parseArgs(["webhook", "get", "id", "--show-secret"]).options["show-secret"]).toBe(true);
expect(parseArgs(["webhook", "update", "id", "--min-file-size", "10", "--clear-max-file-size"]).options)
.toEqual({ "min-file-size": "10", "clear-max-file-size": true });
expect(() => parseArgs(["report", "data", "--templates"])).toThrow("requires a value");
expect(() => parseArgs(["corps", "list", "--limitt=5"])).toThrow("Unknown option: --limitt");
});
test("boolean and value sets partition the registry apart from the ambiguous three", () => {
+29 -73
View File
@@ -2,7 +2,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";
import { usageError, validationError } from "../core/errors.js";
/**
* Flag metadata for argv parsing, derived from how the code reads each flag:
@@ -23,15 +23,16 @@ import { usageError } from "./errors.js";
// Read with booleanOption(...) / Boolean(...) / presence check.
export const BOOLEAN_FLAGS = new Set([
"V", "add", "all", "as-hose", "attachments", "auto",
"allow-empty", "allowEmpty", "clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret",
"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-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
"r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
@@ -40,10 +41,13 @@ export const BOOLEAN_FLAGS = new Set([
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"allowed-extensions", "allowedExtensions", "extensions", "auto-approval-rate", "autoApprovalRate", "approval-rate",
"min-file-size", "min-file-size-bytes", "minFileSize", "minFileSizeBytes",
"max-file-size", "max-file-size-bytes", "maxFileSize", "maxFileSizeBytes", "templates",
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "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",
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"content-format", "contentFormat", "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",
@@ -52,20 +56,20 @@ export const VALUE_FLAGS = new Set([
"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",
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"max-runs", "max-scan", "maxScan",
"month",
"n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
"path", "phone", "policy", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "rejection-num", "rejectionNum",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum",
"reviewed-by", "reviewedBy",
"report-id",
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
"repo", "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window",
"reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id",
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
"sealUrl", "search", "secret", "selector", "session-id", "sign-key", "signKey",
@@ -86,60 +90,9 @@ export const VALUE_FLAGS = new Set([
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "ai", "ai-accuracy", "aiAccuracy", "add", "all", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
"default", "departmentId", "dept", "desc", "description", "description-file",
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "exclude-deleted", "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", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "refresh-if-missing", "reject-node", "rejectNode", "rejection-num", "rejectionNum", "repo",
"report-id",
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reviewed-by", "reviewedBy",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-hints", "rule-id", "ruleId",
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
"simulationBatchId", "since", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration",
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
"startDate", "startTime", "state", "status", "strict", "strictness",
"summary", "tag", "tag-id", "tagId", "tags", "target",
"template",
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
"until", "url", "userId", "v", "version", "version-name",
"verdict",
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
"workspace", "yes"
...BOOLEAN_FLAGS,
...VALUE_FLAGS,
"f", "h", "version"
]);
export function parseArgs(argv: string[]): ParsedArgs {
@@ -170,6 +123,9 @@ export function parseArgs(argv: string[]): ParsedArgs {
const key = raw.slice(0, eqIdx);
const val = raw.slice(eqIdx + 1);
if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。");
if (!KNOWN_FLAGS.has(key)) {
throw usageError(`Unknown option: --${key}.${suggestFlag(key)}`);
}
options[key] = val;
continue;
}
@@ -283,7 +239,7 @@ export function booleanOption(value: string | boolean | undefined): boolean | un
export function requiredString(input: Record<string, unknown>, key: string): string {
const value = optionalString(input, key);
if (!value) throw new Error(`Missing required JSON field: ${key}`);
if (!value) throw usageError(`Missing required JSON field: ${key}`);
return value;
}
@@ -292,7 +248,7 @@ export function requiredStringAlias(input: Record<string, unknown>, keys: string
const value = optionalString(input, key);
if (value) return value;
}
throw new Error(`Missing required JSON field: ${keys.join(" or ")}`);
throw usageError(`Missing required JSON field: ${keys.join(" or ")}`);
}
export function optionalString(input: Record<string, unknown>, key: string): string | undefined {
@@ -318,7 +274,7 @@ export function parseStateMode(value: string): boolean {
const normalized = value.trim().toLowerCase();
if (["stateful", "state", "有状态"].includes(normalized)) return true;
if (["stateless", "无状态"].includes(normalized)) return false;
throw new Error("Invalid config mode. Use stateful or stateless.");
throw validationError("Invalid config mode. Use stateful or stateless.");
}
export function parseRuleVersionSelector(value: string) {
@@ -388,7 +344,7 @@ export function parseWebhookMode(value?: string): WebhookMode | undefined {
};
const mode = aliases[normalized];
if (!mode) {
throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
throw validationError("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");
}
return mode;
}
@@ -398,7 +354,7 @@ export function webhookRateOption(options: Record<string, string | boolean>): nu
options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"]
);
if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) {
throw new Error("Webhook auto approval rate must be an integer between 0 and 100");
throw validationError("Webhook auto approval rate must be an integer between 0 and 100");
}
return value;
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { writeFileSync } from "node:fs";
import { booleanOption, stringOption } from "./parser.js";
import { PayloadTooLargeError } from "./errors.js";
import { PayloadTooLargeError } from "../core/errors.js";
import { redactSensitiveText } from "../core/redact.js";
import type { OutputOptions } from "./types.js";
+15 -1
View File
@@ -27,7 +27,8 @@ describe("CLI read-only classification", () => {
"auth test",
"auth doctor",
"auth seal-link list",
"doctor auth"
"doctor auth",
"expenses "
]);
test("every allow-listed command exists in the help registry", () => {
@@ -55,11 +56,19 @@ describe("CLI read-only classification", () => {
["corp", "list"],
["corp", "get", "corp-a"],
["documents", "list", "--corp", "corp-a"],
["expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["expenses", "list", "--record-id", "run-1", "--corp", "corp-a"],
["expense", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["data", "expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["documents", "get", "doc-1", "--corp", "corp-a"],
["documents", "get", "doc-1", "--out", "./body.txt", "--corp", "corp-a"],
["documents", "list", "--summary", "--fields", "id,title", "--corp", "corp-a"],
["documents", "search", "差旅", "--corp", "corp-a"],
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
["approval-runs", "list", "--corp", "corp-a"],
["deploy", "hosecloud", "status", "--corp", "corp-a"],
["hose-ebot", "search", "SN123", "--type", "callback", "--corp", "corp-a"],
["hose-ebot", "messages", "--corp", "corp-a"],
["preferences", "get"],
["doctor", "tenant", "--corp", "corp-a"],
["langfuse", "check"],
@@ -87,10 +96,13 @@ describe("CLI read-only classification", () => {
["rules", "clear"],
["documents", "create"],
["documents", "update", "doc-1"],
["documents", "update", "doc-1", "--content-file", "body.txt", "--dry-run", "--yes"],
["documents", "delete", "doc-1"],
["simulation", "create", "--mode", "hosecloud"],
["deploy", "hosecloud", "sync", "sign-key"],
["deploy", "hosecloud", "configure"],
// The EBot approval callback writes accept/refuse into the live approval flow.
["hose-ebot", "callback", "--flow-id", "f1", "--node-id", "n1", "--action", "accept", "--comment", "ok", "--yes"],
["webhook", "delete", "hook-1"],
["webhook", "replay"],
["users", "reset-password", "corp-a:u1"],
@@ -100,6 +112,8 @@ describe("CLI read-only classification", () => {
["mcp"],
["update"],
["auth", "keys"],
// Mints and prints an OpenAPI credential, so it never qualifies as a read.
["auth", "hose-openapi-token"],
["analytics", "analyze", "record-1"],
["tool", "sealApprovalRuleCreate", "--json", "{}"],
["langfuse", "unknown-verb"],
+7 -8
View File
@@ -1,3 +1,4 @@
import { normalizeCliArea } from "./area-aliases.js";
import { parseArgs } from "./parser.js";
/**
@@ -12,13 +13,6 @@ import { parseArgs } from "./parser.js";
* Prefix matching is boundary-safe by construction: `list-evil` does not match `list`.
*/
/** Area aliases the CLI dispatches under an alternative name; mirrors the pairs in runner.ts. */
const AREA_ALIASES: Record<string, string> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference"
};
/**
* Commands that only read tenant state, produce a local file, or inspect local configuration.
* Deliberately excluded even though they look harmless: anything that writes local config
@@ -59,11 +53,15 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
"specifications",
"approval-definitions",
"list",
"search",
"get",
"templates",
"integrations"
],
deploy: ["hosecloud requirements", "hosecloud list", "hosecloud get", "hosecloud status"],
// `hose-ebot callback` is deliberately absent: it mints an accessToken and writes an
// approval action into the live flow. Only the two discovery verbs read.
"hose-ebot": ["search", "messages"],
preference: ["get", "thinking-depth policies list"],
// `config mode`/`config lint` are omitted: classification is token-prefix based, so their
// read forms cannot be separated from the value-taking write forms. `config get` returns
@@ -73,6 +71,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
users: ["search", "get"],
contacts: ["departments", "children", "users", "sync-time"],
data: ["expenses", "invoices"],
expenses: ["", "list"],
llm: ["config", "providers"],
permissions: ["available", "configs"],
billing: ["status", "plans", "features"],
@@ -119,7 +118,7 @@ export function describeCliCommand(argv: string[]): { area: string; actionTokens
const { command } = parseArgs(argv);
const area = (command[0] ?? "").toLowerCase();
return {
area: AREA_ALIASES[area] ?? area,
area: normalizeCliArea(area),
actionTokens: command.slice(1).map((token) => token.toLowerCase())
};
}
+131 -222
View File
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
import type { CorpConfig } from "../core/config/types.js";
import { VERSION_INFO } from "../version.js";
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js";
import { classifyCliError } from "./errors.js";
import { classifyCliError, usageError } from "../core/errors.js";
import {
booleanOption,
materialPackFilePolicyOptions,
@@ -22,51 +22,72 @@ import {
printJson,
redactSensitiveText
} from "./printer.js";
import type { CliResult, CliRunOptions, CliRuntime } from "./types.js";
import type { KyInstance } from "ky";
import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
export const UPDATE_ALIASES = new Set([
"update",
"upgrade",
"up",
"self-update",
"selfupdate"
]);
export { UPDATE_ALIASES } from "./area-aliases.js";
import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "./area-aliases.js";
type LocalCommand = (args: ParsedArgs, runtime: CliRuntime) => Promise<void>;
type CorpCommand = (args: ParsedArgs, corp: CorpConfig) => Promise<void>;
type ClientCommand = (args: ParsedArgs, corp: CorpConfig, client: KyInstance) => Promise<void>;
// Handler tables also define the known command surface. Imports stay lazy so
// local discovery never loads the tenant, Excel, or zip implementation graphs.
const LOCAL_COMMANDS: Record<string, LocalCommand> = {
"mcp-config": async () => (await import("./commands/mcp.js")).printMcpConfig(),
skill: async (args) => (await import("./commands/skill.js")).handleSkillCommand(args.command[1], args.command[2], args),
mcp: async (args) => (await import("./commands/mcp.js")).handleMcpCommand(args.command[1]),
probe: async (args) => (await import("./commands/probe.js")).handleProbeCommand(args.command[1], args.command[2], args),
doctor: async (args) => (await import("./commands/doctor.js")).handleDoctorCommand(args.command[1], args.command[2], args),
langfuse: async (args) => (await import("./commands/langfuse.js")).handleLangfuseCommand(args.command[1], args.command[2], args),
test: async (args) => (await import("./commands/test.js")).handleTestCommand(args.command[1], args.command[2], args),
config: async (args) => (await import("./commands/config.js")).handleConfigCommand(args.command[1], args.command[2], args),
update: dispatchUpdate,
changelog: dispatchUpdate,
corps: async (args) => {
const action = args.command[1];
if (action === "regression" || action === "test-regression") {
await (await import("./commands/test.js")).handleTestCommand("regression", args.command[2], args);
return;
}
await (await import("./commands/corps.js")).handleCorpsCommand(action, args.command[2], args);
}
};
const CORP_COMMANDS: Record<string, CorpCommand> = {
source: async (args, corp) => (await import("./commands/source.js")).handleSourceCommand(args.command[1], corp),
auth: async (args, corp) => (await import("./commands/auth.js")).handleAuthCommand(args.command[1], corp, args)
};
const CLIENT_COMMANDS: Record<string, ClientCommand> = {
"users": async (args, corp, client) => (await import("./commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args),
"contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
"data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
"invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
"expenses": async (args, corp, client) => (await import("./commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args),
"llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
"permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
"billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
"webhook": async (args, corp, client) => (await import("./commands/webhook.js")).handleWebhookCommand(args.command[1], args.command[2], client, corp, args),
"context": async (args, corp, client) => (await import("./commands/context.js")).handleContextCommand(client, corp, args),
"documents": async (args, corp, client) => (await import("./commands/documents.js")).handleDocumentsCommand(args.command[1], args.command[2], client, corp, args),
"rules": async (args, corp, client) => (await import("./commands/rules.js")).handleRulesCommand(args.command[1], args.command[2], client, corp, args),
"approval-runs": async (args, corp, client) => (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(args.command[1], args.command[2], client, corp, args),
"analytics": async (args, corp, client) => (await import("./commands/analytics.js")).handleAnalyticsCommand(args.command[1], args.command[2], client, corp, args),
"report": async (args, corp, client) => (await import("./commands/report.js")).handleReportCommand(args.command[1], client, corp, args),
"simulation": async (args, corp, client) => (await import("./commands/simulation.js")).handleSimulationCommand(args.command[1], args.command[2], client, corp, args),
"deploy": async (args, corp, client) => (await import("./commands/deploy.js")).handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args),
"hose-ebot": async (args, corp, client) => (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args),
"preference": async (args, corp, client) => (await import("./commands/preference.js")).handlePreferenceCommand(args.command[1], args.command[2], args.command[3], args.command[4], client, corp, args),
};
export const KNOWN_AREAS = new Set([
"config",
"update",
"corps",
"corp",
"source",
"auth",
"users",
"contacts",
"data",
"llm",
"permissions",
"billing",
"webhook",
"webhooks",
"context",
"documents",
"rules",
"approval-runs",
"analytics",
"report",
"simulation",
"deploy",
"preference",
"preferences",
"mcp",
"server",
"mcp-config",
"skill",
"probe",
"doctor",
"langfuse",
"changelog",
"test"
...Object.keys(LOCAL_COMMANDS),
...Object.keys(CORP_COMMANDS),
...Object.keys(CLIENT_COMMANDS),
...Object.keys(AREA_ALIASES)
]);
export type { CliResult, CliRunOptions } from "./types.js";
@@ -139,12 +160,53 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliRe
}
}
async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<void> {
const [rawArea, action] = args.command;
const isUpdate = rawArea ? UPDATE_ALIASES.has(rawArea.toLowerCase()) : false;
const area = rawArea?.toLowerCase();
if (isUpdate && rawArea !== "update") {
console.error(`⚠️ Notice: '${rawArea}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);
}
const lowerAction = action?.toLowerCase();
const isChangelog =
area === "changelog" ||
lowerAction === "changelog" ||
lowerAction === "log" ||
lowerAction === "history" ||
booleanOption(args.options.changelog) === true;
const isCheck =
lowerAction === "check" ||
booleanOption(args.options.check) === true ||
booleanOption(args.options["check-only"]) === true;
const isBgSave =
booleanOption(args.options["bg-save"]) === true ||
booleanOption(args.options["silent-save"]) === true;
const targetVersion =
stringOption(args.options.version) ??
stringOption(args.options.tag) ??
(!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined);
await (await import("./commands/update.js")).handleUpdateCommand(runtime, {
checkOnly: isCheck || isBgSave,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
force: booleanOption(args.options.force),
targetVersion,
repo: stringOption(args.options.repo),
bgSave: isBgSave
});
return;
}
async function dispatch(argv: string[], runtime: CliRuntime) {
const args = parseArgs(argv);
const [rawArea, action, maybeName] = args.command;
const lowerArea = rawArea?.toLowerCase();
const isUpdate = lowerArea ? UPDATE_ALIASES.has(lowerArea) : false;
const area = isUpdate ? "update" : lowerArea;
const area = lowerArea ? normalizeCliArea(lowerArea) : undefined;
if (
area === "version" ||
@@ -185,7 +247,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
}
if (!area || !KNOWN_AREAS.has(area)) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
if (
@@ -194,104 +256,30 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
maybeName === "preview"
) {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");
if (!filePath) throw usageError("Usage: seal-use webhook resource-pack preview <资源包.zip>");
await (await import("./commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
return;
}
if (area === "mcp-config") {
(await import("./commands/mcp.js")).printMcpConfig();
return;
}
if (area === "skill") {
(await import("./commands/skill.js")).handleSkillCommand(action, maybeName, args);
return;
}
if (area === "mcp" || area === "server") {
await (await import("./commands/mcp.js")).handleMcpCommand(action);
return;
}
if (area === "probe") {
await (await import("./commands/probe.js")).handleProbeCommand(action, maybeName, args);
return;
}
if (area === "doctor") {
await (await import("./commands/doctor.js")).handleDoctorCommand(action, maybeName, args);
return;
}
if (area === "report" && (action === "validate" || action === "render" || action === "export" || action === "template" || action === "chart")) {
if (
area === "report" &&
(action === "validate" ||
action === "render" ||
action === "export" ||
action === "template" ||
action === "chart" ||
action === "review" ||
Boolean(args.options.ledger))
) {
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
return;
}
// Langfuse trace inspection needs no tenant: it authenticates with the
// compile-time injected read-only key pair, so it dispatches before corp
// selection (like probe/doctor) and never touches a Seal client.
if (area === "langfuse") {
await (await import("./commands/langfuse.js")).handleLangfuseCommand(action, maybeName, args);
return;
}
if (area === "test") {
await (await import("./commands/test.js")).handleTestCommand(action, maybeName, args);
return;
}
if (area === "config") {
(await import("./commands/config.js")).handleConfigCommand(action, maybeName, args);
return;
}
if (isUpdate || area === "changelog") {
if (isUpdate && rawArea !== "update") {
console.error(`⚠️ Notice: '${rawArea}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);
}
const lowerAction = action?.toLowerCase();
const isChangelog =
area === "changelog" ||
lowerAction === "changelog" ||
lowerAction === "log" ||
lowerAction === "history" ||
booleanOption(args.options.changelog) === true;
const isCheck =
lowerAction === "check" ||
booleanOption(args.options.check) === true ||
booleanOption(args.options["check-only"]) === true;
const isBgSave =
booleanOption(args.options["bg-save"]) === true ||
booleanOption(args.options["silent-save"]) === true;
const targetVersion =
stringOption(args.options.version) ??
stringOption(args.options.tag) ??
(!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined);
await (await import("./commands/update.js")).handleUpdateCommand(runtime, {
checkOnly: isCheck || isBgSave,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
force: booleanOption(args.options.force),
targetVersion,
repo: stringOption(args.options.repo),
bgSave: isBgSave
});
return;
}
if (area === "corps" || area === "corp") {
if (action === "regression" || action === "test-regression") {
await (await import("./commands/test.js")).handleTestCommand("regression", maybeName, args);
return;
}
await (await import("./commands/corps.js")).handleCorpsCommand(action, maybeName, args);
// These handlers intentionally run before enterprise selection, including
// Langfuse's compile-time credentials and purely local discovery commands.
const localCommand = LOCAL_COMMANDS[area];
if (localCommand) {
await localCommand(args, runtime);
return;
}
@@ -329,97 +317,18 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
if (area === "source") {
await (await import("./commands/source.js")).handleSourceCommand(action, corp);
const corpCommand = CORP_COMMANDS[area];
if (corpCommand) {
await corpCommand(args, corp);
return;
}
if (area === "auth") {
await (await import("./commands/auth.js")).handleAuthCommand(action, corp, args);
const clientCommand = CLIENT_COMMANDS[area];
if (clientCommand) {
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
await clientCommand(args, corp, client);
return;
}
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
if (area === "users") {
await (await import("./commands/users.js")).handleUsersCommand(action, maybeName, client, corp, args);
return;
}
if (area === "contacts") {
await (await import("./commands/contacts.js")).handleContactsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "data") {
await (await import("./commands/data.js")).handleDataCommand(action, client, corp, args);
return;
}
if (area === "llm") {
await (await import("./commands/llm.js")).handleLlmCommand(action, client, corp, args);
return;
}
if (area === "permissions") {
await (await import("./commands/permissions.js")).handlePermissionsCommand(action, client, corp, args);
return;
}
if (area === "billing") {
await (await import("./commands/billing.js")).handleBillingCommand(action, client, corp, args);
return;
}
if (area === "webhook" || area === "webhooks") {
await (await import("./commands/webhook.js")).handleWebhookCommand(action, maybeName, client, corp, args);
return;
}
if (area === "context") {
await (await import("./commands/context.js")).handleContextCommand(client, corp, args);
return;
}
if (area === "documents") {
await (await import("./commands/documents.js")).handleDocumentsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "rules") {
await (await import("./commands/rules.js")).handleRulesCommand(action, maybeName, client, corp, args);
return;
}
if (area === "approval-runs") {
await (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "analytics") {
await (await import("./commands/analytics.js")).handleAnalyticsCommand(action, maybeName, client, corp, args);
return;
}
if (area === "report") {
await (await import("./commands/report.js")).handleReportCommand(action, client, corp, args);
return;
}
if (area === "simulation") {
await (await import("./commands/simulation.js")).handleSimulationCommand(action, maybeName, client, corp, args);
return;
}
if (area === "deploy") {
await (await import("./commands/deploy.js")).handleDeployCommand(action, maybeName, args.command[3], client, corp, args);
return;
}
if (area === "preference" || area === "preferences") {
await (await import("./commands/preference.js")).handlePreferenceCommand(action, maybeName, args.command[3], args.command[4], client, corp, args);
return;
}
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
throw usageError(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
+3 -2
View File
@@ -3,6 +3,7 @@
* reach the CLI intact. Lives in its own module because both the MCP server and the HTTP routes
* need it; importing it from the server entry would make the CLI graph circular.
*/
import { usageError } from "../core/errors.js";
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
@@ -53,8 +54,8 @@ export function tokenizeCommand(command: string): string[] {
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (escaped) throw usageError("Invalid command: trailing escape");
if (quote) throw usageError("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
+59
View File
@@ -10,6 +10,7 @@ import {
exchangeHoseAssistLink,
fetchHoseStaffDetails,
getHoseEnterpriseUrl,
getHoseOpenapiToken,
getHoseProvisionalAuthLink,
getHoseSealSession,
normalizeBaseUrl,
@@ -402,4 +403,62 @@ describe("hose auth helpers", () => {
expect(getHoseProvisionalAuthLink(corp, -100)).rejects.toThrow("Invalid expire seconds");
expect(getHoseProvisionalAuthLink(corp, 0)).rejects.toThrow("Invalid expire seconds");
});
test("getHoseOpenapiToken serves a fresh cached token and mints a new one under force", async () => {
setupTokenStore({
"corp-test": {
hose: {
openapi: {
token: "cached-openapi-token",
expiresAt: Date.now() + 3600_000
}
}
}
});
const corp: CorpConfig = {
id: "corp-test",
name: "Corp Test",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "key",
appSecurity: "sec",
staffId: "staff-1",
corpId: "CORP-TEST"
},
auth: { refreshTtl: 300 }
};
let mintCount = 0;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
if (new URL(urlStr).pathname === "/api/openapi/v1/auth/getAccessToken") {
mintCount += 1;
return new Response(JSON.stringify({ value: { accessToken: "minted-openapi-token" } }), {
status: 200,
headers: { "content-type": "application/json" }
});
}
return new Response("not found", { status: 404 });
}) as typeof fetch;
const cached = await getHoseOpenapiToken(corp);
expect(cached.cached).toBe(true);
expect(cached.token).toBe("cached-openapi-token");
expect(mintCount).toBe(0);
const forced = await getHoseOpenapiToken(corp, { force: true });
expect(forced.cached).toBe(false);
expect(forced.token).toBe("minted-openapi-token");
expect(mintCount).toBe(1);
expect(getHoseAuthCache("corp-test").openapi?.token).toBe("minted-openapi-token");
const reused = await getHoseOpenapiToken(corp);
expect(reused.cached).toBe(true);
expect(reused.token).toBe("minted-openapi-token");
expect(mintCount).toBe(1);
});
});
+22 -9
View File
@@ -113,7 +113,10 @@ export type HoseProbeResult = {
expireTime?: number;
};
const openapiTokenRequests = new Map<string, Promise<string>>();
/** A Hose OpenAPI access token plus whether it was served from the local SWR cache. */
export type HoseOpenapiTokenResult = TokenEntry & { cached: boolean };
const openapiTokenRequests = new Map<string, Promise<TokenEntry>>();
const closeApiTokenRequests = new Map<string, Promise<TokenEntry>>();
export function normalizeBaseUrl(url: string): string {
@@ -298,17 +301,20 @@ async function fetchHoseOpenapiToken(source: HoseSealSource): Promise<TokenEntry
};
}
export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string> {
export async function getHoseOpenapiToken(
corp: CorpConfig,
options?: { force?: boolean }
): Promise<HoseOpenapiTokenResult> {
if (corp.source.type !== "hose") {
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
}
const cache = getHoseAuthCache(corp.id);
if (isFresh(cache.openapi)) {
return cache.openapi.token;
if (!options?.force && isFresh(cache.openapi)) {
return { ...cache.openapi, cached: true };
}
const pending = openapiTokenRequests.get(corp.id);
if (pending) return pending;
if (pending) return { ...(await pending), cached: false };
const request = fetchHoseOpenapiToken(corp.source)
.then((openapi) => {
@@ -316,11 +322,18 @@ export async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string>
...getHoseAuthCache(corp.id),
openapi
});
return openapi.token;
return openapi;
})
.finally(() => openapiTokenRequests.delete(corp.id));
openapiTokenRequests.set(corp.id, request);
return request;
return { ...(await request), cached: false };
}
export async function ensureHoseOpenapiToken(
corp: CorpConfig,
options?: { force?: boolean }
): Promise<string> {
return (await getHoseOpenapiToken(corp, options)).token;
}
export async function fetchHoseCloseApiToken(
@@ -415,7 +428,7 @@ export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise<string> {
export async function getHoseProvisionalAuthLink(
corp: CorpConfig,
expiresIn = 7200,
_options?: { force?: boolean }
options?: { force?: boolean }
): Promise<{
corpId: string;
staffId: string;
@@ -431,7 +444,7 @@ export async function getHoseProvisionalAuthLink(
throw new Error(`Invalid expire seconds: ${expiresIn}. Must be a positive integer.`);
}
const openapiToken = await ensureHoseOpenapiToken(corp);
const openapiToken = await ensureHoseOpenapiToken(corp, { force: options?.force });
const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn);
if (!provisional.url) {
throw new Error("Hose provisional auth URL was not available");
+18 -4
View File
@@ -5,6 +5,7 @@ import { clearSealSession, getSealSession, setSealSession } from "./token-store.
import { SealEnterpriseConfig, SealSession } from "./types.js";
const memoryCache = new Map<string, SealSession>();
const pendingSessions = new Map<string, Promise<SealSession>>();
function isExpired(session: SealSession, refreshTtl: number): boolean {
return Date.now() >= session.expiresAt - refreshTtl * 1000;
@@ -32,10 +33,15 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
return stored;
}
const next = await refreshSealSession(corp);
memoryCache.set(corp.id, next);
setSealSession(corp.id, next);
return next;
const pending = pendingSessions.get(corp.id);
if (pending) return pending;
const request = refreshSealSession(corp).then((next) => {
memoryCache.set(corp.id, next);
setSealSession(corp.id, next);
return next;
}).finally(() => pendingSessions.delete(corp.id));
pendingSessions.set(corp.id, request);
return request;
}
export async function resolveSealEnterpriseConfig(
@@ -48,3 +54,11 @@ export function clearSealToken(corpId: string): void {
memoryCache.delete(corpId);
clearSealSession(corpId);
}
/** Reuse a concurrent refresh rather than invalidating a newer session on a late 401. */
export async function recoverSealSessionForCorp(corp: CorpConfig, rejectedToken: string): Promise<SealSession> {
const current = await getSealSessionForCorp(corp);
if (current.token !== rejectedToken) return current;
clearSealToken(corp.id);
return getSealSessionForCorp(corp);
}
+12 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -80,6 +80,17 @@ describe("token-store", () => {
expect(getSealSession("corp-1")).toBeUndefined();
});
test.skipIf(process.platform === "win32")("tightens an existing token store without losing other corp caches", () => {
const path = makeTempStore();
const cache = { openapi: { token: "fixture-token", expiresAt: Date.now() + 3600000 } };
setHoseAuthCache("other", cache);
chmodSync(path, 0o644);
setHoseAuthCache("target", cache);
expect(statSync(path).mode & 0o777).toBe(0o600);
expect(getHoseAuthCache("other")).toEqual(cache);
expect(getHoseAuthCache("target")).toEqual(cache);
});
test("sets, retrieves, and clears hose auth cache", () => {
makeTempStore();
const hoseCache = {
+4 -4
View File
@@ -1,5 +1,6 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { writeSecureFile } from "../secure-file.js";
import { SEAL_CONFIG_DIR } from "../paths.js";
import {
CorpTokenCache,
@@ -41,8 +42,7 @@ function readStore(): TokenStore {
function writeStore(store: TokenStore): void {
const path = resolveWriteStorePath();
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
writeFileSync(path, JSON.stringify(store, null, 2), { mode: 0o600 });
writeSecureFile(path, JSON.stringify(store, null, 2));
}
export function getSealSession(corpId: string): SealSession | undefined {
+65 -1
View File
@@ -1,7 +1,8 @@
import { afterEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { saveCorpConfig } from "./repository.js";
import {
findCorpConfigFile,
getLastCorpConfigLoadIssues,
@@ -118,6 +119,69 @@ describe("loadCorpConfigs", () => {
expect(corps.map((corp) => corp.id).sort()).toEqual(["test-corp", "user-corp"].sort());
});
test("updates the same user override that reads select", () => {
delete process.env.SEAL_USE_ENTERPRISES_DIR;
delete process.env.SEAL_HOME_ENTERPRISES_DIR;
const testDir = makeTempDir();
const userDir = makeTempDir();
process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir;
process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json");
saveGlobalConfig({ testEnterprisesDir: testDir });
const testPath = join(testDir, "corp.json");
const userPath = join(userDir, "corp.json");
writeCorpConfig(testPath, "duplicate", "Test copy");
writeCorpConfig(userPath, "duplicate", "User copy");
expect(loadCorpConfigs()[0]?.name).toBe("User copy");
expect(findCorpConfigFile("duplicate")).toBe(userPath);
updateCorpConfig("duplicate", { name: "Renamed" });
expect(loadCorpConfigs()[0]?.name).toBe("Renamed");
expect(JSON.parse(readFileSync(testPath, "utf8")).name).toBe("Test copy");
});
test("same-directory duplicates and invalid shadows use the selected valid file", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
const first = join(dir, "a.json");
const second = join(dir, "b.json");
writeCorpConfig(first, "duplicate", "First");
writeCorpConfig(second, "duplicate", "Second");
writeFileSync(join(dir, "z-invalid.json"), JSON.stringify({ id: "duplicate" }));
// Filesystem enumeration order differs across platforms; writes must follow reads.
const selectedName = loadCorpConfigs()[0]?.name;
expect(["First", "Second"]).toContain(selectedName ?? "");
const selected = selectedName === "First" ? first : second;
const untouched = selectedName === "First" ? second : first;
const untouchedName = JSON.parse(readFileSync(untouched, "utf8")).name;
expect(findCorpConfigFile("duplicate")).toBe(selected);
updateCorpConfig("duplicate", { name: "Updated" });
expect(loadCorpConfigs()[0]?.name).toBe("Updated");
expect(JSON.parse(readFileSync(selected, "utf8")).name).toBe("Updated");
expect(JSON.parse(readFileSync(untouched, "utf8")).name).toBe(untouchedName);
});
test.skipIf(process.platform === "win32")("credential updates and overwrites tighten existing files", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
const path = join(dir, "alpha.json");
writeCorpConfig(path, "alpha", "Alpha");
chmodSync(path, 0o644);
const config = updateCorpConfig("alpha", { name: "Updated" });
expect(statSync(path).mode & 0o777).toBe(0o600);
chmodSync(path, 0o644);
saveCorpConfig(config, { overwrite: true });
expect(statSync(path).mode & 0o777).toBe(0o600);
const globalPath = join(dir, "global-config");
process.env.SEAL_USE_CONFIG_FILE = globalPath;
writeFileSync(globalPath, "{}");
chmodSync(globalPath, 0o644);
saveGlobalConfig({ stateful: false });
expect(statSync(globalPath).mode & 0o777).toBe(0o600);
const migratedDir = makeTempDir();
syncLegacyEnterprisesDir(migratedDir, dir);
expect(statSync(join(migratedDir, "alpha.json")).mode & 0o777).toBe(0o600);
});
test("defaults global config to stateless", () => {
process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json");
+15 -28
View File
@@ -1,8 +1,10 @@
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js";
import { writeSecureFile } from "../secure-file.js";
const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR";
const LEGACY_CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
const USER_DIR_ENV = "SEAL_USE_USER_ENTERPRISES_DIR";
@@ -39,13 +41,13 @@ export function syncLegacyEnterprisesDir(
const primaryPath = join(primaryDir, file);
if (!existsSync(primaryPath)) {
copyFileSync(legacyPath, primaryPath);
writeSecureFile(primaryPath, readFileSync(legacyPath));
copied.push(file);
} else {
const legacyMtime = statSync(legacyPath).mtimeMs;
const primaryMtime = statSync(primaryPath).mtimeMs;
if (legacyMtime > primaryMtime) {
copyFileSync(legacyPath, primaryPath);
writeSecureFile(primaryPath, readFileSync(legacyPath));
copied.push(file);
}
}
@@ -103,8 +105,12 @@ export function getLastCorpConfigLoadIssues(): CorpConfigLoadIssue[] {
}
export function loadCorpConfigs(): CorpConfig[] {
return loadCorpConfigEntries().map((entry) => entry.config);
}
function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
const dirs = resolveEnterprisesDirs();
const byId = new Map<string, CorpConfig>();
const byId = new Map<string, { config: CorpConfig; path: string }>();
const issues: CorpConfigLoadIssue[] = [];
for (const dir of dirs) {
@@ -120,7 +126,7 @@ export function loadCorpConfigs(): CorpConfig[] {
issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) });
continue;
}
byId.set(corp.id, corp);
byId.set(corp.id, { config: corp, path: fullPath });
}
}
@@ -241,31 +247,12 @@ export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
const normalized = GlobalConfigSchema.parse(config);
const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim();
const file = configured || PRIMARY_GLOBAL_CONFIG_FILE;
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
writeSecureFile(file, `${JSON.stringify(normalized, null, 2)}\n`);
return normalized;
}
export function findCorpConfigFile(corpId: string): string | undefined {
const dirs = resolveEnterprisesDirs();
for (const dir of dirs) {
if (!existsSync(dir)) continue;
for (const file of readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.filter((item) => !item.startsWith("example."))) {
const fullPath = join(dir, file);
try {
const content = readFileSync(fullPath, "utf-8");
const parsed = JSON.parse(content);
if (parsed && typeof parsed === "object" && parsed.id === corpId) {
return fullPath;
}
} catch {
// ignore malformed files
}
}
}
return undefined;
return loadCorpConfigEntries().find((entry) => entry.config.id === corpId)?.path;
}
export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): CorpConfig {
@@ -281,6 +268,6 @@ export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): Co
}
}
const validated = CorpConfigSchema.parse(merged);
writeFileSync(filePath, `${JSON.stringify(validated, null, 2)}\n`, "utf-8");
writeSecureFile(filePath, `${JSON.stringify(validated, null, 2)}\n`);
return validated;
}
+6 -9
View File
@@ -1,3 +1,4 @@
import { validationError } from "../errors.js";
import { CorpConfig, GlobalConfig } from "./types.js";
export function resolveCorpConfig(
@@ -18,23 +19,19 @@ export function resolveCorpConfig(
if (caseInsensitive) return caseInsensitive;
const byName = corps.find((item) => item.name.toLowerCase() === selectedCorpId.toLowerCase());
if (byName) return byName;
throw new Error(`No enterprise config found for ${selectedCorpId}`);
throw validationError(`No enterprise config found for ${selectedCorpId}`);
}
if (!options.stateful) {
throw new Error(
"Stateless mode is enabled. Every enterprise command requires --corp <corpId>. " +
"Use `seal-use config mode stateful` to enable a default enterprise."
);
throw validationError("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. " +
"Use `seal-use config mode stateful` to enable a default enterprise.");
}
const firstCorp = corps[0];
if (firstCorp) return firstCorp;
throw new Error(
"No enterprise config found. Add a non-example JSON file under one of: " +
(candidates.length ? candidates.join(", ") : "the configured enterprise directories")
);
throw validationError("No enterprise config found. Add a non-example JSON file under one of: " +
(candidates.length ? candidates.join(", ") : "the configured enterprise directories"));
}
export type CorpContextOptions = Pick<GlobalConfig, "stateful" | "defaultCorpId">;
+3 -3
View File
@@ -1,4 +1,5 @@
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { existsSync } from "node:fs";
import { writeSecureFile } from "../secure-file.js";
import { join } from "node:path";
import { resolveWritableEnterprisesDir } from "./loader.js";
import { CorpConfigSchema, type CorpConfig } from "./types.js";
@@ -20,13 +21,12 @@ export function saveCorpConfig(
): SavedCorpConfig {
const config = CorpConfigSchema.parse(input);
const enterprisesDir = resolveWritableEnterprisesDir();
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
const path = join(enterprisesDir, `${safeCorpFileName(config.id)}.json`);
if (existsSync(path) && options.overwrite !== true) {
throw new Error(`Enterprise config already exists: ${path}. Pass "overwrite": true to replace it.`);
}
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
writeSecureFile(path, `${JSON.stringify(config, null, 2)}\n`);
return { config, path };
}
-8
View File
@@ -1,8 +0,0 @@
// Re-export from domain layer — this file is the legacy entry point.
// tenant-diagnose inherently depends on domains/seal/api, so it now lives there.
export {
type TenantHealthCheck,
type TenantDoctorDiagnosis,
diagnoseTenantContract,
formatTenantDoctorDashboard
} from "../../domains/seal/doctor/tenant-diagnose.js";
+35 -29
View File
@@ -2,28 +2,30 @@
import file0 from "../../skills/seal-use/SKILL.md" with { type: "text" };
import file1 from "../../skills/seal-use/agents/openai.yaml" with { type: "text" };
const file2 = "iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO+LPn9tu6wy0Line truncated
const file3 = "iVBORw0KGgoAAAANSUhEUgAADVoAAAdqCAYAAAAy4TUmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWqADAAQAAAABAAAHagAAAAAG88xiAABAAElEQVR4AeydB2AcxfX/nyT3TrNNTJFNDdgYML2EYnoNfzoG4wCBAKF3CAQcejM19E4wAULnRwBDQiimGGPTm3HBxqYa3OQi6f7zmdM7za32TifpJN9J79mr2Z22s9/dnZ3de9/5liSciZkhYAgYAoaAIWAIGAKGgCFgCBgChoAhYAgYAoaAIWAIGAKGgCFgCBgChoAhsJQRmD59unTu3Hkpt8J2bwgYAoaAIWAItF4ESioqpPTtsVI2fpyUzJopJbNnS8miRa33gO3IJNGxoySWWVYSfftK1ZCNpXrTzSXRqZMhYwgYAoaAIWAIGAKGgCFgCBgChoAhYAgYAoaAIZABgRIjWmVAxqINAUPAEDAEDAFDwBAwBAwBQ8AQMAQMAUPAEDAEDAFDwBAwBAwBQ8AQMARaFAEjWrUo3LYzQ8AQMAQMgTaEQMmvv0q7Z5+SslfGSMmSJW3oyO1QowgkOnSQqqE7StUee0l19x7RZNs2BAwBQ8AQMAQMAUPAEDAEDAFDwBAwBAwBQ6DNI2BEqzZ/CRgAhoAhYAgYAoaAIWAIGAKGgCFgCBgChoAhYAgYAoaAIWAIGAKGgCFgCBQGAka0KozzYK0wBAwBQ8AQaF0IlE14X9rfdL2ULDblqtZ1Zpt2NIlOnWXxCSdL9aD1mlaRlTYEDAFDwBAwBAwBQ8AQMAQMAUPAEDAEDAFDoJUhYESrVnZC7XAMAUPAEDAEDAFDwBAwBAwBQ8AQMAQMAUPAEDAEDAFDwBAwBAwBQ8AQKFYEjGhVrGfO2m0IGAKGgCFQqAi0f/45aTf6wUJtnrWrABBYcuhwqdxp1wJoiTXBEDAEDAFDwBAwBAwBQ8AQMAQMAUPAEDAEDIHCQKBdYTTDWmEIGAKGgCFgCBgChoAhYAgYAoZACyOwYIFUvvaqVL31plTPmC6Jn34SWbiwhRthuzMEckCgUycpWW55Ke3XT8o231Labb2NSOfOORS0LIaAIWAIGAKGgCFgCBgChoAhYAgYAoaAIWAIGAJtGYF2b75uJKu2fAHkeOztH7xfpEdPqdxsixxLWDZDwBAwBAwBQ8AQMAQMAUPAEDAEDIFiRODTnxbLJz8ulq9+WSLT5y+WWRWVMr+qWhIl1dKtfYn07lwmK3dvJ6v36CADl+skay9jvinFeJ6tzflBwBSt8oOj1WIIGAKGgCFgCBgChoAhYAgYAkWCQGL2bFny6MNS6WZylcWLi6TV1kxDIECgY0dpt9se0mH/A0V69goSbNUQMAQMAUPAEDAEDAFDwBAofgRM0ar4z6EdgSFgCBgChkBhIFA6/RvpeO6ZhdEYa0VRILDoimukesXfFEVbrZGGgCFgCBgChoAhYAgYAoaAIWAIGAK5ITBrXrWMmbxQ/vvNQvluYaUjVSX8Ii4UgWQlbqnyIdslfpv4hPymU5kM/U03GbpST1mxa/vcdmi5DIFWgoARrVrJibTDMAQMAUPAEDAEDAFDwBAwBAyB+hGoeudtWXT5JSKLTLmqfrQsR8Ej0LmLc5Y5X8o2HFLwTbUGGgKGgCFgCBgChoAhYAgYArkiYESrXJGyfIaAIWAIGAKGQHYEOtxwrZSNezd7Jks1BAIEqjbdXBYff2IQY6uGgCFgCBgChoAhYAgYAoaAIWAIGALFisC8RSL//KhCnvwaH6kkkQrlKnFEqiShKiFVjkxVWkO88mmSJGGlyFhuuwRCllv2W7WHHLL68tK1fVmxQmLtNgQahIARrRoEl2U2BAwBQ8AQMAQMAUPAEDAEDIFiRaDy8cdk8V23F2vzrd2GQEYEOhxzrLTba5+M6ZZgCBgChoAhYAgYAoaAIWAIFBMCRrQqprNlbTUEDAFDwBAoVARK58yRjn8+plCbZ+0qYAQW3nKHJLp2K+AWWtMMAUPAEDAEDAFDwBAwBAwBQ8AQMATqQ+Ctbyrl+ncrZH5lUpnKaVY5wlR1iljFdopMBZEqULZC0araK1ul5yF/93Yipw3sI1v06VFfEyzdECh6BNzlbmYIGAKGgCFgCBgChoAhYAgYAoZA60ag6j8vG8mqdZ/iNn10i2+7RUp69pKybbZr0zjYwRsChoAhYAgYAoaAIWAIGAKGQHEiUFFR4RveuXPn4jwAa7UhYAgYAgWIQOlbb9TbqqoNNpTK3feSRL+VHLGma735LUPxIlAyf76UzJgu7Z55UsomTsh6IGVvvyWV2++QNY8lGgKGgCFgCBgChoAhYAgYAoaAIWAINA6BlvgWOnrCEhn96SJHrIJO5cSoWHEkKaddJaUJVbaqab/LkCCfy1Pqc/O32olelfgtyrPwh2rmLUnIhRNmyeH9F8qwNXvXVGKBIdA6ETCiVes8r3ZUhoAhYAgYAoaAIWAIGAKGgCFQg0Bi6hRZdPUVhoch0KoRWHTlZdJ5tdWlZKWVW/Vx2sEZAoaAIWAIGAKGgCFgCBgChoAhYAgYAoaAIWAI1I9A2dtvZ81Utf4GsviUM7LmscTWgwBEusSaa8ni086SDu5bedkHmclWpW+9KWJEq9Zz8u1IDAFDwBAwBAwBQ8AQMAQMAUOgTSFw05uV8vKUJVJWQ5QqLYE4BZuq1JOtxKWUOiKVo1vVEKtI5V+1w8nRqxKEZY54VeVxQ+zKlUySsXxM8s99k3+RnxdXygkDfxPELr3Viy++WD799NPYBuy7777y29/+1i+xGSzSEMiAANe+mSFgCBgChoAhYAgYAoaAIWAIGAKtFoHFD97Xao/NDswQCBFY/OD94aatGwKGgCFgCBgChoAhYAgYAoaAQ+Dxxx+XYcOGpWHBj67EsYQ/vmpe4llXI4/mp2xobId5wzRbNwQMAUPAEDAElhYCJdOmZN115V77ZE23xNaLQOXv/1/Wgyv9ZlrWdEs0BAwBQ8AQMAQMAUPAEDAEDAFDwBAoTARuer1Kxnxd6VlR1U6mqsQtiZqQ9ZJq4lyyI12VOj4VnKpqv00cslZsJ/OUuDy+jNsmLbVQR009z8yYJzd+9O1SB4Pv8+F3/miD/vWvfwmLmSHQUASMaNVQxCy/IWAIGAKGgCFgCBgChoAhYAgUDwK//CJVb75RPO21lhoCTUCg6rVXnU773CbUYEUNAUPAEDAEDAFDwBAwBAyB1oUAP7A29w+o/IDLPrL9kNu6ULWjMQQMAUPAECgGBEoWLcrazMTKq2RNt8TWi0Ci74pZD66+aydrYUs0BAwBQ8AQMAQMAUPAEDAEDAFDwBBYKgiMHp+QVyajUuUIU+5vMixJhahVJRdNQ9kKGgl/S6XME6uS68QlSVZlvsyWfXv6kDq13qTOVYlAtnrwqx9c+tKz8DcAVa7SUFtl3+8VCQsbgkC7hmS2vIaAIWAIGAKGgCFgCBgChoAhYAgUEwKV//tPvc0t23Qzab/fgVK6yqoi3brVm98yGAItjsC8eVI9baoseWS0VL37TtbdV/7vVWm32x5Z81iiIWAIGAKGgCFgCBgChoAh0FYQ+OSTT1rsUPkx9y9/+UuL7S+6o5Yglf3jH/+I7ta2DQFDwBAwBIoUgUTHjkXacmt2UxFI1PcNvNLNfm5mCBgChoAhYAgYAoaAIWAIGAJ5QaDkP/f7ehLbDc9LfVaJIRCHwNtTRB79sFoQpRJHmEK2KlHiVKjI7P6UuvghK3fyVKuEVItLcukuocRJWvlcrIuMnTlPt1w8pCpqKJXrdl5dTn7hK3lj1q9+H8Q6iStXjyvk6rl/0mwZ0L2jbNGnBylLzSBXRb/RX3zxxa1qkjT9HYBjXWeddeT//b/sqtVL7WS0kh0b0aqVnEg7DEPAEDAEDAFDwBAwBAwBQ8AQqItA5f/+VzcyiCnbZFPpeMHIIMZWDYECRMA5P5Sus650vPBiWfTXv0jVuMxkq8r//deIVgV4Cq1JhoAhYAgYAoaAIWAIGAJLB4Hoj6raikzx/CgZ98MkP1pmIhllitd9tUSoP662xL5sH4aAIWAIGAKGgCFgCBgChoAhYAgYAoaAIWAIGAKGgCGQGwKVY27xGcuMaJUbYJarwQjMc4LWN7/hijmWVZkjR1U58lQJrCnHhip1pCrIVzf+v94yuF/2CVcmzqyQt59d4Mq5Mq58wpOwRI5fv69v0x8G93VEqznwqjxRi9odnculOWKXC6/56DsZvGxX6doeFazmMUhTWEgw4tu4GvHZjLx8/0fdSlWwwrqylS2EtPB3AI6BJarcVQjtbE1tMKJVazqbdiyGgCFgCBgChoAhYAgYAoaAIZCGQPXkSWnb0Y32Bx4SjbJtQ6CgEWh/8LCsRKvqyV8XdPutcYaAIWAIGAKGgCFgCBgChoAhkH8EWlK5K/+tb5s1JtyMr5if9bVtQpA66iVLlsh3330n/fr1K3g8qqqqpKys+ZxFUqC0oRXOf/v27escsd0jdSCxiBZGgG6aibnNDIGWRIA+EeNZU1qKs2LTjWfX4sWLpXPnzk2vrBXUUFFRIR2dol++8G0FkOTtEBYuXCjV1dXSpUuXvNVpFRkChoAhYAgYAsWOgKpZcRyJu06RkiNH5e2Q5s2bJ5MmTZKpU6dK7969ZbXVVpMVVlghtv5p06b553RsYiRy2WWXlR496qoSzZkzRz777DO/dHMTxULuWH311WPf6SNVNnxzykQpmTyx4eUiJdqKitgj75XI/MVQo0qgVfkwSYBC0apUjtqse70kK4Wu2n+y5GWYGkpkixW7yvANevvkwX27yZ8H95ObJ8yAi+WIWMk8qmw1b0m1PPTVj/LH3/bR6vIahspUSpTiOmQ9m0Gk0jyQq/iWrtuUY524TJOzZau7pdPifgfgmIqh7WClpLi4ye5ywbKp Line truncated
const file4 = "iVBORw0KGgoAAAANSUhEUgAADVoAAAd4CAYAAAB8/5a2AAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWqADAAQAAAABAAAHeAAAAAAc0wiAAABAAElEQVR4AeydB2AUVReFbzodG72jgiJFmh0RFXtDwQZ2FBVQsKN0ESxYUFGQrqK/ioD0jkpRpAoYmvQO0iGB1P+etzub2c3WZBNCcq4uM/P6fNky8+adeyPS1YRGAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAgWYQGQBPneeOgmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAkYAhRa8Y1AAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRQ4AlQaFXg3wIEQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQKEV3wMkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIFngCFVgX+LUAAJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACFFrxPUACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJFDgCVBoVeDfAgRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAoRXfAyRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAgWeAIVWBf4tQAAkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQALRO3fvlNTUVJIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggQJLgBGtCuyfnidOAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRgEYhIV7MOuCUBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiCBgkiAEa0K4l+d50wCJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJOBGgEIrNxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKIgEKLQqiH91njMJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkIAbAQqt3HDwgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIoCASoNCqIP7Vec4kQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAJuBCi0csPBAxIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggYJIgEKrgvhX5zmTAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAm4EaDQyg0HD0iABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABAoiAQqtCuJfnedMAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiTgRoBCKzccPCABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiiIBCi0Koh/dZ4zCZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZCAGwEKrdxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKAgEqDQqiD+1XnOJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACbgQotHLDwQMSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIIGCSIBCq4L4V+c5kwAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJuBGg0MoNBw9IgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgAQKIgEKrQriX53nTAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIk4EaAQis3HDwgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIoiASiC+JJ85xJgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgATyAIFlSyVtyWJJjY+XlK3bJP3QYTOoiLPPkugqlSWqVi2JbNRYpEHDPDBYDoEESCC/E4hIV8vvJ8nzIwESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESyDsE0idPlOQxYyRl89agBhVVrYrEtmwpEbffGVR5FiIBEiCBrBCg0Cor1FiHBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEggdAL/rpfkzz+T5BWrQq+rNWIurSMxHTqKXFAjS/VZiQRIgAT8EaDQyh8d5pEACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACYSHwG+/SUKPHmFpq0ivXiJNm4alLTZCAiRAAhYBCq0sEl626ZoWoS9raxVJ04RIzUhJE3n151T5UyMVFi8eIeVLRkqFs0XOP0fFsaVEyhQXKVdMpEScVZNbEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiiABMIosrLoUWxlkeC2IBJIS0uT5JQUSUlJldTUVMExXunp6eYFJhEREeYVGRkpeEVFRUl0dJTEREeb44LILdA5U2hlIwQBVVKqyMaDIv/sF7mvlkiUCqogtLLMEl6h7IY9adJmRKqcStfUmEiRaBVgxeobT7exMSq+ihUpqSKrS0uL3HmRSM3zND3KIdKy2uOWBEiABEiABEiABEiABEiABHwSWL5cZOkySY2Pl9SNWyRt525JO3zcFI88q5hEVignUedXlahaevPSsIFI/fo+m2IGCZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZw2Av+ul4S2zwTdfXSNCyTyLI2Copa8fIWkJyf7rFtk6FcaKaWGz3xmkEB+IpCcnCJJSUmSpJ8JiKuyYxBdxcbESGxsrMTEqBCGZggULine truncated
const file5 = "iVBORw0KGgoAAAANSUhEUgAADVoAAAdyCAYAAADdZLXQAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWqADAAQAAAABAAAHcgAAAABWYxAhAABAAElEQVR4AeydB6BO5R/Hf3fbWshOS4QiWipR2ktRirZSoWgPMhLtPciISv0rITOzZJRkhMyQlVW2u8f/933e93nved/7zrtc935/9TrnPPt87jvOec7v+/yistSERgIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIlmEB0CT53njoJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJGAIUWvGNQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkUOIJUGhV4t8CBEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJBC7bfs2ycjIIAkSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKLEEGNGqxP7peeIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAKWQFSWmj3glgRIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARKIgFGtCqJf3WeMwmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQgBcBCq28cPCABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEigJBKg0Kok/tV5ziRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAl4EKLTywsEDEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiCBkkiAQquS+FfnOZMACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACXgRoNDKCwcPSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESiIBCq1K4l+d50wCJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJOBFgEIrLxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKIkEKLQqiX91njMJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkIAXAQqtvHDwgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIoCQSoNCqJP7Vec4kQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAJeBCi08sLBAxIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggZJIgEKrkvhX5zmTAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAl4EaDQygsHD0iABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEoiAQqtSuJfnedMAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiTgRYBCKy8cPCABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiiJBCi0Kol/dZ4zCZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZCAFwEKrbxw8IAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESKAkEogtiSfNcyYBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEigCBBYvkszfF0rGypWSvmmzZO3dZwYVdewxElu7lsTUry/RTZuJNDmnCAyWQyABEijuBKKy1Ir7SfL8SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAEig6BrEkTJG30aEnfuCmsQcXUqS3xbdtK1LXXh1WehUiABEggNwQotMoNNdYhARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARKInMBfayXtg/clbenyyOtqjbizG0pc124ip56eq/qsRAIkQALBCFBoFYwO80iABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABPKHwOzZkti7d760VaZvX5EWLfKlLTZCAiRAApYAhVaWhJ9tlqZF6ctubZFMTYjWjPRMkae+y5BfNVJh+fJRUq1itFQ/VuSU41QcW0mkSnmRquVEKiTYmtySAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQAkkkI8iK0uPYitLgtuSSCAzM1PS0tMlPT1DMjIyBMd4ZWVlmReYREVFmVd0dLTgFRMTI7GxMRIXG2uOSyK3UOdMoZWDEARUqRki6/eI/Llb5Jb6IjEqqILQypoVXqHsuh2Z0vHTDEnJ0tS4aJFYFWDF6xtPt/FxKr6KF6moIquzK4tcf4ZI3RM0PcYl0rLtcUsCJEACJEACJEACJEACJEACAQksWSKyaLFkrFwpGev/lsxt2yVz3yFTPPqYchJdvarEnHKSxNTXm5dzmog0bhywKWaQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQG4IZKrDZFpaqjrvwmlXV6inkUABE4iKghN4tMTFxasDODx3aSRAAsWCwF9rJbHTg2GfSuzpp0r0MRoFRS1tyVLJSksLWLfM0E80UsrpAfOZQQLFiUBaWrqkpqZKqn4mIK7Ki0F0FR8XJ/Hx8fq7q0IYmiFQ4oVWKtSTDH1tPSCyYLPI9PUia/eK9LhA5EYVR+H6DEIre5mGfVhaepa89UOmjPpdlX96MSdxURKtYqss3Y3W/QwIqlxFBdkJ+mqoQqvWJ4ucW0ukVgUVcWmaigNpJEACJEACJEACJEACJEACJJBNYMtmyRr7vaSMmyiZm7dnp4exF12rqiTcdK1EtblJpKbeeNBIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIIA8EUlPTjMgqD02wKgnkiQDEVvGIfkAjARI46gmkde8maUuXh3Ue0eXLSamv/idSrpxGR1GB1gPBBVpxZzeUuHfeD6ttFiKBo5EAIlQlJ6dIckpKnsVVgc4foqtSCQlSqlSCiYAVqFxJSC+xkjMIpjQimhxOFfnqD32tENmj+xBdVSmtUaiqZv/5oYWyAiubujdRhVnrM0UXaBAVzgsWachCZVVOYd8ItLQiIl8ZMVe6yK/qI7l4h0iZhSLtVMR1zzka9UojXmn0NY+Qy7bPLQmQAAmQAAmQAAmQAAmQQAkjsP+AZH38sSQNHZXrE4cwK+m9oSL6Kt2pg0Q9/LCG2dVVHmgkQAIkQAIkQAIkQAIkQAIkLine truncated
const file6 = "iVBORw0KGgoAAAANSUhEUgAADVwAAAdqCAIAAACwndI2AAAACXBIWXMAAAAAAAAAAQCEeRdzAAAAXGVYSWZJSSoACAAAAAMAaYcNAAEAAAAyAAAAAAEEAAEAAABcDQAAAQEEAAEAAABqBwAAAAAAAAMAAaADAAEAAAABAAAAAqADAAEAAABcDQAAA6ADAAEAAABqBwAAXAAAALB3cgIAAAABc1JHQgHZySx/AAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAEZ0FNQQAAsY8L/GEFAAAQAElEQVR4nOzdB0AUZ94G8HdmYQFZpBcFBRR7F7uJLRprLDHGaBJjejnz5S79TDO9t0uPKcZUkxhrolFjBxQrFgRBeu9lgWXLzPfOzDIs21iqiM/vuM3su9NYBnbWefb/Z+Li4nQ6HQEAAAAAAAAAgJbhed50ghdxHCfdSuTpGTNmXNadBQAAAAAAAAAAAIDOyely7wAAAAAAAAAAQCfE1yEmYUGzcQAAAAAAAAAAAACAVodQIAAAAAAAAABAmzMNAiIUCAAAAAAAAAAAAABtB6FAAAAAAAAAAIA2ZLVMIEKBAAAAAAAAAAAAANBGEAoEAAAAAAAAAGhNloE/y1bCCAUCAAAAAAAAAAAAQBtBKBAAAAAAAAAAoJ0gEQgAAAAAAAAAAAAAbQ2hQAAAAAAAAACAtmIr/4dcIAAAAAAAAAAAAAC0EYQCAQAAAAAAAADaD+KAAAAAAAAAAAAAANCmEAoEAAAAAAAAAAAAAAAAAAAAAAAA6CQQCgQAAAAAAAAAaFcoFggAAAAAAAAAAAAAbQehQAAAAAAAAAAAAAAAAAAAAAAAAIBOAqFAAAAAAAAAAAAAAAAAAAAAAAAAgE4CoUAAAAAAAAAAAAAAAAAAAAAAAACATgKhQAAAAAAAAAAAAAAAAAAAAAAAAIBOAqFAAAAAAAAAAIB2wvP85d4FAAAAAAAAAAAAAOjkEAoEAAAAAAAAAAAAAAAAAAAAAAAA6CQQCgQAAAAAAAAAAAAAAAAAAAAAAADoJBAKBAAAAAAAAAAAAAAAAAAAAAAAAOgkEAoEAAAAAAAAAAAAAAAAAAAAAAAA6CSullAgTwhDiIEnH/7Dncsjbl2YAHfGvysT4klCvBm/LsS3C+/uzF/u3QQAAAAAAAAAAAAAAAAAAAAAAABovs4TCuQJ0RtIZiWbUsJP68WzDR9lCOEIySrhT2VwWoZVV/FFGl5RzrI5jJMzr3JiuiiZvt5kUjgJ9+SdFML8AAAAAGALk5jIX0jgU1IN2dl8YTGnrqGDrMqN8fdVBAczvcKZAf35fv0u924CAAAAAAAAAAAAAAAAAFx1OkMo0MCTQjVzJp/EZpJUNbl9iPVIH2cgey/wOh0hLOEZht7q9LyCEC1hNDqe1JCsSnIwk0R4MWODyeAgEuTOK1hrKwIAAAC4WjEFBfy+fbr9h7n8IstHhWigOsuQmkUOH6V32UA/5ynXMFOn8gEB7b6nAAAAAAAAAAAAAAAAAABXqSs7FMjxpEbH/H2R7Ewhah3R88TXhfTztT5zpYacz+Q4jjAsYXnC04UVDKF36Q1DeJ4OMAaenCsiF4uJSzyZHsbM60/clTyLsoEAAABw1WOqqvjfNmq27nB8ES6/qHbDZrJhs8v82cySxby7e9vtHgAAAAAAAAAAAAAAAAAASK7gUKBWT/ankD3JJL2Sl0acGNLbmwR68JYpPl7sHZxRwnMsq+AIwxFiYHmG1zNEwQnzi4sITYfpIzr6pSdbE8ipbGZ6bzKlN1Fewc8TAAAAQIvFxmo//lzqEdwMtVt3sHv3O696gIwZ07r7BQAAAAAAAAAAAAAAAAAAZq7IsBvHk7xK5tNoJr2cM/CUOEiImxOZ2Ye32vJXryc7T+s5A53keYYV5hYygUJakOeESCBdJ8sQnXgrTdN5Myr470+TI+nsveP5QBVKBgIAAMBVacMGoeBfy3Dqmto33ndZupAsXdoqOwUAAAAAAAAAAAAAAAAAAFZdeaFAnZ4cTmG2JJD8Ko7jxXSfOM4QEuLB9PPlrS6VX86fy+CFPKAQBBQmGMLwBroYwwu9hImCCAFBRnjQOM2J9QU1hFwo5t76h5k7gJ3cm3O+8p4wAAAAgBb47LPa3Qdba2W1Gza7lJSQBx9srRUCAAAAAAAAAAAAAAAAAICZKyzjVq1j/jxH/kzgawwMzwi5PSIUDmSEaB9DBgcSJ4X1BU+mGDS1RCgRyBMxF0gYPWGdhAggzwmLSysRQ4EMXbeCp3eEEoR0RM8xOWry/UmutJqZN5i4OVvPHQIAAAB0Nq2aCJTQFbrQ/yAXCAAAAAAAAAAAAAAAAADQNq6kUGClhlkbTU7l8bUGsY+v0Aa4Ds84Kfi+AcRqh1+dgSRkGjgDwzGE4YRooNA1mCcsR3g9YZyExRlxJURMATJiY2GWN65LCA4ypEbPbL3AZ5Uw90xkPFyRCwQAAIDObsOGVk8ESoRcoI8P+ggDAAAAAAAAAAAAAAAAALSFKyYUWKlh1h0hx7OJwSAE+KQagVIoUJr2cGZ6+VhftqaWpOWKvYM5wrNiyI8nCqFGoFg70EDkcCFnshRLjL2JGbGPMKU1MEdziHMMuWM8coEAAADQqcXG1m7Y3HarF/oIh4eTMWPabhMAAAAAAAAAAAAAAAAAAFenKyMUqNEyaw+T2EwiB/FYk0el6THhROViPagXn64vUYsPCTcMxxMFJ5YFrGsibLYqs7umg7yeRKWTGj3512SmixK5QAAAAOiEmKoq7ceft/VWdB9/rvxsEO/u3tYbAgAAAAAAAAAAAAAAAAC4qlwBoUCdnmyNIyeyhMJ9vEl1QKGGn1jZj2cJw5DJvQnLWlmcLvLnMb3BwHMMr2AZwvE8XU7sIKwQCwcyerFeoLg2XlyDXCNQWFyap25D0grjssj2OLJoBHG+Ap4/AAAAgKbhf9vIqWvaeit0E3RDZOWKtt4QAAAAAAAAAAAAAAAAAMBVpaOH2jie7Etkt5zldXoxBcgYiwXy8peY7QvyJN09zev8SUoq+aRMg55npMggL1UM5ISmwAaWsGIHYemumBY0blTaEC9OGBOB4qP0lhP6CJMtZ4mvOzt1AMcy7fJEAAAAALQLpqBAs3VH0xbp4ubUt5cht4DLL2zSgrVbd7jOmcUHBDRpKQAAAAAAAAAAAAAAAAAAsKOjhwLzytjtcbxOK6b0eCJm98R6geJdRowJ0ttQH+LEWmnmy/EkKdPA88bGwUL4T1hGuCdMCC2ECScmAolxROwpTIg0JNwYlzU+ykgbYYheS7ac5vt3Y4O9ufZ4IgAAAADaBb9vn+MzO08cq1i8gA8No6dKwucviovJrl21v21t2uaWLm3yXgIAAAAAAAAAAAAAAAAAgA0dOhSo1ZPP95GCSmHawImFAOsyeTwn3kqJPQXpE2i9d7AQCsw2cMZCgDzDM0xdjUGhHCBfHw6kd9m60KFwK66fEzdnrAUoLSU1FxbH6Y598g9Zs5Ao2+BZLC0tpbfe3t6tv2oAAAAA23T7Dzs4p3LGJOb+++npFZuawqelkdBQPrwXWbbMxdu79sv1dedtjW/OGaFAAAAAAAAAAAAAAAAAAIDW03FDgRxP9sYzlwp4g1iJjzG9sMyb3BKhq2//IDHcZ2UtJCldz/E8J1SvYaRSf5zUHpgTSw2ydaviiYEhrNxcmKkrGVjXcdi4rbrQIGUwkPQinu7k9UN4NBHulKqraz74+DODVkun58yZFTlyuIMLJiUn79tnTFTMm3t99+7dpemU1LQ9e/ZL07NnTe/RI6SpuxQdfSQ7N0+avmHuLFdXV1tzlpaWHTwclZ1F/5fXs2fwA/fd3dRtdXxFRcWffb5Wml52y5KIiN6Xd38AADoBJjGRyy9yZE42JJB58EHGYDC8/0Ft1DFp0Pnasewj/0dmzXI+clR3JsGR9dDN0Y3y/fo1f6cBAAAAAAAAAAAAAAAAAMBExw0FVmmY3WeJziCE8KT6fKakNr68GOpTuZJQH95aoUBSoyPJuQbOwDIK41KcWC9Qiv0xnFgQkBHWY1xh3YJSEJAO8iZpP0asFEhIfQDRYCB/nyXX9GVUrg7VwoEryy8bfouPv0AnvD09hwweaDmDTqcrKSm1HL94MflgVJQ0PWBAX4XC+IuWlFQ/3ieil1KpNFvQ2dnZx8deecgjscdOnj4jTU+fNsVOKNCti9uOv/eo1Wo6nZeXd9vyW1QqdztrvhL5+fmqVKoTp+Po9Nff/PDKy88qFIrLvVMAAFc2/oJDST7KecQw4T8HD+jqEoGU7tBRl2uOk9FjmOHDiGOhQONGEQoEAAAAAAAAAAAAAAAAAGglHTQUaODI5mMks4QYhCgez0hdf8UJaQa+LrHHsmRkT2I1CMTx5PwlnaaGZxRiw1+O51giJQKFhQ0MrxBSfrxYFVBYv7AZccWMcVs8MalHKJYbNG6dF2agE3rCZJSQHaeZG8fwCquxRLhiJSYm7T9wSJq+cdECywAflXwp5dU33rG/ni+++tbq+NfffW852Kd3+AvPrW7inlrn6uIye8Z1v23aQoRO3LromKPXz5jWKmvuUJYsufFk3Fn625mZk/XXjr9vmDfncu8RAMCVjU9JdXTW7t2ZwiLuzHnz8eRLQigwvFeTNoqaywAAAAAAAAAAAAAAAAAAraWDhgJzy5i95wkvRPmEXr1CIE+cYMUonlQ4ULjliYIlkWHWryNzBhJzTkeMiT8xRCguzCjEaKDQd5gRWgqzvLQ2Op+4Ip4xtifmTSsUcqRBI2HGeCvMvOM0mdCPDfbm2uKpgMtCr9d/s+576ScaFBQ4edLEy7xDzTJ9xrRtO3ZpNDV0ev+hqE4ZCgwJ7j5x/JjD0Ufo9KYtf44bO9rf3/9y7xTA5VepVru5ujo52XyVr6qqUqurAgMD2nOvrmZ5efn01cT+PEVFxZWVlZ6envZLLine truncated
const file7 = "iVBORw0KGgoAAAANSUhEUgAADVwAAAdwCAIAAAAS0PPLAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANXKADAAQAAAABAAAHcAAAAACLl/RJAABAAElEQVR4AeydB2AURRuGJ52E3jsIUqR35KcjKooFFBCkSRORXhRF6QioICJNehNQpPfee5fea+i9pSd3/7s3ybC527tcCnAJ73oes998Mzv77GZ3b/adb9yuXr8aEREhuJAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACSRmAh4eHu6Juf1sOwmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQwDMCbmaz+dkaUyRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAomWACMFJtpDx4aTAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQHQCFAVG58E1EiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEki0BCgKTLSHjg0nARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggegEKAqMzoNrJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJJBoCVAUmGgPHRtOAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAtEJUBQYnQfXSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESCDREqAoMNEeOjacBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABKIToCgwOg+ukQAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkECiJUBRYKI9dGw4CZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACZAACUQnQFFgdB5cIwESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIIFES4CiwER76NhwEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEohOgKLA6Dy4RgIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAKJlgBFgYn20LHhJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJBCdAEWB0XlwjQRIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgAQSLQGKAhPtoWPDSYAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESCA6AYoCo/PgGgmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAkkWgIUBSbaQ8eGkwAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkEB0AhQFRufBNRIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARJItAQ8E23L2XASIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAGXJ3BgfwQ+x4+H+18x33+E5rqlS+2ZM5dHkSIeZcoKfLiQAAkkKAE3s9mcoBWyMhIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIQ5hXLQufPC794xQELjzy5fOo3cPvgIwc+zCIBEogVAYoCY4WLziRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAiRAAjEROHcmdPSosMPHYvKLzPcqUdS7U2eRr4CT/nQjARJwQICiQAdwmEUCJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJEACJBBLAps3B/TvH8symntylKpePQ4FWYQESEBPIGmKAjEjspsQ8lvurcks3N1EuEn0nGfafcWcIpVbtlTu2dKJ19OKfJlE1hQiS0qRykdPhmkSIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIIFYEoirIlBuhrrAWOKmezQCJpMpLBxLhLZgJSLCbFng5GZZ3D08PNy1L09PDy9PT3d392jlk8pK0hEFQvYXGiHO3xPH74p6hYWHmyYKlIsUCMLh7A1T02kRIWY34eXu5incfNw9PIW3l0iFj48omVl8VFAUzCi8PTQFIRcSIAESIAESIAESIAG7BA4dFPsPhZ88HnH+sunaTdPDJ/B0T5PSPXsWj9dzexYqIsqWEqVK2y3ODBIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIgARIggSRJ4NyZgDZtHe+ZR4F8HmnSwifs4H/m8DBb5+STJ3IeYVsstDggEBYWHhoaGhIaFhER7sDNNgviQB9vL29vby8vT9vcxGtJ9KJAs1lEmIX/I7HXX6w/J04/FN3+J+q8oan6VKRAqQ4MCzePWG2avT8iwgOKQDd3L3eTu3D3douABNByAD3chY+7KJZevJ1XlM8lcqcWsLhRHZh4z262nARIgARIgARIIMEJXLlsWrw0ZNEKk//1GOt2z5nN55Pa7nXriFy5Y3SmAwmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQQBIgENqlY9jhYw52xD2ln+/f/4oUKcTZMwFfGssHvUoU9f5jjINKmEUCkgCCAAYHhwQFh8RWC2gLEOpA32Q+yZL5IJ6gbW6isyRihSOkfiaTCAgVc/4T/xwX90M1dWBmX1EiS+RRkAEC1SG5Hyj2nDNFmIQbNIAmYYowa4cwwiIfdBOII6jpC8PF7pvi4C3ht180KChalBUpfQSCRCaFQ61AMEECJEACJEACJEACcSDw6LFp3LigKXOcLwrhYNCoyWLUZN/Wjd3btxepUzlflp4kQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAIkQAKJjoB5xTLHikDskU+9+poiEGECZ860t4OoxGvFMrcPPrLnQDsJQA4YFBQcGBSERILQgKzwaUB4QGCgny+WZIldGpiIJ0UODhP/HhYt54nR+8SdQE3P52kSxTKJ3GkiJ/9VB1xTB5rFhVvms7fCzZg7GLpAk5u7SUtAVmg2CU0aqPsODRcPg8TU/0Sb+eLf/wQ2xIUESIAESIAESIAEXmkC69YH1Xw/VopAPS4URHGxbr3eyDQJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkAAJkEASIxAyf57jPXJL4etev4Hmc/5s6LbtDpxDY6rKQVlmJXkCQcHB9+4/hIAvoRSBihgqRLWoHJtQxsSYSJSiQET7O39PfDlPDNsuzt0X7uHaR4QLHzfRqKjwsEwcrBSB8qhg7uC/t4ebIiABxH9umhQQ/5ihDtTKukVoxfENZaFKw/nMPTFsh2i/QFy4L7BRLiRAAiRAAiRAAiTwChIwjR4V8HV308Mn8dl3FNcqGT0qPpWwLAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQAAmQgOsSOLA/4uIVx81LVq+BSJESPmHTZzj2DEdVB/Y79mHuK0ggwmR69PjJ06cBZi0O3PNaUDk2gQ1hc89rG8+53sQnCgwJE4sPiy6LxdFbIixMhEPPBwGg5VMgrSiZTUtiQXRANecvLP53zHtPhyM0oEeEcEPYQJObG6SBKItggchGpECLQBCFccJEpjUFocDmDt4QXRaKhf9paS4kQAIkQAIkQAIk8EoRiOjdJ+iPyQm1y6gKFSZUbayHBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEjAdQhExKThc/P1c/+0vtbgs6cdhwmUOxVjha6z72zJiyEQEhJ6//6D0NDQF7M5bAibw0ZfzOYSdiueCVvdc60N4r2nIWLmbjHzoAgKF5Z5gLUNQuPn5qYFCCyXXXh7aFpAeOLzbDGLrScjAkPMmFdYm0UaQkCIIS0qQMj+NPkgggsi4SY0s6YYFB6Wb4QShCXCLC4/EL9uEbefiC8qiOQ+z+SGzzbBFAmQAAmQAAmQAAkkOQIQ8AX/syRhdwsVJhPC46dBCVstayMBEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEiABEni5BCKOH3fcAJ9PPxGpU8EndOpUx54yFxV6OONHn1eDQGBgECb2ffH7+vjJk+QRfn5+vi9+0/HZYqKJFAit3qNA0W+5mLZfPA3VJvNFnD93RPWzxPNDqD/IG4vnEB6WHZIxAjW1n4VNSIT5 Line truncated
import file2 from "../../skills/seal-use/assets/hose-curl-copy-as-curl.png" with { type: "file" };
import file3 from "../../skills/seal-use/assets/hose-curl-network-fetch-xhr.png" with { type: "file" };
import file4 from "../../skills/seal-use/assets/hose-curl-open-page-check.png" with { type: "file" };
import file5 from "../../skills/seal-use/assets/hose-open-platform-app-center.png" with { type: "file" };
import file6 from "../../skills/seal-use/assets/hose-open-platform-credentials.png" with { type: "file" };
import file7 from "../../skills/seal-use/assets/hose-open-platform-product-config.png" with { type: "file" };
import file8 from "../../skills/seal-use/references/approval-attachment-trace.md" with { type: "text" };
import file9 from "../../skills/seal-use/references/approval-bad-cases.md" with { type: "text" };
import file10 from "../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" };
import file11 from "../../skills/seal-use/references/cli.md" with { type: "text" };
import file12 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" };
import file13 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
import file14 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
import file15 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
import file16 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
import file17 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
import file18 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file13 from "../../skills/seal-use/references/documents.md" with { type: "text" };
import file14 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
import file15 from "../../skills/seal-use/references/expense-data.md" with { type: "text" };
import file16 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
import file17 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
import file18 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file24 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -33,20 +35,22 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/approval-run-lightweight.md": file10,
"references/cli.md": file11,
"references/customer-feedback-rule-remediation.md": file12,
"references/enterprise-onboarding.md": file13,
"references/first-time-user.md": file14,
"references/hose-enterprise-auth.md": file15,
"references/hose-enterprise-deploy.md": file16,
"references/hose-enterprise-init.md": file17,
"references/langfuse-trace.md": file18,
"references/report-templates.md": file19,
"references/rule-lightweight.md": file20,
"references/rule-lint.md": file21,
"references/staging-simulation-workflow.md": file22,
"references/webhook-resource-pack.md": file23,
"references/documents.md": file13,
"references/enterprise-onboarding.md": file14,
"references/expense-data.md": file15,
"references/first-time-user.md": file16,
"references/hose-enterprise-auth.md": file17,
"references/hose-enterprise-deploy.md": file18,
"references/hose-enterprise-init.md": file19,
"references/langfuse-trace.md": file20,
"references/report-templates.md": file21,
"references/rule-lightweight.md": file22,
"references/rule-lint.md": file23,
"references/staging-simulation-workflow.md": file24,
"references/webhook-resource-pack.md": file25,
};
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
"assets/hose-curl-copy-as-curl.png": file2,
"assets/hose-curl-network-fetch-xhr.png": file3,
"assets/hose-curl-open-page-check.png": file4,
@@ -69,7 +73,9 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/approval-run-lightweight.md",
"references/cli.md",
"references/customer-feedback-rule-remediation.md",
"references/documents.md",
"references/enterprise-onboarding.md",
"references/expense-data.md",
"references/first-time-user.md",
"references/hose-enterprise-auth.md",
"references/hose-enterprise-deploy.md",
+5 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import packageJson from "../../package.json" with { type: "json" };
@@ -37,6 +37,10 @@ describe("embedded-skill", () => {
expect(existsSync(join(tmp, "references", "enterprise-onboarding.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "first-time-user.md"))).toBe(true);
expect(existsSync(join(tmp, "assets", "hose-curl-copy-as-curl.png"))).toBe(true);
expect([...res.files].sort()).toEqual([...EMBEDDED_SKILL_ALL_PATHS].sort());
for (const path of EMBEDDED_SKILL_ALL_PATHS) {
expect(readFileSync(join(tmp, path))).toEqual(readFileSync(join(import.meta.dir, "../../skills/seal-use", path)));
}
} finally {
rmSync(tmp, { recursive: true, force: true });
}
+11 -4
View File
@@ -3,16 +3,23 @@ import { homedir } from "node:os";
import { dirname, join } from "node:path";
import {
EMBEDDED_SKILL_ASSET_DATA,
EMBEDDED_SKILL_ASSET_PATHS,
EMBEDDED_SKILL_TEXT_FILES
} from "./embedded-skill.generated.js";
export { EMBEDDED_SKILL_ALL_PATHS } from "./embedded-skill.generated.js";
export const EMBEDDED_SKILL_FILES = EMBEDDED_SKILL_TEXT_FILES;
export const EMBEDDED_SKILL_ASSETS: Record<string, Uint8Array> = Object.fromEntries(
Object.entries(EMBEDDED_SKILL_ASSET_DATA).map(([relPath, base64]) => [relPath, Buffer.from(base64, "base64")])
);
// Runtime self-healing imports this module even for `version`. Read asset bytes
// only when installation actually asks for them, preserving local startup latency.
export const EMBEDDED_SKILL_ASSETS: Record<string, Uint8Array> = {};
for (const [relPath, path] of Object.entries(EMBEDDED_SKILL_ASSET_PATHS)) {
let bytes: Uint8Array | undefined;
Object.defineProperty(EMBEDDED_SKILL_ASSETS, relPath, {
enumerable: true,
get: () => bytes ??= readFileSync(path)
});
}
export function getSkillContent(): string {
return EMBEDDED_SKILL_FILES["SKILL.md"] || "";
@@ -44,44 +44,22 @@ describe("CLI semantic errors", () => {
expect(classifyCliError(new Error("Unknown deploy hosecloud action: x"))).toEqual({ exitCode: 2 });
});
test("classifies local config and input-data failures as validation errors (13)", () => {
// Chinese-language usage wording: the message names a flag/parameter to supply.
expect(
classifyCliError(new Error("当前租户存在多个 Webhook 通道 [\"a\" (1)],请通过 --webhook <idOrName> 指定目标通道。"))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。"))).toEqual({ exitCode: 13 });
// Enterprise selection: well-formed command, incomplete local config.
expect(
classifyCliError(new Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>."))
).toEqual({ exitCode: 13 });
expect(classifyCliError(new Error("No enterprise config found for nope"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("rules lint requires an authenticated enterprise. Run 'seal-use corps list' to select one."))
).toEqual({ exitCode: 13 });
// Local file input the caller must fix.
expect(classifyCliError(new Error("File not found: /tmp/missing.json"))).toEqual({ exitCode: 13 });
expect(
classifyCliError(new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象"))
).toEqual({ exitCode: 13 });
// Structural signals that carry no message prefix.
test("classifies structural input failures without matching their wording", () => {
expect(classifyCliError(validationError("请选择目标通道"))).toMatchObject({ exitCode: 13 });
expect(classifyCliError(new SyntaxError("JSON Parse error: Expected '}'"))).toEqual({ exitCode: 13 });
expect(classifyCliError({ issues: [{ path: ["environment"], message: "Invalid option" }] })).toEqual({ exitCode: 13 });
});
test("classifies safety-guard blocks distinctly (14)", () => {
expect(
classifyCliError(new Error("目标企业「生产目标企业」(prod) 标记为生产正式环境 (production)。"))
).toEqual({ exitCode: 14 });
expect(classifyCliError(new Error("重放目标企业「T」(t) 的环境为「production」,非测试环境!"))).toEqual({
exitCode: 14
});
expect(classifyCliError(safetyBlocked("blocked by environment guard", "seal-use webhook replay --force"))).toEqual({
exitCode: 14,
nextAction: "seal-use webhook replay --force"
});
test("safety guards carry their code independently of user-facing text", () => {
expect(classifyCliError(safetyBlocked("blocked by environment guard", "seal-use webhook replay --force")))
.toEqual({ exitCode: 14, nextAction: "seal-use webhook replay --force" });
expect(classifyCliError(safetyBlocked("换一种中文解释"))).toMatchObject({ exitCode: 14 });
});
test("upstream messages containing validation or safety words stay domain failures", () => {
for (const message of ["上游格式错误,请提供工单", "No enterprise config found upstream", "File not found: remote object", "禁止向生产环境传输失败"]) {
expect(classifyCliError(new Error(message))).toEqual({ exitCode: 1 });
}
});
test("validationError helper carries exit 13 with next action", () => {
-28
View File
@@ -54,25 +54,6 @@ export function confirmationRequired(message: string, nextAction: string): CliEr
const USAGE_PREFIX =
/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )*(?:command|action|subcommand|target)|Invalid (?:number|boolean|command)|--json must|Missing required JSON field|Invalid JSON:)/i;
// 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 =
/^(?:Stateless mode is enabled\.|No enterprise config found|.*requires an authenticated enterprise|.*requires an enterprise\.)/;
// Local file input problems that are the caller's responsibility to fix. Exit `13`.
const LOCAL_FILE_INPUT =
/^(?:File not found:|本地规则文件(?: JSON 解析失败|格式错误|包含重复)|未找到本地规则文件|第 \d+ 条规则(?:格式错误|缺少有效的)|ZIP 根目录缺少|起始时间 .* 不能晚于结束时间)/;
// Safety-guard wording: blocked by target environment, not by input shape. Exit `14`.
const SAFETY_GUARD =
/(?:标记为生产正式环境|非测试环境|严禁在生产环境|禁止向生产环境)/;
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
@@ -89,15 +70,6 @@ export function classifyCliError(error: unknown): {
if (USAGE_PREFIX.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
if (SAFETY_GUARD.test(value)) {
return { exitCode: 14 };
}
if (CN_USAGE.test(value) || CORP_SELECTION.test(value) || LOCAL_FILE_INPUT.test(value)) {
return { exitCode: 13 };
}
// Structural validation: a ZodError carries an `issues` array rather than a
// message prefix, so it never matches a text pattern.
if (isValidationIssueList(error)) {
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more