Organize Seal modules and add guarded rule recoding

This commit is contained in:
gitea committed 2026-10-13 02:24:41 +00:00
1 parent f788f9c6db
commit 8c7cb219a0
65 files changed
+837 -131

No files matched your search

+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 })
}
})
+13 -1
View File
@@ -1,7 +1,7 @@
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 {
listAvailableLinters,
PRIMARY_LINTERS_DIR,
@@ -66,6 +66,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)) {
+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,
+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");
+6
View File
@@ -351,6 +351,12 @@ export const HELP_REGISTRY: AreaHelp[] = [
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",
+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",
+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";
+3 -3
View File
@@ -23,9 +23,9 @@ 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";
export type CapabilityContext = {
+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";
+22 -6
View File
@@ -1,20 +1,21 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import * as api from "../api.js";
import { recodeRules, type RecodeOptions } from "../rules/recode.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
@@ -48,6 +49,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 +155,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 +172,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,
+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;
@@ -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")
}
+192
View File
@@ -0,0 +1,192 @@
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 { 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", async () => {
const f = fixture()
const code = await ticket(f)
await Bun.sleep(510)
f.corruptReadback()
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("回读规则与预览不一致")
})
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
}
})
})
+117
View File
@@ -0,0 +1,117 @@
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 { 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)
if (options.confirmCode === undefined) {
const ticket = tickets.issue(target, draftFingerprint)
const quotedCorp = `'${corp.id.replace(/'/g, "'\\''")}'`
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 Error("重排请求已发送,但回读规则与预览不一致。请先核对当前草稿,勿重复执行旧确认码。")
}
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";
+11
View File
@@ -172,6 +172,17 @@ export function startServer(): StdioServerHandle {
export { tokenizeCommand };
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }): CallToolResult {
// Confirmation-required commands can carry a structured, unexecuted preview.
// Preserve it for MCP consumers instead of returning only the next-step prose.
if (result.exitCode === 10 && 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: [