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,