Compare commits

..
12 Commits
Author SHA1 Message Date
yunyingk 03189c072d Merge pull request #285 from yunyingk/codex/release-v0.11.21
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish GitHub Release (push) Canceled after 0s
Release v0.11.21: Automated release bump
2026-11-13 12:42:13 +08:00
gitea 1a023f9996 Release v0.11.21: Automated release bump 2026-11-13 12:40:58 +08:00
yunyingk 0ddd8283fe Merge pull request #284 from yunyingk/mac15/cli-langfuse-diagnose-ergonomics
Refactor: 优化 Langfuse 检索与审批单诊断的 CLI 人体工程学体验
2026-11-13 12:40:01 +08:00
gitea b980c60c3a Improve CLI ergonomics for Langfuse search and approval run diagnosis 2026-11-13 12:35:59 +08:00
yunyingk 67cd168ed4 Merge pull request #283 from yunyingk/mac15/fix-flow-error-attribution
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
fix(approval-runs): 不再把传输层失败当成业务结论
2026-11-10 19:49:37 +08:00
yunyingk 8bc1401eae Merge pull request #282 from yunyingk/mac15/fix-retired-flow-switch
fix(cli): 停止在用户可见面上宣传已退役的 --flow 拼写
2026-11-10 19:49:28 +08:00
yunyingk c572cba842 fix(approval-runs): 传输层失败不再被误判为业务结论
`sealApprovalRunFlowGet` 用两次"请求被拒"充当路由信号:记录查询被拒,就
认为入参是单号;运行记录列表被拒,就认为该单据没有 AI 记录。两处都写成
裸 `catch {}`,于是所有失败都被吸收进这两个业务结论。

后果不是偶尔不准,而是以十足的语气给出错误答案:token 过期、连接重置、
网关 5xx 会被渲染成「单据已删除」或「AI 从未审核」,用户没有任何线索去
怀疑刚才那次请求其实失败了;退出码同时失去语义,本该由 classifyCliError
产出 11(认证/上游失败),实际退化成一次"成功的查询"。

现在只有标识符形态的拒绝才计为未命中:HTTP 400/404/422,或响应体确实
到达但不是一条审批记录。认证失败、5xx、限流、以及根本没有响应的传输
错误一律原样上抛。

- errors:导出既有的 `responseStatus` 结构读取器,让调用方能区分"没有
  响应"与"收到了 400/404 响应"。
- approval-runs:新增 `isUpstreamLookupMiss`,替换两处裸 catch。
- test:新增四个回归用例(401/403/503/连接失败),断言原始错误对象抵达
  调用方;另加一条非合思租户的守卫用例。
2026-11-10 19:47:48 +08:00
yunyingk 71845c35e7 fix(cli): 不再在帮助与文档中暴露已退役的 --flow 拼写
`approval-runs get --flow` 至今仍是 `approval-runs hose-flow` 的静默遗留
别名:解析器的布尔标志白名单里还留着它,命令实现里也仍在转发。但 CLI
协议第 6 节要求兼容拼写只能停留在实现层,不得出现在 help、Skill、
references、README 或正常运行时提示中。

问题在于这条规矩被自己的文档破了:`get --help` 中 `--raw-json` 的描述写着
"incompatible with --summary, --fields and --flow",references 里同一句话也
照抄了一遍。用户只要撞上一次参数冲突,就会被 CLI 主动教一遍退役拼写。

- help:`--raw-json` 描述去掉 `--flow`,改为指向规范命令
  `approval-runs hose-flow <recordId|SN>`。
- approval-run-lightweight.md:同步修正,并补上原生合思流程时间线的入口。
- 运行时:冲突报错改为只列调用方实际传入的标志,不再主动广播退役拼写。
- naming-charter:新增裸 `--flow` 的边界守卫。原有
  LEGACY_SURFACE_TOKENS 是子串匹配,无法表达这个概念(`--flow-id`、
  `--flow-ids`、`--flow-concurrency` 都是规范参数),这正是该泄漏存活
  八个版本的根因。
2026-11-10 19:47:43 +08:00
yunyingk 8ecadbb124 Merge pull request #281 from yunyingk/codex/release-v0.11.20
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish GitHub Release (push) Canceled after 0s
chore: 发布 v0.11.20 补丁版本
2026-11-08 23:19:40 +08:00
gitea dec52cf5fa chore: 发布 v0.11.20 补丁版本 2026-11-08 23:18:00 +08:00
yunyingk b49e3a6ea0 Merge pull request #280 from yunyingk/mac15/tenant-disable-active-gate
feat: 新增租户 active 状态与统一禁用闸门
2026-11-08 12:53:31 +08:00
gitea 0ff3d9a313 feat: 新增租户 active 状态与统一禁用闸门 2026-11-08 12:52:05 +08:00
34 changed files with 1080 additions and 48 deletions

No files matched your search

