Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3cde2cf1e0 | ||
|
|
c84fd2a858 | ||
|
|
57e01e5079 | ||
|
|
71a2e9a2e3 | ||
|
|
887df2d32f | ||
|
|
837f4e2db6 | ||
|
|
ca9d87e13f | ||
|
|
37b54065d9 | ||
|
|
a189f49223 | ||
|
|
666a12c676 | ||
|
|
7fe5cae62c | ||
|
|
35f761e8a0 | ||
|
|
8d6b65d3d5 | ||
|
|
8adae54c54 | ||
|
|
09c72d998a | ||
|
|
e88f472b50 | ||
|
|
1ddf6db9e8 | ||
|
|
4b92d397df | ||
|
|
d25c09c3be | ||
|
|
03189c072d | ||
|
|
1a023f9996 | ||
|
|
0ddd8283fe | ||
|
|
b980c60c3a | ||
|
|
67cd168ed4 | ||
|
|
8bc1401eae | ||
|
|
c572cba842 | ||
|
|
71845c35e7 | ||
|
|
8ecadbb124 | ||
|
|
dec52cf5fa | ||
|
|
b49e3a6ea0 | ||
|
|
0ff3d9a313 |
No files matched your search
@@ -8,7 +8,7 @@ This directory (`.agents/`) maintains modular configuration, skills, and guideli
|
||||
|
||||
```
|
||||
.agents/
|
||||
├── README.md # This document: architecture & trigger policy
|
||||
├── agents.readme.md # This document: architecture & trigger policy
|
||||
├── skills.json # Declarative skill path and exclusion filters
|
||||
├── skills/ # Project-level skills
|
||||
│ └── repo-gh/ # GitHub CLI & Git Markdown-First operations
|
||||
@@ -13,7 +13,7 @@ When developing or refactoring CLI commands under `src/cli/`:
|
||||
- **Machine Channel (`stdout`)**:
|
||||
- Data commands **MUST** output pure, parseable JSON on `stdout`.
|
||||
- **NEVER** output human text, logs, spinners, progress banners, or update notices to `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
|
||||
- **Documented exceptions**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally output Markdown documents on `stdout` because their output *is* the requested document payload (e.g. `seal-use skill dump > SKILL.md`). Never add new stdout-prose commands outside this list.
|
||||
- **Documented exceptions**: `seal-use --help` / `seal-use help <area>` (`src/cli/output/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally output Markdown documents on `stdout` because their output *is* the requested document payload (e.g. `seal-use skill dump > SKILL.md`). Never add new stdout-prose commands outside this list.
|
||||
- **Diagnostics & Guidance Channel (`stderr`)**:
|
||||
- Use `stderr` for runtime logs, network probing status, self-healing notifications, and human tips.
|
||||
- Explicit **Next-Step Command Suggestions** MUST follow the format:
|
||||
@@ -27,7 +27,7 @@ When developing or refactoring CLI commands under `src/cli/`:
|
||||
|
||||
- **Sub-70ms Local Execution**:
|
||||
- Read-only discovery commands (e.g. `seal-use version`, `seal-use doctor paths`, `seal-use corps list`) MUST return in under 70ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~60ms for the module graph).
|
||||
- Achieved by keeping `src/cli/runner.ts` free of static command-module imports: dispatch branches load their handler with `await import("./commands/<area>.js")` on demand, so `seal-use version` never loads the Excel/zip tool chain.
|
||||
- Achieved by keeping `src/cli/run/runner.ts` free of static command-module imports: dispatch branches load their handler with `await import("./commands/<area>.js")` on demand, so `seal-use version` never loads the Excel/zip tool chain.
|
||||
- Never trigger synchronous external HTTP requests during routine discovery or inspection invocations. Measured on the maintainer's machine (2026-09): version 45ms, help 41ms, corps list 41ms, bare `bun -e` 7ms.
|
||||
- **Stale-While-Revalidate (SWR) Pattern**:
|
||||
1. Synchronously read local cache from `~/.config/seal-use/*.json` (<0.2ms).
|
||||
@@ -74,13 +74,13 @@ When developing or refactoring CLI commands under `src/cli/`:
|
||||
| `13` | **Config / Input Validation** | Well-formed command with an unusable value: missing `--corp` in stateless mode, unparseable enterprise JSON, missing required parameter (Chinese-language usage wording), Zod/schema validation failure |
|
||||
| `14` | **Safety Guard Block** | Target environment forbids the action: replay into a production tenant, regression matrix outside a test tenant. Requires a different target or an explicit override flag |
|
||||
|
||||
**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors (`usageError` → 2, `validationError` → 13, `safetyBlocked` → 14, `confirmationRequired` → 10) and let `src/cli/runner.ts` handle error classification, stream routing, and exit code assignment. Domain failures and quality gates stay at `1`.
|
||||
**Rule**: Never call `process.exit()` deep in domain functions. Throw structured errors (`usageError` → 2, `validationError` → 13, `safetyBlocked` → 14, `confirmationRequired` → 10) and let `src/cli/run/runner.ts` handle error classification, stream routing, and exit code assignment. Domain failures and quality gates stay at `1`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Argument Parsing Conventions
|
||||
|
||||
- Use helpers from `src/cli/parser.ts`:
|
||||
- Use helpers from `src/cli/parse/parser.ts`:
|
||||
- `booleanOption(args.options.flag)`
|
||||
- `stringOption(args.options.param)`
|
||||
- `numberOption(args.options.limit)`
|
||||
|
||||
@@ -13,8 +13,8 @@ When writing or modifying automated tests in `src/`:
|
||||
- **Runner**: Use `bun:test` primitives (`describe`, `test`, `it`, `expect`, `beforeEach`, `afterEach`).
|
||||
- **Colocation**: Place test files directly next to the code they cover using the `*.test.ts` naming convention:
|
||||
```text
|
||||
src/core/update-cache.ts
|
||||
src/core/update-cache.test.ts
|
||||
src/core/update/update-cache.ts
|
||||
src/core/update/update-cache.test.ts
|
||||
```
|
||||
- Do not create isolated `tests/` directories unless testing full external integration fixtures.
|
||||
|
||||
|
||||
@@ -130,4 +130,8 @@ if printf '%s\n' "$staged" | grep -qE "^skills/seal-use/(SKILL\.md|references/[^
|
||||
bun run verify:skill-md || exit 1
|
||||
fi
|
||||
|
||||
if printf '%s\n' "$staged" | grep -qiE "(^|/)readme"; then
|
||||
bun run verify:readme-naming || exit 1
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -53,6 +53,9 @@ jobs:
|
||||
- name: Embedded Skill Sync
|
||||
run: bun run verify:embedded-skill
|
||||
|
||||
- name: README Naming Checks
|
||||
run: bun run verify:readme-naming
|
||||
|
||||
- name: Colocated Unit Tests
|
||||
run: bun test
|
||||
|
||||
|
||||
+39
-12
@@ -1,34 +1,61 @@
|
||||
node_modules/
|
||||
# ---------------------------------------------------------------------------
|
||||
# OS & editor noise
|
||||
# ---------------------------------------------------------------------------
|
||||
.DS_Store
|
||||
._*
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
*.swp
|
||||
.idea/
|
||||
.vscode/
|
||||
*.tsbuildinfo
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dependencies
|
||||
# ---------------------------------------------------------------------------
|
||||
node_modules/
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Build outputs
|
||||
dist/bin/
|
||||
# ---------------------------------------------------------------------------
|
||||
dist/
|
||||
build/
|
||||
coverage/
|
||||
|
||||
# Local runtime caches and system noise (regenerate at any time)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local caches and tool state (regenerate at any time)
|
||||
# ---------------------------------------------------------------------------
|
||||
.cache/
|
||||
.mimosa/
|
||||
.apifox/
|
||||
tmp/
|
||||
*.log
|
||||
|
||||
# Local runtime state (rule snapshots, bridge, reports) — never committed
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local runtime state (never committed)
|
||||
# ---------------------------------------------------------------------------
|
||||
.local/
|
||||
/reports/
|
||||
.workbuddy/
|
||||
|
||||
# Developer-only build-time credentials for compile-time injection — never committed
|
||||
.env.langfuse
|
||||
# ---------------------------------------------------------------------------
|
||||
# Secrets and build-time credentials (never committed)
|
||||
# ---------------------------------------------------------------------------
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
# Local drafts for repo-gh & AI Agents
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local drafts, one-off harnesses, and review notes
|
||||
# ---------------------------------------------------------------------------
|
||||
.drafts/*
|
||||
!.drafts/.gitkeep
|
||||
|
||||
# ZCode session plan artifacts (workspace-local, never committed)
|
||||
.zcode/plans/
|
||||
|
||||
# One-off export harnesses dropped in scripts/ while exporting
|
||||
scripts/export-*.ts
|
||||
*.local.md
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ZCode session artifacts
|
||||
# ---------------------------------------------------------------------------
|
||||
.zcode/plans/
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.19",
|
||||
"version": "0.11.23",
|
||||
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -6,7 +6,7 @@ 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`.
|
||||
|
||||
Engineering toolchain, code generators, build pipelines, and governance gate scripts live under `scripts/`. Scripts under `scripts/` are offline harnesses, not application runtime code — never import them into `src/`. Governance gates are grouped under `scripts/governance/` (`check-agents-md.ts`, `check-skill-md.ts`, `check-readme.ts`, `doc-md-common.ts`). Destructive release scripts (`scripts/release.ts`, `scripts/bump-version.ts`) must never be triggered autonomously by agents without explicit human instruction.
|
||||
Engineering toolchain, code generators, build pipelines, and governance gate scripts live under `scripts/`. Scripts under `scripts/` are offline harnesses, not application runtime code — never import them into `src/`. Governance gates are grouped under `scripts/governance/` (`check-agents-md.ts`, `check-skill-md.ts`, `check-readme.ts`, `check-readme-naming.ts`, `doc-md-common.ts`). Destructive release scripts (`scripts/release.ts`, `scripts/bump-version.ts`) must never be triggered autonomously by agents without explicit human instruction.
|
||||
|
||||
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`.
|
||||
|
||||
@@ -25,6 +25,7 @@ Tests are colocated as `*.test.ts` files in `src/`.
|
||||
- `bun run verify:agents-md`: validate the root `AGENTS.md` developer contract (structure, required sections, `.agents/rules/` reference integrity and reverse coverage); wired into pre-commit (staged docs only) and CI.
|
||||
- `bun run verify:skill-md`: validate the `skills/seal-use/SKILL.md` routing hub (structure and bidirectional `references/` routing); wired into pre-commit (staged docs only) and CI.
|
||||
- `bun run verify:readme`: lightweight hygiene and structure checks for `README.md` (warnings only, never blocks).
|
||||
- `bun run verify:readme-naming`: enforce the root `README.md` and subdirectory `<dir>.readme.md` naming rule (leading dots stripped, e.g. `src/src.readme.md`); wired into pre-commit (staged README files) and CI.
|
||||
- `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 existing global command found on PATH (falling back to a standalone bin directory), and sync the local Agent Skill.
|
||||
|
||||
@@ -37,7 +38,7 @@ Prefer small domain functions over broad utility modules.
|
||||
## CLI & Agent Harness Protocol Guidelines
|
||||
|
||||
- **Machine Channel (`stdout`)**: Data commands MUST output clean, parseable JSON on `stdout`. Never dump human prose, raw logs, or progress banners into `stdout`. The Agent Harness parses `stdout` directly into typed payloads.
|
||||
- **Documented exception — document-output commands**: `seal-use --help` / `seal-use help <area>` (`src/cli/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract.
|
||||
- **Documented exception — document-output commands**: `seal-use --help` / `seal-use help <area>` (`src/cli/output/printer.ts`), `seal-use doctor guide` (`src/cli/commands/doctor.ts`), and `seal-use skill dump` (`src/cli/commands/skill.ts`) intentionally write Markdown to `stdout`, because their output *is* the payload the caller redirects or reads (e.g. `seal-use doctor guide > guide.md`, `seal-use skill dump > SKILL.md`). Never add a new prose-on-stdout command outside this list: return structured JSON and put the readable rendering on `stderr` instead. `src/probe.ts` is a local developer probe script rather than a `bin` entry point, so its `[probe] …` lines are outside this contract.
|
||||
- **Guidance & Diagnostic Channel (`stderr`)**: Use `stderr` for runtime logs, network probing status, self-healing notifications, and explicit **Next-Step Command Suggestions** (e.g. `👉 Next action: seal-use deploy hosecloud sync <signKey>`).
|
||||
- **Performance Contract & SWR Architecture**: Read-only discovery and version commands (`seal-use version`, `seal-use doctor`, `seal-use corps list`) MUST execute in under 70ms wall clock (Bun startup alone is ~7ms; runner dispatch uses lazy `await import()` per command area, so the version path never loads the Excel/zip tool chain). Never block on external network I/O during routine invocations. Use the Stale-While-Revalidate (SWR) pattern: read local cache from `~/.config/seal-use/*.json` synchronously (<0.2ms), and refresh stale/missing data via detached, unref'd child processes (`triggerBackgroundUpdateCheck`, `unref()`).
|
||||
- **Safety Guardrail & Mutation Preview (`--dry-run`)**: All potentially destructive or state-mutating commands (e.g. `rules push/clear`, `corps sync-test`, `preference update`, `webhook create/update`) MUST support `--dry-run` returning structured JSON previews with `preview: true` and a clean diff, without executing mutations. Live execution requires explicit `--yes` or `--confirm`.
|
||||
@@ -50,7 +51,7 @@ Prefer small domain functions over broad utility modules.
|
||||
- `12`: Output protection — response exceeds the size limit; use `--summary`/`--fields`/`--count`/`--output-file` (or `--full` when the full payload is genuinely required).
|
||||
- `13`: Local configuration or input-data validation failure — well-formed command, but the value or config file is unusable (missing `--corp`, unparseable enterprise JSON, missing required parameter named in a Chinese-language error).
|
||||
- `14`: Safety guard block — the target environment forbids the action (replay into production, regression outside a test tenant); requires a different target or an explicit override.
|
||||
- Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/runner.ts` handle stream routing and exit code assignment.
|
||||
- Never call `process.exit()` deep in domain functions; throw structured errors and let `src/cli/run/runner.ts` handle stream routing and exit code assignment.
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
@@ -111,7 +112,7 @@ Recent commits use concise imperative subjects, often `Add ...` or `Refine ...`,
|
||||
git push origin refs/tags/vX.Y.Z
|
||||
```
|
||||
- GitHub Actions (`release.yml`) is responsible only for cross-compiling all 5 target binaries and publishing the GitHub Release.
|
||||
- **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (`wsl-infra/systemd/`).
|
||||
- **Gitea Pull-Based Promotion & Mirroring**: On WSL (`wsl-dev`), `seal-use-release-sync.timer` polls GitHub every 15 minutes (or can be triggered immediately via `systemctl start seal-use-release-sync.service`), mirrors Git repository refs (branches and tags) and pulls release assets into Gitea (`host-infra/systemd/`).
|
||||
- The workflow enforces the merge-before-tag rule rather than trusting the operator: `release.yml` refuses to publish unless the tagged commit is an ancestor of `origin/main`. Actions in both workflows are pinned to commit SHAs rather than moving tags for supply-chain integrity.
|
||||
|
||||
## Security & Configuration Tips
|
||||
|
||||
@@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.11.23] - 2026-11-19
|
||||
|
||||
### Added
|
||||
- Merge pull request #290 from yunyingk/mac15/cloud-enterprise-config
|
||||
- Add bridge device login and cloud credential resolution
|
||||
- Add cloud enterprise storage mode and credential resolver
|
||||
- Merge pull request #289 from yunyingk/mac15/remove-enterprise-provider-field
|
||||
- Group CLI modules into parse, run, output, and help
|
||||
- Remove workspace backup script
|
||||
- Group core utility modules into util, skill, and update
|
||||
- Enforce README naming convention for subdirectories
|
||||
|
||||
|
||||
## [0.11.22] - 2026-11-17
|
||||
|
||||
### Added
|
||||
- Merge pull request #286 from yunyingk/mac15/simulation-rule-source-maycur
|
||||
- feat(simulation): 支持单租户未发布草稿快照、已发布版本回溯与每刻报销接入
|
||||
|
||||
|
||||
## [0.11.21] - 2026-11-13
|
||||
|
||||
### Added
|
||||
- Merge pull request #284 from yunyingk/mac15/cli-langfuse-diagnose-ergonomics
|
||||
- Improve CLI ergonomics for Langfuse search and approval run diagnosis
|
||||
- Merge pull request #283 from yunyingk/mac15/fix-flow-error-attribution
|
||||
- Merge pull request #282 from yunyingk/mac15/fix-retired-flow-switch
|
||||
- fix(approval-runs): 传输层失败不再被误判为业务结论
|
||||
- fix(cli): 不再在帮助与文档中暴露已退役的 --flow 拼写
|
||||
|
||||
|
||||
## [0.11.20] - 2026-11-08
|
||||
|
||||
### Added
|
||||
- 新增租户 active 状态与启用/禁用管理命令,统一阻止对已禁用租户执行操作;完善配置校验、CLI/MCP 闸门及使用文档。
|
||||
|
||||
## [0.11.19] - 2026-11-06
|
||||
|
||||
### Added
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
Bun + TypeScript CLI for pulling Seal enterprise approval context from provider credentials.
|
||||
|
||||
The first provider is Hose/合思: `key`, `password`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences.
|
||||
The first provider is Hose/合思: `appKey`, `appSecurity`, `corpId`, `staffId`, and an optional Hose domain. The provider exchanges those credentials for a Seal enterprise session, then the Seal domain tools can read and maintain approval rules, approval documents, and approval style preferences.
|
||||
|
||||
Seal-native enterprise pages can be added with a Seal Bearer token.
|
||||
|
||||
@@ -15,9 +15,10 @@ An incoming Hose/合思 `thirdparty.html` assistance link can be imported direct
|
||||
|
||||
## Quick Install (Standalone Binary)
|
||||
|
||||
No Node.js, Bun, or external runtime required. Run the one-line installer for macOS and Linux:
|
||||
No Node.js, Bun, or external runtime required. Run the one-line installer:
|
||||
|
||||
```bash
|
||||
# macOS & Linux (Bash)
|
||||
# 国内高速安装(Gitea 镜像源,免代理、秒级完成)
|
||||
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
|
||||
|
||||
@@ -25,13 +26,22 @@ curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/insta
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
```powershell
|
||||
# Windows (PowerShell)
|
||||
# 国内高速安装(Gitea 镜像源,免代理、秒级完成)
|
||||
irm https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.ps1 | iex
|
||||
|
||||
# Global / GitHub Direct
|
||||
irm https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.ps1 | iex
|
||||
```
|
||||
|
||||
Or download the native binary directly from [GitHub Releases](https://github.com/yunyingk/seal-use/releases/latest) or [Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases):
|
||||
|
||||
- **macOS (Apple Silicon)**: `curl -fsSL https://github.com/yunyingk/seal-use/releases/latest/download/seal-use-darwin-arm64 -o /usr/local/bin/seal-use && chmod +x /usr/local/bin/seal-use`
|
||||
- **macOS (Intel)**: `curl -fsSL https://github.com/yunyingk/seal-use/releases/latest/download/seal-use-darwin-x64 -o /usr/local/bin/seal-use && chmod +x /usr/local/bin/seal-use`
|
||||
- **Linux (x86_64)**: `curl -fsSL https://github.com/yunyingk/seal-use/releases/latest/download/seal-use-linux-x64 -o /usr/local/bin/seal-use && chmod +x /usr/local/bin/seal-use`
|
||||
- **Linux (ARM64)**: `curl -fsSL https://github.com/yunyingk/seal-use/releases/latest/download/seal-use-linux-arm64 -o /usr/local/bin/seal-use && chmod +x /usr/local/bin/seal-use`
|
||||
- **Windows (x64)**: Download `seal-use-windows-x64.zip` from Releases and extract `seal-use-windows-x64.exe`.
|
||||
- **Windows (x64)**: One-liner via PowerShell above, or download `seal-use-windows-x64.zip` from Releases and extract `seal-use-windows-x64.exe`.
|
||||
|
||||
After installation:
|
||||
|
||||
@@ -111,7 +121,7 @@ Import a Hose/合思 assistance link when you do not have OpenAPI app credential
|
||||
seal-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=<temporary-token>&ekbCorpId=<corpId>&pageType=home" [--name "企业名称"]
|
||||
```
|
||||
|
||||
The command accepts HTTPS links from the supported Hose domains, verifies the Seal tenant with `/api/v1/auth/me`, and writes a Hose source with `provider: "hosecloud"`, `closeToken`, and `staffId`. The incoming token is never printed. Use `--overwrite` to replace an existing config explicitly.
|
||||
The command accepts HTTPS links from the supported Hose domains, verifies the Seal tenant with `/api/v1/auth/me`, and writes a Hose source with `closeToken` and `staffId`. The incoming token is never printed. Use `--overwrite` to replace an existing config explicitly.
|
||||
|
||||
To generate a Seal delegation link directly from the same incoming Hose link without saving a config:
|
||||
|
||||
@@ -144,6 +154,7 @@ Three layers of documentation serve distinct audiences and boundaries, each vali
|
||||
- **`README.md` — the user/evaluator entry point.** High-level overview, quick installation, architecture, and governance outline (`bun run verify:readme`).
|
||||
- **`AGENTS.md` — the developer contract.** How contributors (human or agent) change this codebase: module boundaries, CLI stream/exit-code protocol, testing, release rules (`bun run verify:agents-md`).
|
||||
- **`skills/seal-use/SKILL.md` — the user/agent routing hub.** How an agent session uses the shipped skill: bootstrap, credential boundaries, and the terminal `## 参考文档路由` table that routes intents to `skills/seal-use/references/*.md`, which stay the single source of truth for operational detail (`bun run verify:skill-md`).
|
||||
- **Subdirectory readmes — `<dir>.readme.md`.** The root keeps `README.md`; every other README carries its directory name as a prefix, such as `src/src.readme.md` and `host-infra/host-infra.readme.md` (`bun run verify:readme-naming`).
|
||||
|
||||
Workflow rules live in `.agents/rules/*.md`; the root `AGENTS.md` indexes them and carries the enforced contract. Engineering and governance scripts live under `scripts/`, partitioned into `scripts/governance/` (automated gates) and root build/release pipelines.
|
||||
|
||||
@@ -207,8 +218,8 @@ Use `seal-use auth diagnose --corp <corpId>` when login fails in stateless mode.
|
||||
"source": {
|
||||
"type": "hose",
|
||||
"domain": "https://app.ekuaibao.com",
|
||||
"key": "hose-app-key",
|
||||
"password": "hose-app-security",
|
||||
"appKey": "hose-app-key",
|
||||
"appSecurity": "hose-app-security",
|
||||
"staffId": "hose-staff-id",
|
||||
"corpId": "hose-corp-id"
|
||||
},
|
||||
@@ -344,4 +355,4 @@ bun run bump 0.8.5
|
||||
**CI & Promotion Pipeline:**
|
||||
- GitHub Actions triggers automatically upon pushing a `v*` tag to `origin`;
|
||||
- Cross-compiles standalone binaries for 5 target platforms (macOS Apple Silicon/Intel, Linux x86_64/ARM64, Windows x64) and publishes them to **[GitHub Releases](https://github.com/yunyingk/seal-use/releases)**;
|
||||
- WSL `seal-use-release-sync.timer` polls the latest GitHub Release and promotes all assets to **[Gitea Releases](https://git.ying-qing.cn/gitea/seal-use/releases)** (`wsl-infra/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)** (`host-infra/host-infra.readme.md`).
|
||||
@@ -0,0 +1,160 @@
|
||||
# 云端企业配置方案(seal-use 侧)
|
||||
|
||||
状态:阶段一、二、三已实施(2026-11-19);桥接设备码已接入,`doctor` 已增加云端登录检查。
|
||||
|
||||
## 仓库边界
|
||||
|
||||
- `seal-use` 与 `hose-fde-workbench` 保持**两个独立仓库**,不合并为 monorepo(2026-11-19 决定)。
|
||||
- 对 seal-use 而言,cloud 企业配置是**增量功能**:默认 `storage: local`,现有用户、配置与命令行为不变。
|
||||
- 桥接作为独立凭据服务,通过 HTTP 契约交互;登录、scope、审计都在桥接侧。
|
||||
|
||||
## 进度
|
||||
|
||||
| 侧 | 状态 |
|
||||
|---|---|
|
||||
| seal-use | 阶段一、二已实施并提交(`mac15/cloud-enterprise-config`,`887df2d`);阶段三待设备码 |
|
||||
| 桥接 | 凭据服务已交付(PR #102);设备码端点需求已发送,待实现 |
|
||||
| 下一步 | 设备码契约定稿 → seal-use `bridge-client` + `auth login` → 预签发 token 注入、提权禁用、doctor 检查 |
|
||||
|
||||
## 已定决策
|
||||
|
||||
1. 企业配置新增根级 `storage: "local" | "cloud"`,默认 `local`,两种 `source.type` 通用。
|
||||
2. `cloud` 企业的本地 JSON **不保存任何密钥**(`appKey`/`appSecurity`/`closeToken`/`token`/`seal.cookies`),只保留路由与身份元数据。
|
||||
3. 登录不是下载的前置条件;**只有 cloud 企业需要登录**。安装包分发维持 GitHub(私有)+ Gitea(公开镜像)现状。
|
||||
4. cloud 企业:本地不写 `tokens.json`,凭据只在内存缓存到 `expiresAt - 60s`;不自动续费;不提供提权命令。
|
||||
5. 云端不可达或未登录时硬失败,不回退、不静默降级。
|
||||
|
||||
## 配置形态
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "ID01D3GcYxuyfl",
|
||||
"name": "南京测绘",
|
||||
"storage": "cloud",
|
||||
"environment": "production",
|
||||
"active": true,
|
||||
"seal": {
|
||||
"url": "https://id01d3gcyxuyfl.sealai.cc",
|
||||
"tenantSlug": "ID01D3GcYxuyfl",
|
||||
"endpoints": { "approvalStylePreferences": "api/v1/agent/ai-approval/config" }
|
||||
},
|
||||
"source": {
|
||||
"type": "hose",
|
||||
"domain": "https://app.ekuaibao.com",
|
||||
"corpId": "ID01D3GcYxuyfl",
|
||||
"staffId": "ID01D3GcYxuyfl:ID01JbL19boRwH"
|
||||
},
|
||||
"auth": { "refreshTtl": 300 }
|
||||
}
|
||||
```
|
||||
|
||||
校验规则(fail-closed):
|
||||
|
||||
- `storage: "cloud"` 时出现任何密钥字段 → 加载报错,不静默剥离。
|
||||
- `storage: "local"` 行为与现在完全一致。
|
||||
- `source.type`、`staffId`、`corpId`、`seal.url` 等路由字段仍为必填。
|
||||
|
||||
## 与桥接的接口契约(待对齐)
|
||||
|
||||
### 凭据获取
|
||||
|
||||
```http
|
||||
GET /api/enterprise-credentials/resolve?type=hose&corpId=<corpId>
|
||||
Cookie: hose_sealai_session=<token>
|
||||
```
|
||||
|
||||
响应(桥接实际返回):
|
||||
|
||||
```json
|
||||
// hose:服务端已用 appKey/appSecurity 换好短期 accessToken
|
||||
{ "ok": true, "credential": {
|
||||
"type": "hose", "corpId": "...", "name": "...", "baseUrl": "...",
|
||||
"token": "<accessToken>", "tokenType": "query", "tokenName": "accessToken",
|
||||
"expiresAt": "2026-11-19T10:05:00.000Z", "metadata": { "note": "生产" } } }
|
||||
|
||||
// seal:Bearer Token,可能附带协助授权会话 Cookie,expiresAt 可能为 null
|
||||
{ "ok": true, "credential": {
|
||||
"type": "seal", "corpId": "...", "name": "...", "baseUrl": "...",
|
||||
"token": "<bearer>", "tokenType": "bearer", "tokenName": "Authorization",
|
||||
"expiresAt": "2026-12-01T00:00:00.000Z", "sessionCookie": "sid=...", "metadata": null } }
|
||||
```
|
||||
|
||||
与本文早期假设的关键差异:
|
||||
|
||||
1. **hose 返回的是已换好的 accessToken**,不是 appKey/appSecurity。`getHoseOpenapiToken` 需要新增"预签发 token"路径,跳过本地换发。
|
||||
2. **`tokenType` / `tokenName` 决定注入位置**(`query` / `header` / `bearer` / `body`)。现有 `fetchHoseCloseApiToken` 与 SSO 请求写死 `accessToken` 查询参数,需要按响应注入。
|
||||
3. **seal 的 `expiresAt` 可能为 null**:此时按本地保守策略缓存,并在 401/403 时重新拉取。
|
||||
4. **读取需要菜单 scope**:hose 要 `expense`,seal 要 `sealai`;403 响应带 `requiredScope`。
|
||||
|
||||
错误语义(桥接实际):
|
||||
|
||||
| HTTP / code | seal-use 行为 | 退出码 |
|
||||
|---|---|---|
|
||||
| 401 `AUTH_REQUIRED` | 提示重新登录后重试一次 | 11 |
|
||||
| 403 `FORBIDDEN` | 提示管理员授予 `expense` / `sealai` scope | 11 |
|
||||
| 404 `CREDENTIAL_NOT_FOUND` | 该企业未在云端登记 | 13 |
|
||||
| 409 `CREDENTIAL_DISABLED` / `CREDENTIAL_MISMATCH` | 提示管理员启用或核对密钥归属 | 13 |
|
||||
| 500 `DECRYPT_FAILED` / `INTERNAL_ERROR` | 平台侧问题,退避后告警 | 1 |
|
||||
| 502 `UPSTREAM_AUTH_FAILED` | 合思授权失败,指数退避重试 | 1 |
|
||||
|
||||
### CLI 登录
|
||||
|
||||
**决定:采用设备码登录,等待桥接新增 `/api/auth/device/start` 与 `/api/auth/device/token`。** 在设备码端点可用前,不实现基于账号密码或 Cookie 的登录方式。
|
||||
|
||||
桥接当前只提供账号密码登录换会话 Cookie,**没有设备码或 PAT**:
|
||||
|
||||
```http
|
||||
POST /api/auth/login
|
||||
Origin: https://<bridge-host>
|
||||
{ "username": "seal-use-service", "password": "..." }
|
||||
```
|
||||
|
||||
- 会话 Cookie `hose_sealai_session` 有效期 180 天、滑动续期;响应带新 `Set-Cookie` 时覆盖保存。
|
||||
- seal-use 保存 Cookie 到 `~/.config/seal-use/bridge.json`(`0600`),支持 `SEAL_USE_BRIDGE_TOKEN` 环境变量覆盖。
|
||||
- **遗留缺口**:Cookie 过期后必须重新用密码登录。若不想在本地保存服务账号密码,需要桥接补设备码或 PAT;当前契约下只能二选一(存密码自动重登,或过期后交互式输入)。
|
||||
|
||||
## seal-use 改动清单
|
||||
|
||||
### 阶段一:不依赖桥接 API
|
||||
|
||||
1. [config/types.ts](../../../src/core/config/types.ts):根级 `storage` 枚举,默认 `local`;cloud 分支的 fail-closed 校验。
|
||||
2. [config/repository.ts](../../../src/core/config/repository.ts):`saveCorpConfig` 在 cloud 模式下拒绝含密钥的配置。
|
||||
3. `corps list` / `corps get` 输出增加 `storage`。
|
||||
4. 测试:cloud 配置合法/非法两种形态、旧配置默认 local。
|
||||
|
||||
### 阶段二:凭据解析器
|
||||
|
||||
5. 新增 `src/core/auth/credentials.ts`:`resolveCorpCredentials(corp)`,local 分支直接返回现有字段;cloud 分支在未登录时报 `authRequired`。
|
||||
6. 收口现有 7 处直接读取([auth/hose.ts:277](../../../src/core/auth/hose.ts:277)、[hose/open/approval.ts:45](../../../domains/hose/open/approval.ts:45)、[cli/auth.ts:178](../../../cli/commands/auth.ts:178)、[cli/auth.ts:240](../../../cli/commands/auth.ts:240)、[corps/shared.ts:23](../../../cli/commands/corps/shared.ts:23)、[corps/onboarding.ts:412](../../../cli/commands/corps/onboarding.ts:412)、[testing/sync.ts:321](../../../domains/seal/testing/sync.ts:321))。
|
||||
7. cloud 企业跳过 `tokens.json` 写入与 `renewNativeSealSession` 的配置回写;401 自愈改为重新向云端取。
|
||||
|
||||
### 阶段三:桥接接入
|
||||
|
||||
8. 新增 `src/core/auth/bridge-client.ts`:账号登录换 Cookie、Cookie 持久化与滑动续期、凭据请求与内存缓存。
|
||||
9. `resolveCorpCredentials` 的 cloud 分支返回预签发凭据;`getHoseOpenapiToken` 增加预签发 token 路径,并按 `tokenType` / `tokenName` 注入请求。
|
||||
10. `seal-use auth login/logout/status` 命令;`doctor` 增加登录、scope 与连通性检查。
|
||||
11. cloud 企业禁用提权类命令(`add-link --as-hose`、`hose-extract-keys`、`corps keys`),提示到云端管理。
|
||||
|
||||
实施状态:8–11 已完成。CLI 命令为 `auth login` / `auth logout` / `auth bridge`。
|
||||
|
||||
## 兼容与行为变化
|
||||
|
||||
- 旧配置无 `storage` → 解析为 `local`,行为不变。
|
||||
- cloud 配置不会因加载被改写;切换 `local → cloud` 需要专门命令(本期不做自动切换)。
|
||||
- `corps list/get` 的 JSON 新增 `storage` 字段;依赖旧输出结构的脚本需要容忍新增键。
|
||||
- cloud 企业离线不可用,这是预期代价。
|
||||
|
||||
## 验证
|
||||
|
||||
1. 配置:cloud 合法形态通过、含密钥被拒、旧配置默认 local。
|
||||
2. 解析器:local 行为回归(现有全部测试);cloud 未登录报 11。
|
||||
3. 缓存:cloud 企业运行后 `tokens.json` 不新增条目。
|
||||
4. 命令:提权命令对 cloud 企业返回明确错误。
|
||||
5. `bun run check`、`bun run lint`、全部治理门禁、全量 `bun test`。
|
||||
|
||||
## 未决问题
|
||||
|
||||
1. 桥接设备码端点的具体形态与令牌有效期(已决定用设备码,待桥接提供)。
|
||||
2. cloud 企业是否允许本地缓存派生会话(当前定为不允许,纯内存)。
|
||||
3. 切换 `local ↔ cloud` 的命令形态。
|
||||
4. 桥接管理端前端页面(当前仅 API,凭据由管理员通过接口维护)。
|
||||
@@ -0,0 +1,69 @@
|
||||
# 企业 provider 字段清理方案
|
||||
|
||||
状态:已实施并验证(2026-11-19)。范围仅限企业 provider 元数据及其直接引用。
|
||||
|
||||
## 结论与证据
|
||||
|
||||
建议删除企业配置的 `source.provider`、`source.providerName`,同时删除本地认证会话的 `enterprise.provider` 及相关输入、展示、检索、赋值和测试负载。不新增替代分类字段。
|
||||
|
||||
- [配置定义](../../../src/core/config/types.ts:9):`provider` 在两种 source 上均为可选自由字符串,不是三值枚举;`providerName` 只有声明,没有业务读写。
|
||||
- [企业选择](../../../src/core/config/manager.ts:11):选择依据是企业 ID、名称、默认企业和 active 门禁;provider 不参与。
|
||||
- [搜索](../../../src/core/corp-search/corp.ts:26):provider 作为权重 0.8 的可选匹配文本。
|
||||
- [列表与当前企业](../../../src/cli/commands/corps/overview.ts:97) 使用 `provider ?? source.type`;[详情](../../../src/cli/commands/corps/shared.ts:26) 的 Hose 分支使用 `provider ?? "hosecloud"`。持久凭据企业未存 provider 时,两者输出不同值。
|
||||
- [Seal 接入](../../../src/domains/seal/enterprise/onboarding.ts:142) 从输入或远端身份中复制 provider;[Hose Web 接入](../../../src/domains/hose/onboarding.ts:278) 写死 hosecloud;Hose 持久凭据不写该字段。
|
||||
- [缓存类型](../../../src/core/auth/types.ts:9) 要求 enterprise.provider,由 [native](../../../src/core/auth/native.ts:18)、[seal](../../../src/core/auth/seal.ts:72)、[hose](../../../src/core/auth/hose.ts:498) 构造,但仓库内没有按它决策的消费者。
|
||||
- 三处企业密钥相关输出也含固定 `provider: "hose"`,见 [corps/onboarding.ts](../../../src/cli/commands/corps/onboarding.ts:342)。它们不是企业配置写入点,但属于同一冗余标签。
|
||||
|
||||
证据边界:以上为仓库内静态引用调查,不能据此断言没有外部脚本读取 CLI JSON 中的 provider。此前“三种分类”以及“只需改几处展示”的描述不准确;实际涉及配置、接入、缓存、输出和测试。
|
||||
|
||||
## 目标与涉及文件
|
||||
|
||||
| 模块 | 文件 | 具体修改 |
|
||||
|---|---|---|
|
||||
| 配置 | [types.ts](../../../src/core/config/types.ts) | 删除 Hose、Seal source 的 provider,以及 Seal source 的 providerName |
|
||||
| 本地会话 | [auth/types.ts](../../../src/core/auth/types.ts)、[native.ts](../../../src/core/auth/native.ts)、[seal.ts](../../../src/core/auth/seal.ts)、[hose.ts](../../../src/core/auth/hose.ts) | 删除 enterprise.provider 的 schema 与三处构造赋值 |
|
||||
| 接入 | [seal/enterprise/onboarding.ts](../../../src/domains/seal/enterprise/onboarding.ts)、[hose/onboarding.ts](../../../src/domains/hose/onboarding.ts) | 删除 SealBearerInput.provider、远端复制和固定值写入;保留其它身份与凭据数据 |
|
||||
| CLI | [corps/onboarding.ts](../../../src/cli/commands/corps/onboarding.ts)、[overview.ts](../../../src/cli/commands/corps/overview.ts)、[shared.ts](../../../src/cli/commands/corps/shared.ts) | 停止解析 add-seal-bearer 的 provider;删除列表、当前企业、详情和三处密钥相关输出中的 provider |
|
||||
| 检索 | [corp-search/corp.ts](../../../src/core/corp-search/corp.ts) | 删除 provider 匹配项 |
|
||||
| 文档 | [README.md](../../../README.md:124) | 删除接入后保存 provider: hosecloud 的承诺,继续说明真实凭据字段 |
|
||||
|
||||
测试同步范围:
|
||||
|
||||
- [config/types.test.ts](../../../src/core/config/types.test.ts)、[cli/commands/corps.test.ts](../../../src/cli/commands/corps.test.ts):更新字段预期,覆盖旧字段兼容和输出不再带 provider。
|
||||
- [auth/native.test.ts](../../../src/core/auth/native.test.ts)、[auth/hose.test.ts](../../../src/core/auth/hose.test.ts)、[auth/seal-renew.test.ts](../../../src/core/auth/seal-renew.test.ts)、[auth/token-store.test.ts](../../../src/core/auth/token-store.test.ts):更新会话构造及断言,验证旧缓存仍可读。
|
||||
- [http/factory.test.ts](../../../src/core/http/factory.test.ts)、[cli/commands/report-review-cli.test.ts](../../../src/cli/commands/report-review-cli.test.ts)、[probe.test.ts](../../../src/probe.test.ts):仅清理本地会话 fixture 的冗余标签;保留模拟远端接口的真实字段。
|
||||
|
||||
## 边界与取舍
|
||||
|
||||
保留以下内容:
|
||||
|
||||
1. `source.type: hose | seal`:仍决定认证实现。
|
||||
2. `closeToken`、`appKey/appSecurity`、Seal token 和委托 cookie:仍决定实际凭据与认证过程。
|
||||
3. `providerUserId`:接入和刷新元数据使用它,且 [onboarding.ts:141](../../../src/domains/seal/enterprise/onboarding.ts:141) 用它推导 staffId;不能因名字相似而连带删除。
|
||||
4. [Seal API 用户身份判断](../../../src/domains/seal/api.ts:1283) 与 [远端类型](../../../src/domains/seal/types.ts):这里的 provider 属于服务端协议,实际参与本地密码及合思身份判断,继续保留。
|
||||
5. 远端原始对象中的 provider、LLM provider 等同名概念。
|
||||
6. 企业启停、环境标签、生产测试绑定、默认企业选择等其它管理机制。
|
||||
|
||||
不扩展到企业管理整体重构;此次明确有证据的冗余字段可独立清理。
|
||||
|
||||
## 兼容与预期行为变化
|
||||
|
||||
- 旧企业 JSON 即使仍有 provider/providerName,也应正常加载;Zod 默认剥离未声明键,运行时对象不再包含它们。不会因加载而主动改写原文件。
|
||||
- 新建或经现有 schema 保存的企业配置不再写入这些键。不编写迁移脚本,也不扫描或批量重写真实企业目录。
|
||||
- 旧 tokens.json 带 enterprise.provider 时仍应解析成功,后续会话不再生成该键;现有 token、有效期和其它缓存条目保留。通过隔离测试验证,不操作真实 token 文件。
|
||||
- add-seal-bearer 的旧 JSON 中仍带 provider 时按无效元数据忽略,不因这一额外键报错,也不再检查或保存它。
|
||||
- corps list/current/get/show 及三处密钥相关输出不再有 provider;已有 sourceType、source.type 或 kind 等字段继续按现有命令输出,避免重新添加同义标签。
|
||||
- 依赖 JSON provider 字段的外部调用方需要调整;不能承诺输出结构完全兼容。
|
||||
- 仅凭 provider 匹配的检索结果会消失,例如 Seal source 中曾存 feishu、用户以 feishu 搜企业。企业 ID、名称等现有搜索字段继续工作,Hose 仍可由 source.type 匹配。
|
||||
- 认证与租户操作的分派依据不变,删除的是元数据链路。
|
||||
|
||||
## 验证方案
|
||||
|
||||
1. 隔离配置测试:旧 provider/providerName 存在时仍能加载,解析结果不再含键;Hose 持久凭据、Web 会话与 Seal source 仍通过校验。
|
||||
2. 隔离缓存测试:带 provider 的旧缓存及不带 provider 的新缓存均能读取,token、有效期和其它条目不丢失。
|
||||
3. 接入与 CLI 回归:两类 Hose 接入、Seal bearer、委托与续期既有测试;断言新配置、会话和相关 JSON 输出不再产生 provider。
|
||||
4. 检索回归:验证删除 provider 搜索项后 ID、名称、source.type 等正常匹配。
|
||||
5. 执行 `bun run check`、`bun run lint` 与上述受影响的 Bun 测试;测试禁用后台更新并使用临时配置路径,不访问真实企业数据。
|
||||
6. 最后复查 Diff 和全仓引用,确认剩余 provider 仅属于服务端协议、其它业务概念或明确的旧格式兼容测试;若有新增发现,报告实际差异。
|
||||
|
||||
实施结果:已按上表完成清理,`bun run check`、`bun run lint` 与全量 `bun test`(1180 通过)均通过。未改写本机企业配置或认证缓存;旧配置与旧缓存的兼容性由隔离测试覆盖。
|
||||
@@ -42,26 +42,10 @@ Credentials are stored as `0600` files under
|
||||
From mac15, run:
|
||||
|
||||
```sh
|
||||
./ops/infra-healthcheck.sh
|
||||
./host-infra/infra-healthcheck.sh
|
||||
```
|
||||
|
||||
It emits JSON checks for mac15, the Mac15-to-WSL Tailscale/SSH path, WSL,
|
||||
Windows, mac13, and Aliyun, including the release-sync timer state and the last
|
||||
successful Gitea promotion. The script is read-only; a failed check
|
||||
does not restart or mutate any service.
|
||||
|
||||
## Workspace backups
|
||||
|
||||
The repository is the source of truth. After the ops changes are committed to
|
||||
`main`, back up the tracked `ops/` directory to each machine's global workspace:
|
||||
|
||||
```sh
|
||||
./ops/backup-workspace-scripts.sh
|
||||
```
|
||||
|
||||
Each run creates a commit-named snapshot under
|
||||
`~/Workspace/ops-backups/seal-use/` on mac15 and mac13, and under
|
||||
`~/workspace/ops-backups/seal-use/` on WSL and Aliyun. Each snapshot includes a
|
||||
manifest with its source commit and backup time. Only tracked `ops/` files are
|
||||
copied; private runtime configuration and credentials are excluded. Run the
|
||||
backup command again after changing operational scripts or service templates.
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "seal-use",
|
||||
"version": "0.11.19",
|
||||
"version": "0.11.23",
|
||||
"private": true,
|
||||
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
|
||||
"license": "MIT",
|
||||
@@ -42,7 +42,8 @@
|
||||
"verify:cli-md": "bun run scripts/check-cli-md.mjs",
|
||||
"verify:agents-md": "bun run scripts/governance/check-agents-md.ts",
|
||||
"verify:skill-md": "bun run scripts/governance/check-skill-md.ts",
|
||||
"verify:readme": "bun run scripts/governance/check-readme.ts"
|
||||
"verify:readme": "bun run scripts/governance/check-readme.ts",
|
||||
"verify:readme-naming": "bun run scripts/governance/check-readme-naming.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
|
||||
|
||||
---
|
||||
|
||||
## 1. 审核测试结果
|
||||
|
||||
### 1.1 数据来源与范围
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 数据来源 | 客户授权的已完成历史审批单据 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
|
||||
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
|
||||
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
|
||||
|
||||
### 1.2 核心准确率结论
|
||||
|
||||
基于已经给定的规则库:
|
||||
|
||||
| 审核方式 | 准确率 |
|
||||
| --- | --- |
|
||||
| AI 审核 | **92.08%** |
|
||||
| 人工审核 | **83.33%** |
|
||||
|
||||
AI 审核准确率的计算方式:
|
||||
|
||||
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
|
||||
|
||||

|
||||
|
||||
*图 1 · AI 与人工审核准确率对比*
|
||||
|
||||
---
|
||||
|
||||
## 2. AI 失准分析(学习优化空间)
|
||||
|
||||
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
|
||||
|
||||
### 2.1 失准构成总览
|
||||
|
||||
| 维度 | 失准类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
|
||||
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
|
||||
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
|
||||
| 合计 | — | 100% | 19 张 |
|
||||
|
||||
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
|
||||
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
|
||||
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
|
||||
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
|
||||
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
|
||||
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
|
||||
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
---
|
||||
|
||||
## 3. AI 发现的潜在风险
|
||||
|
||||
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
|
||||
|
||||
### 3.1 风险构成总览
|
||||
|
||||
| 维度 | 风险类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
|
||||
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
|
||||
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
|
||||
| 合计 | — | 100% | 40 张 |
|
||||
|
||||
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260011 | 改衣费未附改衣明细表 |
|
||||
| FP260012 | 咨询费报销资料不全 |
|
||||
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
|
||||
|
||||
*(节选 3 例,全量 23 张)*
|
||||
|
||||
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
|
||||
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
|
||||
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
|
||||
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
|
||||
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
|
||||
|
||||
*(节选 3 条,全量 8 张)*
|
||||
|
||||
---
|
||||
|
||||
## 4. 综合效益
|
||||
|
||||
| 维度 | 结论 | 关键数据 |
|
||||
| --- | --- | --- |
|
||||
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
|
||||
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
|
||||
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||
---
|
||||
|
||||
## 5. 审核分歧与复核归因
|
||||
|
||||
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
|
||||
|
||||
| 原因分类 | 占比 | 单数 | 核心说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
|
||||
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
|
||||
| 合计 | 100% | 3 张 | — |
|
||||
|
||||
**分歧分析与后续建议**:
|
||||
|
||||
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
|
||||
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
|
||||
|
||||
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
|
||||
|
||||
---
|
||||
|
||||
## 6. 支撑数据与交付材料
|
||||
|
||||
### 6.1 分模板准确率与自动审批率
|
||||
|
||||
全量 N = 240:
|
||||
|
||||
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
|
||||
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
|
||||
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
|
||||
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
*(其余 10 类模板从略,实际报告列出全量 16 类)*
|
||||
|
||||
### 6.2 跑批原始数据与交付台账
|
||||
|
||||
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
|
||||
@@ -1,64 +0,0 @@
|
||||
# AI 审核报告编制与校验规范
|
||||
|
||||
本目录提供标准的 AI 审核报告 Markdown 模板与配套的离线校验脚本。
|
||||
|
||||
---
|
||||
|
||||
## 一、标准模板与章节规范
|
||||
|
||||
报告应以 Markdown 格式编写(可参考同目录下的 [`example-report.md`](example-report.md))。
|
||||
|
||||
### 1. 核心必填章节(按大标题名称识别)
|
||||
核心章节通过 `##` 大标题名称自动识别与归属,包含以下板块:
|
||||
|
||||
| 核心大标题名称 | 说明与要求 |
|
||||
| :--- | :--- |
|
||||
| **开篇「报告信息」表** | 文档顶部表格,必填 5 项:`报告编号`、`客户名称`、`统计期间`、`报告状态`、`生成日期`,均不可为空。 |
|
||||
| **`审核测试结果`** | 汇总效能指标、AI 与人工准确率结论、LaTeX 计算公式(`$$ \text{AI 审核准确率} = \frac{A}{B} = C\% $$`)与对比图表。 |
|
||||
| **`AI 失准分析`** | 包含失准构成总览表、TOP 1~N 典型错判案例表格与调优方案。 |
|
||||
| **`AI 发现的潜在风险`** | 包含潜在风险总览表、TOP 1~N 真实拦截案例表格(如凭证缺失、比价缺失、超期等)。 |
|
||||
| **`综合效益`** | 时效、准确度、风险拦截笔数宏观总结表(纯内部核对时可按需裁剪)。 |
|
||||
| **`审核分歧与复核归因`** | 人机分歧分类统计表(如“未在线配置规则”与“识别偏差”)与管理建议。 |
|
||||
| **`支撑数据与交付材料`** | 分模板统计表与说明。 |
|
||||
|
||||
### 2. 中间自定义插入章节
|
||||
* 如需针对特定部门、专项费用做深入穿透,允许在任意位置插入自定义章节(例如 `## 2. 营销业务线专项分析`)。
|
||||
* **规则**:大标题序号从 1 开始自然连续递增(1, 2, 3, 4, 5...);自定义插入的章节内容不受业务规则限制,写什么格式都直接放行。
|
||||
|
||||
---
|
||||
|
||||
## 二、核心格式规范
|
||||
|
||||
为保证文档严谨自洽,报告编写需满足以下格式守则:
|
||||
|
||||
1. **纯净 Markdown 语法**:
|
||||
* 严禁在开头使用 YAML Frontmatter(`---`),元数据请统一写在开篇「报告信息」表中;
|
||||
* 严禁残留草稿占位标记(如 `<!--slot:xxx-->`、`{{variable}}` 等);
|
||||
* 代码块(```)必须成对闭合。
|
||||
2. **表格结构**:
|
||||
* 表格每行单元格数量必须严格与表头对齐;
|
||||
* 表头文字保持纯文本,禁止包含加粗符号(`**`);
|
||||
* 案例表格推荐使用纯净紧凑的 2 列格式(`| 单号 | 问题描述 |`),无需手工填写长链接。
|
||||
3. **数学总账守恒**:
|
||||
* 失准总览表与潜在风险总览表中,各 TOP 行的单数相加必须严格等于「合计」行单数,百分比相加必须等于 100%(误差 $\le 0.15\%$);
|
||||
* 各子小节标题中声明的张数(如 `### 2.2 TOP 1 · xxx(9 张 / 47.4%)`)必须与总览表该行单数完全一致;
|
||||
* LaTeX 公式中的算术计算必须成立(如 $\frac{221}{240} = 92.08\%$),且公式中的数字在正文中有对应出处。
|
||||
|
||||
---
|
||||
|
||||
## 三、校验脚本使用说明
|
||||
|
||||
同目录下已提供独立的 Python 校验脚本 [`validate.py`](validate.py)(纯 Python 标准库编写,无需安装任何第三方库)。
|
||||
|
||||
### 运行校验
|
||||
```bash
|
||||
python3 validate.py example-report.md
|
||||
```
|
||||
|
||||
* **校验通过**:终端输出绿色通过提示,退出码为 `0`;
|
||||
* **校验未通过**:终端会明确打印出具体报错的行号、错误代码及修复指南,退出码为 `1`。
|
||||
|
||||
支持输出 JSON 格式供程序化调用:
|
||||
```bash
|
||||
python3 validate.py example-report.md --json
|
||||
```
|
||||
@@ -1,51 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="400" viewBox="0 0 960 400" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif">
|
||||
<defs>
|
||||
<!-- 精确交集透镜裁剪路径 -->
|
||||
<clipPath id="left-circle-clip">
|
||||
<circle cx="410" cy="160" r="135"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect width="960" height="400" fill="#ffffff"/>
|
||||
|
||||
<!-- Left Circle: Pastel Blue -->
|
||||
<circle cx="410" cy="160" r="135" fill="#b9deff"/>
|
||||
|
||||
<!-- Right Circle: Pastel Mint -->
|
||||
<circle cx="550" cy="160" r="135" fill="#d2ede8"/>
|
||||
|
||||
<!-- Distinct Intersection Lens: Perfect blend tone (#9ed4eb) -->
|
||||
<circle cx="550" cy="160" r="135" clip-path="url(#left-circle-clip)" fill="#9ed4eb"/>
|
||||
|
||||
<!-- Left Text Block (Horizontally centered lines) -->
|
||||
<g text-anchor="middle" fill="#111111">
|
||||
<text x="140" y="146" font-size="18"><tspan letter-spacing="1.5px">AI</tspan><tspan letter-spacing="0px">审核准确</tspan></text>
|
||||
<text x="140" y="176" font-size="18">(总准确率92.08%)</text>
|
||||
</g>
|
||||
<!-- Left dashed line: comfortable gap from text, extends into circle -->
|
||||
<line x1="245" y1="160" x2="310" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Left percentage -->
|
||||
<text x="348" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">16.66%</text>
|
||||
|
||||
<!-- Overlap percentage (in intersection lens) -->
|
||||
<text x="480" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">75.42%</text>
|
||||
|
||||
<!-- Right percentage -->
|
||||
<text x="612" y="160" font-size="22" fill="#111111" text-anchor="middle" dominant-baseline="central">7.91%</text>
|
||||
|
||||
<!-- Right dashed line -->
|
||||
<line x1="650" y1="160" x2="715" y2="160" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Right Text Block (Horizontally centered lines) -->
|
||||
<g text-anchor="middle" fill="#111111">
|
||||
<text x="820" y="146" font-size="18">人工审核准确</text>
|
||||
<text x="820" y="176" font-size="18">(总准确率83.33%)</text>
|
||||
</g>
|
||||
|
||||
<!-- Bottom vertical dashed pointer -->
|
||||
<line x1="480" y1="215" x2="480" y2="305" stroke="#222222" stroke-width="1.8" stroke-dasharray="6,4.5"/>
|
||||
|
||||
<!-- Bottom label: refined kerning on AI and comfortable character spacing -->
|
||||
<text x="480" y="338" font-size="18" fill="#111111" text-anchor="middle" dominant-baseline="central"><tspan letter-spacing="2px">AI</tspan><tspan letter-spacing="1px">与人工都准确</tspan></text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
@@ -1,190 +0,0 @@
|
||||
# 【模板企业】8月AI审核准确率报告
|
||||
|
||||
| 报告信息 | 内容 |
|
||||
| --- | --- |
|
||||
| 报告编号 | RPT-202608-A3F8C2 |
|
||||
| 客户名称 | 模板企业 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 |
|
||||
| 报告状态 | 草稿 |
|
||||
| 生成日期 | 2026-09-23 |
|
||||
|
||||
> **摘要**:以模板企业授权的 240 笔已完成历史审批单据为样本,对 AI 审核结论与人工审核结论进行全量复核。AI 审核准确率 **92.08%**,人工审核准确率 **83.33%**。AI 还在人工已同意的单据中额外识别出 **40 笔**存在风险。
|
||||
|
||||
---
|
||||
|
||||
## 1. 审核测试结果
|
||||
|
||||
### 1.1 数据来源与范围
|
||||
|
||||
| 项目 | 内容 |
|
||||
| --- | --- |
|
||||
| 数据来源 | 客户授权的已完成历史审批单据 |
|
||||
| 统计期间 | 2026-08-01 ~ 2026-08-31 期间单据 |
|
||||
| 单据模板 | 涵盖一般费用报销单【发票】-个人报销、一般费用报销单【发票】-对外支付、一般费用报销单【收据】-个人报销、差旅报销单-定额、采购付款单等 **16 类**业务单据模板 |
|
||||
| 样本总量 | **240 张**(100 张同意 + 100 张驳回 + 40 张建议复核) |
|
||||
|
||||
### 1.2 核心准确率结论
|
||||
|
||||
基于已经给定的规则库:
|
||||
|
||||
| 审核方式 | 准确率 |
|
||||
| --- | --- |
|
||||
| AI 审核 | **92.08%** |
|
||||
| 人工审核 | **83.33%** |
|
||||
|
||||
AI 审核准确率的计算方式:
|
||||
|
||||
$$ \text{AI 审核准确率} = \frac{\text{依规判定正确单数}}{\text{样本总量}} = \frac{221}{240} = 92.08\% $$
|
||||
|
||||

|
||||
|
||||
*图 1 · AI 与人工审核准确率对比*
|
||||
|
||||
---
|
||||
|
||||
## 2. AI 失准分析(学习优化空间)
|
||||
|
||||
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
|
||||
|
||||
### 2.1 失准构成总览
|
||||
|
||||
| 维度 | 失准类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
|
||||
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
|
||||
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
|
||||
| 合计 | — | 100% | 19 张 |
|
||||
|
||||
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
|
||||
|
||||
**解决方案**:严格校准规则触发后动作,按规则执行。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
|
||||
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
|
||||
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
|
||||
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
|
||||
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
|
||||
|
||||
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
|
||||
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
|
||||
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
|
||||
|
||||
*(节选 3 例,全量 5 张)*
|
||||
|
||||
---
|
||||
|
||||
## 3. AI 发现的潜在风险
|
||||
|
||||
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
|
||||
|
||||
### 3.1 风险构成总览
|
||||
|
||||
| 维度 | 风险类型 | 占比 | 单数 |
|
||||
| --- | --- | --- | --- |
|
||||
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
|
||||
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
|
||||
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
|
||||
| 合计 | — | 100% | 40 张 |
|
||||
|
||||
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260011 | 改衣费未附改衣明细表 |
|
||||
| FP260012 | 咨询费报销资料不全 |
|
||||
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
|
||||
|
||||
*(节选 3 例,全量 23 张)*
|
||||
|
||||
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
|
||||
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
|
||||
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
|
||||
|
||||
*(节选 3 例,全量 9 张)*
|
||||
|
||||
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
|
||||
|
||||
| 单号 | 问题描述 |
|
||||
| --- | --- |
|
||||
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
|
||||
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
|
||||
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
|
||||
|
||||
*(节选 3 条,全量 8 张)*
|
||||
|
||||
---
|
||||
|
||||
## 4. 综合效益
|
||||
|
||||
| 维度 | 结论 | 关键数据 |
|
||||
| --- | --- | --- |
|
||||
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
|
||||
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
|
||||
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
|
||||
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
|
||||
|
||||
---
|
||||
|
||||
## 5. 审核分歧与复核归因
|
||||
|
||||
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
|
||||
|
||||
| 原因分类 | 占比 | 单数 | 核心说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
|
||||
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
|
||||
| 合计 | 100% | 3 张 | — |
|
||||
|
||||
**分歧分析与后续建议**:
|
||||
|
||||
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
|
||||
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
|
||||
|
||||
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
|
||||
|
||||
---
|
||||
|
||||
## 6. 支撑数据与交付材料
|
||||
|
||||
### 6.1 分模板准确率与自动审批率
|
||||
|
||||
全量 N = 240:
|
||||
|
||||
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
|
||||
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
|
||||
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
|
||||
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
|
||||
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
|
||||
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
|
||||
|
||||
*(其余 10 类模板从略,实际报告列出全量 16 类)*
|
||||
|
||||
### 6.2 跑批原始数据与交付台账
|
||||
|
||||
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
|
||||
@@ -1,374 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI 审核报告(Markdown)独立校验器
|
||||
Independent Markdown Validator for AI Audit Reports
|
||||
|
||||
特点:
|
||||
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台开箱即用
|
||||
- 核心章节按大标题名称硬匹配,中间插入的自定义章节直接放行
|
||||
- 严格守护格式合规与数学总账守恒
|
||||
|
||||
用法:
|
||||
python3 validate.py <report.md>
|
||||
python3 validate.py <report.md> --json
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
|
||||
REQUIRED_INFO_ROWS = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
|
||||
FORBIDDEN_MARKS = [
|
||||
(re.compile(r"<!--slot:"), "slot 标记"),
|
||||
(re.compile(r"<!--/slot"), "slot 闭合"),
|
||||
(re.compile(r"<!--@"), "@table/@block 区域标记"),
|
||||
(re.compile(r"<!-- render:stop"), "render:stop 标记"),
|
||||
(re.compile(r"\{\{"), "{{槽位}}"),
|
||||
]
|
||||
|
||||
class ReportIssue:
|
||||
def __init__(self, level: str, code: str, message: str, line: Optional[int] = None):
|
||||
self.level = level # "ERROR" | "WARN"
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.line = line
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
d: Dict[str, Any] = {"level": self.level, "code": self.code, "message": self.message}
|
||||
if self.line is not None:
|
||||
d["line"] = self.line
|
||||
return d
|
||||
|
||||
|
||||
class TableRow:
|
||||
def __init__(self, line_num: int, cells: List[str]):
|
||||
self.line_num = line_num
|
||||
self.cells = cells
|
||||
|
||||
|
||||
class ParsedTable:
|
||||
def __init__(self, line_num: int, header: List[str], rows: List[TableRow]):
|
||||
self.line_num = line_num
|
||||
self.header = header
|
||||
self.rows = rows
|
||||
|
||||
|
||||
def split_cells(line: str) -> List[str]:
|
||||
text = line.strip()
|
||||
if text.startswith("|"):
|
||||
text = text[1:]
|
||||
if text.endswith("|") and not text.endswith(r"\|"):
|
||||
text = text[:-1]
|
||||
# Split on unescaped pipe
|
||||
raw_cells = re.split(r"(?<!\\)\|", text)
|
||||
return [c.replace(r"\|", "|").strip() for c in raw_cells]
|
||||
|
||||
|
||||
def parse_tables(lines: List[str]) -> List[ParsedTable]:
|
||||
result: List[ParsedTable] = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
line = lines[i].strip()
|
||||
if i + 1 < len(lines):
|
||||
separator = lines[i + 1].strip()
|
||||
if line.startswith("|") and "-" in separator and re.match(r"^[|\-: ]+$", separator):
|
||||
header = split_cells(line)
|
||||
table = ParsedTable(line_num=i + 1, header=header, rows=[])
|
||||
i += 2
|
||||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||||
table.rows.append(TableRow(line_num=i + 1, cells=split_cells(lines[i])))
|
||||
i += 1
|
||||
result.append(table)
|
||||
continue
|
||||
i += 1
|
||||
return result
|
||||
|
||||
|
||||
def extract_numeric(text: str, is_percent: bool = False) -> Optional[float]:
|
||||
pattern = r"(\d+(?:\.\d+)?)\s*%" if is_percent else r"(\d+(?:\.\d+)?)"
|
||||
m = re.search(pattern, text)
|
||||
if m:
|
||||
try:
|
||||
return float(m.group(1))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def validate_report(filepath: str) -> Dict[str, Any]:
|
||||
path = Path(filepath).resolve()
|
||||
if not path.is_file():
|
||||
return {
|
||||
"file": str(path),
|
||||
"valid": False,
|
||||
"tables": 0,
|
||||
"figures": 0,
|
||||
"issues": [{"level": "ERROR", "code": "FS001", "message": f"文件不存在: {filepath}"}],
|
||||
}
|
||||
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
text = f.read().replace("\r\n", "\n").replace("\r", "\n")
|
||||
|
||||
lines = text.split("\n")
|
||||
issues: List[ReportIssue] = []
|
||||
|
||||
def add_error(code: str, message: str, line: Optional[int] = None):
|
||||
issues.append(ReportIssue(level="ERROR", code=code, message=message, line=line))
|
||||
|
||||
# 1. 纯净性:严禁 Frontmatter 和 模板草稿占位标记
|
||||
if text.startswith("---\n"):
|
||||
add_error("FM001", "文件以 YAML frontmatter 开头;元数据请放正文开头的「报告信息」表格中", line=1)
|
||||
for pattern, name in FORBIDDEN_MARKS:
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
if pattern.search(l):
|
||||
add_error("MK001", f"出现模板未渲染痕迹({name}),交付文件应为纯 Markdown 文档", line=idx)
|
||||
|
||||
# 2. 代码围栏成对闭合
|
||||
fences = [idx for idx, l in enumerate(lines, start=1) if l.strip().startswith("```")]
|
||||
if len(fences) % 2 != 0:
|
||||
add_error("MD001", f"代码围栏为奇数(共 {len(fences)} 个),存在未闭合代码块", line=fences[-1] if fences else None)
|
||||
|
||||
# 3. 表格结构规范(列对齐、表头无加粗)
|
||||
parsed_tables = parse_tables(lines)
|
||||
for table in parsed_tables:
|
||||
header_len = len(table.header)
|
||||
for row in table.rows:
|
||||
if len(row.cells) != header_len:
|
||||
add_error("TB001", f"第 {row.line_num} 行表格列数 {len(row.cells)} ≠ 表头 {header_len} 列", line=row.line_num)
|
||||
for cell in table.header:
|
||||
if "**" in cell:
|
||||
add_error("TB002", f"第 {table.line_num} 行表头含有加粗标记 **(表头应保持纯文本)", line=table.line_num)
|
||||
|
||||
# 4. 标题层级与章节序号连续性
|
||||
previous_level = 0
|
||||
numbered_h2s: List[Tuple[int, str, int]] = [] # (chapter_num, full_heading, line_num)
|
||||
chapters: List[Dict[str, Any]] = []
|
||||
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
m = re.match(r"^(#{1,6})\s+(.*)$", l)
|
||||
if not m:
|
||||
continue
|
||||
level = len(m.group(1))
|
||||
heading_text = m.group(2).strip()
|
||||
if previous_level > 0 and level > previous_level + 1:
|
||||
add_error("HD001", f"标题层级跳级(从 H{previous_level} 直接跳到 H{level}):{heading_text[:40]}", line=idx)
|
||||
previous_level = level
|
||||
|
||||
if level == 2:
|
||||
num_match = re.match(r"^(\d+)\.", heading_text)
|
||||
if num_match:
|
||||
numbered_h2s.append((int(num_match.group(1)), heading_text, idx))
|
||||
chapters.append({"heading": heading_text, "start_line": idx, "line_num": idx})
|
||||
|
||||
# 检查大标题数字是否严格连续递增:1, 2, 3...
|
||||
if numbered_h2s:
|
||||
seen_nums = [item[0] for item in numbered_h2s]
|
||||
expected_nums = list(range(1, len(seen_nums) + 1))
|
||||
if seen_nums != expected_nums:
|
||||
add_error("HD002", f"## 大章节编号应自 1 开始连续递增,期望 {expected_nums},实际 {seen_nums}", line=numbered_h2s[0][2])
|
||||
|
||||
# 为每个大章节划分文本切片(从当前 ## 到下一个 ##)
|
||||
for i, chap in enumerate(chapters):
|
||||
start_idx = chap["start_line"] - 1
|
||||
end_idx = chapters[i + 1]["start_line"] - 1 if i + 1 < len(chapters) else len(lines)
|
||||
chap["text"] = "\n".join(lines[start_idx:end_idx])
|
||||
|
||||
def find_chapter_by_keyword(kw: str) -> Optional[Dict[str, Any]]:
|
||||
for c in chapters:
|
||||
if kw in c["heading"]:
|
||||
return c
|
||||
return None
|
||||
|
||||
def by_header_in_scope(keyword: str, scope_lines: Optional[List[str]] = None) -> Optional[ParsedTable]:
|
||||
target_tables = parse_tables(scope_lines) if scope_lines is not None else parsed_tables
|
||||
for t in target_tables:
|
||||
header_str = "".join(t.header).replace(" ", "")
|
||||
if keyword in header_str:
|
||||
return t
|
||||
return None
|
||||
|
||||
# 5. 开篇「报告信息」表完备性
|
||||
info_table = by_header_in_scope("报告信息")
|
||||
if not info_table:
|
||||
add_error("INFO001", "缺少开篇「报告信息」表(必须包含客户名称、期间、报告编号等元数据)")
|
||||
else:
|
||||
existing_keys = {r.cells[0] for r in info_table.rows if r.cells}
|
||||
missing_keys = [k for k in REQUIRED_INFO_ROWS if k not in existing_keys]
|
||||
if missing_keys:
|
||||
add_error("INFO001", f"「报告信息」表缺少必要字段:{', '.join(missing_keys)}", line=info_table.line_num)
|
||||
empty_keys = [r.cells[0] for r in info_table.rows if len(r.cells) > 1 and not r.cells[1].strip()]
|
||||
if empty_keys:
|
||||
add_error("INFO002", f"「报告信息」表以下字段值为空:{', '.join(empty_keys)}", line=info_table.line_num)
|
||||
|
||||
# 6. 本地图片资产存活性
|
||||
figure_count = 0
|
||||
for idx, l in enumerate(lines, start=1):
|
||||
for img_match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", l):
|
||||
figure_count += 1
|
||||
src = img_match.group(1).strip()
|
||||
if src.startswith("http://") or src.startswith("https://") or src.startswith("data:"):
|
||||
continue
|
||||
# 解码 URL 编码的中文路径
|
||||
try:
|
||||
import urllib.parse
|
||||
decoded_src = urllib.parse.unquote(src)
|
||||
except Exception:
|
||||
decoded_src = src
|
||||
target_path = (path.parent / decoded_src).resolve()
|
||||
if not target_path.exists():
|
||||
add_error("IMG001", f"本地引用的图片文件不存在:{src}", line=idx)
|
||||
|
||||
# 7. 核心业务章节硬匹配校验与数学总账守恒
|
||||
|
||||
# 7.1 【AI 失准分析】核心章节
|
||||
mismatch_chapter = find_chapter_by_keyword("失准")
|
||||
if mismatch_chapter:
|
||||
c_lines = mismatch_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("失准类型", c_lines)
|
||||
if table:
|
||||
tops = []
|
||||
totals = []
|
||||
for r in table.rows:
|
||||
if len(r.cells) > 3:
|
||||
if r.cells[0].startswith("TOP"):
|
||||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||||
totals.append(extract_numeric(r.cells[3]))
|
||||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||||
if s != totals[0]:
|
||||
add_error("NM001", f"失准类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||||
base = totals[0]
|
||||
for r in table.rows:
|
||||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||||
share = extract_numeric(r.cells[2], is_percent=True)
|
||||
count = extract_numeric(r.cells[3])
|
||||
if share is not None and count is not None and base > 0:
|
||||
calc_share = (count / base) * 100
|
||||
if abs(calc_share - share) > 0.15:
|
||||
add_error("NM003", f"失准类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||||
# 校验小节标题张数与总览表严格一致
|
||||
for top in tops:
|
||||
esc = re.escape(top["name"])
|
||||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", mismatch_chapter["text"])
|
||||
if m and top["count"] is not None:
|
||||
c_in_h = int(m.group(1))
|
||||
if c_in_h != int(top["count"]):
|
||||
add_error("NM001", f"失准分析 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||||
|
||||
# 7.2 【AI 发现的潜在风险】核心章节
|
||||
risk_chapter = find_chapter_by_keyword("风险")
|
||||
if risk_chapter:
|
||||
c_lines = risk_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("风险类型", c_lines)
|
||||
if table:
|
||||
tops = []
|
||||
totals = []
|
||||
for r in table.rows:
|
||||
if len(r.cells) > 3:
|
||||
if r.cells[0].startswith("TOP"):
|
||||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||||
totals.append(extract_numeric(r.cells[3]))
|
||||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||||
if s != totals[0]:
|
||||
add_error("NM002", f"风险类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||||
base = totals[0]
|
||||
for r in table.rows:
|
||||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||||
share = extract_numeric(r.cells[2], is_percent=True)
|
||||
count = extract_numeric(r.cells[3])
|
||||
if share is not None and count is not None and base > 0:
|
||||
calc_share = (count / base) * 100
|
||||
if abs(calc_share - share) > 0.15:
|
||||
add_error("NM003", f"风险类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||||
for top in tops:
|
||||
esc = re.escape(top["name"])
|
||||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", risk_chapter["text"])
|
||||
if m and top["count"] is not None:
|
||||
c_in_h = int(m.group(1))
|
||||
if c_in_h != int(top["count"]):
|
||||
add_error("NM002", f"潜在风险 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||||
|
||||
# 7.3 【审核分歧与复核归因】核心章节
|
||||
diverged_chapter = find_chapter_by_keyword("分歧") or find_chapter_by_keyword("复核归因")
|
||||
if diverged_chapter:
|
||||
c_lines = diverged_chapter["text"].split("\n")
|
||||
table = by_header_in_scope("原因分类", c_lines)
|
||||
if table:
|
||||
count_idx = -1
|
||||
for ci, col in enumerate(table.header):
|
||||
if "单数" in col:
|
||||
count_idx = ci
|
||||
break
|
||||
if count_idx >= 0:
|
||||
rows = [r.cells for r in table.rows]
|
||||
non_totals = [r for r in rows if r and r[0] not in ["合计", "总计", "—"]]
|
||||
total_row = next((r for r in rows if r and r[0] in ["合计", "总计", "—"]), None)
|
||||
s = sum(extract_numeric(r[count_idx]) or 0 for r in non_totals if len(r) > count_idx)
|
||||
if total_row and len(total_row) > count_idx:
|
||||
tv = extract_numeric(total_row[count_idx])
|
||||
if tv is not None and s != tv:
|
||||
add_error("NM004", f"原因分类各维度单数之和 {s} ≠ 合计 {tv}", line=table.line_num)
|
||||
|
||||
# 7.4 LaTeX 公式算术自洽
|
||||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
||||
outside_text = "\n".join([l for l in lines if not l.strip().startswith("$$")])
|
||||
for fl in formula_lines:
|
||||
for frac_match in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", fl):
|
||||
a = int(frac_match.group(1))
|
||||
b = int(frac_match.group(2))
|
||||
pct_val = float(frac_match.group(3))
|
||||
if b > 0:
|
||||
real_pct = (a / b) * 100
|
||||
if abs(real_pct - pct_val) > 0.05:
|
||||
add_error("NM005", f"公式 \\frac{{{a}}}{{{b}}} = {pct_val}% 算术不成立(实为 {real_pct:.2f}%)")
|
||||
for num_token in re.findall(r"\d+(?:\.\d+)?", fl):
|
||||
if num_token not in outside_text:
|
||||
add_error("NM005", f"公式中的数值 {num_token} 在正文别处找不到,可能与实际数据脱节")
|
||||
|
||||
return {
|
||||
"file": str(path),
|
||||
"valid": len(issues) == 0,
|
||||
"tables": len(parsed_tables),
|
||||
"figures": figure_count,
|
||||
"issues": [i.to_dict() for i in issues],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2 or sys.argv[1] in ["-h", "--help"]:
|
||||
print("用法: python3 validate.py <report.md> [--json]")
|
||||
print("说明: 离线静态校验 AI 审核报告 Markdown 文档的结构纯净度与数学总账守恒。")
|
||||
sys.exit(0)
|
||||
|
||||
target_file = sys.argv[1]
|
||||
is_json = "--json" in sys.argv
|
||||
|
||||
result = validate_report(target_file)
|
||||
|
||||
if is_json:
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
else:
|
||||
status_symbol = "✅" if result["valid"] else "❌"
|
||||
print(f"\n{status_symbol} 报告文件: {result['file']}")
|
||||
print(f"📊 识别表格: {result['tables']} 个 | 配图资产: {result['figures']} 个")
|
||||
|
||||
if result["valid"]:
|
||||
print("🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。\n")
|
||||
sys.exit(0)
|
||||
else:
|
||||
print(f"⚠️ 发现 {len(result['issues'])} 项格式或勾稽问题,必须修正后方可交付:\n")
|
||||
for i, issue in enumerate(result["issues"], 1):
|
||||
loc = f" [第 {issue['line']} 行]" if "line" in issue else ""
|
||||
print(f" {i}. [{issue['code']}]{loc} {issue['message']}")
|
||||
print("\n💡 提示:请根据上述提示调整对应行的数字或表格结构,直至校验通过。\n")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,7 +2,7 @@ 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";
|
||||
import { resolveTargetBinaryPath } from "./dev-override.js";
|
||||
|
||||
describe("development CLI install target", () => {
|
||||
test("npm-linked source is never selected as the binary replacement target", () => {
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { HELP_REGISTRY } from "../src/cli/help.ts";
|
||||
import { HELP_REGISTRY } from "../src/cli/help/help.ts";
|
||||
|
||||
export const cliDocPath = resolve(import.meta.dirname, "../skills/seal-use/references/cli.md");
|
||||
const begin = "<!-- BEGIN GENERATED CLI COMMANDS -->";
|
||||
|
||||
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const skillRoot = resolve(root, "skills", "seal-use");
|
||||
export const embeddedSkillOutput = resolve(root, "src", "core", "embedded-skill.generated.ts");
|
||||
export const embeddedSkillOutput = resolve(root, "src", "core", "skill", "embedded-skill.generated.ts");
|
||||
const textExtensions = new Set([".md", ".yaml", ".yml", ".json", ".txt"]);
|
||||
|
||||
function walk(dir) {
|
||||
@@ -20,7 +20,7 @@ function walk(dir) {
|
||||
return files;
|
||||
}
|
||||
|
||||
export function renderEmbeddedSkill(sourceDir = skillRoot, coreDir = resolve(root, "src", "core")) {
|
||||
export function renderEmbeddedSkill(sourceDir = skillRoot, coreDir = resolve(root, "src", "core", "skill")) {
|
||||
const files = walk(sourceDir).map((fullPath) => ({
|
||||
relativePath: relative(sourceDir, fullPath).split("\\").join("/"),
|
||||
importPath: relative(coreDir, fullPath).split("\\").join("/"),
|
||||
|
||||
@@ -50,15 +50,17 @@ describe("generated documentation contracts", () => {
|
||||
tempDirs.push(dir)
|
||||
const scripts = join(dir, "scripts")
|
||||
const core = join(dir, "src/core")
|
||||
const coreSkill = join(core, "skill")
|
||||
const cli = join(dir, "src/cli")
|
||||
const cliHelp = join(cli, "help")
|
||||
const skill = join(dir, "skills/seal-use")
|
||||
for (const path of [scripts, core, cli, join(skill, "references")]) mkdirSync(path, { recursive: true })
|
||||
for (const path of [scripts, core, coreSkill, cli, cliHelp, join(skill, "references")]) mkdirSync(path, { recursive: true })
|
||||
for (const name of ["generate-embedded-skill.mjs", "check-embedded-skill.mjs", "generate-cli-md.mjs", "check-cli-md.mjs"]) {
|
||||
copyFileSync(join(import.meta.dir, name), join(scripts, name))
|
||||
}
|
||||
writeFileSync(join(cli, "help.ts"), 'export const HELP_REGISTRY = [{ commands: [{ usage: ["seal-use fixture list"] }] }];')
|
||||
writeFileSync(join(cliHelp, "help.ts"), 'export const HELP_REGISTRY = [{ commands: [{ usage: ["seal-use fixture list"] }] }];')
|
||||
writeFileSync(join(skill, "SKILL.md"), "fixture skill")
|
||||
const embeddedPath = join(core, "embedded-skill.generated.ts")
|
||||
const embeddedPath = join(coreSkill, "embedded-skill.generated.ts")
|
||||
const markdownPath = join(skill, "references/cli.md")
|
||||
writeFileSync(embeddedPath, "stale embedded fixture")
|
||||
const markdown = renderCliCommandBlock().replace("seal-use version", "seal-use stale-command")
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import {
|
||||
checkReadmeNaming,
|
||||
expectedReadmeName,
|
||||
isReadmeLike,
|
||||
validateReadmePaths
|
||||
} from "./check-readme-naming.js"
|
||||
|
||||
describe("isReadmeLike", () => {
|
||||
test("matches README variants", () => {
|
||||
for (const name of ["README.md", "readme.md", "README.txt", "src.readme.md"]) {
|
||||
expect(isReadmeLike(name)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
test("ignores unrelated files", () => {
|
||||
for (const name of ["index.md", "readme-assets.ts", "README_GUIDE.md"]) {
|
||||
expect(isReadmeLike(name)).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("expectedReadmeName", () => {
|
||||
test("prefixes with the directory name", () => {
|
||||
expect(expectedReadmeName("src")).toBe("src.readme.md")
|
||||
expect(expectedReadmeName("host-infra")).toBe("host-infra.readme.md")
|
||||
})
|
||||
|
||||
test("strips leading dots from dot-directories", () => {
|
||||
expect(expectedReadmeName(".agents")).toBe("agents.readme.md")
|
||||
})
|
||||
})
|
||||
|
||||
describe("validateReadmePaths", () => {
|
||||
test("accepts the conventional layout", () => {
|
||||
const issues = validateReadmePaths([
|
||||
"README.md",
|
||||
"src/src.readme.md",
|
||||
".agents/agents.readme.md",
|
||||
"host-infra/host-infra.readme.md",
|
||||
"src/domains/seal/reports/reports.readme.md"
|
||||
])
|
||||
expect(issues).toEqual([])
|
||||
})
|
||||
|
||||
test("rejects a plain README.md in a subdirectory", () => {
|
||||
const issues = validateReadmePaths(["README.md", "src/README.md"])
|
||||
expect(issues).toHaveLength(1)
|
||||
expect(issues[0].file).toBe("src/README.md")
|
||||
expect(issues[0].rule).toBe("subdir-readme-name")
|
||||
})
|
||||
|
||||
test("rejects a subdirectory README with the wrong prefix", () => {
|
||||
const issues = validateReadmePaths(["README.md", "src/docs.readme.md"])
|
||||
expect(issues).toHaveLength(1)
|
||||
expect(issues[0].rule).toBe("subdir-readme-name")
|
||||
expect(issues[0].message).toContain("src.readme.md")
|
||||
})
|
||||
|
||||
test("rejects a lowercase root readme", () => {
|
||||
const issues = validateReadmePaths(["readme.md"])
|
||||
expect(issues.some((issue) => issue.rule === "root-readme-name")).toBe(true)
|
||||
expect(issues.some((issue) => issue.rule === "missing-root-readme")).toBe(true)
|
||||
})
|
||||
|
||||
test("requires a root README", () => {
|
||||
const issues = validateReadmePaths(["src/src.readme.md"])
|
||||
expect(issues.some((issue) => issue.rule === "missing-root-readme")).toBe(true)
|
||||
})
|
||||
|
||||
test("accepts nested directories with matching prefixes", () => {
|
||||
const issues = validateReadmePaths([
|
||||
"README.md",
|
||||
"src/domains/seal/reports/reports.readme.md",
|
||||
"src/domains/seal/reports/templates/templates.readme.md"
|
||||
])
|
||||
expect(issues).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe("checkReadmeNaming", () => {
|
||||
test("skips the local root reports directory but checks nested ones", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "readme-naming-"))
|
||||
try {
|
||||
writeFileSync(join(root, "README.md"), "# Root")
|
||||
mkdirSync(join(root, "reports"))
|
||||
writeFileSync(join(root, "reports", "README.md"), "# Local-only")
|
||||
mkdirSync(join(root, "src"))
|
||||
writeFileSync(join(root, "src", "README.md"), "# Wrong")
|
||||
|
||||
const issues = checkReadmeNaming(root)
|
||||
expect(issues).toHaveLength(1)
|
||||
expect(issues[0].file).toBe("src/README.md")
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("the committed repository passes the naming rule", () => {
|
||||
const root = join(import.meta.dirname, "../..")
|
||||
expect(checkReadmeNaming(root)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Governance check for README naming.
|
||||
*
|
||||
* Rule: the repository root keeps the conventional `README.md`; every
|
||||
* subdirectory README must carry its directory name as a prefix, e.g.
|
||||
* `src/src.readme.md`, `.agents/agents.readme.md` (leading dots are stripped
|
||||
* so the file stays visible).
|
||||
*
|
||||
* Invoked as `bun run verify:readme-naming` (CI + pre-commit) and with
|
||||
* `--soft` from the ZCode SessionStart hook.
|
||||
*/
|
||||
import { readdirSync } from "node:fs"
|
||||
import { join, relative, sep } from "node:path"
|
||||
|
||||
export const ROOT_README = "README.md"
|
||||
|
||||
/** Directories whose contents are generated, vendored, or local-only. */
|
||||
export const SKIP_DIRS: ReadonlySet<string> = new Set([
|
||||
"node_modules",
|
||||
".git",
|
||||
"dist",
|
||||
"build",
|
||||
"coverage",
|
||||
".cache",
|
||||
"tmp",
|
||||
".local",
|
||||
".drafts",
|
||||
".workbuddy",
|
||||
".mimosa",
|
||||
".apifox"
|
||||
])
|
||||
|
||||
/**
|
||||
* Only the repository-root copy is local-only; a nested `reports/` directory
|
||||
* (e.g. `src/domains/seal/reports/`) is tracked and must still be checked.
|
||||
*/
|
||||
export const ROOT_ONLY_SKIP_DIRS: ReadonlySet<string> = new Set(["reports"])
|
||||
|
||||
export type ReadmeNamingIssue = {
|
||||
file: string
|
||||
rule: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/** `README.md`, `readme.txt`, `src.readme.md` — any file named like a README. */
|
||||
export function isReadmeLike(name: string): boolean {
|
||||
const lower = name.toLowerCase()
|
||||
return lower === "readme" || lower.startsWith("readme.") || lower.endsWith(".readme.md")
|
||||
}
|
||||
|
||||
/** Directory name → required README prefix, stripping leading dots. */
|
||||
export function expectedReadmeName(dirName: string): string {
|
||||
const prefix = dirName.replace(/^\.+/, "") || dirName
|
||||
return `${prefix}.readme.md`
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure validation over repo-relative paths so tests do not need a temp tree.
|
||||
*/
|
||||
export function validateReadmePaths(paths: readonly string[]): ReadmeNamingIssue[] {
|
||||
const issues: ReadmeNamingIssue[] = []
|
||||
const normalized = paths.map((path) => path.split(sep).join("/"))
|
||||
|
||||
if (!normalized.includes(ROOT_README)) {
|
||||
issues.push({
|
||||
file: ROOT_README,
|
||||
rule: "missing-root-readme",
|
||||
message: "repository root must keep README.md"
|
||||
})
|
||||
}
|
||||
|
||||
for (const path of normalized) {
|
||||
const parts = path.split("/")
|
||||
const name = parts.pop() ?? ""
|
||||
if (!isReadmeLike(name)) continue
|
||||
|
||||
if (parts.length === 0) {
|
||||
if (name !== ROOT_README) {
|
||||
issues.push({
|
||||
file: path,
|
||||
rule: "root-readme-name",
|
||||
message: `root README must be named ${ROOT_README}, found ${name}`
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const dirName = parts[parts.length - 1]
|
||||
const expected = expectedReadmeName(dirName)
|
||||
if (name !== expected) {
|
||||
issues.push({
|
||||
file: path,
|
||||
rule: "subdir-readme-name",
|
||||
message: `subdirectory README must be named ${expected} (directory "${dirName}"), found ${name}`
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return issues
|
||||
}
|
||||
|
||||
function collectFiles(rootDir: string, dir = rootDir, files: string[] = []): string[] {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.isDirectory()) {
|
||||
if (SKIP_DIRS.has(entry.name)) continue
|
||||
const relDir = relative(rootDir, join(dir, entry.name)).split(sep).join("/")
|
||||
if (ROOT_ONLY_SKIP_DIRS.has(entry.name) && relDir === entry.name) continue
|
||||
collectFiles(rootDir, join(dir, entry.name), files)
|
||||
} else if (entry.isFile()) {
|
||||
files.push(relative(rootDir, join(dir, entry.name)).split(sep).join("/"))
|
||||
}
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
export function checkReadmeNaming(rootDir: string): ReadmeNamingIssue[] {
|
||||
return validateReadmePaths(collectFiles(rootDir))
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const root = join(import.meta.dirname, "../..")
|
||||
const issues = checkReadmeNaming(root)
|
||||
|
||||
if (process.argv.includes("--soft")) {
|
||||
if (issues.length > 0) {
|
||||
const summary = issues.map((issue) => issue.message).join("; ")
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
additionalContext: `README 命名检查发现 ${issues.length} 项问题:${summary}。本地运行 bun run verify:readme-naming 查看详情。`
|
||||
})
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (issues.length > 0) {
|
||||
for (const issue of issues) {
|
||||
console.error(`✗ ${issue.file}: ${issue.message} [${issue.rule}]`)
|
||||
}
|
||||
console.error(`README naming checks failed (${issues.length} issue(s)).`)
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
|
||||
console.log("README naming checks passed.")
|
||||
}
|
||||
|
||||
if (import.meta.main) main()
|
||||
@@ -0,0 +1,310 @@
|
||||
# scripts/install.ps1 - Native Windows PowerShell installer for seal-use CLI.
|
||||
# Usage:
|
||||
# irm https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.ps1 | iex
|
||||
# Or with parameters:
|
||||
# & ([scriptblock]::Create((irm ...))) -Version 0.11.22
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$Version = "",
|
||||
[string]$InstallDir = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
# Enable modern TLS protocols on older PowerShell 5.1 hosts
|
||||
try {
|
||||
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
|
||||
} catch {
|
||||
# Ignore if TLS12 is already default or unsupported
|
||||
}
|
||||
|
||||
Write-Host "==> Detecting Windows platform and architecture..." -ForegroundColor Cyan
|
||||
|
||||
if (-not [System.Environment]::Is64BitOperatingSystem) {
|
||||
Write-Error "seal-use requires a 64-bit Windows operating system (x64)."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$ARCH_NAME = "x64"
|
||||
$PLATFORM = "windows"
|
||||
$REPO = if ($env:SEAL_USE_GITHUB_REPO) { $env:SEAL_USE_GITHUB_REPO }
|
||||
elseif ($env:SEAL_HOME_GITHUB_REPO) { $env:SEAL_HOME_GITHUB_REPO }
|
||||
else { "yunyingk/seal-use" }
|
||||
|
||||
$REQ_VERSION = if ($Version) { $Version }
|
||||
elseif ($env:SEAL_USE_VERSION) { $env:SEAL_USE_VERSION }
|
||||
elseif ($env:SEAL_HOME_VERSION) { $env:SEAL_HOME_VERSION }
|
||||
else { "latest" }
|
||||
|
||||
if ($REQ_VERSION -ne "latest" -and -not $REQ_VERSION.StartsWith("v")) {
|
||||
$REQ_VERSION = "v$REQ_VERSION"
|
||||
}
|
||||
|
||||
# Resolve target directory without requiring administrator privileges
|
||||
$TARGET_DIR = if ($InstallDir) { $InstallDir }
|
||||
elseif ($env:SEAL_USE_INSTALL_DIR) { $env:SEAL_USE_INSTALL_DIR }
|
||||
elseif ($env:SEAL_HOME_INSTALL_DIR) { $env:SEAL_HOME_INSTALL_DIR }
|
||||
else { "" }
|
||||
|
||||
if (-not $TARGET_DIR) {
|
||||
$existing = Get-Command "seal-use" -ErrorAction SilentlyContinue
|
||||
if ($existing -and $existing.Source -and (Test-Path $existing.Source)) {
|
||||
$existingDir = Split-Path -Parent $existing.Source
|
||||
if ($existingDir -notlike "*WindowsApps*" -and (Test-Path $existingDir)) {
|
||||
$TARGET_DIR = $existingDir
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $TARGET_DIR) {
|
||||
$TARGET_DIR = Join-Path $HOME ".local\bin"
|
||||
}
|
||||
|
||||
if (-not (Test-Path $TARGET_DIR)) {
|
||||
New-Item -ItemType Directory -Path $TARGET_DIR -Force | Out-Null
|
||||
}
|
||||
|
||||
$ASSET_NAME = "seal-use-$PLATFORM-$ARCH_NAME.exe"
|
||||
$ARCHIVE_NAME = "seal-use-$PLATFORM-$ARCH_NAME.zip"
|
||||
$TARGET_PATH = Join-Path $TARGET_DIR "seal-use.exe"
|
||||
|
||||
function Format-Bytes([long]$bytes) {
|
||||
if ($bytes -ge 1048576) {
|
||||
return ("{0:N2} MB ({1:N0} bytes)" -f ($bytes / 1MB), $bytes)
|
||||
} elseif ($bytes -ge 1024) {
|
||||
return ("{0:N2} KB ({1:N0} bytes)" -f ($bytes / 1KB), $bytes)
|
||||
} else {
|
||||
return ("{0} bytes" -f $bytes)
|
||||
}
|
||||
}
|
||||
|
||||
function Extract-Host([string]$url) {
|
||||
try {
|
||||
$uri = [System.Uri]$url
|
||||
return $uri.Host
|
||||
} catch {
|
||||
return $url
|
||||
}
|
||||
}
|
||||
|
||||
$GITEA_TAG = if ($REQ_VERSION -eq "latest") { "latest" } else { $REQ_VERSION }
|
||||
$GH_RELEASE_PATH = if ($REQ_VERSION -eq "latest") { "latest/download" } else { $REQ_VERSION }
|
||||
|
||||
$MIRROR_MODE = if ($env:SEAL_USE_MIRROR) { $env:SEAL_USE_MIRROR }
|
||||
elseif ($env:SEAL_HOME_MIRROR) { $env:SEAL_HOME_MIRROR }
|
||||
else { "auto" }
|
||||
|
||||
function Get-CandidateUrls([string]$asset) {
|
||||
$urls = [System.Collections.Generic.List[string]]::new()
|
||||
if ($MIRROR_MODE -ne "github") {
|
||||
$urls.Add("https://git.ying-qing.cn/gitea/seal-use/releases/download/$GITEA_TAG/$asset")
|
||||
$urls.Add("https://git.ying-qing.cn/gitea/seal-home/releases/download/$GITEA_TAG/$asset")
|
||||
}
|
||||
if ($MIRROR_MODE -ne "gitea") {
|
||||
$urls.Add("https://github.com/$REPO/releases/download/$GH_RELEASE_PATH/$asset")
|
||||
$urls.Add("https://ghfast.top/https://github.com/$REPO/releases/download/$GH_RELEASE_PATH/$asset")
|
||||
}
|
||||
return $urls
|
||||
}
|
||||
|
||||
function Download-Candidate([string]$url, [string]$dest) {
|
||||
$hostName = Extract-Host $url
|
||||
Write-Host "==> Downloading from $hostName" -ForegroundColor Cyan
|
||||
Write-Host " Source Host: $hostName"
|
||||
Write-Host " Source URL: $url"
|
||||
|
||||
try {
|
||||
# Test headers and download using Invoke-WebRequest with basic parsing
|
||||
Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing -TimeoutSec 45 -ErrorAction Stop
|
||||
if (Test-Path $dest) {
|
||||
$item = Get-Item $dest
|
||||
if ($item.Length -gt 1000000) {
|
||||
Write-Host "✓ Download complete! Total size: $(Format-Bytes $item.Length)" -ForegroundColor Green
|
||||
Write-Host "✓ Successfully fetched from host: $hostName" -ForegroundColor Green
|
||||
return $true
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Write-Host " ↳ Source unreachable or asset not ready ($($_.Exception.Message)), falling back to next mirror..." -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
if (Test-Path $dest) {
|
||||
Remove-Item -Path $dest -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
function Verify-Checksum([string]$filePath, [string]$assetName) {
|
||||
$checksumUrls = [System.Collections.Generic.List[string]]::new()
|
||||
if ($MIRROR_MODE -ne "github") {
|
||||
$checksumUrls.Add("https://git.ying-qing.cn/gitea/seal-use/releases/download/$GITEA_TAG/checksums.txt")
|
||||
$checksumUrls.Add("https://git.ying-qing.cn/gitea/seal-home/releases/download/$GITEA_TAG/checksums.txt")
|
||||
}
|
||||
if ($MIRROR_MODE -ne "gitea") {
|
||||
$checksumUrls.Add("https://github.com/$REPO/releases/download/$GH_RELEASE_PATH/checksums.txt")
|
||||
$checksumUrls.Add("https://ghfast.top/https://github.com/$REPO/releases/download/$GH_RELEASE_PATH/checksums.txt")
|
||||
}
|
||||
|
||||
$tmpSum = [System.IO.Path]::GetTempFileName()
|
||||
$checksumFound = $false
|
||||
|
||||
foreach ($cUrl in $checksumUrls) {
|
||||
try {
|
||||
Invoke-WebRequest -Uri $cUrl -OutFile $tmpSum -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop
|
||||
if (Test-Path $tmpSum) {
|
||||
$checksumFound = $true
|
||||
break
|
||||
}
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if ($checksumFound) {
|
||||
try {
|
||||
$lines = Get-Content -Path $tmpSum -ErrorAction SilentlyContinue
|
||||
$expectedHash = ""
|
||||
foreach ($line in $lines) {
|
||||
$parts = -split $line.Trim()
|
||||
if ($parts.Length -ge 2 -and $parts[1] -eq $assetName) {
|
||||
$expectedHash = $parts[0]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($expectedHash) {
|
||||
$actualHash = (Get-FileHash -Path $filePath -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
if ($actualHash -eq $expectedHash.ToLowerInvariant()) {
|
||||
Write-Host "✓ Checksum verification passed (SHA-256: $($actualHash.Substring(0, 12))...)" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Warning "Checksum mismatch for $assetName! Expected: $expectedHash, got: $actualHash"
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
Remove-Item -Path $tmpSum -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "==> Target install location: $TARGET_PATH"
|
||||
Write-Host "==> Requested version: $REQ_VERSION"
|
||||
|
||||
$TMP_ZIP = Join-Path ([System.IO.Path]::GetTempPath()) ("seal-use-download-" + [System.Guid]::NewGuid().ToString("N") + ".zip")
|
||||
$TMP_EXE = Join-Path ([System.IO.Path]::GetTempPath()) ("seal-use-download-" + [System.Guid]::NewGuid().ToString("N") + ".exe")
|
||||
$TMP_FILE = ""
|
||||
$DOWNLOAD_SUCCESS = $false
|
||||
$IS_ARCHIVE = $false
|
||||
$USED_ASSET = ""
|
||||
|
||||
# Prefer compressed archive (zip) over raw binary: smaller download (~44MB vs ~107MB)
|
||||
foreach ($url in (Get-CandidateUrls $ARCHIVE_NAME)) {
|
||||
if (Download-Candidate -url $url -dest $TMP_ZIP) {
|
||||
$DOWNLOAD_SUCCESS = $true
|
||||
$IS_ARCHIVE = $true
|
||||
$USED_ASSET = $ARCHIVE_NAME
|
||||
$TMP_FILE = $TMP_ZIP
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $DOWNLOAD_SUCCESS) {
|
||||
foreach ($url in (Get-CandidateUrls $ASSET_NAME)) {
|
||||
if (Download-Candidate -url $url -dest $TMP_EXE) {
|
||||
$DOWNLOAD_SUCCESS = $true
|
||||
$IS_ARCHIVE = $false
|
||||
$USED_ASSET = $ASSET_NAME
|
||||
$TMP_FILE = $TMP_EXE
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $DOWNLOAD_SUCCESS) {
|
||||
Write-Error "Failed to download $ARCHIVE_NAME or $ASSET_NAME ($REQ_VERSION) from all candidate mirrors."
|
||||
if (Test-Path $TMP_FILE) { Remove-Item -Path $TMP_FILE -Force -ErrorAction SilentlyContinue }
|
||||
exit 1
|
||||
}
|
||||
|
||||
Verify-Checksum -filePath $TMP_FILE -assetName $USED_ASSET
|
||||
|
||||
if ($IS_ARCHIVE) {
|
||||
$EXTRACT_DIR = Join-Path ([System.IO.Path]::GetTempPath()) ("seal-use-extract-" + [System.Guid]::NewGuid().ToString("N"))
|
||||
Write-Host "==> Extracting $USED_ASSET..." -ForegroundColor Cyan
|
||||
try {
|
||||
Expand-Archive -Path $TMP_FILE -DestinationPath $EXTRACT_DIR -Force
|
||||
$extractedExe = Get-ChildItem -Path $EXTRACT_DIR -Filter "*seal-use*.exe" -Recurse | Select-Object -First 1
|
||||
if (-not $extractedExe) {
|
||||
Write-Error "$USED_ASSET did not contain a seal-use binary."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Handle locked running binary by moving old image first
|
||||
if (Test-Path $TARGET_PATH) {
|
||||
$oldPath = "$TARGET_PATH.old.$([DateTimeOffset]::UtcNow.ToUnixTimeSeconds())"
|
||||
try {
|
||||
Move-Item -Path $TARGET_PATH -Destination $oldPath -Force -ErrorAction SilentlyContinue
|
||||
} catch {
|
||||
# Ignore if file is not locked
|
||||
}
|
||||
}
|
||||
|
||||
Move-Item -Path $extractedExe.FullName -Destination $TARGET_PATH -Force
|
||||
} finally {
|
||||
Remove-Item -Path $EXTRACT_DIR -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item -Path $TMP_FILE -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
} else {
|
||||
if (Test-Path $TARGET_PATH) {
|
||||
$oldPath = "$TARGET_PATH.old.$([DateTimeOffset]::UtcNow.ToUnixTimeSeconds())"
|
||||
try {
|
||||
Move-Item -Path $TARGET_PATH -Destination $oldPath -Force -ErrorAction SilentlyContinue
|
||||
} catch {}
|
||||
}
|
||||
Move-Item -Path $TMP_FILE -Destination $TARGET_PATH -Force
|
||||
}
|
||||
|
||||
# Ensure TARGET_DIR is in Windows User PATH environment variable
|
||||
try {
|
||||
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
|
||||
$paths = ($userPath -split ';') | Where-Object { $_ -and $_.Trim() -ne "" }
|
||||
if ($paths -notcontains $TARGET_DIR) {
|
||||
$newUserPath = if ([string]::IsNullOrEmpty($userPath)) { $TARGET_DIR } else { "$userPath;$TARGET_DIR" }
|
||||
[Environment]::SetEnvironmentVariable("Path", $newUserPath, "User")
|
||||
Write-Host "==> Added $TARGET_DIR to User PATH environment variable." -ForegroundColor Cyan
|
||||
}
|
||||
} catch {
|
||||
Write-Warning "Could not update User PATH environment variable automatically. Please add $TARGET_DIR to your PATH manually."
|
||||
}
|
||||
|
||||
# Update current session environment PATH
|
||||
$sessionPaths = ($env:Path -split ';') | Where-Object { $_ -and $_.Trim() -ne "" }
|
||||
if ($sessionPaths -notcontains $TARGET_DIR) {
|
||||
$env:Path = "$TARGET_DIR;$env:Path"
|
||||
}
|
||||
|
||||
# Clean legacy skill to avoid model routing collisions
|
||||
$LEGACY_SKILL_DIR = Join-Path $HOME ".agents\skills\seal-home"
|
||||
if (Test-Path $LEGACY_SKILL_DIR) {
|
||||
Write-Host "==> Removing legacy agent skill at $LEGACY_SKILL_DIR..." -ForegroundColor Cyan
|
||||
Remove-Item -Path $LEGACY_SKILL_DIR -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
# Initialize agent skill
|
||||
Write-Host "==> Initializing agent skill to ~/.agents/skills/seal-use..." -ForegroundColor Cyan
|
||||
try {
|
||||
& $TARGET_PATH skill install 2>$null | Out-Null
|
||||
Write-Host "✓ Agent skill installed to ~/.agents/skills/seal-use" -ForegroundColor Green
|
||||
} catch {
|
||||
Write-Warning "Could not initialize agent skill automatically. Run 'seal-use skill install' to complete."
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "✨ seal-use successfully installed to $TARGET_PATH!" -ForegroundColor Green
|
||||
& $TARGET_PATH version
|
||||
Write-Host ""
|
||||
Write-Host "Quick start:"
|
||||
Write-Host " 1. Add enterprise: seal-use corps add-hose-persistent --json '{...}'"
|
||||
Write-Host " 2. View MCP config: seal-use mcp-config"
|
||||
Write-Host " 3. Self-update: seal-use update"
|
||||
Write-Host ""
|
||||
@@ -13,6 +13,7 @@ scripts/
|
||||
│ ├── check-agents-md.ts # AGENTS.md 开发者契约校验器
|
||||
│ ├── check-skill-md.ts # SKILL.md 路由中枢与 references 双向路由校验器
|
||||
│ ├── check-readme.ts # README.md 结构与卫生巡检器(警告级别)
|
||||
│ ├── check-readme-naming.ts # 子目录 README 命名规范校验器(目录名前缀)
|
||||
│ ├── doc-md-common.ts # 共享 fence 感知 Markdown 解析纯函数库
|
||||
│ └── *.test.ts # 逻辑 fixture 与真实文档现状双覆盖测试
|
||||
│
|
||||
@@ -20,7 +21,8 @@ scripts/
|
||||
├── bump-version.ts # 多清单版本原子同步(package.json / plugin.json / SKILL.md 等)
|
||||
├── release.ts # 受控保护分支发布流水线(严格遵循 merge-before-tag)
|
||||
├── dev-override.ts # 本地开发二进制编译与全局 PATH 覆盖测试
|
||||
├── install.sh # 生产级免 sudo 快速安装 Shell 脚本(公开 cURL 入口,不可移动)
|
||||
├── install.sh # 生产级免 sudo 快速安装 Shell 脚本(macOS / Linux 公开 cURL 入口,不可移动)
|
||||
├── install.ps1 # 生产级免管理员提权快速安装 PowerShell 脚本(Windows 原生公开 irm 入口)
|
||||
│
|
||||
├── generate-cli-md.mjs # 从 CLI 注册表自动生成 references/cli.md
|
||||
├── check-cli-md.mjs # CLI 文档防漂移校验
|
||||
@@ -36,6 +38,6 @@ scripts/
|
||||
1. **绝对隔离**:`src/` 业务代码不可依赖 `scripts/`。`scripts/` 是外部工具,不是领域服务。
|
||||
2. **高危受限脚本**:
|
||||
- `release.ts` 与 `bump-version.ts` 具有强版本与 Git 标签推进副作用,**必须且仅能在人类明确发出发布指令时**通过 `bun run release` 调度,任何 Agent 不得擅自调用。
|
||||
- `install.sh` 是被公开文档直接通过 `curl .../scripts/install.sh | bash` 引用的外部入口,路径不可擅改。
|
||||
- `install.sh` 与 `install.ps1` 是被公开文档直接通过 `curl .../install.sh | bash` 与 `irm .../install.ps1 | iex` 引用的外部安装入口,路径不可擅改。
|
||||
3. **治理优先**:
|
||||
- 日常执行 `bun test` 会自动回归 `scripts/governance/*.test.ts`,确保治理规则与真实文件不漂移。
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: seal-use
|
||||
description: "v0.11.19: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
description: "v0.11.23: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
|
||||
metadata:
|
||||
version: 0.11.19
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.19)
|
||||
version: 0.11.23
|
||||
short-description: Seal tenant and Hose approval automation (v0.11.23)
|
||||
---
|
||||
|
||||
# Seal Use
|
||||
@@ -15,8 +15,10 @@ CLI 是主执行通道。运行 `seal-use help` 获取完整命令清单,使
|
||||
在执行具体业务前,先通过 `command -v seal-use` 检查 CLI 是否已就绪。若命令未安装或需要升级:
|
||||
|
||||
### 1. 一键免环境安装(推荐)
|
||||
独立预编译原生二进制分发,无需 Node.js 或 Bun 运行环境,自动识别系统架构(macOS Apple Silicon/Intel、Linux x64/arm64):
|
||||
独立预编译原生二进制分发,无需 Node.js 或 Bun 运行环境,自动识别系统架构(macOS、Linux、Windows x64):
|
||||
|
||||
```bash
|
||||
# macOS & Linux (Bash)
|
||||
# 国内高速镜像(免代理推荐,秒级完成)
|
||||
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
|
||||
|
||||
@@ -24,6 +26,15 @@ curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/insta
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
```powershell
|
||||
# Windows (PowerShell)
|
||||
# 国内高速镜像(免代理推荐,秒级完成)
|
||||
irm https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.ps1 | iex
|
||||
|
||||
# GitHub 直连
|
||||
irm https://raw.githubusercontent.com/yunyingk/seal-use/main/scripts/install.ps1 | iex
|
||||
```
|
||||
|
||||
### 2. 下载预编译原生二进制
|
||||
亦可从 Releases 页面直接下载对应平台可执行文件并放入 PATH:
|
||||
- **Gitea Releases(国内高速)**:`https://git.ying-qing.cn/gitea/seal-use/releases`
|
||||
@@ -84,13 +95,15 @@ bun run dev:override # 编译本机二进制、打版本号并原子覆盖
|
||||
2. 读取 `references/first-time-user.md`,只渲染与当前路径对应的截图;不能只给纯文字步骤。
|
||||
3. 接收材料后由 Agent 自动发现企业、域名和管理员。除非自动发现失败,不要要求用户先填写 `corpId`、`staffId` 或域名。
|
||||
|
||||
## `corps` 主线
|
||||
## `corps` 主线与规则演进
|
||||
|
||||
企业接入、发现、维护与测试配对的具体语法见 `seal-use help corps`;材料选择与操作流程按下方 reference 路由。
|
||||
|
||||
Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`approval-runs hose-flow`、`deploy hosecloud`、`simulation --mode hosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--type hose-document` 时才启用对应 Hose 能力。
|
||||
|
||||
生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
|
||||
规则变更与验证闭环:
|
||||
- **单租户快照测试(首选,无需双企业组)**:`simulation create` 原生支持 `ruleSource`(默认以当前线上生效规则运行;加 `--draft` 显式对未发布草稿拍摄不可变快照;`--rule-version` 挂载指定历史版本),单个企业租户内执行 `seal-use simulation create --corp <corpId> --flow-ids <SN> --draft --wait` 即可原地完成草稿快照测试,不再需要双企业组与 `sync-test` 预发版造快照。
|
||||
- **双租户物理隔离(可选)**:仅在需严格物理隔离外部审批流出站、跨租户出站仿真重放或执行全量自动化回归矩阵(`test regression` 阻断生产环境)时,才使用 `corps bind-test` 与 `corps sync-test`。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
|
||||
|
||||
## 规则编号重排:两次调用
|
||||
|
||||
@@ -155,6 +168,7 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
|
||||
| 导出审核记录 Excel、额外人工审批流、高级筛选或导出任务等待 | `references/approval-run-export.md` | 只查命令语法时读 `cli.md`;报告与复核台账走 `report-templates.md` |
|
||||
| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` |
|
||||
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
|
||||
| 租户禁用/启用、企业已停用、命令提示「已禁用」 | `references/tenant-status.md` | 只查命令语法时读 `cli.md` |
|
||||
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
|
||||
| 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
|
||||
| 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` |
|
||||
|
||||
@@ -76,7 +76,7 @@ seal-use approval-runs get <recordId> --raw-json --full --corp <corpId>
|
||||
- `--raw-json` 保留上游响应的 JSON 结构(包括 `data` 包装、嵌套内容、新字段及上游同名字段),绕过审核记录的业务 schema 校验,不额外添加或覆盖字段。它仍只调用同一条只读审核详情接口,沿用企业认证和 HTTP 错误处理。
|
||||
- 该模式解析并重新序列化 JSON,缩进等文本格式可能变化,不是 HTTP 响应的字节级副本。上游未返回的内容不会补查;无效 JSON、网络错误或 HTTP 失败仍按原协议报错。
|
||||
- 输出不会静默截断。共享的 stdout 大小保护超过 200,000 字节时返回退出码 12;`--full` 或 `--output-file` 可输出完整内容。`--full` 只控制大小保护,不会绕过字段校验,也不会撤销 `--summary/--fields`。
|
||||
- `--raw-json` 不能与 `--summary`、`--fields` 或 `--flow` 同用;这些参数会改写结构或切换接口,CLI 会以退出码 2 明确拒绝。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
|
||||
- `--raw-json` 不能与 `--summary` 或 `--fields` 同用;这两个参数会改写返回结构,CLI 会以退出码 2 明确拒绝。需要合思原生审批流时间线时,用 `seal-use approval-runs hose-flow <recordId|SN>`,不要从审核详情接口取。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
|
||||
- 不把兜底入口作为默认查询,也不将大段原生 JSON 直接贴给用户;Agent 可按需读取文件中的特定字段。
|
||||
|
||||
## Understand The Case First
|
||||
|
||||
@@ -46,6 +46,8 @@ seal-use corps current [--corp <corpId>]
|
||||
seal-use corps switch <corpId>
|
||||
seal-use corps mark <corpId> --env <production|test> [--dry-run] [--confirm]
|
||||
seal-use corps rename <corpId> --name <newName>
|
||||
seal-use corps disable <corpId> [--dry-run] [--confirm]
|
||||
seal-use corps enable <corpId> [--dry-run] [--confirm]
|
||||
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
|
||||
seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]
|
||||
seal-use corps unbind-test [<corpId>] [--confirm]
|
||||
@@ -134,8 +136,9 @@ seal-use report review dismiss [--hours <n>] [--corp <corpId>]
|
||||
seal-use report review list [--corp <corpId>]
|
||||
seal-use report review import <台账.xlsx|csv> --corp <corpId>
|
||||
seal-use simulation batch-records <batchId> [--corp <corpId>]
|
||||
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]
|
||||
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]
|
||||
seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--draft] [--rule-version <versionId>] [--corp <corpId>]
|
||||
seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--draft] [--rule-version <versionId>] [--corp <corpId>]
|
||||
seal-use simulation create --mode maycur --form-codes "MC001,MC002" [--draft] [--corp <corpId>]
|
||||
seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp <corpId>]
|
||||
seal-use simulation status <batchId> [--corp <corpId>]
|
||||
seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
|
||||
@@ -172,6 +175,9 @@ seal-use config mode <stateful|stateless> [--corp <corpId>]
|
||||
seal-use config test-dir [<path>|--clear]
|
||||
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
|
||||
seal-use auth check [--corp <corpId>]
|
||||
seal-use auth login [--bridge <https://bridge-host>]
|
||||
seal-use auth logout
|
||||
seal-use auth bridge
|
||||
seal-use auth link [--note <note>] [--expire <duration>] [--corp <corpId>]
|
||||
seal-use auth link --from-link <url> [--note <note>] [--expire <duration>]
|
||||
seal-use auth link list [--corp <corpId>]
|
||||
|
||||
@@ -13,17 +13,46 @@
|
||||
# 国内镜像源秒级自愈与升级
|
||||
curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash
|
||||
```
|
||||
2. **测试先行,优先草稿隔离 (Staging-First Recommendation)**:
|
||||
- 强烈建议生产环境的规则修改优先以草稿态(`draft`)保存,并通过 `seal-use corps sync-test` 自动同步到绑定的测试企业进行模拟验证。
|
||||
- Agent 应主动向用户建议该安全演进闭环,但**绝不替用户做决定**。最终的操作权在用户手中;若用户明确指示直接在生产企业发布,Agent 必须尊重并遵照用户意图执行。
|
||||
3. **合思集成安全隔离 (Hosecloud Zero-Impact Sync)**:
|
||||
- 测试环境进行合思模拟测试,必须在测试企业中保存合思凭证。
|
||||
- `corps sync-test` 会自动读取本地生产 source 凭证并为测试环境配置 `assisted`(辅助)模式的合思集成,名称格式为 `{企业名前缀}(Seal测)`。
|
||||
2. **单租户原生快照测试(首选,不再强求双企业组)**:
|
||||
- 过去平台模拟测试因无法指定规则版本,必须通过双企业组(生产 + 测试)与 `corps sync-test` 在测试企业预发版来固化快照。
|
||||
- 现在 Seal 后端原生支持 `ruleSource`:创建模拟时默认以当前线上生效的正式规则运行;若要测试刚刚修改的未发布规则草稿,显式传递 `--draft` 即可自动对当前草稿拍摄不可变快照(`ruleSource: { type: "current" }`);亦可通过 `--rule-version <versionId>` 挂载指定历史发布版本。
|
||||
- **单企业租户即可原生闭环草稿快照测试与多版本对比**,无需强行开通或绑定第二个测试企业。
|
||||
3. **双企业租户物理隔离场景(保留边界)**:
|
||||
- 双企业组(`corps bind-test` + `corps sync-test`)不再是为了“制造快照”,而是为了:
|
||||
1. 物理隔离外部费控审批流出站(测试端合思集成设为 `assisted`,防止外部推送副作用);
|
||||
2. 执行全自动大样本回归测试矩阵(`seal-use test regression` 硬阻断生产企业执行);
|
||||
3. 跨租户 Webhook 与出站仿真重放。
|
||||
- **严禁向合思执行同步 (`deploy hosecloud sync`)**:测试环境的合思配置只保存在 Seal 端,绝不向合思生产系统推送 EBot 节点或创建真实出站消息,保障生产费控审批流的绝对安全。
|
||||
|
||||
---
|
||||
|
||||
## 端到端标准演进闭环 (The 5-Stage Lifecycle)
|
||||
## 端到端标准演进闭环 (Evolution Lifecycles)
|
||||
|
||||
### 路径 A:单企业租户原生快照演进闭环(优先首选)
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Stage 1: 规则草稿修改 (rules update)"] --> B["Stage 2: 单租户原生快照模拟 (simulation create --draft --wait)"]
|
||||
B --> C{"快照模拟与版本比对是否通过?"}
|
||||
C -- 存在偏差/翻转误伤 --> A
|
||||
C -- 验证通过 --> D["Stage 3: 生产正式发布 (rules publish)"]
|
||||
```
|
||||
|
||||
1. **修改草稿**:`seal-use rules update <code> --corp <corpId>`。
|
||||
2. **原地快照模拟验证**:
|
||||
```bash
|
||||
# 显式使用 --draft 为当前未发布草稿拍摄不可变快照
|
||||
seal-use simulation create --corp <corpId> --flow-ids "<单号>" --draft --wait
|
||||
|
||||
# 或与线上当前生效规则基线、历史已发布版本回溯比对
|
||||
seal-use simulation create --corp <corpId> --flow-ids "<单号>" --wait
|
||||
seal-use simulation create --corp <corpId> --flow-ids "<单号>" --rule-version "<versionId>" --wait
|
||||
```
|
||||
3. **正式发布**:用户确认后执行 `seal-use rules publish "<变更说明>" --corp <corpId>`。
|
||||
|
||||
---
|
||||
|
||||
### 路径 B:双企业租户物理隔离演进闭环(特定场景选)
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
@@ -125,7 +154,7 @@ flowchart TD
|
||||
- 对账知识库文档(覆盖更新已有文档、创建新文档、删除测试环境多余文档);
|
||||
- 清空测试环境旧草稿规则,灌入生产企业当前草稿规则并重算 code;
|
||||
- **自动同步合思集成**:
|
||||
- 从本地 source 读入 `appKey`/`appSecurity`(兼容 `key`/`password`);
|
||||
- 从本地 source 读入 `appKey`/`appSecurity`;
|
||||
- 截取企业名前缀并附加 `(Seal测)`(严格受控于 13 字符限制,例如 `钰泰半导体(Seal测)`);
|
||||
- 强制将审批模式设为 `assisted`;
|
||||
- 自动去重:若生产有多个相同 `corporationId` 的集成(如全自动与辅助),在测试环境自动合并为单条辅助集成;
|
||||
@@ -163,12 +192,26 @@ flowchart TD
|
||||
```
|
||||
> **红线保障**:系统硬性规定回归测试严禁在生产环境发起;且前置计算点数余额,余额不足直接拒绝执行;基于出站 HTTPS 轮询,客户端无公网 IP 亦可稳定工作。
|
||||
|
||||
- **方式 B:合思原生模拟任务 (Simulation Create,单据与附件测试首选)**:
|
||||
针对目标真实单据号(或客诉单据)在测试环境发起模拟。**强烈建议单据及附件审核优先采用本方式**,因为平台原生模拟通道会调用合思官方 OpenAPI 完整抓取单据正文与全部发票、合同等二进制附件,完整度最高;且支持 `--wait` 自动挂起轮询直至出结果:
|
||||
- **方式 B:平台原生模拟任务 (Simulation Create,单据与附件测试首选)**:
|
||||
针对目标真实单据号(或客诉单据)在测试环境发起模拟。**强烈建议单据及附件审核优先采用本方式**,因为平台原生模拟通道会调用上游官方 API 完整抓取单据正文与全部发票、合同等二进制附件,完整度最高;且支持 `--wait` 自动挂起轮询直至出结果:
|
||||
```bash
|
||||
# 异步创建后自动轮询等待结果(推荐)
|
||||
# 异步创建后自动轮询等待结果(默认使用当前规则草稿快照)
|
||||
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>" --wait
|
||||
|
||||
# 指定已发布历史规则版本进行回溯比对(例如比对修复前后的版本差异)
|
||||
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号>" --rule-version "<versionId>" --wait
|
||||
|
||||
# 深度推理与附件无缓存全量重跑(深度思考模式下生效)
|
||||
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号>" --thinking-depth high --disable-attachment-cache --wait
|
||||
|
||||
# 每刻报销原生单据模拟测试
|
||||
seal-use simulation create --corp <testCorpId> --mode maycur --form-codes "<单号1>,<单号2>" --wait
|
||||
```
|
||||
> **规则源与版本快照(`ruleSource`)**:
|
||||
> - 默认或显式传 `--rule-source current` 时,系统自动为当前草稿拍摄规则快照(`type: "snapshot"`),界面与批次详情显示 `当前规则快照(未发布)· 拍摄时间`。
|
||||
> - 指定 `--rule-version <versionId>` 时,锁定使用已发布的历史版本(`type: "published"`),用于精准评估特定版本的判定准确度。
|
||||
> - 审核记录中同步包含 `ruleSetSnapshotCreatedAt` 与思考深度(`thinkingDepthLevel`)。
|
||||
>
|
||||
> **打断/重发防重复扣费**:批次创建默认幂等——复用窗口(默认 5 分钟,`--reuse-window` 可调)内对同一组 `--flow-ids`/`--package-ids` 再次执行 `simulation create` 会直接返回既有批次(`reused: true`),不会重复扣费。若 `--wait` 挂起期间命令被用户消息打断或后台 task 被 kill,**先执行 `seal-use simulation list --limit 3` 查最近批次**(同单批次可能已在服务端跑完),拿到批次 ID 后用 `status`/`batch-records` 取结果;确认无在途同单批次再决定重发。确需立刻重跑同组单号时显式加 `--force`。
|
||||
>
|
||||
> **按界面名称找历史批次**:模拟测试服务端没有名称/关键词检索,批次也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。用 `seal-use simulation search "任务 fe1993e4" --since 7d` 或 `seal-use simulation list --query <关键词> --since <时间>`;这是 **CLI 本地聚合检索**(先按 `limit`/`offset` 拉取再过滤,响应带 `retrieval.serverSideSearch: false`),命中范围以 `scanned` 为准,需要覆盖更早批次时加 `--all`(可用 `--max-scan` 控上限)。
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# 租户启用 / 禁用状态
|
||||
|
||||
适用信号:企业已停用、需要临时封禁某个租户、命令报「已禁用」、想确认禁用后还能不能搜到该企业。
|
||||
|
||||
## 状态定义
|
||||
|
||||
企业配置文件(`~/.config/seal-use/enterprises/*.json`)顶层的 `active` 字段:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "acme",
|
||||
"name": "Acme Corporation",
|
||||
"active": false,
|
||||
"source": { "type": "hose", "...": "..." }
|
||||
}
|
||||
```
|
||||
|
||||
- 字段在**企业**上,不在 `source` 里。合思来源(`type: "hose"`)与 Seal 本源(`type: "seal"`)共用同一个开关,行为完全一致,不存在某一来源例外。
|
||||
- **字段缺失 = 启用**。旧配置零迁移;读取和任何配置更新都会把缺省值物化成显式的 `active: true`。
|
||||
- **字段值非法 = 禁用(fail-closed)**。`"false"` 字符串、`null`、`0`、对象等任何非布尔值都归一化为 `active: false`。配置文件**不会**被丢弃,企业仍可检索并显示 `active: false`,指向它的命令一律阻断,stderr 告警并给出修复命令。绝不会把写坏的值当成启用。
|
||||
- 显式 `active: false` = 禁用。不要靠删除配置文件、改文件名或清空凭据来「禁用」,那会破坏检索可见性与恢复路径。
|
||||
|
||||
## 命令
|
||||
|
||||
```bash
|
||||
seal-use corps disable <corpId> --dry-run # 预览,不写文件
|
||||
seal-use corps disable <corpId> --confirm # 实际禁用
|
||||
seal-use corps enable <corpId> --confirm # 恢复
|
||||
```
|
||||
|
||||
- 不加 `--confirm` / `--yes` 会返回退出码 `10`(确认门)。
|
||||
- `--dry-run` 返回 `preview: true` 与 `changesDiff: { before, after }`,不写配置。
|
||||
- 这两个命令是**唯一**能解析禁用企业的命令;没有它们,禁用后无法恢复。
|
||||
|
||||
## 行为口径(严格遵守)
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| `corps list` / `corps search` / `corps find` | 禁用企业**仍可检索**,输出带 `active: false`。禁用不影响搜索可见性 |
|
||||
| 任何显式指定该企业 ID 的命令 | **统一阻断、不执行**,退出码 `14`,stderr 提示 `seal-use corps enable <corpId> --confirm` |
|
||||
| `corps enable` / `corps disable` | 允许执行(唯一豁免) |
|
||||
|
||||
阻断发生在企业解析处(`resolveCorpConfig`),早于创建 HTTP client、认证续期和任何业务 handler,因此不会有网络请求或副作用。覆盖:
|
||||
|
||||
- CLI 所有 `--corp <id>` 与位置参数形式(查询、写操作、绑定、同步、诊断、本地导出任务);
|
||||
- MCP 的 `seal_use` 与 `seal_use_write` 两个网关;
|
||||
- stateful 模式下 `defaultCorpId` 指向禁用企业、或无显式 ID 时兜底命中的第一个企业;
|
||||
- webhook 重放的 `--source-corp` / `--target-corp` 以及能力注册表中的等价解析;
|
||||
- 本地 `rules lint --file` 与 `report --ledger` 的降级分支不会吞掉该阻断。
|
||||
|
||||
## 排查步骤
|
||||
|
||||
1. `seal-use corps search <关键词>` 确认企业仍在列表中并读取 `active` 字段。
|
||||
2. 若确需操作该企业:`seal-use corps enable <corpId> --confirm`。这个值非法时同样有效——该命令会把字段重写为 `true`,一并修复坏配置。
|
||||
3. 若确需保持禁用,不要绕过闸门(不要直接改 ID、不要复制配置换新 ID)。解除封禁是唯一正当路径。
|
||||
4. 退出码 `14` 属安全守卫拦截,不是认证失败(`11`)或参数错误(`2`)。若看到 `13`「No enterprise config found」,说明整个配置文件被跳过(JSON 格式错误或必填字段缺失),与本开关无关。详见 `references/cli.md`。
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { isCompiledBinary, performRuntimeSelfHealing, resolveAppRoot, resolveDefaultLauncher } from "./core/runtime.js";
|
||||
import { runCli } from "./cli/run/runner.js";
|
||||
import { isCompiledBinary, performRuntimeSelfHealing, resolveAppRoot, resolveDefaultLauncher } from "./core/util/runtime.js";
|
||||
|
||||
process.stdout.on("error", (err: any) => {
|
||||
if (err?.code === "EPIPE") process.exit(0);
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { exportInsightReportToExcel } from "../../domains/seal/insight/export.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, dryRunOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { booleanOption, dryRunOption, numberOption, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleAnalyticsCommand(
|
||||
|
||||
@@ -4,9 +4,9 @@ import { tmpdir } from "node:os"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { join } from "node:path"
|
||||
import ExcelJS from "exceljs"
|
||||
import { parseArgs } from "../parser.js"
|
||||
import { runCli } from "../runner.js"
|
||||
import { isReadOnlyCliCommand } from "../read-only.js"
|
||||
import { parseArgs } from "../parse/parser.js"
|
||||
import { runCli } from "../run/runner.js"
|
||||
import { isReadOnlyCliCommand } from "../run/read-only.js"
|
||||
import { getExportTask, startExportTask, waitForExportTask, writeExportTask } from "../../domains/seal/approval-runs/export-task.js"
|
||||
import { resolveExportOptions } from "./approval-runs-export.js"
|
||||
import type { CorpConfig } from "../../core/config/types.js"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { appendFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { extname, join, resolve } from "node:path"
|
||||
import { durationSeconds, tokenizeDuration } from "../../core/duration.js"
|
||||
import { durationSeconds, tokenizeDuration } from "../../core/util/duration.js"
|
||||
import { classifyCliError, CliError, usageError } from "../../core/errors.js"
|
||||
import { formatBeijingIso } from "../../core/config/timestamps.js"
|
||||
import { resolveDefaultLauncher } from "../../core/runtime.js"
|
||||
import { resolveDefaultLauncher } from "../../core/util/runtime.js"
|
||||
import { createSealClient } from "../../core/http/factory.js"
|
||||
import { exportApprovalRunsToExcel, normalizeManualApprovalStatus, resolveExportDateRange } from "../../domains/seal/approval-runs/export.js"
|
||||
import {
|
||||
@@ -12,8 +12,8 @@ import {
|
||||
type ExportTaskOptions
|
||||
} from "../../domains/seal/approval-runs/export-task.js"
|
||||
import { selectCorp } from "../helpers.js"
|
||||
import { booleanOption, dryRunOption, numberOption, stringOption } from "../parser.js"
|
||||
import { formatConsoleOutput, printJson, redactSensitiveText } from "../printer.js"
|
||||
import { booleanOption, dryRunOption, numberOption, stringOption } from "../parse/parser.js"
|
||||
import { formatConsoleOutput, printJson, redactSensitiveText } from "../output/printer.js"
|
||||
import type { CliRuntime, ParsedArgs } from "../types.js"
|
||||
import { approvalRunsExportOptions } from "./approval-runs.js"
|
||||
import type { CorpConfig } from "../../core/config/types.js"
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
import { runCli } from "../run/runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_DISABLE_BG_UPDATE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
@@ -102,6 +102,9 @@ describe("approval run native JSON fallback", () => {
|
||||
expect(result.exitCode).toBe(2)
|
||||
expect(result.stdout).toBe("")
|
||||
expect(result.stderr).toContain("--raw-json cannot be combined")
|
||||
// The message names only what the caller actually passed, so the retired
|
||||
// `--flow` spelling is never advertised to anyone who did not use it.
|
||||
expect(result.stderr).toContain(flags[0]!)
|
||||
}
|
||||
expect(requests).toHaveLength(0)
|
||||
})
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
extractApprovalRunAttachments
|
||||
} from "../../domains/seal/approval-runs/attachments.js";
|
||||
import { runCapability, runCapabilityResult } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
|
||||
@@ -187,11 +187,18 @@ export async function handleApprovalRunsCommand(
|
||||
}
|
||||
|
||||
if (action === "get") {
|
||||
const recordId = args.command[2];
|
||||
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
|
||||
if (!recordId) throw new Error("Missing approval run recordId");
|
||||
const rawJson = booleanOption(args.options["raw-json"]) ?? booleanOption(args.options.rawJson);
|
||||
if (rawJson && (booleanOption(args.options.flow) || booleanOption(args.options.summary) || stringOption(args.options.fields) !== undefined)) {
|
||||
throw usageError("--raw-json cannot be combined with --flow, --summary or --fields");
|
||||
if (rawJson) {
|
||||
// Name only the flags the caller actually passed: legacy spellings stay
|
||||
// implementation-only and must not be advertised to everyone else.
|
||||
const conflicts = [
|
||||
booleanOption(args.options.flow) ? "--flow" : undefined,
|
||||
booleanOption(args.options.summary) ? "--summary" : undefined,
|
||||
stringOption(args.options.fields) !== undefined ? "--fields" : undefined
|
||||
].filter((flag): flag is string => flag !== undefined);
|
||||
if (conflicts.length) throw usageError(`--raw-json cannot be combined with ${conflicts.join(", ")}`);
|
||||
}
|
||||
if (booleanOption(args.options.flow)) {
|
||||
await runCapability(
|
||||
@@ -219,21 +226,21 @@ export async function handleApprovalRunsCommand(
|
||||
}
|
||||
|
||||
if (action === "cited-rules") {
|
||||
const recordId = args.command[2];
|
||||
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
|
||||
if (!recordId) throw usageError("Usage: seal-use approval-runs cited-rules <recordId>");
|
||||
await runCapability("sealApprovalRunCitedRulesGet", client, corp, { recordId }, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "document-summary") {
|
||||
const recordId = args.command[2];
|
||||
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
|
||||
if (!recordId) throw usageError("Usage: seal-use approval-runs document-summary <recordId>");
|
||||
await runCapability("sealApprovalRunDocumentSummaryGet", client, corp, { recordId }, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "diagnose") {
|
||||
const recordId = args.command[2];
|
||||
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
|
||||
if (!recordId && !sn) {
|
||||
throw usageError("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
|
||||
+86
-11
@@ -6,6 +6,18 @@ import {
|
||||
normalizeBaseUrl
|
||||
} from "../../core/auth/hose.js";
|
||||
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
||||
import { resolveCorpCredentials } from "../../core/auth/credentials.js";
|
||||
import {
|
||||
clearBridgeCredentialCache,
|
||||
pollBridgeDeviceToken,
|
||||
revokeBridgeToken,
|
||||
startBridgeDeviceLogin
|
||||
} from "../../core/auth/bridge-client.js";
|
||||
import {
|
||||
clearBridgeSession,
|
||||
readBridgeSession,
|
||||
saveBridgeSession
|
||||
} from "../../core/auth/bridge-token.js";
|
||||
import { formatBeijingIso } from "../../core/config/timestamps.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { CliError, validationError, usageError } from "../../core/errors.js";
|
||||
@@ -19,8 +31,8 @@ import {
|
||||
parseDelegationExpireHours,
|
||||
parseHoseExpireSeconds,
|
||||
stringOption
|
||||
} from "../parser.js";
|
||||
import { outputOptions, printJson, redactSensitiveText } from "../printer.js";
|
||||
} from "../parse/parser.js";
|
||||
import { outputOptions, printJson, redactSensitiveText } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { runCapability, runCapabilityResult } from "../helpers.js";
|
||||
import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js";
|
||||
@@ -46,10 +58,71 @@ export async function handleAuthExtractKeysCommand(maybeName: string | undefined
|
||||
});
|
||||
}
|
||||
|
||||
async function handleBridgeLogin(args: ParsedArgs): Promise<void> {
|
||||
const url = stringOption(args.options.bridge) ?? stringOption(args.options.url) ?? process.env.SEAL_USE_BRIDGE_URL?.trim();
|
||||
if (!url) {
|
||||
throw usageError("Usage: seal-use auth login --bridge <https://bridge-host>");
|
||||
}
|
||||
|
||||
const start = await startBridgeDeviceLogin(url);
|
||||
console.error(`👉 请在浏览器打开: ${start.verificationUrl}`);
|
||||
console.error(` 核对代码: ${start.userCode}(${Math.round(start.expiresIn / 60)} 分钟内有效)`);
|
||||
|
||||
const token = await pollBridgeDeviceToken(url, start.deviceCode, start.interval, start.expiresIn, {
|
||||
onPending: (attempt) => {
|
||||
if (attempt === 1) console.error("⏳ 等待浏览器确认...");
|
||||
}
|
||||
});
|
||||
|
||||
saveBridgeSession({ url, token: token.token, expiresAt: token.expiresAt, username: token.username });
|
||||
printJson({
|
||||
ok: true,
|
||||
url,
|
||||
username: token.username ?? null,
|
||||
expiresAt: token.expiresAt ?? null
|
||||
});
|
||||
}
|
||||
|
||||
async function handleBridgeLogout(): Promise<void> {
|
||||
const session = readBridgeSession();
|
||||
if (session) await revokeBridgeToken(session);
|
||||
clearBridgeSession();
|
||||
clearBridgeCredentialCache();
|
||||
printJson({ ok: true, loggedOut: true });
|
||||
}
|
||||
|
||||
async function handleBridgeStatus(): Promise<void> {
|
||||
const session = readBridgeSession();
|
||||
if (!session) {
|
||||
printJson({ ok: true, loggedIn: false });
|
||||
return;
|
||||
}
|
||||
printJson({
|
||||
ok: true,
|
||||
loggedIn: true,
|
||||
url: session.url,
|
||||
username: session.username ?? null,
|
||||
expiresAt: session.expiresAt ?? null
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig | null, args: ParsedArgs) {
|
||||
const subAction = args.command[2]?.toLowerCase();
|
||||
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined);
|
||||
|
||||
if (action === "login") {
|
||||
await handleBridgeLogin(args);
|
||||
return;
|
||||
}
|
||||
if (action === "logout") {
|
||||
await handleBridgeLogout();
|
||||
return;
|
||||
}
|
||||
if (action === "bridge" || action === "bridge-status") {
|
||||
await handleBridgeStatus();
|
||||
return;
|
||||
}
|
||||
|
||||
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
|
||||
const note = stringOption(args.options.note);
|
||||
const expireOption = args.options.expire ?? args.options["expires-in"] ?? args.options.expiresIn;
|
||||
@@ -175,11 +248,12 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
2
|
||||
);
|
||||
}
|
||||
const appKey = corp.source.appKey ?? corp.source.key;
|
||||
const appSecurity = corp.source.appSecurity ?? corp.source.password;
|
||||
const credentials = await resolveCorpCredentials(corp);
|
||||
const appKey = credentials.appKey;
|
||||
const appSecurity = credentials.appSecurity;
|
||||
if (!appKey || !appSecurity) {
|
||||
throw validationError(
|
||||
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法向合思 OpenAPI 签发 accessToken。`
|
||||
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity,无法向合思 OpenAPI 签发 accessToken。`
|
||||
);
|
||||
}
|
||||
const force =
|
||||
@@ -237,13 +311,14 @@ async function diagnoseAuth(corp: CorpConfig) {
|
||||
|
||||
clearCorpTokenCache(corp.id);
|
||||
const source = corp.source;
|
||||
const appKey = source.appKey ?? source.key;
|
||||
const appSecurity = source.appSecurity ?? source.password;
|
||||
const credentials = await resolveCorpCredentials(corp);
|
||||
const appKey = credentials.appKey;
|
||||
const appSecurity = credentials.appSecurity;
|
||||
const sealUrl = (corp.seal.url ?? source.sealUrl ?? `https://${source.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
|
||||
const uid = source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`;
|
||||
const stages: Array<Record<string, unknown>> = [];
|
||||
|
||||
if ((!appKey || !appSecurity) && !source.closeToken) {
|
||||
if ((!appKey || !appSecurity) && !credentials.closeToken) {
|
||||
return {
|
||||
corp: {
|
||||
id: corp.id,
|
||||
@@ -255,7 +330,7 @@ async function diagnoseAuth(corp: CorpConfig) {
|
||||
{
|
||||
name: "hose.openapi",
|
||||
ok: false,
|
||||
error: "Hose source requires appKey/key and appSecurity/password"
|
||||
error: "Hose source requires appKey and appSecurity"
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -282,7 +357,7 @@ async function diagnoseAuth(corp: CorpConfig) {
|
||||
if (openapi) stages.push(openapi.public);
|
||||
|
||||
const openapiToken = openapi?.private?.token;
|
||||
const provisional = source.closeToken
|
||||
const provisional = credentials.closeToken
|
||||
? {
|
||||
public: {
|
||||
name: "hose.closeapi",
|
||||
@@ -292,7 +367,7 @@ async function diagnoseAuth(corp: CorpConfig) {
|
||||
configured: true,
|
||||
expiresAt: source.expiresAt
|
||||
},
|
||||
private: { token: source.closeToken }
|
||||
private: { token: credentials.closeToken }
|
||||
}
|
||||
: openapiToken
|
||||
? await runDiagnoseStage("hose.provisional", async () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleBillingCommand(
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
} from "../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../core/config/manager.js";
|
||||
import { globalConfigSummary } from "../helpers.js";
|
||||
import { parseStateMode, stringOption } from "../parser.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import { parseStateMode, stringOption } from "../parse/parser.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export function handleConfigCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleContactsCommand(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { numberOption, ruleVersionContextOptions, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { numberOption, ruleVersionContextOptions, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleContextCommand(
|
||||
|
||||
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
@@ -739,9 +739,10 @@ describe("sync-test hosecloud integration auto-sync", () => {
|
||||
expect(writtenIntegrations[0].apiOrigin).toBe("wechat");
|
||||
});
|
||||
|
||||
test("supports key/password fallback in source config when appKey/appSecurity are omitted", async () => {
|
||||
test("rejects legacy key/password source config instead of falling back", async () => {
|
||||
const { enterprises } = setupHoseTestEnv();
|
||||
// Overwrite hose-prod.json to use key / password instead of appKey / appSecurity
|
||||
// Legacy key/password aliases are no longer part of the schema; the file
|
||||
// must be skipped on load rather than silently used for sync.
|
||||
const prodCorpWithKeyPassword = JSON.parse(readFileSync(join(enterprises, "hose-prod.json"), "utf-8"));
|
||||
delete prodCorpWithKeyPassword.source.appKey;
|
||||
delete prodCorpWithKeyPassword.source.appSecurity;
|
||||
@@ -749,25 +750,8 @@ describe("sync-test hosecloud integration auto-sync", () => {
|
||||
prodCorpWithKeyPassword.source.password = "fallback-secret-012";
|
||||
writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorpWithKeyPassword, null, 2));
|
||||
|
||||
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
||||
|
||||
let capturedBody: any;
|
||||
mockHoseSyncRequests({
|
||||
onConfigWrite: (isProd, body) => {
|
||||
if (!isProd) capturedBody = body;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync.skipped).toBe(false);
|
||||
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
||||
|
||||
const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud");
|
||||
expect(writtenIntegration?.apiKey).toBe("fallback-key-789");
|
||||
expect(writtenIntegration?.apiSecret).toBe("fallback-secret-012");
|
||||
const result = await runCli(["corps", "get", "hose-prod"]);
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
@@ -45,7 +45,6 @@ describe("corps link onboarding", () => {
|
||||
type: string;
|
||||
closeToken: string;
|
||||
staffId: string;
|
||||
provider?: string;
|
||||
corpId?: string;
|
||||
};
|
||||
};
|
||||
@@ -60,7 +59,6 @@ describe("corps link onboarding", () => {
|
||||
type: "hose",
|
||||
closeToken: "hose-token",
|
||||
staffId: "acme-01:admin",
|
||||
provider: "hosecloud",
|
||||
corpId: "acme-01"
|
||||
}
|
||||
});
|
||||
@@ -117,7 +115,6 @@ describe("corps link onboarding", () => {
|
||||
source: {
|
||||
type: string;
|
||||
token: string;
|
||||
provider?: string;
|
||||
};
|
||||
};
|
||||
expect(config).toMatchObject({
|
||||
@@ -129,8 +126,7 @@ describe("corps link onboarding", () => {
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "mock-delegate-token",
|
||||
provider: "seal"
|
||||
token: "mock-delegate-token"
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -193,7 +189,7 @@ describe("corps link onboarding", () => {
|
||||
expect(result.exitCode).toBe(0);
|
||||
const config = JSON.parse(readFileSync(join(enterprises, "acme-01.json"), "utf-8"));
|
||||
expect(config.source.type).toBe("hose");
|
||||
expect(config.source.provider).toBe("hosecloud");
|
||||
expect(config.source).not.toHaveProperty("provider");
|
||||
expect(config.source.closeToken).toBe("hose-token");
|
||||
expect(config.source.staffId).toBe("staff-1");
|
||||
});
|
||||
@@ -331,8 +327,7 @@ describe("corps get and search", () => {
|
||||
token: "veryLongSecretBearerToken1234567890",
|
||||
expiresIn: 3600,
|
||||
tenantSlug: "native-slug",
|
||||
tenantName: "原生租户",
|
||||
provider: "feishu"
|
||||
tenantName: "原生租户"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
@@ -346,7 +341,7 @@ describe("corps get and search", () => {
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data.id).toBe("native-seal");
|
||||
expect(data.source.type).toBe("seal");
|
||||
expect(data.source.provider).toBe("feishu");
|
||||
expect(data.source).not.toHaveProperty("provider");
|
||||
expect(data.source.hasToken).toBe(true);
|
||||
expect(data.source.tokenMasked).toContain("...");
|
||||
});
|
||||
@@ -1145,7 +1140,7 @@ describe("Hose OpenAPI key extraction from assistance link", () => {
|
||||
});
|
||||
|
||||
test("RULE_SUMMARY_FIELDS excludes raw internal UUID and prioritizes business fields", async () => {
|
||||
const { RULE_SUMMARY_FIELDS } = await import("../printer.js");
|
||||
const { RULE_SUMMARY_FIELDS } = await import("../output/printer.js");
|
||||
expect(RULE_SUMMARY_FIELDS).not.toContain("id");
|
||||
expect(RULE_SUMMARY_FIELDS).toContain("code");
|
||||
expect(RULE_SUMMARY_FIELDS).toContain("status");
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { usageError } from "../../core/errors.js";
|
||||
import { handleCorpActive } from "./corps/active.js";
|
||||
import { handleCorpBindings } from "./corps/bindings.js";
|
||||
import { handleCorpOnboarding, extractKeysFromLinkAction, showCorpKeysAction } from "./corps/onboarding.js";
|
||||
import { handleCorpOverview } from "./corps/overview.js";
|
||||
@@ -14,6 +15,7 @@ export async function handleCorpsCommand(
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (await handleCorpOverview(action, maybeName, args)) return;
|
||||
if (await handleCorpActive(action, maybeName, args)) return;
|
||||
if (await handleCorpBindings(action, maybeName, args)) return;
|
||||
if (await handleCorpSync(action, maybeName, args)) return;
|
||||
if (await handleCorpOnboarding(action, maybeName, args)) return;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { updateCorpConfig } from "../../../core/config/loader.js";
|
||||
import { confirmationRequired, usageError } from "../../../core/errors.js";
|
||||
import { booleanOption, dryRunOption, stringOption } from "../../parse/parser.js";
|
||||
import { printJson } from "../../output/printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
/**
|
||||
* Tenant availability switch for both `hose` and `seal` sources.
|
||||
*
|
||||
* This is the ONLY command surface allowed to resolve a disabled tenant: without
|
||||
* it, `corps enable` could not restore an enterprise that the gate now blocks.
|
||||
* All other commands resolve through `selectCorp()` and are refused upstream.
|
||||
*/
|
||||
export async function handleCorpActive(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
args: ParsedArgs
|
||||
): Promise<boolean> {
|
||||
if (action !== "disable" && action !== "enable") return false;
|
||||
|
||||
const corpId = maybeName ?? stringOption(args.options.corp);
|
||||
if (!corpId) {
|
||||
throw usageError(`Usage: seal-use corps ${action} <corpId> [--dry-run] [--confirm]`);
|
||||
}
|
||||
|
||||
const targetActive = action === "enable";
|
||||
const { selectCorp } = await import("../../helpers.js");
|
||||
const corp = selectCorp(corpId, { allowDisabled: true });
|
||||
const previousActive = corp.active ?? true;
|
||||
|
||||
if (dryRunOption(args)) {
|
||||
printJson({
|
||||
preview: true,
|
||||
dryRun: true,
|
||||
mutation: `corps ${action}`,
|
||||
corpId: corp.id,
|
||||
corpName: corp.name,
|
||||
sourceType: corp.source.type,
|
||||
changesDiff: { before: previousActive, after: targetActive },
|
||||
note: "禁用只阻断显式指定该企业 ID 的命令,不影响 corps list/search 的检索可见性。"
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
|
||||
if (!confirmed) {
|
||||
throw confirmationRequired(
|
||||
`Refusing to ${action} enterprise '${corp.name}' (${corp.id}) without --confirm.`,
|
||||
`seal-use corps ${action} ${corp.id} --confirm`
|
||||
);
|
||||
}
|
||||
|
||||
const updated = updateCorpConfig(corp.id, { active: targetActive });
|
||||
printJson({
|
||||
success: true,
|
||||
id: updated.id,
|
||||
name: updated.name,
|
||||
sourceType: updated.source.type,
|
||||
active: updated.active,
|
||||
previousActive
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { updateCorpConfig } from "../../../core/config/loader.js";
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { confirmationRequired, usageError } from "../../../core/errors.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { booleanOption, stringOption } from "../../parse/parser.js";
|
||||
import { printJson } from "../../output/printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
export async function handleCorpBindings(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { maskHoseSecurity } from "../../../core/auth/hose.js";
|
||||
import { resolveCorpCredentials } from "../../../core/auth/credentials.js";
|
||||
import { scoreAssistLink } from "../../../core/auth/delegate.js";
|
||||
import { onboardSealBearer } from "../../../domains/seal/enterprise/onboarding.js";
|
||||
import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js";
|
||||
@@ -23,8 +24,8 @@ import {
|
||||
optionalString,
|
||||
requiredString,
|
||||
stringOption
|
||||
} from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
} from "../../parse/parser.js";
|
||||
import { printJson } from "../../output/printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
import { maskCellphone } from "./shared.js";
|
||||
|
||||
@@ -264,7 +265,6 @@ async function addSealCorp(input: Record<string, unknown>) {
|
||||
tenantName: optionalString(input, "tenantName"),
|
||||
corpId: optionalString(input, "corpId"),
|
||||
staffId: optionalString(input, "staffId"),
|
||||
provider: optionalString(input, "provider"),
|
||||
force: input.force === true,
|
||||
verify: input.verify === false,
|
||||
overwrite: input.overwrite === true,
|
||||
@@ -339,7 +339,6 @@ async function addLinkAsHoseCorp(link: string, name: string | undefined, overwri
|
||||
printJson({
|
||||
dryRun: true,
|
||||
kind: "hose",
|
||||
provider: "hose",
|
||||
corpId: result.corpId,
|
||||
corpName: result.corpName,
|
||||
baseUrl: result.baseUrl,
|
||||
@@ -394,7 +393,6 @@ export async function extractKeysFromLinkAction(link: string, options: { reveal?
|
||||
if (!reveal) console.error("ℹ️ [合思子域提权] 成功提取合思 (Hose) OpenAPI 密钥。接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文;附加 --save 可将临时会话提权并持久化为标准合思企业。\n");
|
||||
else console.error("⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。\n");
|
||||
printJson({
|
||||
provider: "hose",
|
||||
capability: "privilege-elevation",
|
||||
corpId: result.corpId,
|
||||
corpName: result.corpName ?? result.corpId,
|
||||
@@ -408,16 +406,22 @@ export async function extractKeysFromLinkAction(link: string, options: { reveal?
|
||||
export async function showCorpKeysAction(targetCorpId: string | undefined, options: { reveal?: boolean }) {
|
||||
const corp = selectCorp(targetCorpId);
|
||||
const reveal = options.reveal === true;
|
||||
if ((corp.storage ?? "local") === "cloud") {
|
||||
throw new CliError(
|
||||
`企业「${corp.name}」(id: ${corp.id}) 使用云端凭据,本地不提供密钥查看或提权。\n请在桥接平台的凭据管理中维护该企业。`,
|
||||
2
|
||||
);
|
||||
}
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new CliError(`【合思子域专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
|
||||
"OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。", 2);
|
||||
}
|
||||
const appKey = corp.source.appKey ?? corp.source.key;
|
||||
const appSecurity = corp.source.appSecurity ?? corp.source.password;
|
||||
const credentials = await resolveCorpCredentials(corp);
|
||||
const appKey = credentials.appKey;
|
||||
const appSecurity = credentials.appSecurity;
|
||||
if (!reveal) console.error("💡 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。\n");
|
||||
else console.error("⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。\n");
|
||||
printJson({
|
||||
provider: "hose",
|
||||
capability: "privilege-elevation",
|
||||
corpId: corp.id,
|
||||
corpName: corp.name,
|
||||
|
||||
@@ -11,8 +11,8 @@ import {
|
||||
} from "../../../core/stats/usage-tracker.js";
|
||||
import type { CorpEnvironment } from "../../../core/config/types.js";
|
||||
import { confirmationRequired, usageError } from "../../../core/errors.js";
|
||||
import { booleanOption, dryRunOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { booleanOption, dryRunOption, numberOption, stringOption } from "../../parse/parser.js";
|
||||
import { printJson } from "../../output/printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
export async function handleCorpOverview(
|
||||
@@ -35,6 +35,9 @@ export async function handleCorpOverview(
|
||||
}
|
||||
|
||||
const corpId = stringOption(args.options.corp);
|
||||
// Deliberately NOT filtered by `active`: disabling a tenant gates command
|
||||
// execution at corp resolution, never discovery. Keep disabled enterprises
|
||||
// searchable for both `hose` and `seal` sources and just surface the flag.
|
||||
const allCorps = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const currentCorpId = corpId ?? (
|
||||
@@ -88,9 +91,10 @@ export async function handleCorpOverview(
|
||||
printJson(displayList.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
active: item.active ?? true,
|
||||
environment: item.environment ?? "production",
|
||||
storage: item.storage ?? "local",
|
||||
sourceType: item.source.type,
|
||||
provider: (item.source as any).provider ?? item.source.type,
|
||||
staffId: item.source.staffId,
|
||||
testCorpId: item.testCorpId,
|
||||
prodCorpId: item.prodCorpId,
|
||||
@@ -113,7 +117,9 @@ export async function handleCorpOverview(
|
||||
printJson({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
active: corp.active ?? true,
|
||||
environment: corp.environment ?? "production",
|
||||
storage: corp.storage ?? "local",
|
||||
configFile,
|
||||
seal: {
|
||||
url: sealUrl,
|
||||
@@ -139,9 +145,10 @@ export async function handleCorpOverview(
|
||||
printJson({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
active: corp.active ?? true,
|
||||
environment: corp.environment ?? "production",
|
||||
storage: corp.storage ?? "local",
|
||||
sourceType: corp.source.type,
|
||||
provider: (corp.source as any).provider ?? corp.source.type,
|
||||
staffId: corp.source.staffId,
|
||||
testCorpId: corp.testCorpId,
|
||||
prodCorpId: corp.prodCorpId
|
||||
|
||||
@@ -20,15 +20,14 @@ export function resolveCorpSealUrl(corp: CorpConfig): string | undefined {
|
||||
|
||||
export function formatSafeSourceDetail(source: SealSource) {
|
||||
if (source.type === "hose") {
|
||||
const key = source.appKey ?? source.key;
|
||||
const key = source.appKey;
|
||||
return {
|
||||
type: "hose",
|
||||
provider: source.provider ?? "hosecloud",
|
||||
domain: source.domain,
|
||||
corpId: source.corpId,
|
||||
staffId: source.staffId,
|
||||
appKey: maskSecret(key),
|
||||
hasAppSecurity: Boolean(source.appSecurity ?? source.password),
|
||||
hasAppSecurity: Boolean(source.appSecurity),
|
||||
hasCloseToken: Boolean(source.closeToken),
|
||||
closeTokenExpiresIn: source.closeToken ? source.expiresIn : undefined,
|
||||
closeTokenExpiresAt: source.closeToken ? source.expiresAt : undefined,
|
||||
@@ -40,7 +39,6 @@ export function formatSafeSourceDetail(source: SealSource) {
|
||||
if (source.type === "seal") {
|
||||
return {
|
||||
type: "seal",
|
||||
provider: source.provider ?? "seal",
|
||||
tenantId: source.tenantId,
|
||||
tenantSlug: source.tenantSlug,
|
||||
tenantName: source.tenantName,
|
||||
|
||||
@@ -4,8 +4,8 @@ import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js";
|
||||
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js";
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { CliError, confirmationRequired, usageError } from "../../../core/errors.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { outputOptions, printJson } from "../../printer.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../../output/printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
export { buildTestHosecloudOutboundName } from "../../../domains/seal/testing/sync.js";
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../../run/runner.js";
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "../../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../../core/config/manager.js";
|
||||
import { resolveReplayCorpPair } from "../../../domains/seal/replay/webhook.js";
|
||||
|
||||
const ENV_KEYS = [
|
||||
"SEAL_USE_ENTERPRISES_DIR",
|
||||
"SEAL_USE_CONFIG_FILE",
|
||||
"SEAL_USE_TOKEN_STORE",
|
||||
"SEAL_USE_USAGE_FILE",
|
||||
"SEAL_DISABLE_BG_UPDATE"
|
||||
] as const;
|
||||
|
||||
const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of ENV_KEYS) {
|
||||
const value = ORIGINAL_ENV[key];
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const SOURCE_VARIANTS = [
|
||||
{
|
||||
label: "hose",
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "app-key",
|
||||
appSecurity: "app-security",
|
||||
corpId: "ID01",
|
||||
staffId: "ID01:STAFF01"
|
||||
}
|
||||
},
|
||||
{
|
||||
label: "seal",
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://acme.sealai.cc"
|
||||
}
|
||||
}
|
||||
] as const;
|
||||
|
||||
function setup(): { root: string; enterprises: string } {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-tenant-active-"));
|
||||
tempDirs.push(root);
|
||||
const enterprises = join(root, "enterprises");
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
|
||||
process.env.SEAL_DISABLE_BG_UPDATE = "1";
|
||||
return { root, enterprises };
|
||||
}
|
||||
|
||||
function writeCorp(
|
||||
dir: string,
|
||||
options: {
|
||||
id: string;
|
||||
name: string;
|
||||
source: Record<string, unknown>;
|
||||
active?: unknown;
|
||||
}
|
||||
): string {
|
||||
const payload: Record<string, unknown> = {
|
||||
id: options.id,
|
||||
name: options.name,
|
||||
source: options.source,
|
||||
seal: { url: "https://acme.sealai.cc" },
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
if (options.active !== undefined) payload.active = options.active;
|
||||
const path = join(dir, `${options.id}.json`);
|
||||
writeFileSync(path, JSON.stringify(payload));
|
||||
return path;
|
||||
}
|
||||
|
||||
function corpFile(dir: string, id: string): Record<string, unknown> {
|
||||
return JSON.parse(readFileSync(join(dir, `${id}.json`), "utf-8"));
|
||||
}
|
||||
|
||||
/** Fail loudly if a command reaches any upstream API: a blocked command must never execute. */
|
||||
function guardNetwork(): { calls: () => number } {
|
||||
let calls = 0;
|
||||
globalThis.fetch = (async () => {
|
||||
calls += 1;
|
||||
throw new Error("network request must not happen for a disabled tenant");
|
||||
}) as unknown as typeof globalThis.fetch;
|
||||
return { calls: () => calls };
|
||||
}
|
||||
|
||||
/** Commands that explicitly name the tenant id, spanning local/corp/client handlers. */
|
||||
function commandsNamingCorp(id: string): string[][] {
|
||||
return [
|
||||
["corps", "get", id],
|
||||
["corps", "current", "--corp", id],
|
||||
["corps", "mark", id, "--env", "test"],
|
||||
["corps", "rename", id, "--name", "Renamed"],
|
||||
["contacts", "departments", "--corp", id],
|
||||
["rules", "list", "--corp", id],
|
||||
["documents", "list", "--corp", id],
|
||||
["billing", "status", "--corp", id],
|
||||
["webhook", "list", "--corp", id],
|
||||
["source", "config", "--corp", id],
|
||||
["auth", "status", "--corp", id]
|
||||
];
|
||||
}
|
||||
|
||||
describe("tenant active state: both sources share one gate", () => {
|
||||
for (const { label, source } of SOURCE_VARIANTS) {
|
||||
const id = `acme-${label}`;
|
||||
const name = `Acme ${label} Corporation`;
|
||||
|
||||
test(`${label}: disabled tenant stays visible in corps list and search`, async () => {
|
||||
const { enterprises } = setup();
|
||||
writeCorp(enterprises, { id, name, source, active: false });
|
||||
|
||||
const listed = await runCli(["corps", "list", "--all"]);
|
||||
expect(listed.exitCode).toBe(0);
|
||||
expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({
|
||||
id, name, active: false, sourceType: label
|
||||
}));
|
||||
|
||||
const searched = await runCli(["corps", "search", "Acme", "--strict"]);
|
||||
expect(searched.exitCode).toBe(0);
|
||||
const matches = JSON.parse(searched.stdout) as Array<{ id: string; active: boolean }>;
|
||||
expect(matches.find((item) => item.id === id)).toMatchObject({ id, active: false });
|
||||
});
|
||||
|
||||
test(`${label}: every command explicitly naming the disabled tenant is blocked without executing`, async () => {
|
||||
const { enterprises } = setup();
|
||||
writeCorp(enterprises, { id, name, source, active: false });
|
||||
const network = guardNetwork();
|
||||
|
||||
for (const command of commandsNamingCorp(id)) {
|
||||
const result = await runCli(command);
|
||||
expect({ command, exitCode: result.exitCode }).toEqual({ command, exitCode: 14 });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.stdout).toBe("");
|
||||
expect(result.stderr).toContain("已禁用");
|
||||
expect(result.stderr).toContain(`seal-use corps enable ${id}`);
|
||||
}
|
||||
|
||||
expect(network.calls()).toBe(0);
|
||||
});
|
||||
|
||||
test(`${label}: a malformed active value fails closed without hiding the enterprise`, async () => {
|
||||
const { enterprises } = setup();
|
||||
writeCorp(enterprises, { id, name, source, active: "false" });
|
||||
const network = guardNetwork();
|
||||
|
||||
const listed = await runCli(["corps", "list", "--all"]);
|
||||
expect(listed.exitCode).toBe(0);
|
||||
expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({
|
||||
id, name, active: false, sourceType: label
|
||||
}));
|
||||
expect(listed.stderr).toContain("active 字段值非法");
|
||||
|
||||
// The block reports a disabled tenant (14), not a missing config (13),
|
||||
// and the enterprise never disappears from discovery.
|
||||
const blocked = await runCli(["corps", "get", id]);
|
||||
expect(blocked.exitCode).toBe(14);
|
||||
expect(blocked.stdout).toBe("");
|
||||
expect(blocked.stderr).toContain("已禁用");
|
||||
expect(network.calls()).toBe(0);
|
||||
|
||||
const recovered = await runCli(["corps", "enable", id, "--confirm"]);
|
||||
expect(recovered.exitCode).toBe(0);
|
||||
expect(corpFile(enterprises, id).active).toBe(true);
|
||||
});
|
||||
|
||||
test(`${label}: an active tenant with the same source still runs through corp resolution`, async () => {
|
||||
const { enterprises } = setup();
|
||||
writeCorp(enterprises, { id, name, source, active: true });
|
||||
|
||||
const result = await runCli(["corps", "get", id]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ id, active: true });
|
||||
});
|
||||
|
||||
test(`${label}: disable/enable lifecycle with dry-run and confirmation gate`, async () => {
|
||||
const { enterprises } = setup();
|
||||
writeCorp(enterprises, { id, name, source });
|
||||
|
||||
const preview = await runCli(["corps", "disable", id, "--dry-run"]);
|
||||
expect(preview.exitCode).toBe(0);
|
||||
expect(JSON.parse(preview.stdout)).toMatchObject({
|
||||
preview: true,
|
||||
dryRun: true,
|
||||
mutation: "corps disable",
|
||||
corpId: id,
|
||||
sourceType: label,
|
||||
changesDiff: { before: true, after: false }
|
||||
});
|
||||
expect(corpFile(enterprises, id).active).toBeUndefined();
|
||||
|
||||
const unconfirmed = await runCli(["corps", "disable", id]);
|
||||
expect(unconfirmed.exitCode).toBe(10);
|
||||
expect(corpFile(enterprises, id).active).toBeUndefined();
|
||||
|
||||
const disabled = await runCli(["corps", "disable", id, "--confirm"]);
|
||||
expect(disabled.exitCode).toBe(0);
|
||||
expect(JSON.parse(disabled.stdout)).toMatchObject({ id, active: false, previousActive: true });
|
||||
expect(corpFile(enterprises, id).active).toBe(false);
|
||||
|
||||
// Re-enabling must work even though the tenant is disabled: this is the
|
||||
// single documented exemption from the block.
|
||||
const enabled = await runCli(["corps", "enable", id, "--confirm"]);
|
||||
expect(enabled.exitCode).toBe(0);
|
||||
expect(JSON.parse(enabled.stdout)).toMatchObject({ id, active: true, previousActive: false });
|
||||
expect(corpFile(enterprises, id).active).toBe(true);
|
||||
|
||||
const afterEnable = await runCli(["corps", "get", id]);
|
||||
expect(afterEnable.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
test(`${label}: a stateful default pointing at a disabled tenant is blocked`, async () => {
|
||||
const { root, enterprises } = setup();
|
||||
writeCorp(enterprises, { id, name, source, active: false });
|
||||
writeFileSync(join(root, "config.json"), JSON.stringify({
|
||||
stateful: true,
|
||||
defaultCorpId: id
|
||||
}));
|
||||
const network = guardNetwork();
|
||||
|
||||
const result = await runCli(["contacts", "departments"]);
|
||||
expect(result.exitCode).toBe(14);
|
||||
expect(result.stdout).toBe("");
|
||||
expect(network.calls()).toBe(0);
|
||||
});
|
||||
|
||||
test(`${label}: replay refuses a disabled source or target corp through both selectors`, () => {
|
||||
const { enterprises } = setup();
|
||||
const activeId = `active-${label}`;
|
||||
const disabledId = `off-${label}`;
|
||||
writeCorp(enterprises, { id: activeId, name: "Active Corp", source, active: true });
|
||||
writeCorp(enterprises, { id: disabledId, name: "Disabled Corp", source, active: false });
|
||||
const activeCorp = selectCorp(activeId);
|
||||
|
||||
// CLI replay path: `selectCorp` is passed straight into resolveReplayCorpPair.
|
||||
expect(() => resolveReplayCorpPair(
|
||||
{ sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true },
|
||||
selectCorp
|
||||
)).toThrow("已禁用");
|
||||
expect(() => resolveReplayCorpPair(
|
||||
{ sourceCorpId: disabledId, targetCorpId: activeId, activeCorp, force: true },
|
||||
selectCorp
|
||||
)).toThrow("已禁用");
|
||||
|
||||
// Capability registry replay path builds its own resolveCorpConfig selector.
|
||||
const capabilitySelector = (id?: string) => resolveCorpConfig(
|
||||
loadCorpConfigs(),
|
||||
{
|
||||
stateful: loadGlobalConfig().stateful,
|
||||
defaultCorpId: loadGlobalConfig().defaultCorpId,
|
||||
corpId: id
|
||||
},
|
||||
getEnterprisesDirCandidates()
|
||||
);
|
||||
expect(() => resolveReplayCorpPair(
|
||||
{ sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true },
|
||||
capabilitySelector
|
||||
)).toThrow("已禁用");
|
||||
});
|
||||
|
||||
test(`${label}: local lint/ledger fallbacks cannot swallow a disabled-tenant block`, async () => {
|
||||
const { enterprises } = setup();
|
||||
writeCorp(enterprises, { id, name, source, active: false });
|
||||
|
||||
const lint = await runCli(["rules", "lint", "--file", "rules.json", "--corp", id]);
|
||||
expect(lint.exitCode).toBe(14);
|
||||
expect(lint.stderr).toContain("已禁用");
|
||||
|
||||
const ledger = await runCli(["report", "validate", "--ledger", "ledger.xlsx", "--corp", id]);
|
||||
expect(ledger.exitCode).toBe(14);
|
||||
expect(ledger.stderr).toContain("已禁用");
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { parseArgs } from "../parse/parser.js";
|
||||
import { runCapabilityResult } from "../helpers.js";
|
||||
import { handleDeployCommand } from "./deploy.js";
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ import { readFileSync } from "node:fs";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, jsonObject, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { booleanOption, jsonObject, numberOption, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
import { listHoseIntegrations } from "../../domains/seal/outbound/push.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
describe("seal-use doctor CLI", () => {
|
||||
test("runs full system diagnosis and outputs JSON to stdout and dashboard to stderr", async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { diagnoseSystem, formatDoctorDashboard } from "../../core/doctor/diagnose.js";
|
||||
import { getEmbeddedGuideMarkdown } from "../../core/doctor/knowledge.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import { booleanOption } from "../parse/parser.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleDoctorCommand(
|
||||
@@ -28,7 +28,7 @@ export async function handleDoctorCommand(
|
||||
// 2.5. Output auth session diagnostics (seal-use doctor auth)
|
||||
if (subAction === "auth") {
|
||||
const { selectCorp } = await import("../helpers.js");
|
||||
const { stringOption } = await import("../parser.js");
|
||||
const { stringOption } = await import("../parse/parser.js");
|
||||
const { handleAuthCommand } = await import("./auth.js");
|
||||
const corpSelector =
|
||||
stringOption(args.options.corp) ??
|
||||
@@ -43,7 +43,7 @@ export async function handleDoctorCommand(
|
||||
if (subAction === "tenant" || subAction === "corp" || subAction === "enterprise") {
|
||||
const { selectCorp } = await import("../helpers.js");
|
||||
const { createSealClient } = await import("../../core/http/factory.js");
|
||||
const { stringOption } = await import("../parser.js");
|
||||
const { stringOption } = await import("../parse/parser.js");
|
||||
const { diagnoseTenantContract, formatTenantDoctorDashboard } = await import("../../domains/seal/doctor/tenant-diagnose.js");
|
||||
|
||||
const corpSelector =
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
import { runCli } from "../run/runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
|
||||
@@ -12,8 +12,8 @@ import {
|
||||
numberOption,
|
||||
splitOption,
|
||||
stringOption
|
||||
} from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
} from "../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
function contentFilePath(args: ParsedArgs): string | undefined {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
/**
|
||||
* Mutation-preview (`--dry-run`) gates for commands that previously mutated
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { runCli } from "../runner.js"
|
||||
import { runCli } from "../run/runner.js"
|
||||
|
||||
const envKeys = ["SEAL_USE_CONFIG_FILE", "SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const
|
||||
const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]]))
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { createSealClient } from "../../core/http/factory.js"
|
||||
import { usageError } from "../../core/errors.js"
|
||||
import { ExpenseLookupError } from "../../domains/seal/expenses/lookup.js"
|
||||
import { runCapabilityResult } from "../helpers.js"
|
||||
import { numberOption, stringOption } from "../parser.js"
|
||||
import { outputOptions, printJson } from "../printer.js"
|
||||
import { numberOption, stringOption } from "../parse/parser.js"
|
||||
import { outputOptions, printJson } from "../output/printer.js"
|
||||
import type { ParsedArgs } from "../types.js"
|
||||
|
||||
export async function handleExpensesCommand(action: string | undefined, client: Awaited<ReturnType<typeof createSealClient>>, corp: CorpConfig, args: ParsedArgs) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { join } from "node:path";
|
||||
import type { KyInstance } from "ky";
|
||||
import { CorpConfigSchema } from "../../core/config/types.js";
|
||||
import { classifyCliError } from "../../core/errors.js";
|
||||
import { parseArgs } from "../parser.js";
|
||||
import { parseArgs } from "../parse/parser.js";
|
||||
import { handleHoseEbotCommand } from "./hose-ebot.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
const USAGE =
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { traceInvoice } from "../../domains/seal/approval-runs/invoices.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleInvoicesCommand(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { validationError, usageError } from "../../core/errors.js";
|
||||
import { booleanOption, numberOption, splitOption, stringOption } from "../parser.js";
|
||||
import { booleanOption, numberOption, splitOption, stringOption } from "../parse/parser.js";
|
||||
import { runLangfuseCapability } from "../helpers.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
/**
|
||||
@@ -20,7 +20,12 @@ export async function handleLangfuseCommand(
|
||||
const options = args.options;
|
||||
const out = outputOptions(options);
|
||||
const traceId = () => maybeName ?? stringOption(options["trace-id"]);
|
||||
const refreshIfMissing = () => booleanOption(options["refresh-if-missing"]);
|
||||
const refreshIfMissing = () => {
|
||||
if (booleanOption(options["no-refresh"]) || booleanOption(options.offline)) return false;
|
||||
const explicit = booleanOption(options["refresh-if-missing"]);
|
||||
if (explicit !== undefined) return explicit;
|
||||
return true;
|
||||
};
|
||||
|
||||
if (action === "check") {
|
||||
await runLangfuseCapability("sealLangfuseConnectionCheck", {}, out);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleLlmCommand(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { printJson } from "../printer.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
|
||||
export async function handleMcpCommand(action: string | undefined) {
|
||||
if (action === "config" || action === "json") {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handlePermissionsCommand(
|
||||
|
||||
@@ -3,8 +3,8 @@ import { readFileSync } from "node:fs";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, jsonObject, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { booleanOption, jsonObject, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handlePreferenceCommand(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { runProbe } from "../../probe.js";
|
||||
import { stringOption } from "../parser.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import { stringOption } from "../parse/parser.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
import { saveCorpConfig } from "../../core/config/repository.js";
|
||||
import {
|
||||
closeReviewsDb,
|
||||
@@ -29,8 +29,7 @@ const testCorp: CorpConfig = {
|
||||
staffId: "u-triage",
|
||||
corpId: "corp-triage-test",
|
||||
tenantId: "t-triage",
|
||||
tenantSlug: "triage",
|
||||
provider: "seal"
|
||||
tenantSlug: "triage"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
@@ -3,9 +3,10 @@ import { resolve } from "node:path";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { runCapabilityResult } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../output/printer.js";
|
||||
import { CliError, usageError } from "../../core/errors.js";
|
||||
import { isCorpDisabledError } from "../../core/config/active.js";
|
||||
import {
|
||||
BUILTIN_MONTHLY_TEMPLATE,
|
||||
exportReportPackage,
|
||||
@@ -36,7 +37,10 @@ export async function handleLocalReportCommand(action: string | undefined, args:
|
||||
try {
|
||||
const { selectCorp } = await import("../helpers.js");
|
||||
corp = selectCorp(corpId);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// Ledger/review work is tenant-free, but if the caller explicitly named a
|
||||
// disabled enterprise, the block must still stand instead of falling back.
|
||||
if (isCorpDisabledError(error)) throw error;
|
||||
corp = {
|
||||
corpId,
|
||||
id: corpId,
|
||||
|
||||
@@ -20,13 +20,13 @@ import {
|
||||
ruleVersionSearchOptions,
|
||||
splitOption,
|
||||
stringOption
|
||||
} from "../parser.js";
|
||||
} from "../parse/parser.js";
|
||||
import {
|
||||
outputOptions,
|
||||
printJson,
|
||||
protectLargeRuleListOutput,
|
||||
RULE_SUMMARY_FIELDS
|
||||
} from "../printer.js";
|
||||
} from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
function readDescriptionInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
numberOption,
|
||||
splitOption,
|
||||
stringOption
|
||||
} from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
} from "../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleSimulationCommand(
|
||||
@@ -87,6 +87,31 @@ export async function handleSimulationCommand(
|
||||
);
|
||||
}
|
||||
|
||||
const isDraft =
|
||||
booleanOption(args.options.draft) ||
|
||||
booleanOption(args.options.current) ||
|
||||
booleanOption(args.options["current-rules"]) ||
|
||||
booleanOption(args.options.currentRules) ||
|
||||
stringOption(args.options.ruleSource) === "current" ||
|
||||
stringOption(args.options["rule-source"]) === "current";
|
||||
|
||||
const ruleVersion =
|
||||
stringOption(args.options.ruleVersion) ??
|
||||
stringOption(args.options["rule-version"]) ??
|
||||
stringOption(args.options["rule-version-id"]) ??
|
||||
stringOption(args.options.ruleVersionId);
|
||||
|
||||
let ruleSource: { type: "current" } | { type: "published"; versionId: string } | undefined;
|
||||
if (isDraft) {
|
||||
ruleSource = { type: "current" };
|
||||
} else if (ruleVersion) {
|
||||
ruleSource = { type: "published", versionId: ruleVersion };
|
||||
}
|
||||
|
||||
const formCodes =
|
||||
splitOption(args.options.formCodes) ??
|
||||
splitOption(args.options["form-codes"]);
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealSimulationBatchCreate",
|
||||
client,
|
||||
@@ -96,11 +121,14 @@ export async function handleSimulationCommand(
|
||||
sourceSystem: mode,
|
||||
flowIds,
|
||||
documentSn: flowIds,
|
||||
formCodes,
|
||||
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
|
||||
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
|
||||
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
|
||||
skipExpenseExtraction,
|
||||
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
|
||||
ruleSource,
|
||||
ruleVersion,
|
||||
signKey,
|
||||
packageIds,
|
||||
packageId,
|
||||
|
||||
@@ -10,11 +10,11 @@ import {
|
||||
getDefaultGlobalSkillDir,
|
||||
getSkillContent,
|
||||
installSkillFiles
|
||||
} from "../../core/embedded-skill.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson } from "../printer.js";
|
||||
} from "../../core/skill/embedded-skill.js";
|
||||
import { booleanOption, stringOption } from "../parse/parser.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { getSkillVersionStatus } from "../../core/skill-version.js";
|
||||
import { getSkillVersionStatus } from "../../core/skill/skill-version.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
|
||||
export function handleSkillCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { usageError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
|
||||
export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) {
|
||||
if (action === "config") {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CliError } from "../../core/errors.js";
|
||||
import { selectCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parse/parser.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { createSealClient } from "../../core/http/factory.js";
|
||||
import {
|
||||
|
||||
@@ -191,7 +191,7 @@ describe("update command bgSave and cache integration", () => {
|
||||
const { mkdtempSync, rmSync } = await import("node:fs");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { handleUpdateCommand } = await import("./update.js");
|
||||
const { loadUpdateCache, UPDATE_CACHE_FILE_ENV } = await import("../../core/update-cache.js");
|
||||
const { loadUpdateCache, UPDATE_CACHE_FILE_ENV } = await import("../../core/update/update-cache.js");
|
||||
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "seal-use-bg-save-test-"));
|
||||
const tempCacheFile = join(tempDir, "update-cache.json");
|
||||
|
||||
@@ -2,12 +2,12 @@ import { accessSync, chmodSync, constants, existsSync, lstatSync, mkdirSync, rea
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary } from "../../core/runtime.js";
|
||||
import { isCompiledBinary } from "../../core/util/runtime.js";
|
||||
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
|
||||
import { readInstalledSkillVersion } from "../../core/embedded-skill.js";
|
||||
import { saveUpdateCache } from "../../core/update-cache.js";
|
||||
import { readInstalledSkillVersion } from "../../core/skill/embedded-skill.js";
|
||||
import { saveUpdateCache } from "../../core/update/update-cache.js";
|
||||
import { VERSION, IS_RELEASE } from "../../version.js";
|
||||
import { printJson } from "../printer.js";
|
||||
import { printJson } from "../output/printer.js";
|
||||
import { validationError } from "../../core/errors.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
@@ -1043,7 +1043,7 @@ function extractZip(archivePath: string, targetDir: string, platform: string): s
|
||||
return resolveExtractedBinary(targetDir, platform, archivePath);
|
||||
}
|
||||
|
||||
import { compareSemVer, isNewerVersion } from "../../core/semver.js";
|
||||
import { compareSemVer, isNewerVersion } from "../../core/util/semver.js";
|
||||
// Re-exported for tests and callers that historically imported from here.
|
||||
export { compareSemVer, isNewerVersion };
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { confirmationRequired, usageError } from "../../core/errors.js";
|
||||
import { runCapability } from "../helpers.js";
|
||||
import { booleanOption, dryRunOption, parseDelegationExpireHours, stringOption } from "../parser.js";
|
||||
import { outputOptions } from "../printer.js";
|
||||
import { booleanOption, dryRunOption, parseDelegationExpireHours, stringOption } from "../parse/parser.js";
|
||||
import { outputOptions } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleUsersCommand(
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
|
||||
const ORIGINAL_ENV = {
|
||||
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runCli } from "../run/runner.js";
|
||||
import { exportApprovalRunsToResourcePack } from "../../domains/seal/material-pack/export.js";
|
||||
import { previewResourcePack } from "../../domains/seal/material-pack/service.js";
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ import {
|
||||
stringOption,
|
||||
webhookRateOption,
|
||||
webhookShowSecretOption
|
||||
} from "../parser.js";
|
||||
import { outputOptions, printJson } from "../printer.js";
|
||||
} from "../parse/parser.js";
|
||||
import { outputOptions, printJson } from "../output/printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
|
||||
import { CliError, confirmationRequired, usageError, validationError } from "../../core/errors.js";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { parseArgs } from "./parser.js";
|
||||
import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js";
|
||||
import { parseArgs } from "../parse/parser.js";
|
||||
import { KNOWN_AREAS, UPDATE_ALIASES } from "../run/runner.js";
|
||||
|
||||
/**
|
||||
* Documentation cross-check: every command a maintained doc shows a reader must
|
||||
@@ -21,7 +21,7 @@ import { KNOWN_AREAS, UPDATE_ALIASES } from "./runner.js";
|
||||
* like "the seal-use wrapped API" is not a command and is not matched.
|
||||
*/
|
||||
|
||||
const REPO_ROOT = join(import.meta.dir, "..", "..");
|
||||
const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
|
||||
|
||||
const DOC_FILES = [
|
||||
"README.md",
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { extractHelpRequest, HELP_REGISTRY, renderHelp } from "./help.js";
|
||||
import { KNOWN_AREAS, runCli } from "./runner.js";
|
||||
import { KNOWN_AREAS, runCli } from "../run/runner.js";
|
||||
|
||||
describe("extractHelpRequest", () => {
|
||||
test("detects global help from empty command or help option", () => {
|
||||
@@ -1,6 +1,6 @@
|
||||
import { normalizeCliArea } from "./area-aliases.js";
|
||||
import type { ParsedArgs } from "./types.js";
|
||||
import { usageError } from "../core/errors.js";
|
||||
import { normalizeCliArea } from "../parse/area-aliases.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { usageError } from "../../core/errors.js";
|
||||
|
||||
export interface CommandOptionHelp {
|
||||
flag: string;
|
||||
@@ -98,6 +98,28 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
],
|
||||
description: "Safely updates the display name of a configured enterprise without modifying underlying files manually."
|
||||
},
|
||||
{
|
||||
name: "disable",
|
||||
group: "企业配置",
|
||||
summary: "Disable a tenant without removing it from enterprise search",
|
||||
usage: ["seal-use corps disable <corpId> [--dry-run] [--confirm]"],
|
||||
options: [
|
||||
{ flag: "--dry-run", description: "Preview the active-state change without writing local config" },
|
||||
{ flag: "--confirm", description: "Confirm the state change (required for live execution)" }
|
||||
],
|
||||
description: "Sets active=false on a Hose or Seal enterprise. The enterprise stays visible in `corps list/search`, but every command that explicitly resolves its ID is refused until it is enabled again."
|
||||
},
|
||||
{
|
||||
name: "enable",
|
||||
group: "企业配置",
|
||||
summary: "Re-enable a disabled tenant",
|
||||
usage: ["seal-use corps enable <corpId> [--dry-run] [--confirm]"],
|
||||
options: [
|
||||
{ flag: "--dry-run", description: "Preview the active-state change without writing local config" },
|
||||
{ flag: "--confirm", description: "Confirm the state change (required for live execution)" }
|
||||
],
|
||||
description: "Sets active=true. This is the only command allowed to resolve a disabled enterprise, so a disabled tenant can always be restored."
|
||||
},
|
||||
{
|
||||
name: "bind-test",
|
||||
group: "测试配对与验证",
|
||||
@@ -556,7 +578,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
summary: "Get detailed approval record payload",
|
||||
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary, --fields and --flow" },
|
||||
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary and --fields. Native Hose flow timeline lives in `seal-use approval-runs hose-flow <recordId|SN>`" },
|
||||
{ flag: "--full", description: "Bypass the shared 200,000-byte stdout size guard; this does not change payload structure" },
|
||||
{ flag: "--output-file <path>", description: "Write the complete JSON payload to a file, bypassing the stdout size guard" }
|
||||
]
|
||||
@@ -827,10 +849,11 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "create",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction)",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction; defaults to latest published rules; pass --draft for unreleased draft snapshot)",
|
||||
usage: [
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--draft] [--rule-version <versionId>] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--draft] [--rule-version <versionId>] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode maycur --form-codes \"MC001,MC002\" [--draft] [--corp <corpId>]",
|
||||
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
|
||||
]
|
||||
},
|
||||
@@ -1085,6 +1108,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
summary: "Check auth session and platform connectivity",
|
||||
usage: ["seal-use auth check [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "login",
|
||||
summary: "【云端企业】通过设备码登录桥接凭据服务",
|
||||
usage: ["seal-use auth login [--bridge <https://bridge-host>]"],
|
||||
options: [
|
||||
{ flag: "--bridge <url>", description: "桥接服务地址;也可用 SEAL_USE_BRIDGE_URL 环境变量" }
|
||||
],
|
||||
description:
|
||||
"仅 cloud 企业需要。CLI 申请设备码后,用户在浏览器确认授权;令牌保存在 ~/.config/seal-use/bridge.json(0600),30 天有效,到期后重新登录。"
|
||||
},
|
||||
{
|
||||
name: "logout",
|
||||
summary: "【云端企业】撤销并删除本地桥接令牌",
|
||||
usage: ["seal-use auth logout"]
|
||||
},
|
||||
{
|
||||
name: "bridge",
|
||||
aliases: ["bridge-status"],
|
||||
summary: "【云端企业】查看桥接登录状态",
|
||||
usage: ["seal-use auth bridge"]
|
||||
},
|
||||
{
|
||||
name: "link",
|
||||
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { HELP_REGISTRY } from "./help.js";
|
||||
import { parseArgs } from "./parser.js";
|
||||
import { parseArgs } from "../parse/parser.js";
|
||||
|
||||
/**
|
||||
* Naming charter guard (.agents/rules/cli-protocol.md "Naming Charter").
|
||||
@@ -76,6 +76,16 @@ describe("naming charter: visible help surface", () => {
|
||||
const offenders = LEGACY_SURFACE_TOKENS.filter((token) => serialized.includes(token));
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
|
||||
test("never documents the retired bare flow switch", () => {
|
||||
// `--flow` on `approval-runs get` is a silent legacy alias for
|
||||
// `approval-runs hose-flow`, so the visible surface must not name it.
|
||||
// LEGACY_SURFACE_TOKENS matches by substring and cannot express this:
|
||||
// `--flow-id`, `--flow-ids` and `--flow-concurrency` are canonical.
|
||||
const serialized = JSON.stringify(HELP_REGISTRY);
|
||||
const offenders = serialized.match(/--flow(?![A-Za-z0-9-])/g) ?? [];
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("naming charter: parser accepts canonical and legacy spellings", () => {
|
||||
@@ -100,20 +110,20 @@ describe("naming charter: canonical accept-sets are wired in commands", () => {
|
||||
const read = (path: string) => readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf8");
|
||||
|
||||
test("webhook resource-pack export reads --out and --downloads (no silent ignore)", () => {
|
||||
const source = read("./commands/webhook.ts");
|
||||
const source = read("../commands/webhook.ts");
|
||||
expect(source).toContain("stringOption(args.options.out) ??");
|
||||
expect(source).toContain("booleanOption(args.options.downloads) ??");
|
||||
expect(source).toContain("booleanOption(args.options.download) ??");
|
||||
});
|
||||
|
||||
test("webhook secret reveal accepts --reveal alongside legacy --show-secret", () => {
|
||||
const source = read("./parser.ts");
|
||||
const source = read("../parse/parser.ts");
|
||||
expect(source).toContain("booleanOption(options.reveal)");
|
||||
expect(source).toContain('booleanOption(options["show-secret"])');
|
||||
});
|
||||
|
||||
test("approval-runs reads canonical --start-date/--end-date everywhere", () => {
|
||||
const source = read("./commands/approval-runs.ts");
|
||||
const source = read("../commands/approval-runs.ts");
|
||||
const startDateReads = source.match(/args\.options\["start-date"\]/g)?.length ?? 0;
|
||||
const endDateReads = source.match(/args\.options\["end-date"\]/g)?.length ?? 0;
|
||||
expect(startDateReads).toBeGreaterThanOrEqual(3);
|
||||
+4
-3
@@ -7,10 +7,10 @@ import { createLangfuseService, findLangfuseCapability } from "../domains/langfu
|
||||
import type { LangfuseService } from "../domains/langfuse/service.js";
|
||||
import { validationError } from "../core/errors.js";
|
||||
import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import { printJson } from "./output/printer.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
|
||||
export function selectCorp(corpId?: string): CorpConfig {
|
||||
export function selectCorp(corpId?: string, options: { allowDisabled?: boolean } = {}): CorpConfig {
|
||||
const corps = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const corp = resolveCorpConfig(
|
||||
@@ -18,7 +18,8 @@ export function selectCorp(corpId?: string): CorpConfig {
|
||||
{
|
||||
stateful: globalConfig.stateful,
|
||||
defaultCorpId: globalConfig.defaultCorpId,
|
||||
corpId
|
||||
corpId,
|
||||
allowDisabled: options.allowDisabled
|
||||
},
|
||||
getEnterprisesDirCandidates()
|
||||
);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { booleanOption, stringOption } from "./parser.js";
|
||||
import { PayloadTooLargeError } from "../core/errors.js";
|
||||
import { redactSensitiveText } from "../core/redact.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
import { booleanOption, stringOption } from "../parse/parser.js";
|
||||
import { PayloadTooLargeError } from "../../core/errors.js";
|
||||
import { redactSensitiveText } from "../../core/util/redact.js";
|
||||
import type { OutputOptions } from "../types.js";
|
||||
|
||||
export { redactSensitiveText };
|
||||
|
||||
@@ -68,7 +68,7 @@ export function outputOptions(options: Record<string, string | boolean>): Output
|
||||
};
|
||||
}
|
||||
|
||||
import { renderHelp } from "./help.js";
|
||||
import { renderHelp } from "../help/help.js";
|
||||
|
||||
export function printHelp(target: string[] = []) {
|
||||
console.log(renderHelp(target));
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AREA_ALIASES, UPDATE_ALIASES, normalizeCliArea } from "./area-aliases.js";
|
||||
import { KNOWN_AREAS } from "./runner.js";
|
||||
import { KNOWN_AREAS } from "../run/runner.js";
|
||||
|
||||
/**
|
||||
* Drift guard for the shared alias table.
|
||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user