Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0af76f692 | ||
|
|
b2f72959ee | ||
|
|
dd0ca78e5b | ||
|
|
586ad521dc | ||
|
|
75017ab49c | ||
|
|
50414e100a | ||
|
|
4f3fb82856 | ||
|
|
8c7cb219a0 | ||
|
|
d71be55ec8 | ||
|
|
140d7bb33a | ||
|
|
9ef38cda0f | ||
|
|
87b691bd4e | ||
|
|
b3c8e93f0b | ||
|
|
c4a1148cbf | ||
|
|
f788f9c6db | ||
|
|
66673f3878 | ||
|
|
d3659c076c | ||
|
|
2e13b53351 | ||
|
|
59ef8c45db | ||
|
|
7e8b9e6220 | ||
|
|
6a50512c4a | ||
|
|
d3642b93d8 | ||
|
|
9cf3e8ce56 | ||
|
|
90c366ebb2 | ||
|
|
736728496f | ||
|
|
904c9d4b8b | ||
|
|
0efd87a874 | ||
|
|
fb7948307c | ||
|
|
c1a5cc20e9 | ||
|
|
4bee160086 | ||
|
|
fc9e148764 | ||
|
|
fa304ca4dc | ||
|
|
2654e1b870 | ||
|
|
64af86ba9b | ||
|
|
f726c22445 | ||
|
|
c4df5ad325 | ||
|
|
22f4c87ecc | ||
|
|
fa2be3a4e9 | ||
|
|
5a25cd5225 | ||
|
|
67a461452c | ||
|
|
b17bd09194 | ||
|
|
0de2db14ae | ||
|
|
19c8dd3146 | ||
|
|
8c3d98fd98 | ||
|
|
9ece30255e | ||
|
|
8d7f930596 | ||
|
|
6e3d4634f1 | ||
|
|
df44791779 |
No files matched your search
@@ -25,3 +25,20 @@ When modifying or adding TypeScript files in `src/`:
|
|||||||
|
|
||||||
4. **Architecture**:
|
4. **Architecture**:
|
||||||
- Prefer small, cohesive domain functions over large generic utility files.
|
- Prefer small, cohesive domain functions over large generic utility files.
|
||||||
|
- Place Seal business implementations and their colocated tests in the matching
|
||||||
|
feature directory under `src/domains/seal/`, for example `rules/recode.ts`
|
||||||
|
and `rules/recode.test.ts`. The domain root is reserved for `api.ts`,
|
||||||
|
`api.test.ts`, `types.ts`, and `capabilities.ts`; do not add business files
|
||||||
|
or old-path forwarding stubs there. See `AGENTS.md` for the feature layout.
|
||||||
|
|
||||||
|
5. **Frozen Utility Modules**:
|
||||||
|
- `src/domains/seal/capabilities/helpers.ts` is FROZEN: no new exports. It is
|
||||||
|
the historical catch-all (~85 exports, re-exported into every capability's
|
||||||
|
namespace via `export *`), and `helpers.freeze.test.ts` fails CI when it
|
||||||
|
grows past its line/export ceiling.
|
||||||
|
- Put new logic in a focused module beside the domain that owns it. Moving an
|
||||||
|
existing export OUT of `helpers.ts` is encouraged — then lower the ceiling
|
||||||
|
constants in the ratchet test.
|
||||||
|
- Apply the same instinct to any other module you are tempted to treat as a
|
||||||
|
scrap drawer: if the file's name is `helpers`/`utils`/`common`, it is
|
||||||
|
already a sign the logic belongs somewhere more specific.
|
||||||
@@ -118,5 +118,5 @@ jobs:
|
|||||||
path: dist/bin/
|
path: dist/bin/
|
||||||
retention-days: 1
|
retention-days: 1
|
||||||
|
|
||||||
# Gitea asset promotion and Homebrew tap updates are owned by the WSL
|
# Gitea asset promotion is owned by the WSL
|
||||||
# seal-use-release-sync.timer after this GitHub Release is published.
|
# seal-use-release-sync.timer after this GitHub Release is published.
|
||||||
@@ -8,9 +8,11 @@ dist/bin/
|
|||||||
.cache/
|
.cache/
|
||||||
.mimosa/
|
.mimosa/
|
||||||
.apifox/
|
.apifox/
|
||||||
|
tmp/
|
||||||
|
|
||||||
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
||||||
.local/
|
.local/
|
||||||
|
/reports/
|
||||||
|
|
||||||
# Developer-only build-time credentials for compile-time injection — never committed
|
# Developer-only build-time credentials for compile-time injection — never committed
|
||||||
.env.langfuse
|
.env.langfuse
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "seal-use",
|
"name": "seal-use",
|
||||||
"version": "0.11.5",
|
"version": "0.11.6",
|
||||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "yingqing"
|
"name": "yingqing"
|
||||||
|
|||||||
+18
-17
@@ -1,26 +1,27 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
*.log
|
|
||||||
.cache/
|
# Build outputs
|
||||||
tmp/*
|
|
||||||
!tmp/.gitkeep
|
|
||||||
dist/bin/
|
dist/bin/
|
||||||
|
|
||||||
|
# Local runtime caches and system noise (regenerate at any time)
|
||||||
|
.cache/
|
||||||
.mimosa/
|
.mimosa/
|
||||||
|
|
||||||
# Local enterprise configs can contain credentials.
|
|
||||||
enterprises/*.json
|
|
||||||
!enterprises/example.*.json
|
|
||||||
|
|
||||||
# Local generated reports and exported deliverables.
|
|
||||||
.local/
|
|
||||||
.apifox/
|
.apifox/
|
||||||
exports/
|
tmp/
|
||||||
scripts/export-*.ts
|
|
||||||
|
|
||||||
# Local custom linters. Loaded and executed from <cwd>/linters at runtime, so a fresh
|
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
||||||
# clone has none — README.md is tracked to explain the convention, the linters stay private.
|
.local/
|
||||||
linters/*
|
/reports/
|
||||||
!linters/README.md
|
|
||||||
|
# Developer-only build-time credentials for compile-time injection — never committed
|
||||||
|
.env.langfuse
|
||||||
|
|
||||||
|
# ZCode session plan artifacts (workspace-local, never committed)
|
||||||
|
.zcode/plans/
|
||||||
|
|
||||||
|
# One-off export harnesses dropped in scripts/ while exporting
|
||||||
|
scripts/export-*.ts
|
||||||
|
|
||||||
# ===== ↑ 以上同步自 .gitignore(「从 .gitignore 同步」只重写以上部分)=====
|
# ===== ↑ 以上同步自 .gitignore(「从 .gitignore 同步」只重写以上部分)=====
|
||||||
.git/
|
.git/
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP
|
|||||||
|
|
||||||
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
|
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
|
||||||
|
|
||||||
|
Within `src/domains/seal/`, the root contains only shared protocol boundaries (`api.ts`, `api.test.ts`, `types.ts`) and the public capability export (`capabilities.ts`). Business implementations belong in their feature directories: `rules/`, `approval-runs/`, `insight/`, `replay/`, `outbound/`, `enterprise/`, `search/`, and `testing/`; existing `reports/`, `linter/`, `material-pack/`, `doctor/`, and `regression/` retain their own boundaries. Put new Seal implementations and their tests in the matching feature directory (for example `rules/recode.ts` and `rules/recode.test.ts`), rather than adding business files or legacy forwarding stubs to the domain root. The registry-wide tests live in `capabilities/capabilities.test.ts`.
|
||||||
|
|
||||||
Tests are colocated as `*.test.ts` files in `src/`.
|
Tests are colocated as `*.test.ts` files in `src/`.
|
||||||
|
|
||||||
## Build, Test, and Development Commands
|
## Build, Test, and Development Commands
|
||||||
@@ -19,7 +21,7 @@ Tests are colocated as `*.test.ts` files in `src/`.
|
|||||||
- `bun run lint`: lint with `oxlint src` (zero-warning gate; CI fails on warnings).
|
- `bun run lint`: lint with `oxlint src` (zero-warning gate; CI fails on warnings).
|
||||||
- `bun test`: run all colocated Bun tests.
|
- `bun test`: run all colocated Bun tests.
|
||||||
- `bun run bump <version | patch | minor>`: bump version across all manifest and skill files.
|
- `bun run bump <version | patch | minor>`: bump version across all manifest and skill files.
|
||||||
- `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the Mac global command (`/opt/homebrew/bin/seal-use`), and sync the local Agent Skill.
|
- `bun run dev:override`: compile the host binary with Git dev version metadata, macOS sign, atomically override the existing global command found on PATH (falling back to a standalone bin directory), and sync the local Agent Skill.
|
||||||
|
|
||||||
## Coding Style & Naming Conventions
|
## Coding Style & Naming Conventions
|
||||||
|
|
||||||
@@ -102,7 +104,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
|||||||
git push origin refs/tags/vX.Y.Z
|
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.
|
- GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release.
|
||||||
- **Gitea & Homebrew Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea, and updates the Homebrew tap (`wsl-infra/systemd/`).
|
- **Gitea Pull-Based Promotion**: Do not manually push branches or tags to `home` (Gitea). On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls the latest GitHub Release every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), pulls the release and assets from GitHub into Gitea (`wsl-infra/systemd/`).
|
||||||
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
|
- 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
|
## Security & Configuration Tips
|
||||||
|
|||||||
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.11.6] - 2026-10-13
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Merge pull request #230 from yunyingk/mac15/rule-import-renumber
|
||||||
|
- Harden post-write error codes, rules push recovery ledger, and capability param normalization
|
||||||
|
- Merge remote-tracking branch 'origin/main' into mac15/rule-import-renumber
|
||||||
|
- Merge pull request #231 from yunyingk/mac15/venn-chart-4x
|
||||||
|
- Add companion XLSX/CSV report ledgers and unify reviewed accuracy metrics
|
||||||
|
- Organize Seal modules and add guarded rule recoding
|
||||||
|
- Refine report asset naming and include review notes in section 6
|
||||||
|
- Fix Venn chart dynamic rendering and eliminate EEKA mock data across report sections
|
||||||
|
|
||||||
|
|
||||||
## [0.11.5] - 2026-10-10
|
## [0.11.5] - 2026-10-10
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ After installation:
|
|||||||
seal-use version # Check version
|
seal-use version # Check version
|
||||||
seal-use skill install # Install Agent skill to ~/.agents/skills/seal-use
|
seal-use skill install # Install Agent skill to ~/.agents/skills/seal-use
|
||||||
seal-use mcp-config # Print an MCP server snippet (for Cursor / Claude Desktop / Codex)
|
seal-use mcp-config # Print an MCP server snippet (for Cursor / Claude Desktop / Codex)
|
||||||
seal-use update # Self-update (GitHub Releases binary, Homebrew, or source)
|
seal-use update # Self-update (release binary or source checkout)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Source Setup & Development
|
## Source Setup & Development
|
||||||
@@ -62,7 +62,7 @@ npm link
|
|||||||
seal-use version
|
seal-use version
|
||||||
```
|
```
|
||||||
|
|
||||||
`npm link` creates a symlink from `/opt/homebrew/lib/node_modules/seal-use` → your local checkout. The `seal-use` binary on PATH then runs source files directly via bun — **no reinstall needed after editing source code**.
|
`npm link` creates a symlink from the global npm package directory (`npm root -g`) to your local checkout. The `seal-use` binary on PATH then runs source files directly via bun — **no reinstall needed after editing source code**.
|
||||||
|
|
||||||
> ⚠️ **Do NOT use `npm install -g .`** for development. That copies files into the global node_modules directory and the copy becomes stale as soon as you edit the source. Always use `npm link` so edits take effect immediately.
|
> ⚠️ **Do NOT use `npm install -g .`** for development. That copies files into the global node_modules directory and the copy becomes stale as soon as you edit the source. Always use `npm link` so edits take effect immediately.
|
||||||
|
|
||||||
@@ -129,13 +129,13 @@ Update an existing checkout:
|
|||||||
seal-use update
|
seal-use update
|
||||||
```
|
```
|
||||||
|
|
||||||
`seal-use update` adapts to how it was installed: from a source checkout it runs `git pull --ff-only` and refreshes dependencies with `bun install`; a standalone binary downloads the matching GitHub Release asset and replaces itself; a Homebrew install upgrades through `brew upgrade seal-use`.
|
`seal-use update` adapts to how it was installed: from a source checkout it runs `git pull --ff-only` and refreshes dependencies with `bun install`; a standalone binary downloads the matching GitHub Release asset and replaces itself.
|
||||||
|
|
||||||
Because `npm link` makes the global command a symlink into your checkout, **updating the checkout is sufficient** — no reinstall step required. The symlink continues to point to the updated source.
|
Because `npm link` makes the global command a symlink into your checkout, **updating the checkout is sufficient** — no reinstall step required. The symlink continues to point to the updated source.
|
||||||
|
|
||||||
Enterprise configs live only in the global directory `~/.config/seal-use/enterprises` (legacy fallback `~/.config/seal-home/enterprises`); the project tree carries none.
|
Enterprise configs live only in the global directory `~/.config/seal-use/enterprises` (legacy fallback `~/.config/seal-home/enterprises`); the project tree carries none.
|
||||||
|
|
||||||
The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.agents/skills/seal-use` symlink; run `seal-use skill install` (or copy that folder yourself) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`.
|
The canonical plugin skill lives at `skills/seal-use`. There is no in-repo `.agents/skills/seal-use` symlink; run `seal-use skill install` (or `seal-use skill install --dir <target>`) to place it in a Codex skills directory such as `~/.agents/skills/seal-use` when you want Codex to invoke the workflow as `$seal-use`. The installer includes the full embedded manifest, including report references sourced outside that folder; manually copying only the skill folder omits those references.
|
||||||
|
|
||||||
## ZCode Plugin
|
## ZCode Plugin
|
||||||
|
|
||||||
@@ -214,7 +214,7 @@ Most users do not need MCP. The public/shared path is the global `seal-use` CLI.
|
|||||||
|
|
||||||
### One registry, two doors
|
### One registry, two doors
|
||||||
|
|
||||||
All approval/logic lives once in the capability registry under `src/domains/seal/capabilities/` (`src/domains/seal/capabilities.ts` re-exports it). Two surfaces enter the same handlers, each with its own naming:
|
Shared approval behavior lives in the business modules under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` dispatches it (`src/domains/seal/capabilities.ts` re-exports the registry). Two surfaces enter the same handlers, each with its own naming:
|
||||||
|
|
||||||
| Surface | Entry | Naming |
|
| Surface | Entry | Naming |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -240,6 +240,8 @@ Both run the same CLI dispatcher as the global binary, so `config` and `update`
|
|||||||
|
|
||||||
## CLI-First Architecture
|
## CLI-First Architecture
|
||||||
|
|
||||||
|
Seal implementations and their tests are grouped by feature: `src/domains/seal/rules/` owns local rule files, diffs, mappings, version snapshots, recoding and confirmation tickets; `approval-runs/` owns record export and attachments; `insight/` owns insight export; `replay/` owns Webhook/Hose replay and environment guards; `outbound/` owns downstream pushes; `enterprise/` owns Seal onboarding and identity resolution; `search/` owns cross-resource search; and `testing/` owns test-enterprise synchronization. Existing `reports/`, `linter/`, `material-pack/`, `doctor/` and `regression/` stay separate. Only shared API/types and the capability export remain at the domain root.
|
||||||
|
|
||||||
All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the `seal_use` / `seal_use_write` MCP tools passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`.
|
All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the `seal_use` / `seal_use_write` MCP tools passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`.
|
||||||
|
|
||||||
Key CLI command groups:
|
Key CLI command groups:
|
||||||
@@ -256,6 +258,8 @@ For rule list commands, prefer `seal-use rules count --corp <corpId>` or `seal-u
|
|||||||
|
|
||||||
For test tenants that need a clean slate before importing another rule set, use `seal-use rules clear --corp <corpId> --dry-run` first, then `seal-use rules clear --corp <corpId> --yes` to delete the current draft rules and verify the remaining count.
|
For test tenants that need a clean slate before importing another rule set, use `seal-use rules clear --corp <corpId> --dry-run` first, then `seal-use rules clear --corp <corpId> --yes` to delete the current draft rules and verify the remaining count.
|
||||||
|
|
||||||
|
To compact draft rule numbers from `0000`, run `seal-use rules recode --corp <corpId>`. The first call returns an impact preview and an enterprise/environment/draft-bound one-use credential (exit 10), without executing the recode. Inspect the preview, then run the returned `nextCommand` separately; the credential expires after five minutes, and `--yes` cannot bypass it. `--dry-run` only previews. The server determines ordering, and every rule can change number; the verified per-rule mapping is returned after execution. Recode does not publish a version; old rule numbers must be interpreted with their published version. Clearing and test synchronization reset numbering only after verifying an empty draft.
|
||||||
|
|
||||||
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
|
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
|
||||||
|
|
||||||
## Approval Run To Langfuse Bridge
|
## Approval Run To Langfuse Bridge
|
||||||
@@ -330,4 +334,4 @@ bun run bump 0.8.5
|
|||||||
**CI & Promotion Pipeline:**
|
**CI & Promotion Pipeline:**
|
||||||
- GitHub Actions triggers automatically upon pushing a `v*` tag to `origin`;
|
- GitHub Actions triggers automatically upon pushing a `v*` tag to `origin`;
|
||||||
- Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) and publishes them to **[GitHub Releases](https://github.com/yunyingk/seal-use/releases)**;
|
- Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) and publishes them to **[GitHub Releases](https://github.com/yunyingk/seal-use/releases)**;
|
||||||
- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** and the Homebrew tap (`ops/README.md`).
|
- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** (`wsl-infra/README.md`).
|
||||||
+4
-3
@@ -17,10 +17,10 @@ initial response within a few business days — this is a small project, not a s
|
|||||||
|
|
||||||
| Path | Contents | Mode |
|
| Path | Contents | Mode |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `~/.config/seal-use/seal_tokens.json` | Session tokens and derived keys | `0600` |
|
| `~/.config/seal-use/tokens.json` | Session tokens and derived keys | `0600` |
|
||||||
| `~/.config/seal-use/enterprises/*.json` | Per-enterprise Hose app key/password or Seal bearer token | `0600` |
|
| `~/.config/seal-use/enterprises/*.json` | Per-enterprise Hose app key/password or Seal bearer token | `0600` |
|
||||||
| `enterprises/*.json` (working tree) | Same, for enterprises added from a checkout | `0600` |
|
| `enterprises/*.json` (working tree) | Same, for enterprises added from a checkout | `0600` |
|
||||||
| `~/.config/seal-use/usage.json` | Per-enterprise command counts | `0600` |
|
| `~/.cache/seal-use/usage.json` | Per-enterprise command counts | `0600` |
|
||||||
|
|
||||||
The tool writes these `0600`; a config placed by hand can keep the `0o644` default, so
|
The tool writes these `0600`; a config placed by hand can keep the `0o644` default, so
|
||||||
`seal-use doctor` reports any credential file whose mode is wider than `0600`. Real enterprise
|
`seal-use doctor` reports any credential file whose mode is wider than `0600`. Real enterprise
|
||||||
@@ -41,7 +41,8 @@ than described here.
|
|||||||
full API access, so "read-only" is guaranteed only by this client (it exposes `GET` only — see
|
full API access, so "read-only" is guaranteed only by this client (it exposes `GET` only — see
|
||||||
`src/domains/langfuse/client.ts`), and anyone with the binary can extract the key pair. The
|
`src/domains/langfuse/client.ts`), and anyone with the binary can extract the key pair. The
|
||||||
repository and its Releases are private, which is what bounds distribution. Treat Langfuse traces
|
repository and its Releases are private, which is what bounds distribution. Treat Langfuse traces
|
||||||
and `.cache/langfuse/` as sensitive (they can contain enterprise approval data); rotate the key
|
and `~/.cache/seal-use/langfuse/` (plus legacy `.cache/langfuse/` entries) as sensitive
|
||||||
|
(they can contain enterprise approval data); rotate the key
|
||||||
pair in Langfuse and update the four `LANGFUSE_*` repository secrets to re-key.
|
pair in Langfuse and update the four `LANGFUSE_*` repository secrets to re-key.
|
||||||
- **Self-update and the install script do not verify signatures.** `seal-use update` downloads a
|
- **Self-update and the install script do not verify signatures.** `seal-use update` downloads a
|
||||||
release binary and replaces the running executable; `scripts/install.sh` compares
|
release binary and replaces the running executable; `scripts/install.sh` compares
|
||||||
|
|||||||
@@ -9,7 +9,9 @@
|
|||||||
"exceljs": "^4.4.0",
|
"exceljs": "^4.4.0",
|
||||||
"iconv-lite": "^0.7.3",
|
"iconv-lite": "^0.7.3",
|
||||||
"ky": "^2.0.2",
|
"ky": "^2.0.2",
|
||||||
|
"marked": "15.0.12",
|
||||||
"pinyin-pro": "^3.29.3",
|
"pinyin-pro": "^3.29.3",
|
||||||
|
"pngjs": "7.0.0",
|
||||||
"yauzl": "^3.4.0",
|
"yauzl": "^3.4.0",
|
||||||
"zod": "^4.4.3",
|
"zod": "^4.4.3",
|
||||||
},
|
},
|
||||||
@@ -17,6 +19,7 @@
|
|||||||
"@modelcontextprotocol/client": "^2.0.0",
|
"@modelcontextprotocol/client": "^2.0.0",
|
||||||
"@types/archiver": "^8.0.0",
|
"@types/archiver": "^8.0.0",
|
||||||
"@types/bun": "^1.3.14",
|
"@types/bun": "^1.3.14",
|
||||||
|
"@types/pngjs": "6.0.5",
|
||||||
"@types/yauzl": "^3.4.0",
|
"@types/yauzl": "^3.4.0",
|
||||||
"bun-types": "^1.3.14",
|
"bun-types": "^1.3.14",
|
||||||
"oxlint": "1.86.0",
|
"oxlint": "1.86.0",
|
||||||
@@ -80,6 +83,8 @@
|
|||||||
|
|
||||||
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
|
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
|
||||||
|
|
||||||
|
"@types/pngjs": ["@types/pngjs@6.0.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ=="],
|
||||||
|
|
||||||
"@types/readdir-glob": ["@types/readdir-glob@1.1.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg=="],
|
"@types/readdir-glob": ["@types/readdir-glob@1.1.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg=="],
|
||||||
|
|
||||||
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
|
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
|
||||||
@@ -228,6 +233,8 @@
|
|||||||
|
|
||||||
"lodash.uniq": ["lodash.uniq@4.5.0", "", {}, "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ=="],
|
"lodash.uniq": ["lodash.uniq@4.5.0", "", {}, "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ=="],
|
||||||
|
|
||||||
|
"marked": ["marked@15.0.12", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="],
|
||||||
|
|
||||||
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
|
"minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
|
||||||
|
|
||||||
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
|
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
|
||||||
@@ -250,6 +257,8 @@
|
|||||||
|
|
||||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||||
|
|
||||||
|
"pngjs": ["pngjs@7.0.0", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
|
||||||
|
|
||||||
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
|
"process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
|
||||||
|
|
||||||
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
|
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
|
||||||
|
|||||||
+4
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "seal-use",
|
"name": "seal-use",
|
||||||
"version": "0.11.5",
|
"version": "0.11.6",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@@ -43,7 +43,9 @@
|
|||||||
"exceljs": "^4.4.0",
|
"exceljs": "^4.4.0",
|
||||||
"iconv-lite": "^0.7.3",
|
"iconv-lite": "^0.7.3",
|
||||||
"ky": "^2.0.2",
|
"ky": "^2.0.2",
|
||||||
|
"marked": "15.0.12",
|
||||||
"pinyin-pro": "^3.29.3",
|
"pinyin-pro": "^3.29.3",
|
||||||
|
"pngjs": "7.0.0",
|
||||||
"yauzl": "^3.4.0",
|
"yauzl": "^3.4.0",
|
||||||
"zod": "^4.4.3"
|
"zod": "^4.4.3"
|
||||||
},
|
},
|
||||||
@@ -51,6 +53,7 @@
|
|||||||
"@modelcontextprotocol/client": "^2.0.0",
|
"@modelcontextprotocol/client": "^2.0.0",
|
||||||
"@types/archiver": "^8.0.0",
|
"@types/archiver": "^8.0.0",
|
||||||
"@types/bun": "^1.3.14",
|
"@types/bun": "^1.3.14",
|
||||||
|
"@types/pngjs": "6.0.5",
|
||||||
"@types/yauzl": "^3.4.0",
|
"@types/yauzl": "^3.4.0",
|
||||||
"bun-types": "^1.3.14",
|
"bun-types": "^1.3.14",
|
||||||
"oxlint": "1.86.0",
|
"oxlint": "1.86.0",
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
# Report templates
|
|
||||||
|
|
||||||
月度 AI 审核准确率报告的模板与配套资产(供 `seal-use report monthly` 消费)。
|
|
||||||
|
|
||||||
| 文件 | 用途 |
|
|
||||||
| --- | --- |
|
|
||||||
| `monthly.md` | 模板本体。**可变的皮**:章节标题、表格结构允许增删改名——填充逻辑从标题反推数据需求(`src/domains/seal/reports/describe.ts`),改这里通常不用改代码 |
|
|
||||||
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
|
|
||||||
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
|
|
||||||
| `validate.py` / `render.py` | 下游工具:结构校验 + HTML/PNG/PDF 渲染。**不进包**,需要时用 `python3 report-templates/validate.py` 执行 |
|
|
||||||
|
|
||||||
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="400" viewBox="0 0 880 400" font-family="PingFang SC, Hiragino Sans GB, Microsoft YaHei, sans-serif">
|
|
||||||
<rect x="0" y="0" width="880" height="400" fill="#ffffff"/>
|
|
||||||
<g stroke="#eceff3" stroke-width="1">
|
|
||||||
<line x1="110" y1="265" x2="800" y2="265"/>
|
|
||||||
<line x1="110" y1="190" x2="800" y2="190"/>
|
|
||||||
<line x1="110" y1="115" x2="800" y2="115"/>
|
|
||||||
<line x1="110" y1="40" x2="800" y2="40"/>
|
|
||||||
</g>
|
|
||||||
<line x1="110" y1="340" x2="800" y2="340" stroke="#d1d9e0" stroke-width="1.5"/>
|
|
||||||
<g font-size="13" fill="#8b949e" text-anchor="end">
|
|
||||||
<text x="98" y="345">0%</text>
|
|
||||||
<text x="98" y="270">25%</text>
|
|
||||||
<text x="98" y="195">50%</text>
|
|
||||||
<text x="98" y="120">75%</text>
|
|
||||||
<text x="98" y="45">100%</text>
|
|
||||||
</g>
|
|
||||||
<rect x="270" y="63.76" width="150" height="276.24" rx="4" fill="#4c8bf5"/>
|
|
||||||
<rect x="510" y="90.01" width="150" height="249.99" rx="4" fill="#6fbf9a"/>
|
|
||||||
<g font-size="22" font-weight="600" fill="#1f2328" text-anchor="middle">
|
|
||||||
<text x="345" y="54">92.08%</text>
|
|
||||||
<text x="585" y="80">83.33%</text>
|
|
||||||
</g>
|
|
||||||
<g font-size="15" fill="#59636e" text-anchor="middle">
|
|
||||||
<text x="345" y="372">AI 审核</text>
|
|
||||||
<text x="585" y="372">人工审核</text>
|
|
||||||
</g>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 1.2 KiB |
@@ -1,5 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="360" viewBox="0 0 880 360">
|
|
||||||
<rect x="4" y="4" width="872" height="352" rx="10" fill="#f6f8fa" stroke="#c9d1d9" stroke-width="2" stroke-dasharray="8 6"/>
|
|
||||||
<text x="440" y="168" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="22" fill="#8b949e">配图占位:效率、准确度、风险拦截、工作量综合对比</text>
|
|
||||||
<text x="440" y="202" text-anchor="middle" font-family="PingFang SC, Hiragino Sans GB, sans-serif" font-size="14" fill="#adb5bd">实际报告替换为正式图表</text>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 605 B |
@@ -1,270 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""md → 渲染产物三件套:HTML + 全长度 PNG + A4 PDF。
|
|
||||||
|
|
||||||
用法:
|
|
||||||
python3 tools/render.py 模板.md -o build/模板
|
|
||||||
# 产出 build/模板.html、build/模板.png(完整长图,非第一页)、build/模板.pdf(A4 分页)
|
|
||||||
|
|
||||||
PNG 先量出文档真实高度再整页截取;超过单次截取上限时自动分带截取并用 Pillow 拼接。
|
|
||||||
PDF 走 Chrome 打印管线,A4 分页,表头跨页重复、行不跨页截断。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import re
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
from pathlib import Path
|
|
||||||
from urllib.parse import unquote
|
|
||||||
|
|
||||||
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
|
|
||||||
PNG_WIDTH = 1200 # PNG 视口宽度(CSS 像素)
|
|
||||||
PNG_BAND = 14000 # 单次截取的最大高度,超出则分带拼接
|
|
||||||
|
|
||||||
# KaTeX 公式渲染(CDN 引入一次并缓存到本地,此后渲染不依赖网络)
|
|
||||||
KATEX_CSS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css"
|
|
||||||
KATEX_JS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"
|
|
||||||
KATEX_AUTO = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
|
|
||||||
|
|
||||||
CSS = """
|
|
||||||
:root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; }
|
|
||||||
* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
|
||||||
body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg);
|
|
||||||
font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
|
|
||||||
-webkit-font-smoothing:antialiased; }
|
|
||||||
h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); }
|
|
||||||
h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); }
|
|
||||||
h3 { font-size:18px; margin:28px 0 12px; }
|
|
||||||
h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); }
|
|
||||||
p, li { margin:10px 0; }
|
|
||||||
blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head);
|
|
||||||
color:#33404d; border-radius:0 6px 6px 0; }
|
|
||||||
blockquote p { margin:6px 0; }
|
|
||||||
code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px;
|
|
||||||
font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; }
|
|
||||||
pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; }
|
|
||||||
pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; }
|
|
||||||
table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; }
|
|
||||||
th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; }
|
|
||||||
th { background:var(--head); font-weight:600; }
|
|
||||||
tr:nth-child(even) td { background:#fbfcfd; }
|
|
||||||
img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; }
|
|
||||||
em { color:var(--muted); font-size:14px; }
|
|
||||||
hr { border:0; border-top:1px solid var(--line); margin:32px 0; }
|
|
||||||
a { color:#0969da; }
|
|
||||||
.katex-display { margin:18px 0; }
|
|
||||||
@page { size: A4; margin: 14mm 12mm; }
|
|
||||||
@media print {
|
|
||||||
body { max-width:none; padding:0; font-size:12pt; }
|
|
||||||
h2, h3 { page-break-after:avoid; break-after:avoid; }
|
|
||||||
tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; }
|
|
||||||
thead { display:table-header-group; }
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def chrome(args: list[str], timeout: int = 300) -> subprocess.CompletedProcess:
|
|
||||||
return subprocess.run(
|
|
||||||
[CHROME, "--headless", "--disable-gpu", "--hide-scrollbars",
|
|
||||||
"--run-all-compositor-stages-before-draw", *args],
|
|
||||||
capture_output=True, text=True, timeout=timeout,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def doc_title(md: str, fallback: str) -> str:
|
|
||||||
"""标题取自正文 H1;顺带剥掉可能夹在里面的 HTML 注释。"""
|
|
||||||
m = re.search(r"(?m)^#\s+(.+?)\s*$", md)
|
|
||||||
if not m:
|
|
||||||
return fallback
|
|
||||||
return re.sub(r"<!--.*?-->", "", m.group(1), flags=re.S).strip() or fallback
|
|
||||||
|
|
||||||
|
|
||||||
def md_to_html(md: str) -> str:
|
|
||||||
with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as f:
|
|
||||||
f.write(md)
|
|
||||||
tmp = f.name
|
|
||||||
try:
|
|
||||||
res = subprocess.run(["npx", "--yes", "marked@15", "-i", tmp],
|
|
||||||
capture_output=True, text=True, check=True)
|
|
||||||
finally:
|
|
||||||
Path(tmp).unlink(missing_ok=True)
|
|
||||||
return res.stdout
|
|
||||||
|
|
||||||
|
|
||||||
def build_html(src: Path) -> tuple[str, str]:
|
|
||||||
"""渲染出完整 HTML 文本,返回 (html, 标题)。"""
|
|
||||||
text = src.read_text(encoding="utf-8")
|
|
||||||
body = md_to_html(text)
|
|
||||||
base = src.resolve().parent
|
|
||||||
|
|
||||||
# 相对图片路径改为绝对 file:// URI;marked 输出已做一次百分号编码,先 unquote 再转
|
|
||||||
def absolutize(m: re.Match) -> str:
|
|
||||||
s = m.group(1)
|
|
||||||
if s.startswith(("http://", "https://", "file://", "data:")):
|
|
||||||
return m.group(0)
|
|
||||||
return m.group(0).replace(s, (base / unquote(s)).as_uri(), 1)
|
|
||||||
|
|
||||||
body = re.sub(r'<img src="([^"]+)"', absolutize, body)
|
|
||||||
title = doc_title(text, src.stem)
|
|
||||||
|
|
||||||
# $…$ / $$…$$ → KaTeX 显示式;原文中的反斜杠需先转义回渲染器写法
|
|
||||||
has_math = False
|
|
||||||
if "$$" in text or re.search(r"(?<!\\)\$(?!\$)[^$]+?\$(?!\$)", text):
|
|
||||||
has_math = True
|
|
||||||
body = body.replace("<", "<").replace(">", ">").replace("&", "&")
|
|
||||||
|
|
||||||
def _display(m: re.Match) -> str:
|
|
||||||
# KaTeX 把裸 % 当注释符,须转义
|
|
||||||
return "\\(\\displaystyle " + m.group(1).replace("%", "\\%") + " \\)"
|
|
||||||
|
|
||||||
def _inline(m: re.Match) -> str:
|
|
||||||
return "\\(" + m.group(1).replace("%", "\\%") + " \\)"
|
|
||||||
|
|
||||||
body = re.sub(r"\$\$(.+?)\$\$", _display, body, flags=re.S)
|
|
||||||
body = re.sub(r"(?<!\\)\$(?!\$)([^$]+?)\$(?!\$)", _inline, body)
|
|
||||||
|
|
||||||
href_css, _ = local_assets("katex.min.css", KATEX_CSS)
|
|
||||||
js_local = [local_assets(n, u) for n, u in (
|
|
||||||
("katex.min.js", KATEX_JS), ("auto-render.min.js", KATEX_AUTO))]
|
|
||||||
head = (
|
|
||||||
'<!doctype html>\n<html lang="zh-CN">\n<head>\n<meta charset="utf-8">\n'
|
|
||||||
f"<title>{title}</title>\n"
|
|
||||||
f'<link rel="stylesheet" href="{href_css}">\n'
|
|
||||||
f"<style>{CSS}</style>\n</head>\n"
|
|
||||||
)
|
|
||||||
if has_math:
|
|
||||||
init = (
|
|
||||||
"<script>document.addEventListener('DOMContentLoaded',function(){"
|
|
||||||
"renderMathInElement(document.body,{"
|
|
||||||
"delimiters:[{left:'\\\\(',right:'\\\\)',display:false}],"
|
|
||||||
"throwOnError:false});});</script>"
|
|
||||||
)
|
|
||||||
body += "\n" + init
|
|
||||||
scripts = "\n".join(f'<script src="{u}"></script>' for _, u in js_local)
|
|
||||||
body = scripts + "\n" + body
|
|
||||||
html = head + f"<body>\n{body}\n</body>\n</html>\n"
|
|
||||||
return html, title
|
|
||||||
|
|
||||||
|
|
||||||
def local_assets(name: str, url: str) -> tuple[str, str]:
|
|
||||||
"""CDN 资源下载到 .cache/assets 后用本地路径,渲染离线可用;缓存命中不联网。"""
|
|
||||||
d = Path(__file__).resolve().parent.parent / ".cache" / "assets"
|
|
||||||
d.mkdir(parents=True, exist_ok=True)
|
|
||||||
f = d / name
|
|
||||||
if not f.exists() or f.stat().st_size == 0:
|
|
||||||
r = subprocess.run(["curl", "-sSL", "-o", str(f), url], capture_output=True)
|
|
||||||
if not f.exists() or f.stat().st_size == 0:
|
|
||||||
if f.exists():
|
|
||||||
f.unlink()
|
|
||||||
return "", url # 回退 CDN
|
|
||||||
return f.as_uri(), f.as_uri()
|
|
||||||
|
|
||||||
|
|
||||||
def measure_height(html_path: Path) -> int:
|
|
||||||
"""注入测量脚本,用 dump-dom 取文档真实高度(等待全部图片加载完)。"""
|
|
||||||
probe = html_path.with_name("_measure.html")
|
|
||||||
script = ("<script>window.addEventListener('load',function(){"
|
|
||||||
"document.title='PAGEH:'+Math.ceil(document.documentElement.scrollHeight)});"
|
|
||||||
"setTimeout(function(){document.title='PAGEH:'+Math.ceil("
|
|
||||||
"document.documentElement.scrollHeight)},3000)</script>")
|
|
||||||
probe.write_text(html_path.read_text(encoding="utf-8").replace("</body>", script + "</body>"),
|
|
||||||
encoding="utf-8")
|
|
||||||
try:
|
|
||||||
res = chrome(["--virtual-time-budget=30000", "--dump-dom", probe.as_uri()])
|
|
||||||
finally:
|
|
||||||
probe.unlink(missing_ok=True)
|
|
||||||
hits = re.findall(r"PAGEH:(\d+)", res.stdout)
|
|
||||||
if not hits:
|
|
||||||
raise RuntimeError("量取页面高度失败:" + res.stderr[-300:])
|
|
||||||
return int(hits[-1])
|
|
||||||
|
|
||||||
|
|
||||||
def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None:
|
|
||||||
h = measure_height(html_path)
|
|
||||||
uri = html_path.as_uri()
|
|
||||||
if h <= PNG_BAND:
|
|
||||||
chrome([f"--screenshot={png_path}", f"--window-size={width},{h}",
|
|
||||||
"--virtual-time-budget=30000", uri])
|
|
||||||
else:
|
|
||||||
bands: list[Path] = []
|
|
||||||
offset, i = 0, 0
|
|
||||||
while offset < h:
|
|
||||||
bh = min(PNG_BAND, h - offset)
|
|
||||||
band_html = html_path.with_name(f"_band{i}.html")
|
|
||||||
band_html.write_text(
|
|
||||||
html_path.read_text(encoding="utf-8").replace(
|
|
||||||
"</style>", f"body{{margin-top:-{offset}px}}</style>", 1),
|
|
||||||
encoding="utf-8")
|
|
||||||
out = html_path.parent / f"_band{i}.png"
|
|
||||||
chrome([f"--screenshot={out}", f"--window-size={width},{bh}",
|
|
||||||
"--virtual-time-budget=30000", band_html.as_uri()])
|
|
||||||
bands.append(out)
|
|
||||||
band_html.unlink(missing_ok=True)
|
|
||||||
offset += bh
|
|
||||||
i += 1
|
|
||||||
from PIL import Image
|
|
||||||
imgs = [Image.open(b) for b in bands]
|
|
||||||
total = sum(im.height for im in imgs)
|
|
||||||
canvas = Image.new("RGB", (imgs[0].width, total), "white")
|
|
||||||
y = 0
|
|
||||||
for im in imgs:
|
|
||||||
canvas.paste(im, (0, y))
|
|
||||||
y += im.height
|
|
||||||
canvas.save(png_path)
|
|
||||||
for b, im in zip(bands, imgs):
|
|
||||||
b.unlink(missing_ok=True)
|
|
||||||
im.close()
|
|
||||||
|
|
||||||
|
|
||||||
def render_pdf(html_path: Path, pdf_path: Path) -> None:
|
|
||||||
chrome([f"--print-to-pdf={pdf_path}", "--no-pdf-header-footer",
|
|
||||||
"--virtual-time-budget=30000", html_path.as_uri()])
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
ap = argparse.ArgumentParser()
|
|
||||||
ap.add_argument("src")
|
|
||||||
ap.add_argument("-o", "--out", required=True, help="产物路径词干,如 build/模板")
|
|
||||||
ap.add_argument("--width", type=int, default=PNG_WIDTH, help="PNG 视口宽度")
|
|
||||||
a = ap.parse_args()
|
|
||||||
|
|
||||||
src = Path(a.src)
|
|
||||||
stem = Path(a.out).resolve()
|
|
||||||
stem.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
|
|
||||||
html_path = stem.with_suffix(".html")
|
|
||||||
html, _ = build_html(src)
|
|
||||||
html_path.write_text(html, encoding="utf-8")
|
|
||||||
|
|
||||||
png_path = stem.with_suffix(".png")
|
|
||||||
render_png(html_path, png_path, a.width)
|
|
||||||
|
|
||||||
pdf_path = stem.with_suffix(".pdf")
|
|
||||||
render_pdf(html_path, pdf_path)
|
|
||||||
|
|
||||||
for p in (html_path, png_path, pdf_path):
|
|
||||||
size = p.stat().st_size
|
|
||||||
extra = ""
|
|
||||||
if p.suffix == ".png":
|
|
||||||
try:
|
|
||||||
from PIL import Image
|
|
||||||
with Image.open(p) as im:
|
|
||||||
extra = f",{im.width}×{im.height}px"
|
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
if p.suffix == ".pdf":
|
|
||||||
try:
|
|
||||||
import subprocess as sp
|
|
||||||
r = sp.run(["mdls", "-name", "kMDItemNumberOfPages", "-raw", str(p)],
|
|
||||||
capture_output=True, text=True)
|
|
||||||
if r.stdout.strip().isdigit():
|
|
||||||
extra = f",{r.stdout.strip()} 页"
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
print(f" {p} ({size / 1024:.0f} KB{extra})")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
@@ -1,233 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""AI 审核报告结构校验器。
|
|
||||||
|
|
||||||
文档是纯 Markdown(无 frontmatter、无模板标记),校验器只看文档本身:
|
|
||||||
- 结构:标题层级、章节编号、表格列数、代码围栏、必填报告信息、图片可解析
|
|
||||||
- 纯净:不得出现任何模板机制痕迹(slot/@table/{{}}/render:stop/frontmatter)
|
|
||||||
- 数值:总览表求和与占比、小节标题张数、§6 明细与正文、公式算术——全部从正文推导
|
|
||||||
|
|
||||||
用法:
|
|
||||||
python3 tools/validate.py # 校验根目录全部 .md(README 除外)
|
|
||||||
python3 tools/validate.py 某文件.md
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
SECTION_NUMBERS = ["1", "2", "3", "4", "5", "6", "7"]
|
|
||||||
REQUIRED_INFO_ROWS = {"报告编号", "客户名称", "统计期间", "报告状态", "生成日期"}
|
|
||||||
FORBIDDEN_MARKS = [
|
|
||||||
(r"<!--slot:", "slot 标记"),
|
|
||||||
(r"<!--/slot", "slot 闭合"),
|
|
||||||
(r"<!--@", "@table/@block 区域标记"),
|
|
||||||
(r"<!-- render:stop", "render:stop 标记"),
|
|
||||||
(r"\{\{", "{{槽位}}"),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
class Report:
|
|
||||||
def __init__(self, path: Path):
|
|
||||||
self.path = path
|
|
||||||
self.issues: list[tuple[str, str, str]] = []
|
|
||||||
self.n_tables = 0
|
|
||||||
self.n_figs = 0
|
|
||||||
|
|
||||||
def err(self, code: str, msg: str) -> None:
|
|
||||||
self.issues.append(("ERROR", code, msg))
|
|
||||||
|
|
||||||
def warn(self, code: str, msg: str) -> None:
|
|
||||||
self.issues.append(("WARN", code, msg))
|
|
||||||
|
|
||||||
def ok(self) -> bool:
|
|
||||||
return not any(lv == "ERROR" for lv, _, _ in self.issues)
|
|
||||||
|
|
||||||
|
|
||||||
def cells(line: str) -> list[str]:
|
|
||||||
"""按未转义的 | 拆单元格;\\| 视为字面竖线。"""
|
|
||||||
s = line.strip()
|
|
||||||
if s.startswith("|"):
|
|
||||||
s = s[1:]
|
|
||||||
if s.endswith("|") and not s.endswith("\\|"):
|
|
||||||
s = s[:-1]
|
|
||||||
return [p.replace("\\|", "|").strip() for p in re.split(r"(?<!\\)\|", s)]
|
|
||||||
|
|
||||||
|
|
||||||
def is_sep(line: str) -> bool:
|
|
||||||
return line.strip() != "" and "-" in line and set(line.strip()) <= set("|-: ")
|
|
||||||
|
|
||||||
|
|
||||||
def iter_tables(lines: list[str]):
|
|
||||||
i = 0
|
|
||||||
while i < len(lines):
|
|
||||||
if lines[i].startswith("|") and i + 1 < len(lines) and is_sep(lines[i + 1]):
|
|
||||||
header = cells(lines[i])
|
|
||||||
body, j = [], i + 2
|
|
||||||
while j < len(lines) and lines[j].startswith("|"):
|
|
||||||
body.append((j + 1, cells(lines[j])))
|
|
||||||
j += 1
|
|
||||||
yield i + 1, header, body
|
|
||||||
i = j
|
|
||||||
else:
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
|
|
||||||
def table_by_header(lines: list[str], keyword: str) -> dict | None:
|
|
||||||
"""按表头关键词找表,返回 {rows, start, end}(行号 1-based,含表头与分隔行)。"""
|
|
||||||
for lineno, header, rows in iter_tables(lines):
|
|
||||||
if keyword in "".join(header).replace(" ", ""):
|
|
||||||
end = rows[-1][0] if rows else lineno + 1
|
|
||||||
return {"rows": [r for _, r in rows], "start": lineno, "end": end}
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def pct(x: str) -> float | None:
|
|
||||||
m = re.search(r"(\d+(?:\.\d+)?)\s*%", x)
|
|
||||||
return float(m.group(1)) if m else None
|
|
||||||
|
|
||||||
|
|
||||||
def count(x: str) -> float | None:
|
|
||||||
m = re.search(r"(\d+(?:\.\d+)?)", x)
|
|
||||||
return float(m.group(1)) if m else None
|
|
||||||
|
|
||||||
|
|
||||||
def check(path: Path) -> Report:
|
|
||||||
r = Report(path)
|
|
||||||
text = path.read_text(encoding="utf-8")
|
|
||||||
lines = text.split("\n")
|
|
||||||
|
|
||||||
# 1. 纯净性:单层纯 Markdown
|
|
||||||
if text.startswith("---\n"):
|
|
||||||
r.err("FM001", "文件以 YAML frontmatter 开头;元数据请放正文「报告信息」表")
|
|
||||||
for pat, name in FORBIDDEN_MARKS:
|
|
||||||
if re.search(pat, text):
|
|
||||||
r.err("MK001", f"出现模板机制痕迹({name}),模板应是纯 Markdown 文档")
|
|
||||||
|
|
||||||
# 2. 代码围栏
|
|
||||||
fences = [i for i, ln in enumerate(lines, 1) if ln.startswith("```")]
|
|
||||||
if len(fences) % 2:
|
|
||||||
r.err("MD001", f"代码围栏为奇数({len(fences)}),存在未闭合代码块")
|
|
||||||
|
|
||||||
# 3. 表格列数与表头
|
|
||||||
for lineno, header, rows in iter_tables(lines):
|
|
||||||
r.n_tables += 1
|
|
||||||
n = len(header)
|
|
||||||
for rl, row in rows:
|
|
||||||
if len(row) != n:
|
|
||||||
r.err("TB001", f"第 {rl} 行表格列数 {len(row)} ≠ 表头 {n} 列")
|
|
||||||
if any("**" in c for c in header):
|
|
||||||
r.err("TB002", f"第 {lineno} 行表头含加粗标记 **")
|
|
||||||
|
|
||||||
# 4. 标题层级与章节编号
|
|
||||||
prev, seen = 0, []
|
|
||||||
for ln in lines:
|
|
||||||
m = re.match(r"^(#{1,6})\s+(.*)$", ln)
|
|
||||||
if not m:
|
|
||||||
continue
|
|
||||||
lvl = len(m.group(1))
|
|
||||||
if prev and lvl > prev + 1:
|
|
||||||
r.err("HD001", f"标题层级跳级({prev} → {lvl}):{m.group(2)[:40]}")
|
|
||||||
prev = lvl
|
|
||||||
m2 = re.match(r"^(\d+)\.", m.group(2))
|
|
||||||
if lvl == 2 and m2:
|
|
||||||
seen.append(m2.group(1))
|
|
||||||
if seen and seen != SECTION_NUMBERS:
|
|
||||||
r.err("HD002", f"## 章节编号应为 {SECTION_NUMBERS},实际 {seen}")
|
|
||||||
|
|
||||||
# 5. 报告信息表
|
|
||||||
info = table_by_header(lines, "报告信息")
|
|
||||||
if not info:
|
|
||||||
r.err("INFO001", "缺少「报告信息」表")
|
|
||||||
else:
|
|
||||||
keys = {row[0] for row in info["rows"] if row}
|
|
||||||
missing = REQUIRED_INFO_ROWS - keys
|
|
||||||
if missing:
|
|
||||||
r.err("INFO001", f"报告信息表缺少:{', '.join(sorted(missing))}")
|
|
||||||
empty = [row[0] for row in info["rows"] if row and len(row) > 1 and not row[1].strip()]
|
|
||||||
if empty:
|
|
||||||
r.err("INFO002", f"报告信息表以下项为空:{', '.join(empty)}")
|
|
||||||
|
|
||||||
# 6. 图片可解析:http(s) 或存在的本地文件
|
|
||||||
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
|
|
||||||
src = m.group(1).strip()
|
|
||||||
r.n_figs += 1
|
|
||||||
if src.startswith(("http://", "https://")):
|
|
||||||
continue
|
|
||||||
if not (path.parent / src).exists():
|
|
||||||
r.err("IMG001", f"图片不存在:{src}")
|
|
||||||
|
|
||||||
# 7. 数值自洽(全部从正文推导)
|
|
||||||
for tag, kw in (("NM001", "失准类型"), ("NM002", "风险类型")):
|
|
||||||
tb = table_by_header(lines, kw)
|
|
||||||
if not tb:
|
|
||||||
continue
|
|
||||||
rows = tb["rows"]
|
|
||||||
tops = [(c[0], count(c[3])) for c in rows if len(c) > 3 and c[0].startswith("TOP")]
|
|
||||||
totals = [count(c[3]) for c in rows if len(c) > 3 and c[0] in ("合计", "总计", "—")]
|
|
||||||
if tops and totals and all(c is not None for _, c in tops):
|
|
||||||
if sum(c for _, c in tops) != totals[0]:
|
|
||||||
r.err(tag, f"{kw}各维度之和 {sum(c for _, c in tops)} ≠ 合计 {totals[0]}")
|
|
||||||
base = totals[0] if totals else None
|
|
||||||
for c in rows:
|
|
||||||
if len(c) < 4:
|
|
||||||
continue
|
|
||||||
share, cnt = pct(c[2]), count(c[3])
|
|
||||||
if share and cnt and base and c[0].startswith("TOP") and abs(cnt / base * 100 - share) > 0.15:
|
|
||||||
r.err("NM003", f"{kw}「{c[1]}」占比 {share}% ≠ {cnt:.0f}/{base:.0f} = {cnt / base * 100:.1f}%")
|
|
||||||
# 小节标题里的张数与总览表一致
|
|
||||||
for no, cnt in tops:
|
|
||||||
sec = "2" if kw == "失准类型" else "3"
|
|
||||||
m = re.search(r"###\s*%s\.\d+\s*%s[^(]*((\d+)\s*张" % (sec, re.escape(no)), text)
|
|
||||||
if m and cnt is not None and int(m.group(1)) != cnt:
|
|
||||||
r.err(tag, f"{no} 小节标题写 {m.group(1)} 张,总览表写 {cnt:.0f} 张")
|
|
||||||
|
|
||||||
# NM004:§6 明细表的结论分类计数 = 正文数字
|
|
||||||
pr = table_by_header(lines, "原因分类")
|
|
||||||
if pr:
|
|
||||||
d4 = sum(1 for c in pr["rows"] if len(c) > 4 and "依规正确" in c[4])
|
|
||||||
miss = sum(1 for c in pr["rows"] if len(c) > 4 and "失准" in c[4])
|
|
||||||
m = re.search(r"((\d+)\s*/\s*(\d+)\s*笔)", text)
|
|
||||||
m2 = re.search(r"仅有\s*\*{0,2}(\d+)\s*笔", text)
|
|
||||||
if m and int(m.group(1)) != d4:
|
|
||||||
r.err("NM004", f"正文称依规正确 {m.group(1)} 笔,明细表实际 {d4} 行")
|
|
||||||
if m and int(m.group(2)) != len(pr["rows"]):
|
|
||||||
r.err("NM004", f"正文称合计 {m.group(2)} 笔,明细表实际 {len(pr['rows'])} 行")
|
|
||||||
if m2 and int(m2.group(1)) != miss:
|
|
||||||
r.err("NM004", f"正文称 AI 失准 {m2.group(1)} 笔,明细表实际 {miss} 行")
|
|
||||||
|
|
||||||
# NM005:公式算术自洽,且代入值能在正文别处找到
|
|
||||||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
|
||||||
outside = "\n".join(l for l in lines if not l.strip().startswith("$$"))
|
|
||||||
for ln in formula_lines:
|
|
||||||
for frac in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", ln):
|
|
||||||
a, b, p = int(frac.group(1)), int(frac.group(2)), float(frac.group(3))
|
|
||||||
if b and abs(a / b * 100 - p) > 0.05:
|
|
||||||
r.err("NM005", f"公式 {a}/{b} = {p}% 算术不成立(实为 {a / b * 100:.2f}%)")
|
|
||||||
for tok in re.findall(r"\d+(?:\.\d+)?", ln):
|
|
||||||
if tok not in outside:
|
|
||||||
r.err("NM005", f"公式中的数值 {tok} 在正文别处找不到,可能与数据脱节")
|
|
||||||
|
|
||||||
return r
|
|
||||||
|
|
||||||
|
|
||||||
def default_paths() -> list[Path]:
|
|
||||||
"""默认校验根目录全部 .md(README.md 除外)。"""
|
|
||||||
return sorted(p for p in Path(".").glob("*.md") if p.name != "README.md")
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
paths = [Path(a) for a in sys.argv[1:]] or default_paths()
|
|
||||||
failed = False
|
|
||||||
for p in paths:
|
|
||||||
rep = check(p)
|
|
||||||
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
|
|
||||||
for lv, code, msg in rep.issues:
|
|
||||||
print(f" {lv} {code}: {msg}")
|
|
||||||
failed |= not rep.ok()
|
|
||||||
return 1 if failed else 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
+11
-10
@@ -1,7 +1,8 @@
|
|||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
import { readFileSync, writeFileSync } from "node:fs";
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
|
import { homedir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { execSync } from "node:child_process";
|
import { execSync, spawnSync } from "node:child_process";
|
||||||
|
|
||||||
const ROOT = join(import.meta.dirname, "..");
|
const ROOT = join(import.meta.dirname, "..");
|
||||||
const pkgPath = join(ROOT, "package.json");
|
const pkgPath = join(ROOT, "package.json");
|
||||||
@@ -87,14 +88,14 @@ console.log("✓ Updated skills/seal-use/SKILL.md");
|
|||||||
|
|
||||||
|
|
||||||
// 5. Sync to global ~/.agents/skills/seal-use/ if present
|
// 5. Sync to global ~/.agents/skills/seal-use/ if present
|
||||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "seal-use");
|
const globalSkillDir = join(homedir(), ".agents", "skills", "seal-use");
|
||||||
const legacyGlobalSkillDir = join(process.env.HOME || "", ".agents", "skills", "seal-home");
|
const legacyGlobalSkillDir = join(homedir(), ".agents", "skills", "seal-home");
|
||||||
const { existsSync, cpSync, rmSync } = await import("node:fs");
|
if (existsSync(globalSkillDir) || existsSync(legacyGlobalSkillDir)) {
|
||||||
if (existsSync(legacyGlobalSkillDir)) {
|
// A fresh source process reads the bumped skill, including the full embedded resource manifest.
|
||||||
rmSync(legacyGlobalSkillDir, { recursive: true, force: true });
|
const sync = spawnSync(process.execPath, [join(ROOT, "src", "cli.ts"), "skill", "install", "--dir", globalSkillDir], {
|
||||||
}
|
cwd: ROOT, stdio: "inherit", env: { ...process.env, SEAL_DISABLE_BG_UPDATE: "1" }
|
||||||
if (existsSync(globalSkillDir)) {
|
});
|
||||||
cpSync(join(ROOT, "skills", "seal-use"), globalSkillDir, { recursive: true });
|
if (sync.status !== 0) throw new Error(`Failed to sync bumped Agent Skill: ${sync.error || sync.status}`);
|
||||||
console.log("✓ Synchronized ~/.agents/skills/seal-use/");
|
console.log("✓ Synchronized ~/.agents/skills/seal-use/");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+27
-32
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, rmSync } from "node:fs";
|
import { chmodSync, copyFileSync, existsSync, mkdirSync, realpathSync, renameSync, rmSync } from "node:fs";
|
||||||
import { spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { dirname, join, resolve } from "node:path";
|
import { dirname, join, resolve } from "node:path";
|
||||||
@@ -7,14 +7,16 @@ import { fileURLToPath } from "node:url";
|
|||||||
|
|
||||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||||
|
|
||||||
function resolveTargetBinaryPath(): string {
|
export function resolveTargetBinaryPath(): string {
|
||||||
// 1. Check which seal-use
|
// 1. Check which seal-use
|
||||||
try {
|
try {
|
||||||
const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8" });
|
const whichRes = spawnSync("which", ["seal-use"], { encoding: "utf8", env: { ...process.env } });
|
||||||
if (whichRes.status === 0 && whichRes.stdout) {
|
if (whichRes.status === 0 && whichRes.stdout) {
|
||||||
const p = whichRes.stdout.trim();
|
const p = whichRes.stdout.trim();
|
||||||
if (p && existsSync(p)) {
|
if (p && existsSync(p)) {
|
||||||
return p;
|
// Preserve native binary symlinks, but never overwrite an npm-linked source entry.
|
||||||
|
const target = realpathSync(p);
|
||||||
|
return /\.(?:[cm]?[jt]sx?|sh)$/i.test(target) ? p : target;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -23,7 +25,6 @@ function resolveTargetBinaryPath(): string {
|
|||||||
|
|
||||||
// 2. Fallback candidate paths in order of preference
|
// 2. Fallback candidate paths in order of preference
|
||||||
const candidates = [
|
const candidates = [
|
||||||
"/opt/homebrew/bin/seal-use",
|
|
||||||
"/usr/local/bin/seal-use",
|
"/usr/local/bin/seal-use",
|
||||||
join(homedir(), ".local", "bin", "seal-use"),
|
join(homedir(), ".local", "bin", "seal-use"),
|
||||||
join(homedir(), "bin", "seal-use")
|
join(homedir(), "bin", "seal-use")
|
||||||
@@ -97,8 +98,7 @@ async function main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
copyFileSync(tmpTarget, targetPath);
|
renameSync(tmpTarget, targetPath);
|
||||||
chmodSync(targetPath, 0o755);
|
|
||||||
try {
|
try {
|
||||||
rmSync(tmpTarget, { force: true });
|
rmSync(tmpTarget, { force: true });
|
||||||
} catch {
|
} catch {
|
||||||
@@ -106,24 +106,14 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 4. Sync Agent Skill to ~/.agents/skills/seal-use
|
// 4. Sync Agent Skill to ~/.agents/skills/seal-use
|
||||||
const skillSource = join(root, "skills", "seal-use");
|
|
||||||
const skillTarget = join(homedir(), ".agents", "skills", "seal-use");
|
const skillTarget = join(homedir(), ".agents", "skills", "seal-use");
|
||||||
const legacySkill = join(homedir(), ".agents", "skills", "seal-home");
|
// Install the binary's manifest, including references sourced outside skills/seal-use.
|
||||||
if (existsSync(legacySkill)) {
|
// A custom destination avoids changing unrelated agent host settings during development.
|
||||||
try {
|
const skillRes = spawnSync(targetPath, ["skill", "install", "--dir", skillTarget], { encoding: "utf8" });
|
||||||
rmSync(legacySkill, { recursive: true, force: true });
|
if (skillRes.status !== 0) {
|
||||||
} catch {}
|
throw new Error(`[dev:override] Failed to sync agent skill: ${skillRes.stderr || skillRes.error || "unknown error"}`);
|
||||||
}
|
|
||||||
if (existsSync(skillSource)) {
|
|
||||||
try {
|
|
||||||
const { cpSync } = await import("node:fs");
|
|
||||||
mkdirSync(dirname(skillTarget), { recursive: true });
|
|
||||||
cpSync(skillSource, skillTarget, { recursive: true });
|
|
||||||
console.error(`✓ [dev:override] Synced agent skill to ${skillTarget}`);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(`⚠️ [dev:override] Failed to sync agent skill: ${err}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
console.error(`✓ [dev:override] Synced agent skill to ${skillTarget}`);
|
||||||
|
|
||||||
// 5. Restart service daemon if it was previously running
|
// 5. Restart service daemon if it was previously running
|
||||||
if (serviceWasRunning) {
|
if (serviceWasRunning) {
|
||||||
@@ -132,16 +122,21 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 6. Verify and output
|
// 6. Verify and output
|
||||||
console.error("✨ [dev:override] Success! Active global seal-use binary is now updated:");
|
|
||||||
const testRes = spawnSync(targetPath, ["v"], { encoding: "utf8" });
|
const testRes = spawnSync(targetPath, ["v"], { encoding: "utf8" });
|
||||||
if (testRes.status === 0 && testRes.stdout) {
|
if (testRes.status !== 0 || !testRes.stdout) {
|
||||||
process.stdout.write(testRes.stdout);
|
throw new Error(testRes.stderr || "Failed to verify updated binary");
|
||||||
} else {
|
|
||||||
console.error(testRes.stderr || "Failed to verify updated binary");
|
|
||||||
}
|
}
|
||||||
|
const installed = JSON.parse(testRes.stdout);
|
||||||
|
if (installed.name !== "seal-use" || typeof installed.version !== "string") {
|
||||||
|
throw new Error("Updated binary returned an invalid version payload");
|
||||||
|
}
|
||||||
|
console.error("✨ [dev:override] Success! Active global seal-use binary is now updated:");
|
||||||
|
process.stdout.write(testRes.stdout);
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
if (import.meta.main) {
|
||||||
console.error(err);
|
main().catch((err) => {
|
||||||
process.exit(1);
|
console.error(err);
|
||||||
});
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -27,6 +27,15 @@ const files = walk(skillRoot).map((fullPath) => ({
|
|||||||
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
|
kind: textExtensions.has(extname(fullPath).toLowerCase()) ? "text" : "asset"
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// The skill's report reference is owned by the repository too; install it without maintaining a second copy.
|
||||||
|
const reportReadme = resolve(root, "src", "domains", "seal", "reports", "templates", "README.md");
|
||||||
|
files.push({
|
||||||
|
fullPath: reportReadme,
|
||||||
|
relativePath: "references/report-templates.md",
|
||||||
|
importPath: relative(resolve(root, "src", "core"), reportReadme).split("\\").join("/"),
|
||||||
|
kind: "text"
|
||||||
|
});
|
||||||
|
|
||||||
const lines = [
|
const lines = [
|
||||||
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
|
"// Generated by scripts/generate-embedded-skill.mjs. Do not edit manually.",
|
||||||
""
|
""
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
// 生成 src/domains/seal/linter/plaintext.generated.ts:
|
// 生成 src/domains/seal/linter/plaintext.generated.ts:
|
||||||
// 把 manifest 中 plaintext: true 的官方校验器源码嵌入为字符串,
|
// 把 manifest 中 plaintext: true 的官方校验器源码嵌入为字符串,
|
||||||
// 供 syncOfficialLinters 写入 ~/.config/seal-use/linters/official/。
|
// 供 syncOfficialLinters 写入 ~/.cache/seal-use/linters/official/。
|
||||||
// 修改 checkers/ 下任一源码后运行 `bun run generate:linter-plaintext` 刷新。
|
// 修改 checkers/ 下任一源码后运行 `bun run generate:linter-plaintext` 刷新。
|
||||||
import { readFileSync, writeFileSync } from "node:fs";
|
import { readFileSync, writeFileSync } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
|||||||
+12
-6
@@ -44,12 +44,18 @@ TARGET_DIR="${SEAL_USE_INSTALL_DIR:-${SEAL_HOME_INSTALL_DIR:-}}"
|
|||||||
if [ -n "$TARGET_DIR" ]; then
|
if [ -n "$TARGET_DIR" ]; then
|
||||||
mkdir -p "$TARGET_DIR"
|
mkdir -p "$TARGET_DIR"
|
||||||
else
|
else
|
||||||
for candidate in "/opt/homebrew/bin" "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
|
# Reuse an existing command's directory so a second installation does not get shadowed on PATH.
|
||||||
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
EXISTING_COMMAND="$(command -v seal-use || true)"
|
||||||
TARGET_DIR="$candidate"
|
if [ -n "$EXISTING_COMMAND" ] && [ -f "$EXISTING_COMMAND" ] && [ -w "$(dirname "$EXISTING_COMMAND")" ]; then
|
||||||
break
|
TARGET_DIR="$(dirname "$EXISTING_COMMAND")"
|
||||||
fi
|
else
|
||||||
done
|
for candidate in "/usr/local/bin" "$HOME/.local/bin" "$HOME/bin"; do
|
||||||
|
if [ -d "$candidate" ] && [ -w "$candidate" ]; then
|
||||||
|
TARGET_DIR="$candidate"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ -z "$TARGET_DIR" ]; then
|
if [ -z "$TARGET_DIR" ]; then
|
||||||
|
|||||||
+2
-2
@@ -131,7 +131,7 @@ if (isDryRun) {
|
|||||||
console.log(` 4. git commit -m "Release ${tag}: ..."`);
|
console.log(` 4. git commit -m "Release ${tag}: ..."`);
|
||||||
console.log(` 5. git push origin HEAD:refs/heads/${releaseBranch}`);
|
console.log(` 5. git push origin HEAD:refs/heads/${releaseBranch}`);
|
||||||
console.log(` 6. gh pr create && gh pr checks --watch && gh pr merge --merge`);
|
console.log(` 6. gh pr create && gh pr checks --watch && gh pr merge --merge`);
|
||||||
console.log(` 7. 同步 main,打标 ${tag} 并推送到 origin(Gitea 与 Homebrew 由 WSL seal-use-release-sync 主动拉取)`);
|
console.log(` 7. 同步 main,打标 ${tag} 并推送到 origin(Gitea 由 WSL seal-use-release-sync 主动拉取)`);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,6 +229,6 @@ if (success) {
|
|||||||
console.log(`🎉 恭喜!Seal Use ${tag} 已成功发布并触发多平台自动化编译!`);
|
console.log(`🎉 恭喜!Seal Use ${tag} 已成功发布并触发多平台自动化编译!`);
|
||||||
console.log(" • GitHub Actions 构建中心: https://github.com/yunyingk/seal-use/actions");
|
console.log(" • GitHub Actions 构建中心: https://github.com/yunyingk/seal-use/actions");
|
||||||
console.log(` • GitHub Release 页面: https://github.com/yunyingk/seal-use/releases/tag/${tag}`);
|
console.log(` • GitHub Release 页面: https://github.com/yunyingk/seal-use/releases/tag/${tag}`);
|
||||||
console.log(" • Gitea 与 Homebrew Tap 将由 WSL seal-use-release-sync.timer 自动拉取晋升");
|
console.log(" • Gitea 将由 WSL seal-use-release-sync.timer 自动拉取晋升");
|
||||||
console.log("========================================================\n");
|
console.log("========================================================\n");
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
---
|
---
|
||||||
name: seal-use
|
name: seal-use
|
||||||
description: "v0.11.5: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
description: "v0.11.6: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||||
metadata:
|
metadata:
|
||||||
version: 0.11.5
|
version: 0.11.6
|
||||||
short-description: Seal tenant and Hose approval automation (v0.11.5)
|
short-description: Seal tenant and Hose approval automation (v0.11.6)
|
||||||
---
|
---
|
||||||
|
|
||||||
# Seal Use
|
# Seal Use
|
||||||
@@ -63,6 +63,14 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
|||||||
|
|
||||||
生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
|
生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
|
||||||
|
|
||||||
|
## 规则编号重排:两次调用
|
||||||
|
|
||||||
|
`seal-use rules recode --corp <corpId>` 将当前草稿编号从 `0000` 连续编排。具体顺序由服务端决定,新建草稿可能排在已有规则之前;所有规则均可能变号,不能把预览中的编号范围当作逐条映射。第一次只返回影响预览、6 位一次性凭证、到期时间和 `nextCommand`,`executed: false`,退出码为 10;尚未执行重排。核对目标企业和完整影响范围后,另一次调用返回的完整命令才执行;成功返回的 `changes` 是按稳定身份回读验证的真实编号映射。
|
||||||
|
|
||||||
|
凭证绑定企业、环境及草稿状态,5 分钟有效且只能使用一次;`--yes` / `--confirm` 不能替代凭证。`--dry-run` 只预览,不签发凭证。确认码尚未生效时停止连调,不把两阶段写成自动执行脚本;草稿变化或凭证失效时重新预览。执行失败或超时后先回读当前草稿,再决定是否重新申请,不能重用旧码或盲目重跑。
|
||||||
|
|
||||||
|
重排不发布版本。旧编号可能对应不同规则,查看历史记录需指定发布版本。具体预览与返回字段见 `references/rule-lightweight.md`。
|
||||||
|
|
||||||
## 业务术语契约
|
## 业务术语契约
|
||||||
|
|
||||||
对外统一使用以下术语:
|
对外统一使用以下术语:
|
||||||
@@ -93,13 +101,13 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
|
|||||||
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
|
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
|
||||||
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
|
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
|
||||||
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
|
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
|
||||||
| 规则数量、摘要列表、历史规则、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
||||||
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
|
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
|
||||||
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
|
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
|
||||||
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
|
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
|
||||||
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
|
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
|
||||||
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
|
||||||
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 需要结构校验或 PDF 渲染时,再读 `report-templates/README.md` |
|
| 月度审核准确率报告、月报生成、accuracy report | 本文「月度审核准确率报告」一节 | 校验/渲染参数先查 `seal-use report render --help`;CLI 安装的 Skill 另附 `references/report-templates.md` |
|
||||||
|
|
||||||
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
|
||||||
|
|
||||||
@@ -131,14 +139,18 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
|
|||||||
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
|
月度报告一次调用生成,不要手搓 Markdown 表格或串行取数:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
seal-use report monthly --month <YYYY-MM> --corp <corpId>
|
seal-use report monthly --month <YYYY-MM> --corp <corpId> --out reports/报告.md
|
||||||
|
seal-use report validate reports/报告.md
|
||||||
|
seal-use report render reports/报告.md --out build/报告
|
||||||
```
|
```
|
||||||
|
|
||||||
按模板结构(`report-templates/monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
按模板结构(内置 `monthly.md`)自动从效能/风险/审批运行接口取数填充,返回填充后的 Markdown、各章节数据完备度(`sections`)与数据缺口标注(`notes`)。要点:
|
||||||
|
|
||||||
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
|
- **模板是可变的皮**:章节增删改名只要关键词仍命中,取数需求自动跟着走(`src/domains/seal/reports/describe.ts`)。改模板通常不用改代码。
|
||||||
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
- **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。
|
||||||
- 结果里的 `next` 给出下游 `validate` / `render` 指引(校验与 HTML/PNG/PDF 渲染用 `report-templates/validate.py`、`render.py`,不进包)。
|
- 默认模板、配图和校验/渲染引擎由仓库 Git 管理并随二进制内嵌,不依赖当前目录或原模板仓库。`--out` 保存 Markdown 与配图;不传则继续返回 `content`。`--output-file` 保存的是 JSON。
|
||||||
|
- 结果里的 `next` 给出 CLI 校验与导出命令。`report validate` / `report render` 不需企业登录;校验失败返回 issues 和退出码 1,阻止导出。`render` 默认产出 HTML / 全长 PNG / A4 PDF,`--format html|png|pdf` 可选格式。已有文件须显式 `--overwrite` 才允许替换。
|
||||||
|
- 本地运行环境:生成月报、校验与 HTML 导出只需 CLI;PNG/PDF 另需 Chrome/Chromium(可用 `--chrome` 指定)。无需 Python、Pillow、Node 或 npm;`--python` 已移除,传入返回用法错误。Markdown 解析和长图拼接已打包;含公式时首次渲染联网缓存 KaTeX。模板配图仍是示例/占位图,对外使用前检查 `notes` 并替换配图。
|
||||||
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
- 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。
|
||||||
|
|
||||||
### 人工裁决回填(算出人工审核准确率)
|
### 人工裁决回填(算出人工审核准确率)
|
||||||
@@ -153,7 +165,7 @@ seal-use report review set --month <YYYY-MM> --sn <SN> --verdict <ai_correct|hum
|
|||||||
seal-use report review list --month <YYYY-MM> --corp <corpId>
|
seal-use report review list --month <YYYY-MM> --corp <corpId>
|
||||||
```
|
```
|
||||||
|
|
||||||
- **存储**:`~/.config/seal-use/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
|
- **存储**:`~/.config/seal-use/state/reviews/<corpId>-<YYYY-MM>.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。
|
||||||
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
|
- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。
|
||||||
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
|
- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。
|
||||||
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
|
- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。
|
||||||
@@ -50,7 +50,7 @@ If `seal-use langfuse search` does not find Chinese terms reliably, grep the cac
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附件(定额发票)|<file-name-or-fileId>" \
|
rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附件(定额发票)|<file-name-or-fileId>" \
|
||||||
.cache/langfuse/traces/default/<traceId>.json
|
~/.cache/seal-use/langfuse/traces/default/<traceId>.json
|
||||||
```
|
```
|
||||||
|
|
||||||
Read focused IO for the relevant observations.
|
Read focused IO for the relevant observations.
|
||||||
@@ -103,7 +103,7 @@ jq -r '
|
|||||||
or contains("附件中存在定额发票")
|
or contains("附件中存在定额发票")
|
||||||
or contains("检查该附件(定额发票)"))
|
or contains("检查该附件(定额发票)"))
|
||||||
| [.id,.name,.type,.startTime,((.output|tostring)|gsub("\n";" ")|.[0:500])] | @tsv
|
| [.id,.name,.type,.startTime,((.output|tostring)|gsub("\n";" ")|.[0:500])] | @tsv
|
||||||
' .cache/langfuse/traces/default/<traceId>.json
|
' ~/.cache/seal-use/langfuse/traces/default/<traceId>.json
|
||||||
```
|
```
|
||||||
|
|
||||||
Then inspect the earliest matching observation. Typical interpretation:
|
Then inspect the earliest matching observation. Typical interpretation:
|
||||||
@@ -125,7 +125,7 @@ jq -r '
|
|||||||
.trace.observations[] | walkobs(.; 0)
|
.trace.observations[] | walkobs(.; 0)
|
||||||
| select(.name? | test("pre_analysis"))
|
| select(.name? | test("pre_analysis"))
|
||||||
| [.startTime,.id,.name,.type,.parentObservationId,((.input|tostring|length)//0),((.output|tostring|length)//0)] | @tsv
|
| [.startTime,.id,.name,.type,.parentObservationId,((.input|tostring|length)//0),((.output|tostring|length)//0)] | @tsv
|
||||||
' .cache/langfuse/traces/default/<traceId>.json
|
' ~/.cache/seal-use/langfuse/traces/default/<traceId>.json
|
||||||
```
|
```
|
||||||
|
|
||||||
Then inspect its output for the disputed file and rule:
|
Then inspect its output for the disputed file and rule:
|
||||||
@@ -136,7 +136,7 @@ jq -r '
|
|||||||
.trace.observations[] | walkobs(.)
|
.trace.observations[] | walkobs(.)
|
||||||
| select(.name? == "pre_analysis:ai.streamText")
|
| select(.name? == "pre_analysis:ai.streamText")
|
||||||
| .output
|
| .output
|
||||||
' .cache/langfuse/traces/default/<traceId>.json | rg -n "fileId|fileName|<file-name>|付款截图金额|收款金额|金额合计"
|
' ~/.cache/seal-use/langfuse/traces/default/<traceId>.json | rg -n "fileId|fileName|<file-name>|付款截图金额|收款金额|金额合计"
|
||||||
```
|
```
|
||||||
|
|
||||||
Look for these failure patterns:
|
Look for these failure patterns:
|
||||||
|
|||||||
@@ -124,10 +124,10 @@ When diagnosing a bad case or verifying rule fixes, replay the historic run's st
|
|||||||
seal-use webhook replay <recordId> --dry-run --corp <corpId>
|
seal-use webhook replay <recordId> --dry-run --corp <corpId>
|
||||||
|
|
||||||
# 执行重放,生成全新审批实例(支持自动附加单号后缀防重)
|
# 执行重放,生成全新审批实例(支持自动附加单号后缀防重)
|
||||||
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId>
|
seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix '-retest'] --corp <corpId> --yes
|
||||||
|
|
||||||
# 跨企业提取:从生产企业提取单据并推送至测试企业 Webhook 进行回归验证
|
# 跨企业提取:从生产企业提取单据并推送至测试企业 Webhook 进行回归验证
|
||||||
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId>
|
seal-use webhook replay <recordId> --source-corp <prodCorpId> --corp <testCorpId> --yes
|
||||||
```
|
```
|
||||||
|
|
||||||
## Output Discipline
|
## Output Discipline
|
||||||
|
|||||||
@@ -57,7 +57,9 @@ seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|la
|
|||||||
seal-use rules linters [--corp <corpId>]
|
seal-use rules linters [--corp <corpId>]
|
||||||
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
|
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
|
||||||
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
|
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
|
||||||
|
seal-use rules push status [--file <path>] [--corp <corpId>]
|
||||||
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
|
seal-use rules 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 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 list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
|
||||||
seal-use documents get <documentId> [--corp <corpId>]
|
seal-use documents get <documentId> [--corp <corpId>]
|
||||||
@@ -145,15 +147,15 @@ seal-use webhook delete <idOrName> [--yes|--dry-run] [--corp <corpId>]
|
|||||||
seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] [--corp <corpId>]
|
seal-use webhook resource-pack 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 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 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] [--force] [--corp <corpId>]
|
seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--channel webhook|hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--dry-run] [--yes|--confirm] [--force] [--corp <corpId>]
|
||||||
seal-use approval-runs replay --sn <sn> [--channel hose-outbound] [--rejection-num <n>] [--message-id <msgId>] [--flow-id <flowId>] [--target-corp <corpId>] [--dry-run] [--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 requirements [--corp <corpId>]
|
||||||
seal-use deploy hosecloud list [--corp <corpId>]
|
seal-use deploy hosecloud list [--corp <corpId>]
|
||||||
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
||||||
seal-use deploy hosecloud status [--corp <corpId>]
|
seal-use deploy hosecloud status [--corp <corpId>]
|
||||||
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]
|
seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]
|
||||||
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--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] [--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 get [--corp <corpId>]
|
||||||
seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--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 set --default <medium|high> [--dry-run] [--corp <corpId>]
|
||||||
@@ -265,7 +267,7 @@ Test Enterprise Binding, Staging Synchronization & Automated Regression Testing:
|
|||||||
- In the **Production Enterprise**: Rules remain strictly in **draft state** without publishing any live version.
|
- In the **Production Enterprise**: Rules remain strictly in **draft state** without publishing any live version.
|
||||||
- In the **Test Enterprise**: Style preferences (`decisionPreferences`, `thinkingDepthPreference`) are updated to match production, test draft rules are cleared and populated with production draft rules, recoded, and immediately **published as a new official version** in the test tenant (`--version-name <name>`).
|
- In the **Test Enterprise**: Style preferences (`decisionPreferences`, `thinkingDepthPreference`) are updated to match production, test draft rules are cleared and populated with production draft rules, recoded, and immediately **published as a new official version** in the test tenant (`--version-name <name>`).
|
||||||
- **Semantic Version Naming**: Defaults to `Sync from <ProdCorp> [Prod v<N> · #<Iteration>]` tracking production baseline version and test draft iteration without redundant date strings.
|
- **Semantic Version Naming**: Defaults to `Sync from <ProdCorp> [Prod v<N> · #<Iteration>]` tracking production baseline version and test draft iteration without redundant date strings.
|
||||||
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
|
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/state/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
|
||||||
- `--dry-run` previews the full preference diff, version mapping plan, and rule sync plan without sending mutations. Execution requires `--yes`.
|
- `--dry-run` previews the full preference diff, version mapping plan, and rule sync plan without sending mutations. Execution requires `--yes`.
|
||||||
- **Approval Run Replay to Test Enterprise (`corps replay-test`)**:
|
- **Approval Run Replay to Test Enterprise (`corps replay-test`)**:
|
||||||
- Automatically identifies the bound test enterprise for `<prodCorpId>` (or current corp).
|
- Automatically identifies the bound test enterprise for `<prodCorpId>` (or current corp).
|
||||||
@@ -299,10 +301,12 @@ Approval rule maintenance:
|
|||||||
- `seal-use rules version <versionNumber|latest> [--corp <corpId>]`
|
- `seal-use rules version <versionNumber|latest> [--corp <corpId>]`
|
||||||
- `seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
|
- `seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
|
||||||
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
|
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
|
||||||
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: `~/.config/seal-use/linters` and `official/`)
|
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: custom in `~/.config/seal-use/linters` and official in `~/.cache/seal-use/linters/official`)
|
||||||
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
|
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
|
||||||
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
|
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Live execution persists a per-step recovery ledger (`status`: `not_started`, `partial`, `completed`, `uncertain`) and hydrates newly created IDs so an interrupted run can be inspected and resumed without duplicating rules.
|
||||||
|
- `seal-use rules push status [--file <path>] [--corp <corpId>]` (or `--check`) inspects the last push recovery ledger and reconciles remaining diff against the live draft without mutating state.
|
||||||
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
|
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
|
||||||
|
- `seal-use rules recode [--dry-run] --corp <corpId>`: first returns an unexecuted numbering preview and a one-use credential (exit 10). Inspect the preview, then invoke the returned `nextCommand` separately. The credential is enterprise/environment/draft-bound, valid for five minutes, and cannot be replaced by `--yes`/`--confirm`. `--dry-run` only previews (exit 0). Recode does not publish; failed/uncertain executions require a draft read before another request. Do not script both phases into automatic consecutive execution.
|
||||||
- `seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]` (reads local sync rule mapping snapshot)
|
- `seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]` (reads local sync rule mapping snapshot)
|
||||||
|
|
||||||
Rule identity and versioning (Draft by default vs. `--version latest`):
|
Rule identity and versioning (Draft by default vs. `--version latest`):
|
||||||
@@ -346,7 +350,7 @@ Webhook integrations:
|
|||||||
- `seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>` (将线上审核记录打包导出为标准 Webhook 资源包,支持按条数、状态或指定单据 ID 筛选)
|
- `seal-use webhook resource-pack export [--limit <n>] [--status <status>] [--output <file.zip>] [--to-downloads] --corp <corpId>` (将线上审核记录打包导出为标准 Webhook 资源包,支持按条数、状态或指定单据 ID 筛选)
|
||||||
- `seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
|
- `seal-use webhook resource-pack preview <资源包.zip|信息表.xlsx> [--min-file-size <bytes>] [--max-file-size <bytes>] [--allowed-extensions <.pdf,.xlsx,...>] --corp <corpId>`
|
||||||
- `seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>` (别名 `pack`,旧名 `material-pack` 兼容支持)
|
- `seal-use webhook resource-pack push <资源包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>` (别名 `pack`,旧名 `material-pack` 兼容支持)
|
||||||
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持)
|
- `seal-use webhook replay [<recordId>] [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--sn-suffix <str>] [--dry-run] [--yes|--confirm] [--force] [--corp <corpId>]` (通用单据重放:从历史审批单据汲取结构化表单与明细,清洗规范化字段类型,支持单条或批量重放到目标企业的 Webhook 触发审批。实际重放要求 `--yes` 或 `--confirm`;默认阻止向未授权生产环境重放以防污染数据,提供 `--force` 显式覆盖支持)
|
||||||
|
|
||||||
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
|
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.
|
||||||
|
|
||||||
@@ -373,7 +377,7 @@ Approval runs, simulations, and Langfuse bridge:
|
|||||||
Langfuse trace inspection (built-in, read-only, credentials injected at compile time; no `--corp` and no user config required; all verbs are `seal_use` MCP-read-only):
|
Langfuse trace inspection (built-in, read-only, credentials injected at compile time; no `--corp` and no user config required; all verbs are `seal_use` MCP-read-only):
|
||||||
|
|
||||||
- `seal-use langfuse check` verifies connectivity of the embedded read-only credentials (missing credentials → exit 11).
|
- `seal-use langfuse check` verifies connectivity of the embedded read-only credentials (missing credentials → exit 11).
|
||||||
- `seal-use langfuse cache-refresh <traceId>` fetches one full trace into `<cwd>/.cache/langfuse/traces/default/<traceId>.json` (shared format with langfuse-home); other cache-first verbs answer from it and point here (exit 13) when it is missing, unless `--refresh-if-missing`.
|
- `seal-use langfuse cache-refresh <traceId>` fetches one full trace into `~/.cache/seal-use/langfuse/traces/default/<traceId>.json` (shared format with langfuse-home); other cache-first verbs answer from it across working directories and point here (exit 13) when it is missing, unless `--refresh-if-missing`. `SEAL_USE_LANGFUSE_CACHE_DIR` overrides the cache root. Matching legacy cwd caches are copied on first read, preserving their original files and timestamps.
|
||||||
- `seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]` returns the compact observation tree with sizes, usage, cost, and `warnings[]` for >20k-char fields.
|
- `seal-use langfuse outline <traceId> [--include-io-preview] [--max-preview-chars <n>] [--full]` returns the compact observation tree with sizes, usage, cost, and `warnings[]` for >20k-char fields.
|
||||||
- `seal-use langfuse search <traceId> --query <term1,term2>` is the ranked single-trace keyword search (qrep): hierarchy paths, `observationId`, before/match/after context; `--metadata <json>` and `--observation-types` narrow it.
|
- `seal-use langfuse search <traceId> --query <term1,term2>` is the ranked single-trace keyword search (qrep): hierarchy paths, `observationId`, before/match/after context; `--metadata <json>` and `--observation-types` narrow it.
|
||||||
- `seal-use langfuse observation <traceId> <observationId> [--max-chars <n>] [--json-path <path>]` reads focused IO last (middle-truncated to 8000 chars by default, 30000 max, 500000 with `--full`).
|
- `seal-use langfuse observation <traceId> <observationId> [--max-chars <n>] [--json-path <path>]` reads focused IO last (middle-truncated to 8000 chars by default, 30000 max, 500000 with `--full`).
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ seal-use deploy hosecloud list --corp <corpId>
|
|||||||
seal-use deploy hosecloud requirements --corp <corpId>
|
seal-use deploy hosecloud requirements --corp <corpId>
|
||||||
|
|
||||||
# 3. 添加新配置(自动探测平台)
|
# 3. 添加新配置(自动探测平台)
|
||||||
seal-use deploy hosecloud configure --corp <corpId> --json '{
|
seal-use deploy hosecloud configure --corp <corpId> --yes --json '{
|
||||||
"apiKey": "your-app-key",
|
"apiKey": "your-app-key",
|
||||||
"apiSecret": "your-app-secret",
|
"apiSecret": "your-app-secret",
|
||||||
"outboundName": "SealAI 财务审批",
|
"outboundName": "SealAI 财务审批",
|
||||||
@@ -58,7 +58,7 @@ seal-use deploy hosecloud configure --corp <corpId> --json '{
|
|||||||
}'
|
}'
|
||||||
|
|
||||||
# 4. 编辑已有配置(传入原 signKey)
|
# 4. 编辑已有配置(传入原 signKey)
|
||||||
seal-use deploy hosecloud configure --corp <corpId> --json '{
|
seal-use deploy hosecloud configure --corp <corpId> --yes --json '{
|
||||||
"signKey": "<原 signKey>",
|
"signKey": "<原 signKey>",
|
||||||
"apiKey": "your-app-key",
|
"apiKey": "your-app-key",
|
||||||
"apiSecret": "your-app-secret",
|
"apiSecret": "your-app-secret",
|
||||||
@@ -67,11 +67,13 @@ seal-use deploy hosecloud configure --corp <corpId> --json '{
|
|||||||
}'
|
}'
|
||||||
|
|
||||||
# 5. 一键同步发布到合思审批流
|
# 5. 一键同步发布到合思审批流
|
||||||
seal-use deploy hosecloud sync <signKey> --corp <corpId>
|
seal-use deploy hosecloud sync <signKey> --dry-run --corp <corpId>
|
||||||
|
seal-use deploy hosecloud sync <signKey> --yes --corp <corpId>
|
||||||
|
|
||||||
# 5.1 单配置企业一键自动同步 (--auto)
|
# 5.1 单配置企业一键自动同步 (--auto)
|
||||||
# 若企业内仅存在 1 个合思配置卡片,可直接传入 --auto 自动锁定执行,免去查询复制 signKey:
|
# 若企业内仅存在 1 个合思配置卡片,可传入 --auto 自动选择,免去查询复制 signKey;实际同步仍需确认:
|
||||||
seal-use deploy hosecloud sync --auto --corp <corpId>
|
seal-use deploy hosecloud sync --auto --dry-run --corp <corpId>
|
||||||
|
seal-use deploy hosecloud sync --auto --yes --corp <corpId>
|
||||||
|
|
||||||
# 6. 查看单项配置详情(未传 signKey 时自动列出当前企业候选列表与查看命令)
|
# 6. 查看单项配置详情(未传 signKey 时自动列出当前企业候选列表与查看命令)
|
||||||
seal-use deploy hosecloud get [<signKey>] --corp <corpId>
|
seal-use deploy hosecloud get [<signKey>] --corp <corpId>
|
||||||
@@ -79,10 +81,16 @@ seal-use deploy hosecloud get [<signKey>] --corp <corpId>
|
|||||||
# 7. 检查发布与多平台集成状态
|
# 7. 检查发布与多平台集成状态
|
||||||
seal-use deploy hosecloud status --corp <corpId>
|
seal-use deploy hosecloud status --corp <corpId>
|
||||||
|
|
||||||
# 8. 测试/重放出站请求 (要求 assisted 模式,强制中文 nodeId 阻断安全门禁)
|
# 8. 测试/重放出站请求 (要求 assisted 模式,默认使用中文 nodeId 阻断标记)
|
||||||
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--dry-run] --corp <corpId>
|
seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <flowId> --message-id <msgId> [--sn <sn>] [--dry-run] [--yes|--confirm] --corp <corpId>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`configure` 保存 Seal 端集成配置,`sync` 在合思创建或更新出站消息及回调地址;两者实际写入都要求 `--yes` 或 `--confirm`。保存配置前可将示例中的 `--yes` 换成 `--dry-run` 查看脱敏后的前后差异。
|
||||||
|
`sync --dry-run` 只列出待提交的名称、回调地址和模式;`remoteStateKnown: false` 表示未读取合思远端当前配置,不能把预览视为远端现状验证。
|
||||||
|
|
||||||
|
实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。
|
||||||
|
出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. 关键配置参数定义
|
## 4. 关键配置参数定义
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
`seal-use langfuse` 是内建的只读 Langfuse trace 检索域:凭据在编译期注入,最终用户**零配置**,无需 `langfuse-home` 或任何本地 `.env`。命令不需要 `--corp`,MCP `seal_use` 网关全部可达。
|
`seal-use langfuse` 是内建的只读 Langfuse trace 检索域:凭据在编译期注入,最终用户**零配置**,无需 `langfuse-home` 或任何本地 `.env`。命令不需要 `--corp`,MCP `seal_use` 网关全部可达。
|
||||||
|
|
||||||
只读边界:client 只发 `GET`,本地只写 `.cache/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。
|
只读边界:client 只发 `GET`,本地只写用户目录 `~/.cache/seal-use/langfuse/` 缓存。凭据缺失(源码直跑未注入)→ exit 11;Langfuse 401/403 → exit 11;其它上游失败 → exit 1;参数缺失/越界 → exit 13。
|
||||||
|
|
||||||
## IO-last 工作流
|
## IO-last 工作流
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
seal-use langfuse cache-refresh <traceId>
|
seal-use langfuse cache-refresh <traceId>
|
||||||
```
|
```
|
||||||
|
|
||||||
缓存写入 `<cwd>/.cache/langfuse/traces/default/<traceId>.json`(与 langfuse-home 同格式,可共享)。后续命令缺缓存时报 exit 13 并提示补缓存,或加 `--refresh-if-missing` 现场拉取。
|
缓存写入 `~/.cache/seal-use/langfuse/traces/default/<traceId>.json`,换目录后仍可读;可用 `SEAL_USE_LANGFUSE_CACHE_DIR` 显式指定缓存根目录。与 langfuse-home 的 JSON 格式保持兼容:从旧工作目录读取时,会将匹配当前项目的 `<cwd>/.cache/langfuse/traces/default/<traceId>.json` 复制到用户缓存,保留原文件和原缓存时间。后续命令缺缓存时报 exit 13 并提示补缓存,或加 `--refresh-if-missing` 现场拉取。
|
||||||
|
|
||||||
### 2. 读大纲(不打印原始 IO)
|
### 2. 读大纲(不打印原始 IO)
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ seal-use langfuse search <traceId> --query "关键词" --fields input,output --o
|
|||||||
seal-use langfuse search <traceId> --query "关键词" --metadata '{"stage":"review"}'
|
seal-use langfuse search <traceId> --query "关键词" --metadata '{"stage":"review"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" .cache/langfuse/traces/default/<traceId>.json`。
|
返回带 `path` 层级、`observationId`、`context{before,match,after}` 的排序片段。output 命中权重最高,`approval_review`/`审核` 观测加成。中文分词不理想时直接 grep 缓存:`rg -n "<原文>" ~/.cache/seal-use/langfuse/traces/default/<traceId>.json`。
|
||||||
|
|
||||||
### 4. 焦点 observation IO
|
### 4. 焦点 observation IO
|
||||||
|
|
||||||
|
|||||||
@@ -92,6 +92,19 @@ Expected shape:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Recode Draft Rule Numbers
|
||||||
|
|
||||||
|
```bash
|
||||||
|
seal-use rules recode --corp <corpId>
|
||||||
|
seal-use rules recode --dry-run --corp <corpId>
|
||||||
|
```
|
||||||
|
|
||||||
|
The first command returns a preview, a six-character one-use confirmation code, `expiresAt`, and `nextCommand`, with `executed: false` and exit code 10. Inspect the enterprise and full impact scope, then invoke the returned command separately. Preview `changesDiff` shows the existing and resulting number ranges, not a per-rule mapping (`mappingAvailable: false`); every rule can change number. The code is bound to the enterprise, environment and exact draft state, expires in five minutes, and is consumed before the POST. Ordinary `--yes`/`--confirm` cannot bypass this flow. Do not combine both phases into an automatic script.
|
||||||
|
|
||||||
|
`--dry-run` returns only the preview (exit 0) without issuing a code. A successful second call returns `executed: true`, the verified per-rule `changes` (`mappingAvailable: true`), and `nextCode`. Recode starts at `0000`, and the server determines ordering: new drafts may move before existing active rules. It does not publish. A not-yet-active code should not trigger immediate repeated calls. On expiry or draft changes request a fresh preview; on POST failure/timeout, read the current draft before requesting another code. A spent code is never reusable.
|
||||||
|
|
||||||
|
Clearing rules and test synchronization reset the allocation counter only after verifying the draft is empty. If clear leaves any rules behind, it skips automatic recoding and reports a warning.
|
||||||
|
|
||||||
## Output Discipline
|
## Output Discipline
|
||||||
|
|
||||||
If a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports.
|
If a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports.
|
||||||
@@ -58,8 +58,8 @@ seal-use config lint disable
|
|||||||
| 层 | 位置 | 说明 |
|
| 层 | 位置 | 说明 |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| 内置引擎 | 编译进二进制 | 永远可用,`builtin` 即此层 |
|
| 内置引擎 | 编译进二进制 | 永远可用,`builtin` 即此层 |
|
||||||
| 官方明文版 | `~/.config/seal-use/linters/official/` | `syncOfficialLinters` 自动同步,改动会被覆盖;agent 可直接阅读源码理解校验逻辑 |
|
| 官方明文版 | `~/.cache/seal-use/linters/official/` | `syncOfficialLinters` 自动同步,改动会被覆盖;agent 可直接阅读源码理解校验逻辑 |
|
||||||
| 用户自定义 | `~/.config/seal-use/linters/<name>.ts`(全局唯一位置) | 私有脚本,跨项目共用;不再从项目 cwd 读取 |
|
| 用户自定义 | `~/.config/seal-use/linters/<name>.ts`(全局唯一位置) | 私有脚本,跨项目共用;保留在 ~/.config 防止随缓存清理误删 |
|
||||||
|
|
||||||
哪些官方校验器明文下发由 `src/domains/seal/linter/manifest.ts` 的 `plaintext` 标记决定:`true` 的条目源码会被写入 `official/`(源码嵌入物 `plaintext.generated.ts` 由 `bun run generate:linter-plaintext` 从 `linter/checkers/` 生成,改动校验器后必须重跑并提交,CI 的 `verify:linter-plaintext` 会拦截漂移);`false` 的条目只以进程内函数存在、不下发明文。
|
哪些官方校验器明文下发由 `src/domains/seal/linter/manifest.ts` 的 `plaintext` 标记决定:`true` 的条目源码会被写入 `official/`(源码嵌入物 `plaintext.generated.ts` 由 `bun run generate:linter-plaintext` 从 `linter/checkers/` 生成,改动校验器后必须重跑并提交,CI 的 `verify:linter-plaintext` 会拦截漂移);`false` 的条目只以进程内函数存在、不下发明文。
|
||||||
|
|
||||||
@@ -103,7 +103,7 @@ seal-use rules lint --linter hlab --file ./rules.local.json
|
|||||||
|
|
||||||
## Custom TS Linters (Plugin-as-Code)
|
## Custom TS Linters (Plugin-as-Code)
|
||||||
|
|
||||||
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts` or `./linters/<name>.ts`:
|
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts`:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// ~/.config/seal-use/linters/finance-strict.ts
|
// ~/.config/seal-use/linters/finance-strict.ts
|
||||||
|
|||||||
@@ -185,10 +185,10 @@ flowchart TD
|
|||||||
seal-use corps replay-test <prodCorpId> --sn '<单据号>' --confirm
|
seal-use corps replay-test <prodCorpId> --sn '<单据号>' --confirm
|
||||||
|
|
||||||
# 跨企业通用重放
|
# 跨企业通用重放
|
||||||
seal-use webhook replay --limit 5 --status failed --prod-corp <prodCorpId> --test-corp <testCorpId>
|
seal-use webhook replay --limit 5 --status failed --prod-corp <prodCorpId> --test-corp <testCorpId> --yes
|
||||||
|
|
||||||
# 未绑定测试企业 / 明确需要重放到生产企业(必须显式指定 --force 覆盖生产保护拦截)
|
# 未绑定测试企业 / 明确需要重放到生产企业(必须显式指定 --force 覆盖生产保护拦截)
|
||||||
seal-use webhook replay <recordId> --force
|
seal-use webhook replay <recordId> --force --yes
|
||||||
```
|
```
|
||||||
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
|
> **生产环境直接重放说明**:若企业未配置独立测试租户,用户确实需要直接在生产环境重放验证时,系统支持通过 `--force` 显式放行。执行前请确认生产 Webhook 通道的回调地址(若有)不会影响外部下游生产系统。
|
||||||
|
|
||||||
@@ -199,14 +199,15 @@ flowchart TD
|
|||||||
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --dry-run
|
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --dry-run
|
||||||
|
|
||||||
# 正式执行(自动推送到绑定的测试企业,并在测试企业异步生成 AI 审核记录)
|
# 正式执行(自动推送到绑定的测试企业,并在测试企业异步生成 AI 审核记录)
|
||||||
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId>
|
seal-use approval-runs replay --sn <SN> --channel hose-outbound --corp <prodCorpId> --yes
|
||||||
|
|
||||||
# 精准匹配指定驳回重提轮次
|
# 精准匹配指定驳回重提轮次
|
||||||
seal-use approval-runs replay --sn <SN> --channel hose-outbound --rejection-num 1 --corp <prodCorpId>
|
seal-use approval-runs replay --sn <SN> --channel hose-outbound --rejection-num 1 --corp <prodCorpId> --yes
|
||||||
|
|
||||||
# 底层直接推送出站调试消息(仅限 assisted 模式)
|
# 底层直接推送出站调试消息(仅限 assisted 模式)
|
||||||
seal-use deploy hosecloud test-outbound --flow-id <flowId> --message-id <msgId> --corp <testCorpId>
|
seal-use deploy hosecloud test-outbound --flow-id <flowId> --message-id <msgId> --corp <testCorpId> --yes
|
||||||
```
|
```
|
||||||
|
指定 `--rejection-num N` 时只接受第 N 轮出站日志,找不到则报错;按审核记录创建时间推测出站事件时,只接受相差小于 60 秒的记录,不会退回更旧的轮次或日志。
|
||||||
> **专属安全红线契约**:
|
> **专属安全红线契约**:
|
||||||
> 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。
|
> 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。
|
||||||
> 2. **锁死 assisted 模式**:目标测试环境的合思配置必须为 `assisted` 辅助模式,否则直接触发 Exit 14 安全阻断。
|
> 2. **锁死 assisted 模式**:目标测试环境的合思配置必须为 `assisted` 辅助模式,否则直接触发 Exit 14 安全阻断。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import type { createSealClient } from "../../core/http/factory.js";
|
import type { createSealClient } from "../../core/http/factory.js";
|
||||||
import { exportInsightReportToExcel } from "../../domains/seal/insight-export.js";
|
import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js";
|
||||||
import { runCapability } from "../helpers.js";
|
import { runCapability } from "../helpers.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||||
import { outputOptions, printJson } from "../printer.js";
|
import { outputOptions, printJson } from "../printer.js";
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import type { createSealClient } from "../../core/http/factory.js";
|
import type { createSealClient } from "../../core/http/factory.js";
|
||||||
import * as api from "../../domains/seal/api.js";
|
import * as api from "../../domains/seal/api.js";
|
||||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs-export.js";
|
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs/export.js";
|
||||||
import {
|
import {
|
||||||
downloadApprovalRunAttachments,
|
downloadApprovalRunAttachments,
|
||||||
extractApprovalRunAttachments
|
extractApprovalRunAttachments
|
||||||
} from "../../domains/seal/attachments.js";
|
} from "../../domains/seal/approval-runs/attachments.js";
|
||||||
import { runCapability, runCapabilityResult } from "../helpers.js";
|
import { runCapability, runCapabilityResult } from "../helpers.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||||
import { outputOptions, printJson } from "../printer.js";
|
import { outputOptions, printJson } from "../printer.js";
|
||||||
|
|||||||
@@ -355,6 +355,10 @@ describe("corps sync-test", () => {
|
|||||||
expect(createdRules.length).toBe(2);
|
expect(createdRules.length).toBe(2);
|
||||||
expect((createdRules[0]!.body as any).description).toBe("Production Rule A");
|
expect((createdRules[0]!.body as any).description).toBe("Production Rule A");
|
||||||
expect((createdRules[1]!.body as any).description).toBe("Production Rule B");
|
expect((createdRules[1]!.body as any).description).toBe("Production Rule B");
|
||||||
|
const resetIndex = requests.findIndex(r => r.path === "/api/v1/rules/batch-recode");
|
||||||
|
const firstCreateIndex = requests.findIndex(r => r.method === "POST" && r.path === "/api/v1/rules");
|
||||||
|
expect(resetIndex).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(resetIndex).toBeLessThan(firstCreateIndex);
|
||||||
|
|
||||||
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
|
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
|
||||||
expect(publishVersion).toBeDefined();
|
expect(publishVersion).toBeDefined();
|
||||||
@@ -909,6 +913,9 @@ describe("corps replay-test", () => {
|
|||||||
function mockSealSyncRequests(options: {
|
function mockSealSyncRequests(options: {
|
||||||
onMutation?: (method: string, path: string, body?: unknown) => void;
|
onMutation?: (method: string, path: string, body?: unknown) => void;
|
||||||
} = {}) {
|
} = {}) {
|
||||||
|
let remainingTestRules = [
|
||||||
|
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
|
||||||
|
];
|
||||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
const requestUrl = typeof input === "string"
|
const requestUrl = typeof input === "string"
|
||||||
? input
|
? input
|
||||||
@@ -1071,9 +1078,7 @@ function mockSealSyncRequests(options: {
|
|||||||
} else {
|
} else {
|
||||||
return jsonResponse({
|
return jsonResponse({
|
||||||
data: {
|
data: {
|
||||||
rules: [
|
rules: remainingTestRules,
|
||||||
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
|
|
||||||
],
|
|
||||||
hasPendingDeletes: false
|
hasPendingDeletes: false
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -1082,6 +1087,7 @@ function mockSealSyncRequests(options: {
|
|||||||
|
|
||||||
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
|
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
|
||||||
options.onMutation?.("DELETE", url.pathname);
|
options.onMutation?.("DELETE", url.pathname);
|
||||||
|
remainingTestRules = remainingTestRules.filter(rule => rule.id !== url.pathname.split("/").pop());
|
||||||
return jsonResponse({ data: { success: true } });
|
return jsonResponse({ data: { success: true } });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { maskHoseSecurity } from "../../../core/auth/hose.js";
|
import { maskHoseSecurity } from "../../../core/auth/hose.js";
|
||||||
import { scoreAssistLink } from "../../../core/auth/delegate.js";
|
import { scoreAssistLink } from "../../../core/auth/delegate.js";
|
||||||
import { onboardSealBearer } from "../../../domains/seal/onboarding.js";
|
import { onboardSealBearer } from "../../../domains/seal/enterprise/onboarding.js";
|
||||||
import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js";
|
import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js";
|
||||||
import {
|
import {
|
||||||
listHoseStaffs,
|
listHoseStaffs,
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { createSealClient } from "../../../core/http/factory.js";
|
import { createSealClient } from "../../../core/http/factory.js";
|
||||||
import type { CorpConfig } from "../../../core/config/types.js";
|
import type { CorpConfig } from "../../../core/config/types.js";
|
||||||
import { syncTestEnterprise } from "../../../domains/seal/test-sync.js";
|
import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js";
|
||||||
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/webhook-replay.js";
|
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js";
|
||||||
import { selectCorp } from "../../helpers.js";
|
import { selectCorp } from "../../helpers.js";
|
||||||
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
||||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||||
import { outputOptions, printJson } from "../../printer.js";
|
import { outputOptions, printJson } from "../../printer.js";
|
||||||
import type { ParsedArgs } from "../../types.js";
|
import type { ParsedArgs } from "../../types.js";
|
||||||
|
|
||||||
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
|
export { buildTestHosecloudOutboundName } from "../../../domains/seal/testing/sync.js";
|
||||||
|
|
||||||
export async function handleCorpSync(
|
export async function handleCorpSync(
|
||||||
action: string | undefined,
|
action: string | undefined,
|
||||||
@@ -126,7 +126,8 @@ export async function handleCorpSync(
|
|||||||
snSuffix: stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]),
|
snSuffix: stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]),
|
||||||
docIdPrefix: stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]),
|
docIdPrefix: stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]),
|
||||||
docIdSuffix: stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]),
|
docIdSuffix: stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]),
|
||||||
dryRun
|
dryRun,
|
||||||
|
confirm: confirmed
|
||||||
});
|
});
|
||||||
if (dryRun) {
|
if (dryRun) {
|
||||||
console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`);
|
console.error(`[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。`);
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import { afterEach, describe, expect, test } from "bun:test";
|
||||||
|
import type { KyInstance } from "ky";
|
||||||
|
import { CorpConfigSchema } from "../../core/config/types.js";
|
||||||
|
import { parseArgs } from "../parser.js";
|
||||||
|
import { runCapabilityResult } from "../helpers.js";
|
||||||
|
import { handleDeployCommand } from "./deploy.js";
|
||||||
|
|
||||||
|
const originalLog = console.log;
|
||||||
|
const originalError = console.error;
|
||||||
|
afterEach(() => {
|
||||||
|
console.log = originalLog;
|
||||||
|
console.error = originalError;
|
||||||
|
});
|
||||||
|
|
||||||
|
const corp = CorpConfigSchema.parse({
|
||||||
|
id: "deploy-test", name: "Deployment test", environment: "test",
|
||||||
|
seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } },
|
||||||
|
source: { type: "seal", sealUrl: "https://seal.test", token: "mock-token" }
|
||||||
|
});
|
||||||
|
|
||||||
|
const input = {
|
||||||
|
apiKey: "mock-key", apiSecret: "mock-secret", signKey: "sign-key",
|
||||||
|
apiOrigin: "custom", customApiUrl: "https://hose.test", mode: "assisted"
|
||||||
|
};
|
||||||
|
|
||||||
|
function fakeClient(signKeys = ["sign-key"]) {
|
||||||
|
const requests: Array<{ method: string; path: string; json?: unknown }> = [];
|
||||||
|
let config: Record<string, unknown> = {
|
||||||
|
integrations: signKeys.map((signKey) => ({
|
||||||
|
type: "hosecloud", signKey, outboundName: "AI review", mode: "assisted",
|
||||||
|
apiKey: "existing-key", apiSecret: "existing-secret"
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
const client = {
|
||||||
|
get: (path: string) => {
|
||||||
|
requests.push({ method: "GET", path });
|
||||||
|
return { json: async () => ({ data: config }) };
|
||||||
|
},
|
||||||
|
post: (path: string, options: { json: Record<string, unknown> }) => {
|
||||||
|
requests.push({ method: "POST", path, json: options.json });
|
||||||
|
if (path === "api/hosecloud/corporation") {
|
||||||
|
return { json: async () => ({ data: { corporationId: "hose-corp" } }) };
|
||||||
|
}
|
||||||
|
if (path === corp.seal.endpoints.approvalStylePreferences) {
|
||||||
|
config = options.json;
|
||||||
|
return { json: async () => ({ data: config }) };
|
||||||
|
}
|
||||||
|
if (path === "api/hosecloud/outbound-config/sync") {
|
||||||
|
return { json: async () => ({ data: { outboundMessageId: "message" } }) };
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected POST ${path}`);
|
||||||
|
}
|
||||||
|
} as unknown as KyInstance;
|
||||||
|
return { client, requests };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function callDeploy(client: KyInstance, argv: string[]) {
|
||||||
|
const lines: string[] = [];
|
||||||
|
console.log = (line: string) => lines.push(line);
|
||||||
|
console.error = () => {};
|
||||||
|
const args = parseArgs(argv);
|
||||||
|
await handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args);
|
||||||
|
return JSON.parse(lines.join("\n")) as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Hose configure and sync confirmation", () => {
|
||||||
|
test("both execution handlers refuse unconfirmed writes before any network call", async () => {
|
||||||
|
for (const name of ["sealDeployHosecloudConfigure", "sealDeployHosecloudSync"]) {
|
||||||
|
for (const confirm of [undefined, false]) {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
await expect(runCapabilityResult(name, fixture.client, corp, {
|
||||||
|
...(name.endsWith("Configure") ? input : { signKey: "sign-key" }), confirm
|
||||||
|
})).rejects.toMatchObject({ exitCode: 10 });
|
||||||
|
expect(fixture.requests).toHaveLength(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("configure previews a masked diff without persisting credentials or control flags", async () => {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
const preview = await callDeploy(fixture.client, [
|
||||||
|
"deploy", "hosecloud", "configure", "--json", JSON.stringify(input), "--dry-run", "--yes"
|
||||||
|
]);
|
||||||
|
expect(preview.preview).toBe(true);
|
||||||
|
expect(preview.targetUrl).toBe("https://seal.test/api/custom/preferences");
|
||||||
|
expect(JSON.stringify(preview)).not.toContain("mock-secret");
|
||||||
|
expect(JSON.stringify(preview)).not.toContain("existing-secret");
|
||||||
|
expect(fixture.requests.filter((request) => request.method === "POST").map((request) => request.path))
|
||||||
|
.toEqual(["api/hosecloud/corporation"]);
|
||||||
|
const after = (preview.changesDiff as { after: { integrations: Record<string, unknown>[] } }).after;
|
||||||
|
expect(after.integrations[0]?.confirm).toBeUndefined();
|
||||||
|
expect(after.integrations[0]?.dryRun).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("configure honors either CLI confirmation flag and keeps control flags out of saved configuration", async () => {
|
||||||
|
for (const flag of ["--yes", "--confirm"]) {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
await callDeploy(fixture.client, ["deploy", "hosecloud", "configure", "--json", JSON.stringify(input), flag]);
|
||||||
|
const saved = fixture.requests.find((request) => request.path === corp.seal.endpoints.approvalStylePreferences && request.method === "POST");
|
||||||
|
expect(saved).toBeDefined();
|
||||||
|
const integration = (saved!.json as { integrations: Record<string, unknown>[] }).integrations[0]!;
|
||||||
|
expect(integration.apiSecret).toBe("mock-secret");
|
||||||
|
expect(integration.confirm).toBeUndefined();
|
||||||
|
expect(integration.dryRun).toBeUndefined();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a JSON confirm field cannot replace an explicit CLI flag", async () => {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
await expect(callDeploy(fixture.client, [
|
||||||
|
"deploy", "hosecloud", "configure", "--json", JSON.stringify({ ...input, confirm: true })
|
||||||
|
])).rejects.toMatchObject({ exitCode: 10 });
|
||||||
|
expect(fixture.requests).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("legacy credential spellings are normalized and masked in previews", async () => {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
const { apiKey, apiSecret, ...settings } = input;
|
||||||
|
const preview = await callDeploy(fixture.client, [
|
||||||
|
"deploy", "hosecloud", "configure", "--json",
|
||||||
|
JSON.stringify({ ...settings, appKey: apiKey, appSecurity: apiSecret }), "--dry-run"
|
||||||
|
]);
|
||||||
|
expect(JSON.stringify(preview)).not.toContain("mock-secret");
|
||||||
|
const after = (preview.changesDiff as { after: { integrations: Record<string, unknown>[] } }).after;
|
||||||
|
expect(after.integrations[0]?.apiSecret).toBe("***");
|
||||||
|
expect(after.integrations[0]?.appSecurity).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sync preview matches the live request without calling the synchronization endpoint", async () => {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
const preview = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "sign-key", "--dry-run"]);
|
||||||
|
expect(preview.preview).toBe(true);
|
||||||
|
expect(preview.remoteStateKnown).toBe(false);
|
||||||
|
expect(preview.targetUrl).toBe("https://seal.test/api/hosecloud/outbound-config/sync");
|
||||||
|
expect((preview.changesDiff as { before: unknown }).before).toBeNull();
|
||||||
|
expect(fixture.requests.every((request) => request.method === "GET")).toBe(true);
|
||||||
|
expect(fixture.requests[0]?.path).toBe(corp.seal.endpoints.approvalStylePreferences);
|
||||||
|
|
||||||
|
for (const flag of ["--yes", "--confirm"]) {
|
||||||
|
const live = fakeClient();
|
||||||
|
const result = await callDeploy(live.client, ["deploy", "hosecloud", "sync", "sign-key", flag]);
|
||||||
|
expect(result.synced).toBe(true);
|
||||||
|
expect(live.requests.find((request) => request.path === "api/hosecloud/outbound-config/sync")?.json)
|
||||||
|
.toEqual((preview.changesDiff as { after: unknown }).after);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("auto only selects a singleton and never replaces confirmation", async () => {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
await expect(callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "--auto"]))
|
||||||
|
.rejects.toMatchObject({ exitCode: 10 });
|
||||||
|
expect(fixture.requests.every((request) => request.method === "GET")).toBe(true);
|
||||||
|
const preview = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "--auto", "--dry-run"]);
|
||||||
|
expect(preview.preview).toBe(true);
|
||||||
|
const multiple = fakeClient(["first", "second"]);
|
||||||
|
await expect(callDeploy(multiple.client, ["deploy", "hosecloud", "sync", "--auto", "--yes"]))
|
||||||
|
.rejects.toMatchObject({ exitCode: 2 });
|
||||||
|
expect(multiple.requests.every((request) => request.method === "GET")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("either confirmation flag supports singleton selection without a positional signKey", async () => {
|
||||||
|
for (const flag of ["--yes", "--confirm"]) {
|
||||||
|
const fixture = fakeClient();
|
||||||
|
const result = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", flag]);
|
||||||
|
expect(result.synced).toBe(true);
|
||||||
|
expect(fixture.requests[0]?.path).toBe(corp.seal.endpoints.approvalStylePreferences);
|
||||||
|
expect(fixture.requests.filter((request) => request.path === "api/hosecloud/outbound-config/sync")).toHaveLength(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
+21
-16
@@ -6,6 +6,7 @@ import { booleanOption, jsonObject, numberOption, stringOption } from "../parser
|
|||||||
import { outputOptions } from "../printer.js";
|
import { outputOptions } from "../printer.js";
|
||||||
import type { ParsedArgs } from "../types.js";
|
import type { ParsedArgs } from "../types.js";
|
||||||
import * as api from "../../domains/seal/api.js";
|
import * as api from "../../domains/seal/api.js";
|
||||||
|
import { listHoseIntegrations } from "../../domains/seal/outbound/push.js";
|
||||||
import { CliError } from "../errors.js";
|
import { CliError } from "../errors.js";
|
||||||
|
|
||||||
export async function handleDeployCommand(
|
export async function handleDeployCommand(
|
||||||
@@ -68,7 +69,7 @@ export async function handleDeployCommand(
|
|||||||
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
||||||
if (!signKey) {
|
if (!signKey) {
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
const config = await api.getApprovalStylePreferences(client);
|
||||||
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
const hoseConfigs = listHoseIntegrations(config);
|
||||||
if (hoseConfigs.length === 0) {
|
if (hoseConfigs.length === 0) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
|
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
|
||||||
@@ -78,9 +79,9 @@ export async function handleDeployCommand(
|
|||||||
console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${corp.id}]\n`);
|
console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${corp.id}]\n`);
|
||||||
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
|
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
|
||||||
for (const item of hoseConfigs) {
|
for (const item of hoseConfigs) {
|
||||||
const name = (item as any).outboundName ?? "SealAI 审批";
|
const name = item.outboundName ?? "SealAI 审批";
|
||||||
const key = item.signKey;
|
const key = item.signKey;
|
||||||
const origin = (item as any).apiOrigin ?? "production";
|
const origin = item.apiOrigin ?? "production";
|
||||||
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
|
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
|
||||||
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
|
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
|
||||||
}
|
}
|
||||||
@@ -111,18 +112,21 @@ export async function handleDeployCommand(
|
|||||||
}
|
}
|
||||||
await runCapability("sealDeployHosecloudConfigure", client, corp, {
|
await runCapability("sealDeployHosecloudConfigure", client, corp, {
|
||||||
...payload,
|
...payload,
|
||||||
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"])
|
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
|
||||||
|
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
|
||||||
}, outputOptions(args.options));
|
}, outputOptions(args.options));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (action === "sync") {
|
if (action === "sync") {
|
||||||
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
|
||||||
const autoOpt = booleanOption(args.options.auto) ?? booleanOption(args.options.yes);
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||||
|
const confirm = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
||||||
|
const autoOpt = booleanOption(args.options.auto) ?? confirm;
|
||||||
|
|
||||||
if (!signKey) {
|
if (!signKey) {
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
const config = await api.getApprovalStylePreferences(client, corp.seal.endpoints.approvalStylePreferences);
|
||||||
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
const hoseConfigs = listHoseIntegrations(config);
|
||||||
|
|
||||||
if (hoseConfigs.length === 0) {
|
if (hoseConfigs.length === 0) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -135,34 +139,34 @@ export async function handleDeployCommand(
|
|||||||
if (firstHose && hoseConfigs.length === 1 && autoOpt) {
|
if (firstHose && hoseConfigs.length === 1 && autoOpt) {
|
||||||
const singleKey = firstHose.signKey;
|
const singleKey = firstHose.signKey;
|
||||||
console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${singleKey})`);
|
console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${singleKey})`);
|
||||||
await runCapability("sealDeployHosecloudSync", client, corp, { signKey: singleKey }, outputOptions(args.options));
|
await runCapability("sealDeployHosecloudSync", client, corp, { signKey: singleKey, dryRun, confirm }, outputOptions(args.options));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${corp.id}]\n`);
|
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--dry-run] [--yes|--confirm] [--corp ${corp.id}]\n`);
|
||||||
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
|
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
|
||||||
for (const item of hoseConfigs) {
|
for (const item of hoseConfigs) {
|
||||||
const name = (item as any).outboundName ?? "SealAI 审批";
|
const name = item.outboundName ?? "SealAI 审批";
|
||||||
const key = item.signKey;
|
const key = item.signKey;
|
||||||
const origin = (item as any).apiOrigin ?? "production";
|
const origin = item.apiOrigin ?? "production";
|
||||||
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
|
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
|
||||||
console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`);
|
console.error(` 👉 同步预览: seal-use deploy hosecloud sync ${key} --dry-run --corp ${corp.id}\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hoseConfigs.length === 1) {
|
if (hoseConfigs.length === 1) {
|
||||||
console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`);
|
console.error(`💡 提示:若希望自动选择单配置,可使用:seal-use deploy hosecloud sync --auto --dry-run --corp ${corp.id}\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new CliError(
|
throw new CliError(
|
||||||
"缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",
|
"缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",
|
||||||
2,
|
2,
|
||||||
hoseConfigs.length === 1
|
hoseConfigs.length === 1
|
||||||
? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --corp ${corp.id}`
|
? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --dry-run --corp ${corp.id}`
|
||||||
: undefined
|
: undefined
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await runCapability("sealDeployHosecloudSync", client, corp, { signKey }, outputOptions(args.options));
|
await runCapability("sealDeployHosecloudSync", client, corp, { signKey, dryRun, confirm }, outputOptions(args.options));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,7 +192,8 @@ export async function handleDeployCommand(
|
|||||||
nodeId,
|
nodeId,
|
||||||
rejectionNum,
|
rejectionNum,
|
||||||
corporationId,
|
corporationId,
|
||||||
dryRun
|
dryRun,
|
||||||
|
confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true
|
||||||
},
|
},
|
||||||
outputOptions(args.options)
|
outputOptions(args.options)
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,11 +1,51 @@
|
|||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import type { createSealClient } from "../../core/http/factory.js";
|
import type { createSealClient } from "../../core/http/factory.js";
|
||||||
import { runCapability } from "../helpers.js";
|
import { runCapabilityResult } from "../helpers.js";
|
||||||
import { numberOption, stringOption } from "../parser.js";
|
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||||
import { outputOptions, printJson } from "../printer.js";
|
import { outputOptions, printJson } from "../printer.js";
|
||||||
import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js";
|
import { CliError, usageError } from "../../core/errors.js";
|
||||||
|
import {
|
||||||
|
exportReportPackage,
|
||||||
|
renderReportFile,
|
||||||
|
saveReportMarkdown,
|
||||||
|
validateReportFile,
|
||||||
|
loadReviews,
|
||||||
|
reviewFilePath,
|
||||||
|
writeReview,
|
||||||
|
type MonthlyReportResult
|
||||||
|
} from "../../domains/seal/reports/index.js";
|
||||||
import type { ParsedArgs } from "../types.js";
|
import type { ParsedArgs } from "../types.js";
|
||||||
|
|
||||||
|
/** Tenant-free commands: dispatch these before resolving enterprise configuration or authentication. */
|
||||||
|
export async function handleLocalReportCommand(action: "validate" | "render" | "export", args: ParsedArgs) {
|
||||||
|
const file = args.command[2] ?? stringOption(args.options.file);
|
||||||
|
if (!file) throw usageError(`Usage: seal-use report ${action} <报告文件.md>${action === "render" ? " --out <产物路径词干>" : action === "export" ? " --out <目标文件夹>" : ""}`);
|
||||||
|
if ("python" in args.options) throw usageError("报告工具已移除 Python 依赖,请去掉 --python 参数。");
|
||||||
|
if (action === "validate") {
|
||||||
|
const result = await validateReportFile(file);
|
||||||
|
printJson(result, outputOptions(args.options));
|
||||||
|
if (!result.valid) throw new CliError("报告校验未通过,请按 issues 修正后重试。", 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||||
|
if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`);
|
||||||
|
if (action === "export") {
|
||||||
|
const result = await exportReportPackage(file, {
|
||||||
|
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
||||||
|
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
|
||||||
|
});
|
||||||
|
printJson(result, outputOptions(args.options));
|
||||||
|
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await renderReportFile(file, {
|
||||||
|
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
|
||||||
|
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
|
||||||
|
});
|
||||||
|
printJson(result, outputOptions(args.options));
|
||||||
|
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
|
||||||
|
}
|
||||||
|
|
||||||
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
|
/** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */
|
||||||
export async function handleReportCommand(
|
export async function handleReportCommand(
|
||||||
action: string | undefined,
|
action: string | undefined,
|
||||||
@@ -18,7 +58,7 @@ export async function handleReportCommand(
|
|||||||
if (!month) {
|
if (!month) {
|
||||||
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
|
throw new Error("Usage: seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--corp <corpId>]");
|
||||||
}
|
}
|
||||||
await runCapability(
|
const result = await runCapabilityResult(
|
||||||
"sealReportMonthlyGet",
|
"sealReportMonthlyGet",
|
||||||
client,
|
client,
|
||||||
corp,
|
corp,
|
||||||
@@ -27,9 +67,24 @@ export async function handleReportCommand(
|
|||||||
templatePath: stringOption(args.options.template),
|
templatePath: stringOption(args.options.template),
|
||||||
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
|
reportId: stringOption(args.options["report-id"]) ?? stringOption(args.options.reportId),
|
||||||
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
maxRuns: numberOption(args.options["max-runs"]) ?? numberOption(args.options.maxRuns)
|
||||||
},
|
}
|
||||||
outputOptions(args.options)
|
) as MonthlyReportResult;
|
||||||
);
|
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
|
||||||
|
if (out) {
|
||||||
|
const saved = saveReportMarkdown(
|
||||||
|
result.content,
|
||||||
|
result.templatePath,
|
||||||
|
out,
|
||||||
|
booleanOption(args.options.overwrite),
|
||||||
|
result.dynamicAssets,
|
||||||
|
result.companionFiles
|
||||||
|
);
|
||||||
|
const quotedFile = `'${saved.file.replace(/'/g, "'\\''")}'`;
|
||||||
|
printJson({ ...result, content: undefined, dynamicAssets: undefined, companionFiles: undefined, ...saved, next: {
|
||||||
|
validate: `seal-use report validate ${quotedFile}`,
|
||||||
|
render: `seal-use report render ${quotedFile} --out build/report`
|
||||||
|
} }, outputOptions(args.options));
|
||||||
|
} else printJson({ ...result, dynamicAssets: undefined, companionFiles: undefined }, outputOptions(args.options));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { expect, test } from "bun:test"
|
||||||
|
import { Client, InMemoryTransport } from "@modelcontextprotocol/client"
|
||||||
|
import { randomBytes } from "node:crypto"
|
||||||
|
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||||
|
import { tmpdir } from "node:os"
|
||||||
|
import { join } from "node:path"
|
||||||
|
import { createServer, SEAL_USE_MCP_TOOL_NAME, SEAL_USE_MCP_WRITE_TOOL_NAME } from "../../server.js"
|
||||||
|
|
||||||
|
test("separate CLI processes share one-use tickets and MCP retains the first-phase JSON preview", async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "seal-recode-cli-"))
|
||||||
|
const corpId = `recode-${randomBytes(4).toString("hex")}`
|
||||||
|
let posts = 0
|
||||||
|
const rules = [
|
||||||
|
{ id: "a", tenantId: "tenant", code: 0, description: "First", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" },
|
||||||
|
{ id: "b", tenantId: "tenant", code: 2, description: "Second", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" }
|
||||||
|
]
|
||||||
|
const upstream = Bun.serve({
|
||||||
|
hostname: "127.0.0.1", port: 0,
|
||||||
|
fetch(request) {
|
||||||
|
const path = new URL(request.url).pathname
|
||||||
|
if (path === "/api/v1/rules" && request.method === "GET") {
|
||||||
|
return Response.json({ data: { rules, hasPendingDeletes: false } })
|
||||||
|
}
|
||||||
|
if (path === "/api/v1/auth/me") {
|
||||||
|
return Response.json({ data: { user: { id: "operator", tenantId: "tenant", name: "Operator" }, tenant: { id: "tenant", name: "Test" } } })
|
||||||
|
}
|
||||||
|
if (path === "/api/v1/rules/batch-recode" && request.method === "POST") {
|
||||||
|
posts++
|
||||||
|
rules.forEach((rule, index) => { rule.code = index })
|
||||||
|
return Response.json({ data: { activeRules: 2, pendingDeleteRules: 0, nextCode: 2 } })
|
||||||
|
}
|
||||||
|
return Response.json({ error: "Unexpected request" }, { status: 404 })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const enterprises = join(dir, "enterprises")
|
||||||
|
const store = join(dir, "tickets.sqlite")
|
||||||
|
mkdirSync(enterprises)
|
||||||
|
const url = `http://127.0.0.1:${upstream.port}`
|
||||||
|
writeFileSync(join(enterprises, "corp.json"), JSON.stringify({
|
||||||
|
id: corpId, name: "CLI Test", environment: "test",
|
||||||
|
seal: { url }, source: { type: "seal", token: "test-token", sealUrl: url }
|
||||||
|
}))
|
||||||
|
writeFileSync(join(dir, "config.json"), JSON.stringify({ stateful: false }))
|
||||||
|
const env = {
|
||||||
|
SEAL_USE_ENTERPRISES_DIR: enterprises,
|
||||||
|
SEAL_USE_CONFIG_FILE: join(dir, "config.json"),
|
||||||
|
SEAL_USE_TOKEN_STORE: join(dir, "tokens.json"),
|
||||||
|
SEAL_USE_USAGE_FILE: join(dir, "usage.json"),
|
||||||
|
SEAL_USE_RECODE_STORE: store,
|
||||||
|
SEAL_DISABLE_BG_UPDATE: "1"
|
||||||
|
}
|
||||||
|
const previous = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]]))
|
||||||
|
const server = createServer({ enableCli: true })
|
||||||
|
const client = new Client({ name: "recode-preview-test", version: "1.0.0" })
|
||||||
|
const run = async (args: string[]) => {
|
||||||
|
const child = Bun.spawn([process.execPath, join(import.meta.dirname, "../../cli.ts"), "rules", "recode", "--corp", corpId, ...args], {
|
||||||
|
env: { ...process.env, ...env }, stdout: "pipe", stderr: "pipe"
|
||||||
|
})
|
||||||
|
const [stdout, stderr, exitCode] = await Promise.all([
|
||||||
|
new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited
|
||||||
|
])
|
||||||
|
return { stdout, stderr, exitCode }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const dry = await run(["--dry-run"])
|
||||||
|
expect(dry.exitCode).toBe(0)
|
||||||
|
expect(JSON.parse(dry.stdout).executed).toBe(false)
|
||||||
|
expect(existsSync(store)).toBe(false)
|
||||||
|
const first = await run(["--yes"])
|
||||||
|
expect(first.exitCode).toBe(10)
|
||||||
|
const preview = JSON.parse(first.stdout)
|
||||||
|
expect(preview).toMatchObject({ phase: "confirmation_required", executed: false, impactCount: 2, mappingAvailable: false })
|
||||||
|
expect(first.stderr).toContain(preview.nextCommand)
|
||||||
|
expect(posts).toBe(0)
|
||||||
|
await Bun.sleep(510)
|
||||||
|
const competed = await Promise.all([run(["--confirm-code", preview.confirmCode]), run(["--confirmCode", preview.confirmCode])])
|
||||||
|
expect(competed.map(result => result.exitCode).sort()).toEqual([0, 10])
|
||||||
|
const executed = JSON.parse(competed.find(result => result.exitCode === 0)!.stdout)
|
||||||
|
expect(executed).toMatchObject({ executed: true, nextCode: 2 })
|
||||||
|
expect(executed.changes).toEqual([{ beforeCode: "0000", afterCode: "0000" }, { beforeCode: "0002", afterCode: "0001" }])
|
||||||
|
expect(posts).toBe(1)
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(env)) process.env[key] = value
|
||||||
|
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
|
||||||
|
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)])
|
||||||
|
const denied = await client.callTool({ name: SEAL_USE_MCP_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } })
|
||||||
|
expect(denied.isError).toBe(true)
|
||||||
|
const result = await client.callTool({ name: SEAL_USE_MCP_WRITE_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } })
|
||||||
|
expect(result.isError).toBe(true)
|
||||||
|
const content = result.content as Array<{ type: "text"; text: string }>
|
||||||
|
expect(JSON.parse(content[0]!.text)).toMatchObject({ executed: false, phase: "confirmation_required" })
|
||||||
|
expect(content[1]!.text).toContain("nextCommand")
|
||||||
|
expect(posts).toBe(1)
|
||||||
|
} finally {
|
||||||
|
await Promise.allSettled([client.close(), server.close()])
|
||||||
|
upstream.stop(true)
|
||||||
|
for (const [key, value] of Object.entries(previous)) {
|
||||||
|
if (value === undefined) delete process.env[key]
|
||||||
|
else process.env[key] = value
|
||||||
|
}
|
||||||
|
rmSync(dir, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
})
|
||||||
+53
-13
@@ -1,7 +1,8 @@
|
|||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import type { createSealClient } from "../../core/http/factory.js";
|
import type { createSealClient } from "../../core/http/factory.js";
|
||||||
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js";
|
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rules/mapping.js";
|
||||||
|
import { RulePushExecutionError } from "../../domains/seal/rules/push.js";
|
||||||
import {
|
import {
|
||||||
listAvailableLinters,
|
listAvailableLinters,
|
||||||
PRIMARY_LINTERS_DIR,
|
PRIMARY_LINTERS_DIR,
|
||||||
@@ -66,6 +67,18 @@ export async function handleRulesCommand(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (action === "recode") {
|
||||||
|
const result = await runCapabilityResult("sealApprovalRulesRecode", client!, corp, {
|
||||||
|
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
|
||||||
|
confirmCode: stringOption(args.options.confirmCode) ?? stringOption(args.options["confirm-code"])
|
||||||
|
}) as { phase: string; nextCommand?: string };
|
||||||
|
printJson(result, outputOptions(args.options));
|
||||||
|
if (result.phase === "confirmation_required") {
|
||||||
|
throw confirmationRequired("尚未执行规则重排。请核对预览后运行返回的 nextCommand。", result.nextCommand!);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (action === "list") {
|
if (action === "list") {
|
||||||
const version = resolveVersionOption(args);
|
const version = resolveVersionOption(args);
|
||||||
if (booleanOption(args.options.count)) {
|
if (booleanOption(args.options.count)) {
|
||||||
@@ -326,7 +339,26 @@ export async function handleRulesCommand(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (action === "push") {
|
if (action === "push") {
|
||||||
const file = stringOption(args.options.file) ?? stringOption(args.options.f) ?? maybeName;
|
const statusOnly =
|
||||||
|
maybeName === "status" ||
|
||||||
|
booleanOption(args.options.check) === true ||
|
||||||
|
args.options.status === "true" ||
|
||||||
|
args.options.status === true;
|
||||||
|
const file =
|
||||||
|
stringOption(args.options.file) ??
|
||||||
|
stringOption(args.options.f) ??
|
||||||
|
(maybeName && maybeName !== "status" && !maybeName.startsWith("-") ? maybeName : undefined);
|
||||||
|
if (statusOnly) {
|
||||||
|
await runCapability(
|
||||||
|
"sealApprovalRulesPush",
|
||||||
|
client!,
|
||||||
|
corp,
|
||||||
|
{ file, statusOnly: true },
|
||||||
|
outputOptions(args.options)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const confirmed = booleanOption(args.options.yes) === true;
|
const confirmed = booleanOption(args.options.yes) === true;
|
||||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
|
||||||
const publish = booleanOption(args.options.publish);
|
const publish = booleanOption(args.options.publish);
|
||||||
@@ -339,18 +371,26 @@ export async function handleRulesCommand(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await runCapabilityResult(
|
let result: unknown;
|
||||||
"sealApprovalRulesPush",
|
try {
|
||||||
client!,
|
result = await runCapabilityResult(
|
||||||
corp,
|
"sealApprovalRulesPush",
|
||||||
{
|
client!,
|
||||||
file,
|
corp,
|
||||||
dryRun,
|
{
|
||||||
confirm: confirmed,
|
file,
|
||||||
publish,
|
dryRun,
|
||||||
versionName
|
confirm: confirmed,
|
||||||
|
publish,
|
||||||
|
versionName
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof RulePushExecutionError) {
|
||||||
|
printJson(error.recoveryPayload, outputOptions(args.options));
|
||||||
}
|
}
|
||||||
);
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
if (!confirmed && dryRun && result && typeof result === "object") {
|
if (!confirmed && dryRun && result && typeof result === "object") {
|
||||||
printJson(
|
printJson(
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js";
|
||||||
import { printJson } from "../printer.js";
|
import { printJson } from "../printer.js";
|
||||||
|
|
||||||
export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) {
|
export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { describe, expect, test } from "bun:test";
|
import { describe, expect, test } from "bun:test";
|
||||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { compareSemVer, getMirrorMode, isHomebrewInstall, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js";
|
import { compareSemVer, getMirrorMode, handleUpdateCommand, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js";
|
||||||
|
|
||||||
type Asset = { name: string; downloadUrl: string; size: number };
|
type Asset = { name: string; downloadUrl: string; size: number };
|
||||||
|
|
||||||
@@ -241,33 +241,58 @@ describe("update command bgSave and cache integration", () => {
|
|||||||
rmSync(tempDir, { recursive: true, force: true });
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("isHomebrewInstall", () => {
|
describe("update installation modes", () => {
|
||||||
test("requires the executable to resolve inside Homebrew's registered formula prefix", () => {
|
test("a copied source package cannot update its parent application's Git repository", async () => {
|
||||||
const root = mkdtempSync(join(tmpdir(), "seal-use-homebrew-detect-"));
|
const dir = mkdtempSync(join(tmpdir(), "seal-source-update-test-"));
|
||||||
try {
|
try {
|
||||||
const formulaPrefix = join(root, "opt", "seal-use");
|
await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }))
|
||||||
const cellarBin = join(root, "Cellar", "seal-use", "0.10.33", "bin");
|
.rejects.toMatchObject({ exitCode: 13 });
|
||||||
const nativeBin = join(root, "bin");
|
expect(existsSync(join(dir, "bun.lock"))).toBe(false);
|
||||||
const formulaExecutable = join(cellarBin, "seal-use");
|
} finally {
|
||||||
const nativeExecutable = join(nativeBin, "seal-use");
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
mkdirSync(cellarBin, { recursive: true });
|
test("native updates ignore package managers and allow selecting a release", async () => {
|
||||||
mkdirSync(nativeBin, { recursive: true });
|
const dir = mkdtempSync(join(tmpdir(), "seal-native-update-test-"));
|
||||||
mkdirSync(join(root, "opt"), { recursive: true });
|
const originalExecPath = process.execPath;
|
||||||
writeFileSync(formulaExecutable, "homebrew binary");
|
const originalEnv = { ...process.env };
|
||||||
writeFileSync(nativeExecutable, "native binary");
|
const originalFetch = globalThis.fetch;
|
||||||
symlinkSync(join(root, "Cellar", "seal-use", "0.10.33"), formulaPrefix);
|
const originalLog = console.log;
|
||||||
|
try {
|
||||||
expect(isHomebrewInstall(formulaExecutable, formulaPrefix)).toBe(true);
|
// Every executable, cache and response is a temp fixture; never update the running test engine.
|
||||||
expect(isHomebrewInstall(nativeExecutable, formulaPrefix)).toBe(false);
|
const binary = join(dir, "seal-use");
|
||||||
} finally {
|
const invoked = join(dir, "package-manager-invoked");
|
||||||
rmSync(root, { recursive: true, force: true });
|
writeFileSync(binary, "native fixture");
|
||||||
}
|
writeFileSync(join(dir, "brew"), `#!/bin/sh\ntouch '${invoked}'\nprintf '%s\\n' '${dir}'\n`, { mode: 0o755 });
|
||||||
});
|
process.execPath = binary;
|
||||||
|
process.env.PATH = `${dir}:${originalEnv.PATH ?? ""}`;
|
||||||
test("does not infer Homebrew from a matching directory name alone", () => {
|
process.env.SEAL_USE_UPDATE_CACHE_FILE = join(dir, "update-cache.json");
|
||||||
expect(isHomebrewInstall("/opt/homebrew/bin/seal-use", "/tmp/not-installed-seal-use")).toBe(false);
|
process.env.SEAL_USE_MIRROR = "github";
|
||||||
});
|
globalThis.fetch = Object.assign(async () => new Response(JSON.stringify([
|
||||||
|
{ tag_name: "v100.0.0", assets: [] },
|
||||||
|
{ tag_name: "v99.0.0", assets: [] }
|
||||||
|
]), { headers: { "Content-Type": "application/json" } }), { preconnect: originalFetch.preconnect });
|
||||||
|
let stdout = "";
|
||||||
|
console.log = (message: string) => { stdout += message; };
|
||||||
|
const runtime = { appRoot: dir, entryFile: join(dir, "src", "cli.ts") };
|
||||||
|
await handleUpdateCommand(runtime, { checkOnly: true, targetVersion: "99.0.0" });
|
||||||
|
expect(JSON.parse(stdout)).toMatchObject({ mode: "binary", latestVersion: "99.0.0", updateAvailable: true });
|
||||||
|
stdout = "";
|
||||||
|
// Reaching asset selection proves explicit versions are not blocked by a removed installation mode.
|
||||||
|
await expect(handleUpdateCommand(runtime, { targetVersion: "v99.0.0" }))
|
||||||
|
.rejects.toThrow("in release v99.0.0");
|
||||||
|
expect(stdout).toBe("");
|
||||||
|
expect(existsSync(invoked)).toBe(false);
|
||||||
|
expect(readFileSync(binary, "utf8")).toBe("native fixture");
|
||||||
|
} finally {
|
||||||
|
process.execPath = originalExecPath;
|
||||||
|
process.env = originalEnv;
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
console.log = originalLog;
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
+9
-276
@@ -1,12 +1,13 @@
|
|||||||
import { chmodSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||||
import { basename, dirname, isAbsolute, join, relative } from "node:path";
|
import { basename, dirname, join } from "node:path";
|
||||||
import { spawn, spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { isCompiledBinary } from "../../core/runtime.js";
|
import { isCompiledBinary } from "../../core/runtime.js";
|
||||||
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
|
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
|
||||||
import { readInstalledSkillVersion } from "../../core/embedded-skill.js";
|
import { readInstalledSkillVersion } from "../../core/embedded-skill.js";
|
||||||
import { saveUpdateCache } from "../../core/update-cache.js";
|
import { saveUpdateCache } from "../../core/update-cache.js";
|
||||||
import { VERSION, IS_RELEASE } from "../../version.js";
|
import { VERSION, IS_RELEASE } from "../../version.js";
|
||||||
import { printJson } from "../printer.js";
|
import { printJson } from "../printer.js";
|
||||||
|
import { validationError } from "../../core/errors.js";
|
||||||
import type { CliRuntime } from "../types.js";
|
import type { CliRuntime } from "../types.js";
|
||||||
|
|
||||||
const DEFAULT_GITHUB_REPO = "yunyingk/seal-use";
|
const DEFAULT_GITHUB_REPO = "yunyingk/seal-use";
|
||||||
@@ -130,6 +131,10 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Source updates must operate on this package's checkout, never a parent app's repository.
|
||||||
|
if (!existsSync(join(runtime.appRoot, ".git"))) {
|
||||||
|
throw validationError("当前源码安装目录不是 seal-use 的 Git 工作区。请使用发行版二进制,或从 seal-use 仓库通过 npm link 安装。");
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
|
runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -145,19 +150,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Homebrew managed mode
|
// 3. Standalone binary mode: check GitHub Releases
|
||||||
if (isHomebrewInstall()) {
|
|
||||||
try {
|
|
||||||
await handleHomebrewUpdate(options, repo, targetVersion);
|
|
||||||
return;
|
|
||||||
} catch (err) {
|
|
||||||
console.error(
|
|
||||||
`⚠️ Homebrew 自动更新失败,回退至原生二进制更新: ${err instanceof Error ? err.message : String(err)}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Standalone binary mode: check GitHub Releases
|
|
||||||
const platform = detectPlatform();
|
const platform = detectPlatform();
|
||||||
const arch = detectArch();
|
const arch = detectArch();
|
||||||
|
|
||||||
@@ -201,18 +194,6 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (targetVersion && !options.checkOnly) {
|
|
||||||
printJson({
|
|
||||||
updated: false,
|
|
||||||
currentVersion: VERSION,
|
|
||||||
targetVersion,
|
|
||||||
latestVersion,
|
|
||||||
mode: "homebrew",
|
|
||||||
message: "Homebrew-managed installations follow the formula version and do not support selecting a historical release. Use Homebrew directly for version pinning."
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.checkOnly) {
|
if (options.checkOnly) {
|
||||||
printJson({
|
printJson({
|
||||||
updated: false,
|
updated: false,
|
||||||
@@ -440,254 +421,6 @@ function detectArch(): "arm64" | "x64" {
|
|||||||
return process.arch === "arm64" ? "arm64" : "x64";
|
return process.arch === "arm64" ? "arm64" : "x64";
|
||||||
}
|
}
|
||||||
|
|
||||||
function homebrewFormulaPrefix(): string | undefined {
|
|
||||||
try {
|
|
||||||
const result = spawnSync("brew", ["--prefix", "seal-use"], {
|
|
||||||
stdio: ["ignore", "pipe", "ignore"],
|
|
||||||
encoding: "utf-8"
|
|
||||||
});
|
|
||||||
if (result.status !== 0 || typeof result.stdout !== "string") return undefined;
|
|
||||||
const prefix = result.stdout.trim();
|
|
||||||
return prefix || undefined;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function homebrewInstalledVersion(): string | undefined {
|
|
||||||
try {
|
|
||||||
const result = spawnSync("brew", ["list", "--versions", "seal-use"], {
|
|
||||||
stdio: ["ignore", "pipe", "ignore"],
|
|
||||||
encoding: "utf-8"
|
|
||||||
});
|
|
||||||
if (result.status !== 0 || typeof result.stdout !== "string") return undefined;
|
|
||||||
const parts = result.stdout.trim().split(/\s+/);
|
|
||||||
return parts.length >= 2 ? parts[parts.length - 1] : undefined;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isHomebrewInstall(
|
|
||||||
execPath = process.execPath,
|
|
||||||
formulaPrefix = homebrewFormulaPrefix()
|
|
||||||
): boolean {
|
|
||||||
if (!formulaPrefix) return false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const resolvedExec = realpathSync(execPath);
|
|
||||||
const resolvedPrefix = realpathSync(formulaPrefix);
|
|
||||||
const fromFormula = relative(resolvedPrefix, resolvedExec);
|
|
||||||
const parentPrefix = `..${process.platform === "win32" ? "\\" : "/"}`;
|
|
||||||
return Boolean(fromFormula && fromFormula !== ".." && !fromFormula.startsWith(parentPrefix) && !isAbsolute(fromFormula));
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleHomebrewUpdate(
|
|
||||||
options: UpdateOptions,
|
|
||||||
repo: string,
|
|
||||||
targetVersion?: string
|
|
||||||
): Promise<void> {
|
|
||||||
const releases = await fetchGitHubReleases(repo, 30);
|
|
||||||
const release = targetVersion
|
|
||||||
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
|
|
||||||
await fetchGitHubRelease(repo, targetVersion))
|
|
||||||
: (releases[0] ?? await fetchGitHubRelease(repo));
|
|
||||||
|
|
||||||
const latestVersion = release?.version ?? VERSION;
|
|
||||||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
|
||||||
const shouldUpdate = isUpgrade || Boolean(options.force);
|
|
||||||
|
|
||||||
if (release?.version) {
|
|
||||||
saveUpdateCache({
|
|
||||||
latestVersion: release.version,
|
|
||||||
publishedAt: release.publishedAt,
|
|
||||||
releaseUrl: release.htmlUrl
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.bgSave) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.checkOnly) {
|
|
||||||
const currentRelease = releases.find((r) => r.version === VERSION);
|
|
||||||
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
|
|
||||||
printJson({
|
|
||||||
updated: false,
|
|
||||||
updateAvailable: isUpgrade,
|
|
||||||
currentVersion: VERSION,
|
|
||||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
|
||||||
latestVersion,
|
|
||||||
latestVersionPublishedAt: release?.publishedAt,
|
|
||||||
behindCount: pendingReleases.length,
|
|
||||||
pendingReleases: pendingReleases.map((r) => ({
|
|
||||||
version: r.version,
|
|
||||||
tagName: r.tagName,
|
|
||||||
publishedAt: r.publishedAt,
|
|
||||||
author: r.author,
|
|
||||||
releaseNotes: r.notes,
|
|
||||||
releaseUrl: r.htmlUrl
|
|
||||||
})),
|
|
||||||
releaseNotes: release?.notes ?? "",
|
|
||||||
releaseUrl: release?.htmlUrl ?? "",
|
|
||||||
mode: "homebrew"
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!shouldUpdate) {
|
|
||||||
printJson({
|
|
||||||
updated: false,
|
|
||||||
currentVersion: VERSION,
|
|
||||||
latestVersion,
|
|
||||||
mode: "homebrew",
|
|
||||||
message: `seal-use is already up to date (v${VERSION})`
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error("ℹ️ 检测到当前 seal-use 由 Homebrew 管理。");
|
|
||||||
console.error("📦 正在通过 Homebrew 极速更新: brew update && brew upgrade seal-use ...");
|
|
||||||
|
|
||||||
const installedBefore = homebrewInstalledVersion();
|
|
||||||
const alreadyLatestBeforeUpdate = installedBefore
|
|
||||||
? !isNewerVersion(latestVersion, installedBefore)
|
|
||||||
: false;
|
|
||||||
let alreadyLatest = alreadyLatestBeforeUpdate;
|
|
||||||
// `brew update` refreshes all configured taps. Passing a tap name here is
|
|
||||||
// parsed as a formula upgrade by newer Homebrew versions (and fails with
|
|
||||||
// "No available formula ... tap").
|
|
||||||
const tapUpdate = await runHomebrewCommand(
|
|
||||||
["update"],
|
|
||||||
"🔄 [1/2] 正在刷新 Homebrew 软件源(可能需要几分钟)..."
|
|
||||||
);
|
|
||||||
|
|
||||||
if (tapUpdate.status !== 0) {
|
|
||||||
const msg = tapUpdate.stderr?.trim() || tapUpdate.stdout?.trim();
|
|
||||||
throw new Error(`brew update failed (exit ${tapUpdate.status}): ${msg || "unknown error"}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Upgrade the formula
|
|
||||||
const upgradeRes = await runHomebrewCommand(
|
|
||||||
["upgrade", "seal-use"],
|
|
||||||
"⬆️ [2/2] 正在升级 seal-use..."
|
|
||||||
);
|
|
||||||
|
|
||||||
const outCombined = `${upgradeRes.stdout || ""} ${upgradeRes.stderr || ""}`;
|
|
||||||
const brewReportsAlreadyLatest =
|
|
||||||
outCombined.includes("already installed") || outCombined.includes("latest version already installed");
|
|
||||||
|
|
||||||
if (upgradeRes.status !== 0 && !brewReportsAlreadyLatest) {
|
|
||||||
throw new Error(
|
|
||||||
`brew upgrade seal-use failed (exit ${upgradeRes.status}): ${upgradeRes.stderr.trim() || upgradeRes.stdout.trim()}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const installedVersion = homebrewInstalledVersion();
|
|
||||||
if (installedVersion && isNewerVersion(latestVersion, installedVersion)) {
|
|
||||||
throw new Error(
|
|
||||||
`Homebrew still has seal-use v${installedVersion}; expected v${latestVersion}. ` +
|
|
||||||
"Refresh the tap and run `brew upgrade seal-use` again."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
alreadyLatest = alreadyLatestBeforeUpdate;
|
|
||||||
|
|
||||||
// Refresh installed skill through new binary
|
|
||||||
try {
|
|
||||||
spawnSync("seal-use", ["skill", "install"], { stdio: "ignore" });
|
|
||||||
} catch {
|
|
||||||
// best-effort
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error(
|
|
||||||
alreadyLatest
|
|
||||||
? "ℹ️ seal-use 已是 Homebrew 中的最新版本。"
|
|
||||||
: "✅ seal-use 已通过 Homebrew 成功更新!"
|
|
||||||
);
|
|
||||||
|
|
||||||
printJson({
|
|
||||||
updated: !alreadyLatest,
|
|
||||||
previousVersion: VERSION,
|
|
||||||
latestVersion,
|
|
||||||
mode: "homebrew",
|
|
||||||
message: alreadyLatest
|
|
||||||
? `seal-use is already at the latest version v${latestVersion} in Homebrew`
|
|
||||||
: `Successfully upgraded seal-use to v${latestVersion} via Homebrew`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
type HomebrewCommandResult = {
|
|
||||||
status: number | null;
|
|
||||||
signal: NodeJS.Signals | null;
|
|
||||||
stdout: string;
|
|
||||||
stderr: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Runs Homebrew without buffering its output until completion. Homebrew can spend several minutes
|
|
||||||
* refreshing taps or downloading a formula, so its output belongs on stderr as live diagnostics;
|
|
||||||
* stdout must remain reserved for the command's final machine-readable JSON payload.
|
|
||||||
*/
|
|
||||||
function runHomebrewCommand(args: string[], startMessage: string): Promise<HomebrewCommandResult> {
|
|
||||||
console.error(startMessage);
|
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
let child;
|
|
||||||
try {
|
|
||||||
child = spawn("brew", args, {
|
|
||||||
stdio: ["ignore", "pipe", "pipe"],
|
|
||||||
env: { ...process.env, NONINTERACTIVE: "1" }
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
reject(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let stdout = "";
|
|
||||||
let stderr = "";
|
|
||||||
let lastOutputAt = Date.now();
|
|
||||||
let settled = false;
|
|
||||||
|
|
||||||
const forward = (chunk: Buffer, stream: "stdout" | "stderr") => {
|
|
||||||
const text = chunk.toString();
|
|
||||||
if (stream === "stdout") stdout += text;
|
|
||||||
else stderr += text;
|
|
||||||
lastOutputAt = Date.now();
|
|
||||||
try {
|
|
||||||
process.stderr.write(text);
|
|
||||||
} catch {
|
|
||||||
// Ignore a closed diagnostic stream; the child process still needs to complete normally.
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
child.stdout?.on("data", (chunk: Buffer) => forward(chunk, "stdout"));
|
|
||||||
child.stderr?.on("data", (chunk: Buffer) => forward(chunk, "stderr"));
|
|
||||||
|
|
||||||
const heartbeat = setInterval(() => {
|
|
||||||
if (Date.now() - lastOutputAt >= 15000) {
|
|
||||||
console.error("⏳ Homebrew 仍在运行,当前没有新的输出,请稍候...");
|
|
||||||
lastOutputAt = Date.now();
|
|
||||||
}
|
|
||||||
}, 15000);
|
|
||||||
heartbeat.unref?.();
|
|
||||||
|
|
||||||
const finish = (callback: () => void) => {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearInterval(heartbeat);
|
|
||||||
callback();
|
|
||||||
};
|
|
||||||
|
|
||||||
child.once("error", (error) => finish(() => reject(error)));
|
|
||||||
child.once("close", (status, signal) =>
|
|
||||||
finish(() => resolve({ status, signal, stdout, stderr }))
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
type GitHubAsset = {
|
type GitHubAsset = {
|
||||||
name: string;
|
name: string;
|
||||||
downloadUrl: string;
|
downloadUrl: string;
|
||||||
|
|||||||
@@ -288,7 +288,7 @@ describe("seal-use webhook replay CLI", () => {
|
|||||||
return new Response("Not found", { status: 404 });
|
return new Response("Not found", { status: 404 });
|
||||||
}) as any;
|
}) as any;
|
||||||
|
|
||||||
const result = await runCli(["webhook", "replay", "run-001"]);
|
const result = await runCli(["webhook", "replay", "run-001", "--yes"]);
|
||||||
|
|
||||||
expect(result.isError).toBe(false);
|
expect(result.isError).toBe(false);
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
@@ -569,5 +569,66 @@ describe("seal-use webhook replay CLI", () => {
|
|||||||
expect(parsed.safetyGuards.targetModeAssisted).toBe(true);
|
expect(parsed.safetyGuards.targetModeAssisted).toBe(true);
|
||||||
expect(parsed.safetyGuards.nodeId412Blocked).toBe(true);
|
expect(parsed.safetyGuards.nodeId412Blocked).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("webhook replay requires confirmation before provisioning or pushing", async () => {
|
||||||
|
setupMockEnv();
|
||||||
|
let mutations = 0;
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
|
||||||
|
if (method !== "GET") mutations++;
|
||||||
|
return new Response(JSON.stringify({ data: mockApprovalRun }), {
|
||||||
|
status: 200, headers: { "Content-Type": "application/json" }
|
||||||
|
});
|
||||||
|
}) as typeof fetch;
|
||||||
|
const result = await runCli(["approval-runs", "replay", "run-001"]);
|
||||||
|
expect(result.exitCode).toBe(10);
|
||||||
|
expect(result.stderr).toContain("--yes or --confirm");
|
||||||
|
expect(mutations).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("outbound CLI gates both entry points and passes either confirmation flag", async () => {
|
||||||
|
setupMockEnv();
|
||||||
|
let pushes = 0;
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||||
|
const requestUrl = input instanceof Request ? input.url : input.toString();
|
||||||
|
if (requestUrl.includes("/api/hosecloud/outbound")) {
|
||||||
|
pushes++;
|
||||||
|
return new Response(JSON.stringify({ data: { success: true } }), {
|
||||||
|
status: 200, headers: { "Content-Type": "application/json" }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new Response(JSON.stringify({ data: { integrations: [{
|
||||||
|
type: "hosecloud", signKey: "key", mode: "assisted", corporationId: "corp"
|
||||||
|
}] } }), { status: 200, headers: { "Content-Type": "application/json" } });
|
||||||
|
}) as typeof fetch;
|
||||||
|
for (const command of [
|
||||||
|
["approval-runs", "replay", "--sn", "SN", "--channel", "hose-outbound"],
|
||||||
|
["deploy", "hosecloud", "test-outbound"]
|
||||||
|
]) {
|
||||||
|
const args = [...command, "--flow-id", "flow", "--message-id", "message"];
|
||||||
|
for (const flags of [[], ["--yes=false"], ["--force"]]) {
|
||||||
|
const before = pushes;
|
||||||
|
const result = await runCli([...args, ...flags]);
|
||||||
|
expect(result.exitCode).toBe(10);
|
||||||
|
expect(pushes).toBe(before);
|
||||||
|
}
|
||||||
|
for (const flag of ["--yes", "--confirm"]) {
|
||||||
|
const before = pushes;
|
||||||
|
const result = await runCli([...args, flag]);
|
||||||
|
expect(result.exitCode).toBe(0);
|
||||||
|
expect(pushes).toBe(before + 1);
|
||||||
|
const parsed = JSON.parse(result.stdout);
|
||||||
|
expect(parsed.consumptionVerified).toBe(false);
|
||||||
|
expect(parsed.recordId).toBeUndefined();
|
||||||
|
}
|
||||||
|
|
||||||
|
const before = pushes;
|
||||||
|
const preview = await runCli([...args, "--node-id", "FLOW:real-node", "--dry-run"]);
|
||||||
|
expect(preview.exitCode).toBe(0);
|
||||||
|
expect(pushes).toBe(before);
|
||||||
|
const parsed = JSON.parse(preview.stdout);
|
||||||
|
expect((parsed.safetyGuards ?? parsed.safetyCheck).nodeId412Blocked).toBe(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -11,8 +11,8 @@ import {
|
|||||||
executeApprovalRunsReplay,
|
executeApprovalRunsReplay,
|
||||||
resolveReplayCorpPair,
|
resolveReplayCorpPair,
|
||||||
type ReplayRecordsQuery
|
type ReplayRecordsQuery
|
||||||
} from "../../domains/seal/webhook-replay.js";
|
} from "../../domains/seal/replay/webhook.js";
|
||||||
import { executeHoseOutboundReplay } from "../../domains/seal/hose-outbound-replay.js";
|
import { executeHoseOutboundReplay } from "../../domains/seal/replay/hose-outbound.js";
|
||||||
import {
|
import {
|
||||||
checkWebhookReadiness,
|
checkWebhookReadiness,
|
||||||
exportApprovalRunsToResourcePack,
|
exportApprovalRunsToResourcePack,
|
||||||
@@ -148,6 +148,7 @@ export async function handleWebhookCommand(
|
|||||||
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]);
|
||||||
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]);
|
||||||
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]);
|
||||||
|
const confirm = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
|
||||||
|
|
||||||
const channel =
|
const channel =
|
||||||
stringOption(args.options.channel) ??
|
stringOption(args.options.channel) ??
|
||||||
@@ -178,6 +179,7 @@ export async function handleWebhookCommand(
|
|||||||
rejectionNum,
|
rejectionNum,
|
||||||
targetSignKey,
|
targetSignKey,
|
||||||
dryRun,
|
dryRun,
|
||||||
|
confirm,
|
||||||
force
|
force
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -207,7 +209,8 @@ export async function handleWebhookCommand(
|
|||||||
snSuffix,
|
snSuffix,
|
||||||
docIdPrefix,
|
docIdPrefix,
|
||||||
docIdSuffix,
|
docIdSuffix,
|
||||||
dryRun
|
dryRun,
|
||||||
|
confirm
|
||||||
});
|
});
|
||||||
|
|
||||||
if (dryRun) {
|
if (dryRun) {
|
||||||
|
|||||||
@@ -91,12 +91,16 @@ describe("CLI semantic errors", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("keeps domain failures and quality gates at exit 1", () => {
|
test("keeps domain failures, post-mutation recovery errors, and quality gates at exit 1", () => {
|
||||||
expect(classifyCliError(new Error("未找到指定的规则版本: 99"))).toEqual({ exitCode: 1 });
|
expect(classifyCliError(new Error("未找到指定的规则版本: 99"))).toEqual({ exitCode: 1 });
|
||||||
expect(classifyCliError(new Error("[Linter 质量门禁未通过] 综合评分 80 低于要求的最低分 85 分"))).toEqual({
|
expect(classifyCliError(new Error("[Linter 质量门禁未通过] 综合评分 80 低于要求的最低分 85 分"))).toEqual({
|
||||||
exitCode: 1
|
exitCode: 1
|
||||||
});
|
});
|
||||||
expect(classifyCliError(new Error("Webhook 单据推送失败 (500): internal"))).toEqual({ exitCode: 1 });
|
expect(classifyCliError(new Error("Webhook 单据推送失败 (500): internal"))).toEqual({ exitCode: 1 });
|
||||||
expect(classifyCliError(new Error("测试企业「T」AI 审批额度不足:当前剩余 200 点"))).toEqual({ exitCode: 1 });
|
expect(classifyCliError(new Error("测试企业「T」AI 审批额度不足:当前剩余 200 点"))).toEqual({ exitCode: 1 });
|
||||||
|
expect(
|
||||||
|
classifyCliError(new Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。"))
|
||||||
|
).toEqual({ exitCode: 1 });
|
||||||
|
expect(classifyCliError(new Error("上游网关响应超时,请重试或检查网络连接。"))).toEqual({ exitCode: 1 });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -61,6 +61,14 @@ describe("extractHelpRequest", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("renderHelp", () => {
|
describe("renderHelp", () => {
|
||||||
|
test("explains both recode phases without exposing internal activation timing", () => {
|
||||||
|
const help = renderHelp(["rules", "recode"]);
|
||||||
|
expect(help).toContain("一次性凭证");
|
||||||
|
expect(help).toContain("另一次调用");
|
||||||
|
expect(help).toContain("不执行重排");
|
||||||
|
expect(help).not.toContain("500");
|
||||||
|
expect(help).not.toContain("--confirm-code");
|
||||||
|
});
|
||||||
test("renders global help when target is empty", () => {
|
test("renders global help when target is empty", () => {
|
||||||
const help = renderHelp([]);
|
const help = renderHelp([]);
|
||||||
expect(help).toContain("seal-use CLI");
|
expect(help).toContain("seal-use CLI");
|
||||||
|
|||||||
+81
-21
@@ -343,14 +343,23 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "push",
|
name: "push",
|
||||||
summary: "Push rules from local JSON file to enterprise draft space",
|
summary: "Push rules from local JSON file to enterprise draft space (with step recovery & status check)",
|
||||||
usage: ["seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]"]
|
usage: [
|
||||||
|
"seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]",
|
||||||
|
"seal-use rules push status [--file <path>] [--corp <corpId>]"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "clear",
|
name: "clear",
|
||||||
summary: "Clear all draft rules from enterprise",
|
summary: "Clear all draft rules from enterprise",
|
||||||
usage: ["seal-use rules clear [--dry-run|--yes] [--corp <corpId>]"]
|
usage: ["seal-use rules clear [--dry-run|--yes] [--corp <corpId>]"]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "recode",
|
||||||
|
summary: "Preview consecutive rule numbering, then execute with a one-use confirmation code",
|
||||||
|
usage: ["seal-use rules recode [--dry-run] --corp <corpId>"],
|
||||||
|
description: "首次运行只返回影响预览、一次性凭证和 nextCommand,不执行重排;核对后另一次调用返回的命令才会生效。凭证绑定企业、环境和草稿,5 分钟有效且只能使用一次。--yes/--confirm 不能跳过该流程。--dry-run 只预览,不签发凭证。服务端决定编号顺序,所有规则均可能变号;逐条映射在执行后回读。重排不发布版本;查看旧编号需结合发布版本。"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "map",
|
name: "map",
|
||||||
summary: "Inspect locally synced production/test rule code mappings",
|
summary: "Inspect locally synced production/test rule code mappings",
|
||||||
@@ -435,9 +444,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{
|
{
|
||||||
name: "replay",
|
name: "replay",
|
||||||
usage: [
|
usage: [
|
||||||
"seal-use webhook replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--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>]",
|
"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>]"
|
"seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]"
|
||||||
],
|
],
|
||||||
options: [
|
options: [
|
||||||
{ flag: "<recordId>", description: "Approval run record ID to replay" },
|
{ flag: "<recordId>", description: "Approval run record ID to replay" },
|
||||||
@@ -450,6 +459,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN and documentId" },
|
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN and documentId" },
|
||||||
{ flag: "--sn-prefix <str>", description: "Optional prefix prepended to documentSN and documentId" },
|
{ flag: "--sn-prefix <str>", description: "Optional prefix prepended to documentSN and documentId" },
|
||||||
{ flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" },
|
{ flag: "--dry-run", description: "Generate and output Webhook payload JSON without sending HTTP request" },
|
||||||
|
{ flag: "--yes, --confirm", description: "Required for live replay; --force only overrides the environment guard" },
|
||||||
{ flag: "--force", description: "Allow replaying to a production enterprise" }
|
{ flag: "--force", description: "Allow replaying to a production enterprise" }
|
||||||
],
|
],
|
||||||
description: "Extracts structured form fields from historical approval records (Webhook or Hose source), sanitizes field types, and pushes documents to the target Webhook channel. Automatically infers 1-to-1 bound test/production enterprise pairs."
|
description: "Extracts structured form fields from historical approval records (Webhook or Hose source), sanitizes field types, and pushes documents to the target Webhook channel. Automatically infers 1-to-1 bound test/production enterprise pairs."
|
||||||
@@ -582,16 +592,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
name: "replay",
|
name: "replay",
|
||||||
summary: "Replay approval run record into a Webhook integration",
|
summary: "Replay approval run record into a Webhook integration",
|
||||||
usage: [
|
usage: [
|
||||||
"seal-use approval-runs replay <recordId> [--webhook <idOrName>] [--sn-suffix <str>] [--dry-run] [--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>]",
|
"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 [--target-corp <corpId>] [--dry-run]",
|
"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 [--target-corp <corpId>] [--dry-run]",
|
"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>]"
|
"seal-use approval-runs replay --limit <n> [--status <status>] [--source-corp <corpId>] [--target-corp <corpId>] [--yes|--confirm]"
|
||||||
],
|
],
|
||||||
options: [
|
options: [
|
||||||
{ flag: "<recordId>", description: "Approval run record ID" },
|
{ flag: "<recordId>", description: "Approval run record ID" },
|
||||||
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
{ flag: "--sn <sn>", description: "Lookup approval record by source document SN" },
|
||||||
{ flag: "--channel <webhook|hose-outbound>", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" },
|
{ flag: "--channel <webhook|hose-outbound>", description: "Replay channel: webhook (default) or hose-outbound (Hosecloud official outbound)" },
|
||||||
|
{ flag: "--sign-key <key>", description: "Target Hose integration signKey for hose-outbound; required when the target has several integrations" },
|
||||||
{ flag: "--message-id <msgId>", description: "Explicit Hose outbound messageId override" },
|
{ flag: "--message-id <msgId>", description: "Explicit Hose outbound messageId override" },
|
||||||
{ flag: "--rejection-num <n>", description: "Target specific rejection iteration (0, 1, 2, ...)" },
|
{ flag: "--rejection-num <n>", description: "Target specific rejection iteration (0, 1, 2, ...)" },
|
||||||
{ flag: "--limit <n>", description: "Batch replay latest N records" },
|
{ flag: "--limit <n>", description: "Batch replay latest N records" },
|
||||||
@@ -600,7 +611,8 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside" },
|
{ flag: "--source-corp <corpId>", description: "Source enterprise where records reside" },
|
||||||
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed" },
|
{ flag: "--target-corp <corpId>", description: "Target enterprise where records are pushed" },
|
||||||
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
|
{ flag: "--sn-suffix <str>", description: "Optional suffix appended to documentSN" },
|
||||||
{ flag: "--dry-run", description: "Preview payload without sending" }
|
{ flag: "--dry-run", description: "Preview payload without sending" },
|
||||||
|
{ flag: "--yes, --confirm", description: "Required for live replay; --force only overrides environment and pairing guards" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -608,21 +620,56 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{
|
{
|
||||||
area: "report",
|
area: "report",
|
||||||
title: "Monthly audit accuracy reports",
|
title: "Monthly audit accuracy reports",
|
||||||
description: "Generate the monthly AI audit accuracy report (Markdown) from a mutable template plus live tenant data.",
|
description: "Generate monthly audit reports, validate local Markdown, and export HTML/PNG/PDF.",
|
||||||
commands: [
|
commands: [
|
||||||
{
|
{
|
||||||
name: "monthly",
|
name: "monthly",
|
||||||
aliases: ["month"],
|
aliases: ["month"],
|
||||||
summary: "Fill the monthly report template with performance, risk, and approval-run data",
|
summary: "Fill the monthly report template with performance, risk, and approval-run data",
|
||||||
usage: ["seal-use report monthly --month <YYYY-MM> [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
|
usage: ["seal-use report monthly --month <YYYY-MM> [--out <报告.md>] [--template <file>] [--report-id <RPT-...>] [--max-runs <n>] [--corp <corpId>]"],
|
||||||
options: [
|
options: [
|
||||||
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
{ flag: "--month <YYYY-MM>", description: "Statistics month, e.g. 2026-08 (required)" },
|
||||||
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to report-templates/monthly.md" },
|
{ flag: "--template <file>", description: "Custom template Markdown path; defaults to the Git-managed template embedded in the binary, independent of cwd" },
|
||||||
|
{ flag: "--out <file>", description: "Save Markdown plus local images beside the report; stdout stays JSON (without the content field)" },
|
||||||
|
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" },
|
||||||
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
|
{ flag: "--report-id <RPT-...>", description: "Custom report id; defaults to RPT-<YYYYMM>-<random>" },
|
||||||
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
{ flag: "--max-runs <n>", description: "Cap approval-run detail fetch, default 500 (max 500)" }
|
||||||
],
|
],
|
||||||
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 (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers."
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "validate",
|
||||||
|
summary: "Check a local report's structure, images, totals, and formulas",
|
||||||
|
usage: ["seal-use report validate <报告.md>"],
|
||||||
|
options: [],
|
||||||
|
description: "Local only: no --corp, credentials, or Seal requests. Returns JSON issues; exit 1 if validation fails."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "render",
|
||||||
|
summary: "Validate and export HTML, full-length PNG, and A4 PDF from local Markdown",
|
||||||
|
usage: ["seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]"],
|
||||||
|
options: [
|
||||||
|
{ flag: "--out <stem>", description: "Output filename stem; extensions are appended" },
|
||||||
|
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
|
||||||
|
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
|
||||||
|
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
|
||||||
|
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
|
||||||
|
],
|
||||||
|
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "export",
|
||||||
|
summary: "Package Markdown, local 4x assets, self-contained HTML, and PDF into a dedicated directory",
|
||||||
|
usage: ["seal-use report export <报告.md> --out <输出目录> [--format <all|html|pdf>]"],
|
||||||
|
options: [
|
||||||
|
{ flag: "--out <dir>", description: "Dedicated output directory for the report bundle" },
|
||||||
|
{ flag: "--format <format>", description: "all (default), html, or pdf" },
|
||||||
|
{ flag: "--width <px>", description: "PNG viewport width, default 1200" },
|
||||||
|
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
|
||||||
|
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" }
|
||||||
|
],
|
||||||
|
description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF."
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "review set",
|
name: "review set",
|
||||||
summary: "Record one human adjudication (who was right: AI or human) for a document",
|
summary: "Record one human adjudication (who was right: AI or human) for a document",
|
||||||
@@ -634,7 +681,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
{ flag: "--note <text>", description: "Optional adjudication note" },
|
{ flag: "--note <text>", description: "Optional adjudication note" },
|
||||||
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
|
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
|
||||||
],
|
],
|
||||||
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
|
description: "Append-only local JSONL per tenant+month (~/.config/seal-use/state/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "review list",
|
name: "review list",
|
||||||
@@ -745,20 +792,33 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "hosecloud configure",
|
name: "hosecloud configure",
|
||||||
summary: "Configure HoseCloud deployment settings",
|
summary: "Save Hose integration settings in Seal",
|
||||||
usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp <corpId>]"]
|
usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp <corpId>]"],
|
||||||
|
options: [
|
||||||
|
{ flag: "--dry-run", description: "Preview the configuration diff without saving" },
|
||||||
|
{ flag: "--yes, --confirm", description: "Required to save the integration configuration" }
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "hosecloud sync",
|
name: "hosecloud sync",
|
||||||
summary: "Synchronize HoseCloud rules and definitions",
|
summary: "Create or update Hose outbound messages and callback URLs",
|
||||||
usage: ["seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]"]
|
usage: ["seal-use deploy hosecloud sync [<sign-key>] [--auto] [--dry-run] [--yes|--confirm] [--corp <corpId>]"],
|
||||||
|
options: [
|
||||||
|
{ flag: "--auto", description: "Select the sole Hose integration; does not confirm synchronization" },
|
||||||
|
{ flag: "--dry-run", description: "Preview the sync request without creating or updating messages" },
|
||||||
|
{ flag: "--yes, --confirm", description: "Required for live synchronization" }
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "hosecloud test-outbound",
|
name: "hosecloud test-outbound",
|
||||||
summary: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发(要求 assisted 模式)",
|
summary: "向合思出站 (outbound) 接口推送测试/重放消息以模拟工作流触发(要求 assisted 模式)",
|
||||||
usage: [
|
usage: [
|
||||||
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --flow-id <id> --message-id <msgId> [--dry-run] [--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] [--corp <corpId>]"
|
"seal-use deploy hosecloud test-outbound [--sign-key <key>] --sn <SN> --message-id <msgId> [--dry-run] [--yes|--confirm] [--corp <corpId>]"
|
||||||
|
],
|
||||||
|
options: [
|
||||||
|
{ flag: "--dry-run", description: "Preview the outbound payload without sending" },
|
||||||
|
{ flag: "--yes, --confirm", description: "Required for live outbound push" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
+14
-4
@@ -65,10 +65,11 @@ export async function runCapabilityResult(
|
|||||||
);
|
);
|
||||||
// Schema gate: a missing required field or an out-of-range value fails here
|
// Schema gate: a missing required field or an out-of-range value fails here
|
||||||
// with exit 13 instead of reaching the handler as `undefined` and surfacing
|
// with exit 13 instead of reaching the handler as `undefined` and surfacing
|
||||||
// as an opaque upstream error. Valid params pass through untouched.
|
// as an opaque upstream error. Valid params are normalized so the handler
|
||||||
parseCapabilityParams(tool, compactParams);
|
// executes with the exact coerced/defaulted values that passed validation.
|
||||||
|
const normalizedParams = parseCapabilityParams(tool, compactParams);
|
||||||
const handler = tool.handler as SealCapability["handler"];
|
const handler = tool.handler as SealCapability["handler"];
|
||||||
return handler(client, compactParams as never, { corp });
|
return handler(client, normalizedParams as never, { corp });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -98,6 +99,15 @@ export async function runLangfuseCapability(
|
|||||||
throw validationError(`Invalid parameters for ${tool.name}: ${detail}`);
|
throw validationError(`Invalid parameters for ${tool.name}: ${detail}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const normalizedParams =
|
||||||
|
parsed.data && typeof parsed.data === "object"
|
||||||
|
? {
|
||||||
|
...compactParams,
|
||||||
|
...Object.fromEntries(
|
||||||
|
Object.entries(parsed.data as Record<string, unknown>).filter(([, value]) => value !== undefined)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
: compactParams;
|
||||||
const handler = tool.handler as (params: never, service: LangfuseService) => Promise<unknown>;
|
const handler = tool.handler as (params: never, service: LangfuseService) => Promise<unknown>;
|
||||||
printJson(await handler(compactParams as never, createLangfuseService()), options);
|
printJson(await handler(normalizedParams as never, createLangfuseService()), options);
|
||||||
}
|
}
|
||||||
@@ -157,6 +157,48 @@ describe("option helpers", () => {
|
|||||||
expect(() => parseHoseExpireSeconds("0s")).toThrow("必须为大于 0 的有效时长");
|
expect(() => parseHoseExpireSeconds("0s")).toThrow("必须为大于 0 的有效时长");
|
||||||
expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长");
|
expect(() => parseHoseExpireSeconds("invalid")).toThrow("必须为有效时长");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("overflowing --expire literals are usage errors before reaching auth", () => {
|
||||||
|
for (const parse of [parseDelegationExpireHours, parseHoseExpireSeconds]) {
|
||||||
|
for (const literal of ["9".repeat(309), "9".repeat(309) + "s", "9".repeat(308) + "d"]) {
|
||||||
|
expect(() => parse(literal)).toThrow();
|
||||||
|
try {
|
||||||
|
parse(literal);
|
||||||
|
} catch (error) {
|
||||||
|
expect((error as { exitCode: number }).exitCode).toBe(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("both --expire flags read a unitless literal the same way", () => {
|
||||||
|
// Regression: the two parsers used to each carry their own copy of the
|
||||||
|
// unitless heuristic, so `--expire 300` meant 5 minutes on one path and
|
||||||
|
// clamped to 1 hour on the other purely by implementation accident.
|
||||||
|
for (const literal of [300, "300", 86400, "86400", 7200, "7200"]) {
|
||||||
|
const hours = parseDelegationExpireHours(literal);
|
||||||
|
const seconds = parseHoseExpireSeconds(literal);
|
||||||
|
const unitlessSeconds = typeof literal === "number" ? literal : Number(literal);
|
||||||
|
expect(seconds).toBe(unitlessSeconds);
|
||||||
|
// Delegation floors to whole hours and never drops below 1h.
|
||||||
|
expect(hours).toBe(Math.max(Math.floor(seconds / 3600), 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A small unitless value is hours on both paths.
|
||||||
|
expect(parseDelegationExpireHours("24")).toBe(24);
|
||||||
|
expect(parseHoseExpireSeconds("24")).toBe(86_400);
|
||||||
|
expect(parseDelegationExpireHours(2)).toBe(2);
|
||||||
|
expect(parseHoseExpireSeconds(2)).toBe(7200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sub-second input stays a usage error on both --expire flags", () => {
|
||||||
|
// Regression: the shared tokenizer understands `ms` for the simulation
|
||||||
|
// windows, and without a per-caller unit set that grammar leaked into
|
||||||
|
// --expire, silently rounding 500ms up to a 1h / 1s link.
|
||||||
|
expect(() => parseDelegationExpireHours("500ms")).toThrow("必须为有效时长格式");
|
||||||
|
expect(() => parseHoseExpireSeconds("500ms")).toThrow("必须为有效时长");
|
||||||
|
expect(() => parseHoseExpireSeconds("200ms")).toThrow("必须为有效时长");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("flag registry cross-check", () => {
|
describe("flag registry cross-check", () => {
|
||||||
|
|||||||
+63
-115
@@ -1,6 +1,7 @@
|
|||||||
import type { WebhookMode } from "../domains/seal/types.js";
|
import type { WebhookMode } from "../domains/seal/types.js";
|
||||||
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
|
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
|
||||||
import type { ParsedArgs } from "./types.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 } from "./errors.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -41,7 +42,7 @@ export const BOOLEAN_FLAGS = new Set([
|
|||||||
export const VALUE_FLAGS = new Set([
|
export const VALUE_FLAGS = new Set([
|
||||||
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
|
||||||
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
|
||||||
"channel", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
|
"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",
|
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
|
||||||
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
|
||||||
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
|
||||||
@@ -80,7 +81,7 @@ export const VALUE_FLAGS = new Set([
|
|||||||
"trace-id", "trace-limit",
|
"trace-id", "trace-limit",
|
||||||
"type", "until", "url", "userId", "version-name", "versionName",
|
"type", "until", "url", "userId", "version-name", "versionName",
|
||||||
"verdict",
|
"verdict",
|
||||||
"webhook", "workflow-type-id", "workflowTypeId"
|
"webhook", "width", "workflow-type-id", "workflowTypeId"
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Registered flags. Unknown flags are rejected.
|
// Registered flags. Unknown flags are rejected.
|
||||||
@@ -88,8 +89,8 @@ export const KNOWN_FLAGS = new Set([
|
|||||||
"V", "access-token", "accessToken", "add", "all", "app-key",
|
"V", "access-token", "accessToken", "add", "all", "app-key",
|
||||||
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
|
||||||
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
|
||||||
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only",
|
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
|
||||||
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
|
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
|
||||||
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
|
||||||
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
|
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
|
||||||
"default", "departmentId", "dept", "desc", "description", "description-file",
|
"default", "departmentId", "dept", "desc", "description", "description-file",
|
||||||
@@ -137,7 +138,7 @@ export const KNOWN_FLAGS = new Set([
|
|||||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
||||||
"until", "url", "userId", "v", "version", "version-name",
|
"until", "url", "userId", "v", "version", "version-name",
|
||||||
"verdict",
|
"verdict",
|
||||||
"versionName", "wait", "webhook", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
"versionName", "wait", "webhook", "width", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||||
"workspace", "yes"
|
"workspace", "yes"
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -168,6 +169,7 @@ export function parseArgs(argv: string[]): ParsedArgs {
|
|||||||
const eqIdx = raw.indexOf("=");
|
const eqIdx = raw.indexOf("=");
|
||||||
const key = raw.slice(0, eqIdx);
|
const key = raw.slice(0, eqIdx);
|
||||||
const val = raw.slice(eqIdx + 1);
|
const val = raw.slice(eqIdx + 1);
|
||||||
|
if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。");
|
||||||
options[key] = val;
|
options[key] = val;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -437,6 +439,42 @@ export function materialPackFilePolicyOptions(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read an `--expire` literal through the shared tokenizer, raising the two
|
||||||
|
* usage errors both link flags share. The format hint differs per flag only in
|
||||||
|
* which example it recommends.
|
||||||
|
*/
|
||||||
|
function readExpireToken(
|
||||||
|
value: string | boolean | number,
|
||||||
|
options: { formatHint: string; unitlessHint?: string }
|
||||||
|
): DurationToken {
|
||||||
|
if (typeof value === "number") {
|
||||||
|
if (!Number.isFinite(value) || value <= 0) {
|
||||||
|
throw usageError(
|
||||||
|
`Invalid --expire: ${value}。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const token = tokenizeDuration(value, { units: EXPIRE_UNITS });
|
||||||
|
if (!token) throw usageError(`Invalid --expire: ${value}。`);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
throw usageError(`Invalid --expire: ${String(value)}。`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = tokenizeDuration(value, { units: EXPIRE_UNITS });
|
||||||
|
if (!token) {
|
||||||
|
throw usageError(`Invalid --expire: '${value}'。必须为有效时长格式${options.formatHint}`);
|
||||||
|
}
|
||||||
|
if (token.value <= 0) {
|
||||||
|
throw usageError(
|
||||||
|
`Invalid --expire: '${value}'。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
export function parseDelegationExpireHours(
|
export function parseDelegationExpireHours(
|
||||||
value: string | boolean | number | undefined,
|
value: string | boolean | number | undefined,
|
||||||
defaultHours = 24
|
defaultHours = 24
|
||||||
@@ -444,80 +482,30 @@ export function parseDelegationExpireHours(
|
|||||||
if (value === undefined || value === null || value === "") {
|
if (value === undefined || value === null || value === "") {
|
||||||
return defaultHours;
|
return defaultHours;
|
||||||
}
|
}
|
||||||
let rawHours: number;
|
|
||||||
let isFractionalOrTruncated = false;
|
|
||||||
|
|
||||||
if (typeof value === "number") {
|
const token = readExpireToken(value, {
|
||||||
if (!Number.isFinite(value) || value <= 0) {
|
formatHint: ",推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)",
|
||||||
throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`);
|
unitlessHint: ",推荐使用 '7d' 或 '24h'"
|
||||||
}
|
});
|
||||||
if (value > 168) {
|
|
||||||
rawHours = value / 3600;
|
|
||||||
if (value % 3600 !== 0) isFractionalOrTruncated = true;
|
|
||||||
} else {
|
|
||||||
rawHours = value;
|
|
||||||
if (!Number.isInteger(value)) isFractionalOrTruncated = true;
|
|
||||||
}
|
|
||||||
} else if (typeof value === "string") {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
const match = trimmed.match(
|
|
||||||
/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i
|
|
||||||
);
|
|
||||||
if (!match || !match[1]) {
|
|
||||||
throw usageError(
|
|
||||||
`Invalid --expire: '${value}'。必须为有效时长格式,推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)。`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const val = parseFloat(match[1]);
|
|
||||||
if (!Number.isFinite(val) || val <= 0) {
|
|
||||||
throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长,推荐使用 '7d' 或 '24h'。`);
|
|
||||||
}
|
|
||||||
const unit = (match[2] ?? "").toLowerCase();
|
|
||||||
|
|
||||||
if (!unit) {
|
|
||||||
if (val > 168) {
|
|
||||||
rawHours = val / 3600;
|
|
||||||
if (val % 3600 !== 0) isFractionalOrTruncated = true;
|
|
||||||
} else {
|
|
||||||
rawHours = val;
|
|
||||||
if (!Number.isInteger(val)) isFractionalOrTruncated = true;
|
|
||||||
}
|
|
||||||
} else if (unit.startsWith("d")) {
|
|
||||||
rawHours = val * 24;
|
|
||||||
if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true;
|
|
||||||
} else if (unit.startsWith("h")) {
|
|
||||||
rawHours = val;
|
|
||||||
if (!Number.isInteger(rawHours)) isFractionalOrTruncated = true;
|
|
||||||
} else if (unit.startsWith("m")) {
|
|
||||||
rawHours = val / 60;
|
|
||||||
if (val % 60 !== 0) isFractionalOrTruncated = true;
|
|
||||||
} else if (unit.startsWith("s")) {
|
|
||||||
rawHours = val / 3600;
|
|
||||||
if (val % 3600 !== 0) isFractionalOrTruncated = true;
|
|
||||||
} else {
|
|
||||||
rawHours = val;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw usageError(`Invalid --expire: ${String(value)}。`);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Seal delegation links are hourly and capped at 7 days.
|
||||||
|
const rawHours = expireSeconds(token) / 3600;
|
||||||
if (rawHours > 168) {
|
if (rawHours > 168) {
|
||||||
throw usageError(
|
throw usageError(
|
||||||
`Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。`
|
`Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let finalHours = Math.floor(rawHours);
|
const finalHours = Math.floor(rawHours);
|
||||||
|
|
||||||
if (finalHours < 1) {
|
if (finalHours < 1) {
|
||||||
finalHours = 1;
|
|
||||||
console.error(
|
console.error(
|
||||||
`👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。`
|
`👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。`
|
||||||
);
|
);
|
||||||
return finalHours;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isFractionalOrTruncated) {
|
if (!Number.isInteger(rawHours)) {
|
||||||
console.error(
|
console.error(
|
||||||
`👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。`
|
`👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。`
|
||||||
);
|
);
|
||||||
@@ -533,60 +521,20 @@ export function parseHoseExpireSeconds(
|
|||||||
if (value === undefined || value === null || value === "") {
|
if (value === undefined || value === null || value === "") {
|
||||||
return defaultSeconds;
|
return defaultSeconds;
|
||||||
}
|
}
|
||||||
let seconds: number;
|
|
||||||
if (typeof value === "number") {
|
|
||||||
if (!Number.isFinite(value) || value <= 0) {
|
|
||||||
throw usageError(`Invalid --expire: ${value}。必须为大于 0 的有效时长。`);
|
|
||||||
}
|
|
||||||
if (value <= 168) {
|
|
||||||
seconds = Math.round(value * 3600);
|
|
||||||
console.error(
|
|
||||||
`👉 提示: 检测到未加单位的数值 ${value},已按 ${value} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${value}h。`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
seconds = Math.round(value);
|
|
||||||
}
|
|
||||||
} else if (typeof value === "string") {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
const match = trimmed.match(
|
|
||||||
/^(\d+(?:\.\d+)?)\s*(d|day|days|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?$/i
|
|
||||||
);
|
|
||||||
if (!match || !match[1]) {
|
|
||||||
throw usageError(
|
|
||||||
`Invalid --expire: '${value}'。必须为有效时长,推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)。`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const val = parseFloat(match[1]);
|
|
||||||
if (!Number.isFinite(val) || val <= 0) {
|
|
||||||
throw usageError(`Invalid --expire: '${value}'。必须为大于 0 的有效时长。`);
|
|
||||||
}
|
|
||||||
const unit = (match[2] ?? "").toLowerCase();
|
|
||||||
|
|
||||||
if (!unit) {
|
const token = readExpireToken(value, {
|
||||||
if (val <= 168) {
|
formatHint: ",推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)"
|
||||||
seconds = Math.round(val * 3600);
|
});
|
||||||
console.error(
|
|
||||||
`👉 提示: 检测到未加单位的数值 ${value},已按 ${val} 小时 (${seconds}s) 自动换算。建议明确使用 --expire ${val}h。`
|
// A bare number is ambiguous: <=168 is read as hours, larger as seconds.
|
||||||
);
|
if (token.unit === undefined && token.value <= 168) {
|
||||||
} else {
|
console.error(
|
||||||
seconds = Math.round(val);
|
`👉 提示: 检测到未加单位的数值 ${token.value},已按 ${token.value} 小时 (${Math.round(token.value * 3600)}s) 自动换算。建议明确使用 --expire ${token.value}h。`
|
||||||
}
|
);
|
||||||
} else if (unit.startsWith("d")) {
|
|
||||||
seconds = Math.round(val * 86400);
|
|
||||||
} else if (unit.startsWith("h")) {
|
|
||||||
seconds = Math.round(val * 3600);
|
|
||||||
} else if (unit.startsWith("m")) {
|
|
||||||
seconds = Math.round(val * 60);
|
|
||||||
} else if (unit.startsWith("s")) {
|
|
||||||
seconds = Math.round(val);
|
|
||||||
} else {
|
|
||||||
seconds = Math.round(val);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw usageError(`Invalid --expire: ${String(value)}。`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (seconds <= 0) {
|
const seconds = Math.round(expireSeconds(token));
|
||||||
|
if (!Number.isFinite(seconds) || seconds <= 0) {
|
||||||
throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`);
|
throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`);
|
||||||
}
|
}
|
||||||
return seconds;
|
return seconds;
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ describe("CLI read-only classification", () => {
|
|||||||
"auth status",
|
"auth status",
|
||||||
"auth test",
|
"auth test",
|
||||||
"auth doctor",
|
"auth doctor",
|
||||||
|
"auth seal-link list",
|
||||||
"doctor auth"
|
"doctor auth"
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -134,21 +135,34 @@ describe("CLI read-only classification", () => {
|
|||||||
expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false);
|
expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("allows rules push status / --check as read-only while refusing mutating rules push forms", () => {
|
||||||
|
expect(isReadOnlyCliCommand(["rules", "push", "status", "--corp", "corp-a"])).toBe(true);
|
||||||
|
expect(isReadOnlyCliCommand(["rules", "push", "--check", "--corp", "corp-a"])).toBe(true);
|
||||||
|
expect(isReadOnlyCliCommand(["rules", "push", "--corp", "corp-a"])).toBe(false);
|
||||||
|
expect(isReadOnlyCliCommand(["rules", "push", "status", "--yes", "--corp", "corp-a"])).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
test("refuses command lines that cannot be parsed", () => {
|
test("refuses command lines that cannot be parsed", () => {
|
||||||
expect(isReadOnlyCliCommand(["--json"])).toBe(false);
|
expect(isReadOnlyCliCommand(["--json"])).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// The two classifications are maintained by hand, in different files: the CLI allow-list here and
|
// The two classifications are maintained in different files: the CLI allow-list here and
|
||||||
// SEAL_READ_ONLY_CAPABILITIES in the tool registry. Nothing stopped them from disagreeing, and they did —
|
// SEAL_READ_ONLY_CAPABILITIES in the tool registry. Nothing stopped them from disagreeing, and they did —
|
||||||
// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs
|
// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs
|
||||||
// were simply missing. This derives one from the other and fails on any new disagreement.
|
// were simply missing. This scans both `runCapability` and `runCapabilityResult` and fails on any disagreement.
|
||||||
describe("CLI allow-list agrees with the tool registry", () => {
|
describe("CLI allow-list agrees with the tool registry", () => {
|
||||||
// `deploy` only accepts `deploy hosecloud <action>`; the short `deploy <action>` form throws
|
// `deploy` only accepts `deploy hosecloud <action>`; the short `deploy <action>` form throws
|
||||||
// "未知的发布目标系统" at runtime, so these pairs are unreachable rather than refused.
|
// "未知的发布目标系统" at runtime. `auth seal-link` only calls `sealDelegationList` when the
|
||||||
const UNREACHABLE_CLI_FORMS = new Set(["deploy requirements", "deploy list", "deploy status"]);
|
// third token `list` is present (`auth seal-link list`); bare `auth seal-link` mints a token.
|
||||||
|
const UNREACHABLE_CLI_FORMS = new Set([
|
||||||
|
"deploy requirements",
|
||||||
|
"deploy list",
|
||||||
|
"deploy status",
|
||||||
|
"auth seal-link"
|
||||||
|
]);
|
||||||
|
|
||||||
test("every CLI verb dispatching to a read-only tool is itself read-only", () => {
|
test("every CLI verb dispatching to a read-only tool is itself read-only, and mutating tools are not read-only", () => {
|
||||||
const files = readdirSync(join(import.meta.dir, "commands")).filter(
|
const files = readdirSync(join(import.meta.dir, "commands")).filter(
|
||||||
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
|
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
|
||||||
);
|
);
|
||||||
@@ -157,7 +171,8 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
|||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
const area = file.replace(/\.ts$/, "");
|
const area = file.replace(/\.ts$/, "");
|
||||||
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
|
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
|
||||||
const pattern = /action === "([a-z0-9-]+)"[\s\S]{0,600}?runCapability\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
|
const pattern =
|
||||||
|
/if\s*\(\s*action === "([a-z0-9-]+)"(?:(?!\bif\s*\(\s*action\b)[\s\S]){0,600}?runCapability(?:Result)?\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
|
||||||
let match;
|
let match;
|
||||||
while ((match = pattern.exec(source))) {
|
while ((match = pattern.exec(source))) {
|
||||||
pairs.push({ area, action: match[1]!, tool: match[2]! });
|
pairs.push({ area, action: match[1]!, tool: match[2]! });
|
||||||
@@ -165,7 +180,7 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If the dispatch shape changes this silently finds nothing, which would make the test vacuous.
|
// If the dispatch shape changes this silently finds nothing, which would make the test vacuous.
|
||||||
expect(pairs.length).toBeGreaterThan(50);
|
expect(pairs.length).toBeGreaterThan(55);
|
||||||
|
|
||||||
const disagreements = pairs
|
const disagreements = pairs
|
||||||
.filter((pair) => SEAL_READ_ONLY_CAPABILITIES.has(pair.tool))
|
.filter((pair) => SEAL_READ_ONLY_CAPABILITIES.has(pair.tool))
|
||||||
@@ -174,5 +189,12 @@ describe("CLI allow-list agrees with the tool registry", () => {
|
|||||||
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
|
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
|
||||||
|
|
||||||
expect(disagreements).toEqual([]);
|
expect(disagreements).toEqual([]);
|
||||||
|
|
||||||
|
const unsafeMutating = pairs
|
||||||
|
.filter((pair) => SEAL_MUTATING_CAPABILITIES.has(pair.tool))
|
||||||
|
.filter((pair) => isReadOnlyCliCommand([pair.area, pair.action]))
|
||||||
|
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
|
||||||
|
|
||||||
|
expect(unsafeMutating).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
+18
-3
@@ -37,6 +37,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
|||||||
"count",
|
"count",
|
||||||
"export",
|
"export",
|
||||||
"flow",
|
"flow",
|
||||||
|
"hose-flow",
|
||||||
"list",
|
"list",
|
||||||
// `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry.
|
// `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry.
|
||||||
"search",
|
"search",
|
||||||
@@ -68,8 +69,8 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
|||||||
// read forms cannot be separated from the value-taking write forms. `config get` returns
|
// read forms cannot be separated from the value-taking write forms. `config get` returns
|
||||||
// the same summary (mode + lint included), so read access loses nothing.
|
// the same summary (mode + lint included), so read access loses nothing.
|
||||||
config: ["paths", "get"],
|
config: ["paths", "get"],
|
||||||
auth: ["check", "diagnose", "status", "test", "doctor", "link list"],
|
auth: ["check", "diagnose", "status", "test", "doctor", "link list", "seal-link list"],
|
||||||
users: ["search", "get", "delegation"],
|
users: ["search", "get"],
|
||||||
contacts: ["departments", "children", "users", "sync-time"],
|
contacts: ["departments", "children", "users", "sync-time"],
|
||||||
data: ["expenses", "invoices"],
|
data: ["expenses", "invoices"],
|
||||||
llm: ["config", "providers"],
|
llm: ["config", "providers"],
|
||||||
@@ -78,7 +79,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
|||||||
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
|
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
|
||||||
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
|
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
|
||||||
analytics: ["insight", "risks", "performance", "export"],
|
analytics: ["insight", "risks", "performance", "export"],
|
||||||
report: ["monthly", "review list"],
|
report: ["monthly", "validate", "render", "review list"],
|
||||||
source: ["config"],
|
source: ["config"],
|
||||||
skill: ["dump", "status"],
|
skill: ["dump", "status"],
|
||||||
doctor: ["", "guide", "paths", "tenant", "auth"],
|
doctor: ["", "guide", "paths", "tenant", "auth"],
|
||||||
@@ -126,7 +127,10 @@ export function describeCliCommand(argv: string[]): { area: string; actionTokens
|
|||||||
export function isReadOnlyCliCommand(argv: string[]): boolean {
|
export function isReadOnlyCliCommand(argv: string[]): boolean {
|
||||||
let area: string;
|
let area: string;
|
||||||
let actionTokens: string[];
|
let actionTokens: string[];
|
||||||
|
let options: Record<string, unknown>;
|
||||||
try {
|
try {
|
||||||
|
const parsed = parseArgs(argv);
|
||||||
|
options = parsed.options;
|
||||||
({ area, actionTokens } = describeCliCommand(argv));
|
({ area, actionTokens } = describeCliCommand(argv));
|
||||||
} catch {
|
} catch {
|
||||||
// Unparsable command lines are refused rather than guessed at.
|
// Unparsable command lines are refused rather than guessed at.
|
||||||
@@ -136,6 +140,17 @@ export function isReadOnlyCliCommand(argv: string[]): boolean {
|
|||||||
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
|
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
|
||||||
// The `<corpId>` selector form; the bare form falls through to the `""` entry.
|
// The `<corpId>` selector form; the bare form falls through to the `""` entry.
|
||||||
if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true;
|
if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true;
|
||||||
|
// `rules push status` / `rules push --check` inspects the recovery journal and
|
||||||
|
// reconciles against the remote draft without mutating anything.
|
||||||
|
if (
|
||||||
|
area === "rules" &&
|
||||||
|
actionTokens[0] === "push" &&
|
||||||
|
(actionTokens[1] === "status" || options.check === true || options.status === "true") &&
|
||||||
|
!options.yes &&
|
||||||
|
!options.confirm
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
const allowed = READ_ONLY_COMMANDS[area];
|
const allowed = READ_ONLY_COMMANDS[area];
|
||||||
if (!allowed) return false;
|
if (!allowed) return false;
|
||||||
|
|||||||
@@ -224,6 +224,11 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (area === "report" && (action === "validate" || action === "render" || action === "export")) {
|
||||||
|
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Langfuse trace inspection needs no tenant: it authenticates with the
|
// Langfuse trace inspection needs no tenant: it authenticates with the
|
||||||
// compile-time injected read-only key pair, so it dispatches before corp
|
// compile-time injected read-only key pair, so it dispatches before corp
|
||||||
// selection (like probe/doctor) and never touches a Seal client.
|
// selection (like probe/doctor) and never touches a Seal client.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
import { homedir } from "node:os";
|
import { SEAL_CONFIG_DIR } from "../paths.js";
|
||||||
import {
|
import {
|
||||||
CorpTokenCache,
|
CorpTokenCache,
|
||||||
HoseAuthCache,
|
HoseAuthCache,
|
||||||
@@ -9,14 +9,14 @@ import {
|
|||||||
TokenStoreSchema
|
TokenStoreSchema
|
||||||
} from "./types.js";
|
} from "./types.js";
|
||||||
|
|
||||||
const PRIMARY_TOKEN_STORE = join(homedir(), ".config", "seal-use", "sealTokens.json");
|
const PRIMARY_TOKEN_STORE = join(SEAL_CONFIG_DIR, "tokens.json");
|
||||||
const LEGACY_TOKEN_STORE = join(homedir(), ".config", "seal-home", "sealTokens.json");
|
const MIGRATION_TOKEN_STORE = join(SEAL_CONFIG_DIR, "sealTokens.json");
|
||||||
|
|
||||||
function resolveReadStorePath(): string {
|
function resolveReadStorePath(): string {
|
||||||
const configured = (process.env.SEAL_USE_TOKEN_STORE ?? process.env.SEAL_HOME_TOKEN_STORE)?.trim();
|
const configured = (process.env.SEAL_USE_TOKEN_STORE ?? process.env.SEAL_HOME_TOKEN_STORE)?.trim();
|
||||||
if (configured) return configured;
|
if (configured) return configured;
|
||||||
if (existsSync(PRIMARY_TOKEN_STORE)) return PRIMARY_TOKEN_STORE;
|
if (existsSync(PRIMARY_TOKEN_STORE)) return PRIMARY_TOKEN_STORE;
|
||||||
if (existsSync(LEGACY_TOKEN_STORE)) return LEGACY_TOKEN_STORE;
|
if (existsSync(MIGRATION_TOKEN_STORE)) return MIGRATION_TOKEN_STORE;
|
||||||
return PRIMARY_TOKEN_STORE;
|
return PRIMARY_TOKEN_STORE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { resolveTargetBinaryPath } from "../../scripts/dev-override.js";
|
||||||
|
|
||||||
|
describe("development CLI install target", () => {
|
||||||
|
test("npm-linked source is never selected as the binary replacement target", () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "seal-dev-target-test-"));
|
||||||
|
const originalPath = process.env.PATH;
|
||||||
|
try {
|
||||||
|
const command = join(dir, "seal-use");
|
||||||
|
const source = join(dir, "cli.ts");
|
||||||
|
writeFileSync(source, "#!/usr/bin/env bun\nconsole.log('source fixture')\n");
|
||||||
|
chmodSync(source, 0o755);
|
||||||
|
symlinkSync(source, command);
|
||||||
|
process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${originalPath ?? ""}`;
|
||||||
|
expect(resolveTargetBinaryPath()).toBe(command);
|
||||||
|
expect(readFileSync(source, "utf8")).toContain("source fixture");
|
||||||
|
} finally {
|
||||||
|
if (originalPath === undefined) delete process.env.PATH; else process.env.PATH = originalPath;
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("native command symlinks continue to replace the installed target", () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "seal-dev-target-test-"));
|
||||||
|
const originalPath = process.env.PATH;
|
||||||
|
try {
|
||||||
|
const command = join(dir, "seal-use");
|
||||||
|
mkdirSync(join(dir, "formula"));
|
||||||
|
const target = join(dir, "formula", "seal-use");
|
||||||
|
writeFileSync(target, "native binary fixture");
|
||||||
|
chmodSync(target, 0o755);
|
||||||
|
symlinkSync(target, command);
|
||||||
|
process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${originalPath ?? ""}`;
|
||||||
|
expect(resolveTargetBinaryPath()).toBe(realpathSync(target));
|
||||||
|
} finally {
|
||||||
|
if (originalPath === undefined) delete process.env.PATH; else process.env.PATH = originalPath;
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -112,20 +112,24 @@ function findGroupOrWorldReadable(paths: string[]): string[] {
|
|||||||
export function diagnoseSystem(): DoctorDiagnosis {
|
export function diagnoseSystem(): DoctorDiagnosis {
|
||||||
const home = homedir();
|
const home = homedir();
|
||||||
const configDir = join(home, ".config", "seal-use");
|
const configDir = join(home, ".config", "seal-use");
|
||||||
|
const stateDir = join(configDir, "state");
|
||||||
const enterprisesDir = join(configDir, "enterprises");
|
const enterprisesDir = join(configDir, "enterprises");
|
||||||
const globalConfigFile = join(configDir, "config.json");
|
const globalConfigFile = join(configDir, "config.json");
|
||||||
const tokenStore = join(configDir, "sealTokens.json");
|
const tokenStore = existsSync(join(configDir, "tokens.json"))
|
||||||
const mappingsDir = join(configDir, "mappings");
|
? join(configDir, "tokens.json")
|
||||||
|
: existsSync(join(configDir, "sealTokens.json"))
|
||||||
|
? join(configDir, "sealTokens.json")
|
||||||
|
: join(configDir, "tokens.json");
|
||||||
|
const mappingsDir = existsSync(join(stateDir, "mappings")) ? join(stateDir, "mappings") : join(configDir, "mappings");
|
||||||
const agentSkillDir = getDefaultGlobalSkillDir();
|
const agentSkillDir = getDefaultGlobalSkillDir();
|
||||||
const exportDir = join(home, "Downloads");
|
const exportDir = join(home, "Downloads");
|
||||||
|
|
||||||
const globalBinaryCandidates = [
|
const globalBinaryCandidates = [
|
||||||
"/opt/homebrew/bin/seal-use",
|
|
||||||
"/usr/local/bin/seal-use",
|
"/usr/local/bin/seal-use",
|
||||||
join(home, ".local", "bin", "seal-use"),
|
join(home, ".local", "bin", "seal-use"),
|
||||||
join(home, "bin", "seal-use")
|
join(home, "bin", "seal-use")
|
||||||
];
|
];
|
||||||
const detectedBinary = globalBinaryCandidates.find((p) => existsSync(p)) ?? process.execPath;
|
const detectedBinary = Bun.which("seal-use") ?? globalBinaryCandidates.find((p) => existsSync(p)) ?? process.execPath;
|
||||||
|
|
||||||
const directories: Record<string, DirectoryHealth> = {
|
const directories: Record<string, DirectoryHealth> = {
|
||||||
configDir: {
|
configDir: {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
|
|
||||||
export interface DirectorySpec {
|
export interface DirectorySpec {
|
||||||
name: string;
|
name: string;
|
||||||
category: "config" | "binary" | "skill" | "export" | "temp";
|
category: "config" | "binary" | "skill" | "export" | "temp" | "cache";
|
||||||
standardPath: string;
|
standardPath: string;
|
||||||
purpose: string;
|
purpose: string;
|
||||||
accessMode: "read-write" | "executable" | "transient";
|
accessMode: "read-write" | "executable" | "transient";
|
||||||
@@ -55,23 +55,31 @@ export const EMBEDDED_DIRECTORY_SPECS: DirectorySpec[] = [
|
|||||||
{
|
{
|
||||||
name: "会话凭据安全缓存",
|
name: "会话凭据安全缓存",
|
||||||
category: "config",
|
category: "config",
|
||||||
standardPath: "~/.config/seal-use/sealTokens.json",
|
standardPath: "~/.config/seal-use/tokens.json",
|
||||||
purpose: "缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",
|
purpose: "缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",
|
||||||
accessMode: "read-write",
|
accessMode: "read-write",
|
||||||
retention: "cache"
|
retention: "cache"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "规则版本映射快照",
|
name: "业务持久状态目录",
|
||||||
category: "config",
|
category: "config",
|
||||||
standardPath: "~/.config/seal-use/mappings",
|
standardPath: "~/.config/seal-use/state",
|
||||||
purpose: "存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",
|
purpose: "业务持久状态统一子目录,存放规则映射对照(mappings)、发布快照(snapshots)与人工复核账本(reviews)。",
|
||||||
accessMode: "read-write",
|
accessMode: "read-write",
|
||||||
retention: "persistent"
|
retention: "persistent"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "运行时缓存根目录",
|
||||||
|
category: "cache",
|
||||||
|
standardPath: "~/.cache/seal-use",
|
||||||
|
purpose: "用户本地运行时缓存目录,存放版本检测缓存、打点度量、官方只读校验器及报告离线资源,可随时安全清理。",
|
||||||
|
accessMode: "read-write",
|
||||||
|
retention: "cache"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "全局命令行程序",
|
name: "全局命令行程序",
|
||||||
category: "binary",
|
category: "binary",
|
||||||
standardPath: "/opt/homebrew/bin/seal-use",
|
standardPath: "/usr/local/bin/seal-use",
|
||||||
purpose: "macOS / Linux 全局独立单文件二进制程序;旧版 seal-home 命令仅保留解析兼容,不再新建全局别名。",
|
purpose: "macOS / Linux 全局独立单文件二进制程序;旧版 seal-home 命令仅保留解析兼容,不再新建全局别名。",
|
||||||
accessMode: "executable",
|
accessMode: "executable",
|
||||||
retention: "persistent"
|
retention: "persistent"
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import {
|
||||||
|
durationSeconds,
|
||||||
|
expireSeconds,
|
||||||
|
parseDurationMs,
|
||||||
|
tokenizeDuration
|
||||||
|
} from "./duration.js";
|
||||||
|
|
||||||
|
describe("tokenizeDuration", () => {
|
||||||
|
test("splits magnitude from unit and accepts every alias", () => {
|
||||||
|
expect(tokenizeDuration("7d")).toEqual({ value: 7, unit: "d" });
|
||||||
|
expect(tokenizeDuration("24h")).toEqual({ value: 24, unit: "h" });
|
||||||
|
expect(tokenizeDuration("90m")).toEqual({ value: 90, unit: "m" });
|
||||||
|
expect(tokenizeDuration("7200s")).toEqual({ value: 7200, unit: "s" });
|
||||||
|
expect(tokenizeDuration("1.5h")).toEqual({ value: 1.5, unit: "h" });
|
||||||
|
expect(tokenizeDuration("2 hours")).toEqual({ value: 2, unit: "h" });
|
||||||
|
expect(tokenizeDuration("500ms")).toEqual({ value: 500, unit: "ms" });
|
||||||
|
expect(tokenizeDuration(" 300 ")).toEqual({ value: 300, unit: undefined });
|
||||||
|
expect(tokenizeDuration(168)).toEqual({ value: 168, unit: undefined });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects unparseable input instead of guessing", () => {
|
||||||
|
expect(tokenizeDuration("invalid")).toBeUndefined();
|
||||||
|
expect(tokenizeDuration("")).toBeUndefined();
|
||||||
|
expect(tokenizeDuration("-5m")).toBeUndefined();
|
||||||
|
expect(tokenizeDuration("5parsecs")).toBeUndefined();
|
||||||
|
expect(tokenizeDuration(Number.NaN)).toBeUndefined();
|
||||||
|
expect(tokenizeDuration(true as unknown as string)).toBeUndefined();
|
||||||
|
expect(tokenizeDuration("9".repeat(309))).toBeUndefined();
|
||||||
|
expect(tokenizeDuration("9".repeat(309) + "s")).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("expireSeconds", () => {
|
||||||
|
test("reads a unitless number at most 168 as hours and a larger one as seconds", () => {
|
||||||
|
// Both --expire paths used to reimplement this rule separately, and they
|
||||||
|
// disagreed at the boundary; 300 now means 5 minutes everywhere.
|
||||||
|
expect(expireSeconds({ value: 168, unit: undefined })).toBe(168 * 3600);
|
||||||
|
expect(expireSeconds({ value: 169, unit: undefined })).toBe(169);
|
||||||
|
expect(expireSeconds({ value: 300, unit: undefined })).toBe(300);
|
||||||
|
expect(expireSeconds({ value: 86400, unit: undefined })).toBe(86_400);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("converts explicit units regardless of magnitude", () => {
|
||||||
|
expect(expireSeconds({ value: 7, unit: "d" })).toBe(604_800);
|
||||||
|
expect(expireSeconds({ value: 7200, unit: "s" })).toBe(7200);
|
||||||
|
expect(expireSeconds({ value: 30, unit: "m" })).toBe(1800);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("durationSeconds", () => {
|
||||||
|
test("uses the caller's unitless policy when none is written", () => {
|
||||||
|
expect(durationSeconds({ value: 5, unit: undefined }, "s")).toBe(5);
|
||||||
|
expect(durationSeconds({ value: 5, unit: undefined }, "h")).toBe(18_000);
|
||||||
|
expect(durationSeconds({ value: 5, unit: "ms" }, "h")).toBe(0.005);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parseDurationMs", () => {
|
||||||
|
test("converts simulation windows to milliseconds", () => {
|
||||||
|
expect(parseDurationMs("2s")).toBe(2000);
|
||||||
|
expect(parseDurationMs("10m")).toBe(600_000);
|
||||||
|
expect(parseDurationMs("5m")).toBe(300_000);
|
||||||
|
expect(parseDurationMs("500ms")).toBe(500);
|
||||||
|
expect(parseDurationMs("1h")).toBe(3_600_000);
|
||||||
|
expect(parseDurationMs("1d")).toBe(86_400_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reads unitless input as seconds, matching the flag's defaults", () => {
|
||||||
|
expect(parseDurationMs("30")).toBe(30_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("falls back rather than failing a batch over a bad poll interval", () => {
|
||||||
|
expect(parseDurationMs("soon")).toBe(600_000);
|
||||||
|
expect(parseDurationMs("soon", 1000)).toBe(1000);
|
||||||
|
expect(parseDurationMs("9".repeat(309) + "s", 1000)).toBe(1000);
|
||||||
|
expect(parseDurationMs("9".repeat(308) + "d", 1000)).toBe(1000);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
/**
|
||||||
|
* Duration tokenizing shared by every flag that accepts `7d` / `1.5h` / `300`.
|
||||||
|
*
|
||||||
|
* The tokenizer owns exactly one job: turning the written form into a magnitude
|
||||||
|
* plus a canonical unit. Interpretation stays with each caller, because the
|
||||||
|
* three consumers genuinely disagree — Seal delegation links take whole hours
|
||||||
|
* in 1..168, Hose assistance links take seconds, simulation windows take
|
||||||
|
* milliseconds. Sharing the grammar (and the unitless heuristic) is what stops
|
||||||
|
* `--expire 300` from parsing two different ways in two files.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type DurationUnit = "ms" | "s" | "m" | "h" | "d";
|
||||||
|
|
||||||
|
export interface DurationToken {
|
||||||
|
/** The magnitude exactly as written, before any unit conversion. */
|
||||||
|
value: number;
|
||||||
|
/** `undefined` when the input carried no unit, e.g. `300`. */
|
||||||
|
unit: DurationUnit | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const UNIT_ALIASES: Record<string, DurationUnit> = {
|
||||||
|
ms: "ms",
|
||||||
|
s: "s",
|
||||||
|
sec: "s",
|
||||||
|
secs: "s",
|
||||||
|
second: "s",
|
||||||
|
seconds: "s",
|
||||||
|
m: "m",
|
||||||
|
min: "m",
|
||||||
|
mins: "m",
|
||||||
|
minute: "m",
|
||||||
|
minutes: "m",
|
||||||
|
h: "h",
|
||||||
|
hr: "h",
|
||||||
|
hrs: "h",
|
||||||
|
hour: "h",
|
||||||
|
hours: "h",
|
||||||
|
d: "d",
|
||||||
|
day: "d",
|
||||||
|
days: "d"
|
||||||
|
};
|
||||||
|
|
||||||
|
const DURATION_PATTERN = /^(\d+(?:\.\d+)?)\s*([a-z]+)?$/i;
|
||||||
|
|
||||||
|
export interface TokenizeDurationOptions {
|
||||||
|
/**
|
||||||
|
* Units this caller accepts. Restricting the set keeps a shared tokenizer
|
||||||
|
* from quietly widening a flag's grammar: sub-second input was a usage error
|
||||||
|
* for `--expire` before the parsers were unified, and must stay one.
|
||||||
|
*/
|
||||||
|
units?: readonly DurationUnit[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a duration literal. Returns `undefined` when the input cannot be read
|
||||||
|
* at all — callers decide whether that is a usage error or a default.
|
||||||
|
*
|
||||||
|
* A unitless number keeps whatever magnitude it had; pair it with
|
||||||
|
* {@link expireSeconds} or an explicit `unitless` argument to resolve it.
|
||||||
|
*/
|
||||||
|
export function tokenizeDuration(
|
||||||
|
value: string | number,
|
||||||
|
options: TokenizeDurationOptions = {}
|
||||||
|
): DurationToken | undefined {
|
||||||
|
if (typeof value === "number") {
|
||||||
|
return Number.isFinite(value) ? { value, unit: undefined } : undefined;
|
||||||
|
}
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const match = value.trim().match(DURATION_PATTERN);
|
||||||
|
if (!match || !match[1]) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const magnitude = parseFloat(match[1]);
|
||||||
|
if (!Number.isFinite(magnitude)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawUnit = match[2]?.toLowerCase();
|
||||||
|
if (!rawUnit) {
|
||||||
|
return { value: magnitude, unit: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
const unit = UNIT_ALIASES[rawUnit];
|
||||||
|
if (!unit) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (options.units && !options.units.includes(unit)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return { value: magnitude, unit };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Units the `--expire` flags accept. Sub-second precision is meaningless for
|
||||||
|
* an assistance link and was rejected before the parsers were shared.
|
||||||
|
*/
|
||||||
|
export const EXPIRE_UNITS: readonly DurationUnit[] = ["d", "h", "m", "s"];
|
||||||
|
|
||||||
|
/** Convert a token to seconds, resolving a unitless value as `unitless`. */
|
||||||
|
export function durationSeconds(token: DurationToken, unitless: DurationUnit): number {
|
||||||
|
switch (token.unit ?? unitless) {
|
||||||
|
case "ms":
|
||||||
|
return token.value / 1000;
|
||||||
|
case "m":
|
||||||
|
return token.value * 60;
|
||||||
|
case "h":
|
||||||
|
return token.value * 3600;
|
||||||
|
case "d":
|
||||||
|
return token.value * 86400;
|
||||||
|
case "s":
|
||||||
|
default:
|
||||||
|
return token.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unitless `--expire` heuristic shared by the Seal and Hose link flags:
|
||||||
|
* a bare number at most 168 reads as hours (7 days of them), a larger one
|
||||||
|
* reads as seconds. Without this, `--expire 300` would mean 300 hours on one
|
||||||
|
* path and 5 minutes on another.
|
||||||
|
*/
|
||||||
|
export function expireSeconds(token: DurationToken): number {
|
||||||
|
return durationSeconds(token, token.value <= 168 ? "h" : "s");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Default used by {@link parseDurationMs} when the literal is unreadable. */
|
||||||
|
export const DEFAULT_DURATION_MS = 600_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simulation windows and poll intervals: milliseconds, unitless input read as
|
||||||
|
* seconds, and an unreadable literal falls back to the default instead of
|
||||||
|
* failing the call — a poll interval is not worth aborting a batch over.
|
||||||
|
*/
|
||||||
|
export function parseDurationMs(duration: string, fallbackMs = DEFAULT_DURATION_MS): number {
|
||||||
|
const token = tokenizeDuration(duration);
|
||||||
|
if (!token || token.value < 0) {
|
||||||
|
return fallbackMs;
|
||||||
|
}
|
||||||
|
const milliseconds = Math.round(durationSeconds(token, "s") * 1000);
|
||||||
|
return Number.isFinite(milliseconds) ? milliseconds : fallbackMs;
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ import file19 from "../../skills/seal-use/references/rule-lightweight.md" with {
|
|||||||
import file20 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
import file20 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
|
||||||
import file21 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
import file21 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
|
||||||
import file22 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
import file22 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
|
||||||
|
import file23 from "../domains/seal/reports/templates/README.md" with { type: "text" };
|
||||||
|
|
||||||
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
||||||
"SKILL.md": file0,
|
"SKILL.md": file0,
|
||||||
@@ -42,6 +43,7 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
|
|||||||
"references/rule-lint.md": file20,
|
"references/rule-lint.md": file20,
|
||||||
"references/staging-simulation-workflow.md": file21,
|
"references/staging-simulation-workflow.md": file21,
|
||||||
"references/webhook-resource-pack.md": file22,
|
"references/webhook-resource-pack.md": file22,
|
||||||
|
"references/report-templates.md": file23,
|
||||||
};
|
};
|
||||||
|
|
||||||
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
|
export const EMBEDDED_SKILL_ASSET_DATA: Record<string, string> = {
|
||||||
@@ -77,4 +79,5 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
|
|||||||
"references/rule-lint.md",
|
"references/rule-lint.md",
|
||||||
"references/staging-simulation-workflow.md",
|
"references/staging-simulation-workflow.md",
|
||||||
"references/webhook-resource-pack.md",
|
"references/webhook-resource-pack.md",
|
||||||
|
"references/report-templates.md",
|
||||||
];
|
];
|
||||||
+3
-1
@@ -56,8 +56,10 @@ const USAGE_PREFIX =
|
|||||||
|
|
||||||
// Wording a Chinese-language usage error uses when it names a flag/parameter
|
// 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`.
|
// 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 =
|
const CN_USAGE =
|
||||||
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用|请提供|请重试|请先)/;
|
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用 --|请提供)/;
|
||||||
|
|
||||||
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
|
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
|
||||||
const CORP_SELECTION =
|
const CORP_SELECTION =
|
||||||
|
|||||||
+9
-2
@@ -2,5 +2,12 @@ import { homedir } from "node:os";
|
|||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
|
||||||
export const SEAL_CONFIG_DIR = join(homedir(), ".config", "seal-use");
|
export const SEAL_CONFIG_DIR = join(homedir(), ".config", "seal-use");
|
||||||
export const PRIMARY_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters");
|
export const SEAL_STATE_DIR = join(SEAL_CONFIG_DIR, "state");
|
||||||
export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, "official");
|
export const SEAL_CACHE_DIR = join(homedir(), ".cache", "seal-use");
|
||||||
|
|
||||||
|
/** 用户全局自定义校验器存放目录(属于用户资产,保留在 ~/.config/,防止随缓存被误删) */
|
||||||
|
export const USER_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters");
|
||||||
|
export const PRIMARY_LINTERS_DIR = USER_LINTERS_DIR;
|
||||||
|
|
||||||
|
/** 官方明文下发校验器目录(由 CLI 自动同步与重写,属于只读缓存,归位于 ~/.cache/) */
|
||||||
|
export const OFFICIAL_LINTERS_DIR = join(SEAL_CACHE_DIR, "linters", "official");
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
||||||
import { homedir } from "node:os";
|
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
|
|
||||||
|
import { SEAL_CACHE_DIR } from "../paths.js";
|
||||||
|
|
||||||
export const USAGE_FILE_ENV = "SEAL_USE_USAGE_FILE";
|
export const USAGE_FILE_ENV = "SEAL_USE_USAGE_FILE";
|
||||||
const DEFAULT_USAGE_FILE = join(homedir(), ".config", "seal-use", "usage.json");
|
const DEFAULT_USAGE_FILE = join(SEAL_CACHE_DIR, "usage.json");
|
||||||
const DEFAULT_WINDOW_DAYS = 7;
|
const DEFAULT_WINDOW_DAYS = 7;
|
||||||
|
|
||||||
export type CorpUsageDailyStats = Record<string, number>;
|
export type CorpUsageDailyStats = Record<string, number>;
|
||||||
@@ -66,7 +67,7 @@ function saveUsageStatsAtomic(stats: CorpUsageStats, targetPath: string = resolv
|
|||||||
}
|
}
|
||||||
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`;
|
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2, 8)}.tmp`;
|
||||||
try {
|
try {
|
||||||
// 0o600 like `sealTokens.json`: usage rows name the enterprises this machine has been
|
// 0o600 like `tokens.json`: usage rows name the enterprises this machine has been
|
||||||
// operating, so keep them owner-only instead of inheriting the 0o644 default.
|
// operating, so keep them owner-only instead of inheriting the 0o644 default.
|
||||||
writeFileSync(tempPath, JSON.stringify(stats, null, 2), { encoding: "utf-8", mode: 0o600 });
|
writeFileSync(tempPath, JSON.stringify(stats, null, 2), { encoding: "utf-8", mode: 0o600 });
|
||||||
renameSync(tempPath, targetPath);
|
renameSync(tempPath, targetPath);
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||||
import { homedir } from "node:os";
|
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
import type { LauncherConfig } from "./runtime.js";
|
import type { LauncherConfig } from "./runtime.js";
|
||||||
import { formatBeijingIso, normalizeBeijingIso } from "./config/timestamps.js";
|
import { formatBeijingIso, normalizeBeijingIso } from "./config/timestamps.js";
|
||||||
|
|
||||||
|
import { SEAL_CACHE_DIR } from "./paths.js";
|
||||||
|
|
||||||
export const UPDATE_CACHE_FILE_ENV = "SEAL_USE_UPDATE_CACHE_FILE";
|
export const UPDATE_CACHE_FILE_ENV = "SEAL_USE_UPDATE_CACHE_FILE";
|
||||||
export const DEFAULT_UPDATE_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
export const DEFAULT_UPDATE_CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
|
|
||||||
const DEFAULT_UPDATE_CACHE_FILE = join(homedir(), ".config", "seal-use", "update-cache.json");
|
const DEFAULT_UPDATE_CACHE_FILE = join(SEAL_CACHE_DIR, "update-cache.json");
|
||||||
|
|
||||||
export interface UpdateCacheData {
|
export interface UpdateCacheData {
|
||||||
checkedAt: string;
|
checkedAt: string;
|
||||||
|
|||||||
Vendored
+10
@@ -12,3 +12,13 @@ declare module "*.yml" {
|
|||||||
const content: string;
|
const content: string;
|
||||||
export default content;
|
export default content;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
declare module "*.css" {
|
||||||
|
const content: string;
|
||||||
|
export default content;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module "*.svg" {
|
||||||
|
const content: string;
|
||||||
|
export default content;
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
} from "../../core/auth/delegate.js";
|
} from "../../core/auth/delegate.js";
|
||||||
import { parseHoseAssistLink } from "../../core/auth/hose.js";
|
import { parseHoseAssistLink } from "../../core/auth/hose.js";
|
||||||
import { onboardHoseWebSession } from "../hose/onboarding.js";
|
import { onboardHoseWebSession } from "../hose/onboarding.js";
|
||||||
import { persistSealDelegateSession } from "../seal/onboarding.js";
|
import { persistSealDelegateSession } from "../seal/enterprise/onboarding.js";
|
||||||
|
|
||||||
export type AssistanceLinkOnboardingInput = {
|
export type AssistanceLinkOnboardingInput = {
|
||||||
name?: string;
|
name?: string;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
export * from "./types.js";
|
export * from "./types.js";
|
||||||
export * from "./client.js";
|
export * from "./client.js";
|
||||||
export * from "./api.js";
|
export * from "./api.js";
|
||||||
|
export * from "./outbound.js";
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import type { KyInstance } from "ky";
|
||||||
|
import { validationError } from "../../../core/errors.js";
|
||||||
|
import type { CorpConfig } from "../../../core/config/types.js";
|
||||||
|
import { createHoseCloseClient } from "./client.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single row of the CloseAPI outbound message log. The `request` payload is
|
||||||
|
* the EBot push body, so its fields mirror Seal's `/api/hosecloud/outbound`
|
||||||
|
* contract (flowId / nodeId / messageId / rejectionNum / corporationId).
|
||||||
|
*/
|
||||||
|
export interface HoseOutboundLogItem {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: "INVOKING" | "CALLBACK" | string;
|
||||||
|
state: string;
|
||||||
|
flowId?: {
|
||||||
|
id: string;
|
||||||
|
form?: {
|
||||||
|
code?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
nodeName?: string;
|
||||||
|
createTime: number;
|
||||||
|
messageType?: string;
|
||||||
|
request?: {
|
||||||
|
flowId?: string;
|
||||||
|
nodeId?: string;
|
||||||
|
messageId?: string;
|
||||||
|
rejectionNum?: number;
|
||||||
|
corporationId?: string;
|
||||||
|
action?: string;
|
||||||
|
comment?: string;
|
||||||
|
signKey?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
};
|
||||||
|
response?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query CloseAPI's outbound message log for one document SN (flowId.form.code).
|
||||||
|
*/
|
||||||
|
export async function searchOutboundMessageLogs(
|
||||||
|
client: KyInstance,
|
||||||
|
corpId: string,
|
||||||
|
sn: string
|
||||||
|
): Promise<HoseOutboundLogItem[]> {
|
||||||
|
const response = (await client
|
||||||
|
.post("api/outbound/v1/message/messageLog", {
|
||||||
|
searchParams: {
|
||||||
|
messageType: "flow",
|
||||||
|
corpId
|
||||||
|
},
|
||||||
|
json: {
|
||||||
|
limit: { start: 0, count: 20 },
|
||||||
|
orderBy: [{ value: "createTime", order: "DESC" }],
|
||||||
|
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType",
|
||||||
|
filterBy: `(flowId.form.code==("${sn}"))`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.json()) as { items?: HoseOutboundLogItem[] };
|
||||||
|
|
||||||
|
return response.items ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN.
|
||||||
|
*/
|
||||||
|
export async function fetchHoseOutboundLogs(
|
||||||
|
sourceCorp: CorpConfig,
|
||||||
|
sn: string
|
||||||
|
): Promise<HoseOutboundLogItem[]> {
|
||||||
|
if (sourceCorp.source.type !== "hose") {
|
||||||
|
throw validationError(
|
||||||
|
`源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = await createHoseCloseClient(sourceCorp);
|
||||||
|
return searchOutboundMessageLogs(client, sourceCorp.source.corpId, sn);
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ import { saveCorpConfig, type SavedCorpConfig } from "../../core/config/reposito
|
|||||||
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
|
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../core/config/types.js";
|
||||||
import { getMe } from "../seal/api.js";
|
import { getMe } from "../seal/api.js";
|
||||||
import { resolveLiveSealEnterpriseConfig } from "../seal/source.js";
|
import { resolveLiveSealEnterpriseConfig } from "../seal/enterprise/source.js";
|
||||||
|
|
||||||
export type HosePersistentInput = {
|
export type HosePersistentInput = {
|
||||||
id?: string;
|
id?: string;
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||||
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { DEFAULT_LANGFUSE_CACHE_DIR, LANGFUSE_CACHE_DIR_ENV, TraceCache } from "./cache.js";
|
||||||
|
import type { CachedTrace } from "./types.js";
|
||||||
|
|
||||||
|
const project = { baseUrl: "https://langfuse.test", projectId: "test-project" };
|
||||||
|
const originalCwd = process.cwd();
|
||||||
|
const originalCacheDir = process.env[LANGFUSE_CACHE_DIR_ENV];
|
||||||
|
let dir: string;
|
||||||
|
beforeEach(() => {
|
||||||
|
dir = mkdtempSync(join(tmpdir(), "seal-trace-cache-test-"));
|
||||||
|
process.env[LANGFUSE_CACHE_DIR_ENV] = join(dir, "user-cache");
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
process.chdir(originalCwd);
|
||||||
|
if (originalCacheDir === undefined) delete process.env[LANGFUSE_CACHE_DIR_ENV];
|
||||||
|
else process.env[LANGFUSE_CACHE_DIR_ENV] = originalCacheDir;
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
function legacyEntry(overrides: Record<string, unknown> = {}): string {
|
||||||
|
const cached: CachedTrace = {
|
||||||
|
cacheVersion: 1, cachedAt: "2026-10-01T00:00:00Z",
|
||||||
|
project: { key: "default", ...project }, trace: { id: "trace", projectId: project.projectId, observations: [] }
|
||||||
|
};
|
||||||
|
const file = join(dir, ".cache", "langfuse", "traces", "default", "trace.json");
|
||||||
|
mkdirSync(join(dir, ".cache", "langfuse", "traces", "default"), { recursive: true });
|
||||||
|
writeFileSync(file, JSON.stringify({ ...cached, ...overrides }));
|
||||||
|
process.chdir(dir);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("portable Langfuse cache", () => {
|
||||||
|
test("the default path is independent of cwd without writing to the real user's cache", () => {
|
||||||
|
delete process.env[LANGFUSE_CACHE_DIR_ENV];
|
||||||
|
const first = new TraceCache(project).path("trace");
|
||||||
|
process.chdir(dir);
|
||||||
|
const second = new TraceCache(project).path("trace");
|
||||||
|
expect(first).toBe(join(DEFAULT_LANGFUSE_CACHE_DIR, "default", "trace.json"));
|
||||||
|
expect(second).toBe(first);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a newly created service can read a trace after changing directories", async () => {
|
||||||
|
const first = new TraceCache(project);
|
||||||
|
await first.write("trace", { id: "trace", projectId: project.projectId, observations: [] });
|
||||||
|
const elsewhere = join(dir, "elsewhere");
|
||||||
|
mkdirSync(elsewhere);
|
||||||
|
process.chdir(elsewhere);
|
||||||
|
const second = new TraceCache(project);
|
||||||
|
expect(second.path("trace")).toBe(first.path("trace"));
|
||||||
|
expect((await second.read("trace"))?.trace.id).toBe("trace");
|
||||||
|
expect(statSync(first.path("trace")).mode & 0o777).toBe(0o600);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("legacy cache is copied once with its timestamp and original file retained", async () => {
|
||||||
|
const legacy = legacyEntry();
|
||||||
|
const original = readFileSync(legacy, "utf8");
|
||||||
|
const imported = await new TraceCache(project).read("trace");
|
||||||
|
expect(imported?.cachedAt).toBe("2026-10-01T00:00:00Z");
|
||||||
|
expect(readFileSync(legacy, "utf8")).toBe(original);
|
||||||
|
process.chdir(originalCwd);
|
||||||
|
expect(await new TraceCache(project).read("trace")).toEqual(imported);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a different project's legacy trace is not imported", async () => {
|
||||||
|
legacyEntry({ project: { key: "default", baseUrl: project.baseUrl, projectId: "other-project" } });
|
||||||
|
const cache = new TraceCache(project);
|
||||||
|
expect(await cache.read("trace")).toBeUndefined();
|
||||||
|
expect(existsSync(cache.path("trace"))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("wrong trace IDs and unsupported cache versions are not accepted", async () => {
|
||||||
|
for (const entry of [{ cacheVersion: 2 }, { trace: { id: "another-trace", projectId: project.projectId } }]) {
|
||||||
|
legacyEntry(entry);
|
||||||
|
expect(await new TraceCache(project).read("trace")).toBeUndefined();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,12 +1,16 @@
|
|||||||
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
||||||
import { dirname, resolve } from "node:path";
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { dirname, join, resolve } from "node:path";
|
||||||
import type { CachedTrace, LangfuseTraceSummary } from "./types.js";
|
import type { CachedTrace, LangfuseTraceSummary } from "./types.js";
|
||||||
|
|
||||||
const CACHE_VERSION = 1;
|
const CACHE_VERSION = 1;
|
||||||
const CACHE_ROOT = ".cache/langfuse/traces";
|
const LEGACY_CACHE_ROOT = ".cache/langfuse/traces";
|
||||||
|
export const LANGFUSE_CACHE_DIR_ENV = "SEAL_USE_LANGFUSE_CACHE_DIR";
|
||||||
|
export const DEFAULT_LANGFUSE_CACHE_DIR = join(homedir(), ".cache", "seal-use", "langfuse", "traces");
|
||||||
// Single-project domain: the cache segment stays "default", which keeps this
|
// Single-project domain: the cache segment stays "default", which keeps this
|
||||||
// cache byte-compatible with `langfuse-home` (same cwd-relative layout), so the
|
// cache byte-compatible with `langfuse-home`, so old cwd-relative entries can
|
||||||
// two tools share cached traces instead of re-fetching them.
|
// be imported without re-fetching or removing their original files.
|
||||||
const PROJECT_SEGMENT = "default";
|
const PROJECT_SEGMENT = "default";
|
||||||
|
|
||||||
export type TraceCacheProject = {
|
export type TraceCacheProject = {
|
||||||
@@ -15,18 +19,21 @@ export type TraceCacheProject = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Single-trace JSON cache keyed by traceId, written under `<cwd>/.cache`
|
* Single-trace JSON cache keyed by traceId, written under the user's cache
|
||||||
* (gitignored). Holds the FULL raw trace (including observation IO) so outline,
|
* directory. Holds the FULL raw trace (including observation IO) so outline,
|
||||||
* search, observation and flow tools can answer without touching the network.
|
* search, observation and flow tools can answer without touching the network.
|
||||||
* No TTL: `cache-refresh` overwrites explicitly.
|
* No TTL: `cache-refresh` overwrites explicitly.
|
||||||
*/
|
*/
|
||||||
export class TraceCache {
|
export class TraceCache {
|
||||||
constructor(private readonly project: TraceCacheProject) {}
|
private readonly root: string;
|
||||||
|
|
||||||
|
constructor(private readonly project: TraceCacheProject) {
|
||||||
|
this.root = resolve(process.env[LANGFUSE_CACHE_DIR_ENV]?.trim() || DEFAULT_LANGFUSE_CACHE_DIR);
|
||||||
|
}
|
||||||
|
|
||||||
path(traceId: string): string {
|
path(traceId: string): string {
|
||||||
return resolve(
|
return resolve(
|
||||||
process.cwd(),
|
this.root,
|
||||||
CACHE_ROOT,
|
|
||||||
PROJECT_SEGMENT,
|
PROJECT_SEGMENT,
|
||||||
`${sanitizeSegment(traceId)}.json`
|
`${sanitizeSegment(traceId)}.json`
|
||||||
);
|
);
|
||||||
@@ -42,10 +49,25 @@ export class TraceCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async read(traceId: string): Promise<CachedTrace | undefined> {
|
async read(traceId: string): Promise<CachedTrace | undefined> {
|
||||||
|
const cached = await this.readEntry(this.path(traceId), traceId);
|
||||||
|
if (cached) return cached;
|
||||||
|
const legacyPath = resolve(process.cwd(), LEGACY_CACHE_ROOT, PROJECT_SEGMENT, `${sanitizeSegment(traceId)}.json`);
|
||||||
|
if (legacyPath === this.path(traceId)) return undefined;
|
||||||
|
const legacy = await this.readEntry(legacyPath, traceId);
|
||||||
|
if (!legacy) return undefined;
|
||||||
|
// Preserve cachedAt and the original legacy entry; only copy a matching project's trace.
|
||||||
|
await this.persist(traceId, legacy);
|
||||||
|
return legacy;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async readEntry(path: string, traceId: string): Promise<CachedTrace | undefined> {
|
||||||
try {
|
try {
|
||||||
const content = await readFile(this.path(traceId), "utf8");
|
const content = await readFile(path, "utf8");
|
||||||
const parsed = JSON.parse(content) as CachedTrace;
|
const parsed = JSON.parse(content) as CachedTrace;
|
||||||
return parsed.cacheVersion === CACHE_VERSION ? parsed : undefined;
|
if (parsed.cacheVersion !== CACHE_VERSION || parsed.trace?.id !== traceId) return undefined;
|
||||||
|
if (parsed.project?.baseUrl?.replace(/\/+$/, "") !== this.project.baseUrl.replace(/\/+$/, "")) return undefined;
|
||||||
|
if (this.project.projectId && parsed.project.projectId !== this.project.projectId) return undefined;
|
||||||
|
return parsed;
|
||||||
} catch {
|
} catch {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -63,11 +85,17 @@ export class TraceCache {
|
|||||||
trace
|
trace
|
||||||
};
|
};
|
||||||
|
|
||||||
const path = this.path(traceId);
|
await this.persist(traceId, cached);
|
||||||
await mkdir(dirname(path), { recursive: true });
|
|
||||||
await writeFile(path, `${JSON.stringify(cached, null, 2)}\n`, "utf8");
|
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async persist(traceId: string, cached: CachedTrace): Promise<void> {
|
||||||
|
const path = this.path(traceId);
|
||||||
|
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||||
|
const temp = `${path}.${randomUUID()}.tmp`;
|
||||||
|
await writeFile(temp, `${JSON.stringify(cached, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
||||||
|
await rename(temp, path);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function sanitizeSegment(value: string): string {
|
function sanitizeSegment(value: string): string {
|
||||||
|
|||||||
@@ -0,0 +1,246 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import {
|
||||||
|
ATTACHMENT_STAGES,
|
||||||
|
buildAttachmentFlow,
|
||||||
|
buildRuleFlow,
|
||||||
|
candidatesForStage,
|
||||||
|
classifyAttachmentEvidence,
|
||||||
|
collectEvidence,
|
||||||
|
RULE_FLOW_STAGES,
|
||||||
|
stageTerms,
|
||||||
|
summarizeEvidenceFields
|
||||||
|
} from "./flows.js";
|
||||||
|
import type { LangfuseObservationSummary } from "./types.js";
|
||||||
|
|
||||||
|
function observation(overrides: Partial<LangfuseObservationSummary> & { id: string }): LangfuseObservationSummary {
|
||||||
|
return {
|
||||||
|
traceId: "trace-1",
|
||||||
|
type: "SPAN",
|
||||||
|
...overrides
|
||||||
|
} as LangfuseObservationSummary;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("stage vocabulary", () => {
|
||||||
|
test("every stage resolves bilingual search terms", () => {
|
||||||
|
for (const stage of ATTACHMENT_STAGES) {
|
||||||
|
expect(stageTerms(stage, "attachment").length).toBeGreaterThan(0);
|
||||||
|
}
|
||||||
|
for (const stage of RULE_FLOW_STAGES) {
|
||||||
|
expect(stageTerms(stage, "rule").length).toBeGreaterThan(0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matches observation names case-insensitively in either language", () => {
|
||||||
|
const observations = [
|
||||||
|
observation({ id: "a", name: "Attachment_Parsing" }),
|
||||||
|
observation({ id: "b", name: "文档解析 worker" }),
|
||||||
|
observation({ id: "c", name: "unrelated" })
|
||||||
|
];
|
||||||
|
|
||||||
|
const matched = candidatesForStage(observations, stageTerms("document_parsing", "attachment"));
|
||||||
|
expect(matched.map((item) => item.id)).toEqual(["b"]);
|
||||||
|
|
||||||
|
// The rule vocabulary is broader, so it also picks up the English name.
|
||||||
|
const ruleParsed = candidatesForStage(observations, stageTerms("document parsing", "rule"));
|
||||||
|
expect(ruleParsed.map((item) => item.id)).toEqual(["a", "b"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("collectEvidence", () => {
|
||||||
|
const obs = observation({
|
||||||
|
id: "obs-1",
|
||||||
|
name: "attachment parsing",
|
||||||
|
input: "folder/invoice.pdf",
|
||||||
|
output: "解析完成 invoice.pdf",
|
||||||
|
metadata: { file: "invoice.pdf" }
|
||||||
|
});
|
||||||
|
|
||||||
|
test("scans input, output and metadata and pads the snippet with context", () => {
|
||||||
|
const hits = collectEvidence(obs, ["invoice.pdf"], 5, 10);
|
||||||
|
expect(hits.map((hit) => hit.field)).toEqual(["input", "output", "metadata"]);
|
||||||
|
expect(hits[0]?.matched).toBe("invoice.pdf");
|
||||||
|
// contextChars=5 → 5 chars of lead-in before the needle (index 7 - 5 = 2).
|
||||||
|
expect(hits[0]?.snippet).toBe("lder/invoice.pdf");
|
||||||
|
// Needle sits at index 5 (4 CJK chars + space), so 5 chars of lead-in
|
||||||
|
// reaches the start of the string.
|
||||||
|
expect(hits[1]?.snippet).toBe("解析完成 invoice.pdf");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("caps the number of hits so a pathological trace cannot balloon", () => {
|
||||||
|
const noisy = observation({
|
||||||
|
id: "obs-2",
|
||||||
|
input: "x".repeat(500),
|
||||||
|
output: "x".repeat(500),
|
||||||
|
metadata: { a: "x".repeat(500) }
|
||||||
|
});
|
||||||
|
expect(collectEvidence(noisy, ["x"], 10, 3)).toHaveLength(3);
|
||||||
|
expect(collectEvidence(noisy, ["nope"], 10, 3)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("matching is case-insensitive on both sides", () => {
|
||||||
|
const hits = collectEvidence(obs, ["INVOICE.PDF"], 5, 10);
|
||||||
|
expect(hits.length).toBeGreaterThan(0);
|
||||||
|
// `matched` preserves the original casing from the trace text.
|
||||||
|
expect(hits[0]?.matched).toBe("invoice.pdf");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("classifyAttachmentEvidence", () => {
|
||||||
|
test("returns absent when nothing matched", () => {
|
||||||
|
expect(classifyAttachmentEvidence([], "file-1", "a.pdf")).toBe("absent");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("filename-only and file-id-only when those are the sole hits", () => {
|
||||||
|
expect(
|
||||||
|
classifyAttachmentEvidence([{ matched: "a.pdf", snippet: "a.pdf" }], "file-1", "a.pdf")
|
||||||
|
).toBe("filename-only");
|
||||||
|
expect(
|
||||||
|
classifyAttachmentEvidence([{ matched: "file-1", snippet: "file-1" }], "file-1", "a.pdf")
|
||||||
|
).toBe("file-id-only");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("some other hint wins over filename/id and is graded by the snippet", () => {
|
||||||
|
const other = [{ matched: "some extra token", snippet: "..." }];
|
||||||
|
expect(classifyAttachmentEvidence(other, "file-1", "a.pdf")).toBe("parsed-text");
|
||||||
|
expect(
|
||||||
|
classifyAttachmentEvidence(
|
||||||
|
[...other, { matched: "ocr", snippet: "run OCR on the scan" }],
|
||||||
|
"file-1",
|
||||||
|
"a.pdf"
|
||||||
|
)
|
||||||
|
).toBe("image-ocr");
|
||||||
|
expect(
|
||||||
|
classifyAttachmentEvidence(
|
||||||
|
[...other, { matched: "推断", snippet: "模型认为金额为 120" }],
|
||||||
|
"file-1",
|
||||||
|
"a.pdf"
|
||||||
|
)
|
||||||
|
).toBe("model-inferred");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("with no identifiers every hit is an 'other hint' graded from the snippet", () => {
|
||||||
|
// fileName/fileId undefined → `matched !== undefined` is always true, so
|
||||||
|
// hasOtherHint fires and the snippet decides. Note: the union's "unknown"
|
||||||
|
// arm is unreachable — with both identifiers defined, hasOtherHint false
|
||||||
|
// already implies one of them matched. Kept as a defensive fallback only.
|
||||||
|
expect(
|
||||||
|
classifyAttachmentEvidence([{ matched: "x", snippet: "raw parsed text" }], undefined, undefined)
|
||||||
|
).toBe("parsed-text");
|
||||||
|
expect(
|
||||||
|
classifyAttachmentEvidence([{ matched: "x", snippet: "OCR pipeline output" }], undefined, undefined)
|
||||||
|
).toBe("image-ocr");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("summarizeEvidenceFields", () => {
|
||||||
|
test("counts hits per field and de-duplicates repeated matches", () => {
|
||||||
|
const summary = summarizeEvidenceFields([
|
||||||
|
{ field: "input", matched: "rule-a" } as never,
|
||||||
|
{ field: "input", matched: "rule-a" } as never,
|
||||||
|
{ field: "input", matched: "rule-b" } as never,
|
||||||
|
{ field: "output", matched: "rule-a" } as never
|
||||||
|
]);
|
||||||
|
expect(summary.input).toEqual({ count: 3, matched: ["rule-a", "rule-b"] });
|
||||||
|
expect(summary.output).toEqual({ count: 1, matched: ["rule-a"] });
|
||||||
|
expect(summary.metadata).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildAttachmentFlow", () => {
|
||||||
|
const observations = [
|
||||||
|
observation({ id: "p1", name: "attachment parsing", input: "读取 a.pdf" }),
|
||||||
|
observation({ id: "p2", name: "document_parsing", output: "解析 a.pdf 得到 120 元" }),
|
||||||
|
observation({ id: "p3", name: "approval_review", output: "OCR 结果 a.pdf 金额 120" }),
|
||||||
|
observation({ id: "other", name: "unrelated", input: "nothing here" })
|
||||||
|
];
|
||||||
|
|
||||||
|
test("labels a stage seen and classifies the evidence source", () => {
|
||||||
|
const stages = buildAttachmentFlow({
|
||||||
|
observations,
|
||||||
|
fileName: "a.pdf",
|
||||||
|
// A second, non-identifier needle is what makes hasOtherHint fire — a
|
||||||
|
// filename-only query can never reach the OCR/inference grading.
|
||||||
|
needles: ["a.pdf", "金额"],
|
||||||
|
contextChars: 20
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(stages).toHaveLength(ATTACHMENT_STAGES.length);
|
||||||
|
expect(stages.map((stage) => stage.stage)).toEqual([...ATTACHMENT_STAGES]);
|
||||||
|
|
||||||
|
const parsing = stages.find((stage) => stage.stage === "document_parsing");
|
||||||
|
expect(parsing?.status).toBe("seen");
|
||||||
|
expect(parsing?.source).toBe("filename-only");
|
||||||
|
expect(parsing?.observations.map((item) => item.id)).toEqual(["p2"]);
|
||||||
|
expect(parsing?.evidence[0]?.observationId).toBe("p2");
|
||||||
|
|
||||||
|
const review = stages.find((stage) => stage.stage === "approval_review");
|
||||||
|
expect(review?.evidence.length).toBeGreaterThan(0);
|
||||||
|
// 金额 is a non-identifier hit, so hasOtherHint fires and "OCR" in the
|
||||||
|
// snippet grades this stage as image-ocr.
|
||||||
|
expect(review?.source).toBe("image-ocr");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("stages with no matching observation report absent", () => {
|
||||||
|
const stages = buildAttachmentFlow({
|
||||||
|
observations,
|
||||||
|
fileId: "file-xyz",
|
||||||
|
needles: ["file-xyz"],
|
||||||
|
contextChars: 20
|
||||||
|
});
|
||||||
|
const understanding = stages.find(
|
||||||
|
(stage) => stage.stage === "image/document understanding"
|
||||||
|
);
|
||||||
|
expect(understanding?.status).toBe("absent");
|
||||||
|
expect(understanding?.source).toBe("absent");
|
||||||
|
expect(understanding?.observations).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildRuleFlow", () => {
|
||||||
|
const observations = [
|
||||||
|
observation({ id: "r1", name: "rule matching", input: "规则:禁止差旅超标" }),
|
||||||
|
observation({ id: "g1", name: "generic span", output: "命中规则 禁止差旅超标" }),
|
||||||
|
observation({ id: "f1", name: "final review", output: "审核结论:驳回" })
|
||||||
|
];
|
||||||
|
|
||||||
|
test("falls back to every observation when no stage name matches", () => {
|
||||||
|
const flow = buildRuleFlow({
|
||||||
|
observations,
|
||||||
|
needles: ["禁止差旅超标"],
|
||||||
|
contextChars: 30
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(flow.stages.ruleMatching?.matched).toBe(true);
|
||||||
|
expect(flow.stages.ruleMatching?.matchedObservationIds).toContain("r1");
|
||||||
|
// g1 sits in a generically-named span, reachable only via the fallback pool.
|
||||||
|
expect(flow.relatedObservationIds).toContain("g1");
|
||||||
|
expect(flow.evidenceCount).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
// No observation is named for "document parsing", so the stage has zero
|
||||||
|
// *named* candidates but still scans the whole trace via the fallback —
|
||||||
|
// that is what keeps a rule applied inside a generically-named span visible.
|
||||||
|
const documentParsing = flow.stages.documentParsing;
|
||||||
|
expect(documentParsing?.observations).toEqual([]);
|
||||||
|
expect(documentParsing?.matched).toBe(true);
|
||||||
|
expect(documentParsing?.matchedObservationIds).toContain("r1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reports extracted fields grouped by source field", () => {
|
||||||
|
const flow = buildRuleFlow({
|
||||||
|
observations,
|
||||||
|
needles: ["禁止差旅超标", "驳回"],
|
||||||
|
contextChars: 30
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(flow.stages.ruleMatching?.extractedFields.input?.matched).toEqual(["禁止差旅超标"]);
|
||||||
|
expect(flow.stages.finalReview?.extractedFields.output?.matched).toEqual(["驳回"]);
|
||||||
|
expect(flow.stages.finalReview?.matched).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns the documented stage keys in order", () => {
|
||||||
|
const flow = buildRuleFlow({ observations, needles: ["nothing-matches"], contextChars: 30 });
|
||||||
|
expect(Object.keys(flow.stages)).toEqual(["ruleMatching", "documentParsing", "finalReview"]);
|
||||||
|
expect(flow.evidenceCount).toBe(0);
|
||||||
|
expect(flow.relatedObservationIds).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
import { stringifyValue } from "./search.js";
|
||||||
|
import { summarizeObservation, uniqueStrings } from "./summary.js";
|
||||||
|
import type { LangfuseObservationSummary } from "./types.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deterministic flow reconstruction from cached Langfuse fields.
|
||||||
|
*
|
||||||
|
* Everything here is plain text matching over observation name/input/output/
|
||||||
|
* metadata — no network, no model calls. Both flows answer "where does this
|
||||||
|
* file or rule show up across the stages", so they share one evidence
|
||||||
|
* collector and differ only in their stage vocabulary and in what they report.
|
||||||
|
*
|
||||||
|
* The stage word lists are bilingual heuristics tuned against real traces;
|
||||||
|
* they are deliberately data, not logic, so tuning them cannot change a code
|
||||||
|
* path.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const ATTACHMENT_STAGES = [
|
||||||
|
"attachment parsing",
|
||||||
|
"image/document understanding",
|
||||||
|
"pre_analysis",
|
||||||
|
"document_parsing",
|
||||||
|
"approval_review"
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const;
|
||||||
|
|
||||||
|
export type AttachmentStage = (typeof ATTACHMENT_STAGES)[number];
|
||||||
|
export type RuleFlowStage = (typeof RULE_FLOW_STAGES)[number];
|
||||||
|
|
||||||
|
export type EvidenceField = "input" | "output" | "metadata";
|
||||||
|
|
||||||
|
export interface EvidenceHit {
|
||||||
|
observationId: string;
|
||||||
|
name?: string;
|
||||||
|
type?: string;
|
||||||
|
field: EvidenceField;
|
||||||
|
matched: string;
|
||||||
|
snippet: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AttachmentSource =
|
||||||
|
| "filename-only"
|
||||||
|
| "file-id-only"
|
||||||
|
| "parsed-text"
|
||||||
|
| "image-ocr"
|
||||||
|
| "model-inferred"
|
||||||
|
| "absent"
|
||||||
|
| "unknown";
|
||||||
|
|
||||||
|
const ATTACHMENT_STAGE_TERMS: Record<AttachmentStage, string[]> = {
|
||||||
|
"attachment parsing": ["attachment", "附件", "parse_attachment", "attachment_parsing"],
|
||||||
|
"image/document understanding": [
|
||||||
|
"understanding",
|
||||||
|
"vision",
|
||||||
|
"image",
|
||||||
|
"document_understanding",
|
||||||
|
"文档理解",
|
||||||
|
"图片理解"
|
||||||
|
],
|
||||||
|
pre_analysis: ["pre_analysis", "pre-analysis", "预分析"],
|
||||||
|
document_parsing: ["document_parsing", "document parsing", "文档解析"],
|
||||||
|
approval_review: ["approval_review", "approval review", "审核"]
|
||||||
|
};
|
||||||
|
|
||||||
|
const RULE_STAGE_TERMS: Record<RuleFlowStage, string[]> = {
|
||||||
|
"rule matching": ["rule", "规则", "policy", "match", "matching", "命中"],
|
||||||
|
"document parsing": ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"],
|
||||||
|
"final review": ["approval_review", "approval review", "review", "审核", "结论", "final"]
|
||||||
|
};
|
||||||
|
|
||||||
|
export function stageTerms(
|
||||||
|
stage: AttachmentStage | RuleFlowStage,
|
||||||
|
vocabulary: "attachment" | "rule"
|
||||||
|
): string[] {
|
||||||
|
return vocabulary === "attachment"
|
||||||
|
? ATTACHMENT_STAGE_TERMS[stage as AttachmentStage]
|
||||||
|
: RULE_STAGE_TERMS[stage as RuleFlowStage];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Observations whose name mentions any of the stage's terms. */
|
||||||
|
export function candidatesForStage(
|
||||||
|
observations: LangfuseObservationSummary[],
|
||||||
|
terms: string[]
|
||||||
|
): LangfuseObservationSummary[] {
|
||||||
|
const lowered = terms.map((term) => term.toLowerCase());
|
||||||
|
return observations.filter((observation) => {
|
||||||
|
const name = observation.name?.toLowerCase() ?? "";
|
||||||
|
return lowered.some((term) => name.includes(term));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scan every field of an observation for each needle and return bounded,
|
||||||
|
* context-padded hits. The cap keeps a pathological trace from ballooning the
|
||||||
|
* response.
|
||||||
|
*/
|
||||||
|
export function collectEvidence(
|
||||||
|
observation: LangfuseObservationSummary,
|
||||||
|
needles: string[],
|
||||||
|
contextChars: number,
|
||||||
|
limit: number
|
||||||
|
): EvidenceHit[] {
|
||||||
|
const fields = [
|
||||||
|
["input", stringifyValue(observation.input)],
|
||||||
|
["output", stringifyValue(observation.output)],
|
||||||
|
["metadata", stringifyValue(observation.metadata)]
|
||||||
|
] as const;
|
||||||
|
const evidence: EvidenceHit[] = [];
|
||||||
|
|
||||||
|
for (const [field, text] of fields) {
|
||||||
|
const normalized = text.toLowerCase();
|
||||||
|
for (const needle of needles) {
|
||||||
|
const index = normalized.indexOf(needle.toLowerCase());
|
||||||
|
if (index < 0) continue;
|
||||||
|
evidence.push({
|
||||||
|
observationId: observation.id,
|
||||||
|
name: observation.name,
|
||||||
|
type: observation.type,
|
||||||
|
field,
|
||||||
|
matched: text.slice(index, index + needle.length),
|
||||||
|
snippet: text.slice(
|
||||||
|
Math.max(0, index - contextChars),
|
||||||
|
Math.min(text.length, index + needle.length + contextChars)
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return evidence.slice(0, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decide where an attachment's presence appears to come from. Labels describe
|
||||||
|
* the text that was found — they never assert that a model understood the file.
|
||||||
|
*/
|
||||||
|
export function classifyAttachmentEvidence(
|
||||||
|
evidence: Array<{ matched: string; snippet: string }>,
|
||||||
|
fileId: string | undefined,
|
||||||
|
fileName: string | undefined
|
||||||
|
): AttachmentSource {
|
||||||
|
if (evidence.length === 0) return "absent";
|
||||||
|
|
||||||
|
const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false;
|
||||||
|
const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false;
|
||||||
|
const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName);
|
||||||
|
|
||||||
|
if (hasOtherHint) {
|
||||||
|
const joined = evidence
|
||||||
|
.map((item) => item.snippet)
|
||||||
|
.join("\n")
|
||||||
|
.toLowerCase();
|
||||||
|
if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr";
|
||||||
|
if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred";
|
||||||
|
return "parsed-text";
|
||||||
|
}
|
||||||
|
if (hasFileName) return "filename-only";
|
||||||
|
if (hasFileId) return "file-id-only";
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Count hits per field, de-duplicating the matched substrings. */
|
||||||
|
export function summarizeEvidenceFields(
|
||||||
|
evidence: EvidenceHit[]
|
||||||
|
): Record<string, { count: number; matched: string[] }> {
|
||||||
|
const summary: Record<string, { count: number; matched: string[] }> = {};
|
||||||
|
for (const item of evidence) {
|
||||||
|
const entry = summary[item.field];
|
||||||
|
if (entry) {
|
||||||
|
entry.count += 1;
|
||||||
|
if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched);
|
||||||
|
} else {
|
||||||
|
summary[item.field] = { count: 1, matched: [item.matched] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return summary;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildAttachmentFlow(options: {
|
||||||
|
observations: LangfuseObservationSummary[];
|
||||||
|
fileId?: string;
|
||||||
|
fileName?: string;
|
||||||
|
needles: string[];
|
||||||
|
contextChars: number;
|
||||||
|
}) {
|
||||||
|
const { observations, fileId, fileName, needles, contextChars } = options;
|
||||||
|
|
||||||
|
return ATTACHMENT_STAGES.map((stage) => {
|
||||||
|
const candidates = candidatesForStage(observations, stageTerms(stage, "attachment"));
|
||||||
|
const evidence = candidates.flatMap((observation) =>
|
||||||
|
collectEvidence(observation, needles, contextChars, 10)
|
||||||
|
);
|
||||||
|
const source = classifyAttachmentEvidence(evidence, fileId, fileName);
|
||||||
|
|
||||||
|
return {
|
||||||
|
stage,
|
||||||
|
source,
|
||||||
|
status: source === "absent" ? ("absent" as const) : ("seen" as const),
|
||||||
|
observations: candidates.map(summarizeObservation),
|
||||||
|
evidence
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildRuleFlow(options: {
|
||||||
|
observations: LangfuseObservationSummary[];
|
||||||
|
needles: string[];
|
||||||
|
contextChars: number;
|
||||||
|
}) {
|
||||||
|
const { observations, needles, contextChars } = options;
|
||||||
|
|
||||||
|
const stages = RULE_FLOW_STAGES.map((stage) => {
|
||||||
|
const candidates = candidatesForStage(observations, stageTerms(stage, "rule"));
|
||||||
|
// Unlike attachment flow, a rule query falls back to every observation:
|
||||||
|
// a rule can be applied inside a generically-named span.
|
||||||
|
const pool = candidates.length ? candidates : observations;
|
||||||
|
const evidence = pool
|
||||||
|
.flatMap((observation) => collectEvidence(observation, needles, contextChars, 20))
|
||||||
|
.slice(0, 20);
|
||||||
|
|
||||||
|
return {
|
||||||
|
stage,
|
||||||
|
matched: evidence.length > 0,
|
||||||
|
matchedObservationIds: uniqueStrings(evidence.map((item) => item.observationId)),
|
||||||
|
observations: candidates.map(summarizeObservation),
|
||||||
|
extractedFields: summarizeEvidenceFields(evidence),
|
||||||
|
evidence
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const allEvidence = stages.flatMap((stage) => stage.evidence);
|
||||||
|
|
||||||
|
return {
|
||||||
|
stages: {
|
||||||
|
ruleMatching: stages[0],
|
||||||
|
documentParsing: stages[1],
|
||||||
|
finalReview: stages[2]
|
||||||
|
},
|
||||||
|
relatedObservationIds: uniqueStrings(allEvidence.map((item) => item.observationId)),
|
||||||
|
evidenceCount: allEvidence.length
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||||
import { mkdtempSync, realpathSync, rmSync } from "node:fs";
|
import { mkdtempSync, rmSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { CliError } from "../../core/errors.js";
|
import { CliError } from "../../core/errors.js";
|
||||||
@@ -52,16 +52,21 @@ function sampleTrace(): LangfuseTraceSummary {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let originalCwd: string;
|
let originalCwd: string;
|
||||||
|
let originalCacheDir: string | undefined;
|
||||||
let workdir: string;
|
let workdir: string;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
originalCwd = process.cwd();
|
originalCwd = process.cwd();
|
||||||
|
originalCacheDir = process.env.SEAL_USE_LANGFUSE_CACHE_DIR;
|
||||||
workdir = mkdtempSync(join(tmpdir(), "seal-langfuse-test-"));
|
workdir = mkdtempSync(join(tmpdir(), "seal-langfuse-test-"));
|
||||||
|
process.env.SEAL_USE_LANGFUSE_CACHE_DIR = join(workdir, "cache");
|
||||||
process.chdir(workdir);
|
process.chdir(workdir);
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
process.chdir(originalCwd);
|
process.chdir(originalCwd);
|
||||||
|
if (originalCacheDir === undefined) delete process.env.SEAL_USE_LANGFUSE_CACHE_DIR;
|
||||||
|
else process.env.SEAL_USE_LANGFUSE_CACHE_DIR = originalCacheDir;
|
||||||
rmSync(workdir, { recursive: true, force: true });
|
rmSync(workdir, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -72,13 +77,11 @@ async function seedCache(trace: LangfuseTraceSummary = sampleTrace()) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("trace cache", () => {
|
describe("trace cache", () => {
|
||||||
test("writes the langfuse-home compatible path and round-trips", async () => {
|
test("writes the langfuse-home compatible format in the configured cache directory and round-trips", async () => {
|
||||||
const cache = await seedCache();
|
const cache = await seedCache();
|
||||||
// process.cwd() resolves symlinks, so compare against the physical tmpdir
|
// The cache root is explicit and independent of cwd, including macOS /var symlinks.
|
||||||
// (macOS /var -> /private/var).
|
|
||||||
const physicalWorkdir = realpathSync(workdir);
|
|
||||||
expect(cache.path("trace-1")).toBe(
|
expect(cache.path("trace-1")).toBe(
|
||||||
join(physicalWorkdir, ".cache", "langfuse", "traces", "default", "trace-1.json")
|
join(workdir, "cache", "default", "trace-1.json")
|
||||||
);
|
);
|
||||||
|
|
||||||
const read = await new TraceCache({ baseUrl: CONFIG.baseUrl }).read("trace-1");
|
const read = await new TraceCache({ baseUrl: CONFIG.baseUrl }).read("trace-1");
|
||||||
|
|||||||
+17
-278
@@ -3,7 +3,9 @@ import { LangfuseApi } from "./api.js";
|
|||||||
import { TraceCache } from "./cache.js";
|
import { TraceCache } from "./cache.js";
|
||||||
import type { LangfuseConfig } from "./config.js";
|
import type { LangfuseConfig } from "./config.js";
|
||||||
import { LangfuseClient } from "./client.js";
|
import { LangfuseClient } from "./client.js";
|
||||||
|
import { buildAttachmentFlow, buildRuleFlow } from "./flows.js";
|
||||||
import { searchTrace, stringifyValue } from "./search.js";
|
import { searchTrace, stringifyValue } from "./search.js";
|
||||||
|
import { byteLength, objectKeys, summarizeObservation, summarizeTrace, uniqueStrings } from "./summary.js";
|
||||||
import type {
|
import type {
|
||||||
AttachmentFlowInput,
|
AttachmentFlowInput,
|
||||||
CachedTrace,
|
CachedTrace,
|
||||||
@@ -28,14 +30,6 @@ const DEFAULT_IO_CHARS = 8_000;
|
|||||||
const DEFAULT_PREVIEW_CHARS = 160;
|
const DEFAULT_PREVIEW_CHARS = 160;
|
||||||
const FULL_OUTPUT_WARNING_THRESHOLD = 30_000;
|
const FULL_OUTPUT_WARNING_THRESHOLD = 30_000;
|
||||||
const OUTLINE_FULL_FIELD_THRESHOLD = 20_000;
|
const OUTLINE_FULL_FIELD_THRESHOLD = 20_000;
|
||||||
const ATTACHMENT_STAGES = [
|
|
||||||
"attachment parsing",
|
|
||||||
"image/document understanding",
|
|
||||||
"pre_analysis",
|
|
||||||
"document_parsing",
|
|
||||||
"approval_review"
|
|
||||||
] as const;
|
|
||||||
const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read-only Langfuse trace service, ported from langfuse-home.
|
* Read-only Langfuse trace service, ported from langfuse-home.
|
||||||
@@ -278,15 +272,17 @@ export class LangfuseService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||||
const trace = cached.trace;
|
|
||||||
const contextChars = clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500);
|
const contextChars = clamp(input.contextChars ?? DEFAULT_CONTEXT_CHARS, 20, 500);
|
||||||
const needles = [input.fileId, input.fileName, ...(input.contentHints ?? [])].filter(
|
const needles = [input.fileId, input.fileName, ...(input.contentHints ?? [])].filter(
|
||||||
(value): value is string => Boolean(value?.trim())
|
(value): value is string => Boolean(value?.trim())
|
||||||
);
|
);
|
||||||
const observations = trace.observations ?? [];
|
const stages = buildAttachmentFlow({
|
||||||
const stages = ATTACHMENT_STAGES.map((stage) =>
|
observations: cached.trace.observations ?? [],
|
||||||
inspectAttachmentStage(stage, observations, needles, input.fileId, input.fileName, contextChars)
|
fileId: input.fileId,
|
||||||
);
|
fileName: input.fileName,
|
||||||
|
needles,
|
||||||
|
contextChars
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
traceId: input.traceId,
|
traceId: input.traceId,
|
||||||
@@ -304,27 +300,20 @@ export class LangfuseService {
|
|||||||
|
|
||||||
async getTraceRuleFlow(input: TraceRuleFlowInput) {
|
async getTraceRuleFlow(input: TraceRuleFlowInput) {
|
||||||
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
const cached = await this.getCachedTrace(input.traceId, input.refreshIfMissing ?? false);
|
||||||
const trace = cached.trace;
|
|
||||||
const contextChars = clamp(input.contextChars ?? 300, 20, 500);
|
const contextChars = clamp(input.contextChars ?? 300, 20, 500);
|
||||||
const needles = uniqueStrings([input.rule, ...(input.ruleHints ?? [])]);
|
const flow = buildRuleFlow({
|
||||||
const observations = trace.observations ?? [];
|
observations: cached.trace.observations ?? [],
|
||||||
const stageResults = RULE_FLOW_STAGES.map((stage) =>
|
needles: uniqueStrings([input.rule, ...(input.ruleHints ?? [])]),
|
||||||
inspectRuleStage(stage, observations, needles, contextChars)
|
contextChars
|
||||||
);
|
});
|
||||||
const allEvidence = stageResults.flatMap((stage) => stage.evidence);
|
|
||||||
const relatedObservationIds = uniqueStrings(allEvidence.map((item) => item.observationId));
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
traceId: input.traceId,
|
traceId: input.traceId,
|
||||||
rule: input.rule,
|
rule: input.rule,
|
||||||
ruleHints: input.ruleHints,
|
ruleHints: input.ruleHints,
|
||||||
stages: {
|
stages: flow.stages,
|
||||||
ruleMatching: stageResults[0],
|
relatedObservationIds: flow.relatedObservationIds,
|
||||||
documentParsing: stageResults[1],
|
evidenceCount: flow.evidenceCount,
|
||||||
finalReview: stageResults[2]
|
|
||||||
},
|
|
||||||
relatedObservationIds,
|
|
||||||
evidenceCount: allEvidence.length,
|
|
||||||
note:
|
note:
|
||||||
"Rule flow is deterministic text evidence extraction from cached Langfuse fields. It reports where the rule or hints appear; it does not infer hidden model reasoning or prove causality beyond the recorded trace text.",
|
"Rule flow is deterministic text evidence extraction from cached Langfuse fields. It reports where the rule or hints appear; it does not infer hidden model reasoning or prove causality beyond the recorded trace text.",
|
||||||
cache: {
|
cache: {
|
||||||
@@ -436,45 +425,6 @@ function buildOutlineWarnings(
|
|||||||
return warnings.slice(0, 20);
|
return warnings.slice(0, 20);
|
||||||
}
|
}
|
||||||
|
|
||||||
function summarizeTrace(trace: LangfuseTraceSummary) {
|
|
||||||
return {
|
|
||||||
id: trace.id,
|
|
||||||
name: trace.name,
|
|
||||||
projectId: trace.projectId,
|
|
||||||
sessionId: trace.sessionId,
|
|
||||||
userId: trace.userId,
|
|
||||||
timestamp: trace.timestamp,
|
|
||||||
environment: trace.environment,
|
|
||||||
tags: trace.tags,
|
|
||||||
inputLength: stringifyValue(trace.input).length,
|
|
||||||
outputLength: stringifyValue(trace.output).length,
|
|
||||||
metadata: trace.metadata,
|
|
||||||
latency: trace.latency,
|
|
||||||
totalCost: trace.totalCost
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function summarizeObservation(observation: LangfuseObservationSummary) {
|
|
||||||
return {
|
|
||||||
id: observation.id,
|
|
||||||
traceId: observation.traceId,
|
|
||||||
parentObservationId: observation.parentObservationId,
|
|
||||||
type: observation.type,
|
|
||||||
name: observation.name,
|
|
||||||
startTime: observation.startTime,
|
|
||||||
endTime: observation.endTime,
|
|
||||||
model: observation.providedModelName ?? observation.model,
|
|
||||||
inputLength: stringifyValue(observation.input).length,
|
|
||||||
outputLength: stringifyValue(observation.output).length,
|
|
||||||
inputBytes: byteLength(stringifyValue(observation.input)),
|
|
||||||
outputBytes: byteLength(stringifyValue(observation.output)),
|
|
||||||
metadataKeys: objectKeys(observation.metadata),
|
|
||||||
usageDetails: observation.usageDetails,
|
|
||||||
costDetails: observation.costDetails,
|
|
||||||
totalCost: observation.totalCost
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildTraceUrl(baseUrl: string, projectId: string, traceId: string): string {
|
function buildTraceUrl(baseUrl: string, projectId: string, traceId: string): string {
|
||||||
const url = new URL(
|
const url = new URL(
|
||||||
`/project/${encodeURIComponent(projectId)}/traces/${encodeURIComponent(traceId)}`,
|
`/project/${encodeURIComponent(projectId)}/traces/${encodeURIComponent(traceId)}`,
|
||||||
@@ -545,209 +495,6 @@ function parsePath(path: string): Array<string | number> {
|
|||||||
return segments;
|
return segments;
|
||||||
}
|
}
|
||||||
|
|
||||||
function inspectAttachmentStage(
|
|
||||||
stage: (typeof ATTACHMENT_STAGES)[number],
|
|
||||||
observations: LangfuseObservationSummary[],
|
|
||||||
needles: string[],
|
|
||||||
fileId: string | undefined,
|
|
||||||
fileName: string | undefined,
|
|
||||||
contextChars: number
|
|
||||||
) {
|
|
||||||
const stageTerms = stageSearchTerms(stage);
|
|
||||||
const candidates = observations.filter((observation) => {
|
|
||||||
const name = observation.name?.toLowerCase() ?? "";
|
|
||||||
return stageTerms.some((term) => name.includes(term));
|
|
||||||
});
|
|
||||||
const evidence = candidates.flatMap((observation) =>
|
|
||||||
collectAttachmentEvidence(observation, needles, contextChars)
|
|
||||||
);
|
|
||||||
const source = classifyAttachmentEvidence(evidence, fileId, fileName);
|
|
||||||
|
|
||||||
return {
|
|
||||||
stage,
|
|
||||||
source,
|
|
||||||
status: source === "absent" ? "absent" : "seen",
|
|
||||||
observations: candidates.map(summarizeObservation),
|
|
||||||
evidence
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function stageSearchTerms(stage: (typeof ATTACHMENT_STAGES)[number]): string[] {
|
|
||||||
switch (stage) {
|
|
||||||
case "attachment parsing":
|
|
||||||
return ["attachment", "附件", "parse_attachment", "attachment_parsing"];
|
|
||||||
case "image/document understanding":
|
|
||||||
return ["understanding", "vision", "image", "document_understanding", "文档理解", "图片理解"];
|
|
||||||
case "pre_analysis":
|
|
||||||
return ["pre_analysis", "pre-analysis", "预分析"];
|
|
||||||
case "document_parsing":
|
|
||||||
return ["document_parsing", "document parsing", "文档解析"];
|
|
||||||
case "approval_review":
|
|
||||||
return ["approval_review", "approval review", "审核"];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function collectAttachmentEvidence(
|
|
||||||
observation: LangfuseObservationSummary,
|
|
||||||
needles: string[],
|
|
||||||
contextChars: number
|
|
||||||
): Array<{
|
|
||||||
observationId: string;
|
|
||||||
name?: string;
|
|
||||||
field: "input" | "output" | "metadata";
|
|
||||||
matched: string;
|
|
||||||
snippet: string;
|
|
||||||
}> {
|
|
||||||
const fields = [
|
|
||||||
["input", stringifyValue(observation.input)],
|
|
||||||
["output", stringifyValue(observation.output)],
|
|
||||||
["metadata", stringifyValue(observation.metadata)]
|
|
||||||
] as const;
|
|
||||||
const evidence: ReturnType<typeof collectAttachmentEvidence> = [];
|
|
||||||
|
|
||||||
for (const [field, text] of fields) {
|
|
||||||
const normalized = text.toLowerCase();
|
|
||||||
for (const needle of needles) {
|
|
||||||
const index = normalized.indexOf(needle.toLowerCase());
|
|
||||||
if (index < 0) continue;
|
|
||||||
evidence.push({
|
|
||||||
observationId: observation.id,
|
|
||||||
name: observation.name,
|
|
||||||
field,
|
|
||||||
matched: text.slice(index, index + needle.length),
|
|
||||||
snippet: text.slice(
|
|
||||||
Math.max(0, index - contextChars),
|
|
||||||
Math.min(text.length, index + needle.length + contextChars)
|
|
||||||
)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return evidence.slice(0, 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
function classifyAttachmentEvidence(
|
|
||||||
evidence: Array<{ matched: string; snippet: string; field?: string }>,
|
|
||||||
fileId: string | undefined,
|
|
||||||
fileName: string | undefined
|
|
||||||
): "filename-only" | "file-id-only" | "parsed-text" | "image-ocr" | "model-inferred" | "absent" | "unknown" {
|
|
||||||
if (evidence.length === 0) return "absent";
|
|
||||||
const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false;
|
|
||||||
const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false;
|
|
||||||
const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName);
|
|
||||||
if (hasOtherHint) {
|
|
||||||
const joined = evidence
|
|
||||||
.map((item) => item.snippet)
|
|
||||||
.join("\n")
|
|
||||||
.toLowerCase();
|
|
||||||
if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr";
|
|
||||||
if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred";
|
|
||||||
return "parsed-text";
|
|
||||||
}
|
|
||||||
if (hasFileName && !hasOtherHint) return "filename-only";
|
|
||||||
if (hasFileId && !hasOtherHint) return "file-id-only";
|
|
||||||
return "unknown";
|
|
||||||
}
|
|
||||||
|
|
||||||
function inspectRuleStage(
|
|
||||||
stage: (typeof RULE_FLOW_STAGES)[number],
|
|
||||||
observations: LangfuseObservationSummary[],
|
|
||||||
needles: string[],
|
|
||||||
contextChars: number
|
|
||||||
) {
|
|
||||||
const stageTerms = ruleStageSearchTerms(stage);
|
|
||||||
const candidates = observations.filter((observation) => {
|
|
||||||
const name = observation.name?.toLowerCase() ?? "";
|
|
||||||
return stageTerms.some((term) => name.includes(term));
|
|
||||||
});
|
|
||||||
const candidatePool = candidates.length ? candidates : observations;
|
|
||||||
const evidence = candidatePool
|
|
||||||
.flatMap((observation) => collectRuleEvidence(observation, needles, contextChars))
|
|
||||||
.slice(0, 20);
|
|
||||||
const matchedObservationIds = uniqueStrings(evidence.map((item) => item.observationId));
|
|
||||||
|
|
||||||
return {
|
|
||||||
stage,
|
|
||||||
matched: evidence.length > 0,
|
|
||||||
matchedObservationIds,
|
|
||||||
observations: candidates.map(summarizeObservation),
|
|
||||||
extractedFields: summarizeEvidenceFields(evidence),
|
|
||||||
evidence
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function ruleStageSearchTerms(stage: (typeof RULE_FLOW_STAGES)[number]): string[] {
|
|
||||||
switch (stage) {
|
|
||||||
case "rule matching":
|
|
||||||
return ["rule", "规则", "policy", "match", "matching", "命中"];
|
|
||||||
case "document parsing":
|
|
||||||
return ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"];
|
|
||||||
case "final review":
|
|
||||||
return ["approval_review", "approval review", "review", "审核", "结论", "final"];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function collectRuleEvidence(
|
|
||||||
observation: LangfuseObservationSummary,
|
|
||||||
needles: string[],
|
|
||||||
contextChars: number
|
|
||||||
): Array<{
|
|
||||||
observationId: string;
|
|
||||||
name?: string;
|
|
||||||
type?: string;
|
|
||||||
field: "input" | "output" | "metadata";
|
|
||||||
matched: string;
|
|
||||||
snippet: string;
|
|
||||||
}> {
|
|
||||||
const fields = [
|
|
||||||
["input", stringifyValue(observation.input)],
|
|
||||||
["output", stringifyValue(observation.output)],
|
|
||||||
["metadata", stringifyValue(observation.metadata)]
|
|
||||||
] as const;
|
|
||||||
const evidence: ReturnType<typeof collectRuleEvidence> = [];
|
|
||||||
|
|
||||||
for (const [field, text] of fields) {
|
|
||||||
const normalized = text.toLowerCase();
|
|
||||||
for (const needle of needles) {
|
|
||||||
const index = normalized.indexOf(needle.toLowerCase());
|
|
||||||
if (index < 0) continue;
|
|
||||||
evidence.push({
|
|
||||||
observationId: observation.id,
|
|
||||||
name: observation.name,
|
|
||||||
type: observation.type,
|
|
||||||
field,
|
|
||||||
matched: text.slice(index, index + needle.length),
|
|
||||||
snippet: text.slice(
|
|
||||||
Math.max(0, index - contextChars),
|
|
||||||
Math.min(text.length, index + needle.length + contextChars)
|
|
||||||
)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return evidence;
|
|
||||||
}
|
|
||||||
|
|
||||||
function summarizeEvidenceFields(
|
|
||||||
evidence: Array<{ field: "input" | "output" | "metadata"; matched: string }>
|
|
||||||
): Record<string, { count: number; matched: string[] }> {
|
|
||||||
const summary: Record<string, { count: number; matched: string[] }> = {};
|
|
||||||
for (const item of evidence) {
|
|
||||||
const entry = summary[item.field];
|
|
||||||
if (entry) {
|
|
||||||
entry.count += 1;
|
|
||||||
if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched);
|
|
||||||
} else {
|
|
||||||
summary[item.field] = { count: 1, matched: [item.matched] };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return summary;
|
|
||||||
}
|
|
||||||
|
|
||||||
function uniqueStrings(values: Array<string | undefined>): string[] {
|
|
||||||
return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))];
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasValue(value: unknown): boolean {
|
function hasValue(value: unknown): boolean {
|
||||||
return stringifyValue(value).length > 0;
|
return stringifyValue(value).length > 0;
|
||||||
}
|
}
|
||||||
@@ -759,14 +506,6 @@ function truncateMiddle(text: string, maxChars: number): string {
|
|||||||
return `${text.slice(0, head)}\n...<truncated>...\n${text.slice(text.length - tail)}`;
|
return `${text.slice(0, head)}\n...<truncated>...\n${text.slice(text.length - tail)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function objectKeys(value: unknown): string[] {
|
|
||||||
return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
function byteLength(value: string): number {
|
|
||||||
return Buffer.byteLength(value, "utf8");
|
|
||||||
}
|
|
||||||
|
|
||||||
function clamp(value: number, min: number, max: number): number {
|
function clamp(value: number, min: number, max: number): number {
|
||||||
return Math.max(min, Math.min(max, value));
|
return Math.max(min, Math.min(max, value));
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { stringifyValue } from "./search.js";
|
||||||
|
import type { LangfuseObservationSummary, LangfuseTraceSummary } from "./types.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Size-before-content projections of a cached trace.
|
||||||
|
*
|
||||||
|
* Both the outline/search responses and the flow evidence builders need these
|
||||||
|
* (a stage reports its candidate observations in summary form), so they live
|
||||||
|
* here rather than in `service.ts` — otherwise `flows.ts` would have to import
|
||||||
|
* the service that imports it back.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function summarizeTrace(trace: LangfuseTraceSummary) {
|
||||||
|
return {
|
||||||
|
id: trace.id,
|
||||||
|
name: trace.name,
|
||||||
|
projectId: trace.projectId,
|
||||||
|
sessionId: trace.sessionId,
|
||||||
|
userId: trace.userId,
|
||||||
|
timestamp: trace.timestamp,
|
||||||
|
environment: trace.environment,
|
||||||
|
tags: trace.tags,
|
||||||
|
inputLength: stringifyValue(trace.input).length,
|
||||||
|
outputLength: stringifyValue(trace.output).length,
|
||||||
|
metadata: trace.metadata,
|
||||||
|
latency: trace.latency,
|
||||||
|
totalCost: trace.totalCost
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function summarizeObservation(observation: LangfuseObservationSummary) {
|
||||||
|
return {
|
||||||
|
id: observation.id,
|
||||||
|
traceId: observation.traceId,
|
||||||
|
parentObservationId: observation.parentObservationId,
|
||||||
|
type: observation.type,
|
||||||
|
name: observation.name,
|
||||||
|
startTime: observation.startTime,
|
||||||
|
endTime: observation.endTime,
|
||||||
|
model: observation.providedModelName ?? observation.model,
|
||||||
|
inputLength: stringifyValue(observation.input).length,
|
||||||
|
outputLength: stringifyValue(observation.output).length,
|
||||||
|
inputBytes: byteLength(stringifyValue(observation.input)),
|
||||||
|
outputBytes: byteLength(stringifyValue(observation.output)),
|
||||||
|
metadataKeys: objectKeys(observation.metadata),
|
||||||
|
usageDetails: observation.usageDetails,
|
||||||
|
costDetails: observation.costDetails,
|
||||||
|
totalCost: observation.totalCost
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function objectKeys(value: unknown): string[] {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function byteLength(value: string): number {
|
||||||
|
return Buffer.byteLength(value, "utf8");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function uniqueStrings(values: Array<string | undefined>): string[] {
|
||||||
|
return [...new Set(values.filter((value): value is string => Boolean(value?.trim())))];
|
||||||
|
}
|
||||||
+21
-1
@@ -10,6 +10,7 @@ import { CorpConfig } from "../../core/config/types.js";
|
|||||||
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
|
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
|
||||||
import { createSealClientForUrl } from "../../core/http/factory.js";
|
import { createSealClientForUrl } from "../../core/http/factory.js";
|
||||||
import { redactSensitiveText } from "../../core/redact.js";
|
import { redactSensitiveText } from "../../core/redact.js";
|
||||||
|
import { safetyBlocked } from "../../core/errors.js";
|
||||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||||
import {
|
import {
|
||||||
ApprovalDocumentListData,
|
ApprovalDocumentListData,
|
||||||
@@ -140,7 +141,13 @@ export async function deleteApprovalRule(client: KyInstance, ruleId: string): Pr
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function recodeApprovalRules(client: KyInstance): Promise<unknown> {
|
export async function recodeApprovalRules(client: KyInstance): Promise<unknown> {
|
||||||
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false });
|
// Legacy clear/sync callers may reset an EMPTY draft's allocation counter.
|
||||||
|
// Renumbering existing rules must go through the ticketed recode capability.
|
||||||
|
const draft = await listApprovalRules(client);
|
||||||
|
if (draft.rules.length > 0) {
|
||||||
|
throw safetyBlocked("禁止隐式重排非空草稿,请使用 rules recode 的两阶段确认流程。");
|
||||||
|
}
|
||||||
|
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false, retry: 0 });
|
||||||
const body = await response.json().catch(() => ({}));
|
const body = await response.json().catch(() => ({}));
|
||||||
return z.object({
|
return z.object({
|
||||||
ok: z.boolean(),
|
ok: z.boolean(),
|
||||||
@@ -153,6 +160,19 @@ export async function recodeApprovalRules(client: KyInstance): Promise<unknown>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Called only after the shared recode capability consumes its confirmation ticket. */
|
||||||
|
export async function executeApprovalRulesRecode(client: KyInstance) {
|
||||||
|
const response = await client.post("api/v1/rules/batch-recode", { retry: 0 });
|
||||||
|
const body = await response.json() as { data?: unknown };
|
||||||
|
const result = z.object({
|
||||||
|
activeRules: z.number().int().nonnegative(),
|
||||||
|
pendingDeleteRules: z.number().int().nonnegative(),
|
||||||
|
nextCode: z.number().int().nonnegative()
|
||||||
|
}).safeParse(body.data ?? body);
|
||||||
|
if (!result.success) throw new Error("规则重排接口返回了无效结果,请回读当前草稿确认状态。");
|
||||||
|
return result.data;
|
||||||
|
}
|
||||||
|
|
||||||
export async function listApprovalRuleVersions(client: KyInstance): Promise<RuleSetVersion[]> {
|
export async function listApprovalRuleVersions(client: KyInstance): Promise<RuleSetVersion[]> {
|
||||||
return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema));
|
return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema));
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -9,7 +9,7 @@ import {
|
|||||||
sanitizeFileName,
|
sanitizeFileName,
|
||||||
type FetchLike
|
type FetchLike
|
||||||
} from "./attachments.js";
|
} from "./attachments.js";
|
||||||
import type { ApprovalRun } from "./types.js";
|
import type { ApprovalRun } from "../types.js";
|
||||||
|
|
||||||
describe("attachments domain", () => {
|
describe("attachments domain", () => {
|
||||||
let tmpDir: string;
|
let tmpDir: string;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import type { ApprovalRun } from "./types.js";
|
import type { ApprovalRun } from "../types.js";
|
||||||
|
|
||||||
export interface ApprovalRunAttachment {
|
export interface ApprovalRunAttachment {
|
||||||
path: string;
|
path: string;
|
||||||
+2
-2
@@ -14,8 +14,8 @@ import {
|
|||||||
resolveExportDateRange,
|
resolveExportDateRange,
|
||||||
resolveOutputFilePath,
|
resolveOutputFilePath,
|
||||||
exportApprovalRunsToExcel
|
exportApprovalRunsToExcel
|
||||||
} from "./approval-runs-export.js";
|
} from "./export.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../../core/config/types.js";
|
||||||
|
|
||||||
describe("approval-runs-export helpers", () => {
|
describe("approval-runs-export helpers", () => {
|
||||||
test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => {
|
test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => {
|
||||||
@@ -3,17 +3,17 @@ import { homedir } from "node:os";
|
|||||||
import { dirname, extname, resolve } from "node:path";
|
import { dirname, extname, resolve } from "node:path";
|
||||||
import ExcelJS from "exceljs";
|
import ExcelJS from "exceljs";
|
||||||
import type { KyInstance } from "ky";
|
import type { KyInstance } from "ky";
|
||||||
import { formatBeijingIso } from "../../core/config/timestamps.js";
|
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
import type { CorpConfig } from "../../../core/config/types.js";
|
||||||
import * as api from "./api.js";
|
import * as api from "../api.js";
|
||||||
import {
|
import {
|
||||||
alignApprovalRunsWithHoseFlow,
|
alignApprovalRunsWithHoseFlow,
|
||||||
createHoseOpenClient,
|
createHoseOpenClient,
|
||||||
getHoseOpenFlow,
|
getHoseOpenFlow,
|
||||||
type HoseOpenStaffItem,
|
type HoseOpenStaffItem,
|
||||||
type HoseRunAlignment
|
type HoseRunAlignment
|
||||||
} from "../hose/index.js";
|
} from "../../hose/index.js";
|
||||||
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
|
import type { ApprovalRun, ApprovalRunListData } from "../types.js";
|
||||||
|
|
||||||
export interface ApprovalRunsExportOptions {
|
export interface ApprovalRunsExportOptions {
|
||||||
limit?: number;
|
limit?: number;
|
||||||
@@ -3,8 +3,8 @@ import type { KyInstance } from "ky";
|
|||||||
import * as api from "../api.js";
|
import * as api from "../api.js";
|
||||||
import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
|
import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
|
||||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
|
||||||
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
|
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
|
||||||
import {
|
import {
|
||||||
alignApprovalRunsWithHoseFlow,
|
alignApprovalRunsWithHoseFlow,
|
||||||
createHoseOpenClient,
|
createHoseOpenClient,
|
||||||
|
|||||||
+6
-5
@@ -4,10 +4,10 @@ import { z } from "zod";
|
|||||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { CorpConfig } from "../../core/config/types.js";
|
import { CorpConfig } from "../../../core/config/types.js";
|
||||||
import { CliError } from "../../core/errors.js";
|
import { CliError } from "../../../core/errors.js";
|
||||||
import { saveRuleMappingSnapshot } from "./rule-mapping.js";
|
import { saveRuleMappingSnapshot } from "../rules/mapping.js";
|
||||||
import { buildRulePushPlan, findSealCapability, sealCapabilities } from "./capabilities.js";
|
import { buildRulePushPlan, findSealCapability, sealCapabilities } from "../capabilities.js";
|
||||||
|
|
||||||
type CapabilityHandler = (
|
type CapabilityHandler = (
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
@@ -1198,7 +1198,8 @@ describe("sealCapabilities", () => {
|
|||||||
apiSecret: "test-sk",
|
apiSecret: "test-sk",
|
||||||
apiOrigin: "custom",
|
apiOrigin: "custom",
|
||||||
customApiUrl: "https://dd2.hosecloud.com",
|
customApiUrl: "https://dd2.hosecloud.com",
|
||||||
outboundName: "DingTalk AI Audit"
|
outboundName: "DingTalk AI Audit",
|
||||||
|
confirm: true
|
||||||
},
|
},
|
||||||
fakeContext()
|
fakeContext()
|
||||||
) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } };
|
) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } };
|
||||||
@@ -3,11 +3,19 @@ import type { KyInstance } from "ky";
|
|||||||
import { randomBytes } from "node:crypto";
|
import { randomBytes } from "node:crypto";
|
||||||
import * as api from "../api.js";
|
import * as api from "../api.js";
|
||||||
import { probeHoseDomain } from "../../../core/auth/hose.js";
|
import { probeHoseDomain } from "../../../core/auth/hose.js";
|
||||||
import { safetyBlocked, validationError } from "../../../core/errors.js";
|
import { confirmationRequired, validationError } from "../../../core/errors.js";
|
||||||
|
import { type HosecloudConfigInput } from "../types.js";
|
||||||
import {
|
import {
|
||||||
type ApprovalRun,
|
assertAssistedIntegration,
|
||||||
type HosecloudConfigInput
|
BLOCKING_NODE_ID,
|
||||||
} from "../types.js";
|
buildOutboundPayload,
|
||||||
|
buildOutboundWebhookUrl,
|
||||||
|
flowIdFromDocumentSn,
|
||||||
|
listHoseIntegrations,
|
||||||
|
pushOutboundAndVerify,
|
||||||
|
resolveCorporationId,
|
||||||
|
selectHoseIntegration
|
||||||
|
} from "../outbound/push.js";
|
||||||
import type {
|
import type {
|
||||||
CapabilityContext
|
CapabilityContext
|
||||||
} from "./helpers.js";
|
} from "./helpers.js";
|
||||||
@@ -46,7 +54,7 @@ export const deployCapabilities = [
|
|||||||
parameters: z.object({}),
|
parameters: z.object({}),
|
||||||
handler: async (client: KyInstance) => {
|
handler: async (client: KyInstance) => {
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
const config = await api.getApprovalStylePreferences(client);
|
||||||
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
|
const integrations = listHoseIntegrations(config);
|
||||||
return {
|
return {
|
||||||
count: integrations.length,
|
count: integrations.length,
|
||||||
integrations: integrations.map(redactIntegrationSecrets)
|
integrations: integrations.map(redactIntegrationSecrets)
|
||||||
@@ -61,8 +69,8 @@ export const deployCapabilities = [
|
|||||||
}),
|
}),
|
||||||
handler: async (client: KyInstance, params: { signKey: string }) => {
|
handler: async (client: KyInstance, params: { signKey: string }) => {
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
const config = await api.getApprovalStylePreferences(client);
|
||||||
const integration = (config.integrations ?? []).find(
|
const integration = listHoseIntegrations(config).find(
|
||||||
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
|
(item) => item.signKey === params.signKey
|
||||||
);
|
);
|
||||||
if (!integration) {
|
if (!integration) {
|
||||||
throw new Error(`未找到合思配置:${params.signKey}`);
|
throw new Error(`未找到合思配置:${params.signKey}`);
|
||||||
@@ -77,7 +85,7 @@ export const deployCapabilities = [
|
|||||||
handler: async (client: KyInstance) => {
|
handler: async (client: KyInstance) => {
|
||||||
const status = await api.getSimulationIntegrationStatus(client);
|
const status = await api.getSimulationIntegrationStatus(client);
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
const config = await api.getApprovalStylePreferences(client);
|
||||||
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
|
const integrations = listHoseIntegrations(config);
|
||||||
return {
|
return {
|
||||||
status,
|
status,
|
||||||
integrations: integrations.map(redactIntegrationSecrets)
|
integrations: integrations.map(redactIntegrationSecrets)
|
||||||
@@ -107,12 +115,13 @@ export const deployCapabilities = [
|
|||||||
autoApproveNodeNames: z.array(z.string()).optional(),
|
autoApproveNodeNames: z.array(z.string()).optional(),
|
||||||
apiOrigin: z.string().default("production"),
|
apiOrigin: z.string().default("production"),
|
||||||
customApiUrl: z.string().optional(),
|
customApiUrl: z.string().optional(),
|
||||||
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
|
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入"),
|
||||||
|
confirm: z.boolean().optional().describe("明确确认保存配置;CLI 使用 --yes 或 --confirm")
|
||||||
}),
|
}),
|
||||||
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: CapabilityContext) => {
|
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: CapabilityContext) => {
|
||||||
const { dryRun, ...inputParams } = rawParams;
|
const { dryRun, confirm, appKey, appSecurity, ...inputParams } = rawParams;
|
||||||
const apiKey = inputParams.apiKey ?? (inputParams as any).appKey;
|
const apiKey = inputParams.apiKey ?? (typeof appKey === "string" ? appKey : undefined);
|
||||||
const apiSecret = inputParams.apiSecret ?? (inputParams as any).appSecurity;
|
const apiSecret = inputParams.apiSecret ?? (typeof appSecurity === "string" ? appSecurity : undefined);
|
||||||
if (!apiKey || !apiSecret) {
|
if (!apiKey || !apiSecret) {
|
||||||
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
|
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
|
||||||
}
|
}
|
||||||
@@ -120,6 +129,16 @@ export const deployCapabilities = [
|
|||||||
let effectiveApiOrigin = params.apiOrigin ?? "production";
|
let effectiveApiOrigin = params.apiOrigin ?? "production";
|
||||||
let effectiveCustomApiUrl = params.customApiUrl;
|
let effectiveCustomApiUrl = params.customApiUrl;
|
||||||
|
|
||||||
|
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
|
||||||
|
throw new Error("自定义合思环境必须提供 customApiUrl");
|
||||||
|
}
|
||||||
|
if (!dryRun && confirm !== true) {
|
||||||
|
throw confirmationRequired(
|
||||||
|
"Refusing to save Hose integration configuration without --yes or --confirm. Use --dry-run to preview first.",
|
||||||
|
"seal-use help deploy hosecloud configure"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名
|
// 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名
|
||||||
if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") {
|
if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") {
|
||||||
try {
|
try {
|
||||||
@@ -138,17 +157,13 @@ export const deployCapabilities = [
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
|
|
||||||
throw new Error("自定义合思环境必须提供 customApiUrl");
|
|
||||||
}
|
|
||||||
|
|
||||||
const corpResult = await api.getHosecloudCorporation(client, {
|
const corpResult = await api.getHosecloudCorporation(client, {
|
||||||
apiKey: params.apiKey,
|
apiKey: params.apiKey,
|
||||||
apiSecret: params.apiSecret,
|
apiSecret: params.apiSecret,
|
||||||
apiOrigin: effectiveApiOrigin,
|
apiOrigin: effectiveApiOrigin,
|
||||||
customApiUrl: effectiveCustomApiUrl
|
customApiUrl: effectiveCustomApiUrl
|
||||||
});
|
});
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences);
|
||||||
const signKey = params.signKey ?? randomBytes(6).toString("hex");
|
const signKey = params.signKey ?? randomBytes(6).toString("hex");
|
||||||
const nextIntegration = {
|
const nextIntegration = {
|
||||||
type: "hosecloud",
|
type: "hosecloud",
|
||||||
@@ -179,7 +194,7 @@ export const deployCapabilities = [
|
|||||||
await api.updateApprovalStylePreferences(client, nextConfig, context.corp.seal.endpoints.approvalStylePreferences);
|
await api.updateApprovalStylePreferences(client, nextConfig, context.corp.seal.endpoints.approvalStylePreferences);
|
||||||
|
|
||||||
console.error(`✓ 配置已保存 (signKey: ${signKey})`);
|
console.error(`✓ 配置已保存 (signKey: ${signKey})`);
|
||||||
console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}`);
|
console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --dry-run --corp ${context.corp.id}`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
integration: redactIntegrationSecrets(nextIntegration)
|
integration: redactIntegrationSecrets(nextIntegration)
|
||||||
@@ -190,25 +205,42 @@ export const deployCapabilities = [
|
|||||||
name: "sealDeployHosecloudSync",
|
name: "sealDeployHosecloudSync",
|
||||||
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
|
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
signKey: z.string().describe("合思集成 sign-key")
|
signKey: z.string().describe("合思集成 sign-key"),
|
||||||
|
dryRun: z.boolean().optional().describe("只预览待同步的消息名称、回调地址和模式,不执行同步"),
|
||||||
|
confirm: z.boolean().optional().describe("明确确认同步到合思;CLI 使用 --yes 或 --confirm")
|
||||||
}),
|
}),
|
||||||
handler: async (client: KyInstance, params: { signKey: string }, context: CapabilityContext) => {
|
handler: async (client: KyInstance, params: { signKey: string; dryRun?: boolean; confirm?: boolean }, context: CapabilityContext) => {
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
if (!params.dryRun && params.confirm !== true) {
|
||||||
const integration = (config.integrations ?? []).find(
|
throw confirmationRequired(
|
||||||
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
|
"Refusing to synchronize Hose outbound messages without --yes or --confirm. Use --dry-run to preview first.",
|
||||||
|
`seal-use deploy hosecloud sync ${params.signKey} --dry-run --corp ${context.corp.id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences);
|
||||||
|
const integration = listHoseIntegrations(config).find(
|
||||||
|
(item) => item.signKey === params.signKey
|
||||||
);
|
);
|
||||||
if (!integration) {
|
if (!integration) {
|
||||||
throw new Error(`未找到合思配置:${params.signKey}`);
|
throw new Error(`未找到合思配置:${params.signKey}`);
|
||||||
}
|
}
|
||||||
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
||||||
const messageName = (integration as any).outboundName ?? "SealAI 审批";
|
const messageName = integration.outboundName ?? "SealAI 审批";
|
||||||
const result = await api.syncHosecloudOutbound(client, {
|
const payload = {
|
||||||
signKey: params.signKey,
|
signKey: params.signKey,
|
||||||
webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`,
|
webhookUrl: buildOutboundWebhookUrl(context.corp, params.signKey),
|
||||||
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
|
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
|
||||||
messageName,
|
messageName,
|
||||||
mode: (integration as any).mode ?? "assisted"
|
mode: integration.mode ?? "assisted"
|
||||||
});
|
};
|
||||||
|
if (params.dryRun) {
|
||||||
|
return {
|
||||||
|
...mutationPreview(context, "api/hosecloud/outbound-config/sync", null, payload, 1),
|
||||||
|
signKey: params.signKey,
|
||||||
|
remoteStateKnown: false,
|
||||||
|
note: "仅预览将同步的消息名称、回调地址和模式;合思远端当前配置尚未读取。"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const result = await api.syncHosecloudOutbound(client, payload);
|
||||||
|
|
||||||
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
|
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
|
||||||
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
|
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
|
||||||
@@ -228,10 +260,11 @@ export const deployCapabilities = [
|
|||||||
flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"),
|
flowId: z.string().optional().describe("合思单据/流程 ID (flowId / sourceDocumentId)"),
|
||||||
sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"),
|
sn: z.string().optional().describe("合思单号 (sourceDocumentSN,若未提供 flowId 可自动解析)"),
|
||||||
messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"),
|
messageId: z.string().describe("合思真实的 messageId(合思开放平台消息凭证,必须提供真实有效值以供拉取单据)"),
|
||||||
nodeId: z.string().optional().default("FLOW:测试模拟节点_禁止流转").describe("合思流程节点 ID(默认填入中文阻断标识)"),
|
nodeId: z.string().optional().default(BLOCKING_NODE_ID).describe("合思流程节点 ID(默认填入中文阻断标识)"),
|
||||||
rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"),
|
rejectionNum: z.number().int().optional().default(0).describe("驳回/重提次数(默认 0)"),
|
||||||
corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"),
|
corporationId: z.string().optional().describe("合思企业 ID(若未提供则取自集成配置)"),
|
||||||
dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送")
|
dryRun: z.boolean().optional().default(false).describe("是否仅预览请求载荷与安全检查而不实际推送"),
|
||||||
|
confirm: z.boolean().optional().describe("明确确认实际推送;CLI 使用 --yes 或 --confirm")
|
||||||
}),
|
}),
|
||||||
handler: async (
|
handler: async (
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
@@ -244,43 +277,23 @@ export const deployCapabilities = [
|
|||||||
rejectionNum?: number;
|
rejectionNum?: number;
|
||||||
corporationId?: string;
|
corporationId?: string;
|
||||||
dryRun?: boolean;
|
dryRun?: boolean;
|
||||||
|
confirm?: boolean;
|
||||||
},
|
},
|
||||||
context: CapabilityContext
|
context: CapabilityContext
|
||||||
) => {
|
) => {
|
||||||
const config = await api.getApprovalStylePreferences(client);
|
const config = await api.getApprovalStylePreferences(client);
|
||||||
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
const integration = selectHoseIntegration({
|
||||||
if (hoseConfigs.length === 0) {
|
integrations: listHoseIntegrations(config),
|
||||||
throw new Error(
|
signKey: params.signKey,
|
||||||
`当前企业 (${context.corp.name}) 尚未添加合思发布配置。\n` +
|
corpName: context.corp.name,
|
||||||
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${context.corp.id}`
|
corpId: context.corp.id
|
||||||
);
|
});
|
||||||
}
|
|
||||||
|
|
||||||
let integration: any;
|
|
||||||
if (params.signKey) {
|
|
||||||
integration = hoseConfigs.find((i: any) => i.signKey === params.signKey);
|
|
||||||
if (!integration) {
|
|
||||||
throw validationError(
|
|
||||||
`未找到 signKey 为「${params.signKey}」的合思集成配置。可用 signKey: ${hoseConfigs.map((i: any) => i.signKey).join(", ")}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else if (hoseConfigs.length === 1) {
|
|
||||||
integration = hoseConfigs[0];
|
|
||||||
} else {
|
|
||||||
const list = hoseConfigs.map((i: any) => `"${i.outboundName ?? "SealAI 审批"}" (signKey: ${i.signKey})`).join(", ");
|
|
||||||
throw validationError(
|
|
||||||
`当前企业存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式
|
// 1. 严格安全门禁检查:强制要求目标集成必须为 assisted 模式
|
||||||
const mode = integration.mode ?? "assisted";
|
assertAssistedIntegration(integration, {
|
||||||
if (mode !== "assisted") {
|
corpName: context.corp.name,
|
||||||
throw safetyBlocked(
|
corpId: context.corp.id
|
||||||
`安全阻断:目标合思配置「${integration.outboundName ?? integration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。为防止自动向合思回写审批动作影响生产/线上流程,严禁在此模式下测试出站通道。`,
|
});
|
||||||
`请先在目标企业将模式调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${context.corp.id}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 消息凭证校验
|
// 2. 消息凭证校验
|
||||||
const messageId = params.messageId?.trim();
|
const messageId = params.messageId?.trim();
|
||||||
@@ -309,8 +322,8 @@ export const deployCapabilities = [
|
|||||||
} catch {
|
} catch {
|
||||||
// 忽略
|
// 忽略
|
||||||
}
|
}
|
||||||
if (!flowId && sn.startsWith("ID01")) {
|
if (!flowId) {
|
||||||
flowId = sn;
|
flowId = flowIdFromDocumentSn(sn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -321,26 +334,16 @@ export const deployCapabilities = [
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 4. 解析 corporationId
|
// 4. 解析 corporationId
|
||||||
const corporationId = params.corporationId?.trim() || integration.corporationId;
|
const corporationId = resolveCorporationId([params.corporationId, integration.corporationId]);
|
||||||
if (!corporationId) {
|
|
||||||
throw validationError(
|
|
||||||
"缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const nodeId = params.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转";
|
const payload = buildOutboundPayload({
|
||||||
const rejectionNum = params.rejectionNum ?? 0;
|
|
||||||
|
|
||||||
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
|
||||||
const webhookUrl = `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(integration.signKey)}`;
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
flowId,
|
flowId,
|
||||||
nodeId,
|
|
||||||
messageId,
|
messageId,
|
||||||
rejectionNum,
|
nodeId: params.nodeId,
|
||||||
|
rejectionNum: params.rejectionNum,
|
||||||
corporationId
|
corporationId
|
||||||
};
|
});
|
||||||
|
const webhookUrl = buildOutboundWebhookUrl(context.corp, integration.signKey!);
|
||||||
|
|
||||||
if (params.dryRun) {
|
if (params.dryRun) {
|
||||||
return {
|
return {
|
||||||
@@ -355,36 +358,28 @@ export const deployCapabilities = [
|
|||||||
safetyCheck: {
|
safetyCheck: {
|
||||||
mode: "assisted",
|
mode: "assisted",
|
||||||
passed: true,
|
passed: true,
|
||||||
note: "目标企业出站模式为 assisted,AI 绝不会向合思回写审批动作;且默认 nodeId 包含中文阻断标记,双重安全保障。"
|
nodeId412Blocked: payload.nodeId === BLOCKING_NODE_ID,
|
||||||
|
note: payload.nodeId === BLOCKING_NODE_ID
|
||||||
|
? "目标企业出站模式为 assisted;使用默认中文 nodeId 阻断标记。"
|
||||||
|
: "目标企业出站模式为 assisted;自定义 nodeId 未验证具备 HTTP 412 阻断保障。"
|
||||||
},
|
},
|
||||||
payload
|
payload
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await api.postHosecloudOutbound(client, integration.signKey, payload);
|
const { response, createdRecord } = await pushOutboundAndVerify({
|
||||||
|
client,
|
||||||
// 等待后台队列消费 (2秒)
|
signKey: integration.signKey!,
|
||||||
await new Promise((r) => setTimeout(r, 2000));
|
payload,
|
||||||
let createdRecord: ApprovalRun | undefined;
|
flowId,
|
||||||
try {
|
sn,
|
||||||
const runs = await api.listApprovalRuns(client, {
|
confirm: params.confirm,
|
||||||
limit: 5,
|
corpName: context.corp.name,
|
||||||
search: flowId
|
corpId: context.corp.id,
|
||||||
});
|
pushedMessages: [
|
||||||
createdRecord = (runs.records || []).find(
|
`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`
|
||||||
(r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === flowId
|
]
|
||||||
);
|
});
|
||||||
} catch {
|
|
||||||
// 非阻塞
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error(`✓ 已成功向合思出站通道推送测试消息 (flowId: ${flowId}, signKey: ${integration.signKey})`);
|
|
||||||
if (createdRecord) {
|
|
||||||
console.error(`✓ 异步消费成功!已在【${context.corp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`);
|
|
||||||
console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${context.corp.id}`);
|
|
||||||
} else {
|
|
||||||
console.error(`ℹ️ 消息已入队正在异步消费,可在几秒后刷新后台页面或查询: seal-use approval-runs list --corp ${context.corp.id}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -393,6 +388,7 @@ export const deployCapabilities = [
|
|||||||
mode: integration.mode,
|
mode: integration.mode,
|
||||||
payload,
|
payload,
|
||||||
response,
|
response,
|
||||||
|
consumptionVerified: createdRecord !== undefined,
|
||||||
recordId: createdRecord?.id,
|
recordId: createdRecord?.id,
|
||||||
recordStatus: createdRecord?.status,
|
recordStatus: createdRecord?.status,
|
||||||
taskMode: createdRecord?.taskMode
|
taskMode: createdRecord?.taskMode
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Size ratchet for `helpers.ts` (see the FROZEN header at the top of that file).
|
||||||
|
*
|
||||||
|
* The module is the historical dumping ground for anything a capability needed,
|
||||||
|
* and `export *` from index.ts leaks all of it into every capability's
|
||||||
|
* namespace. A comment alone does not stop the next addition, so the ceiling is
|
||||||
|
* enforced here: adding an export (or growing the file) fails CI with a message
|
||||||
|
* that says where the logic should go instead.
|
||||||
|
*
|
||||||
|
* Both ceilings may go DOWN — moving an export out to a focused module is the
|
||||||
|
* intended fix. Only `helpers.ts` is measured; sibling modules are unrestricted.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const HELPERS_PATH = join(import.meta.dirname, "helpers.ts");
|
||||||
|
|
||||||
|
// Lower these only when logic actually leaves the file.
|
||||||
|
const MAX_LINES = 1694;
|
||||||
|
const MAX_EXPORTS = 85;
|
||||||
|
|
||||||
|
function measure(source: string) {
|
||||||
|
const lines = source.split("\n").length;
|
||||||
|
// Top-level `export` declarations only; re-exports and `export { x } from`
|
||||||
|
// lists would be counted by a looser pattern.
|
||||||
|
const exports = source.match(/^export (?:async )?(?:function|const|class|type|interface|enum) /gm);
|
||||||
|
return { lines, exports: exports?.length ?? 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("capabilities/helpers.ts freeze", () => {
|
||||||
|
const source = readFileSync(HELPERS_PATH, "utf8");
|
||||||
|
const { lines, exports } = measure(source);
|
||||||
|
|
||||||
|
test("stays under the line ceiling", () => {
|
||||||
|
expect(
|
||||||
|
lines,
|
||||||
|
`helpers.ts is ${lines} lines (ceiling ${MAX_LINES}). It is frozen: add new ` +
|
||||||
|
`logic to a focused module next to its domain instead of growing this grab-bag, ` +
|
||||||
|
`or move an existing export out to lower the ceiling.`
|
||||||
|
).toBeLessThanOrEqual(MAX_LINES);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("stays under the export ceiling", () => {
|
||||||
|
expect(
|
||||||
|
exports,
|
||||||
|
`helpers.ts exports ${exports} symbols (ceiling ${MAX_EXPORTS}). New exports are ` +
|
||||||
|
`not accepted here — index.ts re-exports the whole file into every capability's ` +
|
||||||
|
`namespace. Give the function a home beside the domain that owns it.`
|
||||||
|
).toBeLessThanOrEqual(MAX_EXPORTS);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the FROZEN header stays in place", () => {
|
||||||
|
expect(source.startsWith("// FROZEN")).toBe(true);
|
||||||
|
expect(source).toContain("helpers.freeze.test.ts");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("no re-export syntax sneaks new symbols into the namespace", () => {
|
||||||
|
// The declaration counter above does not see `export { x } from "..."` or
|
||||||
|
// `export *`, which would re-publish helpers from this file's namespace
|
||||||
|
// without touching either ceiling.
|
||||||
|
expect(source).not.toMatch(/^export\s*(\{|\*)/m);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("measures what it claims to measure", () => {
|
||||||
|
// Guard the ratchet itself: a pattern that matches nothing would silently
|
||||||
|
// pin the export ceiling at 0 and pass forever.
|
||||||
|
expect(exports).toBeGreaterThan(0);
|
||||||
|
expect(lines).toBeGreaterThan(MAX_LINES - 200);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,16 @@
|
|||||||
|
// FROZEN — see helpers.freeze.test.ts, which fails the build if this file grows.
|
||||||
|
//
|
||||||
|
// This module started as shared plumbing for the capability registry and has
|
||||||
|
// been the default place to drop anything for years. It now holds ~85 exports
|
||||||
|
// spanning unrelated concerns (base URLs, rule versions, Beijing timestamps,
|
||||||
|
// generic object paths), and `export *` in index.ts pushes every one of them
|
||||||
|
// into every capability's namespace — which is why the same helper gets
|
||||||
|
// re-derived instead of reused.
|
||||||
|
//
|
||||||
|
// Rules while frozen:
|
||||||
|
// - No new exports. Put new logic in a focused module next to its domain.
|
||||||
|
// - Existing exports may move out (update importers) — the budget only drops.
|
||||||
|
// - Fixes to existing exports are fine; the line/export ceiling is the guard.
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { KyInstance } from "ky";
|
import type { KyInstance } from "ky";
|
||||||
import type { CorpConfig } from "../../../core/config/types.js";
|
import type { CorpConfig } from "../../../core/config/types.js";
|
||||||
@@ -10,10 +23,11 @@ import type {
|
|||||||
SimulationBatch,
|
SimulationBatch,
|
||||||
WebhookIntegration
|
WebhookIntegration
|
||||||
} from "../types.js";
|
} from "../types.js";
|
||||||
import { extractApprovalRunAttachments } from "../attachments.js";
|
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
|
||||||
import type { LocalRuleItem } from "../rules-local.js";
|
import type { LocalRuleItem } from "../rules/local.js";
|
||||||
import { loadRuleMappingSnapshot } from "../rule-mapping.js";
|
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
|
||||||
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
|
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
|
||||||
|
import { validationError } from "../../../core/errors.js";
|
||||||
|
|
||||||
export type CapabilityContext = {
|
export type CapabilityContext = {
|
||||||
corp: CorpConfig;
|
corp: CorpConfig;
|
||||||
@@ -156,21 +170,17 @@ export function buildRulePushPlan(
|
|||||||
if (localRule.id) {
|
if (localRule.id) {
|
||||||
remoteRule = remoteById.get(localRule.id);
|
remoteRule = remoteById.get(localRule.id);
|
||||||
if (!remoteRule) {
|
if (!remoteRule) {
|
||||||
throw new Error(
|
throw validationError(`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`);
|
||||||
`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (usedRemoteIds.has(localRule.id)) {
|
if (usedRemoteIds.has(localRule.id)) {
|
||||||
throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`);
|
throw validationError(`本地规则文件包含重复的规则 ID:${localRule.id}`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const matches = remoteRules.filter(
|
const matches = remoteRules.filter(
|
||||||
(candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule)
|
(candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule)
|
||||||
);
|
);
|
||||||
if (matches.length > 1) {
|
if (matches.length > 1) {
|
||||||
throw new Error(
|
throw validationError(`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`);
|
||||||
`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
remoteRule = matches[0];
|
remoteRule = matches[0];
|
||||||
}
|
}
|
||||||
@@ -254,21 +264,6 @@ export type SimulationBatchCreateInput = {
|
|||||||
rawParams?: Record<string, unknown>;
|
rawParams?: Record<string, unknown>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function parseDurationMs(duration: string): number {
|
|
||||||
const match = duration.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i);
|
|
||||||
if (!match || !match[1]) return 600000;
|
|
||||||
const val = parseFloat(match[1]);
|
|
||||||
const unit = (match[2] ?? "s").toLowerCase();
|
|
||||||
switch (unit) {
|
|
||||||
case "ms": return val;
|
|
||||||
case "s": return val * 1000;
|
|
||||||
case "m": return val * 60 * 1000;
|
|
||||||
case "h": return val * 3600 * 1000;
|
|
||||||
case "d": return val * 86400 * 1000;
|
|
||||||
default: return val * 1000;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function redactIntegrationSecrets(integration: Record<string, unknown>) {
|
export function redactIntegrationSecrets(integration: Record<string, unknown>) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(integration).map(([key, value]) => [
|
Object.entries(integration).map(([key, value]) => [
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
|
|||||||
"sealApprovalRuleUpdate",
|
"sealApprovalRuleUpdate",
|
||||||
"sealApprovalRuleVersionPublish",
|
"sealApprovalRuleVersionPublish",
|
||||||
"sealApprovalRulesClear",
|
"sealApprovalRulesClear",
|
||||||
|
"sealApprovalRulesRecode",
|
||||||
"sealApprovalRulesPush",
|
"sealApprovalRulesPush",
|
||||||
"sealApprovalStylePreferencesUpdate",
|
"sealApprovalStylePreferencesUpdate",
|
||||||
"sealDelegationCreate",
|
"sealDelegationCreate",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { KyInstance } from "ky";
|
import type { KyInstance } from "ky";
|
||||||
import * as api from "../api.js";
|
import * as api from "../api.js";
|
||||||
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
|
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight/export.js";
|
||||||
import type {
|
import type {
|
||||||
CapabilityContext
|
CapabilityContext
|
||||||
} from "./helpers.js";
|
} from "./helpers.js";
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { KyInstance } from "ky";
|
import type { KyInstance } from "ky";
|
||||||
import { buildMonthlyReport } from "../reports/monthly.js";
|
import { buildMonthlyReport } from "../reports/index.js";
|
||||||
import type { CapabilityContext } from "./helpers.js";
|
import type { CapabilityContext } from "./helpers.js";
|
||||||
|
|
||||||
export const reportCapabilities = [
|
export const reportCapabilities = [
|
||||||
@@ -16,7 +16,7 @@ export const reportCapabilities = [
|
|||||||
templatePath: z
|
templatePath: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe("自定义模板 Markdown 路径;缺省用 report-templates/monthly.md"),
|
.describe("自定义模板 Markdown 路径;缺省用随 CLI 内嵌的仓内 monthly.md,不依赖当前目录"),
|
||||||
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
|
reportId: z.string().optional().describe("自定义报告编号(RPT-YYYYMM-XXXXXX)"),
|
||||||
maxRuns: z
|
maxRuns: z
|
||||||
.number()
|
.number()
|
||||||
|
|||||||
@@ -1,23 +1,24 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { KyInstance } from "ky";
|
import type { KyInstance } from "ky";
|
||||||
import * as api from "../api.js";
|
import * as api from "../api.js";
|
||||||
|
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
|
||||||
|
import { executeRulePush } from "../rules/push.js";
|
||||||
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
import { formatBeijingIso } from "../../../core/config/timestamps.js";
|
||||||
import { loadGlobalConfig } from "../../../core/config/loader.js";
|
import { loadGlobalConfig } from "../../../core/config/loader.js";
|
||||||
import { validationError } from "../../../core/errors.js";
|
import { validationError } from "../../../core/errors.js";
|
||||||
import { redactSensitiveText } from "../../../core/redact.js";
|
import { redactSensitiveText } from "../../../core/redact.js";
|
||||||
import { searchApprovalContent } from "../search.js";
|
import { searchApprovalContent } from "../search/service.js";
|
||||||
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
|
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rules/diff.js";
|
||||||
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
|
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rules/version-snapshot.js";
|
||||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
|
||||||
import {
|
import {
|
||||||
loadLocalRulesFile,
|
loadLocalRulesFile,
|
||||||
saveLocalRulesFile,
|
saveLocalRulesFile,
|
||||||
localRulesToLintTargets,
|
localRulesToLintTargets,
|
||||||
type LocalRuleItem
|
type LocalRuleItem
|
||||||
} from "../rules-local.js";
|
} from "../rules/local.js";
|
||||||
import {
|
import {
|
||||||
type ApprovalRule,
|
type ApprovalRule
|
||||||
type RuleSetVersion
|
|
||||||
} from "../types.js";
|
} from "../types.js";
|
||||||
import type {
|
import type {
|
||||||
CapabilityContext,
|
CapabilityContext,
|
||||||
@@ -27,8 +28,6 @@ import * as helpers from "./helpers.js";
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
projectApprovalRules,
|
projectApprovalRules,
|
||||||
buildRulePushPlan,
|
|
||||||
normalizeRuleStrictness,
|
|
||||||
mutationPreview,
|
mutationPreview,
|
||||||
summarizeRuleVersion,
|
summarizeRuleVersion,
|
||||||
resolveRuleVersionForLookup,
|
resolveRuleVersionForLookup,
|
||||||
@@ -48,6 +47,16 @@ function attachCrossEnvRule(context: CapabilityContext, rule: Record<string, unk
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const rulesCapabilities = [
|
export const rulesCapabilities = [
|
||||||
|
{
|
||||||
|
name: "sealApprovalRulesRecode",
|
||||||
|
description: "重排草稿规则编号;首次返回预览与一次性确认码,第二次携带确认码才执行,不发布版本",
|
||||||
|
parameters: z.object({
|
||||||
|
dryRun: z.boolean().optional().describe("只预览,不签发确认码或执行重排"),
|
||||||
|
confirmCode: z.string().optional().describe("第一次运行返回的一次性确认码")
|
||||||
|
}),
|
||||||
|
handler: async (client: KyInstance, params: RecodeOptions, context: CapabilityContext) =>
|
||||||
|
recodeRules(client, context.corp, params)
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "sealApprovalRulesList",
|
name: "sealApprovalRulesList",
|
||||||
description: "列出 Seal 审批规则(默认当前草稿,传 version='latest' 或版本号则列出对应已发布版本);支持 countOnly、fields、limit",
|
description: "列出 Seal 审批规则(默认当前草稿,传 version='latest' 或版本号则列出对应已发布版本);支持 countOnly、fields、limit",
|
||||||
@@ -144,8 +153,13 @@ export const rulesCapabilities = [
|
|||||||
|
|
||||||
const warnings: string[] = [];
|
const warnings: string[] = [];
|
||||||
let recode: unknown;
|
let recode: unknown;
|
||||||
|
const remaining = await api.listApprovalRules(client);
|
||||||
if (deleted > 0 && params.recode !== false) {
|
if (deleted > 0 && params.recode !== false) {
|
||||||
recode = await api.recodeApprovalRules(client);
|
if (remaining.rules.length > 0) {
|
||||||
|
warnings.push("部分规则未删除,已跳过自动重排;如需重排剩余规则,请使用 rules recode 两阶段流程");
|
||||||
|
} else {
|
||||||
|
recode = await api.recodeApprovalRules(client);
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
recode &&
|
recode &&
|
||||||
typeof recode === "object" &&
|
typeof recode === "object" &&
|
||||||
@@ -156,7 +170,7 @@ export const rulesCapabilities = [
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const after = await api.listApprovalRules(client);
|
const after = recode ? await api.listApprovalRules(client) : remaining;
|
||||||
return {
|
return {
|
||||||
corpId: context.corp.id,
|
corpId: context.corp.id,
|
||||||
corpName: context.corp.name,
|
corpName: context.corp.name,
|
||||||
@@ -640,13 +654,14 @@ export const rulesCapabilities = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "sealApprovalRulesPush",
|
name: "sealApprovalRulesPush",
|
||||||
description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本",
|
description: "将本地规则文件增量同步到远端草稿;支持持久化步骤恢复记录、状态核对(--status)与直接发布正式版本",
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
|
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
|
||||||
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
|
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
|
||||||
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
|
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
|
||||||
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
|
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
|
||||||
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")
|
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)"),
|
||||||
|
statusOnly: z.boolean().optional().describe("仅查询最近一次 rules push 的持久化步骤记录并与远端草稿核对,不执行写入")
|
||||||
}),
|
}),
|
||||||
handler: async (
|
handler: async (
|
||||||
client: KyInstance,
|
client: KyInstance,
|
||||||
@@ -656,110 +671,10 @@ export const rulesCapabilities = [
|
|||||||
confirm?: boolean;
|
confirm?: boolean;
|
||||||
publish?: boolean;
|
publish?: boolean;
|
||||||
versionName?: string;
|
versionName?: string;
|
||||||
|
statusOnly?: boolean;
|
||||||
},
|
},
|
||||||
context: CapabilityContext
|
context: CapabilityContext
|
||||||
) => {
|
) => executeRulePush(client, params, context)
|
||||||
const filePath = params.file ?? "./rules.local.json";
|
|
||||||
let local: ReturnType<typeof loadLocalRulesFile>;
|
|
||||||
try {
|
|
||||||
local = loadLocalRulesFile(filePath);
|
|
||||||
} catch (err) {
|
|
||||||
if (params.publish && !params.file) {
|
|
||||||
const suggestedName = params.versionName ?? "新版本";
|
|
||||||
throw new Error(
|
|
||||||
`${err instanceof Error ? err.message : String(err)}\n👉 Next action: 若您已直接修改远端草稿、仅需发布正式版本,请执行 seal-use rules publish "${suggestedName}" --corp ${context.corp.id}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
const isConfirmed = params.confirm === true;
|
|
||||||
// Fail closed: without an explicit confirm the push always previews, even when dryRun=false.
|
|
||||||
const isDryRun = !isConfirmed || params.dryRun === true;
|
|
||||||
|
|
||||||
const before = await api.listApprovalRules(client);
|
|
||||||
const plan = buildRulePushPlan(before.rules, local.rules);
|
|
||||||
|
|
||||||
if (isDryRun) {
|
|
||||||
return {
|
|
||||||
...mutationPreview(
|
|
||||||
context,
|
|
||||||
"api/v1/rules",
|
|
||||||
before.rules,
|
|
||||||
local.rules.map((rule) => ({
|
|
||||||
description: rule.description,
|
|
||||||
scope: rule.scope ?? "ALL",
|
|
||||||
strictness: rule.strictness ?? "MUST_FOLLOW"
|
|
||||||
})),
|
|
||||||
before.rules.length + local.rules.length
|
|
||||||
),
|
|
||||||
corpId: context.corp.id,
|
|
||||||
dryRun: true,
|
|
||||||
localFile: local.resolvedPath,
|
|
||||||
localRulesCount: local.rules.length,
|
|
||||||
remoteDraftCount: before.rules.length,
|
|
||||||
changes: plan,
|
|
||||||
impactCount: plan.created.length + plan.updated.length + plan.deleted.length,
|
|
||||||
preservedRuleIds: [
|
|
||||||
...plan.updated.map((change) => change.id),
|
|
||||||
...plan.unchanged.map((rule) => rule.id)
|
|
||||||
],
|
|
||||||
warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.",
|
|
||||||
willPublish: Boolean(params.publish),
|
|
||||||
message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const rule of plan.deleted) {
|
|
||||||
await api.deleteApprovalRule(client, rule.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
const created: Array<{ id: string; description: string; code?: string | number }> = [];
|
|
||||||
for (const rule of plan.created) {
|
|
||||||
const newRule = await api.createApprovalRule(client, {
|
|
||||||
description: rule.description,
|
|
||||||
scope: rule.scope ?? "ALL",
|
|
||||||
strictness: normalizeRuleStrictness(rule.strictness)
|
|
||||||
});
|
|
||||||
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
|
|
||||||
}
|
|
||||||
|
|
||||||
const updated: string[] = [];
|
|
||||||
for (const change of plan.updated) {
|
|
||||||
await api.updateApprovalRule(client, change.id, {
|
|
||||||
description: change.rule.description,
|
|
||||||
scope: change.rule.scope ?? "ALL",
|
|
||||||
strictness: normalizeRuleStrictness(change.rule.strictness)
|
|
||||||
});
|
|
||||||
updated.push(change.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
let publishedVersion: unknown = undefined;
|
|
||||||
if (params.publish) {
|
|
||||||
const dateStr = formatBeijingIso().slice(0, 10).replace(/-/g, "");
|
|
||||||
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
|
|
||||||
publishedVersion = await api.publishApprovalRuleVersion(client, name);
|
|
||||||
try {
|
|
||||||
const draft = await api.listApprovalRules(client);
|
|
||||||
savePublishedRuleVersionSnapshot(context.corp.id, (publishedVersion as { version: RuleSetVersion }).version, draft.rules);
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
corpId: context.corp.id,
|
|
||||||
dryRun: false,
|
|
||||||
localFile: local.resolvedPath,
|
|
||||||
deletedRules: plan.deleted.length,
|
|
||||||
createdRules: created.length,
|
|
||||||
updatedRules: updated.length,
|
|
||||||
unchangedRules: plan.unchanged.length,
|
|
||||||
preservedRuleIds: [
|
|
||||||
...updated,
|
|
||||||
...plan.unchanged.map((rule) => rule.id)
|
|
||||||
],
|
|
||||||
recoded: false,
|
|
||||||
published: publishedVersion ?? false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "sealApprovalDocumentsList",
|
name: "sealApprovalDocumentsList",
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ import {
|
|||||||
type SimulationBatch
|
type SimulationBatch
|
||||||
} from "../types.js";
|
} from "../types.js";
|
||||||
import * as helpers from "./helpers.js";
|
import * as helpers from "./helpers.js";
|
||||||
|
import { parseDurationMs } from "../../../core/duration.js";
|
||||||
|
|
||||||
const {
|
const {
|
||||||
parseDurationMs,
|
|
||||||
buildSimulationBatchParams,
|
buildSimulationBatchParams,
|
||||||
summarizeSimulationBatch,
|
summarizeSimulationBatch,
|
||||||
summarizeApprovalRun,
|
summarizeApprovalRun,
|
||||||
|
|||||||
@@ -21,13 +21,11 @@ function rejectsWith(toolName: string, params: Record<string, unknown>): string
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("parseCapabilityParams", () => {
|
describe("parseCapabilityParams", () => {
|
||||||
test("accepts valid params and returns the exact object it was given", () => {
|
test("accepts valid params and returns normalized values without mutating caller input", () => {
|
||||||
const target = tool("sealUserCreate");
|
const target = tool("sealUserCreate");
|
||||||
const params = { name: "张三", phone: "13800001111", departmentIds: ["d1"] };
|
const params = { name: "张三", phone: "13800001111", departmentIds: ["d1"] };
|
||||||
|
|
||||||
// Identity matters: handlers read keys the schema does not declare, so the
|
expect(parseCapabilityParams(target, params)).toEqual(params);
|
||||||
// gate must pass its input through, never zod's (stripped) parse output.
|
|
||||||
expect(parseCapabilityParams(target, params)).toBe(params);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("names the missing required field instead of letting the handler crash on undefined", () => {
|
test("names the missing required field instead of letting the handler crash on undefined", () => {
|
||||||
@@ -42,14 +40,14 @@ describe("parseCapabilityParams", () => {
|
|||||||
expect(message).toContain("limit");
|
expect(message).toContain("limit");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("coerces query-string values before checking, without touching the original", () => {
|
test("coerces query-string values and returns the coerced types without mutating the original", () => {
|
||||||
const target = tool("sealApprovalRunsSearch");
|
const target = tool("sealApprovalRunsSearch");
|
||||||
const params = { limit: "50", includeBridge: "true" } as Record<string, unknown>;
|
const params = { limit: "50", includeBridge: "true" } as Record<string, unknown>;
|
||||||
|
|
||||||
// /v1/* passes url.searchParams through: everything arrives as a string,
|
// /v1/* passes url.searchParams through: everything arrives as a string,
|
||||||
// but the schema declares z.number() / z.boolean(). Without coercion every
|
// but the schema declares z.number() / z.boolean(). Returning the coerced
|
||||||
// REST route would 400 on its own documented query params.
|
// values ensures the handler receives the exact types the schema validated.
|
||||||
expect(parseCapabilityParams(target, params)).toBe(params);
|
expect(parseCapabilityParams(target, params)).toEqual({ limit: 50, includeBridge: true });
|
||||||
expect(params.limit).toBe("50");
|
expect(params.limit).toBe("50");
|
||||||
expect(params.includeBridge).toBe("true");
|
expect(params.includeBridge).toBe("true");
|
||||||
});
|
});
|
||||||
@@ -59,33 +57,40 @@ describe("parseCapabilityParams", () => {
|
|||||||
expect(message).toContain("limit");
|
expect(message).toContain("limit");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("coerces a comma-separated query value into the array the schema wants", () => {
|
test("coerces a comma-separated query value into the array the schema and handler want", () => {
|
||||||
// `?fields=id,code` on /v1/approval/rules: today the handler receives a
|
// `?fields=id,code` on /v1/approval/rules: validation splits the string and
|
||||||
// string and pickRuleFields iterates its characters, returning empty
|
// hands the array to the handler so pickRuleFields iterates field names,
|
||||||
// objects. Validation splits it so the documented form actually works.
|
// not individual characters.
|
||||||
expect(parseCapabilityParams(tool("sealApprovalRulesList"), { fields: "id,code" })).toEqual({
|
expect(parseCapabilityParams(tool("sealApprovalRulesList"), { fields: "id,code" })).toEqual({
|
||||||
fields: "id,code"
|
fields: ["id", "code"]
|
||||||
});
|
});
|
||||||
expect(rejectsWith("sealApprovalRulesList", { fields: "id,not-a-field" })).toContain("fields");
|
expect(rejectsWith("sealApprovalRulesList", { fields: "id,not-a-field" })).toContain("fields");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("ignores undeclared keys rather than rejecting the request", () => {
|
test("preserves undeclared compatibility keys alongside normalized schema fields", () => {
|
||||||
// z.object is non-strict: an extra HTTP body key is a compatibility
|
// z.object is non-strict: an extra HTTP body key or legacy alias is kept
|
||||||
// non-event, not an error. This gate checks declared params only.
|
// while declared fields are coerced and defaulted.
|
||||||
const target = tool("sealApprovalRunsSearch");
|
const target = tool("sealApprovalRunsSearch");
|
||||||
expect(parseCapabilityParams(target, { status: "TERMINATED", corp: "corp-a", stray: 1 })).toBeTypeOf("object");
|
expect(parseCapabilityParams(target, { status: "TERMINATED", limit: "10", corp: "corp-a", stray: 1 })).toEqual({
|
||||||
|
status: "TERMINATED",
|
||||||
|
limit: 10,
|
||||||
|
corp: "corp-a",
|
||||||
|
stray: 1
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("lets the legacy credential aliases through to the handler that supports them", () => {
|
test("lets the legacy credential aliases through to the handler and populates schema defaults", () => {
|
||||||
// sealDeployHosecloudConfigure has always accepted appKey/appSecurity
|
expect(
|
||||||
// alongside apiKey/apiSecret; a schema that declared only apiKey as
|
|
||||||
// required would have blocked that documented path.
|
|
||||||
expect(() =>
|
|
||||||
parseCapabilityParams(tool("sealDeployHosecloudConfigure"), {
|
parseCapabilityParams(tool("sealDeployHosecloudConfigure"), {
|
||||||
appKey: "key-1",
|
appKey: "key-1",
|
||||||
appSecurity: "secret-1",
|
appSecurity: "secret-1",
|
||||||
mode: "assisted"
|
mode: "assisted"
|
||||||
})
|
})
|
||||||
).not.toThrow();
|
).toEqual({
|
||||||
|
appKey: "key-1",
|
||||||
|
appSecurity: "secret-1",
|
||||||
|
mode: "assisted",
|
||||||
|
apiOrigin: "production"
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -4,34 +4,33 @@ import type { SealCapability } from "./index.js";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks one invocation's params against the schema its tool declares, then
|
* Checks one invocation's params against the schema its tool declares, then
|
||||||
* returns the params unchanged.
|
* returns the normalized params (wire-format coercion + schema defaults applied,
|
||||||
|
* while preserving undeclared keys for legacy compatibility).
|
||||||
*
|
*
|
||||||
* Both dispatch paths — `runCapabilityResult` (every CLI command) and
|
* Both dispatch paths — `runCapabilityResult` (every CLI command) and
|
||||||
* `executeSealCapability` (`POST /api/tool/:name`, every `/v1/*` route) — used to
|
* `executeSealCapability` — hand the returned object to `handler`, so the
|
||||||
* hand `params` straight to `handler`, so a required field could be missing, a
|
* values that passed validation are the exact values the handler executes with.
|
||||||
* limit could be `999999`, or a typo'd HTTP body key could sail through and
|
|
||||||
* surface later as an opaque upstream error or a `Cannot read properties of
|
|
||||||
* undefined`. The schema is now the gate, failing fast with the offending field
|
|
||||||
* path (exit `13` on the CLI, HTTP `400` behind the adapter).
|
|
||||||
*
|
*
|
||||||
* Two deliberate properties:
|
* Two deliberate properties:
|
||||||
*
|
*
|
||||||
* - **Original params are returned, not `result.data`.** Handlers read keys the
|
* - **Normalized declared keys + preserved undeclared keys.** Wire strings like
|
||||||
* schema does not declare — `sealDeployHosecloudConfigure` accepts the
|
* `"50"`, `"true"`, or `"id,code"` are coerced to `50`, `true`, `["id", "code"]`
|
||||||
* legacy `appKey`/`appSecurity` aliases alongside `apiKey`/`apiSecret` — and
|
* and schema `.default(...)` values are filled in, while undeclared keys
|
||||||
* zod's default strip would silently drop them. Validation must never change
|
* (such as legacy compatibility aliases) are kept rather than stripped.
|
||||||
* what a working handler receives, only block what would have failed anyway.
|
* - **Caller input is not mutated in place.** A fresh object is returned.
|
||||||
* - **Undeclared keys never fail.** `z.object` is non-strict, so an extra HTTP
|
|
||||||
* body key is ignored rather than rejected; this is a correctness check, not
|
|
||||||
* an API-compatibility verdict.
|
|
||||||
*
|
|
||||||
* Before rejecting, wire-format values are coerced to the shape the schema
|
|
||||||
* declares (see {@link coerceWireTypes}) because `/v1/*` query strings arrive
|
|
||||||
* entirely as strings while the schema says `z.number()`.
|
|
||||||
*/
|
*/
|
||||||
export function parseCapabilityParams(tool: SealCapability, params: Record<string, unknown>): Record<string, unknown> {
|
export function parseCapabilityParams(tool: SealCapability, params: Record<string, unknown>): Record<string, unknown> {
|
||||||
const result = tool.parameters.safeParse(coerceWireTypes(tool.parameters, params));
|
const coerced = coerceWireTypes(tool.parameters, params);
|
||||||
if (result.success) return params;
|
const result = tool.parameters.safeParse(coerced);
|
||||||
|
if (result.success) {
|
||||||
|
const parsedData =
|
||||||
|
result.data && typeof result.data === "object"
|
||||||
|
? Object.fromEntries(
|
||||||
|
Object.entries(result.data as Record<string, unknown>).filter(([, value]) => value !== undefined)
|
||||||
|
)
|
||||||
|
: {};
|
||||||
|
return { ...params, ...coerced, ...parsedData };
|
||||||
|
}
|
||||||
|
|
||||||
const detail = result.error.issues
|
const detail = result.error.issues
|
||||||
.map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`)
|
.map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "
|
|||||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||||
import { createSealClient } from "../../../core/http/factory.js";
|
import { createSealClient } from "../../../core/http/factory.js";
|
||||||
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||||
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
|
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../replay/webhook.js";
|
||||||
import {
|
import {
|
||||||
checkWebhookReadiness,
|
checkWebhookReadiness,
|
||||||
previewMaterialPack,
|
previewMaterialPack,
|
||||||
@@ -239,6 +239,7 @@ export const webhookCapabilities = [
|
|||||||
snPrefix: z.string().optional().describe("重放单号前缀"),
|
snPrefix: z.string().optional().describe("重放单号前缀"),
|
||||||
snSuffix: z.string().optional().describe("重放单号后缀"),
|
snSuffix: z.string().optional().describe("重放单号后缀"),
|
||||||
dryRun: z.boolean().optional().describe("是否仅执行预检转换而不实际推送 (默认 false)"),
|
dryRun: z.boolean().optional().describe("是否仅执行预检转换而不实际推送 (默认 false)"),
|
||||||
|
confirm: z.boolean().optional().describe("明确确认实际重放;CLI 使用 --yes 或 --confirm"),
|
||||||
force: z.boolean().optional().describe("若目标为生产环境,强制执行重放")
|
force: z.boolean().optional().describe("若目标为生产环境,强制执行重放")
|
||||||
}),
|
}),
|
||||||
handler: async (
|
handler: async (
|
||||||
@@ -254,6 +255,7 @@ export const webhookCapabilities = [
|
|||||||
snPrefix?: string;
|
snPrefix?: string;
|
||||||
snSuffix?: string;
|
snSuffix?: string;
|
||||||
dryRun?: boolean;
|
dryRun?: boolean;
|
||||||
|
confirm?: boolean;
|
||||||
force?: boolean;
|
force?: boolean;
|
||||||
},
|
},
|
||||||
context: CapabilityContext
|
context: CapabilityContext
|
||||||
@@ -299,7 +301,8 @@ export const webhookCapabilities = [
|
|||||||
webhookSelector: params.webhook,
|
webhookSelector: params.webhook,
|
||||||
snPrefix: params.snPrefix,
|
snPrefix: params.snPrefix,
|
||||||
snSuffix: params.snSuffix,
|
snSuffix: params.snSuffix,
|
||||||
dryRun: params.dryRun
|
dryRun: params.dryRun,
|
||||||
|
confirm: params.confirm
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { saveCorpConfig, type SavedCorpConfig } from "../../core/config/repository.js";
|
import { saveCorpConfig, type SavedCorpConfig } from "../../../core/config/repository.js";
|
||||||
import { formatBeijingIso, normalizeBeijingIso } from "../../core/config/timestamps.js";
|
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
|
||||||
import {
|
import {
|
||||||
SealCookieMapSchema,
|
SealCookieMapSchema,
|
||||||
SealHeaderMapSchema,
|
SealHeaderMapSchema,
|
||||||
type CorpConfig
|
type CorpConfig
|
||||||
} from "../../core/config/types.js";
|
} from "../../../core/config/types.js";
|
||||||
import { createSealClientForUrl } from "../../core/http/factory.js";
|
import { createSealClientForUrl } from "../../../core/http/factory.js";
|
||||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
|
||||||
import { getMe } from "./api.js";
|
import { getMe } from "../api.js";
|
||||||
|
|
||||||
export type RemoteSealIdentity = {
|
export type RemoteSealIdentity = {
|
||||||
user: Record<string, unknown>;
|
user: Record<string, unknown>;
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { CorpConfig } from "../../core/config/types.js";
|
import { CorpConfig } from "../../../core/config/types.js";
|
||||||
import { createSealClient } from "../../core/http/factory.js";
|
import { createSealClient } from "../../../core/http/factory.js";
|
||||||
import { resolveSealEnterpriseConfig } from "../../core/auth/seal.js";
|
import { resolveSealEnterpriseConfig } from "../../../core/auth/seal.js";
|
||||||
import { SealEnterpriseConfig } from "../../core/auth/types.js";
|
import { SealEnterpriseConfig } from "../../../core/auth/types.js";
|
||||||
import { getMe } from "./api.js";
|
import { getMe } from "../api.js";
|
||||||
|
|
||||||
export async function resolveLiveSealEnterpriseConfig(
|
export async function resolveLiveSealEnterpriseConfig(
|
||||||
corp: CorpConfig
|
corp: CorpConfig
|
||||||
@@ -1,431 +0,0 @@
|
|||||||
import type { KyInstance } from "ky";
|
|
||||||
import type { CorpConfig } from "../../core/config/types.js";
|
|
||||||
import { safetyBlocked, validationError } from "../../core/errors.js";
|
|
||||||
import { createHoseCloseClient } from "../hose/close/client.js";
|
|
||||||
import * as api from "./api.js";
|
|
||||||
import type { ApprovalRun } from "./types.js";
|
|
||||||
|
|
||||||
export interface HoseOutboundLogItem {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
type: "INVOKING" | "CALLBACK" | string;
|
|
||||||
state: string;
|
|
||||||
flowId?: {
|
|
||||||
id: string;
|
|
||||||
form?: {
|
|
||||||
code?: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
nodeName?: string;
|
|
||||||
createTime: number;
|
|
||||||
messageType?: string;
|
|
||||||
request?: {
|
|
||||||
flowId?: string;
|
|
||||||
nodeId?: string;
|
|
||||||
messageId?: string;
|
|
||||||
rejectionNum?: number;
|
|
||||||
corporationId?: string;
|
|
||||||
action?: string;
|
|
||||||
comment?: string;
|
|
||||||
signKey?: string;
|
|
||||||
[key: string]: unknown;
|
|
||||||
};
|
|
||||||
response?: unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HoseOutboundReplayOptions {
|
|
||||||
sourceCorp: CorpConfig;
|
|
||||||
targetCorp: CorpConfig;
|
|
||||||
sourceClient?: KyInstance;
|
|
||||||
targetClient: KyInstance;
|
|
||||||
sn?: string;
|
|
||||||
recordId?: string;
|
|
||||||
flowId?: string;
|
|
||||||
messageId?: string;
|
|
||||||
nodeId?: string;
|
|
||||||
corporationId?: string;
|
|
||||||
rejectionNum?: number;
|
|
||||||
targetSignKey?: string;
|
|
||||||
dryRun?: boolean;
|
|
||||||
force?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch historical outbound message logs from Hosecloud's CloseAPI for a given document SN.
|
|
||||||
*/
|
|
||||||
export async function fetchHoseOutboundLogs(
|
|
||||||
sourceCorp: CorpConfig,
|
|
||||||
sn: string
|
|
||||||
): Promise<HoseOutboundLogItem[]> {
|
|
||||||
if (sourceCorp.source.type !== "hose") {
|
|
||||||
throw validationError(
|
|
||||||
`源企业「${sourceCorp.name}」非合思(hose)租户,无法通过合思 CloseAPI 查询出站消息日志。`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = await createHoseCloseClient(sourceCorp);
|
|
||||||
const corpId = sourceCorp.source.corpId;
|
|
||||||
|
|
||||||
const response = (await client
|
|
||||||
.post("api/outbound/v1/message/messageLog", {
|
|
||||||
searchParams: {
|
|
||||||
messageType: "flow",
|
|
||||||
corpId
|
|
||||||
},
|
|
||||||
json: {
|
|
||||||
limit: { start: 0, count: 20 },
|
|
||||||
orderBy: [{ value: "createTime", order: "DESC" }],
|
|
||||||
select: "id,name,flowId(id, form(code)),nodeName,type,request,response,state,createTime,messageType",
|
|
||||||
filterBy: `(flowId.form.code==("${sn}"))`
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.json()) as { items?: HoseOutboundLogItem[] };
|
|
||||||
|
|
||||||
return response.items ?? [];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select the best matching INVOKING log from a list of outbound message logs.
|
|
||||||
*/
|
|
||||||
export function selectMatchingOutboundLog(
|
|
||||||
logs: HoseOutboundLogItem[],
|
|
||||||
options: {
|
|
||||||
messageId?: string;
|
|
||||||
recordId?: string;
|
|
||||||
recordCreatedAt?: number;
|
|
||||||
rejectionNum?: number;
|
|
||||||
} = {}
|
|
||||||
): HoseOutboundLogItem | undefined {
|
|
||||||
const invokingLogs = logs.filter((item) => item.type === "INVOKING");
|
|
||||||
if (invokingLogs.length === 0) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. Explicit messageId match
|
|
||||||
if (options.messageId) {
|
|
||||||
return invokingLogs.find((item) => item.request?.messageId === options.messageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Exact recordId match via CALLBACK link/comment
|
|
||||||
if (options.recordId) {
|
|
||||||
const callbackWithRecordId = logs.find(
|
|
||||||
(item) =>
|
|
||||||
item.type === "CALLBACK" &&
|
|
||||||
typeof item.request?.comment === "string" &&
|
|
||||||
item.request.comment.includes(options.recordId!)
|
|
||||||
);
|
|
||||||
if (callbackWithRecordId) {
|
|
||||||
// Find the invoking event right before this callback
|
|
||||||
const priorInvoking = invokingLogs.find(
|
|
||||||
(item) => item.createTime <= callbackWithRecordId.createTime
|
|
||||||
);
|
|
||||||
if (priorInvoking) {
|
|
||||||
return priorInvoking;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: match by timestamp delta (< 60s)
|
|
||||||
if (options.recordCreatedAt) {
|
|
||||||
const closestByTime = invokingLogs
|
|
||||||
.filter((item) => item.createTime <= options.recordCreatedAt! + 1000)
|
|
||||||
.sort(
|
|
||||||
(a, b) =>
|
|
||||||
Math.abs(options.recordCreatedAt! - a.createTime) -
|
|
||||||
Math.abs(options.recordCreatedAt! - b.createTime)
|
|
||||||
)[0];
|
|
||||||
if (closestByTime) {
|
|
||||||
return closestByTime;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Match by rejectionNum if provided
|
|
||||||
if (options.rejectionNum !== undefined) {
|
|
||||||
const matchRejection = invokingLogs.find(
|
|
||||||
(item) => item.request?.rejectionNum === options.rejectionNum
|
|
||||||
);
|
|
||||||
if (matchRejection) {
|
|
||||||
return matchRejection;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Default: latest invoking log
|
|
||||||
return invokingLogs[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate security preconditions for Hose outbound replay.
|
|
||||||
*/
|
|
||||||
export function validateHoseOutboundReplaySafety(
|
|
||||||
sourceCorp: CorpConfig,
|
|
||||||
targetCorp: CorpConfig,
|
|
||||||
targetIntegration: { mode?: string; outboundName?: string; signKey?: string },
|
|
||||||
force = false
|
|
||||||
): void {
|
|
||||||
// 1. Double-binding guard: prevent accidental cross-tenant execution outside paired sandbox
|
|
||||||
const isPaired =
|
|
||||||
sourceCorp.testCorpId === targetCorp.id ||
|
|
||||||
targetCorp.prodCorpId === sourceCorp.id ||
|
|
||||||
sourceCorp.id === targetCorp.id;
|
|
||||||
|
|
||||||
if (!isPaired && !force) {
|
|
||||||
throw safetyBlocked(
|
|
||||||
`安全阻断:源企业「${sourceCorp.name}」(${sourceCorp.id}) 与目标企业「${targetCorp.name}」(${targetCorp.id}) 未配置双向测试绑定关系 (testCorpId / prodCorpId)。\n` +
|
|
||||||
`出站重放具备高仿真性,仅允许在绑定的生产-测试企业对之间执行。如确需跨租户测试,请添加 --force 参数。`,
|
|
||||||
`请检查企业配置 ~/.config/seal-use/enterprises/ 或添加 --force`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Production target guard
|
|
||||||
if (targetCorp.environment === "production" && !force) {
|
|
||||||
throw safetyBlocked(
|
|
||||||
`安全阻断:目标企业「${targetCorp.name}」标记为正式生产环境 (production)。\n` +
|
|
||||||
`为防止测试消息污染生产审批流,严禁向生产企业重发出站报文。请通过 --target-corp 指定测试企业。`,
|
|
||||||
`seal-use approval-runs replay --target-corp <testCorpId> ...`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Mode guard: target Hose integration MUST be assisted
|
|
||||||
const mode = targetIntegration.mode ?? "assisted";
|
|
||||||
if (mode !== "assisted") {
|
|
||||||
throw safetyBlocked(
|
|
||||||
`安全阻断:目标测试企业「${targetCorp.name}」的合思配置「${targetIntegration.outboundName ?? targetIntegration.signKey}」当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` +
|
|
||||||
`为防止自动向合思回写审批动作影响流程,严禁在非 assisted 模式下重放出站单据。`,
|
|
||||||
`请先将目标企业的合思配置调整为 assisted 模式后重试:seal-use deploy hosecloud configure --json '{"signKey":"${targetIntegration.signKey}","mode":"assisted"}' --corp ${targetCorp.id}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main execution handler for Hose outbound replay.
|
|
||||||
*/
|
|
||||||
export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptions) {
|
|
||||||
const { sourceCorp, targetCorp, targetClient, dryRun, force } = options;
|
|
||||||
|
|
||||||
// 1. Get target corp's Hose integrations
|
|
||||||
const targetConfig = await api.getApprovalStylePreferences(
|
|
||||||
targetClient,
|
|
||||||
targetCorp.seal?.endpoints?.approvalStylePreferences
|
|
||||||
);
|
|
||||||
const hoseConfigs: Array<{
|
|
||||||
type: string;
|
|
||||||
signKey?: string;
|
|
||||||
outboundName?: string;
|
|
||||||
mode?: string;
|
|
||||||
corporationId?: string;
|
|
||||||
[key: string]: unknown;
|
|
||||||
}> = (targetConfig.integrations ?? []).filter((i: any) => i.type === "hosecloud");
|
|
||||||
if (hoseConfigs.length === 0) {
|
|
||||||
throw validationError(
|
|
||||||
`目标测试企业「${targetCorp.name}」未配置任何合思出站发布通道。请先运行:seal-use deploy hosecloud configure --corp ${targetCorp.id}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const foundIntegration = options.targetSignKey
|
|
||||||
? hoseConfigs.find((i) => i.signKey === options.targetSignKey)
|
|
||||||
: hoseConfigs[0];
|
|
||||||
|
|
||||||
if (!foundIntegration || !foundIntegration.signKey) {
|
|
||||||
if (options.targetSignKey) {
|
|
||||||
throw validationError(
|
|
||||||
`在目标企业中未找到 signKey 为「${options.targetSignKey}」的合思配置。可用配置: ${hoseConfigs.map((i) => i.signKey).filter(Boolean).join(", ")}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw validationError(
|
|
||||||
`目标测试企业「${targetCorp.name}」未配置有效的合思 signKey。`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const targetIntegration = {
|
|
||||||
...foundIntegration,
|
|
||||||
signKey: foundIntegration.signKey
|
|
||||||
};
|
|
||||||
|
|
||||||
// 2. Validate safety constraints
|
|
||||||
validateHoseOutboundReplaySafety(sourceCorp, targetCorp, targetIntegration, force);
|
|
||||||
|
|
||||||
// 3. Resolve document SN & record details
|
|
||||||
let sn = options.sn?.trim();
|
|
||||||
let sourceRecord: ApprovalRun | undefined;
|
|
||||||
|
|
||||||
if (options.recordId) {
|
|
||||||
if (options.sourceClient) {
|
|
||||||
try {
|
|
||||||
sourceRecord = await api.getApprovalRun(options.sourceClient, options.recordId);
|
|
||||||
if (sourceRecord?.sourceDocumentSN) {
|
|
||||||
sn = sourceRecord.sourceDocumentSN;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!sn && !options.messageId) {
|
|
||||||
throw validationError(
|
|
||||||
"缺少必需参数:请提供单号 (--sn <SN>) 或运行记录 ID (<recordId>),以便自动从合思检索出站消息日志。"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Retrieve or match outbound log
|
|
||||||
let selectedLog: HoseOutboundLogItem | undefined;
|
|
||||||
if (!options.messageId && sn) {
|
|
||||||
console.error(`ℹ️ 正在通过合思 CloseAPI 检索单据「${sn}」的历史出站消息日志...`);
|
|
||||||
const logs = await fetchHoseOutboundLogs(sourceCorp, sn);
|
|
||||||
const recordCreatedAt =
|
|
||||||
typeof sourceRecord?.createdAt === "number"
|
|
||||||
? sourceRecord.createdAt
|
|
||||||
: typeof sourceRecord?.createdAt === "string"
|
|
||||||
? Date.parse(sourceRecord.createdAt)
|
|
||||||
: undefined;
|
|
||||||
selectedLog = selectMatchingOutboundLog(logs, {
|
|
||||||
recordId: options.recordId,
|
|
||||||
recordCreatedAt: Number.isNaN(recordCreatedAt) ? undefined : recordCreatedAt,
|
|
||||||
rejectionNum: options.rejectionNum
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!selectedLog || !selectedLog.request?.messageId) {
|
|
||||||
throw validationError(
|
|
||||||
`在合思出站日志中未找到单据「${sn}」的有效出站记录 (type: INVOKING)。\n` +
|
|
||||||
`请确认该单据在合思审批流中是否触发过出站消息(EBot节点),或显式提供 --message-id 参数。`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Construct payload
|
|
||||||
const flowId =
|
|
||||||
options.flowId?.trim() ??
|
|
||||||
selectedLog?.request?.flowId ??
|
|
||||||
selectedLog?.flowId?.id ??
|
|
||||||
sourceRecord?.sourceDocumentId ??
|
|
||||||
(sn?.startsWith("ID01") ? sn : undefined);
|
|
||||||
|
|
||||||
if (!flowId) {
|
|
||||||
throw validationError(
|
|
||||||
`未能解析出单据「${sn}」的合思流程实例 ID (flowId)。请确认单据信息或显式提供 flowId。`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const messageId = options.messageId?.trim() ?? selectedLog?.request?.messageId;
|
|
||||||
if (!messageId) {
|
|
||||||
throw validationError("未能获取到有效 messageId。");
|
|
||||||
}
|
|
||||||
|
|
||||||
const rejectionNum =
|
|
||||||
options.rejectionNum ?? selectedLog?.request?.rejectionNum ?? 0;
|
|
||||||
|
|
||||||
const corporationId =
|
|
||||||
options.corporationId?.trim() ??
|
|
||||||
selectedLog?.request?.corporationId ??
|
|
||||||
(sourceCorp.source as any)?.corpId ??
|
|
||||||
targetIntegration.corporationId;
|
|
||||||
|
|
||||||
// Crucial: Chinese mock nodeId causes Hose to return HTTP 412 on callback, creating an indestructible safety gate
|
|
||||||
const nodeId = options.nodeId?.trim() || "FLOW:测试模拟节点_禁止流转";
|
|
||||||
|
|
||||||
const targetSealUrl = (
|
|
||||||
targetCorp.seal.url ?? `https://${targetCorp.id.toLowerCase()}.sealai.cc`
|
|
||||||
).replace(/\/+$/, "");
|
|
||||||
const targetWebhookUrl = `${targetSealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(targetIntegration.signKey)}`;
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
flowId,
|
|
||||||
nodeId,
|
|
||||||
messageId,
|
|
||||||
rejectionNum,
|
|
||||||
corporationId
|
|
||||||
};
|
|
||||||
|
|
||||||
// 6. Dry run preview
|
|
||||||
if (dryRun) {
|
|
||||||
return {
|
|
||||||
preview: true,
|
|
||||||
channel: "hose-outbound",
|
|
||||||
sourceCorp: {
|
|
||||||
id: sourceCorp.id,
|
|
||||||
name: sourceCorp.name,
|
|
||||||
environment: sourceCorp.environment
|
|
||||||
},
|
|
||||||
targetCorp: {
|
|
||||||
id: targetCorp.id,
|
|
||||||
name: targetCorp.name,
|
|
||||||
environment: targetCorp.environment
|
|
||||||
},
|
|
||||||
targetIntegration: {
|
|
||||||
signKey: targetIntegration.signKey,
|
|
||||||
outboundName: targetIntegration.outboundName,
|
|
||||||
mode: targetIntegration.mode
|
|
||||||
},
|
|
||||||
matchedLog: selectedLog
|
|
||||||
? {
|
|
||||||
logId: selectedLog.id,
|
|
||||||
nodeName: selectedLog.nodeName,
|
|
||||||
createTime: selectedLog.createTime,
|
|
||||||
messageId: selectedLog.request?.messageId,
|
|
||||||
rejectionNum: selectedLog.request?.rejectionNum
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
safetyGuards: {
|
|
||||||
pairedBinding: true,
|
|
||||||
targetModeAssisted: true,
|
|
||||||
nodeId412Blocked: true
|
|
||||||
},
|
|
||||||
targetUrl: targetWebhookUrl,
|
|
||||||
payload
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 7. Live execution
|
|
||||||
const response = await api.postHosecloudOutbound(
|
|
||||||
targetClient,
|
|
||||||
targetIntegration.signKey,
|
|
||||||
payload
|
|
||||||
);
|
|
||||||
|
|
||||||
console.error(`✓ 成功从合思出站日志匹配消息 (messageId: ${messageId}, 轮次: ${rejectionNum})`);
|
|
||||||
console.error(`✓ 已向测试企业「${targetCorp.name}」出站网关推送重放报文 (nodeId: ${nodeId})`);
|
|
||||||
|
|
||||||
// Wait 2.5s for worker queue consumption
|
|
||||||
await new Promise((r) => setTimeout(r, 2500));
|
|
||||||
let createdRecord: ApprovalRun | undefined;
|
|
||||||
try {
|
|
||||||
const runs = await api.listApprovalRuns(targetClient, {
|
|
||||||
limit: 5,
|
|
||||||
search: flowId
|
|
||||||
});
|
|
||||||
createdRecord = (runs.records || []).find(
|
|
||||||
(r) => r.sourceDocumentId === flowId || r.sourceDocumentSN === sn
|
|
||||||
);
|
|
||||||
} catch {
|
|
||||||
// non-blocking
|
|
||||||
}
|
|
||||||
|
|
||||||
if (createdRecord) {
|
|
||||||
console.error(`✓ 异步消费成功!已在【${targetCorp.name}】生成审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`);
|
|
||||||
console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${targetCorp.id}`);
|
|
||||||
} else {
|
|
||||||
console.error(`ℹ️ 消息已入队正在异步消费,可稍后在测试后台页面刷新查看。`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
channel: "hose-outbound",
|
|
||||||
sourceCorp: {
|
|
||||||
id: sourceCorp.id,
|
|
||||||
name: sourceCorp.name
|
|
||||||
},
|
|
||||||
targetCorp: {
|
|
||||||
id: targetCorp.id,
|
|
||||||
name: targetCorp.name
|
|
||||||
},
|
|
||||||
targetSignKey: targetIntegration.signKey,
|
|
||||||
mode: targetIntegration.mode,
|
|
||||||
matchedMessageId: messageId,
|
|
||||||
rejectionNum,
|
|
||||||
payload,
|
|
||||||
response,
|
|
||||||
recordId: createdRecord?.id,
|
|
||||||
recordStatus: createdRecord?.status,
|
|
||||||
taskMode: createdRecord?.taskMode
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -4,8 +4,8 @@ import { homedir } from "node:os";
|
|||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import ExcelJS from "exceljs";
|
import ExcelJS from "exceljs";
|
||||||
import type { KyInstance } from "ky";
|
import type { KyInstance } from "ky";
|
||||||
import { type CorpConfig, CorpConfigSchema } from "../../core/config/types.js";
|
import { type CorpConfig, CorpConfigSchema } from "../../../core/config/types.js";
|
||||||
import { exportInsightReportToExcel, resolveInsightOutputFilePath } from "./insight-export.js";
|
import { exportInsightReportToExcel, resolveInsightOutputFilePath } from "./export.js";
|
||||||
|
|
||||||
describe("insight-export domain", () => {
|
describe("insight-export domain", () => {
|
||||||
test("resolveInsightOutputFilePath respects custom outputFile", () => {
|
test("resolveInsightOutputFilePath respects custom outputFile", () => {
|
||||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user