+3
View File
@@ -15,6 +15,9 @@ tmp/
.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
.env
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.19",
"version": "0.11.21",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+16
View File
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.21] - 2026-11-13
### Added
- Merge pull request #284 from yunyingk/mac15/cli-langfuse-diagnose-ergonomics
- Improve CLI ergonomics for Langfuse search and approval run diagnosis
- Merge pull request #283 from yunyingk/mac15/fix-flow-error-attribution
- Merge pull request #282 from yunyingk/mac15/fix-retired-flow-switch
- fix(approval-runs): 传输层失败不再被误判为业务结论
- fix(cli): 不再在帮助与文档中暴露已退役的 --flow 拼写
## [0.11.20] - 2026-11-08
### Added
- 新增租户 active 状态与启用/禁用管理命令,统一阻止对已禁用租户执行操作;完善配置校验、CLI/MCP 闸门及使用文档。
## [0.11.19] - 2026-11-06
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.19",
"version": "0.11.21",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+4 -3
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.19: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.21: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.19
short-description: Seal tenant and Hose approval automation (v0.11.19)
version: 0.11.21
short-description: Seal tenant and Hose approval automation (v0.11.21)
---
# Seal Use
@@ -155,6 +155,7 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
| 导出审核记录 Excel、额外人工审批流、高级筛选或导出任务等待 | `references/approval-run-export.md` | 只查命令语法时读 `cli.md`;报告与复核台账走 `report-templates.md` |
| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` |
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
| 租户禁用/启用、企业已停用、命令提示「已禁用」 | `references/tenant-status.md` | 只查命令语法时读 `cli.md` |
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
| 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` |
@@ -76,7 +76,7 @@ seal-use approval-runs get <recordId> --raw-json --full --corp <corpId>
- `--raw-json` 保留上游响应的 JSON 结构(包括 `data` 包装、嵌套内容、新字段及上游同名字段),绕过审核记录的业务 schema 校验,不额外添加或覆盖字段。它仍只调用同一条只读审核详情接口,沿用企业认证和 HTTP 错误处理。
- 该模式解析并重新序列化 JSON,缩进等文本格式可能变化,不是 HTTP 响应的字节级副本。上游未返回的内容不会补查;无效 JSON、网络错误或 HTTP 失败仍按原协议报错。
- 输出不会静默截断。共享的 stdout 大小保护超过 200,000 字节时返回退出码 12;`--full` 或 `--output-file` 可输出完整内容。`--full` 只控制大小保护,不会绕过字段校验,也不会撤销 `--summary/--fields`。
- `--raw-json` 不能与 `--summary`、`--fields` 或 `--flow` 同用;这些参数会改写结构或切换接口,CLI 会以退出码 2 明确拒绝。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- `--raw-json` 不能与 `--summary` 或 `--fields` 同用;这两个参数会改写返回结构,CLI 会以退出码 2 明确拒绝。需要合思原生审批流时间线时,用 `seal-use approval-runs hose-flow <recordId|SN>`,不要从审核详情接口取。写入文件时 stdout 仅返回文件路径和字节数的 JSON 回执,原生响应保存在文件中。
- 不把兜底入口作为默认查询,也不将大段原生 JSON 直接贴给用户;Agent 可按需读取文件中的特定字段。
## Understand The Case First
+2
View File
@@ -46,6 +46,8 @@ seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--dry-run] [--confirm]
seal-use corps rename <corpId> --name <newName>
seal-use corps disable <corpId> [--dry-run] [--confirm]
seal-use corps enable <corpId> [--dry-run] [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
@@ -0,0 +1,56 @@
# 租户启用 / 禁用状态
适用信号:企业已停用、需要临时封禁某个租户、命令报「已禁用」、想确认禁用后还能不能搜到该企业。
## 状态定义
企业配置文件(`~/.config/seal-use/enterprises/*.json`)顶层的 `active` 字段:
```json
{
"id": "acme",
"name": "Acme Corporation",
"active": false,
"source": { "type": "hose", "...": "..." }
}
```
- 字段在**企业**上,不在 `source` 里。合思来源(`type: "hose"`)与 Seal 本源(`type: "seal"`)共用同一个开关,行为完全一致,不存在某一来源例外。
- **字段缺失 = 启用**。旧配置零迁移;读取和任何配置更新都会把缺省值物化成显式的 `active: true`。
- **字段值非法 = 禁用(fail-closed)**。`"false"` 字符串、`null`、`0`、对象等任何非布尔值都归一化为 `active: false`。配置文件**不会**被丢弃,企业仍可检索并显示 `active: false`,指向它的命令一律阻断,stderr 告警并给出修复命令。绝不会把写坏的值当成启用。
- 显式 `active: false` = 禁用。不要靠删除配置文件、改文件名或清空凭据来「禁用」,那会破坏检索可见性与恢复路径。
## 命令
```bash
seal-use corps disable <corpId> --dry-run # 预览,不写文件
seal-use corps disable <corpId> --confirm # 实际禁用
seal-use corps enable <corpId> --confirm # 恢复
```
- 不加 `--confirm` / `--yes` 会返回退出码 `10`(确认门)。
- `--dry-run` 返回 `preview: true` 与 `changesDiff: { before, after }`,不写配置。
- 这两个命令是**唯一**能解析禁用企业的命令;没有它们,禁用后无法恢复。
## 行为口径(严格遵守)
| 场景 | 结果 |
| --- | --- |
| `corps list` / `corps search` / `corps find` | 禁用企业**仍可检索**,输出带 `active: false`。禁用不影响搜索可见性 |
| 任何显式指定该企业 ID 的命令 | **统一阻断、不执行**,退出码 `14`,stderr 提示 `seal-use corps enable <corpId> --confirm` |
| `corps enable` / `corps disable` | 允许执行(唯一豁免) |
阻断发生在企业解析处(`resolveCorpConfig`),早于创建 HTTP client、认证续期和任何业务 handler,因此不会有网络请求或副作用。覆盖:
- CLI 所有 `--corp <id>` 与位置参数形式(查询、写操作、绑定、同步、诊断、本地导出任务);
- MCP 的 `seal_use` 与 `seal_use_write` 两个网关;
- stateful 模式下 `defaultCorpId` 指向禁用企业、或无显式 ID 时兜底命中的第一个企业;
- webhook 重放的 `--source-corp` / `--target-corp` 以及能力注册表中的等价解析;
- 本地 `rules lint --file` 与 `report --ledger` 的降级分支不会吞掉该阻断。
## 排查步骤
1. `seal-use corps search <关键词>` 确认企业仍在列表中并读取 `active` 字段。
2. 若确需操作该企业:`seal-use corps enable <corpId> --confirm`。这个值非法时同样有效——该命令会把字段重写为 `true`,一并修复坏配置。
3. 若确需保持禁用,不要绕过闸门(不要直接改 ID、不要复制配置换新 ID)。解除封禁是唯一正当路径。
4. 退出码 `14` 属安全守卫拦截,不是认证失败(`11`)或参数错误(`2`)。若看到 `13`「No enterprise config found」,说明整个配置文件被跳过(JSON 格式错误或必填字段缺失),与本开关无关。详见 `references/cli.md`。
+3
View File
@@ -102,6 +102,9 @@ describe("approval run native JSON fallback", () => {
expect(result.exitCode).toBe(2)
expect(result.stdout).toBe("")
expect(result.stderr).toContain("--raw-json cannot be combined")
// The message names only what the caller actually passed, so the retired
// `--flow` spelling is never advertised to anyone who did not use it.
expect(result.stderr).toContain(flags[0]!)
}
expect(requests).toHaveLength(0)
})
+13 -6
View File
@@ -187,11 +187,18 @@ export async function handleApprovalRunsCommand(
}
if (action === "get") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw new Error("Missing approval run recordId");
const rawJson = booleanOption(args.options["raw-json"]) ?? booleanOption(args.options.rawJson);
if (rawJson && (booleanOption(args.options.flow) || booleanOption(args.options.summary) || stringOption(args.options.fields) !== undefined)) {
throw usageError("--raw-json cannot be combined with --flow, --summary or --fields");
if (rawJson) {
// Name only the flags the caller actually passed: legacy spellings stay
// implementation-only and must not be advertised to everyone else.
const conflicts = [
booleanOption(args.options.flow) ? "--flow" : undefined,
booleanOption(args.options.summary) ? "--summary" : undefined,
stringOption(args.options.fields) !== undefined ? "--fields" : undefined
].filter((flag): flag is string => flag !== undefined);
if (conflicts.length) throw usageError(`--raw-json cannot be combined with ${conflicts.join(", ")}`);
}
if (booleanOption(args.options.flow)) {
await runCapability(
@@ -219,21 +226,21 @@ export async function handleApprovalRunsCommand(
}
if (action === "cited-rules") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw usageError("Usage: seal-use approval-runs cited-rules <recordId>");
await runCapability("sealApprovalRunCitedRulesGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "document-summary") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
if (!recordId) throw usageError("Usage: seal-use approval-runs document-summary <recordId>");
await runCapability("sealApprovalRunDocumentSummaryGet", client, corp, { recordId }, outputOptions(args.options));
return;
}
if (action === "diagnose") {
const recordId = args.command[2];
const recordId = args.command[2] ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id);
const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]);
if (!recordId && !sn) {
throw usageError("Usage: seal-use approval-runs diagnose <recordId>|--sn <documentSN> [--full] [--corp <corpId>]");
+2
View File
@@ -1,4 +1,5 @@
import { usageError } from "../../core/errors.js";
import { handleCorpActive } from "./corps/active.js";
import { handleCorpBindings } from "./corps/bindings.js";
import { handleCorpOnboarding, extractKeysFromLinkAction, showCorpKeysAction } from "./corps/onboarding.js";
import { handleCorpOverview } from "./corps/overview.js";
@@ -14,6 +15,7 @@ export async function handleCorpsCommand(
args: ParsedArgs
) {
if (await handleCorpOverview(action, maybeName, args)) return;
if (await handleCorpActive(action, maybeName, args)) return;
if (await handleCorpBindings(action, maybeName, args)) return;
if (await handleCorpSync(action, maybeName, args)) return;
if (await handleCorpOnboarding(action, maybeName, args)) return;
+63
View File
@@ -0,0 +1,63 @@
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 type { ParsedArgs } from "../../types.js";
/**
* Tenant availability switch for both `hose` and `seal` sources.
*
* This is the ONLY command surface allowed to resolve a disabled tenant: without
* it, `corps enable` could not restore an enterprise that the gate now blocks.
* All other commands resolve through `selectCorp()` and are refused upstream.
*/
export async function handleCorpActive(
action: string | undefined,
maybeName: string | undefined,
args: ParsedArgs
): Promise<boolean> {
if (action !== "disable" && action !== "enable") return false;
const corpId = maybeName ?? stringOption(args.options.corp);
if (!corpId) {
throw usageError(`Usage: seal-use corps ${action} <corpId> [--dry-run] [--confirm]`);
}
const targetActive = action === "enable";
const { selectCorp } = await import("../../helpers.js");
const corp = selectCorp(corpId, { allowDisabled: true });
const previousActive = corp.active ?? true;
if (dryRunOption(args)) {
printJson({
preview: true,
dryRun: true,
mutation: `corps ${action}`,
corpId: corp.id,
corpName: corp.name,
sourceType: corp.source.type,
changesDiff: { before: previousActive, after: targetActive },
note: "禁用只阻断显式指定该企业 ID 的命令,不影响 corps list/search 的检索可见性。"
});
return true;
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to ${action} enterprise '${corp.name}' (${corp.id}) without --confirm.`,
`seal-use corps ${action} ${corp.id} --confirm`
);
}
const updated = updateCorpConfig(corp.id, { active: targetActive });
printJson({
success: true,
id: updated.id,
name: updated.name,
sourceType: updated.source.type,
active: updated.active,
previousActive
});
return true;
}
+6
View File
@@ -35,6 +35,9 @@ export async function handleCorpOverview(
}
const corpId = stringOption(args.options.corp);
// Deliberately NOT filtered by `active`: disabling a tenant gates command
// execution at corp resolution, never discovery. Keep disabled enterprises
// searchable for both `hose` and `seal` sources and just surface the flag.
const allCorps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
const currentCorpId = corpId ?? (
@@ -88,6 +91,7 @@ export async function handleCorpOverview(
printJson(displayList.map((item) => ({
id: item.id,
name: item.name,
active: item.active ?? true,
environment: item.environment ?? "production",
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
@@ -113,6 +117,7 @@ export async function handleCorpOverview(
printJson({
id: corp.id,
name: corp.name,
active: corp.active ?? true,
environment: corp.environment ?? "production",
configFile,
seal: {
@@ -139,6 +144,7 @@ export async function handleCorpOverview(
printJson({
id: corp.id,
name: corp.name,
active: corp.active ?? true,
environment: corp.environment ?? "production",
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type,
@@ -0,0 +1,291 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../../runner.js";
import { selectCorp } from "../../helpers.js";
import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { resolveReplayCorpPair } from "../../../domains/seal/replay/webhook.js";
const ENV_KEYS = [
"SEAL_USE_ENTERPRISES_DIR",
"SEAL_USE_CONFIG_FILE",
"SEAL_USE_TOKEN_STORE",
"SEAL_USE_USAGE_FILE",
"SEAL_DISABLE_BG_UPDATE"
] as const;
const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
for (const key of ENV_KEYS) {
const value = ORIGINAL_ENV[key];
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const SOURCE_VARIANTS = [
{
label: "hose",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://acme.sealai.cc"
}
}
] as const;
function setup(): { root: string; enterprises: string } {
const root = mkdtempSync(join(tmpdir(), "seal-tenant-active-"));
tempDirs.push(root);
const enterprises = join(root, "enterprises");
mkdirSync(enterprises, { recursive: true });
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_USE_USAGE_FILE = join(root, "usage.json");
process.env.SEAL_DISABLE_BG_UPDATE = "1";
return { root, enterprises };
}
function writeCorp(
dir: string,
options: {
id: string;
name: string;
source: Record<string, unknown>;
active?: unknown;
}
): string {
const payload: Record<string, unknown> = {
id: options.id,
name: options.name,
source: options.source,
seal: { url: "https://acme.sealai.cc" },
auth: { refreshTtl: 300 }
};
if (options.active !== undefined) payload.active = options.active;
const path = join(dir, `${options.id}.json`);
writeFileSync(path, JSON.stringify(payload));
return path;
}
function corpFile(dir: string, id: string): Record<string, unknown> {
return JSON.parse(readFileSync(join(dir, `${id}.json`), "utf-8"));
}
/** Fail loudly if a command reaches any upstream API: a blocked command must never execute. */
function guardNetwork(): { calls: () => number } {
let calls = 0;
globalThis.fetch = (async () => {
calls += 1;
throw new Error("network request must not happen for a disabled tenant");
}) as unknown as typeof globalThis.fetch;
return { calls: () => calls };
}
/** Commands that explicitly name the tenant id, spanning local/corp/client handlers. */
function commandsNamingCorp(id: string): string[][] {
return [
["corps", "get", id],
["corps", "current", "--corp", id],
["corps", "mark", id, "--env", "test"],
["corps", "rename", id, "--name", "Renamed"],
["contacts", "departments", "--corp", id],
["rules", "list", "--corp", id],
["documents", "list", "--corp", id],
["billing", "status", "--corp", id],
["webhook", "list", "--corp", id],
["source", "config", "--corp", id],
["auth", "status", "--corp", id]
];
}
describe("tenant active state: both sources share one gate", () => {
for (const { label, source } of SOURCE_VARIANTS) {
const id = `acme-${label}`;
const name = `Acme ${label} Corporation`;
test(`${label}: disabled tenant stays visible in corps list and search`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
const listed = await runCli(["corps", "list", "--all"]);
expect(listed.exitCode).toBe(0);
expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({
id, name, active: false, sourceType: label
}));
const searched = await runCli(["corps", "search", "Acme", "--strict"]);
expect(searched.exitCode).toBe(0);
const matches = JSON.parse(searched.stdout) as Array<{ id: string; active: boolean }>;
expect(matches.find((item) => item.id === id)).toMatchObject({ id, active: false });
});
test(`${label}: every command explicitly naming the disabled tenant is blocked without executing`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
const network = guardNetwork();
for (const command of commandsNamingCorp(id)) {
const result = await runCli(command);
expect({ command, exitCode: result.exitCode }).toEqual({ command, exitCode: 14 });
expect(result.isError).toBe(true);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("已禁用");
expect(result.stderr).toContain(`seal-use corps enable ${id}`);
}
expect(network.calls()).toBe(0);
});
test(`${label}: a malformed active value fails closed without hiding the enterprise`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: "false" });
const network = guardNetwork();
const listed = await runCli(["corps", "list", "--all"]);
expect(listed.exitCode).toBe(0);
expect(JSON.parse(listed.stdout)).toContainEqual(expect.objectContaining({
id, name, active: false, sourceType: label
}));
expect(listed.stderr).toContain("active 字段值非法");
// The block reports a disabled tenant (14), not a missing config (13),
// and the enterprise never disappears from discovery.
const blocked = await runCli(["corps", "get", id]);
expect(blocked.exitCode).toBe(14);
expect(blocked.stdout).toBe("");
expect(blocked.stderr).toContain("已禁用");
expect(network.calls()).toBe(0);
const recovered = await runCli(["corps", "enable", id, "--confirm"]);
expect(recovered.exitCode).toBe(0);
expect(corpFile(enterprises, id).active).toBe(true);
});
test(`${label}: an active tenant with the same source still runs through corp resolution`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: true });
const result = await runCli(["corps", "get", id]);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({ id, active: true });
});
test(`${label}: disable/enable lifecycle with dry-run and confirmation gate`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source });
const preview = await runCli(["corps", "disable", id, "--dry-run"]);
expect(preview.exitCode).toBe(0);
expect(JSON.parse(preview.stdout)).toMatchObject({
preview: true,
dryRun: true,
mutation: "corps disable",
corpId: id,
sourceType: label,
changesDiff: { before: true, after: false }
});
expect(corpFile(enterprises, id).active).toBeUndefined();
const unconfirmed = await runCli(["corps", "disable", id]);
expect(unconfirmed.exitCode).toBe(10);
expect(corpFile(enterprises, id).active).toBeUndefined();
const disabled = await runCli(["corps", "disable", id, "--confirm"]);
expect(disabled.exitCode).toBe(0);
expect(JSON.parse(disabled.stdout)).toMatchObject({ id, active: false, previousActive: true });
expect(corpFile(enterprises, id).active).toBe(false);
// Re-enabling must work even though the tenant is disabled: this is the
// single documented exemption from the block.
const enabled = await runCli(["corps", "enable", id, "--confirm"]);
expect(enabled.exitCode).toBe(0);
expect(JSON.parse(enabled.stdout)).toMatchObject({ id, active: true, previousActive: false });
expect(corpFile(enterprises, id).active).toBe(true);
const afterEnable = await runCli(["corps", "get", id]);
expect(afterEnable.exitCode).toBe(0);
});
test(`${label}: a stateful default pointing at a disabled tenant is blocked`, async () => {
const { root, enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
writeFileSync(join(root, "config.json"), JSON.stringify({
stateful: true,
defaultCorpId: id
}));
const network = guardNetwork();
const result = await runCli(["contacts", "departments"]);
expect(result.exitCode).toBe(14);
expect(result.stdout).toBe("");
expect(network.calls()).toBe(0);
});
test(`${label}: replay refuses a disabled source or target corp through both selectors`, () => {
const { enterprises } = setup();
const activeId = `active-${label}`;
const disabledId = `off-${label}`;
writeCorp(enterprises, { id: activeId, name: "Active Corp", source, active: true });
writeCorp(enterprises, { id: disabledId, name: "Disabled Corp", source, active: false });
const activeCorp = selectCorp(activeId);
// CLI replay path: `selectCorp` is passed straight into resolveReplayCorpPair.
expect(() => resolveReplayCorpPair(
{ sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true },
selectCorp
)).toThrow("已禁用");
expect(() => resolveReplayCorpPair(
{ sourceCorpId: disabledId, targetCorpId: activeId, activeCorp, force: true },
selectCorp
)).toThrow("已禁用");
// Capability registry replay path builds its own resolveCorpConfig selector.
const capabilitySelector = (id?: string) => resolveCorpConfig(
loadCorpConfigs(),
{
stateful: loadGlobalConfig().stateful,
defaultCorpId: loadGlobalConfig().defaultCorpId,
corpId: id
},
getEnterprisesDirCandidates()
);
expect(() => resolveReplayCorpPair(
{ sourceCorpId: activeId, targetCorpId: disabledId, activeCorp, force: true },
capabilitySelector
)).toThrow("已禁用");
});
test(`${label}: local lint/ledger fallbacks cannot swallow a disabled-tenant block`, async () => {
const { enterprises } = setup();
writeCorp(enterprises, { id, name, source, active: false });
const lint = await runCli(["rules", "lint", "--file", "rules.json", "--corp", id]);
expect(lint.exitCode).toBe(14);
expect(lint.stderr).toContain("已禁用");
const ledger = await runCli(["report", "validate", "--ledger", "ledger.xlsx", "--corp", id]);
expect(ledger.exitCode).toBe(14);
expect(ledger.stderr).toContain("已禁用");
});
}
});
+6 -1
View File
@@ -20,7 +20,12 @@ export async function handleLangfuseCommand(
const options = args.options;
const out = outputOptions(options);
const traceId = () => maybeName ?? stringOption(options["trace-id"]);
const refreshIfMissing = () => booleanOption(options["refresh-if-missing"]);
const refreshIfMissing = () => {
if (booleanOption(options["no-refresh"]) || booleanOption(options.offline)) return false;
const explicit = booleanOption(options["refresh-if-missing"]);
if (explicit !== undefined) return explicit;
return true;
};
if (action === "check") {
await runLangfuseCapability("sealLangfuseConnectionCheck", {}, out);
+5 -1
View File
@@ -6,6 +6,7 @@ import { runCapabilityResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
import { CliError, usageError } from "../../core/errors.js";
import { isCorpDisabledError } from "../../core/config/active.js";
import {
BUILTIN_MONTHLY_TEMPLATE,
exportReportPackage,
@@ -36,7 +37,10 @@ export async function handleLocalReportCommand(action: string | undefined, args:
try {
const { selectCorp } = await import("../helpers.js");
corp = selectCorp(corpId);
} catch {
} catch (error) {
// Ledger/review work is tenant-free, but if the caller explicitly named a
// disabled enterprise, the block must still stand instead of falling back.
if (isCorpDisabledError(error)) throw error;
corp = {
corpId,
id: corpId,
+23 -1
View File
@@ -98,6 +98,28 @@ export const HELP_REGISTRY: AreaHelp[] = [
],
description: "Safely updates the display name of a configured enterprise without modifying underlying files manually."
},
{
name: "disable",
group: "企业配置",
summary: "Disable a tenant without removing it from enterprise search",
usage: ["seal-use corps disable <corpId> [--dry-run] [--confirm]"],
options: [
{ flag: "--dry-run", description: "Preview the active-state change without writing local config" },
{ flag: "--confirm", description: "Confirm the state change (required for live execution)" }
],
description: "Sets active=false on a Hose or Seal enterprise. The enterprise stays visible in `corps list/search`, but every command that explicitly resolves its ID is refused until it is enabled again."
},
{
name: "enable",
group: "企业配置",
summary: "Re-enable a disabled tenant",
usage: ["seal-use corps enable <corpId> [--dry-run] [--confirm]"],
options: [
{ flag: "--dry-run", description: "Preview the active-state change without writing local config" },
{ flag: "--confirm", description: "Confirm the state change (required for live execution)" }
],
description: "Sets active=true. This is the only command allowed to resolve a disabled enterprise, so a disabled tenant can always be restored."
},
{
name: "bind-test",
group: "测试配对与验证",
@@ -556,7 +578,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
summary: "Get detailed approval record payload",
usage: ["seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--raw-json] [--full] [--output-file file.json] [--corp <corpId>]"],
options: [
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary, --fields and --flow" },
{ flag: "--raw-json", description: "Compatibility fallback: return the upstream JSON response including its envelope and unknown fields, without business-schema validation or derived fields; incompatible with --summary and --fields. Native Hose flow timeline lives in `seal-use approval-runs hose-flow <recordId|SN>`" },
{ flag: "--full", description: "Bypass the shared 200,000-byte stdout size guard; this does not change payload structure" },
{ flag: "--output-file <path>", description: "Write the complete JSON payload to a file, bypassing the stdout size guard" }
]
+3 -2
View File
@@ -10,7 +10,7 @@ import type { CorpConfig, GlobalConfig } from "../core/config/types.js";
import { printJson } from "./printer.js";
import type { OutputOptions } from "./types.js";
export function selectCorp(corpId?: string): CorpConfig {
export function selectCorp(corpId?: string, options: { allowDisabled?: boolean } = {}): CorpConfig {
const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
const corp = resolveCorpConfig(
@@ -18,7 +18,8 @@ export function selectCorp(corpId?: string): CorpConfig {
{
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId,
corpId
corpId,
allowDisabled: options.allowDisabled
},
getEnterprisesDirCandidates()
);
+10
View File
@@ -76,6 +76,16 @@ describe("naming charter: visible help surface", () => {
const offenders = LEGACY_SURFACE_TOKENS.filter((token) => serialized.includes(token));
expect(offenders).toEqual([]);
});
test("never documents the retired bare flow switch", () => {
// `--flow` on `approval-runs get` is a silent legacy alias for
// `approval-runs hose-flow`, so the visible surface must not name it.
// LEGACY_SURFACE_TOKENS matches by substring and cannot express this:
// `--flow-id`, `--flow-ids` and `--flow-concurrency` are canonical.
const serialized = JSON.stringify(HELP_REGISTRY);
const offenders = serialized.match(/--flow(?![A-Za-z0-9-])/g) ?? [];
expect(offenders).toEqual([]);
});
});
describe("naming charter: parser accepts canonical and legacy spellings", () => {
+5 -1
View File
@@ -6,6 +6,7 @@ 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 {
booleanOption,
materialPackFilePolicyOptions,
@@ -313,7 +314,10 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
let corp: CorpConfig;
try {
corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
} catch {
} catch (error) {
// Local lint tolerates a missing enterprise config, but a disabled tenant
// is an explicit block: never degrade into the synthetic workspace corp.
if (isCorpDisabledError(error)) throw error;
corp = {
id: "local",
name: "Local Workspace",
+38
View File
@@ -0,0 +1,38 @@
import { CliError, safetyBlocked } from "../errors.js";
import type { CorpConfig } from "./types.js";
/** `safetyBlocked` exit code. Shared so local command fallbacks can re-throw this block. */
export const CORP_DISABLED_EXIT_CODE = 14;
/**
* Legacy configs and `as CorpConfig` fixtures omit `active`. Only an explicit
* `false` disables a tenant, so nothing that never set the field can be blocked
* by accident.
*/
export function isCorpActive(corp: CorpConfig): boolean {
return corp.active !== false;
}
/**
* The single tenant gate. `resolveCorpConfig` calls this on every resolution
* path (explicit `--corp`, stateful default, first-corp fallback, replay
* source/target resolution, background export workers), which is what makes the
* block uniform across the CLI and both MCP gateways.
*
* `corps enable` / `corps disable` resolve with `allowDisabled: true`; they are
* the only commands that may touch a disabled tenant, otherwise a disabled
* tenant could never be restored.
*/
export function assertCorpActive(corp: CorpConfig): void {
if (isCorpActive(corp)) return;
throw safetyBlocked(
`企业「${corp.name}」(${corp.id}) 已禁用,命令未执行。启用后才能继续对该企业执行操作。`,
`seal-use corps enable ${corp.id} --confirm`
);
}
/** True for the structured block thrown by {@link assertCorpActive}. */
export function isCorpDisabledError(error: unknown): error is CliError {
return error instanceof CliError && error.exitCode === CORP_DISABLED_EXIT_CODE;
}
+74
View File
@@ -300,6 +300,80 @@ describe("loadCorpConfigs", () => {
});
});
describe("loadCorpConfigs tenant active materialization", () => {
const sources = [
{
label: "hose",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: { type: "seal", token: "seal-token", sealUrl: "https://seal.sealai.cc" }
}
];
test("materializes active=true for legacy configs of both sources and keeps explicit false", () => {
const dir = makeTempDir();
for (const { label, source } of sources) {
writeFileSync(join(dir, `${label}-legacy.json`), JSON.stringify({
id: `${label}-legacy`, name: `${label} Legacy`, source
}));
writeFileSync(join(dir, `${label}-disabled.json`), JSON.stringify({
id: `${label}-disabled`, name: `${label} Disabled`, active: false, source
}));
}
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
const byId = new Map(loadCorpConfigs().map((item) => [item.id, item]));
for (const { label } of sources) {
expect(byId.get(`${label}-legacy`)?.active).toBe(true);
expect(byId.get(`${label}-disabled`)?.active).toBe(false);
}
});
test("a malformed active value loads as disabled without dropping the enterprise", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
for (const { label, source } of sources) {
writeFileSync(join(dir, `${label}-malformed.json`), JSON.stringify({
id: `${label}-malformed`, name: `${label} Malformed`, active: "false", source
}));
}
const byId = new Map(loadCorpConfigs().map((item) => [item.id, item]));
for (const { label } of sources) {
expect(byId.has(`${label}-malformed`)).toBe(true);
expect(byId.get(`${label}-malformed`)?.active).toBe(false);
}
// Fail-closed is NOT a parse failure: the file must never be skipped.
expect(getLastCorpConfigLoadIssues()).toEqual([]);
});
test("updateCorpConfig writes an explicit active value for both sources", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
for (const { label, source } of sources) {
writeFileSync(join(dir, `${label}-update.json`), JSON.stringify({
id: `${label}-update`, name: `${label} Update`, source
}));
const updated = updateCorpConfig(`${label}-update`, { active: false });
expect(updated.active).toBe(false);
expect(JSON.parse(readFileSync(join(dir, `${label}-update.json`), "utf-8")).active).toBe(false);
const restored = updateCorpConfig(`${label}-update`, { active: true });
expect(restored.active).toBe(true);
expect(JSON.parse(readFileSync(join(dir, `${label}-update.json`), "utf-8")).active).toBe(true);
}
});
});
describe("syncLegacyEnterprisesDir", () => {
test("migrates files from legacy to primary and deletes legacy when > 7 days old", () => {
const primary = makeTempDir();
+36 -3
View File
@@ -93,6 +93,9 @@ let lastCorpLoadIssues: CorpConfigLoadIssue[] = [];
// Files already warned about this process: loadCorpConfigs runs several times
// per invocation (selection, dispatch, tool handlers), so warn each file once.
const warnedCorpFiles = new Set<string>();
// A malformed `active` value is normalized to disabled instead of dropping the
// whole file. Track those separately so the warning names the right remedy.
const warnedActiveCorpFiles = new Set<string>();
/**
* Issues from the most recent loadCorpConfigs() call. A malformed file must not
@@ -112,6 +115,7 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
const dirs = resolveEnterprisesDirs();
const byId = new Map<string, { config: CorpConfig; path: string }>();
const issues: CorpConfigLoadIssue[] = [];
const activeWarnings: Array<{ dir: string; file: string; corpId: string }> = [];
for (const dir of dirs) {
for (const file of readdirSync(dir)
@@ -119,13 +123,26 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
.filter((item) => !item.startsWith("example."))) {
const fullPath = join(dir, file);
let corp: CorpConfig;
let activeMalformed = false;
try {
const content = readFileSync(fullPath, "utf-8");
corp = CorpConfigSchema.parse(JSON.parse(content));
const raw = JSON.parse(content) as Record<string, unknown>;
const parsed = CorpConfigSchema.parse(raw);
// `CorpConfigSchema.active` is fail-closed: a non-boolean value parses
// to `false` instead of rejecting the file. Detect it here so the user
// learns why the tenant became unusable and how to fix it.
activeMalformed = "active" in raw && typeof raw.active !== "boolean";
// Materialize the tenant availability default so every config read from
// disk carries an explicit boolean. Legacy files without `active` stay
// enabled; `false` (explicit or normalized) gates command execution.
corp = { ...parsed, active: parsed.active ?? true };
} catch (error) {
issues.push({ dir, file, reason: error instanceof Error ? error.message : String(error) });
continue;
}
if (activeMalformed) {
activeWarnings.push({ dir, file, corpId: corp.id });
}
byId.set(corp.id, { config: corp, path: fullPath });
}
}
@@ -144,6 +161,19 @@ function loadCorpConfigEntries(): Array<{ config: CorpConfig; path: string }> {
console.error(`👉 Next action: seal-use doctor (检查配置文件格式与权限)`);
}
const freshActive = activeWarnings.filter((item) => {
const key = `${item.dir}/${item.file}`;
if (warnedActiveCorpFiles.has(key)) return false;
warnedActiveCorpFiles.add(key);
return true;
});
for (const item of freshActive) {
console.error(
`⚠️ 企业配置 ${item.dir}/${item.file} 的 active 字段值非法(只能是 true/false),企业 ${item.corpId} 已按禁用处理;仍可检索,但指向它的命令会被阻断。`
);
console.error(`👉 Next action: seal-use corps enable ${item.corpId} --confirm (或把配置修正为 "active": true)`);
}
return Array.from(byId.values());
}
@@ -268,6 +298,9 @@ export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): Co
}
}
const validated = CorpConfigSchema.parse(merged);
writeSecureFile(filePath, `${JSON.stringify(validated, null, 2)}\n`);
return validated;
// Keep `active` explicit on disk after any config update (including ones that
// predate the field), matching the materialized value from loadCorpConfigs().
const normalized: CorpConfig = { ...validated, active: validated.active ?? true };
writeSecureFile(filePath, `${JSON.stringify(normalized, null, 2)}\n`);
return normalized;
}
+81
View File
@@ -1,4 +1,6 @@
import { describe, expect, test } from "bun:test";
import { CliError } from "../errors.js";
import { isCorpActive } from "./active.js";
import { CorpConfig } from "./types.js";
import { CorpContext, resolveCorpConfig } from "./manager.js";
@@ -99,3 +101,82 @@ describe("resolveCorpConfig", () => {
).id).toBe("corp-b");
});
});
describe("resolveCorpConfig tenant gate", () => {
const variants: Array<{ label: string; source: CorpConfig["source"] }> = [
{
label: "hose",
source: {
type: "hose",
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: {
type: "seal",
token: "seal-token",
sealUrl: "https://off.sealai.cc",
expiresIn: 3600,
staffId: "seal"
}
}
];
const withSource = (id: string, source: CorpConfig["source"], active?: boolean): CorpConfig =>
({ ...corp(id), source, active });
for (const { label, source } of variants) {
test(`${label}: blocks an explicitly disabled corp with exit 14 and a recovery hint`, () => {
const disabled = withSource("off", source, false);
expect(isCorpActive(disabled)).toBe(false);
let caught: unknown;
try {
resolveCorpConfig([disabled], { stateful: false, corpId: "off" });
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(CliError);
expect((caught as CliError).exitCode).toBe(14);
expect((caught as CliError).message).toContain("已禁用");
expect((caught as CliError).nextAction).toContain("seal-use corps enable off");
});
test(`${label}: blocks case-insensitive and by-name resolution of a disabled corp`, () => {
const disabled = { ...withSource("Off-Corp", source, false), name: "Disabled Corp" };
expect(() => resolveCorpConfig([disabled], { stateful: false, corpId: "off-corp" })).toThrow("已禁用");
expect(() => resolveCorpConfig([disabled], { stateful: false, corpId: "disabled corp" })).toThrow("已禁用");
});
test(`${label}: blocks a disabled stateful default and first-corp fallback`, () => {
const disabled = withSource("off", source, false);
expect(() => resolveCorpConfig(
[disabled, corp("on")],
{ stateful: true, defaultCorpId: "off" }
)).toThrow("已禁用");
expect(() => resolveCorpConfig([disabled, corp("on")], { stateful: true })).toThrow("已禁用");
});
test(`${label}: allowDisabled resolves a disabled corp for status management only`, () => {
const disabled = withSource("off", source, false);
expect(resolveCorpConfig(
[disabled], { stateful: false, corpId: "off", allowDisabled: true }
).id).toBe("off");
});
test(`${label}: an active corp is unaffected by a disabled one in the same directory`, () => {
const disabled = withSource("off", source, false);
const enabled = withSource("on", source, true);
expect(resolveCorpConfig(
[disabled, enabled], { stateful: false, corpId: "on" }
).id).toBe("on");
expect(resolveCorpConfig([corp("legacy")], { stateful: false, corpId: "legacy" }).id).toBe("legacy");
});
}
});
+20 -5
View File
@@ -1,11 +1,26 @@
import { validationError } from "../errors.js";
import { assertCorpActive } from "./active.js";
import { CorpConfig, GlobalConfig } from "./types.js";
export type CorpResolveOptions = Pick<GlobalConfig, "stateful" | "defaultCorpId"> & {
corpId?: string;
/** Only the tenant status-management commands (`corps enable/disable`) may resolve a disabled corp. */
allowDisabled?: boolean;
};
export function resolveCorpConfig(
corps: CorpConfig[],
options: Pick<GlobalConfig, "stateful" | "defaultCorpId"> & { corpId?: string },
options: CorpResolveOptions,
candidates: string[] = []
): CorpConfig {
// Every successful lookup passes through the same gate. This is the single
// choke point for CLI commands, MCP gateway commands, replay source/target
// resolution and background workers — a disabled tenant is never executable.
const accept = (found: CorpConfig): CorpConfig => {
if (!options.allowDisabled) assertCorpActive(found);
return found;
};
const requestedCorpId = options.corpId?.trim() || undefined;
const configuredCorpId = options.stateful
? options.defaultCorpId?.trim() || undefined
@@ -14,11 +29,11 @@ export function resolveCorpConfig(
if (selectedCorpId) {
const exact = corps.find((item) => item.id === selectedCorpId);
if (exact) return exact;
if (exact) return accept(exact);
const caseInsensitive = corps.find((item) => item.id.toLowerCase() === selectedCorpId.toLowerCase());
if (caseInsensitive) return caseInsensitive;
if (caseInsensitive) return accept(caseInsensitive);
const byName = corps.find((item) => item.name.toLowerCase() === selectedCorpId.toLowerCase());
if (byName) return byName;
if (byName) return accept(byName);
throw validationError(`No enterprise config found for ${selectedCorpId}`);
}
@@ -28,7 +43,7 @@ export function resolveCorpConfig(
}
const firstCorp = corps[0];
if (firstCorp) return firstCorp;
if (firstCorp) return accept(firstCorp);
throw validationError("No enterprise config found. Add a non-example JSON file under one of: " +
(candidates.length ? candidates.join(", ") : "the configured enterprise directories"));
+67
View File
@@ -5,6 +5,7 @@ import {
SealCookieMapSchema,
SealHeaderMapSchema
} from "./types.js";
import { isCorpActive } from "./active.js";
describe("CorpConfigSchema", () => {
test("accepts Hose key/password aliases", () => {
@@ -180,6 +181,72 @@ describe("CorpConfigSchema", () => {
});
});
describe("CorpConfigSchema.active (parity across sources)", () => {
const variants = [
{
label: "hose",
source: {
type: "hose" as const,
domain: "https://app.ekuaibao.com",
appKey: "app-key",
appSecurity: "app-security",
corpId: "ID01",
staffId: "ID01:STAFF01"
}
},
{
label: "seal",
source: {
type: "seal" as const,
token: "seal-token",
sealUrl: "https://seal.sealai.cc"
}
}
];
for (const { label, source } of variants) {
test(`${label}: a legacy config without active stays enabled`, () => {
const config = CorpConfigSchema.parse({
id: `${label}-legacy`,
name: "Legacy Corp",
source
});
expect(String(config.source.type)).toBe(label);
expect(config.active).toBeUndefined();
expect(isCorpActive(config)).toBe(true);
});
test(`${label}: accepts explicit active true and false`, () => {
const enabled = CorpConfigSchema.parse({
id: `${label}-on`, name: "Enabled Corp", source, active: true
});
const disabled = CorpConfigSchema.parse({
id: `${label}-off`, name: "Disabled Corp", source, active: false
});
expect(enabled.active).toBe(true);
expect(isCorpActive(enabled)).toBe(true);
expect(disabled.active).toBe(false);
expect(isCorpActive(disabled)).toBe(false);
});
test(`${label}: a malformed active value fails closed to disabled instead of dropping the config`, () => {
for (const malformed of ["false", "true", null, 0, 1, {}, []]) {
const result = CorpConfigSchema.safeParse({
id: `${label}-bad`, name: "Bad Corp", source, active: malformed
});
if (!result.success) {
throw new Error(`config rejected for active=${JSON.stringify(malformed)}`);
}
expect(result.data.active).toBe(false);
expect(isCorpActive(result.data)).toBe(false);
}
});
}
});
describe("Seal custom header schemas", () => {
test("rejects an Authorization header supplied through config", () => {
expect(SealHeaderMapSchema.safeParse({ Authorization: "Bearer x" }).success).toBe(false);
+11
View File
@@ -112,6 +112,17 @@ export const CorpEnvironmentSchema = z.enum(["production", "test"]).default("pro
export const CorpConfigSchema = z.object({
id: z.string(),
name: z.string(),
// Tenant availability gate. It lives on the enterprise, NOT on a source, so
// `hose` and `seal` sources share exactly one switch and cannot diverge.
// Fail-closed three-way semantics:
// - absent -> undefined -> enabled (legacy configs, hand-built
// CorpConfig objects; materialized to true on read)
// - explicit boolean -> used as-is
// - malformed value -> `.catch(false)` -> DISABLED, never silently enabled
// A bad value must not drop the whole file (which would hide the enterprise
// from search and surface as a misleading "no enterprise config found").
// Disabling never affects `corps list/search` visibility.
active: z.boolean().optional().catch(false),
seal: SealEndpointSchema,
source: SealSourceSchema,
auth: CorpAuthConfigSchema,
+5 -2
View File
@@ -27,7 +27,8 @@ import file23 from "../../skills/seal-use/references/rule-lightweight.md" with {
import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/sealai-browser-rum.md" with { type: "text" };
import file26 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file27 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file27 from "../../skills/seal-use/references/tenant-status.md" with { type: "text" };
import file28 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -51,7 +52,8 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/rule-lint.md": file24,
"references/sealai-browser-rum.md": file25,
"references/staging-simulation-workflow.md": file26,
"references/webhook-resource-pack.md": file27,
"references/tenant-status.md": file27,
"references/webhook-resource-pack.md": file28,
};
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
@@ -91,5 +93,6 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/rule-lint.md",
"references/sealai-browser-rum.md",
"references/staging-simulation-workflow.md",
"references/tenant-status.md",
"references/webhook-resource-pack.md",
];
+7 -1
View File
@@ -97,7 +97,13 @@ function isValidationIssueList(error: unknown): boolean {
);
}
function responseStatus(error: unknown): number | undefined {
/**
* Read the HTTP status off an error thrown by the HTTP layer, structurally:
* ky's `HTTPError` is not a dependency of this module, and test doubles only
* carry `{ response: { status } }`. `undefined` means the request never got a
* response (DNS failure, connection reset, timeout).
*/
export function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
+32 -13
View File
@@ -1,3 +1,5 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import { CliError } from "../../core/errors.js";
/**
@@ -9,8 +11,8 @@ import { CliError } from "../../core/errors.js";
* embeds them into release binaries. End users therefore need zero setup.
*
* Precedence: injected build vars → plain `LANGFUSE_*` shell vars (development
* convenience when running from source) → nothing. Reading user config files is
* deliberately absent: this domain must work without any local configuration.
* convenience when running from source) → gitignored local `.env.langfuse` → nothing.
* Reading user config files is deliberately absent: this domain must work without any local configuration.
*/
export type LangfuseConfig = {
baseUrl: string;
@@ -31,6 +33,29 @@ function normalizeBaseUrl(baseUrl: string): string {
return baseUrl.replace(/\/+$/, "");
}
function tryReadEnvLangfuse(): Record<string, string> {
if (process.env.NODE_ENV === "test") return {};
try {
const envPath = resolve(process.cwd(), ".env.langfuse");
if (!existsSync(envPath)) return {};
const content = readFileSync(envPath, "utf8");
const result: Record<string, string> = {};
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const idx = trimmed.indexOf("=");
if (idx !== -1) {
const key = trimmed.slice(0, idx).trim();
const val = trimmed.slice(idx + 1).trim().replace(/^["']|["']$/g, "");
result[key] = val;
}
}
return result;
} catch {
return {};
}
}
export function hasLangfuseCredentials(): boolean {
const { baseUrl, publicKey, secretKey } = readLangfuseCredentials();
return Boolean(baseUrl && publicKey && secretKey);
@@ -43,18 +68,12 @@ function readLangfuseCredentials(): {
secretKey?: string;
projectId?: string;
} {
// Literal `process.env.X` accesses on purpose: `bun build --env=SEAL_BUILD_*`
// inlines static property reads at compile time, while a computed key
// (`process.env["SEAL_BUILD_" + name]`) stays a runtime lookup and comes back
// empty from a release binary. Reads happen per call so tests and dev shells
// can change the environment between invocations. The `LANGFUSE_*` fallbacks
// are deliberately outside the SEAL_BUILD_ prefix: they are never inlined and
// remain live shell-env vars for development runs from source.
const envFile = tryReadEnvLangfuse();
return {
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL),
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY),
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY),
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID)
baseUrl: pick(process.env.SEAL_BUILD_LANGFUSE_BASE_URL, process.env.LANGFUSE_BASE_URL, envFile.LANGFUSE_BASE_URL),
publicKey: pick(process.env.SEAL_BUILD_LANGFUSE_PUBLIC_KEY, process.env.LANGFUSE_PUBLIC_KEY, envFile.LANGFUSE_PUBLIC_KEY),
secretKey: pick(process.env.SEAL_BUILD_LANGFUSE_SECRET_KEY, process.env.LANGFUSE_SECRET_KEY, envFile.LANGFUSE_SECRET_KEY),
projectId: pick(process.env.SEAL_BUILD_LANGFUSE_PROJECT_ID, process.env.LANGFUSE_PROJECT_ID, envFile.LANGFUSE_PROJECT_ID)
};
}
@@ -0,0 +1,95 @@
import { describe, expect, test } from "bun:test";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { findSealCapability } from "../capabilities.js";
/**
* The flow lookup uses a rejected record query as a routing signal ("this was
* not a record ID, treat it as a document number") and a rejected run listing
* as "this document has no AI records". Both are fine for an identifier-shaped
* rejection and catastrophic for anything else: an expired token or a reset
* connection would be reported downstream as 「单据已删除」 or 「AI 从未审核」,
* which is a wrong answer delivered with full confidence.
*
* These cases stop before the Hose client is built, so no tenant is required.
*/
const HOSE_CORP = {
id: "corp-hose",
name: "测试合思企业",
source: { type: "hose" }
} as unknown as CorpConfig;
type Handler = (
client: KyInstance,
params: Record<string, unknown>,
context: { corp: CorpConfig }
) => Promise<unknown>;
function flowHandler(): Handler {
const capability = findSealCapability("sealApprovalRunFlowGet");
expect(capability).toBeDefined();
return capability!.handler as unknown as Handler;
}
function failingClient(error: unknown): KyInstance {
return {
get: () => {
throw error;
}
} as unknown as KyInstance;
}
function httpError(status: number): Error {
return Object.assign(new Error(`Request failed with status code ${status}`), {
response: { status }
});
}
async function captured(promise: Promise<unknown>): Promise<unknown> {
try {
await promise;
return undefined;
} catch (error) {
return error;
}
}
const SURFACED = [
["expired credentials", httpError(401)],
["forbidden credentials", httpError(403)],
["upstream service failure", httpError(503)],
["connection failure without a response", new TypeError("fetch failed")]
] as const;
describe("sealApprovalRunFlowGet failure attribution", () => {
for (const [label, error] of SURFACED) {
test(`surfaces ${label} instead of absorbing it as a document number`, async () => {
const thrown = await captured(
flowHandler()(failingClient(error), { target: "B26001887" }, { corp: HOSE_CORP })
);
// Identity, not message: the original error must reach the CLI layer so
// classifyCliError can still produce exit code 11 for auth failures.
expect(thrown).toBe(error);
});
}
test("keeps rejecting non-Hose enterprises before any request", async () => {
let called = false;
const client = {
get: () => {
called = true;
throw new Error("must not be reached");
}
} as unknown as KyInstance;
const thrown = await captured(
flowHandler()(client, { target: "B26001887" }, {
corp: { id: "corp-seal", name: "Seal 企业", source: { type: "seal" } } as unknown as CorpConfig
})
);
expect(String(thrown)).toContain("非合思");
expect(called).toBe(false);
});
});
+35 -5
View File
@@ -1,4 +1,4 @@
import { usageError, validationError } from "../../../core/errors.js";
import { classifyCliError, responseStatus, usageError, validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
@@ -48,6 +48,28 @@ const {
summarizeRuleVersion
} = helpers;
/**
* Decide whether a failed lookup means "the caller's input was not an ID of
* that kind" or something worse.
*
* Distinguishing them matters because both call sites below use the failure as
* a routing signal: a rejected record lookup means "treat the input as a
* document number", and a rejected run listing means "this document has no AI
* records". Swallowing everything turns a transient failure into a confident
* business verdict — an expired token or a reset connection would surface as
* 「单据已删除」 or 「AI 从未审核」, which is worse than an error.
*/
function isUpstreamLookupMiss(error: unknown): boolean {
const status = responseStatus(error);
if (status !== undefined) {
// Malformed or unknown identifier: the answer we were hoping for.
return status === 400 || status === 404 || status === 422;
}
// No response at all (DNS, reset, timeout) is never a miss. Structural
// validation failures are: the body arrived, it just is not an approval run.
return classifyCliError(error).exitCode === 13;
}
export const approvalRunsCapabilities = [
{
name: "sealApprovalRunsSearch",
@@ -273,8 +295,9 @@ export const approvalRunsCapabilities = [
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
}
} catch {
// Continue as SN
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// Not a record ID: the caller passed a document number. Continue as SN.
}
let runs: ApprovalRun[] = [];
@@ -287,8 +310,9 @@ export const approvalRunsCapabilities = [
runs = (runsData.records || []).filter(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
);
} catch {
// ignore
} catch (error) {
if (!isUpstreamLookupMiss(error)) throw error;
// No AI records for this document is a legitimate outcome.
}
if (runs.length === 0 && targetRecord) {
@@ -763,6 +787,12 @@ export const approvalRunsCapabilities = [
hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`,
diagnoseConflict: invoiceConflicts[0]?.nextCommand,
traceInvoice: invoiceConflicts[0] ? `seal-use invoices trace ${invoiceConflicts[0].invoiceNumber} --corp ${context.corp.id}` : undefined,
traceSearch: detail.sourceExtendData?._langfuseTraceId
? `seal-use langfuse search ${detail.sourceExtendData._langfuseTraceId} --query <关键词>`
: undefined,
traceOutline: detail.sourceExtendData?._langfuseTraceId
? `seal-use langfuse outline ${detail.sourceExtendData._langfuseTraceId} --include-io-preview`
: undefined,
replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}`
}
};
+1 -1
View File
@@ -598,7 +598,7 @@ export function summarizeApprovalRunDetail(record: ApprovalRun) {
export function summarizeApprovalRunResult(record: ApprovalRun) {
const result = asRecord(record.result);
return {
...summarizeExtraFindings(record),
...summarizeExtraFindings(record, true),
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
+64
View File
@@ -1,7 +1,9 @@
import { describe, expect, test } from "bun:test";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import {
createServer,
@@ -207,6 +209,68 @@ describe("seal-use MCP server", () => {
}
});
test("both MCP gateways refuse commands naming a disabled tenant", async () => {
const root = mkdtempSync(join(tmpdir(), "seal-mcp-disabled-tenant-"));
const enterprises = join(root, "enterprises");
mkdirSync(enterprises, { recursive: true });
writeFileSync(join(enterprises, "off.json"), JSON.stringify({
id: "off",
name: "Disabled Corp",
active: false,
seal: { url: "https://off.sealai.cc" },
source: { type: "seal", token: "seal-token", sealUrl: "https://off.sealai.cc" },
auth: { refreshTtl: 300 }
}));
const envKeys = [
"SEAL_USE_ENTERPRISES_DIR",
"SEAL_USE_CONFIG_FILE",
"SEAL_USE_TOKEN_STORE",
"SEAL_DISABLE_BG_UPDATE"
] as const;
const originals = Object.fromEntries(envKeys.map((key) => [key, process.env[key]]));
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
process.env.SEAL_DISABLE_BG_UPDATE = "1";
const server = createServer({ enableCli: true });
const client = new Client({ name: "seal-use-disabled-tenant-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport)
]);
const read = await client.callTool({
name: SEAL_USE_MCP_TOOL_NAME,
arguments: { command: "seal-use corps get off" }
});
expect(read.isError).toBe(true);
const readText = (read.content as Array<{ type: "text"; text: string }>)[0]?.text ?? "";
expect(readText).toContain("已禁用");
expect(readText).toContain("seal-use corps enable off");
const write = await client.callTool({
name: SEAL_USE_MCP_WRITE_TOOL_NAME,
arguments: { command: "seal-use rules list --corp off" }
});
expect(write.isError).toBe(true);
const writeText = (write.content as Array<{ type: "text"; text: string }>)[0]?.text ?? "";
expect(writeText).toContain("已禁用");
} finally {
await Promise.allSettled([client.close(), server.close()]);
for (const key of envKeys) {
const value = originals[key];
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
rmSync(root, { recursive: true, force: true });
}
});
test("does not advertise tools when MCP is disabled", async () => {
const server = createServer({ enableCli: false });
const client = new Client({ name: "seal-home-disabled-test", version: "1.0.0" });