Merge pull request #289 from yunyingk/mac15/remove-enterprise-provider-field

Clean up config metadata and reorganize module layout
This commit is contained in:
yunyingk authored and GitHub committed 2026-11-19 16:39:52 +08:00
commit 837f4e2db6
156 files changed
+843 -1390

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
+4 -4
View File
@@ -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)`
+2 -2
View File
@@ -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.
+4
View File
@@ -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
+3
View File
@@ -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
+38 -14
View File
@@ -1,37 +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 workspace data (memory logs, project state) — keep on disk, never commit
.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/
+5 -4
View File
@@ -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
+6 -5
View File
@@ -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.
@@ -121,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:
@@ -154,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.
@@ -217,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"
},
@@ -354,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,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.
+2 -1
View File
@@ -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",
-190
View File
@@ -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\% $$
![AI 与人工审核准确率对比](assets/图1-准确率对比.svg)
*图 1 · AI 与人工审核准确率对比*
---
## 2. AI 失准分析(学习优化空间)
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
### 2.1 失准构成总览
| 维度 | 失准类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
| 合计 | — | 100% | 19 张 |
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
**解决方案**:严格校准规则触发后动作,按规则执行。
| 单号 | 问题描述 |
| --- | --- |
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
*(节选 3 例,全量 9 张)*
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
| 单号 | 问题描述 |
| --- | --- |
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
*(节选 3 例,全量 5 张)*
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
| 单号 | 问题描述 |
| --- | --- |
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
*(节选 3 例,全量 5 张)*
---
## 3. AI 发现的潜在风险
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
### 3.1 风险构成总览
| 维度 | 风险类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
| 合计 | — | 100% | 40 张 |
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
| 单号 | 问题描述 |
| --- | --- |
| FP260011 | 改衣费未附改衣明细表 |
| FP260012 | 咨询费报销资料不全 |
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
*(节选 3 例,全量 23 张)*
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
| 单号 | 问题描述 |
| --- | --- |
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
*(节选 3 例,全量 9 张)*
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
| 单号 | 问题描述 |
| --- | --- |
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
*(节选 3 条,全量 8 张)*
---
## 4. 综合效益
| 维度 | 结论 | 关键数据 |
| --- | --- | --- |
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
---
## 5. 审核分歧与复核归因
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
| 原因分类 | 占比 | 单数 | 核心说明 |
| --- | --- | --- | --- |
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
| 合计 | 100% | 3 张 | — |
**分歧分析与后续建议**:
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
---
## 6. 支撑数据与交付材料
### 6.1 分模板准确率与自动审批率
全量 N = 240:
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
| --- | --- | --- | --- | --- | --- |
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
*(其余 10 类模板从略,实际报告列出全量 16 类)*
### 6.2 跑批原始数据与交付台账
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
-64
View File
@@ -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

-190
View File
@@ -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\% $$
![AI 与人工审核准确率对比](assets/图1-准确率对比.svg)
*图 1 · AI 与人工审核准确率对比*
---
## 2. AI 失准分析(学习优化空间)
在全量 **240 单**的深度稽核中,AI 依规综合正确 **221 单(92.08%)**,综合失准共 **19 单(7.92%)**。失准主要由以下三个维度构成。
### 2.1 失准构成总览
| 维度 | 失准类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 规则执行与判定偏差 | 47.4% | 9 张 |
| TOP 2 | 数据与附件识别问题 | 26.3% | 5 张 |
| TOP 3 | 费用明细查重冲突 | 26.3% | 5 张 |
| 合计 | — | 100% | 19 张 |
### 2.2 TOP 1 · 规则执行与判定偏差(9 张 / 47.4%)
**解决方案**:严格校准规则触发后动作,按规则执行。
| 单号 | 问题描述 |
| --- | --- |
| FP260001 | 规则仅核验支付凭证金额一致性,不要求个人代垫的收款方必须是公司,AI 误要求 |
| CD260002 | 连续三日均为工作日(周一至周三),AI 误认为有周末未扣减问题 |
| FP260003 | 费用承担主体命中豁免白名单,AI 未执行豁免逻辑导致驳回 |
*(节选 3 例,全量 9 张)*
### 2.3 TOP 2 · 数据与附件识别问题(5 张 / 26.3%)
**解决方案**:持续优化识别模型,提升多附件文字解析稳定性。
| 单号 | 问题描述 |
| --- | --- |
| SJ260004 | 手写收据金额 243 元被 OCR 误识别为 2433 元,导致金额不符误驳回 |
| FP260005 | 微信红包支付记录清晰完整,AI 误判定为无关凭据导致误驳回 |
| SG260006 | 已完整包含福利品发放人员统计表 Excel 文件,AI 因多附件漏提取误判缺件驳回 |
*(节选 3 例,全量 5 张)*
### 2.4 TOP 3 · 费用明细查重冲突(5 张 / 26.3%)
**解决方案**:已去掉跨批次相似费用冲突的默认判定,可按需配置此功能。
| 单号 | 问题描述 |
| --- | --- |
| CGD260007 | 跨批次存在历史同类辅料费用,提示疑似冲突转人工 |
| FP260008 | 跨批次云产品疑似同类费用冲突转人工 |
| FP260009 | 发票金额 180 元(1% 普票),远未达到 500 元专票强制门槛,AI 过度怀疑是否存在专票协议转人工 |
*(节选 3 例,全量 5 张)*
---
## 3. AI 发现的潜在风险
在人工审核同意的单据中,有部分单据被 AI 发现存在风险,问题 TOP 3 如下。
### 3.1 风险构成总览
| 维度 | 风险类型 | 占比 | 单数 |
| --- | --- | --- | --- |
| TOP 1 | 缺失要求凭证 | 57.5% | 23 张 |
| TOP 2 | 大额预付与采购口径偏差 | 22.5% | 9 张 |
| TOP 3 | 票据合规与专票强制违规 | 20.0% | 8 张 |
| 合计 | — | 100% | 40 张 |
### 3.2 TOP 1 · 缺失要求凭证(23 张 / 57.5%)
| 单号 | 问题描述 |
| --- | --- |
| FP260011 | 改衣费未附改衣明细表 |
| FP260012 | 咨询费报销资料不全 |
| FP260013 | 专利代理费未列明发明名称且缺少缴费通知书 |
*(节选 3 例,全量 23 张)*
### 3.3 TOP 2 · 大额预付与采购口径偏差(9 张 / 22.5%)
| 单号 | 问题描述 |
| --- | --- |
| YF260014 | 大额预付款单未关联申购单 / 申请单 |
| CGA260015 | 采购预付款单明细采购订单号与合同号不一致 |
| CGD260016 | 采购付款单品类为上装类但发票明细为服装加工费,业务勾稽不符 |
*(节选 3 例,全量 9 张)*
### 3.4 TOP 3 · 票据合规与专票强制违规(8 张 / 20.0%)
| 单号 | 问题描述 |
| --- | --- |
| FP260017 / FP260018 / FP260019 | 发票类对外支付模板未上传正规发票,上传非正规微信截图或洗衣取衣单据 |
| FP260020 | 高税率业务金额超 500 元未开具增值税专用发票且无免专票佐证 |
| FP260021 | 完税证明纳税人名称与费用承担公司主体不一致 |
*(节选 3 条,全量 8 张)*
---
## 4. 综合效益
| 维度 | 结论 | 关键数据 |
| --- | --- | --- |
| 准确度 | 除去 AI 无法形成可靠判断而转失败的单据,AI 在既定规则范围内的准确率已赶超人工审批 | **92.08%** |
| 时效 | AI 审核单张单据平均耗时赶超人工处理时效 | 平均 **445.4 秒** |
| 风险拦截 | 在人工审核通过的单据中,AI 有效防堵无票支付、大额无合同预付、税票违规等税务与资金安全隐患 | 40 笔 |
| 工作量 | 协助财务人员弥补遗漏、关注单据重点信息,大幅释放财务人员精力,专注于更有价值的工作 | — |
---
## 5. 审核分歧与复核归因
在全量 **240 单**的深度复核中,AI 审核决策与人工实际审批结果存在分歧的单据共 **3 笔**(占全量样本 **1.25%**)。对分歧单据的复核定性与主要原因归类如下:
| 原因分类 | 占比 | 单数 | 核心说明 |
| --- | --- | --- | --- |
| 线下口头要求/未在线配置规则 | 66.7% | 2 张 | 单据凭证齐全且符合现行线上规则,主要因经办人主动撤回、无理由终止或财务执行未上线的口头标准,AI 依既定规则放行 |
| AI 识别或规则理解偏差 | 33.3% | 1 张 | 单据缺少必要发票凭据,AI 未能正确识别缺件卡口放行,已纳入模型调优与规则修复样本 |
| 合计 | 100% | 3 张 | — |
**分歧分析与后续建议**:
1. **规则覆盖与口径统一**:存在分歧的单据中,绝大多数(**66.7%**,2 笔)并非 AI 判定缺陷,而是企业内部存在线下口头补充管控要求。建议根据实际管理需要,将此类管控标准沉淀并补充至线上规则库。
2. **算法与识别调优**:对于真实失准单据(仅 **1 笔**,占全量 **0.42%**),已归入模型样本库进行针对性专项训练。
> 📌 **注**:分歧单据的逐单编号、审核比对意见与复核裁决记录,已完整收录于配套交付的《明细台账.xlsx》中,可供业务与审计部门按单查验核对。
---
## 6. 支撑数据与交付材料
### 6.1 分模板准确率与自动审批率
全量 N = 240:
| 单据模板 | AI 准确率 | 人工准确率 | 自动审批率 | 人工同意:驳回 | AI&人工都准确比例 |
| --- | --- | --- | --- | --- | --- |
| 一般费用报销单【发票】- 个人报销 | 92.86% | 87.14% | 45.71% | 70(57:13) | 80.00% |
| 一般费用报销单【发票】- 对外支付 | 92.19% | 75.00% | 42.19% | 64(50:14) | 67.19% |
| 一般费用报销单【收据】- 个人报销 | 93.94% | 93.94% | 48.48% | 33(20:13) | 87.88% |
| 差旅报销单-定额 | 81.82% | 100.00% | 31.82% | 22(19:3) | 81.82% |
| 预付款单 | 100.00% | 42.86% | 14.29% | 7(7:0) | 42.86% |
| **全量样本总体(N=240)** | **92.08%** | **83.33%** | **41.67%** | **240(185:55)** | **75.42%** |
*(其余 10 类模板从略,实际报告列出全量 16 类)*
### 6.2 跑批原始数据与交付台账
见同目录配套交付的《明细台账.xlsx》及《明细台账.csv》(完整收录本月全量跑批单据、AI 审核意见、人工审批结论及逐笔复核定性台账)。
-374
View File
@@ -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 -1
View File
@@ -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 -->";
+2 -2
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const skillRoot = resolve(root, "skills", "seal-use");
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("/"),
+5 -3
View File
@@ -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([])
})
})
+149
View File
@@ -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()
@@ -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 与真实文档现状双覆盖测试
│
@@ -154,7 +154,7 @@ flowchart TD
- 对账知识库文档(覆盖更新已有文档、创建新文档、删除测试环境多余文档);
- 清空测试环境旧草稿规则,灌入生产企业当前草稿规则并重算 code;
- **自动同步合思集成**:
- 从本地 source 读入 `appKey`/`appSecurity`(兼容 `key`/`password`);
- 从本地 source 读入 `appKey`/`appSecurity`;
- 截取企业名前缀并附加 `(Seal测)`(严格受控于 13 字符限制,例如 `钰泰半导体(Seal测)`);
- 强制将审批模式设为 `assisted`;
- 自动去重:若生产有多个相同 `corporationId` 的集成(如全自动与辅助),在测试环境自动合并为单条辅助集成;
+2 -2
View File
@@ -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);
+2 -2
View File
@@ -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"
+4 -4
View File
@@ -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"
+1 -1
View File
@@ -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]]))
+2 -2
View File
@@ -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";
+1 -1
View File
@@ -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,
+8 -8
View File
@@ -19,8 +19,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";
@@ -175,11 +175,11 @@ 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 appKey = corp.source.appKey;
const appSecurity = corp.source.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,8 +237,8 @@ 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 appKey = source.appKey;
const appSecurity = source.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>> = [];
@@ -255,7 +255,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"
}
]
};
+1 -1
View File
@@ -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(
+2 -2
View File
@@ -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) {
+1 -1
View File
@@ -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(
+2 -2
View File
@@ -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(
+6 -22
View File
@@ -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);
});
});
+6 -11
View File
@@ -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");
+2 -2
View File
@@ -1,7 +1,7 @@
import { updateCorpConfig } from "../../../core/config/loader.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, dryRunOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import { booleanOption, dryRunOption, stringOption } from "../../parse/parser.js";
import { printJson } from "../../output/printer.js";
import type { ParsedArgs } from "../../types.js";
/**
+2 -2
View File
@@ -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(
+4 -8
View File
@@ -23,8 +23,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 +264,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 +338,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 +392,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,
@@ -412,12 +409,11 @@ export async function showCorpKeysAction(targetCorpId: string | undefined, optio
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 appKey = corp.source.appKey;
const appSecurity = corp.source.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,
+2 -4
View File
@@ -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(
@@ -94,7 +94,6 @@ export async function handleCorpOverview(
active: item.active ?? true,
environment: item.environment ?? "production",
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
staffId: item.source.staffId,
testCorpId: item.testCorpId,
prodCorpId: item.prodCorpId,
@@ -147,7 +146,6 @@ export async function handleCorpOverview(
active: corp.active ?? true,
environment: corp.environment ?? "production",
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type,
staffId: corp.source.staffId,
testCorpId: corp.testCorpId,
prodCorpId: corp.prodCorpId
+2 -4
View File
@@ -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,
+2 -2
View File
@@ -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";
+1 -1
View File
@@ -2,7 +2,7 @@ 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 "../../runner.js";
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";
+1 -1
View File
@@ -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 -2
View File
@@ -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 -1
View File
@@ -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 () => {
+4 -4
View File
@@ -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 =
+1 -1
View File
@@ -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]]))
+2 -2
View File
@@ -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 {
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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]]))
+2 -2
View File
@@ -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) {
+1 -1
View File
@@ -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 -2
View File
@@ -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 -2
View File
@@ -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(
+2 -2
View File
@@ -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";
/**
+1 -1
View File
@@ -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 -1
View File
@@ -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") {
+1 -1
View File
@@ -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(
+2 -2
View File
@@ -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(
+2 -2
View File
@@ -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 -3
View File
@@ -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 }
};
+2 -2
View File
@@ -3,8 +3,8 @@ 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 {
+2 -2
View File
@@ -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 {
+1 -1
View File
@@ -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,
+2 -2
View File
@@ -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(
+4 -4
View File
@@ -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 -1
View File
@@ -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") {
+1 -1
View File
@@ -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,
+2 -2
View File
@@ -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 {
+1 -1
View File
@@ -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");
+5 -5
View File
@@ -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 };
+1 -1
View File
@@ -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 -2
View File
@@ -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(
+1 -1
View File
@@ -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";
+2 -2
View File
@@ -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", () => {
+3 -3
View File
@@ -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;
@@ -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").
@@ -110,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);
+1 -1
View File
@@ -7,7 +7,7 @@ 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, options: { allowDisabled?: boolean } = {}): CorpConfig {
@@ -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.
File renamed without changes.
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { HELP_REGISTRY } from "./help.js";
import { HELP_REGISTRY } from "../help/help.js";
import {
booleanOption,
BOOLEAN_FLAGS,
@@ -1,8 +1,8 @@
import type { WebhookMode } from "../domains/seal/types.js";
import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js";
import type { ParsedArgs } from "./types.js";
import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../core/duration.js";
import { usageError, validationError } from "../core/errors.js";
import type { WebhookMode } from "../../domains/seal/types.js";
import type { MaterialPackFilePolicyPatch } from "../../domains/seal/material-pack/policy.js";
import type { ParsedArgs } from "../types.js";
import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../../core/util/duration.js";
import { usageError, validationError } from "../../core/errors.js";
/**
* Flag metadata for argv parsing, derived from how the code reads each flag:
@@ -3,7 +3,7 @@
* reach the CLI intact. Lives in its own module because both the MCP server and the HTTP routes
* need it; importing it from the server entry would make the CLI graph circular.
*/
import { usageError } from "../core/errors.js";
import { usageError } from "../../core/errors.js";
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
@@ -1,9 +1,9 @@
import { describe, expect, test } from "bun:test";
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { HELP_REGISTRY } from "./help.js";
import { HELP_REGISTRY } from "../help/help.js";
import { KNOWN_AREAS } from "./runner.js";
import { SEAL_MUTATING_CAPABILITIES, SEAL_READ_ONLY_CAPABILITIES, sealCapabilities } from "../domains/seal/capabilities.js";
import { SEAL_MUTATING_CAPABILITIES, SEAL_READ_ONLY_CAPABILITIES, sealCapabilities } from "../../domains/seal/capabilities.js";
import { isReadOnlyCliCommand, listReadOnlyCommands } from "./read-only.js";
describe("CLI read-only classification", () => {
@@ -177,14 +177,14 @@ describe("CLI allow-list agrees with the tool registry", () => {
]);
test("every CLI verb dispatching to a read-only tool is itself read-only, and mutating tools are not read-only", () => {
const files = readdirSync(join(import.meta.dir, "commands")).filter(
const files = readdirSync(join(import.meta.dir, "../commands")).filter(
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
);
const pairs: Array<{ area: string; action: string; tool: string }> = [];
for (const file of files) {
const area = file.replace(/\.ts$/, "");
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
const source = readFileSync(join(import.meta.dir, "../commands", file), "utf8");
const pattern =
/if\s*\(\s*action === "([a-z0-9-]+)"(?:(?!\bif\s*\(\s*action\b)[\s\S]){0,600}?runCapability(?:Result)?\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
let match;
@@ -1,5 +1,5 @@
import { normalizeCliArea } from "./area-aliases.js";
import { parseArgs } from "./parser.js";
import { normalizeCliArea } from "../parse/area-aliases.js";
import { parseArgs } from "../parse/parser.js";
/**
* Read-only classification for CLI commands, used to decide whether a command may be executed
@@ -3,8 +3,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runCli } from "./runner.js";
import { saveUpdateCache, UPDATE_CACHE_FILE_ENV } from "../core/update-cache.js";
import { GLOBAL_SKILL_DIR_ENV } from "../core/skill-version.js";
import { saveUpdateCache, UPDATE_CACHE_FILE_ENV } from "../../core/update/update-cache.js";
import { GLOBAL_SKILL_DIR_ENV } from "../../core/skill/skill-version.js";
describe("CLI runner", () => {
let tempSkillDir: string;
+58 -58
View File
@@ -2,34 +2,34 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { CorpConfig } from "../core/config/types.js";
import { VERSION_INFO } from "../version.js";
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js";
import { classifyCliError, usageError, validationError } from "../core/errors.js";
import { isCorpDisabledError } from "../core/config/active.js";
import type { CorpConfig } from "../../core/config/types.js";
import { VERSION_INFO } from "../../version.js";
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../../core/update/update-cache.js";
import { classifyCliError, usageError, validationError } from "../../core/errors.js";
import { isCorpDisabledError } from "../../core/config/active.js";
import {
booleanOption,
materialPackFilePolicyOptions,
numberOption,
parseArgs,
stringOption
} from "./parser.js";
import { extractHelpRequest } from "./help.js";
import { isNewerVersion } from "../core/semver.js";
import { getSkillVersionStatus } from "../core/skill-version.js";
} from "../parse/parser.js";
import { extractHelpRequest } from "../help/help.js";
import { isNewerVersion } from "../../core/util/semver.js";
import { getSkillVersionStatus } from "../../core/skill/skill-version.js";
import {
formatConsoleOutput,
joinOutput,
printHelp,
printJson,
redactSensitiveText
} from "./printer.js";
} from "../output/printer.js";
import type { KyInstance } from "ky";
import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
import type { ParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js";
const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
export { UPDATE_ALIASES } from "./area-aliases.js";
import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "./area-aliases.js";
const DEFAULT_APP_ROOT = dirname(dirname(dirname(dirname(fileURLToPath(import.meta.url)))));
export { UPDATE_ALIASES } from "../parse/area-aliases.js";
import { AREA_ALIASES, normalizeCliArea, UPDATE_ALIASES } from "../parse/area-aliases.js";
type LocalCommand = (args: ParsedArgs, runtime: CliRuntime) => Promise<void>;
type CorpCommand = (args: ParsedArgs, corp: CorpConfig) => Promise<void>;
@@ -38,56 +38,56 @@ type ClientCommand = (args: ParsedArgs, corp: CorpConfig, client: KyInstance) =>
// Handler tables also define the known command surface. Imports stay lazy so
// local discovery never loads the tenant, Excel, or zip implementation graphs.
const LOCAL_COMMANDS: Record<string, LocalCommand> = {
"mcp-config": async () => (await import("./commands/mcp.js")).printMcpConfig(),
skill: async (args) => (await import("./commands/skill.js")).handleSkillCommand(args.command[1], args.command[2], args),
mcp: async (args) => (await import("./commands/mcp.js")).handleMcpCommand(args.command[1]),
probe: async (args) => (await import("./commands/probe.js")).handleProbeCommand(args.command[1], args.command[2], args),
doctor: async (args) => (await import("./commands/doctor.js")).handleDoctorCommand(args.command[1], args.command[2], args),
langfuse: async (args) => (await import("./commands/langfuse.js")).handleLangfuseCommand(args.command[1], args.command[2], args),
test: async (args) => (await import("./commands/test.js")).handleTestCommand(args.command[1], args.command[2], args),
config: async (args) => (await import("./commands/config.js")).handleConfigCommand(args.command[1], args.command[2], args),
"mcp-config": async () => (await import("../commands/mcp.js")).printMcpConfig(),
skill: async (args) => (await import("../commands/skill.js")).handleSkillCommand(args.command[1], args.command[2], args),
mcp: async (args) => (await import("../commands/mcp.js")).handleMcpCommand(args.command[1]),
probe: async (args) => (await import("../commands/probe.js")).handleProbeCommand(args.command[1], args.command[2], args),
doctor: async (args) => (await import("../commands/doctor.js")).handleDoctorCommand(args.command[1], args.command[2], args),
langfuse: async (args) => (await import("../commands/langfuse.js")).handleLangfuseCommand(args.command[1], args.command[2], args),
test: async (args) => (await import("../commands/test.js")).handleTestCommand(args.command[1], args.command[2], args),
config: async (args) => (await import("../commands/config.js")).handleConfigCommand(args.command[1], args.command[2], args),
update: dispatchUpdate,
changelog: dispatchUpdate,
corps: async (args) => {
const action = args.command[1];
// Local discovery must not initialize onboarding, sync or the capability registry.
if (!action || ["list", "search", "find"].includes(action)) {
await (await import("./commands/corps/overview.js")).handleCorpOverview(action, args.command[2], args);
await (await import("../commands/corps/overview.js")).handleCorpOverview(action, args.command[2], args);
return;
}
if (action === "regression" || action === "test-regression") {
await (await import("./commands/test.js")).handleTestCommand("regression", args.command[2], args);
await (await import("../commands/test.js")).handleTestCommand("regression", args.command[2], args);
return;
}
await (await import("./commands/corps.js")).handleCorpsCommand(action, args.command[2], args);
await (await import("../commands/corps.js")).handleCorpsCommand(action, args.command[2], args);
}
};
const CORP_COMMANDS: Record<string, CorpCommand> = {
source: async (args, corp) => (await import("./commands/source.js")).handleSourceCommand(args.command[1], corp),
auth: async (args, corp) => (await import("./commands/auth.js")).handleAuthCommand(args.command[1], corp, args)
source: async (args, corp) => (await import("../commands/source.js")).handleSourceCommand(args.command[1], corp),
auth: async (args, corp) => (await import("../commands/auth.js")).handleAuthCommand(args.command[1], corp, args)
};
const CLIENT_COMMANDS: Record<string, ClientCommand> = {
"users": async (args, corp, client) => (await import("./commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args),
"contacts": async (args, corp, client) => (await import("./commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
"data": async (args, corp, client) => (await import("./commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
"invoices": async (args, corp, client) => (await import("./commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
"expenses": async (args, corp, client) => (await import("./commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args),
"llm": async (args, corp, client) => (await import("./commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
"permissions": async (args, corp, client) => (await import("./commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
"billing": async (args, corp, client) => (await import("./commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
"webhook": async (args, corp, client) => (await import("./commands/webhook.js")).handleWebhookCommand(args.command[1], args.command[2], client, corp, args),
"context": async (args, corp, client) => (await import("./commands/context.js")).handleContextCommand(client, corp, args),
"documents": async (args, corp, client) => (await import("./commands/documents.js")).handleDocumentsCommand(args.command[1], args.command[2], client, corp, args),
"rules": async (args, corp, client) => (await import("./commands/rules.js")).handleRulesCommand(args.command[1], args.command[2], client, corp, args),
"approval-runs": async (args, corp, client) => (await import("./commands/approval-runs.js")).handleApprovalRunsCommand(args.command[1], args.command[2], client, corp, args),
"analytics": async (args, corp, client) => (await import("./commands/analytics.js")).handleAnalyticsCommand(args.command[1], args.command[2], client, corp, args),
"report": async (args, corp, client) => (await import("./commands/report.js")).handleReportCommand(args.command[1], client, corp, args),
"simulation": async (args, corp, client) => (await import("./commands/simulation.js")).handleSimulationCommand(args.command[1], args.command[2], client, corp, args),
"deploy": async (args, corp, client) => (await import("./commands/deploy.js")).handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args),
"hose-ebot": async (args, corp, client) => (await import("./commands/hose-ebot.js")).handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args),
"preference": async (args, corp, client) => (await import("./commands/preference.js")).handlePreferenceCommand(args.command[1], args.command[2], args.command[3], args.command[4], client, corp, args),
"users": async (args, corp, client) => (await import("../commands/users.js")).handleUsersCommand(args.command[1], args.command[2], client, corp, args),
"contacts": async (args, corp, client) => (await import("../commands/contacts.js")).handleContactsCommand(args.command[1], args.command[2], client, corp, args),
"data": async (args, corp, client) => (await import("../commands/data.js")).handleDataCommand(args.command[1], client, corp, args),
"invoices": async (args, corp, client) => (await import("../commands/invoices.js")).handleInvoicesCommand(args.command[1], args.command[2], client, corp, args),
"expenses": async (args, corp, client) => (await import("../commands/expenses.js")).handleExpensesCommand(args.command[1], client, corp, args),
"llm": async (args, corp, client) => (await import("../commands/llm.js")).handleLlmCommand(args.command[1], client, corp, args),
"permissions": async (args, corp, client) => (await import("../commands/permissions.js")).handlePermissionsCommand(args.command[1], client, corp, args),
"billing": async (args, corp, client) => (await import("../commands/billing.js")).handleBillingCommand(args.command[1], client, corp, args),
"webhook": async (args, corp, client) => (await import("../commands/webhook.js")).handleWebhookCommand(args.command[1], args.command[2], client, corp, args),
"context": async (args, corp, client) => (await import("../commands/context.js")).handleContextCommand(client, corp, args),
"documents": async (args, corp, client) => (await import("../commands/documents.js")).handleDocumentsCommand(args.command[1], args.command[2], client, corp, args),
"rules": async (args, corp, client) => (await import("../commands/rules.js")).handleRulesCommand(args.command[1], args.command[2], client, corp, args),
"approval-runs": async (args, corp, client) => (await import("../commands/approval-runs.js")).handleApprovalRunsCommand(args.command[1], args.command[2], client, corp, args),
"analytics": async (args, corp, client) => (await import("../commands/analytics.js")).handleAnalyticsCommand(args.command[1], args.command[2], client, corp, args),
"report": async (args, corp, client) => (await import("../commands/report.js")).handleReportCommand(args.command[1], client, corp, args),
"simulation": async (args, corp, client) => (await import("../commands/simulation.js")).handleSimulationCommand(args.command[1], args.command[2], client, corp, args),
"deploy": async (args, corp, client) => (await import("../commands/deploy.js")).handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args),
"hose-ebot": async (args, corp, client) => (await import("../commands/hose-ebot.js")).handleHoseEbotCommand(args.command[1], args.command[2], client, corp, args),
"preference": async (args, corp, client) => (await import("../commands/preference.js")).handlePreferenceCommand(args.command[1], args.command[2], args.command[3], args.command[4], client, corp, args),
};
export const KNOWN_AREAS = new Set([
@@ -97,7 +97,7 @@ export const KNOWN_AREAS = new Set([
...Object.keys(AREA_ALIASES)
]);
export type { CliResult, CliRunOptions } from "./types.js";
export type { CliResult, CliRunOptions } from "../types.js";
const STANDING_COMMANDS = new Set(["server", "mcp"]);
@@ -210,7 +210,7 @@ async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<vo
stringOption(args.options.tag) ??
(!isChangelog && !isCheck && !isBgSave && !isSystem && !isUser && action && !action.startsWith("-") ? action : undefined);
await (await import("./commands/update.js")).handleUpdateCommand(runtime, {
await (await import("../commands/update.js")).handleUpdateCommand(runtime, {
checkOnly: isCheck || isBgSave,
changelogOnly: isChangelog,
limit: numberOption(args.options.limit),
@@ -284,7 +284,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
) {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw usageError("Usage: seal-use webhook resource-pack preview <资源包.zip>");
await (await import("./commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
await (await import("../commands/webhook.js")).handleWebhookResourcePackPreview(filePath, materialPackFilePolicyOptions(args.options));
return;
}
@@ -298,7 +298,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
action === "review" ||
Boolean(args.options.ledger))
) {
await (await import("./commands/report.js")).handleLocalReportCommand(action, args);
await (await import("../commands/report.js")).handleLocalReportCommand(action, args);
return;
}
@@ -313,7 +313,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
if (area === "rules" && action === "lint" && ("file" in args.options || "f" in args.options)) {
let corp: CorpConfig;
try {
corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
corp = (await import("../helpers.js")).selectCorp(stringOption(args.options.corp));
} catch (error) {
// Local lint tolerates a missing enterprise config, but a disabled tenant
// is an explicit block: never degrade into the synthetic workspace corp.
@@ -324,7 +324,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
source: { type: "native" }
} as any;
}
await (await import("./commands/rules.js")).handleRulesCommand(action, maybeName, null, corp, args);
await (await import("../commands/rules.js")).handleRulesCommand(action, maybeName, null, corp, args);
return;
}
@@ -332,7 +332,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
area === "auth" &&
(action === "extract-keys" || action === "extract-key" || action === "extract-hose-keys" || action === "hose-extract-keys")
) {
await (await import("./commands/auth.js")).handleAuthExtractKeysCommand(maybeName, args);
await (await import("../commands/auth.js")).handleAuthExtractKeysCommand(maybeName, args);
return;
}
@@ -341,23 +341,23 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
(action === "link" || action === "seal-link") &&
("from-link" in args.options || maybeName === "from-link")
) {
await (await import("./commands/auth.js")).handleAuthCommand(action, null, args);
await (await import("../commands/auth.js")).handleAuthCommand(action, null, args);
return;
}
// Local task observation and previews must not authenticate or contact a tenant.
if (area === "approval-runs" && (action === "export" || action === "export-worker")) {
await (await import("./commands/approval-runs-export.js")).handleApprovalRunsExportCommand(args, runtime);
await (await import("../commands/approval-runs-export.js")).handleApprovalRunsExportCommand(args, runtime);
return;
}
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
const corp = (await import("../helpers.js")).selectCorp(stringOption(args.options.corp));
const maybePromptDivergences = async () => {
if (area === "report" && action === "review") return;
try {
const { countUnreviewedDivergences, shouldPromptDivergence } = await import(
"../domains/seal/reports/pipeline/review-store.js"
"../../domains/seal/reports/pipeline/review-store.js"
);
const count = countUnreviewedDivergences(corp.id, 30);
if (count > 0 && shouldPromptDivergence(corp.id)) {
@@ -379,7 +379,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
const clientCommand = CLIENT_COMMANDS[area];
if (clientCommand) {
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
const client = await (await import("../../core/http/factory.js")).createSealClient(corp);
await clientCommand(args, corp, client);
await maybePromptDivergences();
return;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { LauncherConfig } from "../core/runtime.js";
import type { LauncherConfig } from "../core/util/runtime.js";
export type ParsedArgs = {
command: string[];
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more