Merge pull request #230 from yunyingk/mac15/rule-import-renumber

Organize Seal modules and add two-phase rule recoding
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-13 11:51:02 +08:00
commit dd0ca78e5b
74 files changed
+1931 -320

No files matched your search

+5
View File
@@ -25,6 +25,11 @@ When modifying or adding TypeScript files in `src/`:
4. **Architecture**:
- Prefer small, cohesive domain functions over large generic utility files.
- Place Seal business implementations and their colocated tests in the matching
feature directory under `src/domains/seal/`, for example `rules/recode.ts`
and `rules/recode.test.ts`. The domain root is reserved for `api.ts`,
`api.test.ts`, `types.ts`, and `capabilities.ts`; do not add business files
or old-path forwarding stubs there. See `AGENTS.md` for the feature layout.
5. **Frozen Utility Modules**:
- `src/domains/seal/capabilities/helpers.ts` is FROZEN: no new exports. It is
+2
View File
@@ -6,6 +6,8 @@ This is a Bun + TypeScript toolkit for the `seal-use` CLI and a local stdio MCP
The repository doubles as a ZCode plugin: `.zcode-plugin/plugin.json` declares a skills-only plugin manifest and the agent skill lives under `skills/seal-use/`. The plugin ships no MCP surface; the local MCP runs from the CLI (`seal-use mcp`, or the `mcp-config` snippet for Cursor/Claude Desktop). The in-repo `.agents/skills/seal-use` symlink has been dropped; workspace and Codex skill loading use the global `~/.agents/skills/seal-use` copy installed by `seal-use skill install`.
Within `src/domains/seal/`, the root contains only shared protocol boundaries (`api.ts`, `api.test.ts`, `types.ts`) and the public capability export (`capabilities.ts`). Business implementations belong in their feature directories: `rules/`, `approval-runs/`, `insight/`, `replay/`, `outbound/`, `enterprise/`, `search/`, and `testing/`; existing `reports/`, `linter/`, `material-pack/`, `doctor/`, and `regression/` retain their own boundaries. Put new Seal implementations and their tests in the matching feature directory (for example `rules/recode.ts` and `rules/recode.test.ts`), rather than adding business files or legacy forwarding stubs to the domain root. The registry-wide tests live in `capabilities/capabilities.test.ts`.
Tests are colocated as `*.test.ts` files in `src/`.
## Build, Test, and Development Commands
+5 -1
View File
@@ -214,7 +214,7 @@ Most users do not need MCP. The public/shared path is the global `seal-use` CLI.
### One registry, two doors
All approval/logic lives once in the capability registry under `src/domains/seal/capabilities/` (`src/domains/seal/capabilities.ts` re-exports it). Two surfaces enter the same handlers, each with its own naming:
Shared approval behavior lives in the business modules under `src/domains/seal/`; the capability registry under `src/domains/seal/capabilities/` dispatches it (`src/domains/seal/capabilities.ts` re-exports the registry). Two surfaces enter the same handlers, each with its own naming:
| Surface | Entry | Naming |
| --- | --- | --- |
@@ -240,6 +240,8 @@ Both run the same CLI dispatcher as the global binary, so `config` and `update`
## CLI-First Architecture
Seal implementations and their tests are grouped by feature: `src/domains/seal/rules/` owns local rule files, diffs, mappings, version snapshots, recoding and confirmation tickets; `approval-runs/` owns record export and attachments; `insight/` owns insight export; `replay/` owns Webhook/Hose replay and environment guards; `outbound/` owns downstream pushes; `enterprise/` owns Seal onboarding and identity resolution; `search/` owns cross-resource search; and `testing/` owns test-enterprise synchronization. Existing `reports/`, `linter/`, `material-pack/`, `doctor/` and `regression/` stay separate. Only shared API/types and the capability export remain at the domain root.
All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the `seal_use` / `seal_use_write` MCP tools passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`.
Key CLI command groups:
@@ -256,6 +258,8 @@ For rule list commands, prefer `seal-use rules count --corp <corpId>` or `seal-u
For test tenants that need a clean slate before importing another rule set, use `seal-use rules clear --corp <corpId> --dry-run` first, then `seal-use rules clear --corp <corpId> --yes` to delete the current draft rules and verify the remaining count.
To compact draft rule numbers from `0000`, run `seal-use rules recode --corp <corpId>`. The first call returns an impact preview and an enterprise/environment/draft-bound one-use credential (exit 10), without executing the recode. Inspect the preview, then run the returned `nextCommand` separately; the credential expires after five minutes, and `--yes` cannot bypass it. `--dry-run` only previews. The server determines ordering, and every rule can change number; the verified per-rule mapping is returned after execution. Recode does not publish a version; old rule numbers must be interpreted with their published version. Clearing and test synchronization reset numbering only after verifying an empty draft.
For approval run detail commands, prefer the same commands with explicit `--corp <corpId>`—for example `seal-use approval-runs pick --corp <corpId> --sn <单号> --latest` or `seal-use approval-runs get <recordId> --corp <corpId> --summary`—before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-use auth hose-link --corp <corpId> --expire 7200`, which returns the unredacted `getProvisionalAuth` URL.
## Approval Run To Langfuse Bridge
+9 -1
View File
@@ -63,6 +63,14 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。
## 规则编号重排:两次调用
`seal-use rules recode --corp <corpId>` 将当前草稿编号从 `0000` 连续编排。具体顺序由服务端决定,新建草稿可能排在已有规则之前;所有规则均可能变号,不能把预览中的编号范围当作逐条映射。第一次只返回影响预览、6 位一次性凭证、到期时间和 `nextCommand`,`executed: false`,退出码为 10;尚未执行重排。核对目标企业和完整影响范围后,另一次调用返回的完整命令才执行;成功返回的 `changes` 是按稳定身份回读验证的真实编号映射。
凭证绑定企业、环境及草稿状态,5 分钟有效且只能使用一次;`--yes` / `--confirm` 不能替代凭证。`--dry-run` 只预览,不签发凭证。确认码尚未生效时停止连调,不把两阶段写成自动执行脚本;草稿变化或凭证失效时重新预览。执行失败或超时后先回读当前草稿,再决定是否重新申请,不能重用旧码或盲目重跑。
重排不发布版本。旧编号可能对应不同规则,查看历史记录需指定发布版本。具体预览与返回字段见 `references/rule-lightweight.md`。
## 业务术语契约
对外统一使用以下术语:
@@ -93,7 +101,7 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
| 规则数量、摘要列表、历史规则、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` |
| 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 |
| 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference |
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
+5 -1
View File
@@ -57,7 +57,9 @@ seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|la
seal-use rules linters [--corp <corpId>]
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
seal-use rules push status [--file <path>] [--corp <corpId>]
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
seal-use rules recode [--dry-run] --corp <corpId>
seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]
seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]
seal-use documents get <documentId> [--corp <corpId>]
@@ -301,8 +303,10 @@ Approval rule maintenance:
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: custom in `~/.config/seal-use/linters` and official in `~/.cache/seal-use/linters/official`)
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Live execution persists a per-step recovery ledger (`status`: `not_started`, `partial`, `completed`, `uncertain`) and hydrates newly created IDs so an interrupted run can be inspected and resumed without duplicating rules.
- `seal-use rules push status [--file <path>] [--corp <corpId>]` (or `--check`) inspects the last push recovery ledger and reconciles remaining diff against the live draft without mutating state.
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
- `seal-use rules recode [--dry-run] --corp <corpId>`: first returns an unexecuted numbering preview and a one-use credential (exit 10). Inspect the preview, then invoke the returned `nextCommand` separately. The credential is enterprise/environment/draft-bound, valid for five minutes, and cannot be replaced by `--yes`/`--confirm`. `--dry-run` only previews (exit 0). Recode does not publish; failed/uncertain executions require a draft read before another request. Do not script both phases into automatic consecutive execution.
- `seal-use rules map [--version <number|latest>] [--code <code>] [--corp <corpId>]` (reads local sync rule mapping snapshot)
Rule identity and versioning (Draft by default vs. `--version latest`):
@@ -92,6 +92,19 @@ Expected shape:
}
```
## Recode Draft Rule Numbers
```bash
seal-use rules recode --corp <corpId>
seal-use rules recode --dry-run --corp <corpId>
```
The first command returns a preview, a six-character one-use confirmation code, `expiresAt`, and `nextCommand`, with `executed: false` and exit code 10. Inspect the enterprise and full impact scope, then invoke the returned command separately. Preview `changesDiff` shows the existing and resulting number ranges, not a per-rule mapping (`mappingAvailable: false`); every rule can change number. The code is bound to the enterprise, environment and exact draft state, expires in five minutes, and is consumed before the POST. Ordinary `--yes`/`--confirm` cannot bypass this flow. Do not combine both phases into an automatic script.
`--dry-run` returns only the preview (exit 0) without issuing a code. A successful second call returns `executed: true`, the verified per-rule `changes` (`mappingAvailable: true`), and `nextCode`. Recode starts at `0000`, and the server determines ordering: new drafts may move before existing active rules. It does not publish. A not-yet-active code should not trigger immediate repeated calls. On expiry or draft changes request a fresh preview; on POST failure/timeout, read the current draft before requesting another code. A spent code is never reusable.
Clearing rules and test synchronization reset the allocation counter only after verifying the draft is empty. If clear leaves any rules behind, it skips automatic recoding and reports a warning.
## Output Discipline
If a rule command would return many descriptions or more than about 20 rules, use `rules count`, `rules list --summary`, `rules search`, or `--output-file`. Use `--full` only for deliberate exports.
+1 -1
View File
@@ -1,6 +1,6 @@
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 { exportInsightReportToExcel } from "../../domains/seal/insight/export.js";
import { runCapability } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
+2 -2
View File
@@ -1,11 +1,11 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import * as api from "../../domains/seal/api.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs-export.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs/export.js";
import {
downloadApprovalRunAttachments,
extractApprovalRunAttachments
} from "../../domains/seal/attachments.js";
} 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";
+9 -3
View File
@@ -355,6 +355,10 @@ describe("corps sync-test", () => {
expect(createdRules.length).toBe(2);
expect((createdRules[0]!.body as any).description).toBe("Production Rule A");
expect((createdRules[1]!.body as any).description).toBe("Production Rule B");
const resetIndex = requests.findIndex(r => r.path === "/api/v1/rules/batch-recode");
const firstCreateIndex = requests.findIndex(r => r.method === "POST" && r.path === "/api/v1/rules");
expect(resetIndex).toBeGreaterThanOrEqual(0);
expect(resetIndex).toBeLessThan(firstCreateIndex);
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
expect(publishVersion).toBeDefined();
@@ -909,6 +913,9 @@ describe("corps replay-test", () => {
function mockSealSyncRequests(options: {
onMutation?: (method: string, path: string, body?: unknown) => void;
} = {}) {
let remainingTestRules = [
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string"
? input
@@ -1071,9 +1078,7 @@ function mockSealSyncRequests(options: {
} else {
return jsonResponse({
data: {
rules: [
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
],
rules: remainingTestRules,
hasPendingDeletes: false
}
});
@@ -1082,6 +1087,7 @@ function mockSealSyncRequests(options: {
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
options.onMutation?.("DELETE", url.pathname);
remainingTestRules = remainingTestRules.filter(rule => rule.id !== url.pathname.split("/").pop());
return jsonResponse({ data: { success: true } });
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { maskHoseSecurity } from "../../../core/auth/hose.js";
import { scoreAssistLink } from "../../../core/auth/delegate.js";
import { onboardSealBearer } from "../../../domains/seal/onboarding.js";
import { onboardSealBearer } from "../../../domains/seal/enterprise/onboarding.js";
import { onboardAssistanceLink } from "../../../domains/enterprise/onboarding.js";
import {
listHoseStaffs,
+3 -3
View File
@@ -1,14 +1,14 @@
import { createSealClient } from "../../../core/http/factory.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { syncTestEnterprise } from "../../../domains/seal/test-sync.js";
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/webhook-replay.js";
import { syncTestEnterprise } from "../../../domains/seal/testing/sync.js";
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../domains/seal/replay/webhook.js";
import { selectCorp } from "../../helpers.js";
import { CliError, confirmationRequired, usageError } from "../../errors.js";
import { booleanOption, numberOption, stringOption } from "../../parser.js";
import { outputOptions, printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
export { buildTestHosecloudOutboundName } from "../../../domains/seal/testing/sync.js";
export async function handleCorpSync(
action: string | undefined,
+1 -1
View File
@@ -6,7 +6,7 @@ import { booleanOption, jsonObject, numberOption, stringOption } from "../parser
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
import { listHoseIntegrations } from "../../domains/seal/outbound-push.js";
import { listHoseIntegrations } from "../../domains/seal/outbound/push.js";
import { CliError } from "../errors.js";
export async function handleDeployCommand(
+103
View File
@@ -0,0 +1,103 @@
import { expect, test } from "bun:test"
import { Client, InMemoryTransport } from "@modelcontextprotocol/client"
import { randomBytes } from "node:crypto"
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { createServer, SEAL_USE_MCP_TOOL_NAME, SEAL_USE_MCP_WRITE_TOOL_NAME } from "../../server.js"
test("separate CLI processes share one-use tickets and MCP retains the first-phase JSON preview", async () => {
const dir = mkdtempSync(join(tmpdir(), "seal-recode-cli-"))
const corpId = `recode-${randomBytes(4).toString("hex")}`
let posts = 0
const rules = [
{ id: "a", tenantId: "tenant", code: 0, description: "First", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" },
{ id: "b", tenantId: "tenant", code: 2, description: "Second", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE" }
]
const upstream = Bun.serve({
hostname: "127.0.0.1", port: 0,
fetch(request) {
const path = new URL(request.url).pathname
if (path === "/api/v1/rules" && request.method === "GET") {
return Response.json({ data: { rules, hasPendingDeletes: false } })
}
if (path === "/api/v1/auth/me") {
return Response.json({ data: { user: { id: "operator", tenantId: "tenant", name: "Operator" }, tenant: { id: "tenant", name: "Test" } } })
}
if (path === "/api/v1/rules/batch-recode" && request.method === "POST") {
posts++
rules.forEach((rule, index) => { rule.code = index })
return Response.json({ data: { activeRules: 2, pendingDeleteRules: 0, nextCode: 2 } })
}
return Response.json({ error: "Unexpected request" }, { status: 404 })
}
})
const enterprises = join(dir, "enterprises")
const store = join(dir, "tickets.sqlite")
mkdirSync(enterprises)
const url = `http://127.0.0.1:${upstream.port}`
writeFileSync(join(enterprises, "corp.json"), JSON.stringify({
id: corpId, name: "CLI Test", environment: "test",
seal: { url }, source: { type: "seal", token: "test-token", sealUrl: url }
}))
writeFileSync(join(dir, "config.json"), JSON.stringify({ stateful: false }))
const env = {
SEAL_USE_ENTERPRISES_DIR: enterprises,
SEAL_USE_CONFIG_FILE: join(dir, "config.json"),
SEAL_USE_TOKEN_STORE: join(dir, "tokens.json"),
SEAL_USE_USAGE_FILE: join(dir, "usage.json"),
SEAL_USE_RECODE_STORE: store,
SEAL_DISABLE_BG_UPDATE: "1"
}
const previous = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]]))
const server = createServer({ enableCli: true })
const client = new Client({ name: "recode-preview-test", version: "1.0.0" })
const run = async (args: string[]) => {
const child = Bun.spawn([process.execPath, join(import.meta.dirname, "../../cli.ts"), "rules", "recode", "--corp", corpId, ...args], {
env: { ...process.env, ...env }, stdout: "pipe", stderr: "pipe"
})
const [stdout, stderr, exitCode] = await Promise.all([
new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited
])
return { stdout, stderr, exitCode }
}
try {
const dry = await run(["--dry-run"])
expect(dry.exitCode).toBe(0)
expect(JSON.parse(dry.stdout).executed).toBe(false)
expect(existsSync(store)).toBe(false)
const first = await run(["--yes"])
expect(first.exitCode).toBe(10)
const preview = JSON.parse(first.stdout)
expect(preview).toMatchObject({ phase: "confirmation_required", executed: false, impactCount: 2, mappingAvailable: false })
expect(first.stderr).toContain(preview.nextCommand)
expect(posts).toBe(0)
await Bun.sleep(510)
const competed = await Promise.all([run(["--confirm-code", preview.confirmCode]), run(["--confirmCode", preview.confirmCode])])
expect(competed.map(result => result.exitCode).sort()).toEqual([0, 10])
const executed = JSON.parse(competed.find(result => result.exitCode === 0)!.stdout)
expect(executed).toMatchObject({ executed: true, nextCode: 2 })
expect(executed.changes).toEqual([{ beforeCode: "0000", afterCode: "0000" }, { beforeCode: "0002", afterCode: "0001" }])
expect(posts).toBe(1)
for (const [key, value] of Object.entries(env)) process.env[key] = value
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)])
const denied = await client.callTool({ name: SEAL_USE_MCP_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } })
expect(denied.isError).toBe(true)
const result = await client.callTool({ name: SEAL_USE_MCP_WRITE_TOOL_NAME, arguments: { command: `rules recode --corp ${corpId}` } })
expect(result.isError).toBe(true)
const content = result.content as Array<{ type: "text"; text: string }>
expect(JSON.parse(content[0]!.text)).toMatchObject({ executed: false, phase: "confirmation_required" })
expect(content[1]!.text).toContain("nextCommand")
expect(posts).toBe(1)
} finally {
await Promise.allSettled([client.close(), server.close()])
upstream.stop(true)
for (const [key, value] of Object.entries(previous)) {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
rmSync(dir, { recursive: true, force: true })
}
})
+53 -13
View File
@@ -1,7 +1,8 @@
import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js";
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rules/mapping.js";
import { RulePushExecutionError } from "../../domains/seal/rules/push.js";
import {
listAvailableLinters,
PRIMARY_LINTERS_DIR,
@@ -66,6 +67,18 @@ export async function handleRulesCommand(
return;
}
if (action === "recode") {
const result = await runCapabilityResult("sealApprovalRulesRecode", client!, corp, {
dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]),
confirmCode: stringOption(args.options.confirmCode) ?? stringOption(args.options["confirm-code"])
}) as { phase: string; nextCommand?: string };
printJson(result, outputOptions(args.options));
if (result.phase === "confirmation_required") {
throw confirmationRequired("尚未执行规则重排。请核对预览后运行返回的 nextCommand。", result.nextCommand!);
}
return;
}
if (action === "list") {
const version = resolveVersionOption(args);
if (booleanOption(args.options.count)) {
@@ -326,7 +339,26 @@ export async function handleRulesCommand(
}
if (action === "push") {
const file = stringOption(args.options.file) ?? stringOption(args.options.f) ?? maybeName;
const statusOnly =
maybeName === "status" ||
booleanOption(args.options.check) === true ||
args.options.status === "true" ||
args.options.status === true;
const file =
stringOption(args.options.file) ??
stringOption(args.options.f) ??
(maybeName && maybeName !== "status" && !maybeName.startsWith("-") ? maybeName : undefined);
if (statusOnly) {
await runCapability(
"sealApprovalRulesPush",
client!,
corp,
{ file, statusOnly: true },
outputOptions(args.options)
);
return;
}
const confirmed = booleanOption(args.options.yes) === true;
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
const publish = booleanOption(args.options.publish);
@@ -339,18 +371,26 @@ export async function handleRulesCommand(
);
}
const result = await runCapabilityResult(
"sealApprovalRulesPush",
client!,
corp,
{
file,
dryRun,
confirm: confirmed,
publish,
versionName
let result: unknown;
try {
result = await runCapabilityResult(
"sealApprovalRulesPush",
client!,
corp,
{
file,
dryRun,
confirm: confirmed,
publish,
versionName
}
);
} catch (error) {
if (error instanceof RulePushExecutionError) {
printJson(error.recoveryPayload, outputOptions(args.options));
}
);
throw error;
}
if (!confirmed && dryRun && result && typeof result === "object") {
printJson(
+1 -1
View File
@@ -1,5 +1,5 @@
import type { CorpConfig } from "../../core/config/types.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/enterprise/source.js";
import { printJson } from "../printer.js";
export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) {
+2 -2
View File
@@ -11,8 +11,8 @@ import {
executeApprovalRunsReplay,
resolveReplayCorpPair,
type ReplayRecordsQuery
} from "../../domains/seal/webhook-replay.js";
import { executeHoseOutboundReplay } from "../../domains/seal/hose-outbound-replay.js";
} from "../../domains/seal/replay/webhook.js";
import { executeHoseOutboundReplay } from "../../domains/seal/replay/hose-outbound.js";
import {
checkWebhookReadiness,
exportApprovalRunsToResourcePack,
+5 -1
View File
@@ -91,12 +91,16 @@ describe("CLI semantic errors", () => {
});
});
test("keeps domain failures and quality gates at exit 1", () => {
test("keeps domain failures, post-mutation recovery errors, and quality gates at exit 1", () => {
expect(classifyCliError(new Error("未找到指定的规则版本: 99"))).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("[Linter 质量门禁未通过] 综合评分 80 低于要求的最低分 85 分"))).toEqual({
exitCode: 1
});
expect(classifyCliError(new Error("Webhook 单据推送失败 (500): internal"))).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("测试企业「T」AI 审批额度不足:当前剩余 200 点"))).toEqual({ exitCode: 1 });
expect(
classifyCliError(new Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。"))
).toEqual({ exitCode: 1 });
expect(classifyCliError(new Error("上游网关响应超时,请重试或检查网络连接。"))).toEqual({ exitCode: 1 });
});
});
+8
View File
@@ -61,6 +61,14 @@ describe("extractHelpRequest", () => {
});
describe("renderHelp", () => {
test("explains both recode phases without exposing internal activation timing", () => {
const help = renderHelp(["rules", "recode"]);
expect(help).toContain("一次性凭证");
expect(help).toContain("另一次调用");
expect(help).toContain("不执行重排");
expect(help).not.toContain("500");
expect(help).not.toContain("--confirm-code");
});
test("renders global help when target is empty", () => {
const help = renderHelp([]);
expect(help).toContain("seal-use CLI");
+11 -2
View File
@@ -343,14 +343,23 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "push",
summary: "Push rules from local JSON file to enterprise draft space",
usage: ["seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]"]
summary: "Push rules from local JSON file to enterprise draft space (with step recovery & status check)",
usage: [
"seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]",
"seal-use rules push status [--file <path>] [--corp <corpId>]"
]
},
{
name: "clear",
summary: "Clear all draft rules from enterprise",
usage: ["seal-use rules clear [--dry-run|--yes] [--corp <corpId>]"]
},
{
name: "recode",
summary: "Preview consecutive rule numbering, then execute with a one-use confirmation code",
usage: ["seal-use rules recode [--dry-run] --corp <corpId>"],
description: "首次运行只返回影响预览、一次性凭证和 nextCommand,不执行重排;核对后另一次调用返回的命令才会生效。凭证绑定企业、环境和草稿,5 分钟有效且只能使用一次。--yes/--confirm 不能跳过该流程。--dry-run 只预览,不签发凭证。服务端决定编号顺序,所有规则均可能变号;逐条映射在执行后回读。重排不发布版本;查看旧编号需结合发布版本。"
},
{
name: "map",
summary: "Inspect locally synced production/test rule code mappings",
+14 -4
View File
@@ -65,10 +65,11 @@ export async function runCapabilityResult(
);
// Schema gate: a missing required field or an out-of-range value fails here
// with exit 13 instead of reaching the handler as `undefined` and surfacing
// as an opaque upstream error. Valid params pass through untouched.
parseCapabilityParams(tool, compactParams);
// as an opaque upstream error. Valid params are normalized so the handler
// executes with the exact coerced/defaulted values that passed validation.
const normalizedParams = parseCapabilityParams(tool, compactParams);
const handler = tool.handler as SealCapability["handler"];
return handler(client, compactParams as never, { corp });
return handler(client, normalizedParams as never, { corp });
}
/**
@@ -98,6 +99,15 @@ export async function runLangfuseCapability(
throw validationError(`Invalid parameters for ${tool.name}: ${detail}`);
}
const normalizedParams =
parsed.data && typeof parsed.data === "object"
? {
...compactParams,
...Object.fromEntries(
Object.entries(parsed.data as Record<string, unknown>).filter(([, value]) => value !== undefined)
)
}
: compactParams;
const handler = tool.handler as (params: never, service: LangfuseService) => Promise<unknown>;
printJson(await handler(compactParams as never, createLangfuseService()), options);
printJson(await handler(normalizedParams as never, createLangfuseService()), options);
}
+2 -2
View File
@@ -42,7 +42,7 @@ export const BOOLEAN_FLAGS = new Set([
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
"channel", "chrome", "code", "concurrency", "content", "content-file", "content-hints", "content-type", "contentFile",
"channel", "chrome", "code", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
@@ -90,7 +90,7 @@ export const KNOWN_FLAGS = new Set([
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "business-codes", "businessCodes", "channel", "changelog", "check", "check-only", "chrome",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "confirm-code", "confirmCode", "content",
"content-file", "content-hints", "content-type", "contentFile", "contentType", "context-chars", "contextLines", "corp",
"corp-id", "corpId", "corporation-id", "corporationId", "count", "date", "dedupe-by", "dedupeBy",
"default", "departmentId", "dept", "desc", "description", "description-file",
+29 -7
View File
@@ -26,6 +26,7 @@ describe("CLI read-only classification", () => {
"auth status",
"auth test",
"auth doctor",
"auth seal-link list",
"doctor auth"
]);
@@ -134,21 +135,34 @@ describe("CLI read-only classification", () => {
expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false);
});
test("allows rules push status / --check as read-only while refusing mutating rules push forms", () => {
expect(isReadOnlyCliCommand(["rules", "push", "status", "--corp", "corp-a"])).toBe(true);
expect(isReadOnlyCliCommand(["rules", "push", "--check", "--corp", "corp-a"])).toBe(true);
expect(isReadOnlyCliCommand(["rules", "push", "--corp", "corp-a"])).toBe(false);
expect(isReadOnlyCliCommand(["rules", "push", "status", "--yes", "--corp", "corp-a"])).toBe(false);
});
test("refuses command lines that cannot be parsed", () => {
expect(isReadOnlyCliCommand(["--json"])).toBe(false);
});
});
// The two classifications are maintained by hand, in different files: the CLI allow-list here and
// The two classifications are maintained in different files: the CLI allow-list here and
// SEAL_READ_ONLY_CAPABILITIES in the tool registry. Nothing stopped them from disagreeing, and they did —
// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs
// were simply missing. This derives one from the other and fails on any new disagreement.
// were simply missing. This scans both `runCapability` and `runCapabilityResult` and fails on any disagreement.
describe("CLI allow-list agrees with the tool registry", () => {
// `deploy` only accepts `deploy hosecloud <action>`; the short `deploy <action>` form throws
// "未知的发布目标系统" at runtime, so these pairs are unreachable rather than refused.
const UNREACHABLE_CLI_FORMS = new Set(["deploy requirements", "deploy list", "deploy status"]);
// "未知的发布目标系统" at runtime. `auth seal-link` only calls `sealDelegationList` when the
// third token `list` is present (`auth seal-link list`); bare `auth seal-link` mints a token.
const UNREACHABLE_CLI_FORMS = new Set([
"deploy requirements",
"deploy list",
"deploy status",
"auth seal-link"
]);
test("every CLI verb dispatching to a read-only tool is itself read-only", () => {
test("every CLI verb dispatching to a read-only tool is itself read-only, and mutating tools are not read-only", () => {
const files = readdirSync(join(import.meta.dir, "commands")).filter(
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
);
@@ -157,7 +171,8 @@ describe("CLI allow-list agrees with the tool registry", () => {
for (const file of files) {
const area = file.replace(/\.ts$/, "");
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
const pattern = /action === "([a-z0-9-]+)"[\s\S]{0,600}?runCapability\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
const pattern =
/if\s*\(\s*action === "([a-z0-9-]+)"(?:(?!\bif\s*\(\s*action\b)[\s\S]){0,600}?runCapability(?:Result)?\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
let match;
while ((match = pattern.exec(source))) {
pairs.push({ area, action: match[1]!, tool: match[2]! });
@@ -165,7 +180,7 @@ describe("CLI allow-list agrees with the tool registry", () => {
}
// If the dispatch shape changes this silently finds nothing, which would make the test vacuous.
expect(pairs.length).toBeGreaterThan(50);
expect(pairs.length).toBeGreaterThan(55);
const disagreements = pairs
.filter((pair) => SEAL_READ_ONLY_CAPABILITIES.has(pair.tool))
@@ -174,5 +189,12 @@ describe("CLI allow-list agrees with the tool registry", () => {
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
expect(disagreements).toEqual([]);
const unsafeMutating = pairs
.filter((pair) => SEAL_MUTATING_CAPABILITIES.has(pair.tool))
.filter((pair) => isReadOnlyCliCommand([pair.area, pair.action]))
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
expect(unsafeMutating).toEqual([]);
});
});
+17 -2
View File
@@ -37,6 +37,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
"count",
"export",
"flow",
"hose-flow",
"list",
// `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry.
"search",
@@ -68,8 +69,8 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
// read forms cannot be separated from the value-taking write forms. `config get` returns
// the same summary (mode + lint included), so read access loses nothing.
config: ["paths", "get"],
auth: ["check", "diagnose", "status", "test", "doctor", "link list"],
users: ["search", "get", "delegation"],
auth: ["check", "diagnose", "status", "test", "doctor", "link list", "seal-link list"],
users: ["search", "get"],
contacts: ["departments", "children", "users", "sync-time"],
data: ["expenses", "invoices"],
llm: ["config", "providers"],
@@ -126,7 +127,10 @@ export function describeCliCommand(argv: string[]): { area: string; actionTokens
export function isReadOnlyCliCommand(argv: string[]): boolean {
let area: string;
let actionTokens: string[];
let options: Record<string, unknown>;
try {
const parsed = parseArgs(argv);
options = parsed.options;
({ area, actionTokens } = describeCliCommand(argv));
} catch {
// Unparsable command lines are refused rather than guessed at.
@@ -136,6 +140,17 @@ export function isReadOnlyCliCommand(argv: string[]): boolean {
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
// The `<corpId>` selector form; the bare form falls through to the `""` entry.
if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true;
// `rules push status` / `rules push --check` inspects the recovery journal and
// reconciles against the remote draft without mutating anything.
if (
area === "rules" &&
actionTokens[0] === "push" &&
(actionTokens[1] === "status" || options.check === true || options.status === "true") &&
!options.yes &&
!options.confirm
) {
return true;
}
const allowed = READ_ONLY_COMMANDS[area];
if (!allowed) return false;
+3 -1
View File
@@ -56,8 +56,10 @@ const USAGE_PREFIX =
// Wording a Chinese-language usage error uses when it names a flag/parameter
// the caller must supply, or rejects a value the caller chose. Exit `13`.
// Deliberately excludes generic recovery verbs like "请先"/"请重试" so post-write
// or upstream failures that offer recovery advice stay at exit `1`.
const CN_USAGE =
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用|请提供|请重试|请先)/;
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用 --|请提供)/;
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
const CORP_SELECTION =
+1 -1
View File
@@ -6,7 +6,7 @@ import {
} from "../../core/auth/delegate.js";
import { parseHoseAssistLink } from "../../core/auth/hose.js";
import { onboardHoseWebSession } from "../hose/onboarding.js";
import { persistSealDelegateSession } from "../seal/onboarding.js";
import { persistSealDelegateSession } from "../seal/enterprise/onboarding.js";
export type AssistanceLinkOnboardingInput = {
name?: string;
+1 -1
View File
@@ -13,7 +13,7 @@ import { saveCorpConfig, type SavedCorpConfig } from "../../core/config/reposito
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import { getMe } from "../seal/api.js";
import { resolveLiveSealEnterpriseConfig } from "../seal/source.js";
import { resolveLiveSealEnterpriseConfig } from "../seal/enterprise/source.js";
export type HosePersistentInput = {
id?: string;
+21 -1
View File
@@ -10,6 +10,7 @@ import { CorpConfig } from "../../core/config/types.js";
import { ensureHoseOpenapiToken, fetchHoseCloseApiToken, defaultSealUrl, normalizeBaseUrl } from "../../core/auth/hose.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { redactSensitiveText } from "../../core/redact.js";
import { safetyBlocked } from "../../core/errors.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
ApprovalDocumentListData,
@@ -140,7 +141,13 @@ export async function deleteApprovalRule(client: KyInstance, ruleId: string): Pr
}
export async function recodeApprovalRules(client: KyInstance): Promise<unknown> {
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false });
// Legacy clear/sync callers may reset an EMPTY draft's allocation counter.
// Renumbering existing rules must go through the ticketed recode capability.
const draft = await listApprovalRules(client);
if (draft.rules.length > 0) {
throw safetyBlocked("禁止隐式重排非空草稿,请使用 rules recode 的两阶段确认流程。");
}
const response = await client.post("api/v1/rules/batch-recode", { throwHttpErrors: false, retry: 0 });
const body = await response.json().catch(() => ({}));
return z.object({
ok: z.boolean(),
@@ -153,6 +160,19 @@ export async function recodeApprovalRules(client: KyInstance): Promise<unknown>
});
}
/** Called only after the shared recode capability consumes its confirmation ticket. */
export async function executeApprovalRulesRecode(client: KyInstance) {
const response = await client.post("api/v1/rules/batch-recode", { retry: 0 });
const body = await response.json() as { data?: unknown };
const result = z.object({
activeRules: z.number().int().nonnegative(),
pendingDeleteRules: z.number().int().nonnegative(),
nextCode: z.number().int().nonnegative()
}).safeParse(body.data ?? body);
if (!result.success) throw new Error("规则重排接口返回了无效结果,请回读当前草稿确认状态。");
return result.data;
}
export async function listApprovalRuleVersions(client: KyInstance): Promise<RuleSetVersion[]> {
return unwrap(await client.get("api/v1/rule-set-versions"), z.array(RuleSetVersionSchema));
}
@@ -9,7 +9,7 @@ import {
sanitizeFileName,
type FetchLike
} from "./attachments.js";
import type { ApprovalRun } from "./types.js";
import type { ApprovalRun } from "../types.js";
describe("attachments domain", () => {
let tmpDir: string;
@@ -1,6 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import type { ApprovalRun } from "./types.js";
import type { ApprovalRun } from "../types.js";
export interface ApprovalRunAttachment {
path: string;
@@ -14,8 +14,8 @@ import {
resolveExportDateRange,
resolveOutputFilePath,
exportApprovalRunsToExcel
} from "./approval-runs-export.js";
import type { CorpConfig } from "../../core/config/types.js";
} from "./export.js";
import type { CorpConfig } from "../../../core/config/types.js";
describe("approval-runs-export helpers", () => {
test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => {
@@ -3,17 +3,17 @@ import { homedir } from "node:os";
import { dirname, extname, resolve } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow,
type HoseOpenStaffItem,
type HoseRunAlignment
} from "../hose/index.js";
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
} from "../../hose/index.js";
import type { ApprovalRun, ApprovalRunListData } from "../types.js";
export interface ApprovalRunsExportOptions {
limit?: number;
@@ -3,8 +3,8 @@ import type { KyInstance } from "ky";
import * as api from "../api.js";
import { ensureHoseCloseApiToken } from "../../../core/auth/hose.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs/export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
@@ -4,10 +4,10 @@ import { z } from "zod";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CorpConfig } from "../../core/config/types.js";
import { CliError } from "../../core/errors.js";
import { saveRuleMappingSnapshot } from "./rule-mapping.js";
import { buildRulePushPlan, findSealCapability, sealCapabilities } from "./capabilities.js";
import { CorpConfig } from "../../../core/config/types.js";
import { CliError } from "../../../core/errors.js";
import { saveRuleMappingSnapshot } from "../rules/mapping.js";
import { buildRulePushPlan, findSealCapability, sealCapabilities } from "../capabilities.js";
type CapabilityHandler = (
client: KyInstance,
+1 -1
View File
@@ -15,7 +15,7 @@ import {
pushOutboundAndVerify,
resolveCorporationId,
selectHoseIntegration
} from "../outbound-push.js";
} from "../outbound/push.js";
import type {
CapabilityContext
} from "./helpers.js";
+7 -10
View File
@@ -23,10 +23,11 @@ import type {
SimulationBatch,
WebhookIntegration
} from "../types.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import type { LocalRuleItem } from "../rules-local.js";
import { loadRuleMappingSnapshot } from "../rule-mapping.js";
import { extractApprovalRunAttachments } from "../approval-runs/attachments.js";
import type { LocalRuleItem } from "../rules/local.js";
import { loadRuleMappingSnapshot } from "../rules/mapping.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
import { validationError } from "../../../core/errors.js";
export type CapabilityContext = {
corp: CorpConfig;
@@ -169,21 +170,17 @@ export function buildRulePushPlan(
if (localRule.id) {
remoteRule = remoteById.get(localRule.id);
if (!remoteRule) {
throw new Error(
`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`
);
throw validationError(`本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。`);
}
if (usedRemoteIds.has(localRule.id)) {
throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`);
throw validationError(`本地规则文件包含重复的规则 ID:${localRule.id}`);
}
} else {
const matches = remoteRules.filter(
(candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule)
);
if (matches.length > 1) {
throw new Error(
`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`
);
throw validationError(`本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。`);
}
remoteRule = matches[0];
}
+1
View File
@@ -129,6 +129,7 @@ export const SEAL_MUTATING_CAPABILITIES: ReadonlySet<string> = new Set([
"sealApprovalRuleUpdate",
"sealApprovalRuleVersionPublish",
"sealApprovalRulesClear",
"sealApprovalRulesRecode",
"sealApprovalRulesPush",
"sealApprovalStylePreferencesUpdate",
"sealDelegationCreate",
+1 -1
View File
@@ -1,7 +1,7 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight/export.js";
import type {
CapabilityContext
} from "./helpers.js";
+29 -114
View File
@@ -1,23 +1,24 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
import { executeRulePush } from "../rules/push.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
import { validationError } from "../../../core/errors.js";
import { redactSensitiveText } from "../../../core/redact.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { searchApprovalContent } from "../search/service.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rules/diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rules/version-snapshot.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
} from "../rules/local.js";
import {
type ApprovalRule,
type RuleSetVersion
type ApprovalRule
} from "../types.js";
import type {
CapabilityContext,
@@ -27,8 +28,6 @@ import * as helpers from "./helpers.js";
const {
projectApprovalRules,
buildRulePushPlan,
normalizeRuleStrictness,
mutationPreview,
summarizeRuleVersion,
resolveRuleVersionForLookup,
@@ -48,6 +47,16 @@ function attachCrossEnvRule(context: CapabilityContext, rule: Record<string, unk
}
export const rulesCapabilities = [
{
name: "sealApprovalRulesRecode",
description: "重排草稿规则编号;首次返回预览与一次性确认码,第二次携带确认码才执行,不发布版本",
parameters: z.object({
dryRun: z.boolean().optional().describe("只预览,不签发确认码或执行重排"),
confirmCode: z.string().optional().describe("第一次运行返回的一次性确认码")
}),
handler: async (client: KyInstance, params: RecodeOptions, context: CapabilityContext) =>
recodeRules(client, context.corp, params)
},
{
name: "sealApprovalRulesList",
description: "列出 Seal 审批规则(默认当前草稿,传 version='latest' 或版本号则列出对应已发布版本);支持 countOnly、fields、limit",
@@ -144,8 +153,13 @@ export const rulesCapabilities = [
const warnings: string[] = [];
let recode: unknown;
const remaining = await api.listApprovalRules(client);
if (deleted > 0 && params.recode !== false) {
recode = await api.recodeApprovalRules(client);
if (remaining.rules.length > 0) {
warnings.push("部分规则未删除,已跳过自动重排;如需重排剩余规则,请使用 rules recode 两阶段流程");
} else {
recode = await api.recodeApprovalRules(client);
}
if (
recode &&
typeof recode === "object" &&
@@ -156,7 +170,7 @@ export const rulesCapabilities = [
}
}
const after = await api.listApprovalRules(client);
const after = recode ? await api.listApprovalRules(client) : remaining;
return {
corpId: context.corp.id,
corpName: context.corp.name,
@@ -640,13 +654,14 @@ export const rulesCapabilities = [
},
{
name: "sealApprovalRulesPush",
description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本",
description: "将本地规则文件增量同步到远端草稿;支持持久化步骤恢复记录、状态核对(--status)与直接发布正式版本",
parameters: z.object({
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)"),
statusOnly: z.boolean().optional().describe("仅查询最近一次 rules push 的持久化步骤记录并与远端草稿核对,不执行写入")
}),
handler: async (
client: KyInstance,
@@ -656,110 +671,10 @@ export const rulesCapabilities = [
confirm?: boolean;
publish?: boolean;
versionName?: string;
statusOnly?: boolean;
},
context: CapabilityContext
) => {
const filePath = params.file ?? "./rules.local.json";
let local: ReturnType<typeof loadLocalRulesFile>;
try {
local = loadLocalRulesFile(filePath);
} catch (err) {
if (params.publish && !params.file) {
const suggestedName = params.versionName ?? "新版本";
throw new Error(
`${err instanceof Error ? err.message : String(err)}\n👉 Next action: 若您已直接修改远端草稿、仅需发布正式版本,请执行 seal-use rules publish "${suggestedName}" --corp ${context.corp.id}`
);
}
throw err;
}
const isConfirmed = params.confirm === true;
// Fail closed: without an explicit confirm the push always previews, even when dryRun=false.
const isDryRun = !isConfirmed || params.dryRun === true;
const before = await api.listApprovalRules(client);
const plan = buildRulePushPlan(before.rules, local.rules);
if (isDryRun) {
return {
...mutationPreview(
context,
"api/v1/rules",
before.rules,
local.rules.map((rule) => ({
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: rule.strictness ?? "MUST_FOLLOW"
})),
before.rules.length + local.rules.length
),
corpId: context.corp.id,
dryRun: true,
localFile: local.resolvedPath,
localRulesCount: local.rules.length,
remoteDraftCount: before.rules.length,
changes: plan,
impactCount: plan.created.length + plan.updated.length + plan.deleted.length,
preservedRuleIds: [
...plan.updated.map((change) => change.id),
...plan.unchanged.map((rule) => rule.id)
],
warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.",
willPublish: Boolean(params.publish),
message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."
};
}
for (const rule of plan.deleted) {
await api.deleteApprovalRule(client, rule.id);
}
const created: Array<{ id: string; description: string; code?: string | number }> = [];
for (const rule of plan.created) {
const newRule = await api.createApprovalRule(client, {
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(rule.strictness)
});
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
}
const updated: string[] = [];
for (const change of plan.updated) {
await api.updateApprovalRule(client, change.id, {
description: change.rule.description,
scope: change.rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(change.rule.strictness)
});
updated.push(change.id);
}
let publishedVersion: unknown = undefined;
if (params.publish) {
const dateStr = formatBeijingIso().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
publishedVersion = await api.publishApprovalRuleVersion(client, name);
try {
const draft = await api.listApprovalRules(client);
savePublishedRuleVersionSnapshot(context.corp.id, (publishedVersion as { version: RuleSetVersion }).version, draft.rules);
} catch {}
}
return {
corpId: context.corp.id,
dryRun: false,
localFile: local.resolvedPath,
deletedRules: plan.deleted.length,
createdRules: created.length,
updatedRules: updated.length,
unchangedRules: plan.unchanged.length,
preservedRuleIds: [
...updated,
...plan.unchanged.map((rule) => rule.id)
],
recoded: false,
published: publishedVersion ?? false
};
}
) => executeRulePush(client, params, context)
},
{
name: "sealApprovalDocumentsList",
+28 -23
View File
@@ -21,13 +21,11 @@ function rejectsWith(toolName: string, params: Record<string, unknown>): string
}
describe("parseCapabilityParams", () => {
test("accepts valid params and returns the exact object it was given", () => {
test("accepts valid params and returns normalized values without mutating caller input", () => {
const target = tool("sealUserCreate");
const params = { name: "张三", phone: "13800001111", departmentIds: ["d1"] };
// Identity matters: handlers read keys the schema does not declare, so the
// gate must pass its input through, never zod's (stripped) parse output.
expect(parseCapabilityParams(target, params)).toBe(params);
expect(parseCapabilityParams(target, params)).toEqual(params);
});
test("names the missing required field instead of letting the handler crash on undefined", () => {
@@ -42,14 +40,14 @@ describe("parseCapabilityParams", () => {
expect(message).toContain("limit");
});
test("coerces query-string values before checking, without touching the original", () => {
test("coerces query-string values and returns the coerced types without mutating the original", () => {
const target = tool("sealApprovalRunsSearch");
const params = { limit: "50", includeBridge: "true" } as Record<string, unknown>;
// /v1/* passes url.searchParams through: everything arrives as a string,
// but the schema declares z.number() / z.boolean(). Without coercion every
// REST route would 400 on its own documented query params.
expect(parseCapabilityParams(target, params)).toBe(params);
// but the schema declares z.number() / z.boolean(). Returning the coerced
// values ensures the handler receives the exact types the schema validated.
expect(parseCapabilityParams(target, params)).toEqual({ limit: 50, includeBridge: true });
expect(params.limit).toBe("50");
expect(params.includeBridge).toBe("true");
});
@@ -59,33 +57,40 @@ describe("parseCapabilityParams", () => {
expect(message).toContain("limit");
});
test("coerces a comma-separated query value into the array the schema wants", () => {
// `?fields=id,code` on /v1/approval/rules: today the handler receives a
// string and pickRuleFields iterates its characters, returning empty
// objects. Validation splits it so the documented form actually works.
test("coerces a comma-separated query value into the array the schema and handler want", () => {
// `?fields=id,code` on /v1/approval/rules: validation splits the string and
// hands the array to the handler so pickRuleFields iterates field names,
// not individual characters.
expect(parseCapabilityParams(tool("sealApprovalRulesList"), { fields: "id,code" })).toEqual({
fields: "id,code"
fields: ["id", "code"]
});
expect(rejectsWith("sealApprovalRulesList", { fields: "id,not-a-field" })).toContain("fields");
});
test("ignores undeclared keys rather than rejecting the request", () => {
// z.object is non-strict: an extra HTTP body key is a compatibility
// non-event, not an error. This gate checks declared params only.
test("preserves undeclared compatibility keys alongside normalized schema fields", () => {
// z.object is non-strict: an extra HTTP body key or legacy alias is kept
// while declared fields are coerced and defaulted.
const target = tool("sealApprovalRunsSearch");
expect(parseCapabilityParams(target, { status: "TERMINATED", corp: "corp-a", stray: 1 })).toBeTypeOf("object");
expect(parseCapabilityParams(target, { status: "TERMINATED", limit: "10", corp: "corp-a", stray: 1 })).toEqual({
status: "TERMINATED",
limit: 10,
corp: "corp-a",
stray: 1
});
});
test("lets the legacy credential aliases through to the handler that supports them", () => {
// sealDeployHosecloudConfigure has always accepted appKey/appSecurity
// alongside apiKey/apiSecret; a schema that declared only apiKey as
// required would have blocked that documented path.
expect(() =>
test("lets the legacy credential aliases through to the handler and populates schema defaults", () => {
expect(
parseCapabilityParams(tool("sealDeployHosecloudConfigure"), {
appKey: "key-1",
appSecurity: "secret-1",
mode: "assisted"
})
).not.toThrow();
).toEqual({
appKey: "key-1",
appSecurity: "secret-1",
mode: "assisted",
apiOrigin: "production"
});
});
});
+20 -21
View File
@@ -4,34 +4,33 @@ import type { SealCapability } from "./index.js";
/**
* Checks one invocation's params against the schema its tool declares, then
* returns the params unchanged.
* returns the normalized params (wire-format coercion + schema defaults applied,
* while preserving undeclared keys for legacy compatibility).
*
* Both dispatch paths — `runCapabilityResult` (every CLI command) and
* `executeSealCapability` (`POST /api/tool/:name`, every `/v1/*` route) — used to
* hand `params` straight to `handler`, so a required field could be missing, a
* limit could be `999999`, or a typo'd HTTP body key could sail through and
* surface later as an opaque upstream error or a `Cannot read properties of
* undefined`. The schema is now the gate, failing fast with the offending field
* path (exit `13` on the CLI, HTTP `400` behind the adapter).
* `executeSealCapability` — hand the returned object to `handler`, so the
* values that passed validation are the exact values the handler executes with.
*
* Two deliberate properties:
*
* - **Original params are returned, not `result.data`.** Handlers read keys the
* schema does not declare — `sealDeployHosecloudConfigure` accepts the
* legacy `appKey`/`appSecurity` aliases alongside `apiKey`/`apiSecret` — and
* zod's default strip would silently drop them. Validation must never change
* what a working handler receives, only block what would have failed anyway.
* - **Undeclared keys never fail.** `z.object` is non-strict, so an extra HTTP
* body key is ignored rather than rejected; this is a correctness check, not
* an API-compatibility verdict.
*
* Before rejecting, wire-format values are coerced to the shape the schema
* declares (see {@link coerceWireTypes}) because `/v1/*` query strings arrive
* entirely as strings while the schema says `z.number()`.
* - **Normalized declared keys + preserved undeclared keys.** Wire strings like
* `"50"`, `"true"`, or `"id,code"` are coerced to `50`, `true`, `["id", "code"]`
* and schema `.default(...)` values are filled in, while undeclared keys
* (such as legacy compatibility aliases) are kept rather than stripped.
* - **Caller input is not mutated in place.** A fresh object is returned.
*/
export function parseCapabilityParams(tool: SealCapability, params: Record<string, unknown>): Record<string, unknown> {
const result = tool.parameters.safeParse(coerceWireTypes(tool.parameters, params));
if (result.success) return params;
const coerced = coerceWireTypes(tool.parameters, params);
const result = tool.parameters.safeParse(coerced);
if (result.success) {
const parsedData =
result.data && typeof result.data === "object"
? Object.fromEntries(
Object.entries(result.data as Record<string, unknown>).filter(([, value]) => value !== undefined)
)
: {};
return { ...params, ...coerced, ...parsedData };
}
const detail = result.error.issues
.map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`)
+1 -1
View File
@@ -6,7 +6,7 @@ import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../replay/webhook.js";
import {
checkWebhookReadiness,
previewMaterialPack,
@@ -1,13 +1,13 @@
import { saveCorpConfig, type SavedCorpConfig } from "../../core/config/repository.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../core/config/timestamps.js";
import { saveCorpConfig, type SavedCorpConfig } from "../../../core/config/repository.js";
import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js";
import {
SealCookieMapSchema,
SealHeaderMapSchema,
type CorpConfig
} from "../../core/config/types.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { getMe } from "./api.js";
} from "../../../core/config/types.js";
import { createSealClientForUrl } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { getMe } from "../api.js";
export type RemoteSealIdentity = {
user: Record<string, unknown>;
@@ -1,8 +1,8 @@
import { CorpConfig } from "../../core/config/types.js";
import { createSealClient } from "../../core/http/factory.js";
import { resolveSealEnterpriseConfig } from "../../core/auth/seal.js";
import { SealEnterpriseConfig } from "../../core/auth/types.js";
import { getMe } from "./api.js";
import { CorpConfig } from "../../../core/config/types.js";
import { createSealClient } from "../../../core/http/factory.js";
import { resolveSealEnterpriseConfig } from "../../../core/auth/seal.js";
import { SealEnterpriseConfig } from "../../../core/auth/types.js";
import { getMe } from "../api.js";
export async function resolveLiveSealEnterpriseConfig(
corp: CorpConfig
@@ -4,8 +4,8 @@ import { homedir } from "node:os";
import { join } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import { type CorpConfig, CorpConfigSchema } from "../../core/config/types.js";
import { exportInsightReportToExcel, resolveInsightOutputFilePath } from "./insight-export.js";
import { type CorpConfig, CorpConfigSchema } from "../../../core/config/types.js";
import { exportInsightReportToExcel, resolveInsightOutputFilePath } from "./export.js";
describe("insight-export domain", () => {
test("resolveInsightOutputFilePath respects custom outputFile", () => {
@@ -3,11 +3,11 @@ import { homedir } from "node:os";
import { dirname, resolve } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import { getBeijingDate, resolveExportDateRange } from "./approval-runs-export.js";
import type { InsightPerformance } from "./types.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import { getBeijingDate, resolveExportDateRange } from "../approval-runs/export.js";
import type { InsightPerformance } from "../types.js";
export interface InsightExportOptions {
startDate?: string | number;
+1 -1
View File
@@ -7,7 +7,7 @@ import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import { extractApprovalRunAttachments, sanitizeFileName } from "../attachments.js";
import { extractApprovalRunAttachments, sanitizeFileName } from "../approval-runs/attachments.js";
import type { ApprovalRun } from "../types.js";
import type { ResourcePackExportOptions, ResourcePackExportResult } from "./types.js";
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import type { ApprovalIntegration, ApprovalStylePreferences } from "./types.js";
import type { CorpConfig } from "../../../core/config/types.js";
import type { ApprovalIntegration, ApprovalStylePreferences } from "../types.js";
import {
assertAssistedIntegration,
BLOCKING_NODE_ID,
@@ -12,7 +12,7 @@ import {
pushOutboundAndVerify,
resolveCorporationId,
selectHoseIntegration
} from "./outbound-push.js";
} from "./push.js";
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
@@ -1,15 +1,15 @@
import type { KyInstance } from "ky";
import { confirmationRequired, safetyBlocked, validationError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import type { ApprovalIntegration, ApprovalRun, ApprovalStylePreferences } from "./types.js";
import { confirmationRequired, safetyBlocked, validationError } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import type { ApprovalIntegration, ApprovalRun, ApprovalStylePreferences } from "../types.js";
/**
* Shared primitives for pushing a test/replay message into Seal's
* `/api/hosecloud/outbound` gateway. Two callers need them and they must stay
* in lockstep because they build the exact same wire payload:
* - `capabilities/deploy.ts` → `sealDeployHosecloudTestOutbound` (single tenant)
* - `hose-outbound-replay.ts` → `webhook replay --channel hose-outbound` (cross tenant)
* - `replay/hose-outbound.ts` → `webhook replay --channel hose-outbound` (cross tenant)
*
* Anything that describes the outbound contract (payload shape, blocking nodeId,
* integration selection, the assisted-only gate) lives here so a change to the
+1 -1
View File
@@ -9,7 +9,7 @@ import {
ensureTestWebhookIntegration,
pushWebhookDocument,
transformApprovalRunToWebhookDocument
} from "../webhook-replay.js";
} from "../replay/webhook.js";
export interface RegressionTestOptions {
sourceCorp: CorpConfig;
@@ -3,8 +3,8 @@ import {
selectMatchingOutboundLog,
validateHoseOutboundReplaySafety,
type HoseOutboundLogItem
} from "./hose-outbound-replay.js";
import type { CorpConfig } from "../../core/config/types.js";
} from "./hose-outbound.js";
import type { CorpConfig } from "../../../core/config/types.js";
const mockLogs: HoseOutboundLogItem[] = [
{
@@ -1,8 +1,8 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import { safetyBlocked, validationError } from "../../core/errors.js";
import { fetchHoseOutboundLogs, type HoseOutboundLogItem } from "../hose/close/outbound.js";
import * as api from "./api.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { safetyBlocked, validationError } from "../../../core/errors.js";
import { fetchHoseOutboundLogs, type HoseOutboundLogItem } from "../../hose/close/outbound.js";
import * as api from "../api.js";
import {
assertAssistedIntegration,
BLOCKING_NODE_ID,
@@ -13,11 +13,11 @@ import {
pushOutboundAndVerify,
resolveCorporationId,
selectHoseIntegration
} from "./outbound-push.js";
import { assertNonProductionReplayTarget } from "./replay-safety.js";
import type { ApprovalRun } from "./types.js";
} from "../outbound/push.js";
import { assertNonProductionReplayTarget } from "./safety.js";
import type { ApprovalRun } from "../types.js";
export type { HoseOutboundLogItem } from "../hose/close/outbound.js";
export type { HoseOutboundLogItem } from "../../hose/close/outbound.js";
export interface HoseOutboundReplayOptions {
sourceCorp: CorpConfig;
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import type { CorpConfig } from "../../core/config/types.js";
import { assertNonProductionReplayTarget } from "./replay-safety.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { assertNonProductionReplayTarget } from "./safety.js";
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
@@ -1,5 +1,5 @@
import { safetyBlocked } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { safetyBlocked } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
/**
* Shared environment guard for every replay channel: test traffic must never
@@ -9,9 +9,9 @@ import {
ensureTestWebhookIntegration,
executeApprovalRunsReplay,
ALLOWED_WEBHOOK_FIELD_TYPES
} from "./webhook-replay.js";
import type { ApprovalRun, WebhookIntegration } from "./types.js";
import type { CorpConfig } from "../../core/config/types.js";
} from "./webhook.js";
import type { ApprovalRun, WebhookIntegration } from "../types.js";
import type { CorpConfig } from "../../../core/config/types.js";
describe("webhook-replay domain", () => {
const mockWebhookIntegration: WebhookIntegration = {
@@ -1,12 +1,12 @@
import type { KyInstance } from "ky";
import type { ApprovalRun, WebhookIntegration } from "./types.js";
import type { MaterialField } from "./material-pack/types.js";
import { webhookHeaders } from "./material-pack/signature.js";
import { CliError, confirmationRequired, validationError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import * as api from "./api.js";
import { assertNonProductionReplayTarget } from "./replay-safety.js";
import type { ApprovalRun, WebhookIntegration } from "../types.js";
import type { MaterialField } from "../material-pack/types.js";
import { webhookHeaders } from "../material-pack/signature.js";
import { CliError, confirmationRequired, validationError } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import * as api from "../api.js";
import { assertNonProductionReplayTarget } from "./safety.js";
export const ALLOWED_WEBHOOK_FIELD_TYPES = new Set([
"TEXT",
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { diffRuleVersions, truncateRuleDiff } from "./rule-diff.js";
import { PublishedRuleSnapshotSchema, RuleSetVersionSchema, type RuleSetVersion } from "./types.js";
import { diffRuleVersions, truncateRuleDiff } from "./diff.js";
import { PublishedRuleSnapshotSchema, RuleSetVersionSchema, type RuleSetVersion } from "../types.js";
function version(versionNumber: number, rules: Array<Record<string, unknown>>): RuleSetVersion {
return {
@@ -1,4 +1,4 @@
import type { RuleSetVersion } from "./types.js";
import type { RuleSetVersion } from "../types.js";
export type RuleDiffStatus = "added" | "removed" | "modified" | "unchanged";
export type RuleDiffIdentityMode = "stable-id" | "code";
@@ -7,8 +7,8 @@ import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets
} from "./rules-local.js";
import { findSealCapability } from "./capabilities.js";
} from "./local.js";
import { findSealCapability } from "../capabilities.js";
const tempDirs: string[] = [];
@@ -1,6 +1,6 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import type { RuleLintTarget } from "./linter/types.js";
import type { RuleLintTarget } from "../linter/types.js";
export interface LocalRuleItem {
id?: string;
@@ -10,7 +10,7 @@ import {
loadRuleMappingSnapshot,
RuleMappingSnapshot,
saveRuleMappingSnapshot
} from "./rule-mapping.js";
} from "./mapping.js";
describe("rule-mapping", () => {
let testDir: string;
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { normalizeBeijingIso } from "../../core/config/timestamps.js";
import { SEAL_STATE_DIR } from "../../core/paths.js";
import { normalizeBeijingIso } from "../../../core/config/timestamps.js";
import { SEAL_STATE_DIR } from "../../../core/paths.js";
export interface RuleMappingItem {
index: number;
+349
View File
@@ -0,0 +1,349 @@
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 type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import { classifyCliError } from "../../../core/errors.js";
import { handleRulesCommand } from "../../../cli/commands/rules.js";
import { parseArgs } from "../../../cli/parser.js";
import type { ApprovalRule } from "../types.js";
import {
executeRulePush,
inspectRulePushStatus,
RulePushExecutionError,
RulePushJournalStore
} from "./push.js";
const ORIGINAL_JOURNAL = process.env.SEAL_USE_PUSH_JOURNAL;
const tempDirs: string[] = [];
afterEach(() => {
if (ORIGINAL_JOURNAL === undefined) delete process.env.SEAL_USE_PUSH_JOURNAL;
else process.env.SEAL_USE_PUSH_JOURNAL = ORIGINAL_JOURNAL;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function createPushFixture() {
const dir = mkdtempSync(join(tmpdir(), "seal-rules-push-"));
tempDirs.push(dir);
const journalPath = join(dir, "push-journal.json");
const localFilePath = join(dir, "rules.local.json");
process.env.SEAL_USE_PUSH_JOURNAL = journalPath;
const corp: CorpConfig = {
id: "push-corp",
name: "Push Test Corp",
environment: "test",
auth: { refreshTtl: 300 },
source: {
type: "seal",
token: "test-token",
sealUrl: "https://staging.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
seal: {
url: "https://staging.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
}
};
const remoteRules: ApprovalRule[] = [
{
id: "r-keep",
tenantId: "t1",
code: 0,
description: "Existing rule to update",
scope: "ALL",
strictness: "MUST_FOLLOW",
status: "ACTIVE"
},
{
id: "r-delete",
tenantId: "t1",
code: 1,
description: "Obsolete rule to delete",
scope: "ALL",
strictness: "SHOULD_FOLLOW",
status: "ACTIVE"
}
];
writeFileSync(
localFilePath,
JSON.stringify({
corpId: corp.id,
rules: [
{
id: "r-keep",
description: "Existing rule updated locally",
scope: "ALL",
strictness: "MUST_FOLLOW"
},
{
description: "New rule alpha",
scope: "travel",
strictness: "MUST_FOLLOW"
},
{
description: "New rule beta",
scope: "meal",
strictness: "SHOULD_FOLLOW"
}
]
})
);
let nextCreatedIdx = 1;
let failOnDeleteId: string | undefined;
let failOnCreateCall: number | undefined;
let failWithTimeout = false;
let applyBeforeTimeout = false;
let createCalls = 0;
const client = {
get: async (url: string) => {
if (url === "api/v1/rules") {
return Response.json({
data: { rules: structuredClone(remoteRules), hasPendingDeletes: false }
});
}
throw new Error(`Unexpected GET ${url}`);
},
delete: async (url: string) => {
const id = url.split("/").pop()!;
if (failOnDeleteId === id) {
const err = new Error(failWithTimeout ? "upstream timeout" : "Forbidden delete") as Error & {
response?: { status: number };
};
if (!failWithTimeout) err.response = { status: 400 };
throw err;
}
const idx = remoteRules.findIndex((rule) => rule.id === id);
if (idx >= 0) remoteRules.splice(idx, 1);
return Response.json({ data: { deleted: true } });
},
post: async (url: string, options?: { json?: Record<string, unknown> }) => {
if (url === "api/v1/rules") {
createCalls += 1;
const body = options?.json ?? {};
const createdRule: ApprovalRule = {
id: `r-new-${nextCreatedIdx++}`,
tenantId: "t1",
code: remoteRules.length,
description: String(body.description ?? ""),
scope: String(body.scope ?? "ALL"),
strictness: String(body.strictness ?? "MUST_FOLLOW"),
status: "DRAFT"
};
if (failOnCreateCall === createCalls) {
if (applyBeforeTimeout) {
remoteRules.push(createdRule);
}
const err = new Error(
failWithTimeout ? "socket hang up: request timed out" : "Duplicate rule rejected"
) as Error & { response?: { status: number } };
if (!failWithTimeout) err.response = { status: 422 };
throw err;
}
remoteRules.push(createdRule);
return Response.json({ data: createdRule });
}
throw new Error(`Unexpected POST ${url}`);
},
put: async (url: string, options?: { json?: Record<string, unknown> }) => {
const id = url.split("/").pop()!;
const target = remoteRules.find((rule) => rule.id === id);
if (!target) throw new Error(`Rule not found: ${id}`);
const body = options?.json ?? {};
if (typeof body.description === "string") target.description = body.description;
if (typeof body.scope === "string") target.scope = body.scope;
if (typeof body.strictness === "string") target.strictness = body.strictness;
return Response.json({ data: target });
}
} as unknown as KyInstance;
return {
corp,
client,
localFilePath,
journalPath,
remoteRules,
setFailOnDelete(id?: string, options?: { timeout?: boolean }) {
failOnDeleteId = id;
failWithTimeout = options?.timeout === true;
},
setFailOnCreate(callNumber?: number, options?: { timeout?: boolean; applyBeforeTimeout?: boolean }) {
failOnCreateCall = callNumber;
failWithTimeout = options?.timeout === true;
applyBeforeTimeout = options?.applyBeforeTimeout === true;
}
};
}
describe("rules push execution and recovery protocol", () => {
test("distinguishes not_started when the first write is rejected before any mutation", async () => {
const f = createPushFixture();
f.setFailOnDelete("r-delete");
try {
await executeRulePush(f.client, { file: f.localFilePath, confirm: true }, { corp: f.corp });
expect.unreachable();
} catch (error) {
expect(error).toBeInstanceOf(RulePushExecutionError);
const pushErr = error as RulePushExecutionError;
expect(classifyCliError(pushErr).exitCode).toBe(1);
expect(pushErr.journal.status).toBe("not_started");
expect(pushErr.recoveryPayload).toMatchObject({
status: "not_started",
executed: false,
deletedRules: 0,
createdRules: 0,
updatedRules: 0,
failedStep: {
stage: "delete",
targetId: "r-delete",
outcome: "failed"
}
});
}
const store = new RulePushJournalStore(f.journalPath);
expect(store.get(f.corp.id)?.status).toBe("not_started");
});
test("records partial completion, reconciles via status, and resumes idempotently without duplicating rules", async () => {
const f = createPushFixture();
// Delete succeeds, 1st create ("New rule alpha") succeeds, 2nd create ("New rule beta") fails with 422.
f.setFailOnCreate(2);
try {
await executeRulePush(f.client, { file: f.localFilePath, confirm: true }, { corp: f.corp });
expect.unreachable();
} catch (error) {
const pushErr = error as RulePushExecutionError;
expect(pushErr.journal.status).toBe("partial");
expect(pushErr.recoveryPayload).toMatchObject({
status: "partial",
executed: true,
deletedRules: 1,
createdRules: 1,
updatedRules: 0,
failedStep: {
stage: "create",
localIndex: 2,
description: "New rule beta",
outcome: "failed"
},
remaining: {
deleteIds: [],
createIndices: [2],
updateIds: ["r-keep"]
}
});
}
// Inspect status and reconcile against the live remote draft
const statusView = await inspectRulePushStatus(f.client, f.corp, f.localFilePath);
expect(statusView).toMatchObject({
corpId: f.corp.id,
status: "partial",
remoteDraftCount: 2,
reconciliation: {
verifiedDeletedIds: ["r-delete"],
stillPresentDeletedIds: [],
verifiedCreatedIds: ["r-new-1"],
missingCreatedIds: [],
remainingCounts: {
toDelete: 0,
toCreate: 1,
toUpdate: 1,
unchanged: 1
}
}
});
// Clear failure and resume: even if local file wasn't manually edited with r-new-1's ID,
// journal hydration binds r-new-1 to localIndex 1 so only "New rule beta" is created.
f.setFailOnCreate(undefined);
const resumed = await executeRulePush(
f.client,
{ file: f.localFilePath, confirm: true },
{ corp: f.corp }
);
expect(resumed).toMatchObject({
status: "completed",
deletedRules: 0,
createdRules: 1,
updatedRules: 1,
unchangedRules: 1
});
expect(f.remoteRules.map((r) => r.description)).toEqual([
"Existing rule updated locally",
"New rule alpha",
"New rule beta"
]);
});
test("marks timeout during mutation as uncertain and status resolves whether the server applied it", async () => {
const f = createPushFixture();
// Simulate a timeout on the 2nd create AFTER the server already committed the rule.
f.setFailOnCreate(2, { timeout: true, applyBeforeTimeout: true });
try {
await executeRulePush(f.client, { file: f.localFilePath, confirm: true }, { corp: f.corp });
expect.unreachable();
} catch (error) {
const pushErr = error as RulePushExecutionError;
expect(pushErr.journal.status).toBe("uncertain");
expect(pushErr.journal.failedStep).toMatchObject({
stage: "create",
description: "New rule beta",
outcome: "uncertain"
});
}
const statusView = await inspectRulePushStatus(f.client, f.corp, f.localFilePath);
expect(statusView.status).toBe("uncertain");
expect(statusView.reconciliation).toMatchObject({
uncertainStepResolution: "applied",
remainingCounts: {
toDelete: 0,
toCreate: 0,
toUpdate: 1,
unchanged: 2
}
});
});
test("CLI prints structured recovery JSON to stdout before throwing exit 1 on partial failure", async () => {
const f = createPushFixture();
f.setFailOnCreate(2);
const lines: string[] = [];
const originalLog = console.log;
console.log = (...values: unknown[]) => {
lines.push(values.map(String).join(" "));
};
try {
const args = parseArgs(["rules", "push", "--file", f.localFilePath, "--corp", f.corp.id, "--yes"]);
await expect(
handleRulesCommand("push", undefined, f.client, f.corp, args)
).rejects.toMatchObject({ exitCode: 1 });
const payload = JSON.parse(lines.join("\n"));
expect(payload).toMatchObject({
corpId: f.corp.id,
status: "partial",
executed: true,
deletedRules: 1,
createdRules: 1
});
expect(payload.nextCommand).toContain("rules push status");
} finally {
console.log = originalLog;
}
});
});
+533
View File
@@ -0,0 +1,533 @@
import { randomBytes } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { CliError } from "../../../core/errors.js";
import { SEAL_STATE_DIR } from "../../../core/paths.js";
import { redactSensitiveText } from "../../../core/redact.js";
import * as api from "../api.js";
import {
buildRulePushPlan,
mutationPreview,
normalizeRuleStrictness,
type CapabilityContext,
type RulePushPlan
} from "../capabilities/helpers.js";
import type { ApprovalRule, RuleSetVersion } from "../types.js";
import { loadLocalRulesFile, type LocalRuleItem } from "./local.js";
import { savePublishedRuleVersionSnapshot } from "./version-snapshot.js";
export type RulePushStatus = "preview" | "not_started" | "partial" | "completed" | "uncertain";
export type RulePushFailedStep = {
stage: "delete" | "create" | "update" | "publish";
targetId?: string;
localIndex?: number;
description?: string;
outcome: "failed" | "uncertain";
error: string;
};
export type RulePushCreatedRecord = {
localIndex: number;
id: string;
code?: string | number;
description: string;
scope: string;
strictness: string;
};
export type RulePushJournalEntry = {
operationId: string;
corpId: string;
localFile: string;
startedAt: string;
updatedAt: string;
status: Exclude<RulePushStatus, "preview">;
planned: {
deleteIds: string[];
createIndices: number[];
updateIds: string[];
publish: boolean;
};
completed: {
deletedIds: string[];
created: RulePushCreatedRecord[];
updatedIds: string[];
published: unknown;
};
failedStep?: RulePushFailedStep;
remaining: {
deleteIds: string[];
createIndices: number[];
updateIds: string[];
publish: boolean;
};
};
export class RulePushExecutionError extends CliError {
readonly journal: RulePushJournalEntry;
readonly recoveryPayload: Record<string, unknown>;
constructor(journal: RulePushJournalEntry, corpId: string) {
const quotedCorp = `'${corpId.replace(/'/g, "'\\''")}'`;
const nextAction = `seal-use rules push status --corp ${quotedCorp}`;
const label =
journal.status === "not_started"
? "未完成任何写入"
: journal.status === "uncertain"
? "存在结果不确定的写入请求"
: "仅完成部分写入";
super(
`rules push 中途失败(${label},阶段: ${journal.failedStep?.stage ?? "unknown"}):${journal.failedStep?.error ?? "未知错误"}`,
1,
nextAction
);
this.name = "RulePushExecutionError";
this.journal = journal;
this.recoveryPayload = {
corpId: journal.corpId,
dryRun: false,
executed:
journal.completed.deletedIds.length > 0 ||
journal.completed.created.length > 0 ||
journal.completed.updatedIds.length > 0 ||
Boolean(journal.completed.published),
status: journal.status,
operationId: journal.operationId,
localFile: journal.localFile,
deletedRules: journal.completed.deletedIds.length,
createdRules: journal.completed.created.length,
updatedRules: journal.completed.updatedIds.length,
completed: journal.completed,
failedStep: journal.failedStep,
remaining: journal.remaining,
nextCommand: nextAction
};
}
}
export class RulePushJournalStore {
constructor(
private readonly path = process.env.SEAL_USE_PUSH_JOURNAL?.trim() ||
join(SEAL_STATE_DIR, "rules-push-journal.json")
) {}
private readAll(): Record<string, RulePushJournalEntry> {
if (!existsSync(this.path)) return {};
try {
const parsed = JSON.parse(readFileSync(this.path, "utf8"));
return parsed && typeof parsed === "object" ? (parsed as Record<string, RulePushJournalEntry>) : {};
} catch {
return {};
}
}
get(corpId: string): RulePushJournalEntry | undefined {
return this.readAll()[corpId];
}
save(entry: RulePushJournalEntry): void {
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
const all = this.readAll();
all[entry.corpId] = entry;
writeFileSync(this.path, `${JSON.stringify(all, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
try {
chmodSync(this.path, 0o600);
} catch {}
}
}
function isUncertainMutationError(error: unknown): boolean {
if (error && typeof error === "object" && "response" in error) {
const response = (error as { response?: { status?: unknown } }).response;
const status = typeof response?.status === "number" ? response.status : undefined;
if (status !== undefined) {
if (status >= 400 && status < 500) return false;
if (status === 502 || status === 503 || status === 504) return true;
}
}
const message = error instanceof Error ? error.message : String(error);
return /(?:timeout|timed out|hang up|econnreset|etimedout|network|fetch failed|aborted|502|503|504)/i.test(
message
);
}
/**
* Hydrates local rules with IDs recorded during a prior partial/uncertain push
* on the same file when those rule IDs now exist in the remote draft. This
* allows a retry of `rules push` to recognize rules it already created without
* duplicating them or failing on duplicate descriptions.
*/
export function hydrateLocalRulesFromJournal(
localRules: LocalRuleItem[],
resolvedPath: string,
remoteRules: ApprovalRule[],
journal?: RulePushJournalEntry
): LocalRuleItem[] {
if (!journal || journal.localFile !== resolvedPath) return localRules;
if (journal.status !== "partial" && journal.status !== "uncertain") return localRules;
if (!journal.completed.created.length) return localRules;
const remoteById = new Map(remoteRules.map((rule) => [rule.id, rule]));
const usedIds = new Set(localRules.map((rule) => rule.id).filter((id): id is string => Boolean(id)));
const cloned = localRules.map((rule) => ({ ...rule }));
for (const record of journal.completed.created) {
if (usedIds.has(record.id)) continue;
const remote = remoteById.get(record.id);
if (!remote) continue;
const candidate = cloned[record.localIndex];
if (candidate && !candidate.id) {
candidate.id = record.id;
usedIds.add(record.id);
}
}
return cloned;
}
export async function inspectRulePushStatus(
client: KyInstance,
corp: CorpConfig,
filePath = "./rules.local.json"
) {
const store = new RulePushJournalStore();
const lastOperation = store.get(corp.id) ?? null;
const remote = await api.listApprovalRules(client);
const remoteById = new Map(remote.rules.map((rule) => [rule.id, rule]));
const targetFile = lastOperation?.localFile ?? filePath;
let local: ReturnType<typeof loadLocalRulesFile> | undefined;
let remainingPlan: RulePushPlan | undefined;
try {
local = loadLocalRulesFile(targetFile);
const hydrated = hydrateLocalRulesFromJournal(
local.rules,
local.resolvedPath,
remote.rules,
lastOperation ?? undefined
);
remainingPlan = buildRulePushPlan(remote.rules, hydrated);
} catch {
// Local file may have been moved or may need manual fix; still report remote vs journal reconciliation.
}
let reconciliation: Record<string, unknown> | null = null;
if (lastOperation) {
const verifiedDeletedIds = lastOperation.completed.deletedIds.filter((id) => !remoteById.has(id));
const stillPresentDeletedIds = lastOperation.completed.deletedIds.filter((id) => remoteById.has(id));
const verifiedCreatedIds = lastOperation.completed.created
.map((item) => item.id)
.filter((id) => remoteById.has(id));
const missingCreatedIds = lastOperation.completed.created
.map((item) => item.id)
.filter((id) => !remoteById.has(id));
let uncertainStepResolution: "applied" | "not_applied" | "unknown" | undefined;
if (lastOperation.failedStep?.outcome === "uncertain") {
const step = lastOperation.failedStep;
if (step.stage === "delete" && step.targetId) {
uncertainStepResolution = remoteById.has(step.targetId) ? "not_applied" : "applied";
} else if (step.stage === "update" && step.targetId && local && step.localIndex !== undefined) {
const remoteRule = remoteById.get(step.targetId);
const localRule = local.rules[step.localIndex];
if (remoteRule && localRule) {
uncertainStepResolution =
remoteRule.description === localRule.description.trim() &&
remoteRule.scope === (localRule.scope ?? "ALL") &&
remoteRule.strictness === normalizeRuleStrictness(localRule.strictness)
? "applied"
: "not_applied";
} else {
uncertainStepResolution = "unknown";
}
} else if (step.stage === "create" && step.description) {
const matched = remote.rules.some((rule) => rule.description === step.description);
uncertainStepResolution = matched ? "applied" : "not_applied";
} else {
uncertainStepResolution = "unknown";
}
}
reconciliation = {
verifiedDeletedIds,
stillPresentDeletedIds,
verifiedCreatedIds,
missingCreatedIds,
...(uncertainStepResolution ? { uncertainStepResolution } : {}),
...(remainingPlan
? {
remainingCounts: {
toDelete: remainingPlan.deleted.length,
toCreate: remainingPlan.created.length,
toUpdate: remainingPlan.updated.length,
unchanged: remainingPlan.unchanged.length
}
}
: {})
};
}
return {
corpId: corp.id,
status: lastOperation?.status ?? ("not_started" as const),
remoteDraftCount: remote.rules.length,
lastOperation,
reconciliation
};
}
export async function executeRulePush(
client: KyInstance,
params: {
file?: string;
dryRun?: boolean;
confirm?: boolean;
publish?: boolean;
versionName?: string;
statusOnly?: boolean;
},
context: CapabilityContext
) {
if (params.statusOnly) {
return inspectRulePushStatus(client, context.corp, params.file);
}
const filePath = params.file ?? "./rules.local.json";
let local: ReturnType<typeof loadLocalRulesFile>;
try {
local = loadLocalRulesFile(filePath);
} catch (err) {
if (params.publish && !params.file) {
const suggestedName = params.versionName ?? "新版本";
throw new Error(
`${err instanceof Error ? err.message : String(err)}\n👉 Next action: 若您已直接修改远端草稿、仅需发布正式版本,请执行 seal-use rules publish "${suggestedName}" --corp ${context.corp.id}`
);
}
throw err;
}
const isConfirmed = params.confirm === true;
// Fail closed: without an explicit confirm the push always previews, even when dryRun=false.
const isDryRun = !isConfirmed || params.dryRun === true;
const store = new RulePushJournalStore();
const previousJournal = store.get(context.corp.id);
const before = await api.listApprovalRules(client);
const effectiveLocalRules = hydrateLocalRulesFromJournal(
local.rules,
local.resolvedPath,
before.rules,
previousJournal
);
const plan = buildRulePushPlan(before.rules, effectiveLocalRules);
if (isDryRun) {
return {
...mutationPreview(
context,
"api/v1/rules",
before.rules,
effectiveLocalRules.map((rule) => ({
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: rule.strictness ?? "MUST_FOLLOW"
})),
before.rules.length + effectiveLocalRules.length
),
corpId: context.corp.id,
dryRun: true,
status: "preview" as const,
localFile: local.resolvedPath,
localRulesCount: effectiveLocalRules.length,
remoteDraftCount: before.rules.length,
changes: plan,
impactCount: plan.created.length + plan.updated.length + plan.deleted.length,
preservedRuleIds: [
...plan.updated.map((change) => change.id),
...plan.unchanged.map((rule) => rule.id)
],
warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.",
willPublish: Boolean(params.publish),
message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."
};
}
// Map each planned creation back to its index in effectiveLocalRules so the
// recovery journal can bind the newly created remote ID on resume.
const createdLocalIndices: number[] = [];
const usedLocalIndices = new Set<number>();
for (const createdRule of plan.created) {
const idx = effectiveLocalRules.findIndex(
(candidate, index) => !usedLocalIndices.has(index) && candidate === createdRule
);
const resolvedIdx = idx >= 0 ? idx : createdLocalIndices.length;
usedLocalIndices.add(resolvedIdx);
createdLocalIndices.push(resolvedIdx);
}
const startedAt = formatBeijingIso();
const journal: RulePushJournalEntry = {
operationId: `push-${Date.now()}-${randomBytes(3).toString("hex")}`,
corpId: context.corp.id,
localFile: local.resolvedPath,
startedAt,
updatedAt: startedAt,
status: "not_started",
planned: {
deleteIds: plan.deleted.map((rule) => rule.id),
createIndices: [...createdLocalIndices],
updateIds: plan.updated.map((change) => change.id),
publish: Boolean(params.publish)
},
completed: {
deletedIds: [],
created: [],
updatedIds: [],
published: false
},
remaining: {
deleteIds: plan.deleted.map((rule) => rule.id),
createIndices: [...createdLocalIndices],
updateIds: plan.updated.map((change) => change.id),
publish: Boolean(params.publish)
}
};
store.save(journal);
const failStep = (
stage: RulePushFailedStep["stage"],
error: unknown,
meta: { targetId?: string; localIndex?: number; description?: string } = {}
): never => {
const outcome = isUncertainMutationError(error) ? "uncertain" : "failed";
const completedCount =
journal.completed.deletedIds.length +
journal.completed.created.length +
journal.completed.updatedIds.length +
(journal.completed.published ? 1 : 0);
journal.status =
outcome === "uncertain"
? "uncertain"
: completedCount === 0
? "not_started"
: "partial";
journal.updatedAt = formatBeijingIso();
journal.failedStep = {
stage,
...meta,
outcome,
error: redactSensitiveText(error instanceof Error ? error.message : String(error))
};
store.save(journal);
throw new RulePushExecutionError(journal, context.corp.id);
};
for (const rule of plan.deleted) {
try {
await api.deleteApprovalRule(client, rule.id);
journal.completed.deletedIds.push(rule.id);
journal.remaining.deleteIds = journal.remaining.deleteIds.filter((id) => id !== rule.id);
journal.status = "partial";
journal.updatedAt = formatBeijingIso();
store.save(journal);
} catch (error) {
failStep("delete", error, { targetId: rule.id, description: rule.description });
}
}
for (let i = 0; i < plan.created.length; i++) {
const rule = plan.created[i]!;
const localIndex = createdLocalIndices[i] ?? i;
const scope = rule.scope ?? "ALL";
const strictness = normalizeRuleStrictness(rule.strictness);
try {
const newRule = await api.createApprovalRule(client, {
description: rule.description,
scope,
strictness
});
journal.completed.created.push({
localIndex,
id: newRule.id,
code: newRule.code,
description: newRule.description,
scope,
strictness
});
journal.remaining.createIndices = journal.remaining.createIndices.filter((idx) => idx !== localIndex);
journal.status = "partial";
journal.updatedAt = formatBeijingIso();
store.save(journal);
} catch (error) {
failStep("create", error, { localIndex, description: rule.description });
}
}
for (const change of plan.updated) {
const localIndex = effectiveLocalRules.indexOf(change.rule);
try {
await api.updateApprovalRule(client, change.id, {
description: change.rule.description,
scope: change.rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(change.rule.strictness)
});
journal.completed.updatedIds.push(change.id);
journal.remaining.updateIds = journal.remaining.updateIds.filter((id) => id !== change.id);
journal.status = "partial";
journal.updatedAt = formatBeijingIso();
store.save(journal);
} catch (error) {
failStep("update", error, {
targetId: change.id,
...(localIndex >= 0 ? { localIndex } : {}),
description: change.rule.description
});
}
}
let publishedVersion: unknown = undefined;
if (params.publish) {
const dateStr = formatBeijingIso().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
try {
publishedVersion = await api.publishApprovalRuleVersion(client, name);
journal.completed.published = publishedVersion;
journal.remaining.publish = false;
} catch (error) {
failStep("publish", error, { description: name });
}
try {
const draft = await api.listApprovalRules(client);
savePublishedRuleVersionSnapshot(
context.corp.id,
(publishedVersion as { version: RuleSetVersion }).version,
draft.rules
);
} catch {}
}
journal.status = "completed";
journal.updatedAt = formatBeijingIso();
store.save(journal);
return {
corpId: context.corp.id,
dryRun: false,
status: "completed" as const,
operationId: journal.operationId,
localFile: local.resolvedPath,
deletedRules: plan.deleted.length,
createdRules: journal.completed.created.length,
updatedRules: journal.completed.updatedIds.length,
unchangedRules: plan.unchanged.length,
preservedRuleIds: [
...journal.completed.updatedIds,
...plan.unchanged.map((rule) => rule.id)
],
recoded: false,
published: publishedVersion ?? false
};
}
@@ -0,0 +1,74 @@
import { afterEach, describe, expect, test } from "bun:test"
import { mkdtempSync, rmSync, statSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { RecodeTicketStore } from "./recode-tickets.js"
const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
function storePath() {
const dir = mkdtempSync(join(tmpdir(), "seal-recode-tickets-"))
dirs.push(dir)
return join(dir, "tickets.sqlite")
}
describe("recode confirmation tickets", () => {
test("enforces the private activation interval without spending an early ticket", () => {
let now = 1_000_000
const store = new RecodeTicketStore(storePath(), () => now)
const ticket = store.issue("target", "draft")
expect(ticket.confirmCode).toMatch(/^[0-9A-F]{6}$/)
now += 499
expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("尚未生效")
now += 1
store.consume(ticket.confirmCode, "target", "draft")
expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("已使用")
})
test("persists across instances, binds target and draft, and protects file permissions", () => {
let now = 1_000_000
const path = storePath()
const ticket = new RecodeTicketStore(path, () => now).issue("corp-a:staging:recode", "draft-a")
now += 500
const second = new RecodeTicketStore(path, () => now)
expect(() => second.consume(ticket.confirmCode, "corp-b:staging:recode", "draft-a")).toThrow("企业或环境")
expect(() => second.consume(ticket.confirmCode, "corp-a:production:recode", "draft-a")).toThrow("企业或环境")
expect(() => second.consume(ticket.confirmCode, "corp-a:staging:recode", "draft-b")).toThrow("草稿规则已变化")
second.consume(ticket.confirmCode.toLowerCase(), "corp-a:staging:recode", "draft-a")
expect(statSync(path).mode & 0o777).toBe(0o600)
})
test("rejects expired, malformed, unknown and backward-clock tickets", () => {
let now = 1_000_000
const store = new RecodeTicketStore(storePath(), () => now)
const ticket = store.issue("target", "draft")
now -= 1
expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("已失效")
now = ticket.expiresAt
expect(() => store.consume(ticket.confirmCode, "target", "draft")).toThrow("已失效")
expect(() => store.consume("anything", "target", "draft")).toThrow("无效")
const unknown = ticket.confirmCode === "000000" ? "FFFFFF" : "000000"
expect(() => store.consume(unknown, "target", "draft")).toThrow("不存在")
})
test("only one competing process can consume the same ticket", async () => {
const path = storePath()
const ticket = new RecodeTicketStore(path, () => Date.now() - 1_000).issue("target", "draft")
const source = `import { RecodeTicketStore } from ${JSON.stringify(join(import.meta.dirname, "recode-tickets.ts"))};
try { new RecodeTicketStore(${JSON.stringify(path)}).consume(${JSON.stringify(ticket.confirmCode)}, "target", "draft"); console.log("consumed") }
catch { console.log("blocked") }`
const children = Array.from({ length: 8 }, () => Bun.spawn([process.execPath, "-e", source], { stdout: "pipe", stderr: "pipe" }))
const outputs = await Promise.all(children.map(async child => {
const output = await new Response(child.stdout).text()
const errors = await new Response(child.stderr).text()
expect(await child.exited).toBe(0)
expect(errors).toBe("")
return output.trim()
}))
expect(outputs.filter(output => output === "consumed")).toHaveLength(1)
expect(outputs.filter(output => output === "blocked")).toHaveLength(7)
})
})
+105
View File
@@ -0,0 +1,105 @@
import { Database } from "bun:sqlite"
import { createHash, randomBytes } from "node:crypto"
import { chmodSync, mkdirSync } from "node:fs"
import { dirname, join } from "node:path"
import { CliError, confirmationRequired } from "../../../core/errors.js"
import { SEAL_STATE_DIR } from "../../../core/paths.js"
const MIN_CONFIRMATION_AGE_MS = 500
const TICKET_TTL_MS = 5 * 60_000
type Ticket = {
target: string
fingerprint: string
issuedAt: number
expiresAt: number
consumedAt: number | null
}
/** Local, cross-process confirmation state; no daemon or tenant credentials. */
export class RecodeTicketStore {
constructor(
private readonly path = process.env.SEAL_USE_RECODE_STORE?.trim() || join(SEAL_STATE_DIR, "recode-tickets.sqlite"),
private readonly now: () => number = () => Date.now()
) {}
private open(): Database {
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })
const db = new Database(this.path, { create: true, strict: true })
try {
chmodSync(this.path, 0o600)
db.exec("PRAGMA busy_timeout = 5000")
db.exec(`CREATE TABLE IF NOT EXISTS recode_tickets (
codeHash TEXT PRIMARY KEY,
target TEXT NOT NULL,
fingerprint TEXT NOT NULL,
issuedAt INTEGER NOT NULL,
expiresAt INTEGER NOT NULL,
consumedAt INTEGER
)`)
return db
} catch (error) {
db.close()
throw error
}
}
issue(target: string, fingerprint: string): { confirmCode: string; expiresAt: number } {
const db = this.open()
try {
const issuedAt = this.now()
const expiresAt = issuedAt + TICKET_TTL_MS
// Keep spent hashes: a previously issued six-character code is never reissued.
for (let attempt = 0; attempt < 20; attempt++) {
const confirmCode = randomBytes(3).toString("hex").toUpperCase()
const inserted = db.query(`INSERT OR IGNORE INTO recode_tickets
(codeHash, target, fingerprint, issuedAt, expiresAt) VALUES (?, ?, ?, ?, ?)`)
.run(hashCode(confirmCode), target, fingerprint, issuedAt, expiresAt)
if (inserted.changes === 1) return { confirmCode, expiresAt }
}
throw new Error("无法生成规则重排确认码,请重新申请")
} finally {
db.close()
}
}
consume(code: string, target: string, fingerprint: string): void {
const confirmCode = code.trim().toUpperCase()
const nextAction = "seal-use rules recode --corp <corpId>"
if (!/^[0-9A-F]{6}$/.test(confirmCode)) {
throw confirmationRequired("规则重排确认码无效,请重新申请。", nextAction)
}
const db = this.open()
try {
// The write transaction covers validation AND consumption. Competing CLI
// processes cannot both authorize a POST using the same ticket.
db.transaction(() => {
const codeHash = hashCode(confirmCode)
const ticket = db.query<Ticket, [string]>("SELECT * FROM recode_tickets WHERE codeHash = ?").get(codeHash)
if (!ticket || ticket.consumedAt !== null) {
throw confirmationRequired("规则重排确认码不存在或已使用,请重新申请。", nextAction)
}
const now = this.now()
if (now < ticket.issuedAt || now >= ticket.expiresAt) {
throw confirmationRequired("规则重排确认码已失效,请重新申请。", nextAction)
}
if (ticket.target !== target) {
throw confirmationRequired("规则重排确认码不适用于当前企业或环境。", nextAction)
}
if (ticket.fingerprint !== fingerprint) {
throw confirmationRequired("草稿规则已变化,请重新预览并申请确认码。", nextAction)
}
if (now - ticket.issuedAt < MIN_CONFIRMATION_AGE_MS) {
throw new CliError("确认码尚未生效,请稍后使用第一次返回的 nextCommand 重试。", 10)
}
db.query("UPDATE recode_tickets SET consumedAt = ? WHERE codeHash = ?").run(now, codeHash)
}).immediate()
} finally {
db.close()
}
}
}
function hashCode(code: string): string {
return createHash("sha256").update(code).digest("hex")
}
+224
View File
@@ -0,0 +1,224 @@
import { afterEach, describe, expect, test } from "bun:test"
import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import type { KyInstance } from "ky"
import type { CorpConfig } from "../../../core/config/types.js"
import { classifyCliError } from "../../../core/errors.js"
import { recodeRules } from "./recode.js"
import { recodeApprovalRules } from "../api.js"
import type { ApprovalRulesData } from "../types.js"
import { runCapabilityResult } from "../../../cli/helpers.js"
import { handleRulesCommand } from "../../../cli/commands/rules.js"
import { parseArgs } from "../../../cli/parser.js"
const originalStore = process.env.SEAL_USE_RECODE_STORE
const dirs: string[] = []
afterEach(() => {
if (originalStore === undefined) delete process.env.SEAL_USE_RECODE_STORE
else process.env.SEAL_USE_RECODE_STORE = originalStore
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
function fixture() {
const dir = mkdtempSync(join(tmpdir(), "seal-rules-recode-"))
dirs.push(dir)
process.env.SEAL_USE_RECODE_STORE = join(dir, "tickets.sqlite")
const corp: CorpConfig = {
id: "recode-test", name: "Test Corp", environment: "test", auth: { refreshTtl: 300 },
source: { type: "seal", token: "test-token", sealUrl: "https://staging.sealai.cc", expiresIn: 3600, staffId: "seal" },
seal: { url: "https://staging.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } }
}
const state: ApprovalRulesData = {
hasPendingDeletes: true,
rules: [
{ id: "a", tenantId: "tenant-a", code: 0, description: "Keep invoice", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE", updatedAt: 100 },
{ id: "b", tenantId: "tenant-a", code: 4, description: "Attach receipt", scope: "ALL", strictness: "SHOULD_FOLLOW", status: "DRAFT", updatedAt: 100 }
]
}
const calls: string[] = []
let tenantId = "tenant-a"
let origin = "https://staging.sealai.cc"
let failPost = false
let corruptReadback = false
let reorderOnServer = false
const client = {
get: async (url: string) => {
calls.push(`GET ${url}`)
const data = url === "api/v1/rules" ? structuredClone(state) : {
user: { id: "operator", tenantId, name: "Operator" }, tenant: { id: tenantId, name: "Tenant" }
}
const response = Response.json({ data })
Object.defineProperty(response, "url", { value: `${origin}/${url}` })
return response
},
post: async (url: string, options: { retry?: number }) => {
calls.push(`POST ${url}`)
expect(options.retry).toBe(0)
if (failPost) throw new Error("upstream timeout")
const order = [...state.rules].sort((a, b) => Number(a.code) - Number(b.code))
if (reorderOnServer) order.reverse()
order.forEach((rule, index) => { rule.code = index })
if (corruptReadback) state.rules[0]!.description = "concurrent edit"
return Response.json({ data: { activeRules: state.rules.length, pendingDeleteRules: 1, nextCode: state.rules.length } })
}
} as unknown as KyInstance
return {
client, corp, state, calls,
changeTenant: () => { tenantId = "tenant-b" },
changeOrigin: () => { origin = "https://production.sealai.cc" },
failPost: () => { failPost = true },
corruptReadback: () => { corruptReadback = true },
reorderOnServer: () => { reorderOnServer = true }
}
}
async function ticket(f: ReturnType<typeof fixture>) {
const result = await recodeRules(f.client, f.corp, {})
if (!("confirmCode" in result)) throw new Error("expected a confirmation ticket")
return result.confirmCode
}
describe("two-phase rules recode", () => {
test("dry-run never issues a ticket, and yes/confirm cannot bypass the shared capability", async () => {
const f = fixture()
const preview = await recodeRules(f.client, f.corp, { dryRun: true })
expect(preview).toMatchObject({ phase: "preview", executed: false, impactCount: 2, mappingAvailable: false })
expect(preview.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0000", "0001"] })
expect(preview).not.toHaveProperty("confirmCode")
const first = await runCapabilityResult("sealApprovalRulesRecode", f.client, f.corp, { yes: true, confirm: true })
expect(first).toMatchObject({ executed: false, phase: "confirmation_required" })
expect(first).toHaveProperty("confirmCode")
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
})
test("an early second call is rejected; a later call preserves identities and content", async () => {
const f = fixture()
const code = await ticket(f)
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("尚未生效")
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
await Bun.sleep(510)
const result = await recodeRules(f.client, f.corp, { confirmCode: code })
expect(result).toMatchObject({ executed: true, phase: "executed", nextCode: 2 })
expect(result.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0000", "0001"] })
expect(f.state.rules.map(rule => rule.id)).toEqual(["a", "b"])
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow()
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(1)
})
test("does not promise old-code order and reports a server-assigned permutation truthfully", async () => {
const f = fixture()
const code = await ticket(f)
f.reorderOnServer()
await Bun.sleep(510)
const result = await recodeRules(f.client, f.corp, { confirmCode: code })
expect(result).toMatchObject({ executed: true, impactCount: 2, mappingAvailable: true })
expect(result.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0001", "0000"] })
if (!("changes" in result)) throw new Error("expected verified changes")
expect(result.changes).toEqual([{ beforeCode: "0000", afterCode: "0001" }, { beforeCode: "0004", afterCode: "0000" }])
})
test.each(["corp", "origin", "tenant", "content", "timestamp", "pendingDeletes"])("rejects a changed %s before any POST", async change => {
const f = fixture()
const code = await ticket(f)
if (change === "corp") f.corp.id = "another-corp"
if (change === "origin") f.changeOrigin()
if (change === "tenant") f.changeTenant()
if (change === "content") f.state.rules[0]!.description = "Changed"
if (change === "timestamp") f.state.rules[0]!.updatedAt = 101
if (change === "pendingDeletes") f.state.hasPendingDeletes = false
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow()
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
})
test("a failed POST spends the ticket and is not retried", async () => {
const f = fixture()
const code = await ticket(f)
await Bun.sleep(510)
f.failPost()
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("upstream timeout")
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("已使用")
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(1)
})
test("readback detects a concurrent content change after the POST and classifies as exit 1 (never 13)", async () => {
const f = fixture()
const code = await ticket(f)
await Bun.sleep(510)
f.corruptReadback()
try {
await recodeRules(f.client, f.corp, { confirmCode: code })
expect.unreachable()
} catch (error) {
expect((error as Error).message).toContain("回读规则与预览不一致")
expect(classifyCliError(error)).toEqual({
exitCode: 1,
nextAction: "seal-use rules list --corp 'recode-test' --summary"
})
}
})
test("backend contract: handles server placing newly created DRAFT rules ahead of older ACTIVE rules", async () => {
const f = fixture()
f.state.rules = [
{ id: "active-old", tenantId: "tenant-a", code: 2, description: "Existing active rule", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE", updatedAt: 100 },
{ id: "draft-new", tenantId: "tenant-a", code: 9, description: "New draft rule placed first by server", scope: "ALL", strictness: "SHOULD_FOLLOW", status: "DRAFT", updatedAt: 200 }
]
const code = await ticket(f)
f.reorderOnServer()
await Bun.sleep(510)
const result = await recodeRules(f.client, f.corp, { confirmCode: code })
expect(result).toMatchObject({
executed: true,
phase: "executed",
mappingAvailable: true,
impactCount: 2,
changes: [
{ beforeCode: "0002", afterCode: "0001" },
{ beforeCode: "0009", afterCode: "0000" }
]
})
})
test("legacy auto-recode refuses a nonempty draft", async () => {
const f = fixture()
await expect(recodeApprovalRules(f.client)).rejects.toThrow("禁止隐式重排")
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
})
test("partial clear reports remaining rules without silently recoding them", async () => {
const f = fixture()
const client = {
get: f.client.get,
post: f.client.post,
delete: async (url: string) => {
if (url.endsWith("/a")) throw new Error("delete failed")
f.state.rules = f.state.rules.filter(rule => rule.id !== "b")
return Response.json({})
}
} as unknown as KyInstance
const result = await runCapabilityResult("sealApprovalRulesClear", client, f.corp, { dryRun: false })
expect(result).toMatchObject({ deleted: 1, afterCount: 1 })
expect((result as { warnings: string[] }).warnings[0]).toContain("跳过自动重排")
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
expect(f.state.rules[0]!.code).toBe(0)
})
test("CLI prints the JSON preview before returning confirmation-required exit 10", async () => {
const f = fixture()
const lines: string[] = []
const log = console.log
console.log = (...values: unknown[]) => { lines.push(values.map(String).join(" ")) }
try {
const args = parseArgs(["rules", "recode", "--corp", f.corp.id, "--yes"])
await expect(handleRulesCommand("recode", undefined, f.client, f.corp, args)).rejects.toMatchObject({ exitCode: 10 })
const preview = JSON.parse(lines.join("\n"))
expect(preview.executed).toBe(false)
expect(preview.nextCommand).toContain(`--confirm-code ${preview.confirmCode}`)
expect(preview).not.toHaveProperty("notBefore")
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
} finally {
console.log = log
}
})
})
+121
View File
@@ -0,0 +1,121 @@
import { createHash } from "node:crypto"
import type { KyInstance } from "ky"
import type { CorpConfig } from "../../../core/config/types.js"
import { formatBeijingIso } from "../../../core/config/timestamps.js"
import { CliError, validationError } from "../../../core/errors.js"
import * as api from "../api.js"
import { ApprovalRulesDataSchema, type ApprovalRule, type ApprovalRulesData } from "../types.js"
import { RecodeTicketStore } from "./recode-tickets.js"
export type RecodeOptions = { dryRun?: boolean; confirmCode?: string }
function codeNumber(rule: ApprovalRule): number {
const code = typeof rule.code === "number"
? rule.code
: Number(rule.code?.replace(/^(?:#|rule[-_:]?)/i, ""))
if (!Number.isSafeInteger(code) || code < 0) {
throw validationError("当前草稿包含无效规则编号,无法安全预览重排。")
}
return code
}
function orderedRules(data: ApprovalRulesData): ApprovalRule[] {
const rules = [...data.rules].sort((a, b) => codeNumber(a) - codeNumber(b))
if (new Set(rules.map(rule => rule.id)).size !== rules.length ||
new Set(rules.map(codeNumber)).size !== rules.length) {
throw validationError("当前草稿包含重复的规则身份或编号,无法安全重排。")
}
return rules
}
function codeLabel(code: number): string {
return String(code).padStart(4, "0")
}
function fingerprint(data: ApprovalRulesData): string {
return createHash("sha256").update(JSON.stringify({
hasPendingDeletes: data.hasPendingDeletes,
rules: [...data.rules].sort((a, b) => a.id.localeCompare(b.id))
})).digest("hex")
}
function sameContent(before: ApprovalRule, after: ApprovalRule): boolean {
return before.description === after.description && before.scope === after.scope &&
before.strictness === after.strictness && before.status === after.status && before.tenantId === after.tenantId
}
export async function recodeRules(client: KyInstance, corp: CorpConfig, options: RecodeOptions) {
const response = await client.get("api/v1/rules")
const payload = await response.json() as { data?: unknown }
const before = ApprovalRulesDataSchema.parse(payload.data ?? payload)
const rules = orderedRules(before)
const baseUrl = response.url
? response.url.replace(/\/api\/v1\/rules(?:\?.*)?$/, "")
: corp.seal.url ?? corp.source.sealUrl
if (!baseUrl) throw validationError("无法确定规则重排的目标环境。")
const targetUrl = `${baseUrl.replace(/\/+$/, "")}/api/v1/rules/batch-recode`
const beforeCodes = rules.map(rule => codeLabel(codeNumber(rule)))
const expectedCodes = rules.map((_, index) => codeLabel(index))
const preview = {
preview: true,
executed: false,
corpName: corp.name,
targetUrl,
rulesCount: rules.length,
hasPendingDeletes: before.hasPendingDeletes,
// The API has no mapping-preview contract and can put new drafts before
// active rules. Report the full possible scope instead of guessing order.
impactCount: rules.length,
changesDiff: { before: beforeCodes, after: expectedCodes },
mappingAvailable: false,
warning: "规则编号将从 0000 连续编排,所有规则均可能变号。具体顺序由服务端决定,逐条映射将在执行后回读;旧编号需结合发布版本查看。"
}
if (options.dryRun) return { ...preview, phase: "preview" as const }
const me = await api.getMe(client)
const target = JSON.stringify(["rules-recode", corp.id, new URL(baseUrl).href, corp.environment, me.tenant.id])
const tickets = new RecodeTicketStore()
const draftFingerprint = fingerprint(before)
const quotedCorp = `'${corp.id.replace(/'/g, "'\\''")}'`
if (options.confirmCode === undefined) {
const ticket = tickets.issue(target, draftFingerprint)
return {
...preview,
phase: "confirmation_required" as const,
confirmCode: ticket.confirmCode,
expiresAt: formatBeijingIso(ticket.expiresAt),
nextCommand: `seal-use rules recode --corp ${quotedCorp} --confirm-code ${ticket.confirmCode}`
}
}
tickets.consume(options.confirmCode, target, draftFingerprint)
// A failed/uncertain POST still spends the ticket. Never automatically resend it.
const result = await api.executeApprovalRulesRecode(client)
const after = await api.listApprovalRules(client)
const byId = new Map(after.rules.map(rule => [rule.id, rule]))
const actualCodes = after.rules.map(codeNumber).sort((a, b) => a - b)
if (after.rules.length !== rules.length || result.activeRules !== rules.length || result.nextCode !== rules.length ||
actualCodes.some((code, index) => code !== index) ||
rules.some(rule => {
const actual = byId.get(rule.id)
return !actual || !sameContent(rule, actual)
})) {
throw new CliError(
"重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。",
1,
`seal-use rules list --corp ${quotedCorp} --summary`
)
}
const changes = rules.map(rule => ({ beforeCode: codeLabel(codeNumber(rule)), afterCode: codeLabel(codeNumber(byId.get(rule.id)!)) }))
return {
...preview,
preview: false,
executed: true,
phase: "executed" as const,
...result,
impactCount: changes.filter(change => change.beforeCode !== change.afterCode).length,
mappingAvailable: true,
changesDiff: { before: beforeCodes, after: changes.map(change => change.afterCode) },
changes
}
}
@@ -6,8 +6,8 @@ import {
hydrateRuleVersionStableIds,
loadPublishedRuleVersionSnapshot,
savePublishedRuleVersionSnapshot
} from "./rule-version-snapshot.js";
import type { RuleSetVersion } from "./types.js";
} from "./version-snapshot.js";
import type { RuleSetVersion } from "../types.js";
const originalDir = process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR;
let testDir = "";
@@ -1,8 +1,8 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import { SEAL_STATE_DIR } from "../../core/paths.js";
import type { ApprovalRule, RuleSetVersion } from "./types.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { SEAL_STATE_DIR } from "../../../core/paths.js";
import type { ApprovalRule, RuleSetVersion } from "../types.js";
export const MAX_RETAINED_RULE_SNAPSHOTS = 20;
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import { searchApprovalContent } from "./search.js";
import { CorpConfig } from "../../../core/config/types.js";
import { searchApprovalContent } from "./service.js";
function fakeSearchClient(): KyInstance {
return {
@@ -1,19 +1,19 @@
import { KyInstance } from "ky";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import { CorpConfig } from "../../core/config/types.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { CorpConfig } from "../../../core/config/types.js";
import {
ApprovalDocument,
ApprovalRule,
ApprovalStylePreferences,
RuleSetVersion
} from "./types.js";
} from "../types.js";
import {
getApprovalRuleVersion,
getApprovalStylePreferences,
listApprovalDocuments,
listApprovalRuleVersions,
listApprovalRules
} from "./api.js";
} from "../api.js";
type MatchMode = "any" | "all";
type SearchArea = "rules" | "documents" | "preferences";
@@ -1,11 +1,11 @@
import { randomBytes } from "node:crypto";
import type { KyInstance } from "ky";
import { createSealClient } from "../../core/http/factory.js";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import { computeNextSyncIteration, formatSyncVersionName, saveRuleMappingSnapshot } from "./rule-mapping.js";
import { savePublishedRuleVersionSnapshot } from "./rule-version-snapshot.js";
import { createSealClient } from "../../../core/http/factory.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import { computeNextSyncIteration, formatSyncVersionName, saveRuleMappingSnapshot } from "../rules/mapping.js";
import { savePublishedRuleVersionSnapshot } from "../rules/version-snapshot.js";
export type TestSyncOptions = {
versionName?: string;
@@ -203,6 +203,9 @@ export async function syncTestEnterprise(
createdDocs.push({ id: created.id, title: created.title });
}
for (const rule of testRules.rules) await api.deleteApprovalRule(testClient, rule.id);
// Reset only after confirming the draft is empty, before allocating new codes.
const recodeResult = await api.recodeApprovalRules(testClient) as { ok: boolean; status: number };
if (!recodeResult.ok) throw new Error(`Failed to recode test approval rules: HTTP ${recodeResult.status}`);
const createdRules: any[] = [];
for (const rule of prodRules.rules) {
createdRules.push(await api.createApprovalRule(testClient, {
@@ -211,8 +214,6 @@ export async function syncTestEnterprise(
strictness: rule.strictness
}));
}
const recodeResult = await api.recodeApprovalRules(testClient) as { ok: boolean; status: number };
if (!recodeResult.ok) throw new Error(`Failed to recode test approval rules: HTTP ${recodeResult.status}`);
const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient);
const published = await api.publishApprovalRuleVersion(testClient, versionName);
try { savePublishedRuleVersionSnapshot(testCorp.id, published.version, createdRules); } catch {}
+1 -1
View File
@@ -2,7 +2,7 @@ import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig } from "
import { resolveCorpConfig } from "./core/config/manager.js";
import { createSealClient } from "./core/http/factory.js";
import type { SealEnterpriseConfig } from "./core/auth/types.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/enterprise/source.js";
import { getApprovalContext } from "./domains/seal/api.js";
import { printJson } from "./cli/printer.js";
+12
View File
@@ -172,6 +172,18 @@ export function startServer(): StdioServerHandle {
export { tokenizeCommand };
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }): CallToolResult {
// Confirmation-required (exit 10) or partially-executed write commands (exit 1)
// can emit a structured JSON payload on stdout alongside stderr guidance.
// Preserve both for MCP consumers instead of returning only the prose.
if (result.isError && result.stdout) {
return {
content: [
{ type: "text", text: result.stdout },
...(result.stderr ? [{ type: "text" as const, text: result.stderr }] : [])
],
isError: true
};
}
const text = result.isError ? result.stderr || result.stdout : result.stdout;
return {
content: [