Add local approval rules workspace and offline linting
This commit is contained in:
1 parent
39bbf4d7c0
commit
13ed555bbb
5 files changed
+561
-4
No files matched your search
@@ -140,12 +140,63 @@ export async function handleRulesCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "pull") {
|
||||
const version = stringOption(args.options.version) ?? maybeName;
|
||||
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
|
||||
await runTool(
|
||||
"seal_approval_rules_pull",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
version,
|
||||
out
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "push") {
|
||||
const file = stringOption(args.options.file) ?? stringOption(args.options.f) ?? maybeName;
|
||||
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);
|
||||
const versionName = stringOption(args.options.versionName) ?? stringOption(args.options["version-name"]);
|
||||
|
||||
const result = await runToolResult(
|
||||
"seal_approval_rules_push",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
file,
|
||||
dryRun,
|
||||
confirm: confirmed,
|
||||
publish,
|
||||
versionName
|
||||
}
|
||||
);
|
||||
|
||||
if (!confirmed && dryRun && result && typeof result === "object") {
|
||||
printJson(
|
||||
{
|
||||
...result,
|
||||
nextCommand: `seal-use rules push --file ${file ?? "./rules.local.json"} --corp ${corp.id} --yes${publish ? " --publish" : ""}`
|
||||
},
|
||||
outputOptions(args.options)
|
||||
);
|
||||
return;
|
||||
}
|
||||
printJson(result, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "lint") {
|
||||
await runTool(
|
||||
"seal_approval_rules_lint",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
file: stringOption(args.options.file) ?? stringOption(args.options.f),
|
||||
linter: stringOption(args.options.linter),
|
||||
version: stringOption(args.options.version),
|
||||
code: stringOption(args.options.code),
|
||||
@@ -159,5 +210,5 @@ export async function handleRulesCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint. Run 'seal-use help' for available commands.`);
|
||||
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createSealClient } from "../core/http/factory.js";
|
||||
import type { CorpConfig } from "../core/config/types.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { handleApprovalRunsCommand } from "./commands/approval-runs.js";
|
||||
import { handleAuthCommand } from "./commands/auth.js";
|
||||
@@ -248,6 +249,21 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "rules" && action === "lint" && ("file" in args.options || "f" in args.options)) {
|
||||
let corp: CorpConfig;
|
||||
try {
|
||||
corp = selectCorp(stringOption(args.options.corp));
|
||||
} catch {
|
||||
corp = {
|
||||
id: "local",
|
||||
name: "Local Workspace",
|
||||
source: { type: "native" }
|
||||
} as any;
|
||||
}
|
||||
await handleRulesCommand(action, maybeName, null as any, corp, args);
|
||||
return;
|
||||
}
|
||||
|
||||
const corp = selectCorp(stringOption(args.options.corp));
|
||||
|
||||
if (area === "source") {
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, expect, test, afterEach } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
parseLocalRulesContent,
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets
|
||||
} from "./rules-local.js";
|
||||
import { findSealTool } from "./tools.js";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("rules-local workspace", () => {
|
||||
test("parses wrapped rules object", () => {
|
||||
const raw = JSON.stringify({
|
||||
corpId: "corp-1",
|
||||
source: "draft",
|
||||
rules: [
|
||||
{ code: 1, description: "餐饮发票必须提供水单", scope: "MEAL", strictness: "MUST_FOLLOW" },
|
||||
{ code: 2, description: "单张发票金额不得超标", scope: "ALL" }
|
||||
]
|
||||
});
|
||||
|
||||
const parsed = parseLocalRulesContent(raw);
|
||||
expect(parsed.rules.length).toBe(2);
|
||||
expect(parsed.meta.corpId).toBe("corp-1");
|
||||
expect(parsed.meta.source).toBe("draft");
|
||||
expect(parsed.rules[0]!.description).toBe("餐饮发票必须提供水单");
|
||||
expect(parsed.rules[0]!.strictness).toBe("MUST_FOLLOW");
|
||||
expect(parsed.rules[1]!.strictness).toBe("MUST_FOLLOW"); // default
|
||||
});
|
||||
|
||||
test("parses raw rules array", () => {
|
||||
const raw = JSON.stringify([
|
||||
{ description: "打车必须备注起止地点", scope: "TAXI" }
|
||||
]);
|
||||
|
||||
const parsed = parseLocalRulesContent(raw);
|
||||
expect(parsed.rules.length).toBe(1);
|
||||
expect(parsed.rules[0]!.description).toBe("打车必须备注起止地点");
|
||||
expect(parsed.rules[0]!.code).toBe(1);
|
||||
});
|
||||
|
||||
test("rejects invalid format or empty description", () => {
|
||||
expect(() => parseLocalRulesContent("not-json")).toThrow("JSON 解析失败");
|
||||
expect(() => parseLocalRulesContent(JSON.stringify({ other: 123 }))).toThrow("本地规则文件格式错误");
|
||||
expect(() => parseLocalRulesContent(JSON.stringify([{ code: 1 }]))).toThrow("缺少有效的 'description'");
|
||||
});
|
||||
|
||||
test("saves and loads local rules file accurately", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-rules-test-"));
|
||||
tempDirs.push(dir);
|
||||
const filePath = join(dir, "sub", "rules.json");
|
||||
|
||||
const savedPath = saveLocalRulesFile(filePath, {
|
||||
corpId: "test-corp",
|
||||
source: "version:5",
|
||||
rules: [
|
||||
{ code: 10, description: "酒店住宿必须提供明细清单", scope: "HOTEL", strictness: "MUST_FOLLOW" }
|
||||
]
|
||||
});
|
||||
|
||||
expect(savedPath).toBe(filePath);
|
||||
|
||||
const loaded = loadLocalRulesFile(filePath);
|
||||
expect(loaded.rules.length).toBe(1);
|
||||
expect(loaded.meta.corpId).toBe("test-corp");
|
||||
expect(loaded.rules[0]!.code).toBe(10);
|
||||
expect(loaded.rules[0]!.description).toBe("酒店住宿必须提供明细清单");
|
||||
});
|
||||
|
||||
test("converts local rules to lint targets", () => {
|
||||
const targets = localRulesToLintTargets([
|
||||
{ code: 1, description: "规则一", name: "R1" },
|
||||
{ code: "0002", description: "规则二" },
|
||||
{ description: "规则三" }
|
||||
]);
|
||||
|
||||
expect(targets[0]!.code).toBe("#0001");
|
||||
expect(targets[0]!.name).toBe("R1");
|
||||
expect(targets[1]!.code).toBe("#0002");
|
||||
expect(targets[2]!.code).toBe("#0003");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rules-local offline lint tool integration", () => {
|
||||
test("lints local file directly with 0 network calls and high score", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-lint-test-"));
|
||||
tempDirs.push(dir);
|
||||
const filePath = join(dir, "clean-rules.json");
|
||||
|
||||
saveLocalRulesFile(filePath, {
|
||||
corpId: "test-corp",
|
||||
rules: [
|
||||
{
|
||||
code: 1,
|
||||
description: "单张发票金额超过500元时,必须提供经办人签字的费用明细水单与消费清单。",
|
||||
scope: "MEAL",
|
||||
strictness: "MUST_FOLLOW"
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
const lintTool = findSealTool("seal_approval_rules_lint")!;
|
||||
expect(lintTool).toBeDefined();
|
||||
|
||||
const result = await lintTool.handler(
|
||||
null as any,
|
||||
{ file: filePath } as any,
|
||||
{ corp: { id: "test-corp" } } as any
|
||||
) as any;
|
||||
|
||||
expect(result.totalRules).toBe(1);
|
||||
expect(result.passed).toBe(true);
|
||||
expect(result.overallScore).toBe(100);
|
||||
});
|
||||
|
||||
test("detects vague wording in local rules file and enforces minScore gate", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-lint-test-"));
|
||||
tempDirs.push(dir);
|
||||
const filePath = join(dir, "vague-rules.json");
|
||||
|
||||
saveLocalRulesFile(filePath, {
|
||||
corpId: "test-corp",
|
||||
rules: [
|
||||
{
|
||||
code: 1,
|
||||
description: "金额适当即可,视情况而定。",
|
||||
scope: "ALL"
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
const lintTool = findSealTool("seal_approval_rules_lint")!;
|
||||
|
||||
const result = await lintTool.handler(
|
||||
null as any,
|
||||
{ file: filePath } as any,
|
||||
{ corp: { id: "test-corp" } } as any
|
||||
) as any;
|
||||
|
||||
expect(result.totalRules).toBe(1);
|
||||
expect(result.overallScore).toBeLessThan(100);
|
||||
expect(result.issues[0].issues.some((i: any) => i.code === "VAGUE_WORD")).toBe(true);
|
||||
|
||||
// minScore enforcement
|
||||
await expect(
|
||||
lintTool.handler(
|
||||
null as any,
|
||||
{ file: filePath, minScore: 95 } as any,
|
||||
{ corp: { id: "test-corp" } } as any
|
||||
)
|
||||
).rejects.toThrow("Linter 质量门禁未通过");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import type { RuleLintTarget } from "./linter/types.js";
|
||||
|
||||
export interface LocalRuleItem {
|
||||
id?: string;
|
||||
code?: number | string;
|
||||
name?: string;
|
||||
description: string;
|
||||
scope?: string;
|
||||
strictness?: string;
|
||||
status?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface LocalRulesPayload {
|
||||
corpId?: string;
|
||||
source?: string;
|
||||
versionNumber?: number;
|
||||
exportedAt?: string;
|
||||
rulesCount?: number;
|
||||
rules: LocalRuleItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses raw local rule content (JSON array or object with `rules` array)
|
||||
* and normalizes them into a consistent structure.
|
||||
*/
|
||||
export function parseLocalRulesContent(rawText: string): {
|
||||
rules: LocalRuleItem[];
|
||||
meta: Omit<LocalRulesPayload, "rules">;
|
||||
} {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(rawText);
|
||||
} catch (err) {
|
||||
throw new Error(`本地规则文件 JSON 解析失败: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
|
||||
if (Array.isArray(parsed)) {
|
||||
return {
|
||||
rules: normalizeRuleItems(parsed),
|
||||
meta: {
|
||||
rulesCount: parsed.length
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (parsed && typeof parsed === "object") {
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
const rawRules = Array.isArray(obj.rules) ? obj.rules : undefined;
|
||||
if (!rawRules) {
|
||||
throw new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象");
|
||||
}
|
||||
|
||||
return {
|
||||
rules: normalizeRuleItems(rawRules),
|
||||
meta: {
|
||||
corpId: typeof obj.corpId === "string" ? obj.corpId : undefined,
|
||||
source: typeof obj.source === "string" ? obj.source : undefined,
|
||||
versionNumber: typeof obj.versionNumber === "number" ? obj.versionNumber : undefined,
|
||||
exportedAt: typeof obj.exportedAt === "string" ? obj.exportedAt : undefined,
|
||||
rulesCount: rawRules.length
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象");
|
||||
}
|
||||
|
||||
function normalizeRuleItems(items: unknown[]): LocalRuleItem[] {
|
||||
return items.map((item, idx) => {
|
||||
if (!item || typeof item !== "object") {
|
||||
throw new Error(`第 ${idx + 1} 条规则格式错误: 必须为对象`);
|
||||
}
|
||||
const r = item as Record<string, unknown>;
|
||||
const description = typeof r.description === "string" ? r.description.trim() : "";
|
||||
if (!description) {
|
||||
throw new Error(`第 ${idx + 1} 条规则缺少有效的 'description' (规则描述) 字段`);
|
||||
}
|
||||
|
||||
const code =
|
||||
typeof r.code === "number" || typeof r.code === "string"
|
||||
? r.code
|
||||
: idx + 1;
|
||||
|
||||
return {
|
||||
...r,
|
||||
code,
|
||||
description,
|
||||
scope: typeof r.scope === "string" ? r.scope : "ALL",
|
||||
strictness: typeof r.strictness === "string" ? r.strictness : "MUST_FOLLOW"
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a local rules file from path.
|
||||
*/
|
||||
export function loadLocalRulesFile(filePath: string): {
|
||||
rules: LocalRuleItem[];
|
||||
meta: Omit<LocalRulesPayload, "rules">;
|
||||
resolvedPath: string;
|
||||
} {
|
||||
const resolved = resolve(filePath);
|
||||
if (!existsSync(resolved)) {
|
||||
throw new Error(`未找到本地规则文件: ${filePath} (${resolved})`);
|
||||
}
|
||||
const content = readFileSync(resolved, "utf8");
|
||||
const parsed = parseLocalRulesContent(content);
|
||||
return {
|
||||
...parsed,
|
||||
resolvedPath: resolved
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves rules to a formatted JSON file.
|
||||
*/
|
||||
export function saveLocalRulesFile(
|
||||
filePath: string,
|
||||
data: LocalRulesPayload
|
||||
): string {
|
||||
const resolved = resolve(filePath);
|
||||
mkdirSync(dirname(resolved), { recursive: true });
|
||||
writeFileSync(resolved, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts local rule items to linter targets.
|
||||
*/
|
||||
export function localRulesToLintTargets(rules: LocalRuleItem[]): RuleLintTarget[] {
|
||||
return rules.map((r, idx) => {
|
||||
let codeStr: string | undefined;
|
||||
if (typeof r.code === "number") {
|
||||
codeStr = `#${String(r.code).padStart(4, "0")}`;
|
||||
} else if (typeof r.code === "string") {
|
||||
codeStr = r.code.startsWith("#") ? r.code : `#${r.code}`;
|
||||
} else {
|
||||
codeStr = `#${String(idx + 1).padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
return {
|
||||
id: r.id,
|
||||
code: codeStr,
|
||||
name: r.name,
|
||||
description: r.description,
|
||||
scope: r.scope,
|
||||
strictness: r.strictness
|
||||
};
|
||||
});
|
||||
}
|
||||
+177
-3
@@ -9,6 +9,12 @@ import { loadGlobalConfig } from "../../core/config/loader.js";
|
||||
import { createSealClientForToken } from "../../core/http/factory.js";
|
||||
import { searchApprovalContent } from "./search.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
|
||||
import {
|
||||
loadLocalRulesFile,
|
||||
saveLocalRulesFile,
|
||||
localRulesToLintTargets,
|
||||
type LocalRuleItem
|
||||
} from "./rules-local.js";
|
||||
import { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "./material-pack/index.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
@@ -440,8 +446,9 @@ export const sealTools = [
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rules_lint",
|
||||
description: "对 Seal 草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
|
||||
description: "对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
|
||||
parameters: z.object({
|
||||
file: z.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),
|
||||
linter: z.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),
|
||||
version: z.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),
|
||||
code: z.string().optional().describe("按规则展示编号过滤(如 #0038)"),
|
||||
@@ -453,6 +460,7 @@ export const sealTools = [
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
file?: string;
|
||||
linter?: string;
|
||||
version?: string;
|
||||
code?: string;
|
||||
@@ -466,7 +474,11 @@ export const sealTools = [
|
||||
let targets: RuleLintTarget[] = [];
|
||||
let versionNumber: number | undefined;
|
||||
|
||||
if (params.version) {
|
||||
if (params.file) {
|
||||
const local = loadLocalRulesFile(params.file);
|
||||
targets = localRulesToLintTargets(local.rules);
|
||||
versionNumber = local.meta.versionNumber;
|
||||
} else if (params.version) {
|
||||
const versions = await api.listApprovalRuleVersions(client);
|
||||
const versionNumberParsed = Number(params.version);
|
||||
const version = isNaN(versionNumberParsed)
|
||||
@@ -515,7 +527,7 @@ export const sealTools = [
|
||||
const batchResult = await lintRuleBatch(
|
||||
targets,
|
||||
loadedLinter,
|
||||
{ corpId: context.corp.id, versionNumber, allRules: targets },
|
||||
{ corpId: context?.corp?.id, versionNumber, allRules: targets },
|
||||
{ minScore: params.minScore, level: params.level, summary: params.summary }
|
||||
);
|
||||
|
||||
@@ -528,6 +540,164 @@ export const sealTools = [
|
||||
return batchResult;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rules_pull",
|
||||
description: "从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",
|
||||
parameters: z.object({
|
||||
version: z.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),
|
||||
out: z.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
version?: string;
|
||||
out?: string;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const outPath = params.out ?? "./rules.local.json";
|
||||
let rules: LocalRuleItem[] = [];
|
||||
let source = "draft";
|
||||
let versionNumber: number | undefined;
|
||||
|
||||
if (params.version) {
|
||||
const versions = await api.listApprovalRuleVersions(client);
|
||||
const versionNumberParsed = Number(params.version);
|
||||
const targetVersion = isNaN(versionNumberParsed)
|
||||
? params.version === "latest"
|
||||
? versions[0]
|
||||
: versions.find((v) => v.id === params.version)
|
||||
: versions.find((v) => v.versionNumber === versionNumberParsed);
|
||||
|
||||
if (!targetVersion) {
|
||||
throw new Error(`未找到指定的规则版本: ${params.version}`);
|
||||
}
|
||||
versionNumber = targetVersion.versionNumber;
|
||||
source = `version:${versionNumber}`;
|
||||
rules = (targetVersion.rules ?? []).map((r, idx) => ({
|
||||
code: (r as any).code ? Number(String((r as any).code).replace(/^#/, "")) || idx + 1 : idx + 1,
|
||||
name: (r as any).name ?? (r as any).title,
|
||||
description: r.description ?? "",
|
||||
scope: (r as any).scope ?? "ALL",
|
||||
strictness: (r as any).strictness ?? "MUST_FOLLOW"
|
||||
}));
|
||||
} else {
|
||||
const draftData = await api.listApprovalRules(client);
|
||||
rules = (draftData.rules ?? []).map((r, idx) => ({
|
||||
id: r.id,
|
||||
code: r.code ?? idx + 1,
|
||||
name: (r as any).name ?? (r as any).title,
|
||||
description: r.description ?? "",
|
||||
scope: r.scope ?? "ALL",
|
||||
strictness: r.strictness ?? "MUST_FOLLOW",
|
||||
status: r.status
|
||||
}));
|
||||
}
|
||||
|
||||
const savedPath = saveLocalRulesFile(outPath, {
|
||||
corpId: context.corp.id,
|
||||
source,
|
||||
versionNumber,
|
||||
exportedAt: new Date().toISOString(),
|
||||
rulesCount: rules.length,
|
||||
rules
|
||||
});
|
||||
|
||||
return {
|
||||
saved: true,
|
||||
path: savedPath,
|
||||
rulesCount: rules.length,
|
||||
corpId: context.corp.id,
|
||||
source,
|
||||
versionNumber
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_rules_push",
|
||||
description: "将本地规则文件推送到远端草稿(本地调优通过后一键应用,支持直接发布为正式版本)",
|
||||
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 时有效)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: {
|
||||
file?: string;
|
||||
dryRun?: boolean;
|
||||
confirm?: boolean;
|
||||
publish?: boolean;
|
||||
versionName?: string;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const filePath = params.file ?? "./rules.local.json";
|
||||
const local = loadLocalRulesFile(filePath);
|
||||
const isConfirmed = params.confirm === true;
|
||||
const isDryRun = params.dryRun ?? !isConfirmed;
|
||||
|
||||
const before = await api.listApprovalRules(client);
|
||||
|
||||
if (isDryRun) {
|
||||
return {
|
||||
corpId: context.corp.id,
|
||||
dryRun: true,
|
||||
localFile: local.resolvedPath,
|
||||
localRulesCount: local.rules.length,
|
||||
remoteDraftCount: before.rules.length,
|
||||
willPublish: Boolean(params.publish),
|
||||
message: "Preview mode. Use --yes or confirm=true to apply local rules to remote draft."
|
||||
};
|
||||
}
|
||||
|
||||
// Step 1: Clear existing draft rules
|
||||
let deleted = 0;
|
||||
for (const rule of before.rules) {
|
||||
await api.deleteApprovalRule(client, rule.id);
|
||||
deleted += 1;
|
||||
}
|
||||
|
||||
// Step 2: Create new rules from local
|
||||
const created: Array<{ id: string; description: string; code?: number }> = [];
|
||||
for (const rule of local.rules) {
|
||||
const strictness = rule.strictness?.toUpperCase()?.includes("SHOULD")
|
||||
? "SHOULD_FOLLOW"
|
||||
: rule.strictness?.toUpperCase()?.includes("SUGGEST")
|
||||
? "SUGGESTION"
|
||||
: "MUST_FOLLOW";
|
||||
|
||||
const newRule = await api.createApprovalRule(client, {
|
||||
description: rule.description,
|
||||
scope: rule.scope ?? "ALL",
|
||||
strictness
|
||||
});
|
||||
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
|
||||
}
|
||||
|
||||
// Step 3: Recode
|
||||
await api.recodeApprovalRules(client);
|
||||
|
||||
// Step 4: Optional publish
|
||||
let publishedVersion: unknown = undefined;
|
||||
if (params.publish) {
|
||||
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
|
||||
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
|
||||
publishedVersion = await api.publishApprovalRuleVersion(client, name);
|
||||
}
|
||||
|
||||
return {
|
||||
corpId: context.corp.id,
|
||||
dryRun: false,
|
||||
localFile: local.resolvedPath,
|
||||
clearedDraftRules: deleted,
|
||||
createdRules: created.length,
|
||||
published: publishedVersion ?? false
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_documents_list",
|
||||
description: "列出 Seal 审批知识文档",
|
||||
@@ -1877,6 +2047,8 @@ const sealActionNames = [
|
||||
"seal_approval_rule_version_get",
|
||||
"seal_approval_rule_get",
|
||||
"seal_approval_rules_lint",
|
||||
"seal_approval_rules_pull",
|
||||
"seal_approval_rules_push",
|
||||
"seal_approval_rule_version_publish",
|
||||
"seal_approval_documents_list",
|
||||
"seal_approval_document_get",
|
||||
@@ -1935,6 +2107,8 @@ const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
|
||||
"rule.version.get": "seal_approval_rule_version_get",
|
||||
"rule.get": "seal_approval_rule_get",
|
||||
"rule.lint": "seal_approval_rules_lint",
|
||||
"rule.pull": "seal_approval_rules_pull",
|
||||
"rule.push": "seal_approval_rules_push",
|
||||
"rule.publish": "seal_approval_rule_version_publish",
|
||||
"doc.list": "seal_approval_documents_list",
|
||||
"doc.get": "seal_approval_document_get",
|
||||
|
||||
Reference in new issue
Block a user